language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* 根据完全二叉树的定义 具有n个节点的完全二叉树 与 满二叉树中的编号从1~n的节点一一对应 */ //采用层次遍历 将所有节点加入队列(包括空节点)。 //当遇到空节点时,再查看其后是否有非空节点。若有则不是 bool IsComplete(BiTree T) { InitQueue(Q); if(!T) return 1; //空树为满二叉树 Enqueue(Q,T); while(!IsEmpty(Q)) { DeQueue(Q,p); if(p) //节点非空 将其左右孩子入队列 { EnQueue(Q,p->lchild); EnQueue(Q,p->rchild); } else //节点空 检查后面是否还有非空节点 while(!IsEmpty(Q)) { DeQueue(Q,p); if(p) return 0; } } return 1; }
C
#include <stdio.h> #include <stdlib.h> int* activity_selection(int a[], int s[], int f[], int n) { int* arr = malloc(sizeof(int)*n); // array arr of size n arr[0] = 0; //array will start from index 1. So, fake item at index 0 arr[1] = a[1]; int k=1; int i; int iter = 1; for(i=2; i<=n; i++) { if(s[i] >= f[k]) { iter++; arr[iter] = a[i]; k=i; } } arr[0] = iter; return arr; } int main() { //Arrays staring from 1. Elements at index 0 are fake int a[] = {0, 2, 3, 5, 1, 4}; int s[] = {0, 0, 1, 3, 4, 1}; int f[] = {0, 2, 3, 4, 6, 6}; int *p = activity_selection(a, s, f, 5); int i; for(i=1; i<=p[0]; i++) { printf("%d\n",p[i]); } return 0; }
C
/* * Find the smallest member of the longest amicable chain with no members above N */ #include <stdio.h> #include <stdlib.h> #include "utils.h" #include "math_utils.h" #include "linked_list.h" #define INFINITY -1 static int * get_divisor_sums (int); static int get_solution (const int *, const int *, int); int main (int argc, char ** argv) { if (argc != 2) { fprintf (stderr, "usage: %s <N>\n", argv[0]); return 1; } int N = atoi (argv[1]); if (N <= 0) return 1; int * chain_lengths = allocate_array (N + 1, 0); int * divisor_sums = get_divisor_sums (N + 1); for (int i = 1; i <= N; i++) { int member = i; int length = 0; linked_list_t * chain = linked_list_create (); while (member <= N) { int * m_ptr = NULL; bool duplicate = false; while ((m_ptr = linked_list_next (chain, int)) != NULL) if (*m_ptr == member) { duplicate = true; linked_list_stop_iteration (chain); break; } if (duplicate || chain_lengths[member] != 0) break; linked_list_add_copy (chain, &member, int); length++; member = divisor_sums[member]; } if (member == i) chain_lengths[i] = length; else chain_lengths[i] = INFINITY; linked_list_free (chain); } printf ("%d\n", get_solution (chain_lengths, divisor_sums, N)); free (chain_lengths); free (divisor_sums); return 0; } static int * get_divisor_sums (int size) { int * divisor_sums = allocate_array (size, 0); for (int i = 1; i < size; i++) for (int j = i + i; j < size; j += i) divisor_sums[j] += i; return divisor_sums; } static int get_solution (const int * chain_lengths, const int * divisor_sums, int size) { int longest_chain = 1; for (int i = 2; i <= size; i++) if (chain_lengths[i] > chain_lengths[longest_chain]) longest_chain = i; int smallest_member = longest_chain; int member = smallest_member; for (int i = 1; i < chain_lengths[longest_chain]; i++) { member = divisor_sums[member]; if (member < smallest_member) smallest_member = member; } return smallest_member; }
C
#include "holberton.h" /** * create_file - create a file with read/write access for user * @filename: name of file to create * @text_content: string to write to file * Return: 1 on success, -1 on failure */ int create_file(const char *filename, char *text_content) { int fd, rstatus, i; if (filename == NULL) return (-1); fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR); if (fd == -1) return (-1); if (text_content) { for (i = 0; text_content[i] != '\0'; i++) ; rstatus = write(fd, text_content, i); if (rstatus == -1) return (-1); } close(fd); return (1); }
C
#ifndef ROBOT #define ROBOT #define pi 3.14159 #define nombreCranParToursDeRoue 100 #define tailleTableauValeursImpulsions 10000 #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> int nombreCoordonnees; int periode; //en secondes typedef struct position { int roueGaucheX; int roueDroiteX; int roueGaucheY; int roueDroiteY; int centreX; int centreY; float orientation; } position; typedef struct robot { position position; float entraxe; float vitesseMax; float rayonRoue; int nombreCoordonnees; int periode; //distance en mm //vitesse en m.s-1 //angle en radian } robot; typedef struct deplacement { float impulsionGauche[tailleTableauValeursImpulsions]; float impulsionDroite[tailleTableauValeursImpulsions]; } deplacement; typedef struct deplacementEntier { int impulsionGauche[tailleTableauValeursImpulsions]; int impulsionDroite[tailleTableauValeursImpulsions]; } deplacementEntier; void calculDeplacement(robot robot, deplacement *deplacementF, deplacementEntier* deplacementI); void calculImpulsionsReels(deplacement *dep,deplacementEntier *depReel); void calculPositionReel(robot *rob, deplacement *dep); void calculPositionRecu(robot *rob, deplacementEntier *dep ); float randomFloat(float valeurMax); //Calculer un nombre random float entre 0 et valeurMax void initRobot(robot *rob); void calculDeplacementDefini(robot robot, deplacement* deplacementF, deplacementEntier* deplacementI, int choixRand); #endif
C
/* * 2s_w02p01_ultrasonic.c * * Created: 2020-09-23 오전 9:49:37 * Author : Yunseo Hwang */ #define F_CPU 16000000UL #include <avr/io.h> #include <util/delay.h> #include "lcd1602a_h68.h" #include "uart.h" #define BV(n) (1 << n) #define SOUND_VELOCITY 340UL #define TRIG 6 #define ECHO 7 void ultrasonic_set(); unsigned int ultrasonic_distance(); void lcd_print_distance(unsigned int distance); void uart_write_distance(unsigned int distance); int main(void) { unsigned int distance = 0; struct lcd1602a_port port = {&DDRC, &DDRC, &PORTC, &PORTC}; DDRB = 0xFF; DDRD = 0xFF; set_lcd_bit(4); set_lcd_port(port); lcd_init(LCD_ROWS_MAX, LCD_COLS_MAX); uart_init(BAUDRATE(9600)); ultrasonic_set(); while (1) { distance = ultrasonic_distance(); lcd_print_distance(distance); if (distance <= 30) PORTD = BV(0); else if (distance <= 70) PORTD = BV(1); else if (distance <= 100) PORTD = BV(2); else if (distance <= 130) PORTD = BV(3); else if (distance <= 200) PORTD = BV(4); else PORTD = BV(5); uart_write_distance(distance); _delay_ms(1000); } } void ultrasonic_set() { DDRE = (DDRE | (1 << TRIG)) & ~(1 << ECHO); } unsigned int ultrasonic_distance() { unsigned int distance; TCCR1B = 0x03; PORTE &= ~(1<<TRIG); _delay_us(10); PORTE |= (1<<TRIG); _delay_us(10); PORTE &= ~(1<<TRIG); while(!(PINE & (1 << ECHO))); TCNT1 = 0x0000; while(PINE & (1 << ECHO)); TCCR1B = 0x00; distance = SOUND_VELOCITY * (TCNT1 * 4 / 2) / 1000; return distance; } void lcd_print_distance(unsigned int distance) { lcd_clear(); lcd_putc(distance / 1000 + '0'); lcd_putc((distance / 100) % 10 + '0'); lcd_putc((distance / 10) % 10 + '0'); lcd_putc(distance % 10 + '0'); lcd_puts("mm"); } void uart_write_distance(unsigned int distance) { uart_write(distance / 1000 + '0'); uart_write((distance / 100) % 10 + '0'); uart_write((distance / 10) % 10 + '0'); uart_write(distance % 10 + '0'); uart_write(' '); }
C
#include <stdlib.h> #include <stdio.h> #include <time.h> // time for seeding #include <pthread.h> // include pthread functions and structures #include <semaphore.h> // include semaphores #include <unistd.h> // include sleep /** Producer - Consumer Simulation * @author Nefari0uss * * This simulation was to help learn about threading in C using * producers and consumers. Producers create and place an int in * a buffer. Consumers will attempt to remove ints from the * buffer. * * To run: ./pc.out x y z where x, y, z is some integer specifying the * sleep time, number of producers, number of consumers. **/ /** The Buffer **/ typedef int buffer_item; #define BUFFER_SIZE 7 buffer_item buffer[BUFFER_SIZE]; int insertIndex; int removeIndex; /** Semaphores & Mutexes **/ sem_t full; sem_t empty; pthread_mutex_t mutex; /** Seed **/ unsigned int seed; /** Other Variables **/ int SLEEP_TIME; /** Print Buffer to view contents. **/ void printBuffer() { printf("\t\tPrinting Buffer: ["); int i; for(i = 0; i < BUFFER_SIZE; i++) { printf("%d ", buffer[i]); } printf("]\n"); } /** Buffer Methods **/ int insert_item(buffer_item item) { if (buffer[insertIndex] != '\0') { //printf("Could not insert into buffer. An item already exists!\n"); return -1; } else { /* Insert an item into buffer */ buffer[insertIndex] = item; /* Adjust insertIndex position. Increment and modulo for circular buffer. */ insertIndex++; insertIndex = insertIndex % BUFFER_SIZE; printf("---> Produced: %d\n", item); printBuffer(); return 0; } } int remove_item(buffer_item item) { if (buffer[removeIndex] == '\0') { //printf("Could not remove from buffer. The item does not exist!\n"); return -1; } else { /* Remove an object from buffer and place it in item*/ buffer_item removedItem = buffer[removeIndex]; buffer[removeIndex] = '\0'; /* Adjust removeIndex position. Increment and modulo for circular buffer. */ removeIndex++; removeIndex = removeIndex % BUFFER_SIZE; printf("<--- Consumed: %d\n", removedItem); printBuffer(); return 0; } } /** End Buffer Methods **/ /** Producer Entry **/ void *producer(void *param) { buffer_item item; while (1) { printf("in producer.\n"); /* Sleep for a random period of time between 1 and SLEEP_TIME */ sleep(rand_r(&seed) % SLEEP_TIME + 1); // wait on empty sem_wait(&empty); // mutex lock pthread_mutex_lock(&mutex); /* critical section */ printf("in producer critical section.\n"); // generate a random number item = rand_r(&seed); // insert item into buffer and report on error condition if any if (insert_item(item) < 0) { printf("Could not insert into buffer. An item already exists!\n"); } /* end critical section */ // unlock mutex pthread_mutex_unlock(&mutex); // signal full sem_post(&full); } } /** Consumer Entry **/ void *consumer(void *param) { buffer_item *item = (int *)malloc(sizeof(int)); while (1) { printf("in consumer.\n"); /* Sleep for a random period of time between 1 and SLEEP_TIME */ sleep(rand_r(&seed) % SLEEP_TIME + 1); // wait on full sem_wait(&full); // mutex lock pthread_mutex_lock(&mutex); /* critical section */ printf("in consumer critical section.\n"); // generate a random number //item = rand_r(&seed); // insert item into buffer and report on error condition if any if (remove_item(*item) < 0) { printf("Could not remove from buffer. The item does not exist!\n"); } /* end critical section */ // unlock mutex pthread_mutex_unlock(&mutex); // signal empty sem_post(&empty); } free(item); } int main(int argc, char*argv[]) { /* 1. Get command line arguments argv[1], argv[2], argv[3] */ int producerCount; int consumerCount; // check if 3 args are passed if (argv[1] == NULL || argv[2] == NULL || argv[3] == NULL) { printf("Enter 3 arguments: sleep time, number of producers, number of consumers. \n"); return -1; } else { SLEEP_TIME = atoi(argv[1]); producerCount = atoi(argv[2]); consumerCount = atoi(argv[3]); } /* 2. Initialize buffer, mutex, semaphores, and other global vars */ seed = (unsigned int)time(NULL); pthread_mutex_init(&mutex, NULL); sem_init(&empty, 0, BUFFER_SIZE); sem_init(&full, 0, 0); /* 3. Create producer thread(s) */ pthread_t producers[producerCount]; int i; for (i = 0; i < producerCount; i++) { pthread_attr_t pt_attr; // get default attributes pthread_attr_init(&pt_attr); // create thread int producerResults = pthread_create(&producers[i], &pt_attr, producer, NULL); if (producerResults == -1) { printf("Error creating producer thread.\n"); } } /* 4. Create consumer thread(s) */ pthread_t consumers[consumerCount]; for (i = 0; i < consumerCount; i++) { pthread_attr_t ct_attr; // get default attributes pthread_attr_init(&ct_attr); //create thread int consumerResults = pthread_create(&consumers[i], &ct_attr, consumer, NULL); if (consumerResults == -1) { printf("Error creating consumer thread.\n"); } } /* 5. Sleep */ //printf("Sleeping...\n"); sleep(SLEEP_TIME); /* 6. Release resources, e.g. destroy mutex and semaphores */ for(i = 0; i < producerCount; i++) pthread_cancel(producers[i]); for(i = 0; i < consumerCount; i++) pthread_cancel(consumers[i]); pthread_mutex_destroy(&mutex); sem_destroy(&empty); sem_destroy(&full); /* 7. Exit */ return 0; }
C
/******************************************************************** * formula.h * * Defines types for fault trees. * * Author: Clovis Eberhart ********************************************************************/ #ifndef __CCL_FAULT_TREE_H__ #define __CCL_FAULT_TREE_H__ #include <stdbool.h> #include "proof.h" /********* * Types * *********/ #define FLTT_CASES 4 /* Different possible cases for fault trees: * wires, and, or, pand... */ enum CASE_FAULT_TREE { WIRE, AND, OR, PAND }; /* The type structure for fault trees: * - each node has a type (as defined above), a number of "ports", and a list of * children of the size as the number of ports, * - wires have 0 ports and "index" contains the index of the wire, * - for gates, the children correspond to subformulas. */ typedef struct fault_tree_s { enum CASE_FAULT_TREE fault_tree_type; int ports; struct fault_tree_s** children; int index; } *fault_tree; /************ * Creation * ************/ fault_tree fltt_wire( int i ); fault_tree fltt_binary( fault_tree t1, fault_tree t2, enum CASE_FAULT_TREE s ); fault_tree fltt_and( fault_tree t1, fault_tree t2 ); fault_tree fltt_or( fault_tree t1, fault_tree t2 ); fault_tree fltt_pand( fault_tree t1, fault_tree t2 ); /**************** * Manipulation * ****************/ /* fltt_copy: returns a copy of a fault tree. * inputs: * - the fault_tree. * output: a copy. */ fault_tree fltt_copy( fault_tree t ); /* fltt_equal: returns [true] if two fault trees are syntactically equal. * inputs: * - the fault trees [f1] and [f2] to compare. * output: [true] if they are equal, [false] otherwise. */ bool fltt_equal( fault_tree t1, fault_tree t2 ); /* fltt_propagate: propagates faults in a fault tree given faulty wires. * inputs: * - the fault tree [t], * - an array [sigma] of booleans that associates "true" to a wire if it is * faulty. * output: a boolean that represents whether the whole system is faulty. */ bool fltt_propagate( fault_tree t, bool* sigma ); /* fltt_propagate_prob: propagates fault probabilities in a fault tree given * probabilities of fault for wires. * inputs: * - the fault tree [t], * - an array [sigma] of doubles that associates a probability of failure to * each wire. * output: a double that represents the probability of failure of the system. */ double fltt_propagate_prob( fault_tree t, double* sigma ); /* fltt_to_prf: translates a fault tree to a proof. * inputs: * - the maximal index [n] of wires used in [t], * - the fault tree [t], * - the logic [log] (the interpretation of connectors used in the proof). * output: a proof tree corresponding to faults _not_ propagating to the whole * system. */ proof fltt_to_prf( int n, fault_tree t, logic log ); /************ * Printing * ************/ void fltt_printf( fault_tree t ); int fltt_symbol_snprintf( char* buf, int length, enum CASE_FAULT_TREE s ); int fltt_snprintf( char* buf, int length, fault_tree t ); fault_tree cJSON_to_fltt( cJSON* json ); #endif // __CCL_FAULT_TREE_H__
C
#include <stdio.h> #include <stdlib.h> int palidromo(int *p,int n) { int i=0; int j=n-1; int cont=0; for(i=0;i<n;i++) { if(p[i]==p[j]) { } else if(p[i]!=p[j]) { cont++; } j--; } if(cont==0) //e palidromo { return 1; } else return 0; } int tamanho(int n) { int cont=0; while(n!=0) { n/=10; cont++; } return cont; } int verifica(int p) { if (p==0) { printf("nao\n"); } else if(p==1) { printf("sim\n"); } } void copia(int *p, int t,int n) { int aux,i; aux=0; int j=t-1; for(i=0;i<t;i++) { aux=n%10; n/=10; p[j]=aux; j--; } } int main() { int n,t,*p; scanf("%d",&n); t=tamanho(n); p=malloc(t*sizeof(int)); copia(p,t,n); int i; verifica(palidromo(p,t)); }
C
/* Pet Thread Library * (c) 2017, Jack Lange <[email protected]> */ #include <stdio.h> #include <stdlib.h> #include <setjmp.h> #include <assert.h> #include "pet_thread.h" #include "pet_hashtable.h" #include "pet_list.h" #include "pet_log.h" #define VERBOSE 0 #define STACK_SIZE (4096 * 32) typedef enum {PET_THREAD_STOPPED, PET_THREAD_RUNNING, PET_THREAD_READY, PET_THREAD_BLOCKED} thread_run_state_t; struct exec_ctx { uint64_t rbp; uint64_t r15; uint64_t r14; uint64_t r13; uint64_t r12; uint64_t r11; uint64_t r10; uint64_t r9; uint64_t r8; uint64_t rsi; uint64_t rdi; uint64_t rdx; uint64_t rcx; uint64_t rbx; uint64_t rip; // pushed by "call" instruction into __switch_to_stack() } __attribute__((packed)); struct pet_thread { pet_thread_id_t id; pet_thread_fn_t func; // Debugging only void * stack_bottom; // Used only to free stack void * stack_rsp; // Stack pointer struct list_head list; // LIST_HEAD to read_list & blocked_list thread_run_state_t state; struct list_head waiting_for_me_list; // LIST_HEAD to chain of `waiting_thread' void * return_reciever; // threads calling join() expect a return value here }; // Chain of threads blocked waiting for another to exit () struct waiting_thread { struct pet_thread * thread; struct list_head list; }; static int thread_id_count = 1; static pet_thread_id_t current = PET_MASTER_THREAD_ID; struct pet_thread master_dummy_thread; static LIST_HEAD(ready_list); static LIST_HEAD(blocked_list); static struct pet_thread *running; static struct pet_thread *stopped; // Points to the last stopped thread // Used to find thread for cleaning extern void __switch_to_stack(void * tgt_stack, void * saved_stack, pet_thread_id_t current, pet_thread_id_t tgt); extern void __abort_to_stack(void * tgt_stack); extern void __capture_return(void); static struct pet_thread * get_thread(pet_thread_id_t thread_id) { if (thread_id == PET_MASTER_THREAD_ID) { return &(master_dummy_thread); } if(running->id==thread_id) return running; if(stopped!=NULL && stopped->id==thread_id) return stopped; struct pet_thread * pos; list_for_each_entry(pos, &ready_list, list) { if(pos->id==thread_id) { return pos; } } list_for_each_entry(pos, &blocked_list, list) { if(pos->id==thread_id) { return pos; } } return NULL; } static pet_thread_id_t get_thread_id(struct pet_thread * thread) { if (thread == &(master_dummy_thread)) { return PET_MASTER_THREAD_ID; } if(thread!=NULL) return thread->id; return 0; } int pet_thread_init(void) { printf("Initializing Pet Thread library\n"); list_head_init(&ready_list); list_head_init(&blocked_list); master_dummy_thread.state = PET_THREAD_RUNNING; master_dummy_thread.id = PET_MASTER_THREAD_ID; running = &master_dummy_thread; return 0; } void dump_list(struct list_head *head, char* name) { printf("\n-- -- -- -- -- %s (thds=%d) -- -- -- -- --\n", name, thread_id_count-1); struct pet_thread *pos, *n; list_for_each_entry_safe(pos, n, head, list) { printf("%d ", (int)pos->id); if(&n->list!=head) printf("--> "); } printf("\n-- -- -- -- -- -- -- -- -- -- --\n"); } void dump_waiting_list(struct list_head *head, char* name) { printf("\n-- -- -- -- -- %s -- -- -- -- --\n", name); DEBUG("HEAD thread id: %d\n", (int)list_entry(head, struct pet_thread, waiting_for_me_list)->id); struct waiting_thread *pos; list_for_each_entry(pos, head, list) { printf("%d ", (int)pos->thread->id); if(pos->list.next!=head) printf("--> "); } printf("\n-- -- -- -- -- -- -- -- -- -- --\n"); } /* * Returning point for all thread functions that return. Actions: * * 1. Recieves as argument ret_val, which is provided by pet_thread_exit() OR * __capture_return(), depending on how the thread exited. * * 2. Iterates `waiting_for_me_list' of exiting thread (containing the blocked * threads waiting for this exit event) and puts these in ready_list to be * scheduled again. For each of these, inserts ret_val into the return_reciever * so that the unblocked thread can access this threads return value. */ void __quarantine(void * ret_val) { if(VERBOSE) DEBUG("FROM __quarantine(): Thread %d exited\n", (int)running->id); if(VERBOSE) DEBUG("FROM __quarantine(): Checking thread %d's blocked waiters...\n", (int)running->id); // Checked dependent (blocked) threads and move them to ready_list struct waiting_thread *pos, *n; if(!list_empty(&running->waiting_for_me_list)) { if(VERBOSE) dump_waiting_list(&running->waiting_for_me_list, "WAITING_FOR_ME_LIST"); list_for_each_entry_safe(pos, n, &running->waiting_for_me_list, list) { assert(pos->thread->state == PET_THREAD_BLOCKED); pos->thread->return_reciever = ret_val; // Copy exiting thread's ret val to blocked thread pos->thread->state = PET_THREAD_READY; list_del(&pos->thread->list); // remove from blocked_list list_add_tail(&pos->thread->list, &ready_list); // add to ready list list_del(&pos->list); // remove from waiting_for_me_list free(pos); } assert(list_empty(&running->waiting_for_me_list)); } else { if(VERBOSE) DEBUG("Thread %d has no blocked waiters.\n", (int)running->id); } // Exit thread and schedule a new one if(VERBOSE) dump_list(&ready_list, "RL (check 3)"); assert(running->state==PET_THREAD_RUNNING); assert(running != &master_dummy_thread); running->state = PET_THREAD_STOPPED; // signal thread to be cleaned up on next __switch_stack() pet_thread_schedule(); // If you get here, that means an exited thread was re-invoked (error) DEBUG("FROM __quarantine(): ERROR! Thread %d, which exited, was re-invoked\n", (int)running->id); } static void __dump_stack(struct pet_thread * thread) { if(thread == &master_dummy_thread) { DEBUG("WARNING: Cannot dump stack of master_dummy_thread.\n"); return; } if(thread->state == PET_THREAD_STOPPED) { DEBUG("WARNING: Cannot dump stack of exited thread (may have been freed).\n"); return; } printf("\n-------- STACK DUMP thread %d --------\n", (int)thread->id); uintptr_t * stack = (uintptr_t *)thread->stack_bottom; uintptr_t * cur; for( int i=0; (uintptr_t *)thread->stack_rsp != cur; i++) { cur = &stack[STACK_SIZE/sizeof(uintptr_t) - i]; printf("%p:\t%lx", cur, *cur); if(*cur == (uintptr_t)__capture_return) printf(" <__capture_return>"); if(*cur == (uintptr_t)thread->func) printf(" <thread_func>"); if((uintptr_t *)thread->stack_rsp==cur) printf("\t<----- rsp"); if(*(uintptr_t*)thread->stack_rsp == (uintptr_t)cur) printf("\t<----- rbp"); printf("\n"); } printf("\n"); return; } /* * Thread (A) that calls join() will be marked `BLOCKED' (and placed in blocked_list later by __thread_invoker). * Then, thread (A) is added to the linked list `waiting_for_me_list' of thread (B) that was 'joined' to. * When thread B exits and executes __capture_return(), its `waiting_for_me_list' field is checked to see if * any threads are blocked waiting for it to exit. If so, that those blocked threads are put in the ready_list. */ int pet_thread_join(pet_thread_id_t thread_id, void ** ret_val) { if(VERBOSE) DEBUG("ENTERED pet_thread_join\n"); struct pet_thread *thread = get_thread(thread_id); if(thread==NULL) { if(VERBOSE) DEBUG("FROM pet_thread_join: Thread to join doesn't exist.\n"); return -1; } assert(running->state == PET_THREAD_RUNNING); running->state = PET_THREAD_BLOCKED; // __thread_invoker will put thread in blocked_list struct waiting_thread * w_t = (struct waiting_thread*)malloc(sizeof(struct waiting_thread)); w_t->thread = running; list_add_tail(&w_t->list, &thread->waiting_for_me_list); pet_thread_schedule(); // Before thread returns to function, fill `ret_val' from this thread's `return_reciever' field *ret_val = running->return_reciever; return 0; } /* * Threads can exit in two ways: * * 1. By calling "ret" x86 instruction, %rip becomes __capture_return(), which * immediately calls __quaranatine() with %rax (return) value as the argument. * __quarantine() in turn unblocks threads waiting for thie exit event, and * provides the return value to them. (__capture_return() is defined in * pet_thread_hw.S) * * ---> 2. By calling THIS exit() function, the ret_val arg is given as an argument to * __quarantine(). So when __quarantine() is called, the behavior is the same as 1. */ void pet_thread_exit(void * ret_val) { __quarantine(ret_val); } static int __thread_invoker(struct pet_thread * thread) { if(VERBOSE) DEBUG("Entered __thread_invoker(id=%d)\n", (int)thread->id); assert(thread->state == PET_THREAD_READY); assert(running->state != PET_THREAD_READY); // Move `thread' out of ready_list and into `running' struct pet_thread * old_thread = running; running = thread; if(VERBOSE) dump_list(&ready_list, "RL (check 1)"); if(thread != &master_dummy_thread) { list_del(&thread->list); if(VERBOSE) DEBUG("FROM __thread_invoker: Deleting chosen thread from ready_list\n"); } if(VERBOSE) dump_list(&ready_list, "RL (check 2)"); // Put old_thread in appropriate queue switch(old_thread->state) { case PET_THREAD_RUNNING : if(old_thread!=&master_dummy_thread) { list_add_tail(&old_thread->list, &ready_list); if(VERBOSE) DEBUG("FROM __thread_invoker(id=%d)... added old_thread to ready_list\n", (int)thread->id); } old_thread->state = PET_THREAD_READY; break; case PET_THREAD_BLOCKED : list_add_tail(&old_thread->list, &blocked_list); break; case PET_THREAD_STOPPED : stopped = old_thread; break; } running->state = PET_THREAD_RUNNING; current = thread->id; if(VERBOSE) DEBUG("FROM __thread_invoker(id=%d), calling __switch_to_stack()\n", (int)thread->id); __switch_to_stack(&thread->stack_rsp, &old_thread->stack_rsp, old_thread->id, thread->id); return 0; } int pet_thread_create(pet_thread_id_t * thread_id, pet_thread_fn_t func, void * arg) { // Create thread struct and initialize fields struct pet_thread * new_thread = (struct pet_thread*)malloc(sizeof(struct pet_thread)); new_thread->id = (pet_thread_id_t)thread_id_count++; *thread_id = new_thread->id; new_thread->func = func; new_thread->state = PET_THREAD_READY; new_thread->return_reciever = NULL; list_head_init(&new_thread->waiting_for_me_list); assert(new_thread->waiting_for_me_list.next == new_thread->waiting_for_me_list.prev && new_thread->waiting_for_me_list.next == &new_thread->waiting_for_me_list); // Allocate a stack new_thread->stack_bottom = calloc(STACK_SIZE, 1); int num_entries = STACK_SIZE/sizeof(uintptr_t); /* Give stack an initial saved context with the following: (The first stack element is * given the __capture_return() address so that, if a thread ever calls "ret" x86 instruction, * this value will be popped into %rip) * First stack element <-- __capture_return() address (where threads 'return') * %rip restore value <-- thread function address * %rdi restore value <-- thread function argument */ struct exec_ctx * init_ctx = (struct exec_ctx*)&((uintptr_t *)new_thread->stack_bottom)[num_entries-16]; init_ctx->rip = (uintptr_t)func; init_ctx->rbp = (uintptr_t)&((uintptr_t *)new_thread->stack_bottom)[num_entries-1]; init_ctx->rdi = (uintptr_t)arg; ((uintptr_t *)new_thread->stack_bottom)[num_entries-1] = (uintptr_t)__capture_return; // Point stack_rsp to end of saved context new_thread->stack_rsp = (void *)&((uintptr_t *)new_thread->stack_bottom)[num_entries-16]; // Add to ready_list list_add_tail(&new_thread->list, &ready_list); DEBUG("Created new Pet Thread (%p) with id %d:\n", new_thread, (int)new_thread->id); if(VERBOSE) __dump_stack(new_thread); return 0; } void pet_thread_cleanup(pet_thread_id_t prev_id, pet_thread_id_t my_id) { if(VERBOSE) DEBUG("Entered pet_thread_cleanup(): prev_id=%d, my_id=%d\n", (int)prev_id, (int)my_id); if(VERBOSE) __dump_stack(get_thread(my_id)); if(VERBOSE) __dump_stack(get_thread(prev_id)); struct pet_thread * prev_thread = get_thread(prev_id); if(prev_thread->state == PET_THREAD_STOPPED) { // De-allocate thread memory if(VERBOSE) DEBUG("CLEANING THREAD %d\n", (int)prev_thread->id); free(prev_thread->stack_bottom); free(prev_thread); } } /* * Puts running thread in running queue, */ static void __yield_to(struct pet_thread * tgt_thread) { if(tgt_thread==NULL || tgt_thread->state != PET_THREAD_READY) { if(VERBOSE) DEBUG("WARNING: Thread yielded to is not ready, or doesn't exist (may have exited). Scheduling another\n"); pet_thread_schedule(); return; // returning point A... Continue with func } if(VERBOSE) DEBUG("FROM __yield_to: calling __thread_invoker(id=%d)\n", (int)tgt_thread->id); __thread_invoker(tgt_thread); // returning point B... Continue with func } int pet_thread_yield_to(pet_thread_id_t thread_id) { if(VERBOSE) DEBUG("ENTERED pet_thread_yield_to (YT thread_id=%d, running->id=%d)\n", (int)thread_id, (int)running->id); __yield_to(get_thread(thread_id)); return 0; } int pet_thread_schedule() { // If ready queue is empty, schedule master_dummy_thread if(list_empty(&ready_list) && running!=&master_dummy_thread) { __thread_invoker(&master_dummy_thread); return 9; // NEVER REACHED } if(VERBOSE) dump_list(&ready_list, "Ready List"); struct pet_thread *pos; list_for_each_entry(pos, &ready_list, list) { assert(pos->state == PET_THREAD_READY); if(VERBOSE) DEBUG("calling __thread_invoker(id=%d)\n", (int)pos->id); __thread_invoker(pos); // Won't get here until master thread is re-invoked break; } return 0; } int pet_thread_run() { printf("Starting Pet Thread execution\n"); pet_thread_schedule(); printf("Pet Thread execution has finished\n"); return 0; }
C
#include<stdio.h> #include<math.h> char a[100][100]; int n; void printmatrix() { int i,j; for(i=0;i<n;i++) { for( j=0;j<n;j++) printf("%c ",a[i][j]); printf("\n"); } } int getmarkedcol(int row){ int i; for(i=0;i<n;i++) if(a[row][i]=='Q') { return(i); break; } } int feasible(int row,int col) { int i,tcol; for(i=0;i<n;i++){ tcol=getmarkedcol(i); if(col==tcol||abs(row-i)==abs(col-tcol)) return 0; } return 1; } void nqueen(int row) { int i,j; if(row<n) { for(i=0;i<n;i++) { if(feasible(row,i)) { a[row][i]='Q'; nqueen(row-1); a[row][i]='.'; } else{ printf("The solution is:\n"); printmatrix(); } } } } void main() { int i,j; printf("Enter the no of queens\n"); scanf("%d",&n); for(i=0;i<n;i++) for(j=0;j<n;j++) a[i][j]='.'; nqueen(0); }
C
extern char* strfleft(char* string,char separator); /*úַstringĵһseparator䱾ߵַ stringΪַseparatorΪָ stringвseparator򷵻Դַstring separatorΪstring׸ַ򷵻ؿַ stringΪַ򷵻ؿַ*/ extern char* strlleft(char* string,char separator); /*úַstringһseparator䱾ߵַ stringΪַseparatorΪָ stringвseparator򷵻Դַstring separatorΪstring׸ַ򷵻ؿַ stringΪַ򷵻ؿַ*/ extern char* strfright(char* string,char separator); /*úַstringĵһseparator䱾ұߵַ stringΪַseparatorΪָ stringвseparator򷵻Դַstring separatorΪstringĩַ򷵻ؿַ stringΪַ򷵻ؿַ*/ extern char* strlright(char* string,char separator); /*úַstringһseparator䱾ұߵַ stringΪַseparatorΪָ stringвseparator򷵻Դַstring separatorΪstringĩַ򷵻ؿַ stringΪַ򷵻ؿַ*/ extern char* strfleft(const char* string,const char separator); extern char* strlright(const char* string,const char separator); extern bool strincludechrs(const char* string,const char* substring); /*úжַƥ substringַstringڣΪƥ䡱򷵻true򷵻false ַͬtrue substringΪַtrue stringΪַsubstringǿַfalse*/ extern bool strsubstr(const char* string,const char* substring); /*úжַİϵ substringstring򷵻true򷵻false ַͬtrue substringΪַfalse stringΪַsubstringǿַfalse*/ extern char* strdelchr(char* string,char ch); /*ústringڲַchɾ״γߡɾĿַ chstringڣκβԴַ */ extern char* strdelchrs(char* string,char ch); /*ústringڲַchɾchɾĿַ chstringڣκβԴַ */ extern char* strdelstr(char* string,const char* substring); /*ústringڲַsubstringɾ״γߡɾĿַ substringstringڣκβԴַ */ extern char* strdelstrs(char* string,const char* substring); /*ústringڲַsubstringɾsubstringɾĿַ substringstringڣκβԴַ */ extern char* strdeln(char* string,int index); /*úɾstringڵindex0ʼַɾĿַ indexַȣκβԴַ */ extern char* strdelbn(char* string,int index); /*úɾstringڵindex0ʼַɾĿַ indexַȣκβԴַ */ extern char* strreverse(char* string); /*úתַstringطתַ stringΪַؿַ*/ extern int strmid(const char* string,const char* substring); /*ústringڲַsubstring״γߵĶӦַ±ꡣ δҵ-1 substringΪַ0. */
C
#include <unistd.h> #include <time.h> #include <sys/types.h> #include <fcntl.h> int main() { time_t result; pid_t pid; int filedes; ssize_t nread; char buffer[32]; pid = fork(); if(pid > 0) { sleep(1); exit(1); } else if(pid == 0) { setsid(); filedes = open("./curtime.txt", O_RDWR | O_CREAT, 0644); for(;;) { result = time(NULL); strcpy(buffer, asctime(localtime(&result))); printf("%s", buffer); write(filedes, buffer, strlen(buffer)); sleep(2); } } }
C
#include "clientSession.h" #include "packet.h" #define BACKLOG 20 bool message=false; struct message processPacket(struct message incomingPacket, User *current){ printf("in process packet!\n"); struct message packetToSend; //process the packet //1. look at the packet type switch (incomingPacket.type){ //follow the types according to the enumeration case 0: //login: store the clientID in the client list printf("Its a login!\n"); //struct clientStruct * currentClient; //verify if client already logged in or already existing bool addSuccess=false; //strcpy(current->clientID, (unsigned char *) incomingPacket.source); addSuccess = addToClientList(current); printf("^^^^^Add success : %d\n",addSuccess); if (addSuccess){ printf("Login sucess!\n"); current->loggedIn = true; //do LO_ACK packetToSend = makeLoAckPacket(current); }else{ printf("Login fail!\n"); current->loggedIn = false; //do LO_NAK char reasonFailed[] = "This user is already logged in"; packetToSend = makeLoNakPacket(current, reasonFailed); } break; case 1: //Logout: remove the clientID in the client list printf("It's a logout!\n"); removeFromClientList((unsigned char *)incomingPacket.source, current->clientFD); break; case 4: //Joinsession printf("Joining session!\n"); //joining bool joinSuccess=false; char * reasonForFailure = malloc(1000 * sizeof(char)); joinSuccess = joinSession((char *)incomingPacket.data, current, reasonForFailure); printf("\n&&&& IN SERVER: %s\n", reasonForFailure); if (joinSuccess) { printf("Sucessfuly joined session!\n"); //create Jn_ack packet current -> inSess = true; memcpy(current -> sessionID, incomingPacket.data,MAXBUFLEN); packetToSend = makeJnAckPacket(current, incomingPacket.data); }else{ printf("Can't join session !\n"); //make jn_nak packet current -> inSess = false; packetToSend = makeJnNakPacket(current, incomingPacket.data,reasonForFailure); } free(reasonForFailure); break; case 7: //leavesession printf("Leaving session!\n"); leaveSession(current); packetToSend = makeLeaveAckPacket(current); break; case 8: //create session printf("creating session!\n"); bool createSuccess=false; createSuccess = createSession((unsigned char *)incomingPacket.data, current); if (createSuccess) { current->inSess=true; printf("Sucessfuly Created session!\n"); //create Jn_ack packet packetToSend = makeNsAckPacket(current); } else{ current->inSess=false; printf("Unsucessful!\n"); //make jn_nak packet packetToSend = makeNsNakPacket(current); } break; case 11: //list printf("List!\n"); packetToSend = makeQuAckPacket(current->clientID,current->sessionID); break; default: break; } return packetToSend; } int main(int argc, char *argv[]){ char *portNum; struct addrinfo servAddr; struct addrinfo* servAddrPtr; struct sockaddr_storage cliAddr; int sockfd; //expecting server <port num> if(argc != 2){ printf("Error: the number of inputs is incorrect!\n"); exit(EXIT_FAILURE); } //===============Setup=============== //make the socket portNum = argv[1]; printf("%s\n", portNum); memset(&servAddr, 0, sizeof(servAddr)); servAddr.ai_family = AF_INET; //IPv4 servAddr.ai_socktype = SOCK_STREAM; servAddr.ai_flags = AI_PASSIVE; //allocate linked list(fills the structs needed later) using getaddrinfo int structureSetupSuccess = getaddrinfo(NULL, portNum, &servAddr, &servAddrPtr); if(structureSetupSuccess < 0 ) { printf("Structure setup failed!\n"); exit(EXIT_FAILURE); } //create unbound socket in domain //servAddrPtr->ai_family: which is IPv4 //servAddrPtr->ai_socktype is datagram for UDP //protocol is 0: default protocol //sockfd: used to access the socket later sockfd = socket(servAddrPtr -> ai_family, servAddrPtr->ai_socktype, servAddrPtr->ai_protocol); printf("MY SOCKETFD: %d\n", sockfd); if(sockfd < 0){ printf("Socket failed!\n"); exit(EXIT_FAILURE); } //bind socket made //assign address to unbound socket just made, unbound socket CAN'T receive anything //assigns the address in the 2nd parameter(servAddrPtr -> ai_addr) to the socket in the 1st parameter //which is the socket's file descriptor //3rd parameter specifies the size, in bytes, of the address structure pointed to by addr int bindRet = bind(sockfd, (struct sockaddr * )servAddrPtr -> ai_addr,servAddrPtr -> ai_addrlen); printf("bind: %d\n", bindRet); if(bindRet < 0){ printf("Bind failed!\n"); exit(EXIT_FAILURE); } //listen for connections if(listen(sockfd, BACKLOG) == -1){ perror("Listen\n"); exit(1); } //=============Clients coming============= firstClient = true; bool logout = false; int acceptFD; socklen_t addrLen = sizeof(cliAddr); User *newUser = calloc(sizeof(User), 1); newUser->clientFD = accept(sockfd, (struct sockaddr *)&(cliAddr), &addrLen); if(newUser->clientFD < 0){ perror("newUser->clientFD\n"); exit(1); } newUser ->inSess = false; newUser -> next = NULL; struct message * incomingPacket; struct message packetToSend; struct message * ptrToPacketToSend; int recvBytes; while(1){ printf("\n\n****************************\n"); incomingPacket = (struct message * ) malloc (sizeof (struct message)); printf("Before read:\n"); printf("reading from: %d\n",newUser->clientFD); printPacket(incomingPacket); recvBytes = read(newUser->clientFD, incomingPacket, sizeof(struct message)); printf("After read:\n"); printf("bytes received from client: %d\n",recvBytes); if(recvBytes < 0){ perror("Error receiving!\n"); exit(EXIT_FAILURE); } printf("\nReceiving packet: \n"); printPacket(incomingPacket); //before processing packet, fill in user info as much as possible memcpy(newUser -> clientID,incomingPacket -> source,MAXBUFLEN); packetToSend = processPacket(*incomingPacket,newUser); printf("\n###Server's gonna send:\n"); printPacket(&packetToSend); ptrToPacketToSend = &packetToSend; int sendBytes = write(newUser->clientFD, ptrToPacketToSend, sizeof(struct message)); //clean up for next round free(incomingPacket); incomingPacket = NULL; firstClient = false; }//end of while loop close(sockfd); return (EXIT_SUCCESS); }
C
#include<stdio.h> int main() { /*1. жswitch caseʱִ䣻 caseûbreak;ִкĴֱbreak; ûзcaseִdefault; default⣬ûûbreak;ִк䣻 switchһҪbreakdefault ÷*/ int x=3,a=0,b=0; switch(x--) { case 0:b++; case 1:printf("%d",a++); default:b=b-2; case 2:printf("%d",a++),b++; } printf("a=%d,b=%d",a,b); return 0; }
C
#include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> extern int errno; #include "functions.h" void no_such_file_or_directory_error(char *filename){ char error_message[200]; errno = 2; strcpy(error_message, "tail: cannot open '"); strcat(error_message, filename); strcat(error_message, "' for reading"); perror(error_message); // write(STDERR_FILENO, error_message, strlen(error_message)); } void is_a_directory_error(char *filename){ char error_message[200]; errno = 21; strcpy(error_message, "tail: error reading '"); strcat(error_message, filename); strcat(error_message, "'"); perror(error_message); // write(STDERR_FILENO, error_message, strlen(error_message)); } void input_output_error(char *filename){ char error_message[200]; errno = 5; strcpy(error_message, "tail: error reading '"); strcat(error_message, filename); strcat(error_message, "'"); perror(error_message); // write(STDERR_FILENO, error_message, strlen(error_message)); }
C
#include <stdio.h> int main(void) { int input[10]; int sum; float avg; int repeat; do { sum = avg = repeat = 0; printf("Bitte geben sie 10 ganze Zahlen ein.\n"); for (int i = 0; i < 10; i++) { printf("Zahl %d: ", i + 1); scanf("%d", &input[i]); } for (int i = 0; i < 10; i++) { sum = sum + input[i]; } avg = ((float) sum / 10); printf("The avg is: %.2f\n", avg); printf("Möchten Sie das Programm erneut ausführen? (1=yes)\n"); scanf("%d", &repeat); } while (repeat); }
C
#include<stdio.h> #include<math.h> float f(float x) { return sin(x)+3*x-exp(x); } void swap(float* x0,float *x1) { float x; x=*x0; *x0=*x1; *x1=x; } int main() { float x0,x1,x2,e=0.00005; printf("Enter initial guesses: "); scanf("%g%g",&x0,&x1); do { if(fabs((*f)(x0))<fabs((*f)(x1))) swap(&x0,&x1); static int count=0; x2=x1-((x1-x0)/((*f)(x1)-(*f)(x0)))*(*f)(x1); if(fabs((*f)(x2)-(*f)(x1))==0 || count++>=500) {printf("method fails to converge");exit(1);}; x0=x1; x1=x2; }while(fabs((*f)(x0))>e); printf("Root is %6.4g",x0); }
C
/* * File name: CTRL_Application.h * Created on: Oct 21, 2021 * Author: osama */ #ifndef CTRL_APPLICATION_H_ #define CTRL_APPLICATION_H_ /********************************************************/ /* Definitions & Configurations */ /********************************************************/ #define PASSWORD_LENGTH (5) #define DOOR_UNLOCKING_PERIOD (5) #define DOOR_LEFT_OPEN_PERIOD (3) #define NUMBER_OF_WRONG_PASSWORD_ATTEMPTS (3) #define ALARM_ON_DELAY (3) /* following definitions used to communicate with HMI ECU */ #define PASSWORD_MATCHED (1) #define PASSWORD_MISMATCHED (0) #define READY_TO_SEND (0x15) #define READY_TO_RECEIVE (0x16) #define CHANGE_PASSWORD_OPTION (0x18) #define UNLOCKING_DOOR (0x25) #define WRONG_PASSWORD (0x30) #define CHANGING_PASSWORD (0X31) #define TWI_CONTROL_ECU_ADDRESS (0x1) #define EEPROM_STORE_ADDREESS (0x00) /********************************************************/ /* Global variables */ /********************************************************/ uint8 g_receivedPassword[PASSWORD_LENGTH]; uint8 g_storedPassword[PASSWORD_LENGTH]; uint8 g_wrongPasswordCounter=0; uint16 g_seconds = 0; /********************************************************/ /* Functions prototypes */ /********************************************************/ /* * Description: a function to compare the stored pass with the received one * */ uint8 compare_passwords(uint8 a_password1[PASSWORD_LENGTH],uint8 a_password2[PASSWORD_LENGTH]); /* * Description: a function to initialize the password in first-run OR to change the password * */ void initializePassword(void); /* * Decription: A function that rotates on the DC motor for 15 seconds clockwise, stops it for 3 seconds, then * rotates it anti-clockwise for 15 seconds. * */ void DoorOpeningTask(void); /* * Decription: the call-back function called by the timer every 1 second * */ void timerCallBack(void); /* * Description: A function to receive the password via UART by looping on receiveByte function * */ void receivePasswordViaUART(uint8 * passwordArray); /* * Description: A function to retreive the stored password from EEPROM * */ void updateStoredPassword(void); /* * Description: A function to store the password in EEPROM * */ void storePassword(void); #endif /* CTRL_APPLICATION_H_ */
C
#include <math.h> #include "vector.h" struct Vector VEC_N = {0, -1}; struct Vector VEC_S = {0, 1}; struct Vector VEC_E = {1, 0}; struct Vector VEC_W = {-1, 0}; struct Vector VEC_NE = {1 / sqrt(2), -1 / sqrt(2)}; struct Vector VEC_NW = {-1 / sqrt(2), -1 / sqrt(2)}; struct Vector VEC_SE = {1 / sqrt(2), 1 / sqrt(2)}; struct Vector VEC_SW = {-1 / sqrt(2), 1 / sqrt(2)}; struct Vector ZERO = {0, 0}; double magnitude(struct Vector v) { return sqrt(v.x * v.x + v.y * v.y); } struct Vector normalize(struct Vector v) { double m = magnitude(v); if (m != 0) return scale(v, 1 / m); else return ZERO; } struct Vector scale(struct Vector v, double scalar) { struct Vector w = {v.x * scalar, v.y * scalar}; return w; } struct Vector add(struct Vector u, struct Vector v) { struct Vector w = {u.x + v.x, u.y + v.y}; return w; } struct Vector subtract(struct Vector u, struct Vector v) { struct Vector w = {u.x - v.x, u.y - v.y}; return w; } double gaussian(double x, double a) { return exp(-a * x * x); } double dot_product(struct Vector u, struct Vector v) { return u.x * v.x + u.y * v.y; } /* Project v onto b. */ struct Vector projection(struct Vector v, struct Vector b) { struct Vector w = ZERO; w = normalize(b); w = scale(w, dot_product(v, b)); return w; } double signum(double x) { if (x == 0) return 0; else if (x > 0) return 1; else if (x < 0) return -1; } bool equal(struct Vector u, struct Vector v) { return (u.x == v.x) && (u.y == v.y); } struct Vector round_vector(struct Vector v) { v.x = round(v.x); v.y = round(v.y); return v; }
C
/** * @file sock_init.c * @author your name ([email protected]) * @brief * @version 0.1 * @date 2021-09-12 * * @copyright Copyright (c) 2021 * */ #include "tftpd_commands/tftp_sock_init.h" struct tftp_connection *tftp_conn; bool tftp_sock_init (char *ip, u_short port) { int retval; tftp_conn = (struct tftp_connection *)malloc (sizeof (struct tftp_connection)); if (tftp_conn == NULL) return false; tftp_conn->fd = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (tftp_conn->fd == -1) return false; bzero (tftp_conn->mode, 10); tftp_conn->addr.sin_family = AF_INET; tftp_conn->addr.sin_port = htons (port); tftp_conn->addr.sin_addr.s_addr = inet_addr (ip); tftp_conn->saddrLen = sizeof (tftp_conn->addr); retval = bind (tftp_conn->fd, (struct sockaddr *)&tftp_conn->addr, tftp_conn->saddrLen); if (retval == -1) return false; return true; }
C
#include"functions.h" void interface(int socket) { int option=0; printf("Welcome! enter one of the following options to continue...\n"); printf("1 : Sign Up\n"); printf("2 : Sign In\n"); scanf("%d",&option); while(option!=1 && option!=2) { printf("Select either 1 or 2 :- "); scanf("%d",&option); } int c=0; int h=0; if(option==1) { printf("How would you like to sign up?\n"); printf("1 : User\n"); printf("2 : Administrator\n"); printf("3 : Joint Account User\n"); scanf("%d",&option); while(option!=1 && option!=2 && option!=3) { printf("Select either 1 or 2 or 3:- "); scanf("%d",&option); } // printf("%d\n",option); if(option==1) { h=get_details_from_user(socket,SIGN_UP_AS_USER); c=USER; } else if(option==2) { h=get_details_from_user(socket,SIGN_UP_AS_ADMIN); c=ADMIN; } else if(option==3) { h=get_details_from_user(socket,SIGN_UP_AS_JOINT); c=JOINT_USER; } } else if(option==2) { // printf("%d\n",option); printf("How would you like to sign in?\n"); printf("1 : User\n"); printf("2 : Administrator\n"); printf("3 : Joint Account User\n"); scanf("%d",&option); while(option!=1 && option!=2 && option!=3) { printf("Select either 1 or 2 or 3:- "); scanf("%d",&option); } // printf("%d\n",option); if(option==1) { h=get_details_from_user(socket,SIGN_IN_AS_USER); c=USER; } else if(option==2) { h=get_details_from_user(socket,SIGN_IN_AS_ADMIN); c=ADMIN; } else if(option==3) { h=get_details_from_user(socket,SIGN_IN_AS_JOINT); c=JOINT_USER; } } if(h) { while(1) { // printf("%d\n",c); if(c==USER || c==JOINT_USER) { printf("What can we help you with?\n"); printf("1 : Deposit\n"); printf("2 : Withdraw\n"); printf("3 : Check Balance\n"); printf("4 : Change Password\n"); printf("5 : View Details\n"); printf("6 : Sign Out\n"); scanf("%d",&option); while(option!=1 && option!=2 && option!=3 && option!=4 && option!=5 && option!=6) { printf("Select either 1 or 2 or 3 or 4 or 5 or 6:- "); scanf("%d",&option); } char option_string[SIZE]; if(option==1) { sprintf(option_string,"%d",DEPOSIT); write(socket,option_string,SIZE); int damt; char damt_string[SIZE]; printf("Enter amount to be deposited : "); scanf("%d",&damt); sprintf(damt_string,"%d",damt); write(socket, damt_string, SIZE); } else if(option==2) { sprintf(option_string,"%d",WITHDRAW); write(socket,option_string,SIZE); int wamt; char wamt_string[SIZE]; printf("Enter amount to be withdrawn : "); scanf("%d",&wamt); sprintf(wamt_string,"%d",wamt); write(socket, wamt_string, SIZE); } else if(option==3) { sprintf(option_string,"%d",BALANCE); write(socket,option_string,SIZE); } else if(option==4) { sprintf(option_string,"%d",PASSWORD); write(socket,option_string,SIZE); // printf("Enter old password\n"); char old_pass[SIZE],new_pass[SIZE]; // scanf("%s",old_pass); printf("Enter new password:-"); scanf("%s",new_pass); printf("%s",new_pass); // write(socket, old_pass, SIZE); write(socket, new_pass, SIZE); } else if(option==5) { sprintf(option_string,"%d",DETAILS); write(socket,option_string,SIZE); } else if(option==6) { sprintf(option_string,"%d",SIGN_OUT); write(socket,option_string,SIZE); return; } } else if(c==ADMIN) { printf("1 : Add User\n"); printf("2 : Delete User\n"); printf("3 : Modify User\n"); printf("4 : Search User Details\n"); printf("5 : Sign Out\n"); scanf("%d",&option); while(option!=1 && option!=2 && option!=3 && option!=4 && option!=5) { printf("Select either 1 or 2 or 3 or 4 or 5 :- "); scanf("%d",&option); } char option_string[SIZE]; if(option==1) { sprintf(option_string,"%d",ADD_USER); write(socket,option_string,SIZE); int type; char username[SIZE]; char password[SIZE]; printf("Enter User Account Type\n"); printf("1 : Normal\n"); printf("2 : Joint\n"); scanf("%d",&type); while(type!=1 && type!=2) { printf("Select either 1 or 2 :- "); scanf("%d",&type); } printf("Enter username : "); scanf("%s",username); printf("Enter password : "); scanf("%s",password); if(type==1) { char type_string[SIZE]; sprintf(type_string,"%d",SIGN_UP_AS_USER); write(socket,type_string,SIZE); } else if(type==2) { char type_string[SIZE]; sprintf(type_string,"%d",SIGN_UP_AS_JOINT); write(socket,type_string,SIZE); } write(socket,username,SIZE); write(socket,password,SIZE); } else if(option==2) { sprintf(option_string,"%d",DELETE_USER); write(socket,option_string,SIZE); char username[SIZE]; printf("Enter username to be deleted : "); scanf("%s",username); write(socket,username,SIZE); } else if(option==3) { sprintf(option_string,"%d",MODIFY_USER); write(socket,option_string,SIZE); char old_username[SIZE]; char new_username[SIZE]; char password[SIZE]; printf("Enter username to be modified : "); scanf("%s",old_username); printf("Enter new username : "); scanf("%s",new_username); printf("Enter new password : "); scanf("%s",password); write(socket,old_username,SIZE); write(socket,new_username,SIZE); write(socket,password,SIZE); } else if(option==4) { sprintf(option_string,"%d",GET_USER_DETAILS); write(socket,option_string,SIZE); char username[SIZE]; printf("Enter username to get details : "); scanf("%s",username); printf("%s\n",username); write(socket , username , SIZE); } else if(option==5) { sprintf(option_string,"%d",SIGN_OUT); write(socket,option_string,SIZE); return; } } char return_message[SIZE]; read(socket , return_message, SIZE); printf("%s\n\n",return_message); } } else { char option_string[SIZE]; printf("Sign In/Sign Up not successful\n"); sprintf(option_string,"%d",EXIT); write(socket,option_string,SIZE); return; } } int main() { int client_socket_sd; struct sockaddr_in server; int addrlen=sizeof(server); if ((client_socket_sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("Creating Socket failed...\n"); return -1; } server.sin_family = AF_INET; server.sin_port = htons(PORT_NO); // server.sin_addr.s_addr = inet_addr("127.0.0.1"); if(inet_pton(AF_INET, "127.0.0.1", &server.sin_addr)<=0) { printf("Invalid address/ Address not supported \n"); return -1; } if (connect(client_socket_sd, (struct sockaddr *)&server, sizeof(server)) < 0) { printf("Connection to Server Failed \n"); return -1; } interface(client_socket_sd); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "getCharTest.c" #define MAXWORD 50 struct node{ char *string; struct node *downLeft; struct node *downRight; int len; int occurrence; struct node *left; struct node *right; }; int strcmpPre(char *str1, char *str2, int num){ while(num-->0){ if(*str1 != *str2) return *str1 - *str2; str1++; str2++; } return 0; } struct node *addtree(struct node *p,char *word,int num){ int downCond, forwCond; if(p == NULL){ p = (struct node *) malloc(sizeof(struct node)); p->string = strdup(word); p->len = 1; p->occurrence = 1; p->downLeft = NULL; p->downRight = NULL; p->left = NULL; p->right = NULL; }else if((downCond = strcmpPre(word,p->string,num)) == 0){ p->len++; if((forwCond = strcmp(word,p->string) ) == 0){ p->occurrence++; //this is the case }else if(forwCond < 0){ p->downLeft = addtree(p->downLeft,word,num); //printf("%s was added to the downleft of %s\n",word,p->string); }else{ p->downRight = addtree(p->downRight,word,num); //printf("%s was added to the downright of %s\n",word,p->string); } }else if(downCond < 0){ p->left = addtree(p->left,word,num); //printf("%s was added to the left of %s\n",word,p->string); }else{ p->right = addtree(p->right,word,num); //printf("%s was added to the right of %s\n",word,p->string); } return p; } void downPrint(struct node *p){ if(p != NULL){ downPrint(p->downLeft); printf("%s\t",p->string); downPrint(p->downRight); } } void forwPrint(struct node *p){ if(p!= NULL){ forwPrint(p->left); downPrint(p); printf("\n"); forwPrint(p->right); } } int getword(char *word, int lim){ char *w = word; int c, cond = 1; while(isspace(c = getch()) || c == '\t' || c == '\n') ; if(!isalpha(c)){ *w = '\0'; if(c == '/'){ if((c = getch()) == '/'){ while((c = getch()) != '\n') ; }else if(c == '*'){ int d; while(!((c = getch() )== '*' && (d = getch()) == '/')) ; }else{ ungetch(c); } } if( c == '"'){ while((c = getch()) != '"') ; } return c; }else{ *w++ = c; } while(--lim> 0 && cond){ c = getch(); if(isalnum(c)){ *w++ = c; }else{ ungetch(c); cond = 0; } } *w = '\0'; return word[0]; } int tryFindNum(char *str){ //printf("%s",str); int result; while(isdigit(*str)){ result = result*10 + (*str++ - '0'); } if(*str != '\0'){ printf("illegal para: %c\n",*str); return -2; //error }else{ return result; } } int main(int argc, char *argv[]){ int num = -1 , nflag = 0, c,neg = 0,cont = 1; while(--argc>0 && ( (isdigit(c = **(++argv)) && nflag) || (!nflag && c == '-') ) ){ neg = (!nflag && c == '-') ? -1:1; while(cont == 1 && (c = ((nflag && isdigit(c)) ? c:*++argv[0]) ) ){ switch(c){ case 'n': nflag = 1; break; default: if(nflag && isdigit(c)){ cont = 0; num = tryFindNum(*argv) * neg; if(num<0) argc = -1; break; } neg = 0; printf("usage: read [-n num]\n"); argc = -1; break; } } } printf("test output\n"); if(c == '-' && nflag){ printf("usage: read [-n num(nonnegative)]\n"); }else if(num< 0 && nflag){ num = 6; } if(nflag == 0) num = 6; printf("num = %d \t nflag = %d argc = %d\n",num,nflag,argc); if(argc == 0){ char word[MAXWORD]; struct node *root = NULL; while(getword(word,MAXWORD) != EOF){ //printf("word: %s\n",word); if(isalpha(word[0])){ root = addtree(root,word,num); } } forwPrint(root); } //printf("done\n"); }
C
#define MAX_COL 100 #define MAX_LIN 100 typedef struct info_s{ char caminho[MAX_LIN][MAX_COL]; // ponteiro para as linhas do mapa int linhas; // guarda o numero de linhas int colunas; // guarda o numero de colunas }info_t; info_t *infoMapa; typedef struct pilha_s{ int atual; int quantidade; int *linha; int *coluna; }pilha_t; uint8_t **mascara; char nomeArquivo[100]; /* funcao percorre o mapa ate encontrar o ponto final ('y') */ void percorreMapa(pilha_t *pilha){ int i, j, contFalha, ret; for (i=0, j=0, contFalha=0;;){ if(j == 4) j = 0; // volta para a primeira direcao da mascara if(i==10){ mascara[1][0] = mascara[3][0] = mascara[5][0] = mascara[7][0] = mascara[9][0] = 255; i=0; continue; } if(mascara[i+1][0]==0){ i+=2; continue; } if(mascara[i][j] == 0){ ret = andaCima(pilha); if(ret == -1 || ret == 0){ contFalha++; j++; }else if(ret == 1){ mascara[i+1][0]--; contFalha = 0; }else if(ret == 2) break; }else if(mascara[i][j] == 1){ ret = andaEsquerda(pilha); if(ret == -1 || ret == 0){ contFalha++; j++; }else if(ret == 1){ mascara[i+1][0]--; contFalha = 0; }else if(ret == 2) break; }else if(mascara[i][j] == 2){ ret = andaBaixo(pilha); if(ret == -1 || ret == 0){ contFalha++; j++; }else if(ret == 1){ mascara[i+1][0]--; contFalha = 0; }else if(ret == 2) break; }else if(mascara[i][j] == 3){ ret = andaDireita(pilha); if(ret == -1 || ret == 0){ contFalha++; j++; }else if(ret == 1){ mascara[i+1][0]--; contFalha = 0; }else if(ret == 2) break; }else{ printf("problema com a mascara\n"); exit(EXIT_FAILURE); } if(contFalha == 4){ pilha->atual--; contFalha=0; } } } /* funcao imprime mapa carregado na memoria (infoMapa) */ void imprimeMapa(){ int i; getc(stdout); system("clear"); for(i=0; i<infoMapa->linhas; i++) printf("\t\t\t\t\t\t%s", infoMapa->caminho[i]); } /* funcao percorre coluna por coluna, linha por linha ate encontrar um x no mapa, o qual ele considera a posicao inicial do robo */ void encontraInicio(pilha_t *pilha){ int i, j; for (i=0; i<infoMapa->linhas; i++){ for(j=0; j<infoMapa->colunas; j++){ if(infoMapa->caminho[i][j] == 'x'){ pilha->linha[0] = i; pilha->coluna[0] = j; return; } } } } /* Funcao movimenta 'robo' para direcao definida em seu nome retorno revela se encontrou, nao andou ou andou caso funcao encontre um caractere diferente dos esperados (y,*,x,' ') deve interromper a execucao */ int andaCima(pilha_t *pilha){ int atual = pilha->atual; if(infoMapa->caminho[pilha->linha[atual]-1][pilha->coluna[atual]] == 'y') return 2; //achou else if (infoMapa->caminho[pilha->linha[atual]-1][pilha->coluna[atual]] == '*') return 0; //limite, nao pode andar mais nesta direcao else if (infoMapa->caminho[pilha->linha[atual]-1][pilha->coluna[atual]] == 'x') return -1; //posicao ja caminhada else if (infoMapa->caminho[pilha->linha[atual]-1][pilha->coluna[atual]] == ' '){ infoMapa->caminho[pilha->linha[atual]-1][pilha->coluna[atual]] = 'x'; pilha->linha[atual+1] = pilha->linha[atual]-1; pilha->coluna[atual+1] = pilha->coluna[atual]; pilha->atual++; pilha->quantidade++; return 1; //sucesso, andou }else{ imprimeMapa(); printf("simbolo desconhecido no mapa\nsimbolo: '%c'", infoMapa->caminho[pilha->linha[atual]-1][pilha->coluna[atual]]); exit(EXIT_FAILURE); } } /* Funcao movimenta 'robo' para direcao definida em seu nome retorno revela se encontrou, nao andou ou andou caso funcao encontre um caractere diferente dos esperados (y,*,x,' ') deve interromper a execucao */ int andaBaixo(pilha_t *pilha){ int atual = pilha->atual; if(infoMapa->caminho[pilha->linha[atual]+1][pilha->coluna[atual]] == 'y') return 2; //achou else if (infoMapa->caminho[pilha->linha[atual]+1][pilha->coluna[atual]] == '*') return 0; //limite, nao pode andar mais nesta direcao else if (infoMapa->caminho[pilha->linha[atual]+1][pilha->coluna[atual]] == 'x') return -1; //posicao ja caminhada else if (infoMapa->caminho[pilha->linha[atual]+1][pilha->coluna[atual]] == ' '){ infoMapa->caminho[pilha->linha[atual]+1][pilha->coluna[atual]] = 'x'; pilha->linha[atual+1] = pilha->linha[atual]+1; pilha->coluna[atual+1] = pilha->coluna[atual]; pilha->atual++; pilha->quantidade++; return 1; //sucesso, andou }else{ imprimeMapa(); printf("simbolo desconhecido no mapa\nsimbolo: '%c'", infoMapa->caminho[pilha->linha[atual]+1][pilha->coluna[atual]]); exit(EXIT_FAILURE); } } /* Funcao movimenta 'robo' para direcao definida em seu nome retorno revela se encontrou, nao andou ou andou caso funcao encontre um caractere diferente dos esperados (y,*,x,' ') deve interromper a execucao */ int andaDireita(pilha_t *pilha){ int atual = pilha->atual; if(infoMapa->caminho[pilha->linha[atual]][pilha->coluna[atual]+1] == 'y') return 2; //achou else if (infoMapa->caminho[pilha->linha[atual]][pilha->coluna[atual]+1] == '*') return 0; //limite, nao pode andar mais nesta direcao else if (infoMapa->caminho[pilha->linha[atual]][pilha->coluna[atual]+1] == 'x') return -1; //posicao ja caminhada else if (infoMapa->caminho[pilha->linha[atual]][pilha->coluna[atual]+1] == ' '){ infoMapa->caminho[pilha->linha[atual]][pilha->coluna[atual]+1] = 'x'; pilha->linha[atual+1] = pilha->linha[atual]; pilha->coluna[atual+1] = pilha->coluna[atual]+1; pilha->atual++; pilha->quantidade++; return 1; //sucesso, andou }else{ imprimeMapa(); printf("simbolo desconhecido no mapa\nsimbolo: '%c'", infoMapa->caminho[pilha->linha[atual]][pilha->coluna[atual]+1]); exit(EXIT_FAILURE); } } /* Funcao movimenta 'robo' para direcao definida em seu nome retorno revela se encontrou, nao andou ou andou caso funcao encontre um caractere diferente dos esperados (y,*,x,' ') deve interromper a execucao */ int andaEsquerda(pilha_t *pilha){ int atual = pilha->atual; if(infoMapa->caminho[pilha->linha[atual]][pilha->coluna[atual]-1] == 'y') return 2; //achou else if (infoMapa->caminho[pilha->linha[atual]][pilha->coluna[atual]-1] == '*') return 0; //limite, nao pode andar mais nesta direcao else if (infoMapa->caminho[pilha->linha[atual]][pilha->coluna[atual]-1] == 'x') return -1; //posicao ja caminhada else if (infoMapa->caminho[pilha->linha[atual]][pilha->coluna[atual]-1] == ' '){ infoMapa->caminho[pilha->linha[atual]][pilha->coluna[atual]-1] = 'x'; pilha->linha[atual+1] = pilha->linha[atual]; pilha->coluna[atual+1] = pilha->coluna[atual]-1; pilha->atual++; pilha->quantidade++; return 1; //sucesso, andou }else{ imprimeMapa(); printf("simbolo desconhecido no mapa\nsimbolo: '%c'", infoMapa->caminho[pilha->linha[atual]][pilha->coluna[atual]-1]); exit(EXIT_FAILURE); } } /* Função recebe 80 bits e transforma em um conjunto de 5 mascaras com o seguinte formato: mascara[0][0-3] 4 direcoes em ordem mascara[1][0] quantidade de passos a seguir com a mascara [0] mascara[2][0-3]... mascara[9][0] quantidade de passos a seguir com a mascara da posicao [8] */ void criaMascara(uint8_t *p){ int i, j, aux=0; uint8_t byte; for(i=0; i<=8; i+=2, aux=0){ byte = p[i]; // recebe o byte que vai se transformar nas direcoes mascara[i+1][0] = p[i+1]; // recebe byte com a quantidade de passos // utiliza dois bits mais significativos para definir primeira direcao (0-3) mascara[i][0] = (byte >> 6); // utiliza os 5 bits depois do menos significativo para definir a segunda direcao // caso a primeira direcao seja igual a segunda, a segunda eh incrementada em 1 mascara[i][1] = (mascara[i][0] == (((byte & 62) >> 1) % 3)) ? (mascara[i][0]+1) : (((byte & 62) >> 1) % 3); // caso a segunda direcao se torne 4 por causa do incremento, se torna 0 por definicao if(mascara[i][1] == 4) mascara[i][1] = 0; // aux guarda bits para marcar quais as direcoes ja foram utilizadas // caso a direcao 0 ja estiver sendo utilizada, bit menos significativo de aux eh ligado // caso a direcao 1 ja estiver sendo utilizada, segundo bit menos significativo de aux eh ligado // caso a direcao 2 ja estiver sendo utilizada, terceiro bit menos significativo de aux eh ligado // caso a direcao 3 ja estiver sendo utilizada, quarto bit menos significativo de aux eh ligado for(j=0; j<2; j++){ if(mascara[i][j] == 0) aux = aux | 1; else if(mascara[i][j] == 1) aux = aux | 2; else if(mascara[i][j] == 2) aux = aux | 4; else if(mascara[i][j] == 3) aux = aux | 8; } // caso algum erro tenha acontecido na geracao da mascara o programa devera ser finalizado if(!(aux == 3 || aux == 5 || aux == 6 || aux == 9 || aux == 10 || aux == 12)){ printf("erro com a mascara"); exit(EXIT_FAILURE); } // utiliza o bit menos significativo para definir a terceira direcao // se o bit estiver ligado, a maior direcao restante sera a terceira, caso contrario a menor // lembrando que a variavel aux guarda as direcoes que ja foram utilizadas switch(aux){ case 3: if(byte & 1 == 1){ mascara[i][2] = 3; mascara[i][3] = 2; }else{ mascara[i][2] = 2; mascara[i][3] = 3; } break; case 5: if(byte & 1 == 1){ mascara[i][2] = 3; mascara[i][3] = 1; }else{ mascara[i][2] = 1; mascara[i][3] = 3; } break; case 6: if(byte & 1 == 1){ mascara[i][2] = 3; mascara[i][3] = 0; }else{ mascara[i][2] = 0; mascara[i][3] = 3; } break; case 9: if(byte & 1 == 1){ mascara[i][2] = 2; mascara[i][3] = 1; }else{ mascara[i][2] = 1; mascara[i][3] = 2; } break; case 10: if(byte & 1 == 1){ mascara[i][2] = 2; mascara[i][3] = 0; }else{ mascara[i][2] = 0; mascara[i][3] = 2; } break; case 12: if(byte & 1 == 1){ mascara[i][2] = 1; mascara[i][3] = 0; }else{ mascara[i][2] = 0; mascara[i][3] = 1; } break; } } } /* funcao retorna numero de passos utilizados para encontrar o ponto final ('y') */ float fitness(uint8_t *p){ int i,qtd; pilha_t *pilha; FILE *arquivo; // carrega arquivo e atualiza limites do mapa (infoMapa->linhas e infoMapa->colunas) arquivo = fopen(nomeArquivo, "r"); infoMapa->linhas=0; infoMapa->colunas=0; for(i=0;fgets(infoMapa->caminho[i], MAX_COL, arquivo);i++) infoMapa->linhas++; infoMapa->colunas=strlen(infoMapa->caminho[0]); fclose(arquivo); if((pilha = (pilha_t *) malloc(sizeof(pilha_t))) == NULL){ printf("erro na alocacao de memoria para o ponteiro pilha\n"); exit(EXIT_FAILURE); } if((pilha->linha = (int *) malloc(MAX_LIN*MAX_COL*sizeof(int))) == NULL){ printf("erro na alocacao de memoria para o ponteiro pilha->linha\n"); exit(EXIT_FAILURE); } if((pilha->coluna = (int *) malloc(MAX_LIN*MAX_COL*sizeof(int))) == NULL){ printf("erro na alocacao de memoria para o ponteiro pilha->coluna\n"); exit(EXIT_FAILURE); } pilha->atual=0; pilha->quantidade=0; // neste ponto temos memoria alocada para a pilha inteira // ha uma sobra de memoria para os ponteiros linha e coluna pois estou // alocando memoria suficiente para aceitar o maximo de linhas e colunas ao // inves de usar os ponteiros 'linhas' e 'colunas' da estrutura infoMapa // que contem o numero exato de linhas do mapa encontraInicio(pilha); // encontra o ponto x do mapa, aonde o 'robo' deve comecar a andar criaMascara(p); // cria mascara de direcoes e movimentos com os bytes gerados pelo alg genetico percorreMapa(pilha); // percorre mapa e atualiza pilha com a quantidade de movimentos usados qtd = pilha->quantidade; free(pilha->linha); free(pilha->coluna); free(pilha); return 1./(1+qtd); // retorna resultado da fitness }
C
#include<stdio.h> #include<stdlib.h> #define TOKEN_SIZE 2000 #define TOKEN_ARRAY_SIZE 200 int strcmp(const char *s1,const char *s2); char** strtoken(const char *s, const char *delim,int *len); void strcat(char* envPath, char* path); void strcpy(char* dest, char* src); int strlen(char *s); void free_array(char **tokens,int len); void cmd_cd(char** tokens); void cmd_set_path(char* tokens,char *envp[],int path_index,char* envpath); int cmd_set_ps1(char* command, char** ps1); void cmd_binary(char** tokens,int len,char *envp[]); void cmd_script(char** tokens,int len,char *envp[]); int cmd_pipe_init(char **tokens, int pipes, char **envp); int isBinary(char** tokens,int len); int isScript(char** tokens,int len); int runPipe(char *tokens[],char *envp[], int pipes); void trim(char *s); void printPrompt(char* str,int print_prompt_flag); char* getpath(int *index, char *envp[]); int is_path(char *str); int main(int argc, char *argv[],char *envp[]) { char name[1000]; int token_len,index; int i,PRINT_PROMPT_FLAG=1, ps1Flag=0, isValid; //char path char prompt[500]; char *prompt_ret,**tokens,*path; int in; if (argc==2) { //execute script int open(const char *pathname, int flags); if((in=open(argv[1],O_RDONLY))==-1) { perror("unable to read file %s\n",argv[1]); exit(0); } dup2(in,0); PRINT_PROMPT_FLAG=0; } while(1) { //printf("sbush@cse506$ "); path = getpath(&index, envp); //function to get the 'value' of PATH environment variable; gives the index of the same //free path in every iteration if(ps1Flag == 0) { prompt_ret=getcwd(prompt,sizeof(prompt)+1);//no need to free prompt //prompt_ret is pointer to prompt if(prompt_ret!=NULL) { strcat(prompt,"$ "); printPrompt(prompt,PRINT_PROMPT_FLAG); } else{ perror("getcwd failed.\n"); } } else printPrompt(prompt,PRINT_PROMPT_FLAG); if(scanf("%s", name) == -1) break; if((strlen(name)==0) || (name[0]=='#')){ free(path); continue; } if(strcmp(name, "exit") == 0) { break; } trim(name); tokens = strtoken(name, "|", &token_len); if(token_len > 1) //pipes { cmd_pipe_init(tokens, token_len-1, envp); } else //excluding pipes { tokens = strtoken(name, " ",&token_len); i = 0; if(strcmp(tokens[i],"cd")==0) { if(token_len==2) cmd_cd(tokens); else perror("incorrect syntax for cd\n"); } else if(strcmp(tokens[i],"set")==0) { if((strcmp(tokens[i+1], "PATH")==0) && (token_len == 3)) { cmd_set_path(tokens[i+2],envp,index,path); printf("%s\n", envp[index]); } else if((strcmp(tokens[i+1], "PS1")==0) && (token_len >=3)) { isValid = cmd_set_ps1(name, tokens); if(isValid) { strcpy(prompt, tokens[0]); ps1Flag = 1; } else perror("Incorrect syntax for PS1 command\n"); } else perror("incorrect syntax for set command\n"); } else if(token_len >= 1) { //binary or script if(isScript(tokens,token_len)) { if(token_len==2) cmd_script(tokens,token_len,envp); else perror("input filename missing\n"); } else { //printf("binary\n"); cmd_binary(tokens,token_len,envp); } } else perror("unknown command\n"); free_array(tokens,token_len); } } free(path); return 1; } void free_array(char **tokens,int len) { int i; for(i=0; i<len; i++) free(tokens[i]); free(tokens); } void printPrompt(char* str,int print_prompt_flag) { if(print_prompt_flag) printf("%s",str); } int is_path(char *str){ int i=0; while(str[i]!='\0' && str[i]!='/' ){ i++; } if(str[i]=='\0') return 0; return 1; } void cmd_binary(char** tokens,int token_len,char *envp[]) { int status; int path_index,path_len; int pid=fork(); if(pid==0) { //child /*is_path() then do execve(path) if execve fails then do printf('no such file\n') and exit(1);child else then its filename to be searched in path variables */ if(is_path(tokens[0])){ if(execve(tokens[0],tokens,envp)==-1){ perror("unable to execute %s->errno->%d\n",tokens[0],errno); exit(1); } } else{ //printf("child\n"); //printf("binary file-execve-error %s\n",tokens[0]);; //trying path directories char* path_raw=getpath(&path_index,envp); trim(path_raw); char** paths=strtoken(path_raw,":",&path_len); char *org=tokens[0]; int i; for(i=0; i<path_len; i++) { strcat(paths[i],"/"); strcat(paths[i],org); tokens[0]=paths[i]; if(execve(paths[i],tokens,envp)==-1) { //printf("binary file-execve-error %s\n",paths[i]); ; } } perror("cannot execute %s by looking up all directories in PATH\n",org); //free_array(tokens,token_len); //getting error double free //maybe because of copy on write which linux follows tokens[0]=org; free_array(paths,path_len); free(path_raw); exit(1); } } else if(pid > 0) { if(strcmp(tokens[token_len-1],"&")){ int ret = waitpid(-1,&status,0); if(ret ==-1){ perror("error in waitpid. Error no is %d\n",errno); } else{ while( pid != ret ){ ret=waitpid(-1,&status,0); if(ret ==-1){ perror("error in waitpid. Error no is %d\n",errno); break ; } } } } } else { //error on fork perror("error on fork...try again\n"); } } void cmd_script(char** tokens,int token_len,char *envp[]) { int status; int pid=fork(); if(pid==0) { //child char *params[]= {"./rootfs/bin/sbush",0,0}; //hardode must fix this params[1]=tokens[1]; if(execve(params[0],params,envp)==-1) { perror("unable to fork sbush child\n"); } exit(0); } else if(pid > 0) { //parent if(pid == waitpid(pid,&status,0)){ /* wait till child exits */ //printf("child exit successful\n"); ; } else{ perror("error in waitpid. Error no is %d\n",errno); } } else { //error on fork perror("error on fork...try again\n"); } } int isScript(char** tokens,int len) { /* if(strcmp(tokens[0],"sbush")==0) */ /* return 1; */ /* else */ return 0; } int isBinary(char** tokens,int len) { return 1; } void cmd_cd(char** tokens) { if(chdir(tokens[1])<0) perror("error in chdir %d\n",errno); } void cmd_set_path(char* cmdpath, char **envp, int path_index, char* envpath) { int token_len=0, i=0; char *sbushPath = (char*)malloc(TOKEN_SIZE*sizeof(char)); sbushPath[0] = '\0'; char **tokens; trim(cmdpath);//removes leading and trailing white spaces tokens = strtoken(cmdpath, ":", &token_len); //printf("path length is %d, %s\n", token_len, tokens[token_len-1]); for (i=0; i<token_len; i++) { if(i>0) strcat(sbushPath, ":"); if(strcmp(tokens[i], "$PATH")!=0) strcat(sbushPath, tokens[i]); else strcat(sbushPath, envpath); } strcpy(envp[path_index], "PATH="); strcat(envp[path_index], sbushPath); free(sbushPath); free_array(tokens, token_len); } int cmd_set_ps1(char* command, char** ps1) { int token_len = 0; char **tokens; trim(command); tokens = strtoken(command, "\"", &token_len); if(token_len != 2) return 0; strcpy(ps1[0], tokens[1]); free_array(tokens, token_len); return 1; } int cmd_pipe_init(char **tokens, int pipes, char **envp) { //fork a child and run that process int pid,status; pid=fork(); if(pid==-1) { perror("unable to fork child\n"); } else if(pid==0) { //child runPipe(tokens,envp,pipes); } else { //parent, do nothing if(pid == waitpid(pid,&status,0)){ /* pick up all the dead children */ //printf("child exit successful\n"); ; } else{ perror("error in waitpid. Error no is %d\n",status); exit(1); } } return 0; } int runPipe(char *tokens[],char *envp[], int pipes) { int fd[2],pid,status; int param_len; char **params = (char**)malloc(TOKEN_ARRAY_SIZE*sizeof(char*)); trim(tokens[pipes]); params = strtoken(tokens[pipes], " ", &param_len); pipe(fd); if(pipes==0) //end case { close(fd[0]);//close read end //dup2(fd[1],1);//dup write end cmd_binary(params,param_len,envp); exit(0); } else { pid=fork(); if(pid==-1) perror("unable to fork child\n"); else if(pid==0) { //child close(fd[0]); //close read end dup2(fd[1],1); runPipe(tokens,envp,--pipes); } else { //parent close(fd[1]); //close write end dup2(fd[0],0); if(pid == waitpid(pid,&status,0)){ /* pick up all the dead children */ //printf("child exit successful\n"); ; } else{ perror("error in waitpid. Error no is %d\n",status); exit(1); } cmd_binary(params,param_len,envp); exit(0); } } return 0; } void strcat(char* s1, char* s2) { int i=0, j=0; while (s1[i] != '\0') { i++; } while (s2[j] != '\0') { s1[i] = s2[j]; i++; j++; } s1[i] = '\0'; } void strcpy(char* dest, char* src) { int i=0; while(src[i] != '\0') { dest[i] = src[i]; i++; } dest[i] = '\0'; } char* getpath(int *index, char **envp) { int key=0, token_len; char **tokens=(char **)malloc(TOKEN_ARRAY_SIZE*sizeof(char *)); char **temp=tokens; while(envp[key] != '\0') { trim(envp[key]); tokens = strtoken(envp[key],"=", &token_len); if(strcmp(tokens[0], "PATH") == 0) { *index = key; break; } key++; free_array(tokens,token_len);//free strtoken memory for not PATH env variables } free(tokens[0]); free(temp); char *res=tokens[1]; free(tokens); return res; } int strcmp(const char *s1,const char * s2) { int i=0; for(i=0; s1[i]==s2[i]; i++) { if(s1[i]=='\0') return 0; } return s1[i]-s2[i]; } char** strtoken(const char *s, const char *delim,int *len) { int i=0, j=0, k=0; char **tokens = (char**)malloc(TOKEN_ARRAY_SIZE*sizeof(char*)); tokens[j] = (char*)malloc(TOKEN_SIZE*sizeof(char)); while(s[i] != '\0') { if(s[i] == *delim) { tokens[j][k] = '\0'; if(strlen(tokens[j]) > 0) { j++; tokens[j] = (char*)malloc(TOKEN_SIZE*sizeof(char)); } k=0; } else { tokens[j][k] = s[i]; k++; } i++; } if(strlen(tokens[j])>0) { tokens[j][k] = '\0'; tokens[++j] = 0; } else tokens[j] = 0; *len=j; return tokens; } int strlen(char *s) { int i = 0; while(s[i] != '\0') i++; return i; } void trim(char *s) { int lead = 0, trail = 0, i=0,j=0; trail = strlen(s); char *temp = (char*)malloc(TOKEN_SIZE*sizeof(char)); while(s[lead] == ' ') lead++; while(s[trail-1] == ' ') trail--; for(i=lead; i<trail; i++,j++) temp[j] = s[i]; temp[j] = '\0'; strcpy(s, temp); free(temp); }
C
/*Program 5.9 : Write a program that displays sum of the elements passed as command line arguments.*/ #include<stdio.h> #include<stdlib.h> void main(int argc,char* argv[]) { int i; float result; result=0.00; for(i=1;i<argc;i++) result=result+atoi(argv[i]); /* Function atoi(),converts a number represented as a string to number */ printf("\nResult = %f",result); } /* *** OUTPUT *** 15.3 9.4 3.8 Result = 28.5 */
C
#include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct blockInfo { char **blocks; // 2d char array to hold text in keyLength sized blocks char *key; // string used to encipher each block char *IV; // string used to initiate encipher algorithm int keyLength; // must be between 2 and 10 characters inclusive int IVLength; // must be equal to key length int charCount; // number of characters in processed file int numBlocks; // total characters divided by key length int remainder; // dependent on whether keyLength divides evenly into charCount } blockInfo; void panic(char *s) { // print to stderr, just in case normal output is being redirected to a file. fprintf(stderr, "%s", s); // exit with a non-normal return value. exit(1); } // file preprocessing (remove special characters and spaces/ change upper to lower) int processFile(FILE *inputFilePtr, FILE *plainTxtFilePtr) { int charCount; char c; if (inputFilePtr == NULL) panic("ERROR: inputFilePtr is NULL.\n"); if (plainTxtFilePtr == NULL) panic("ERROR: plainTxtFilePtr is NULL.\n"); do { c = getc(inputFilePtr); if (c >= 'A' && c <= 'Z') { c += 32; fprintf(plainTxtFilePtr, "%c", c); charCount++; continue; } else if (c >= 'a' && c <= 'z') { fprintf(plainTxtFilePtr, "%c", c); charCount++; continue; } } while (c != EOF); if (charCount <= 0) panic("ERROR: no text to process in input file!\n"); rewind(plainTxtFilePtr); return charCount; } blockInfo *createBlockInfo(char **array, int charCount) { int i; if (array == NULL) { panic("ERROR: **argv is NULL in createCipherBlock()!\n"); return NULL; } if (charCount <= 0) { panic("ERROR: plain.txt is empty!\n"); return NULL; } blockInfo *info = malloc(sizeof(blockInfo)); info->key = malloc(sizeof(char) * (strlen(array[2]) + 1)); info->IV = malloc(sizeof(char) * (strlen(array[3]) + 1)); // ensure calls to malloc() were successful; free any memory allocated up until that point if (info == NULL) { panic("ERROR: *block is NULL in createCipherBlock()!\n"); free(info); return NULL; } if (info->key == NULL || info->IV == NULL) { panic("ERROR: malloc() failed in main.\n"); free(info->key); free(info->IV); return NULL; } strcpy(info->key, array[2]); strcpy(info->IV, array[3]); info->keyLength = strlen(info->key); info->IVLength = strlen(info->IV); // validate keyLength to avoid segfaults down the road if (info->keyLength < 2 || info->keyLength > 10) panic("ERROR: key length must be between 2 and 10 characters inclusive!\n"); if (info->keyLength != info->IVLength) panic("ERROR: key length must equal intialization vector length!\n"); info->charCount = charCount; info->numBlocks = charCount / info->keyLength;// uses integer division to ensure strings map to correct indices info->remainder = charCount % info->keyLength;// uses mod to identify correct character indices if (info->remainder != 0) info->blocks = malloc(sizeof(char *) * info->numBlocks + 1); else info->blocks = malloc(sizeof(char *) * info->numBlocks); if (info->blocks == NULL) { panic("ERROR: malloc() failed to allocate space for **blocks in encipher().\n"); free(info->blocks); } for (i = 0; i < ((info->remainder) == 0 ? info->numBlocks : info->numBlocks + 1); i++) { info->blocks[i] = malloc(sizeof(char) * info->keyLength + 1); if (info->blocks[i] == NULL) { panic("ERROR: malloc() failed to allocate space for blocks[i] in encipher().\n"); free(info->blocks[i]); } } return info; } int encipher(blockInfo *info, FILE *plainTxtFilePtr, FILE *cipherTxtFilePtr) { int i, j; // avoids segfaults if (info == NULL) { panic("ERROR: *info is NULL in encipher()!\n"); return 1; } if (plainTxtFilePtr == NULL || cipherTxtFilePtr == NULL) { panic("ERROR: a NULL file pointer has been detected in encipher()!\n"); return 1; } for (i = 0; !feof(plainTxtFilePtr); i++) { fgets(info->blocks[i], info->keyLength + 1, plainTxtFilePtr); } // pad remaining cells with 'x' if (info->remainder != 0) for (i = info->keyLength - 1; i > info->remainder - 1; i--) info->blocks[info->numBlocks][i] = 'x'; // convert only the 0th block to cipher text using key and IV for (i = 0; i < info->keyLength; i++) { info->blocks[0][i] = ((((info->blocks[0][i] - 97) + (info->key[i] - 97) + (info->IV[i] - 97)) % 26) + 97); } fprintf(cipherTxtFilePtr, "%s", info->blocks[0]); /// encipher algorithm generalized form: // [(c1 - 97) + (c2 - 97) + (c3 - 97)] = x // ------------------------------------>(x mod 26) + 97 = enciphered character's ASCII value for (i = 1; i <= info->numBlocks; i++) { for (j = 0; j < info->keyLength; j++) info->blocks[i][j] = ((((info->blocks[i][j] - 97) + (info->key[j] - 97) + (info->blocks[i - 1][j] - 97)) % 26) + 97); fprintf(cipherTxtFilePtr, "%s", info->blocks[i]); } rewind(plainTxtFilePtr); rewind(cipherTxtFilePtr); return 0; } void printOutput(blockInfo *info, char **array, FILE *plain, FILE *cipher) { char c; printf("===================================\n"); printf("* ./encipher *\n"); printf("===================================\n"); printf("Input file: %s\n", array[1]); printf("Key: %s\n", info->key); printf("IV: %s\n", info->IV); printf("Block size: %d\n", info->keyLength); printf("\nPlaintext (after preprocessing):\n"); c = fgetc(plain); while (c != EOF) { printf("%c", c); c = fgetc(plain); } printf("\n"); printf("\n# of plaintext characters (before padding): %d\n", info->charCount); printf("\nCiphertext:\n"); c = fgetc(cipher); while (c != EOF) { printf("%c", c); c = fgetc(cipher); } printf("\n"); printf("\nCiphertext file: %s\n", "ciphered.txt"); printf("# of padding characters: %d\n", info->keyLength - info->remainder); return; } blockInfo *destroyBlockInfo(blockInfo *info) { int i; if (info == NULL) return NULL; for (i = 0; i < ((info->remainder) == 0 ? info->numBlocks : info->numBlocks + 1); i++) free(info->blocks[i]); free(info->blocks); free(info->key); free(info->IV); return NULL; } int main(int argc, char **argv) { FILE *inputFilePtr = fopen(argv[1], "r"); FILE *plainTxtFilePtr = fopen("plain.txt", "w+"); FILE *cipherTxtFilePtr = fopen("cipher.txt", "w+"); int i, charCount = processFile(inputFilePtr, plainTxtFilePtr); blockInfo *info = createBlockInfo(argv, charCount); encipher(info, plainTxtFilePtr, cipherTxtFilePtr); printOutput(info, argv, plainTxtFilePtr, cipherTxtFilePtr); destroyBlockInfo(info); fclose(inputFilePtr); fclose(plainTxtFilePtr); fclose(cipherTxtFilePtr); return 0; }
C
#define PCRE2_STATIC #define PCRE2_CODE_UNIT_WIDTH 8 #include <stdio.h> #include <string.h> #include <stdlib.h> #include <string.h> #include "uthash/uthash.h" #include "text_cleanser.h" #include "preg_replace.h" char *replace(char *re, char *replacement, char *subject) { char *output; output = preg_replace(re, replacement, subject); free(subject); return output; } char *cleanse_inbetween_commas(char *subject) { return replace("((?![a-zA-Z]+),(?=[a-zA-Z+]))", " ", subject); } char *cleanse_quotes(char *subject) { return replace("['\"`*]", "", subject); } char *cleanse_brackets(char *subject) { return replace("[\\(\\)\\[\\]\\{\\}]", " " , subject); } char *cleanse_html_entities(char *subject) { return replace("&#?[a-zA-Z0-9]+;", " ", subject); } char *cleanse_newline_characters(char *subject) { return replace("(\\n|\\x0D)", " ", subject); } char *cleanse_article_link_markup(char *subject) { return replace("\\[.+?\\]\\(\\d+\\s\\\".*?\\\"\\)", "", subject); } char *cleanse_non_ascii_characters(char *subject) { return replace("[^\\x00-\\x7F]", "", subject); } char *cleanse_preceding_special_characters(char *subject) { return replace("(^|\\s|\\.\\,)([\\@\\#\\$])+\\b", " ", subject); } char *cleanse_following_special_characters(char *subject) { return replace("\\b([\\!\\?\\%\\.\\,\\:\\;\\/\\$])+(\\Z|\\s|\\.|\\,)", " ",subject); } char *cleanse(char *subject) { char *input = strdup(subject); input = cleanse_non_ascii_characters(input); input = cleanse_article_link_markup(input); input = cleanse_quotes(input); input = cleanse_brackets(input); input = cleanse_inbetween_commas(input); input = cleanse_html_entities(input); input = cleanse_newline_characters(input); input = cleanse_preceding_special_characters(input); input = cleanse_following_special_characters(input); return input; }
C
// Computing the length of a string, recursive function size_t my_strlen_rec(const char *); // Computing the lenght of a string, iterative function size_t my_strlen_ite(const char *); // Comparing two strings "lexical graphically" order, iterative function. int strcmp_ite(const char *, const char *); // Comparing two strings "lexical graphically" order, recursive function. int strcmp_rec(const char *, const char *); // Copy the second string to the first string and return the starting // address of the first string. char *strcpy_ite(char *, const char *); // String pointr break Finds the first character in string str1 that matches // any character specified in str2. Iterative version size_t strspn_ite(const char *, const char *); // Substring matching. Finds the first occurence of the entire string str2 // which appears in the string str1. char *strstr_ite(const char *, const char *);
C
#include "shell.h" /** * call_env - Built in function for env * * @env: Double char pointer * * Return: Integer */ int call_env(char **env) { int i = 0; int len = 0; char *copy = malloc(8192); while (env[i] != NULL) { len = _strlen(env[i]); copy = _strdup(env[i]); write(STDOUT_FILENO, copy, len + 1); write(1, "\n", 1); free(copy); i++; } return (1); }
C
#include<stdio.h> int main(){ int b, p,i; int r=1; printf("Digite o valor da base:"); scanf("%d",&b); getchar(); printf("Digite o valor da potencia:"); scanf("%d",&p); getchar(); for(i=0;i<p;i++){ r= r*b; } printf("O resultado e :%d",r); return 0; }
C
#include "minishell.h" void reset_input_mode (void) { tcsetattr (STDIN_FILENO, TCSANOW, &g_saved_attributes); } /* Make sure stdin is a terminal. */ /* Save the terminal attributes so we can restore them later. */ /* Set the funny terminal modes. */ /* Clear ICANON and ECHO. */ static void set_input_mode (t_term *t) { t->slot = ttyslot(); if (!isatty (t->slot)) { write (STDERR_FILENO, "Not a terminal.\n", \ ft_strlen("Not a terminal.\n")); exit (EXIT_FAILURE); } tcgetattr (STDIN_FILENO, &g_saved_attributes); atexit (reset_input_mode); tcgetattr (STDIN_FILENO, &t->tattr); t->tattr.c_lflag &= ~(ICANON | ECHO); t->tattr.c_cc[VMIN] = 1; t->tattr.c_cc[VTIME] = 0; tcsetattr (STDIN_FILENO, TCSAFLUSH, &t->tattr); } void init_termcap_msh(t_term *t) { set_input_mode(t); t->name = ttyname(t->slot); t->term_type = getenv("TERM"); if (t->term_type == NULL) { write(STDERR_FILENO, "TERM must be set (see 'env').\n", \ ft_strlen("TERM must be set (see 'env').\n")); exit(-1); } t->ret = tgetent(NULL, t->term_type); if (t->ret == -1) { write(STDERR_FILENO, "Could not access to the termcap database..\n", \ ft_strlen("Could not access to the termcap database..\n")); exit(-1); } else if (t->ret == 0) { write(STDERR_FILENO, "Terminal type ", ft_strlen("Terminal type ")); write(STDERR_FILENO, t->term_type, ft_strlen(t->term_type)); write(STDERR_FILENO, " is not defined in termcap database (or have too few \ informations).\n", ft_strlen(" is not defined in termcap database (or have too \ few informations).\n")); exit(-1); } }
C
#include <stdio.h> extern int getPrecision(); extern void setPrecision(int); int main(void){ int choice, precision; do{ printf("1. Check precision\n2. Set precision\n0. Exit\n>"); scanf("%d", &choice); if (choice == 1){ precision = getPrecision(); switch (precision){ case 0: printf("Current precision: single\n"); break; case 2: printf("Current precision: double\n"); break; case 3: printf("Current precision: extended double\n"); break; default: break; } } else if (choice == 2){ printf("Choose precision:\n 0. Single\n 2. Double\n 3. Extended double\n>"); scanf("%d", &precision); if (precision > 3 || precision == 1){ printf("Wrong argument!\n"); continue; } setPrecision(precision); } } while(choice != 0); }
C
#include "raylib.h" int main(void) { // Initialization //-------------------------------------------------------------------------------------- const int screenWidth = 800; const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [core] example - mouse input"); Vector2 ballPosition = {-100.0f, -100.0f}; Color ballColor = DARKBLUE; SetTargetFPS(60); // Set our game to run at 60 frames-per-second //--------------------------------------------------------------------------------------- // Main game loop while (!WindowShouldClose()) // Detect window close button or ESC key { // Update //---------------------------------------------------------------------------------- ballPosition = GetMousePosition(); if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) ballColor = MAROON; else if (IsMouseButtonPressed(MOUSE_MIDDLE_BUTTON)) ballColor = LIME; else if (IsMouseButtonPressed(MOUSE_RIGHT_BUTTON)) ballColor = DARKBLUE; //---------------------------------------------------------------------------------- // Draw //---------------------------------------------------------------------------------- BeginDrawing(); ClearBackground(RAYWHITE); DrawCircleV(ballPosition, 40, ballColor); DrawText("move ball with mouse and click mouse button to change color", 10, 10, 20, DARKGRAY); EndDrawing(); //---------------------------------------------------------------------------------- } // De-Initialization //-------------------------------------------------------------------------------------- CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- return 0; }
C
#include <stdio.h> #include <string.h> #include <stdbool.h> #define LET 26 #define MAX 1000010 #define clr(ar) memset(ar, 0, sizeof(ar)) #define read() freopen("lol.txt", "r", stdin) int r, idx, counter[MAX], trie[MAX][LET]; void initialize(){ int i; r = 0, idx = 1, counter[r] = 0; for (i = 0; i < LET; i++) trie[r][i] = 0; } void insert(int x){ /// Set r = 0 before inserting first character int i, j; if (!trie[r][x]){ trie[r][x] = idx; r = idx++; for (i = 0, counter[r] = 1; i < LET; i++) trie[r][i] = 0; } else r = trie[r][x], counter[r]++; } int main(){ int i, j, x; initialize(); char str[1010]; while (scanf("%s", str) != EOF){ r = 0; /// r = root = 0 for (j = 0; str[j] != 0; j++){ x = str[j] - 'a'; insert(x); } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> void doRead(const int fd) { do { char buffer[100]; bzero(buffer,sizeof(buffer)); if(read(fd,buffer,sizeof(buffer)) < 0) { perror("read error"); break; } printf("read message:%s",buffer); }while(0); } int main(int argc,char *argv[]) { int flag = 0; do { if(argc < 3) { perror("client error"); break; } char *ip = argv[1]; int port = atol(argv[2]); int fd = socket(AF_INET,SOCK_STREAM,0); if(fd < 0) { perror("socket error"); break; } struct sockaddr_in addr; bzero(&addr,sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = ntohs(port); addr.sin_addr.s_addr = inet_addr(ip); //inet_pton(fd,ip,addr.sin_addr.s_addr,sizeof(addr.sin_addr.s_addr)); if(connect(fd,(struct sockaddr*)&addr,sizeof(addr)) < 0) { perror("connect error"); break; } doRead(fd); close(fd); flag = 1; }while(0); return flag; }
C
#include <stdio.h> #include "square.h" int main() { struct square s = newSquare(); printf("perimeter: %d\n", squarePerimeter(s)); printf("area: %d\n", squareArea(s)); return 0; }
C
// WAP to display following pattern: #include <stdio.h> int main() { for (int i = 1; i <= 4; i++) { for (int j = 1; j <= i; j++) { printf("%d", j); } printf("\n"); } printf("\n"); for (int i = 5; i >= 2; i--) { for (int j = 5; j >= i; j--) { printf("%d", j); } printf("\n"); } int k = 1; for (int i = 1; i <= 5; i++) { for (int j = 1; j < i; j++) { printf("%d", k); k++; } printf("\n"); } printf("\n"); for (int i = 1; i <= 4; i++) { for (int j = 1; j <= i; j++) { printf("%c", (j + 96)); } printf("\n"); } printf("\n"); return 0; }
C
#include <stdio.h> int main(){ double k; int n=1; scanf("%lf",&k); double sum=0; while(sum<=k){ sum=sum+1.0/n; n++; } printf("%d",n-1); return 0; }
C
#include <sys/stat.h> #include "memo_int.h" typedef struct _MemoPublisher { int connection; char* hostname; char* port; } MemoPublisher; static int mk_msg(int len, char* msg, char* topic, char** buf) { uint32_t slen; int topic_len = strlen(topic); slen = htonl(len + topic_len + 1); *buf = (char*)malloc(HEADER_LEN + topic_len + 1 + len); memcpy(*buf, &slen, HEADER_LEN); memcpy(*buf + HEADER_LEN, topic, topic_len); memcpy(*buf + HEADER_LEN + topic_len, ":", 1); memcpy(*buf + HEADER_LEN + topic_len + 1, msg, len); return HEADER_LEN + topic_len + 1 + len; } // Waits for an acknowledgement response from the server to indicate // that the message was received by the server. static int await_ack(MemoPublisher* publisher) { int rcvd; char ack_buf[16]; switch (rcvd = recv(publisher->connection, ack_buf, 16, 0)) { case 0: fprintf(stderr, "Connection closed\n"); break; case -1: perror("Error: receiving P_ACK"); break; default: ack_buf[rcvd] = 0; if (strcmp(ack_buf, "P_ACK")) { fprintf(stderr, "Error: bad message published: %s\n", ack_buf); return 0; } printf("Acknowledgement received\n"); break; } return (rcvd > 0) ? rcvd : 0; } void memo_free_publisher(MemoPublisher* pubs) { close(pubs->connection); free(pubs->hostname); free(pubs->port); free(pubs); } // Establishes a new publisher connection to a Memo server listening on the given host / port. void* memo_connect_publisher(char* host, char* port) { int sockfd; if ((sockfd = connect_client(host, port, 0)) == -1) return 0; MemoPublisher* pubs = (MemoPublisher*)malloc(sizeof(MemoPublisher)); pubs->connection = sockfd; pubs->hostname = strdup(host); pubs->port = strdup(port); return pubs; } // Publishes a message on the given topic to the connected Memo server. int memo_publish(MemoPublisher* publisher, char* topic, char* msg, int len) { int sent = 0; int rv = 0; char* msg_buf; int tot_len = mk_msg(len, msg, topic, &msg_buf); printf("Sending %d bytes\n", tot_len); do { rv = send(publisher->connection, msg_buf + sent, tot_len - sent, 0); printf("Sent\n"); if (rv == -1) { perror("Error: sending"); return 0; } sent += rv; } while (sent < tot_len); return (await_ack(publisher)) ? sent : 0; }
C
#include <stdio.h> int cal(int *a, int num){ int max, sum = 0; for(int i = 0; i < num; i += 2){ if(a[i] > a[i + 1]){ max = a[i]; } else{ max = a[i + 1]; } sum += max; } return sum; } int main(){ int a[10]; for (int i = 0; i < 10; i++){ scanf("%d", &a[i]); } printf("%d", cal(a, 10)); return 0; }
C
#include<stdio.h> #include<stdlib.h> typedef struct node { int info; struct node *next; }node; node* insert(node*,int); node* delNode(node*); void display(node*); void main() { node *head; head=NULL; int ch,op,num; do { printf("Menu\n1 INSERT\n2 DELETE nth NODE\n3 DISPLAY\n4 EXIT\nEnter your choice: "); scanf("%d",&ch); switch(ch) { case 1: printf("Enter the number to be inserted: "); scanf("%d",&num); head=insert(head,num); break; case 2: head=delNode(head); break; case 3: display(head); break; case 4: exit(1); break; default: printf("Wrong choice"); } printf("\nPress 0 to continue: "); scanf("%d",&op); } while(op==0); } node* insert(node *head, int num) { node *p,*temp; p=(node*)malloc(sizeof(node)); p->info=num; p->next=NULL; if(head==NULL) head=p; else { temp=head; while(temp->next!=NULL) { temp=temp->next; } temp->next=p; } return(head); } node* delNode(node* head) { int n,i; node *temp,*p; temp=head; printf("Enter the position of the node to be deleted: "); scanf("%d",&n); if(n!=1) { for(i=1;i<n-1;i++) { temp=temp->next; if(temp->next==NULL) { printf("Not enough nodes inserted."); return(head); } } p=temp->next; if(p->next==NULL) { temp->next=NULL; } else { temp->next=p->next; } free(p); } else if(n==1) { head=head->next; free(temp); } return(head); } void display(node* head) { while(head!=NULL) { printf("%2d",head->info); head=head->next; } }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> struct node { int data; struct node* xnp; }; struct node* head = NULL; struct node* XOR(struct node *a, struct node *b) { return (struct node*) ((long long int) (a) ^ (long long int) (b)); } void insert(int pos, int data) { struct node* newptr = (struct node*)malloc(sizeof(struct node)); newptr->data = data; newptr->xnp = XOR(head, NULL); if(head == NULL){ head = newptr; return; } if(pos == 1){ struct node* next = XOR(head->xnp, NULL); head->xnp = XOR(next, newptr); head = newptr; } else { int count = 1; struct node *cur = head, *prev = NULL, *next=XOR(cur->xnp, prev); while(count < pos - 1) { prev = cur; cur = next; count++; next = XOR(cur->xnp, prev); } newptr->xnp = XOR(cur, next); cur->xnp = XOR(newptr, prev); if(next)// if next is not null, ie, insertion is not taking place at end next->xnp = XOR(newptr, XOR(cur, next->xnp)); } } void traverse() { struct node *cur = head, *prev = NULL, *next; while(cur != NULL){ printf("%d-->", cur->data); next = XOR(cur->xnp, prev); prev = cur; cur = next; } printf("NULL"); } void delete(int pos){ if(head == NULL) return; if(pos == 1){ struct node* throw = head; struct node* next = XOR(head->xnp, NULL); head = next; if(head) head->xnp = XOR(head->xnp, throw); free(throw); } else { int count = 1; struct node *cur = head, *prev = NULL, *next = XOR(cur->xnp, prev); while(count < pos - 1) { prev = cur; cur = next; next = XOR(cur->xnp, prev); count++; } struct node *throw = next, *thrownext = XOR(throw->xnp, cur); cur->xnp = XOR(thrownext, prev); if(thrownext) thrownext->xnp = XOR(XOR(thrownext->xnp, next), cur); free(throw); } } void main() { int element; int ch, pos, data; char c; do{ printf( "\n1.Insert 2.Delete 3.Traverse"); printf( "\nEnter choice : "); scanf("%d", &ch); if(ch == 1) { printf("\nEnter position and data : "); scanf("%d%d", &pos, &data ); insert(pos, data); traverse(); } else if(ch == 2) { printf("\nEnter position: "); scanf("%d", &pos); delete(pos); traverse(); } else if(ch == 3) traverse(); printf("\nContinue (y/n)"); getchar(); scanf("%c", &c); }while(c == 'y'); }
C
#include <stdio.h> #include <string.h> typedef struct student { int id; char name [21]; float percentage; } student_t; int main() { student_t record; record.id = 20; strncpy (record.name, "Arowoiya", 21); record.percentage = 97.5; printf("The identity of the student is : %d \n", record.id); printf("The name of the student is %s \n", record.name); printf("The student percentage is %lf \n", record.percentage ); return 0; }
C
#ifndef FUNCTION_C_INCLUDED #define FUNCTION_C_INCLUDED #include "function.h" void printStat(struct car car) { if (car.type != TESLA) { printf("Km: %.2f\nGas: %.2f\n", car.km, car.gas); } else { printf("Km: %.2f\n", car.km); } } #endif // FUNCTION_C_INCLUDED
C
#include <stdio.h> #include <time.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <dirent.h> int main(int argc, char const *argv[]) { int i = copy(argv[1]); printf("%d\n",i ); /* code */ return 0; } int copy(char *argv) { // i代表当前已经打印了的行数 int i = 1; char *target = argv; printf("target:%s\n",target); // 要查看的目标是个目录 DIR *dp = opendir(target); if(dp == NULL) { printf("targetAA:%s\n",target); perror("opendir() failed"); exit(0); } // 进入指定的目录 chdir(target); printf("target:%s\n",target); return i; }
C
#include <stdio.h> /* * The book says: * "environ points to a NULL-terminated list of pointers to null-terminated strings" * * let me see if we can work this out from the symbols: * * environ is a symbol that is a pointer to a pointer to a character variable * "pointer to a character variable" is the same as "pointer to an array of characters" * so environ is a symbol that is a pointer to an array of characters" * */ extern char** environ; int main(int argc, char *argv[]) { printf("hi\n"); return 0; }
C
/* A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc such that a + b + c = n. */
C
/* Fondamenti di Informatica T1 - modulo di laboratorio Anno accademico 2020-2021 Cognome nome: Carr Edoardo Numero matricola: 0000970140 numero esame: */ #include <stdio.h> #include <stdlib.h> #include "array.h" /*TODO * test * check input */ TYPE* subArray(TYPE* a, int dimA, TYPE first, TYPE last, int* dimS) { TYPE* p = a; int dim_volatile = 0; boolean finish = FALSE; for (int i = 0; i < dimA && !finish; i++) { if (isEqualArray(a[i], first)) { p += i; dim_volatile = i; } else if (isEqualArray(a[i], last)) { *dimS = i - dim_volatile + 1; finish = TRUE; } } return p; } TYPE* deleteDuplicates(TYPE a[], int dim, int* newDim) { int count = 1; TYPE* no_duplicate; for (int i = 0; i < dim - 1; i++) { if (!find(&a[i + 1], dim - i, a[i])) count++; } no_duplicate = (TYPE*)malloc(sizeof(TYPE) * count); if (no_duplicate == NULL) exit(BAD_MALLOC_C); *newDim = count; count = 0; for (int i = 0; i < dim - 1; i++) { if (!find(&a[i + 1], dim - i, a[i])) { no_duplicate[count] = a[i]; count++; } } no_duplicate[count] = a[dim - 1]; return no_duplicate; } void fill_random(int a[], int dim) { for (int i = 0; i < dim; i++) { a[i] = 1 + rand() % 100; } } boolean find(TYPE array[], int dim, TYPE el) { boolean found = FALSE; for (int i = 0; i < dim && !found; i++) { if (isEqualArray(array[i], el)) found = TRUE; } return found; } //manca find_position boolean find_position(TYPE array[], int dim, TYPE el, int* pos) { boolean found = FALSE; for (int i = 0; i < dim && !found; i++) { if (isEqualArray(array[i], el)) found = TRUE, * pos = i; } return found; } void printArray(TYPE a[], int dim) { for (int i = 0; i < dim; i++) print_elArray(a[i]), printf("\n"); }
C
#include "help_function.h" /** * @brief Vytvori packet pro dotaz * * @param dns_header Ukazatel na hlavicku protokolu * @param dns_question Ukazatel na dotaz * @return char* Vraci ukazatel na vytvoreny packet ktery se posle na server */ char *create_buffer(DNSHeader *dns_header, DNSQuestion *dns_question) { // Alokace pameti char *buffer; int length; buffer = malloc(512 * sizeof(char)); if (buffer == NULL) { fprintf(stderr, "Problem with allocating\n"); exit(1); } // Ulozeni hlavicky memset(buffer, '\0', 512 * sizeof(char)); memcpy(buffer, &(dns_header->id), sizeof(uint16_t)); memcpy(&(buffer[2]), &(dns_header->header_settings), sizeof(uint16_t)); memcpy(&(buffer[4]), &(dns_header->qdcount), sizeof(uint16_t)); memcpy(&(buffer[6]), &(dns_header->ancount), sizeof(uint16_t)); memcpy(&(buffer[8]), &(dns_header->nscount), sizeof(uint16_t)); memcpy(&(buffer[10]), &(dns_header->arcount), sizeof(uint16_t)); // Ulozeni domenoveho jmena dotazu if (dns_question->q_type == htons(QTypePTR)) { char *part = check_and_reverse_ip(dns_question->q_name); length = convert_domain_name(part, buffer, 12); } else { length = convert_domain_name(dns_question->q_name, buffer, 12); } // Ulozeni typu a tridy dotazu memcpy(&(buffer[13 + length]), &(dns_question->q_type), sizeof(uint16_t)); memcpy(&(buffer[13 + length + sizeof(uint16_t)]), &(dns_question->q_class), sizeof(uint16_t)); return buffer; } /** * @brief Zparsuje odpoved ze serveru do struktury DNSRespond * * @param respond Ukazatel na strukturu kde se ukladaji vysledne informace * @param type Pozadovany typ odpovedi * @param buffer Packet ktery obsahuje vsechny informace * @param address Pomocny buffer kam se zapisuje NS adresa pokud se k ni nenajde IP adresa, nebo IP adresa NS adresy * @param iterative Informace jestli se jedna o iterativni zpusob * @return ParseBufferStatus Navratova hodnota funkce (Nasla se odpoved, nasel se pouze NS server, nasla se IP NS serveru) */ ParseBufferStatus parse_buffer(DNSRespond *respond, QType type, char *buffer, char *address, bool iterative) { uint16_t helper = 0; memcpy(&helper, &(buffer[0]), sizeof(uint16_t)); respond->header->id = htons(helper); memcpy(&helper, &(buffer[2]), sizeof(uint16_t)); helper = htons(helper); respond->header->header_settings = helper; // Kontrola chyby helper = helper << 12; helper = helper >> 12; if (helper != 0) { return FormatError; } // Kontrola jestli nedoslo ke zkraceni zpravy helper = respond->header->header_settings; helper = helper >> 9; if (helper % 2 == 1) { fprintf(stderr, "Truncated message\n"); exit(1); } memcpy(&helper, &(buffer[4]), sizeof(uint16_t)); respond->header->qdcount = htons(helper); memcpy(&helper, &(buffer[6]), sizeof(uint16_t)); respond->header->ancount = htons(helper); memcpy(&helper, &(buffer[8]), sizeof(uint16_t)); respond->header->nscount = htons(helper); memcpy(&helper, &(buffer[10]), sizeof(uint16_t)); respond->header->arcount = htons(helper); int index = 12; // Preskoceni domenoveho jmena dotazu while (buffer[index] != '\0') { index++; } // Preskoceni typu a tridy dotazu index += 2 * sizeof(uint16_t) + 1; // Parsovani odpovedi if (respond->header->ancount != 0) { DNSAnswer answear; for (int i = 0; i < respond->header->ancount; i++) { index = parse_answer(buffer, index, &(answear)); print_answer(&answear); // Ulozeni vysledku pokud se jedna o iterativni zpusob if (answear.type == type && iterative) { memcpy(address, answear.address, strlen(answear.address) + 1); } if (answear.type == type) { return Found; } } } // Pokud se nejedna o iterativni dotazovani a nebyl nalezen spravny typ odpovedi tak se prochazeni ukonci if (iterative == false) { return NotFound; } char *helper_name; helper_name = malloc(255 * sizeof(char)); char *helper_address; helper_address = malloc(255 * sizeof(char)); // Parsovani autorativnich name serveru v pripade iterativniho dotazovani if (respond->header->nscount != 0) { DNSAnswer name_server; // Ulozeni prvniho nameserveru index = parse_answer(buffer, index, &(name_server)); strcpy(helper_name, name_server.name); remove_dots(helper_name, 0); strcpy(helper_address, name_server.address); memcpy(address, name_server.address, strlen(name_server.address) + 1); // Pruchod zbytkem name serveru for (int i = 1; i < respond->header->nscount; i++) { index = parse_answer(buffer, index, &(name_server)); } } // Parsovani doplnujicich informaci if (respond->header->arcount != 0) { DNSAnswer answear; for (int i = 0; i < respond->header->arcount; i++) { index = parse_answer(buffer, index, &(answear)); // Hledani IPv4 name serveru Adresy if (answear.type == htons(QTypeA)) { //Prevedeni domenove jmena na teckovou notaci remove_dots(answear.name, 0); printf("%s IN NS %s\n", helper_name, answear.name); print_answer_without_removing_dots(&(answear)); memcpy(address, answear.address, strlen(answear.address) + 1); return NotFound; } } } // Pokud se nasel Name server ale ne IP adresa serveru if (respond->header->nscount != 0) { printf("%s IN NS %s\n", helper_name, helper_address); return MissingIP; } return NotFound; } /** * @brief Funkce parsuje zaznamy v sekcich odpovedi, name servery, doplnujici informace * * @param buffer Pole ze ktereho se parsuji hodnoty * @param index Misto kde se zacina parsovat * @param answear Ukazatel na strukturu kam se ukladaji informace * @return int Index kde konci zaznam */ int parse_answer(char *buffer, int index, DNSAnswer *answear) { memset(answear, '\0', sizeof(answear)); answear->name = (char *)calloc(255, sizeof(char)); if (answear->name == NULL) { fprintf(stderr, "Problem with allocating\n"); exit(1); } answear->address = (char *)calloc(255, sizeof(char)); if (answear->address == NULL) { fprintf(stderr, "Problem with allocating\n"); exit(1); } // Parsovani domenoveho jmena index = parse_address_ptr(buffer, index, answear->name); memcpy(&(answear->type), &(buffer[index]), sizeof(uint16_t)); index += 2; memcpy(&(answear->an_class), &(buffer[index]), sizeof(uint16_t)); index += 2; memcpy(&(answear->time_to_live), &(buffer[index]), sizeof(int)); index += 4; memcpy(&(answear->data_length), &(buffer[index]), sizeof(uint16_t)); index += 2; // Parsovani datove casti podle typu zaznamu if (htons(answear->type) == QTypeA) { parse_address_a(&(buffer[index]), answear); index += 4; } else if (htons(answear->type) == QTypeAAAA) { parse_address_aaaa(buffer, index, htons(answear->data_length), answear); index += htons(answear->data_length); } else if (htons(answear->type) == QTypeCNAME) { index = parse_address_ptr(buffer, index, answear->address); remove_dots(answear->address, 0); } else if (htons(answear->type) == QTypePTR) { index = parse_address_ptr(buffer, index, answear->address); remove_dots(answear->address, 0); } else if (htons(answear->type) == QTypeNS) { index = parse_address_ptr(buffer, index, answear->address); remove_dots(answear->address, 0); } else { fprintf(stderr, "Not supported in answear\n"); exit(1); } return index; } /** * @brief Parsovani adresy typu AAAA (IPv6) * * @param buffer Buffer ze ktereho se adresa parsuje * @param index Zacatek odkud se parsuji data * @param data_length Delka dat * @param answear Ukazatel na strukturu zaznamu kam se zapisuje adresa */ void parse_address_aaaa(char *buffer, int index, int data_length, DNSAnswer *answear) { uint16_t i = 0; int string_index = 0; memcpy(&i, &(buffer[index]), sizeof(uint16_t)); i = htons(i); index += 2; int zeroes = 0; if (i != 0) { string_index += sprintf(&(answear->address[string_index]), "%x", i); } for (int j = 1; j < data_length / 2; j++) { // Kontrola aby se nevytiskli zasebou 3 : if (zeroes != 2) { string_index += sprintf(&(answear->address[string_index]), ":"); } else { zeroes = 0; } i = 0; memcpy(&i, &(buffer[index]), sizeof(uint16_t)); i = htons(i); index += 2; if (i != 0) { string_index += sprintf(&(answear->address[string_index]), "%x", i); } else { zeroes++; } } } /** * @brief Parsovani domenoveho jmena * * @param buffer Buffer odkud se bude parsovat * @param index Zacatek odkud se parsuji data * @param output Ukazatel na misto kam se zapisuje domenove jmeno * @return int Index kde konci domenove jmeno */ int parse_address_ptr(char *buffer, int index, char *output) { bool routed = false; int helper_index = index; int string_index = 0; unsigned char c; // Situace kdy by se jednalo o . if (buffer[index] == '\0') { return index + 1; } while ((c = buffer[index]) != '\0') { // Odchyceni ukazatele if (c >= 192) { // Kontrola jestli uz nebyl pouzit ukazatel if (routed == false) { helper_index = index + 2; routed = true; } // Vypocet noveho indexu unsigned int nextIndex = c - 192; nextIndex = nextIndex << 8; nextIndex += buffer[index + 1]; index = nextIndex; continue; } output[string_index] = c; string_index++; index++; } if (routed == true) { return helper_index; } else { return index + 1; } } /** * @brief Parsovani Ipv4 adresy * * @param buffer Buffer odkud se bude parsovat adresa * @param answear Ukazatal na strukturu kde se bude ukladat adresa */ void parse_address_a(char *buffer, DNSAnswer *answear) { int index = 0; int string_index = 0; unsigned char c; for (int i = 0, length = htons(answear->data_length) - 1; i < length; i++) { c = buffer[index]; string_index += sprintf(&(answear->address[string_index]), "%d.", c); index++; } c = buffer[index]; string_index += sprintf(&(answear->address[string_index]), "%d", c); } /** * @brief Prevod domenoveho jmena z teckove notace do bufferu * * @param domain_name Domenove jmeno * @param buffer Buffer do ktereho se jmeno zapisuje * @param start Odkud se zacina v bufferu * @return int Vraci delku zapsanych dat */ int convert_domain_name(char *domain_name, char *buffer, int start) { int length_index = start; char length = 0; int index = 0; int c; bool root = true; while ((c = domain_name[index]) != '\0') { if (c == '.') { // Delka subdomeny nesmi byt 64 a vice if (length > 63) { fprintf(stderr, "Maximal length of subdomen is 63 chars\n"); exit(2); } buffer[length_index] = (char)length; length_index = start + index + 1; length = 0; } else { buffer[start + index + 1] = domain_name[index]; root = false; length++; } index++; } // Delka subdomeny nesmi byt 64 a vice if (length > 63) { fprintf(stderr, "Maximal length of subdomen is 63 chars\n"); exit(2); } buffer[length_index] = length; if (length) { return index + 1; } else if (root == false) { return index; } else { return index - 1; } } /** * @brief Ziskani typu z retezce * * @param optarg retezec obsahujici typ * @return QType Vysledny typ */ QType get_qtype(char *optarg) { if (strcmp(optarg, "A") == 0) { return QTypeA; } else if (strcmp(optarg, "AAAA") == 0) { return QTypeAAAA; } else if (strcmp(optarg, "CNAME") == 0) { return QTypeCNAME; } else if (strcmp(optarg, "NS") == 0) { return QTypeNS; } else if (strcmp(optarg, "PTR") == 0) { return QTypePTR; } else { return 0; } } /** * @brief Zkontroluje jestli se jedna o IPv4 nebo IPv6 adresu a podle toho nasledne adrese prevede do bufferu * * @param ip Vstupni retezec ktery by mel obsahovat IP adresu * @return char* Prevedena adresa */ char *check_and_reverse_ip(char *ip) { bool is_ipv4 = true; bool is_ipv6 = true; char buffer[16]; if (inet_pton(AF_INET, ip, buffer)) { return reverse_ipv4(ip); } else if (inet_pton(AF_INET6, ip, buffer)) { return reverse_ipv6(ip); } else { fprintf(stderr, "Wrong address %s\n", ip); exit(2); } } /** * @brief Prevede IPv4 adresu do bufferu * * @param ipv4 Vstupni adresa, predpoklada se prosla kontrolou pomoci funkce check_and_reverse_ip * @return char* Prevedena adresa */ char *reverse_ipv4(char *ipv4) { char *buffer; int adress[4]; buffer = (char *)malloc(29 * sizeof(char)); if (buffer == NULL) { fprintf(stderr, "Problem with allocating\n"); exit(1); } sscanf(ipv4, "%d.%d.%d.%d", &(adress[0]), &(adress[1]), &(adress[2]), &(adress[3])); sprintf(buffer, "%d.%d.%d.%d.in-addr.arpa", adress[3], adress[2], adress[1], adress[0]); return buffer; } /** * @brief Prevede IPv6 adresu do bufferu * * @param ipv6 Vstupni adresa, predpoklada se prosla kontrolou pomoci funkce check_and_reverse_ip * @return char* Prevedena adresa */ char *reverse_ipv6(char *ipv6) { char *buffer; buffer = (char *)malloc(72 * sizeof(char)); if (buffer == NULL) { fprintf(stderr, "Problem with allocating\n"); exit(1); } int length = strlen(ipv6); int part_length = 0; int part_count = 0; int index = 0; for (int i = length - 1; i >= 0; i--) { if (ipv6[i] != ':') { part_length++; buffer[index] = ipv6[i]; buffer[index + 1] = '.'; index += 2; } else { if (part_length == 0) { for (int j = 0; j < i; j++) { if (ipv6[j] == ':') { part_count++; } } for (int k = 0; k < 7 - part_count; k++) { for (int l = 0; l < 4; l++, index += 2) { buffer[index] = '0'; buffer[index + 1] = '.'; } } } else { for (part_length; part_length < 4; part_length++) { buffer[index] = '0'; buffer[index + 1] = '.'; index += 2; } part_length = 0; part_count++; } } } sprintf(&(buffer[index]), "ip6.arpa"); return buffer; } /** * @brief Vypise tridu na vystup * * @param an_class Trida ktera se ma vypsat vystup */ void print_class(uint16_t an_class) { if (an_class == ClassIN) { printf("IN"); } else if (an_class == ClassCH) { printf("CH"); } else if (an_class == ClassHS) { printf("HS"); } else if (an_class == ClassALL) { printf("ALL"); } } /** * @brief Vypise typ na vystup * * @param an_class Typ ktera se ma vypsat vystup */ void print_type(uint16_t type) { if (type == QTypeA) { printf("A"); } else if (type == QTypeAAAA) { printf("AAAA"); } else if (type == QTypeCNAME) { printf("CNAME"); } else if (type == QTypeNS) { printf("NS"); } else if (type == QTypePTR) { printf("PTR"); } else if (type == QTypeSOA) { printf("SOA"); } } /** * @brief Prevede domenove jmeno do teckove notace * * @param buffer Buffer ve kterem se ma prevest domenove jmeno * @param index Index odkud se ma v bufferu zacit */ void remove_dots(char *buffer, int index) { int length = buffer[index]; // Pripad rootu if (length == 0) { buffer[index] = '.'; } index++; while (length != 0) { for (int i = length; i > 0; i--) { buffer[index - 1] = buffer[index]; index++; } length = buffer[index]; if (length != 0) { buffer[index - 1] = '.'; } else { buffer[index - 1] = '\0'; } index++; } } /** * @brief Funkce vypise zaznam na terminal, provadi predtim jeste funkci ktera prevadi domenove jmeno na teckovou notaci * * @param answear Zaznam ktery se ma vypsat */ void print_answer(DNSAnswer *answear) { remove_dots(answear->name, 0); printf("%s ", answear->name); print_class(htons(answear->an_class)); putchar(' '); print_type(htons(answear->type)); printf(" %s\n", answear->address); } /** * @brief Funkce vypise zaznam na terminal * * @param answear Zaznam ktery se ma vypsat */ void print_answer_without_removing_dots(DNSAnswer *answear) { printf("%s ", answear->name); print_class(htons(answear->an_class)); putchar(' '); print_type(htons(answear->type)); printf(" %s\n", answear->address); } /** * @brief Funkce vraci adresu z vrcholu zasobniku * * @param stack Zasobnik * @return char* Adresa ulozena v polozce na vrcholu zasobniku */ char *stack_top(Stack *stack) { if (stack != NULL) { if (stack->Top != NULL) { return stack->Top->address; } else { return NULL; } } } /** * @brief Funkce prida na vrchol zasobniku adresu * * @param address Adresa ktera se prida na vrchol zasobniku * @param stack Zasobnik */ void stack_push(char *address, Stack *stack) { if (address != NULL && stack != NULL) { struct StackItem *item; item = malloc(sizeof(struct StackItem)); if (item == NULL) { fprintf(stderr, "Problem with allocating\n"); exit(1); } item->address = malloc(256 * sizeof(char)); if (item->address == NULL) { fprintf(stderr, "Problem with allocating\n"); exit(1); } strcpy(item->address, address); if (stack->Top == NULL) { stack->Top = item; } else { item->next = stack->Top; stack->Top = item; } } } /** * @brief Funkce zrusi polozku na vrcholu zasobniku * * @param stack Zasobnik */ void stack_pop(Stack *stack) { if (stack != NULL) { if (stack->Top != NULL) { struct StackItem *item; item = stack->Top; stack->Top = item->next; free(item->address); free(item); } } }
C
#include "../include/kernel.h" #include "../include/string.h" #include "../include/io.h" #include "../include/i386/gdt.h" static unsigned char bufkbd[1024] = {0,}; static inline int syscall(int a, int b, int c, int d){ int _a; asm volatile("movl %1, %%eax; movl %2, %%ebx; movl %3, %%ecx; movl %%edx, %4;int $0x60;movl %%eax, %0":"=r"(_a):"r"(a), "r"(b),"r"(c), "r"(d)); return _a; } void dotswitch(){ syscall(1,0,0,0); } void kfork(){ syscall(2,0,0,0); } char getc(void){ return (char) syscall(2,0,0,0); } process *getcurrentproc(){ return running; } /** * * return the free element from list */ process* get_proc(process**list){ process *head = *list, *p, * tmp; if(!head) return 0; for(process* i = head;i;i=i->next){ if(i->status == FREE){ p = i; if(i != head) tmp->next = i->next; else *list = i->next; return p; } tmp = i; } return 0; } /** * * return the first element removed from queue */ process* dequeue(process**list){ process* head = *list,*p; if (!head) return 0; p = head; *list = head->next; return p; } /** * * put a process into the list */ int put_proc(process**list, process*p){ process* head = *list; *list=p; p->next = head; return p->pid; } /** * * put a element by priority into the list */ int enqueue(process**list, process*p){ process *head = *list, *tmp; if(!head){ *list = p; p->next = 0; } else{ for(process* i=head; i; i=i->next) { if(p->priority >= i->priority){ p->next = i; if(i != head) tmp->next = p; else *list = p; return p->pid; } tmp = i; } } tmp->next = p; p->next = 0; return p->pid; }
C
#include<stdio.h> #include<unistd.h> #include<stdlib.h> #include<sys/types.h> #include<sys/wait.h> int findTempSum(int start, int end, const int arry[]) { int ts = 0; for (int j = start; j < end; j++) { ts = ts + arry[j]; } return ts; } int main(){ int arry[1000]; int s1[2],s2[2],s3[2],s4[2],s5[2],s6[2],s7[2],s8[2],s9[2],s10[2]; pipe(s1),pipe(s2),pipe(s3),pipe(s4),pipe(s5),pipe(s6),pipe(s7),pipe(s8),pipe(s9),pipe(s10); int a1=0,a2=0,a3=0,a4=0,a5=0,a6=0,a7=0,a8=0,a9=0,a10=0; int sum=0; int tempSum=0; for(int i=0;i<1000;i++){ arry[i]=i+1; } int cpid1=fork(); if(cpid1==0){ tempSum=findTempSum(0,100,arry); write(s1[1],&tempSum,sizeof(int)); close(s1[1]); exit(0); } else{ wait(NULL); int cpid2=fork(); if(cpid2==0){ tempSum=findTempSum(100,200,arry); write(s2[1],&tempSum,sizeof(int)); close(s2[1]); exit(0); } else{ wait(NULL); int cpid3=fork(); if(cpid3==0){ tempSum=findTempSum(200,300,arry); write(s3[1],&tempSum,sizeof(int)); close(s3[1]); exit(0); } else{ wait(NULL); int cpid4=fork(); if(cpid4==0){ tempSum=findTempSum(300,400,arry); write(s4[1],&tempSum,sizeof(int)); close(s4[1]); exit(0); } else{ wait(NULL); int cpid5=fork(); if(cpid5==0){ tempSum=findTempSum(400,500,arry); write(s5[1],&tempSum,sizeof(int)); close(s5[1]); exit(0); } else{ wait(NULL); int cpid6=fork(); if(cpid6==0){ tempSum=findTempSum(500,600,arry); write(s6[1],&tempSum,sizeof(int)); close(s6[1]); exit(0); } else{ wait(NULL); int cpid7=fork(); if(cpid7==0){ tempSum=findTempSum(600,700,arry); write(s7[1],&tempSum,sizeof(int)); close(s7[1]); exit(0); } else{ wait(NULL); int cpid8=fork(); if(cpid8==0){ tempSum=findTempSum(700,800,arry); write(s8[1],&tempSum,sizeof(int)); close(s8[1]); exit(0); } else{ wait(NULL); int cpid9=fork(); if(cpid9==0){ tempSum=findTempSum(800,900,arry); write(s9[1],&tempSum,sizeof(int)); close(s9[1]); exit(0); } else{ wait(NULL); tempSum=findTempSum(900,1000,arry); write(s10[1],&tempSum,sizeof(int)); close(s10[1]); } } } } } } } } } read(s1[0],&a1,sizeof(int)); read(s2[0],&a2,sizeof(int)); read(s3[0],&a3,sizeof(int)); read(s4[0],&a4,sizeof(int)); read(s5[0],&a5,sizeof(int)); read(s6[0],&a6,sizeof(int)); read(s7[0],&a7,sizeof(int)); read(s8[0],&a8,sizeof(int)); read(s9[0],&a9,sizeof(int)); read(s10[0],&a10,sizeof(int)); sum=sum+a1; sum=sum+a2; sum=sum+a3; sum=sum+a4; sum=sum+a5; sum=sum+a6; sum=sum+a7; sum=sum+a8; sum=sum+a9; sum=sum+a10; printf("Sum of first 1000 numbers is = %d\n\n",sum); close(s1[0]); close(s2[0]); close(s3[0]); close(s4[0]); close(s5[0]); close(s6[0]); close(s7[0]); close(s8[0]); close(s9[0]); close(s10[0]); return 0; }
C
/* ** my_select.c for my_select in /home/menich_a/rendu/PSU_2013_my_select ** ** Made by menich_a ** Login <[email protected]> ** ** Started on Fri Jan 10 12:58:18 2014 menich_a ** Last update Sun Jan 19 20:13:51 2014 menich_a */ #include <sys/ioctl.h> #include <signal.h> #include <ncurses/curses.h> #include <term.h> #include <stdlib.h> #include <unistd.h> #include <termcap.h> #include <termios.h> #include "my_select.h" #include "my.h" t_size g_window; /* ** If a signal SIGWINCH (resizing terminal) is recepted: ** => adapt the global size to display a list with good dimensions. */ void my_resizing(int signal) { t_winsize window_size; t_termios t; if (signal == SIGWINCH) { if (ioctl(g_fd, TIOCGWINSZ, &window_size) != -1) { g_window.height = window_size.ws_row; g_window.width = window_size.ws_col; display_list(g_window.list, g_window.pos, &g_window); } else reinit_then_exit(t, "ioctl error: cannot find window size", -1); } } void my_signal(void) { signal(SIGTERM, &my_kill); signal(SIGKILL, &my_kill); signal(SIGINT, &my_kill); signal(SIGWINCH, &my_resizing); signal(SIGTSTP, &my_ignore_signal); } /* ** Check if user taped on an arrow key then adapt position (i) \ ** and display list with a new position for cursor. */ int check_arrows(char *buff, t_list *list, int pos, int posmax) { if (buff[0] == ESC && buff[1] == 91 && buff[2] == 65) { if (--pos < 0) pos = posmax; } else if (buff[0] == ESC && buff[1] == 91 && buff[2] == 66) { if (++pos > posmax) pos = 0; } else if (buff[0] == ESC && buff[1] == 91 && buff[2] == 67) { if ((pos = pos + (g_window.height - 1)) > posmax) while (list->pos-- > 0) pos = pos - (g_window.height - 1); } else if (buff[0] == ESC && buff[1] == 91 && buff[2] == 68) { if ((pos = pos - (g_window.height - 1)) < 0) while (list->pos-- > 0) pos = pos + (g_window.height - 1); } return (pos); } /* ** Change pos value according on key pressed. ** Adapt global window informations for each key pressed. */ int keypressed(t_termios t, t_list *list, char *buff, int posmax) { static int pos; if (buff[0] == ESC && buff[1] == 91) pos = check_arrows(buff, list, pos, posmax); else if (buff[0] == SPACE) { if (select_elem(list, pos) == 0) if (++pos > posmax) pos = 0; display_list(list, pos, &g_window); } else if (buff[0] == DELETE || buff[0] == BACKSPACE) { if ((pos = delete_elem(t, list, pos, posmax)) == -1) return (1); display_list(list, pos, &g_window); posmax = posmax - 1; } else if (buff[0] == ESC && buff[1] != 91) reinit_then_exit(t, NULL, 0); else pos = dynamic_research_mode(list, buff, pos); g_window.pos = pos; display_list(list, pos, &g_window); return (posmax); } /* ** Initiate the global var used to display the list. ** (pos = 0 => first elem is selectionned). ** my_resizing => display the list with appropriate dimensions. ** my_signal catch signals send by user. ** launch the reading loop used for my_select. */ int my_select(t_termios t, t_list *list, int posmax) { char buff[BUFF_SIZE + 1]; int ret; g_window.list = list; g_window.pos = 0; my_resizing(SIGWINCH); my_signal(); ret = read(0, buff, BUFF_SIZE); if (ret == -1) return (msg_error("read error\n", 1)); buff[ret] = '\0'; while (buff[0] != '\n' && buff[0] != '\r') { posmax = keypressed(t, list, buff, posmax); if (posmax == -1) return (1); g_window.list = list; ret = read(0, buff, BUFF_SIZE); if (ret == -1) return (msg_error("read error\n", 1)); buff[ret] = '\0'; } return (0); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> // Used by qsort(). int cmpfunc (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } // Prints an array, assuming 0 termination void printArray (int *toPrint) { printf("\n[") ; for (int i = 0; toPrint[i] != 0; i++) { if (toPrint[i+1] == 0) { printf("%d]", toPrint[i]); } else { printf("%d, ", toPrint[i]); } } int prod = 1; for (int i = 0; toPrint[i] != 0; i++) { prod *= toPrint[i]; } printf(" = %d", prod); } // Prints a 2D array, assuming zero termination void printArray2D (int toPrint[100][50]) { if (toPrint[0][0] == 0) { printf("\n[]"); } else { printf("\n[ ") ; } for (int i = 0; toPrint[i][0] != 0; i++) { printf("[") ; for (int j = 0; toPrint[i][j] != 0; j++) { if (toPrint[i][j+1] == 0) { printf("%d]", toPrint[i][j]); } else { printf("%d, ", toPrint[i][j]); } } int prod = 1; for (int j = 0; toPrint[i][j] != 0; j++) { prod *= toPrint[i][j]; } printf(" = %d", prod); if (toPrint[i+1][0] == 0) { printf("\n]"); } else { printf("\n, "); } } } // Computes the prime factors of N using a recursion. // Stores factors in "factors" array. void primeFactors_rec (int N, int* factors, int size) { int i = 2; while (N % i != 0) { i += 1; } factors[size] = i; factors[size+1] = 0; if (N != i) { primeFactors_rec( (N / i), factors, size + 1); } } // end of primeFactors // Computes all factor groups for the prime factors given. // Stores factor groups in "all" void allFactors_rec (int primes[50], int all[100][50]) { int temp[50]; // For each pair of factors in primes for (int i = 0; primes[i] != 0; i++) { for (int j = i + 1; primes[j] != 0; j++ ) { // populate temp with the original factors memcpy(temp, primes, 50*sizeof(int)); // delete the element at j for (int k = j; primes[k] != 0; k ++) { temp[k] = temp[k+1]; } // delete the element at i, leaving space to overwrite if (i != 0) { for (int k = i; k > 0; k --) { temp[k] = temp[k-1]; } } // overwrite index 0 with the product of the factor pair temp[0] = primes[i] * primes[j]; int items = 0; // count the number of remaing factors while (temp[items] != 0) { items ++; } // sort the factors qsort(temp, items, sizeof(int), cmpfunc); // Check whether the new set of factors is already in all. bool check1 = false; for (int a = 0; all[a][0] != 0 ; a ++ ) { bool check2 = true; for (int b = 0; temp[b] != 0; b ++ ) { check2 = check2 && (temp[b] == all[a][b]); } check1 = check1 || check2; } if (!check1) { // if not... int q = 0; while (all[q][0] != 0) { q ++; } // copy it in! memcpy(all[q], temp, 50*sizeof(int)); all[q+1][0] = 0; int z = 0; while (temp[z] != 0) { z ++; } // and recursively run again, with the new factor grouping as the starting point. if (z > 2) { allFactors_rec(temp, all); } } } } } // end of allFactors void factor_rec(int d) { int primefactors_rec[50]; primeFactors_rec(d, primefactors_rec, 0); int factors_rec[100][50]; for (int i = 0; i < 100; i++) { for (int j = 0; j < 50; j++) { factors_rec[i][j] = 0; } } memcpy(factors_rec[0], primefactors_rec, 10*sizeof(int)); allFactors_rec(primefactors_rec, factors_rec); printf("The prime factors of %d are ", d); for (int i = 0; primefactors_rec[i] != 0; i++) { printf("%d, ", primefactors_rec[i]); } printf("\n\nAll groups of factors are:"); printArray2D(factors_rec); printf("\n\n"); } void primeFactors_itr (int N, int* factors) { int pos = 0; while (N > 1) { int i = 2; while (N % i != 0) { i += 1; } factors[pos] = i; factors[pos + 1] = 0; pos += 1; N /= i; } } void allFactors_itr(int primes[50], int all[100][50]) { // loop over all elements in "all" (initially 1) // - all will grow dynamically as we add factor groups to it. for (int a = 0; all[a][0] != 0; a++) { // If the number of factors in this row is less than 2, skip it! int z_out; for (int z = 0; all[a][z] != 0; z++) { z_out = z; } if (z_out < 2) { continue; } // for every pair of elements in the current row... for (int i = 0; all[a][i] != 0; i ++) { for (int j = i+1; all[a][j] != 0; j ++) { // set up a temporary buffer to hold our new array of factors. int remainingList[50]; remainingList[0] = 0; int end = 0; // loop through the current row and append everything that isn't at index i or j for (int k = 0; all[a][k] != 0; k++) { if ((k != i) && (k != j)) { remainingList[end] = all[a][k]; remainingList[end+1] = 0; end ++; } } // append i * j remainingList[end] = all[a][i] * all[a][j]; remainingList[end+1] = 0; end ++; // Sort! That! Array! qsort(remainingList, end, sizeof(int), cmpfunc); // Check if the array is already in "all" bool check1 = false; for (int b = 0; all[b][0] != 0 ; b ++ ) { bool check2 = true; for (int c = 0; remainingList[c] != 0; c ++ ) { check2 = check2 && (remainingList[c] == all[b][c]); } check1 = check1 || check2; } if (!check1) { // if not... int q = 0; while (all[q][0] != 0) { q ++; } // copy it in! memcpy(all[q], remainingList, 50*sizeof(int)); all[q+1][0] = 0; } } } } } void factor_itr(int d) { int primefactors_itr[50]; primeFactors_itr(d, primefactors_itr); int allfactors_itr[100][50]; for (int i = 0; i < 100; i++) { for (int j = 0; j < 50; j++) { allfactors_itr[i][j] = 0; } } memcpy(allfactors_itr[0], primefactors_itr, 10*sizeof(int)); allfactors_itr[1][0] = 0; allFactors_itr(primefactors_itr, allfactors_itr); printf("The prime factors of %d are ", d); for (int i = 0; primefactors_itr[i] != 0; i++) { printf("%d, ", primefactors_itr[i]); } printf("\n\nAll groups of factors are:"); printArray2D(allfactors_itr); printf("\n\n"); } int main(int argc, char *argv[]){ if (argc < 3){ return 0; } int d = atoi(argv[2]); switch (atoi(argv[1])){ case 0: printf("Running Recursive Factors \n"); factor_rec(d); return (0); case 1: printf("Running Iterative Factors \n"); factor_itr(d); return (0); default: return (0); } }
C
/* Problem Statement - To accept two numbers from user and display its addition */ #include "Header.h" int main() { int iValue1 = 0; int iValue2 = 0; int iRet = 0; printf("Enter 1st number :\t"); scanf("%d",&iValue1); printf("Enter 2nd number :\t"); scanf("%d",&iValue2); iRet = Addition(iValue1,iValue2); printf("Addition of %d and %d is %d",iValue1,iValue2,iRet); return 0; }
C
/************************************************************************* > File Name: test1.c > Author: > Mail: > Created Time: Sat 14 Nov 2015 04:24:39 PM CST ************************************************************************/ #include<stdio.h> #include<stdlib.h> typedef struct node *ptr; typedef ptr bp; typedef ptr fp; typedef int elementtype; ptr findend(ptr head); void exchange(ptr fp,ptr bp); struct node{ elementtype ele; ptr prior; ptr next; } ptr findend(ptr head){ ptr tmp=head; while(tmp->next!=head){ tmp=tmp->next; } return tmp; } void exchange(ptr fp,ptr bp){ elementtype tmp = bp->ele; bp->ele=fp->ele; fp->ele=tmp; } void inverse(ptr fp,ptr bp){ while((fp->next!=bp)&&(fp->next!=bp->prior)){ exchange(fp,bp); fp=fp->next; bp=bp->next; } fp=fp->next; bp=bp->next; exchange(fp,bp); }
C
#include <stdio.h> void bfs(int); int a[20][20], q[20], visited[20], n, f=0, r=-1, i, j; int main(){ int v; printf("Graph Traversal Breadth First Search\n"); printf("\nEnter the number of vertices: "); scanf(" %d", &n); for(i=1; i<=n; i++){ q[i] = 0; visited[i] = 0; } printf("\nEnter the graph in matrix form:\n"); for(i=1; i<=n; i++){ for(j=1; j<=n; j++){ scanf(" %d", &a[i][j]); } } printf("\nEnter the starting vertex: "); scanf(" %d", &v); bfs(v); printf("\nThe nodes which are reachable are:\n\n"); for(i=1; i<=n; i++){ if(visited[i]){ printf(" %d\t", i); }else{ printf("\nBFS is not possible"); } } printf("\n"); return 0; } void bfs(int v){ int i; for(i=1; i<=n; i++){ if(a[v][i] && !visited[i]){ q[++r] = i; } if(f<=r){ visited[q[f]] = 1; bfs(q[f++]); } } }
C
// William Randall // [email protected] // 805167986 #include <pthread.h> //pthread #include <stdio.h> //fprintf #include <stdlib.h> //exit #include <string.h> //strerror //atoi #include <getopt.h> //getopt #include <time.h> //GLOBAL VARS pthread_mutex_t mutex_lock = PTHREAD_MUTEX_INITIALIZER; volatile int spin_lock = 0; volatile int compare_swap_lock = 0; //flag variables int t_flag = 0; int i_flag = 0; int s_flag = 0; int opt_yield = 0; //argument variables int t_arg = 1; int i_arg = 1; char s_arg = 0; //GLOBAL STRUCT static struct option arr_option[] = { {"threads", required_argument, 0, 't'}, {"iterations", required_argument, 0, 'i'}, {"sync", required_argument, 0, 's'}, {"yield", no_argument, 0, 'y'}, {0, 0, 0, 0} }; struct addParameters { int iterations; char thread_type; long long * counter_pointer; }; typedef struct addParameters addParameters_t; //HELPER FUNCTIONS //general add function to call the other types of adds based on --sync void * general_add(void * parameters); //add but it is not protected void add(long long *pointer, long long value); //add protected with mutex void add_m(long long *pointer, long long value); //add protected with sync void add_s(long long *pointer, long long value); //add protected with compare and swap void add_c(long long *pointer, long long value); int main(int argc, char ** argv) { int ind = 0; int ch = 0; //argument parsing while ( (ch = getopt_long(argc, argv, "t:i:s:y", arr_option, &ind) ) != -1){ switch (ch){ case 't': t_flag = 1; t_arg = atoi(optarg); break; case 'i': i_flag = 1; i_arg = atoi(optarg); break; case 's': s_flag = 1; s_arg = *optarg; break; case 'y': opt_yield = 1; break; default: fprintf(stderr, "incorrect usage: lab2_add [--threads=#] [--iterations=#] [--sync=s|m|c] [--yield]\n"); exit(1); } } //set up variables long long counter = 0; //make timespec structures struct timespec start_time; struct timespec end_time; //set up expected tag fields char name[15]; if(opt_yield){ strcpy(name, "add-yield-"); } else{ strcpy(name, "add-"); } if(s_flag){ if(s_arg == 'm'){ strcat(name, "m\0"); } else if(s_arg == 's'){ strcat(name, "s\0"); } else if(s_arg == 'c'){ strcat(name, "c\0"); } else{ fprintf(stderr, "incorrect argument to --sync: lab2_add [--sync=s|m|c] ...\n"); exit(1); } } else{ strcat(name, "none\0"); } //make a struct with the correct parameters addParameters_t parameters; parameters.iterations = i_arg; parameters.thread_type = s_arg; parameters.counter_pointer = &counter; //start time clock_gettime(CLOCK_REALTIME, &start_time); //make a pthread array of variable size pthread_t * pthread_array = malloc(sizeof(pthread_t) * t_arg); //create each thread for(int i = 0; i < t_arg; i++){ pthread_create(&pthread_array[i], NULL, general_add, &parameters); } //join the threads back together for(int i = 0; i < t_arg; i++){ pthread_join(pthread_array[i], NULL); } //free the pthread array free(pthread_array); //end time clock_gettime(CLOCK_REALTIME, &end_time); //time in seconds long seconds = end_time.tv_sec - start_time.tv_sec; //time in nanoseconds long nano_seconds = end_time.tv_nsec - start_time.tv_nsec; //handle underflow for nanoseconds if(start_time.tv_nsec > end_time.tv_nsec){ seconds -= 1; nano_seconds += 999999999 + 1; } //output in csv format // the name of the test (add-none for the most basic usage) printf("%s,",name); // the number of threads (from --threads=) printf("%d,",t_arg); // the number of iterations (from --iterations=) printf("%d,",i_arg); // the total number of operations performed (threads x iterations x 2, the "x 2" factor because you add 1 first and then add -1) int num_operations = t_arg * i_arg * 2; printf("%d,",num_operations); // the total run time (in nanoseconds) long total_time = seconds * 1000000000 + nano_seconds; printf("%ld,",total_time); // the average time per operation (in nanoseconds). long average_time = total_time / num_operations; printf("%ld,",average_time); // the total at the end of the run (0 if there were no conflicting updates) printf("%lld\n",counter); return 0; } //required function implementations void * general_add(void * parameters){ addParameters_t * ptr_add_parameters = (addParameters_t * ) parameters; //create flags int m = 0; int s = 0; int c = 0; if(s_flag){ switch(ptr_add_parameters->thread_type){ case 'm': m = 1; break; case 's': s = 1; break; case 'c': c = 1; break; default: fprintf(stderr, "ERROR INVALID --SYNC PARAMETER\n"); exit(1); } } int add_or_sub = 1; for(int j = 0; j < 2; j++){ for(int i = 0; i < ptr_add_parameters->iterations; i++){ if(!s_flag && !m && !s && !c){ add(ptr_add_parameters->counter_pointer, add_or_sub); } //perform mutex operation else if(m && !s && !c){ add_m(ptr_add_parameters->counter_pointer, add_or_sub); } //perform spin operation else if(!m && s && !c){ add_s(ptr_add_parameters->counter_pointer, add_or_sub); } //perform compare and swap operation else if(!m && !s && c){ add_c(ptr_add_parameters->counter_pointer, add_or_sub); } //error else{ fprintf(stderr, "ERROR INVALID SYNTAX\n"); exit(1); } } add_or_sub = -1; } return NULL; } void add(long long *pointer, long long value) { long long sum = *pointer + value; if (opt_yield) sched_yield(); *pointer = sum; } void add_m(long long *pointer, long long value) { //lock mutex if(pthread_mutex_lock(&mutex_lock)){ fprintf(stderr, "error locking mutex\n"); exit(2); } //perform add long long sum = *pointer + value; if(opt_yield) sched_yield(); *pointer = sum; //unlock mutex if(pthread_mutex_unlock(&mutex_lock)){ fprintf(stderr, "error unlocking mutex\n"); exit(2); } } void add_s(long long *pointer, long long value) { //set up the spin lock while(__sync_lock_test_and_set(&spin_lock, 1)){ while(spin_lock); } //perform add long long sum = *pointer + value; if (opt_yield) sched_yield(); *pointer = sum; //release the spin lock __sync_lock_release(&spin_lock); } void add_c(long long *pointer, long long value) { //get old value long long old_value = *pointer; long long sum = 0; // perform add with no protection sum = old_value + value; if (opt_yield) sched_yield(); while(__sync_val_compare_and_swap(pointer, old_value, sum) != old_value){ //if the old value is not synced over update and perform add again old_value = *pointer; sum = old_value + value; if (opt_yield) sched_yield(); } }
C
#include "libft.h" void proc_uint(t_option *options, va_list ap) { unsigned long num; char *number; num = va_arg(ap, unsigned int); if (options->precision == 0 && num == 0) { number = ""; print_num(options, number); } else { number = ft_utoa(num); if (number == NULL) { options->error = -1; return ; } print_num(options, number); free(number); } }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <pthread.h> #include <signal.h> #include <time.h> #include <errno.h> #include "common.h" int sendMsg(char *msg,int sock,skaddr *addr,int size){ if(msg && addr){ if(sendto(sock,msg,strlen(msg),0,addr,size)<0){ perror("send failed"); return -1; } return 0; } return -1; } /*reads the "value" from the "filename"*/ char * readConf(char *filename,char *value){ FILE * conf; char rd[MAX_STRING]; char *reply; if(filename && value){ memset(rd,0,MAX_STRING); conf=fopen(filename,"r"); if(conf){ while(!feof(conf)){ fscanf(conf,"%s",rd); if(strstr(rd,value)!=NULL){ reply=malloc(sizeof(rd)-strlen(value)); strcpy(reply,rd+strlen(value)); fclose(conf); return reply; } } fclose(conf); } else printf("Reading failed, file \"%s\" does not exist\n",filename); } return NULL; } /*writes the value "value" associated with the type "type" in the file "filename"*/ int writeConf(char *filename,char *type,char *value){ FILE * conf; char *ptr; char rd[MAX_WRITE_STRING]; conf=fopen(filename,"r+"); memset(rd,0,MAX_WRITE_STRING); fread(rd,sizeof(char),MAX_WRITE_STRING-1,conf); ptr=strstr(rd,type); if(ptr){ memcpy(ptr+strlen(type),value,strlen(value)); fseek(conf,0,SEEK_SET); fwrite(rd,sizeof(char),strlen(rd),conf); fclose(conf); return 0; } fclose(conf); return -1; } /*sends "JOIN" and "DSJOIN" messages depending on "msgType"*/ void setupAndSendMsg(char* srvId,char *msgType,int sock,skaddr *addr,int size){ char reply[JOIN_MSG_LEN]; if(srvId && addr){ memset(reply,0,JOIN_MSG_LEN); strcpy(reply,msgType); strcat(reply,DELIMITER); strcat(reply,srvId); sendMsg(reply,sock,addr,size); } } /*parses tocken from "msg" at "tockenPosition"*/ char * parseTocken(char *msg,int tockenPosition,char *delimiter){ char cpyMsg[CM_MAX_MSG_LEN]; char *cpyPtr; char *tmpTocken; char *tocken; if(msg){ memset(cpyMsg,0,CM_MAX_MSG_LEN); strcpy(cpyMsg,msg); cpyPtr=cpyMsg; while(tockenPosition>0){ tmpTocken=strtok_r(cpyPtr,delimiter,&cpyPtr); tockenPosition--; } if(tmpTocken){ tocken=malloc(strlen(tmpTocken)+1); memset(tocken,0,strlen(tmpTocken)+1); strcpy(tocken,tmpTocken); return tocken; } } return NULL; } int creatUdpSocketIpv4(){ int sock; if((sock=socket(AF_INET,SOCK_DGRAM,0))<0){ perror("Ipv4 socket creation failed"); exit(0); } return sock; } int creatUdpSocketIpv6(){ int sock; if((sock=socket(AF_INET6,SOCK_DGRAM,0))<0){ perror("Ipv6 socket creation failed"); exit(0); } return sock; } int bindSock(int socket,skaddr* addr,int size){ if(bind(socket,addr,size)<0){ perror("bind failed"); return -1; } return 0; } int setAddrIpv4(skaddr_in *addr_ipv4,uint16_t port,char *ipv4){ if(addr_ipv4&&ipv4){ memset(addr_ipv4,0,sizeof(skaddr_in)); addr_ipv4->sin_family=AF_INET; addr_ipv4->sin_port=htons(port); if(inet_pton(AF_INET,ipv4,&(addr_ipv4->sin_addr))<=0){ printf("Ipv4 address assignment failed\n"); return -1; } return 0; } return -1; } int setAddrIpv6(skaddr_in6 *addr_ipv6,uint16_t port,char *ipv6){ if(addr_ipv6&&ipv6){ memset(addr_ipv6,0,sizeof(skaddr_in6)); addr_ipv6->sin6_family=AF_INET6; addr_ipv6->sin6_port=htons(port); if(inet_pton(AF_INET6,ipv6,&(addr_ipv6->sin6_addr))<=0){ printf("Ipv6 address assignment failed\n"); return -1; } return 0; } return -1; } void rcvMsg(int sock,char *msg,skaddr *addr,socklen_t size){ if(recvfrom(sock,msg,CM_MAX_MSG_LEN-1,0,addr,&size)<0){ perror("Receive failed\n"); } }
C
/* * dac8532_set.c: * Very simple program to write the DAC8532 serial port. Expects * the port to be looped back to itself * Matt Ebert 04/2018 /* define from bcm2835.h define from Board DVK511 3.3V | | 5V -> 3.3V | | 5V RPI_V2_GPIO_P1_03 | | 5V -> SDA | | 5V RPI_V2_GPIO_P1_05 | | GND -> SCL | | GND RPI_GPIO_P1_07 | | RPI_GPIO_P1_08 -> IO7 | | TX GND | | RPI_GPIO_P1_10 -> GND | | RX RPI_GPIO_P1_11 | | RPI_GPIO_P1_12 -> IO0 | | IO1 RPI_V2_GPIO_P1_13 | | GND -> IO2 | | GND RPI_GPIO_P1_15 | | RPI_GPIO_P1_16 -> IO3 | | IO4 VCC | | RPI_GPIO_P1_18 -> VCC | | IO5 RPI_GPIO_P1_19 | | GND -> MOSI | | GND RPI_GPIO_P1_21 | | RPI_GPIO_P1_22 -> MISO | | IO6 RPI_GPIO_P1_23 | | RPI_GPIO_P1_24 -> SCK | | CE0 GND | | RPI_GPIO_P1_26 -> GND | | CE1 ::if your raspberry Pi is version 1 or rev 1 or rev A RPI_V2_GPIO_P1_03->RPI_GPIO_P1_03 RPI_V2_GPIO_P1_05->RPI_GPIO_P1_05 RPI_V2_GPIO_P1_13->RPI_GPIO_P1_13 :: */ #include <bcm2835.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <errno.h> //CS ----- SPICS //DIN ----- MOSI //DOUT ----- MISO //SCLK ----- SCLK //DRDY ----- ctl_IO data starting //RST ----- ctl_IO reset #define SPICS RPI_GPIO_P1_16 //P4 #define CS_1() bcm2835_gpio_write(SPICS,HIGH) #define CS_0() bcm2835_gpio_write(SPICS,LOW) #define uint8_t unsigned char #define uint16_t unsigned short #define VREF 5.0 // voltage ref used #define DAC_BITS 16 // 16b DAC word // output cannot exceed vref (2**16- 1b)/2**16, change if lower value is necessary #define MAX_V VREF-VREF/(1<<(DAC_BITS-1)) #define MAX_CHANNEL 2 // 2 DAC channels #define CHANNEL_0 0x30 // dac0, ch A #define CHANNEL_1 0x34 // dac1, ch B void bsp_DelayUS(uint64_t micros); void Write_DAC8532(uint8_t channel, uint16_t Data); uint16_t Voltage_Convert(float voltage); void bsp_DelayUS(uint64_t micros){ bcm2835_delayMicroseconds (micros); } void Write_DAC8532(uint8_t channel, uint16_t Data){ uint8_t i; CS_1() ; CS_0() ; bcm2835_spi_transfer(channel); bcm2835_spi_transfer((Data>>8)); bcm2835_spi_transfer((Data&0xff)); CS_1() ; } uint16_t Voltage_Convert(float voltage){ uint16_t _D_; _D_ = (uint16_t)round(65536 * voltage / VREF); return _D_; } int main(int argc, char **argv){ // process and sanitize inputs if (argc != 3){ printf("Expecting 2 arguments: channel voltage\n"); return 1; } errno = 0; // catch errors, from errno.h int channel = atoi(argv[1]); if (errno != 0){ printf("errno %d encoutered converting %s to `int`\n", errno, argv[1]); return 1; } float voltage = atof(argv[2]); if (errno != 0){ printf("errno %d encoutered converting %s to `float`\n", errno, argv[2]); return 1; } if (channel < 0 || channel > MAX_CHANNEL-1){ printf("channel designation: `%d` exceeds MAX_CHANNEL spec: `%d`.\n", channel, MAX_CHANNEL); return 1; } if (voltage > MAX_V){ printf("voltage designation: `%f` exceeds MAX_VOLTAGE spec: `%f`.\n", voltage, MAX_V); voltage = MAX_V; } else if (voltage < 0){ printf("voltage designation: `%f` exceeds MIN_VOLTAGE spec: `%f`.\n", voltage, 0); voltage = 0; } // set up the spi if (!bcm2835_init()){ return 1; } bcm2835_spi_begin(); bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_LSBFIRST ); // The default bcm2835_spi_setDataMode(BCM2835_SPI_MODE1); // The default; bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_1024); // The default bcm2835_gpio_fsel(SPICS, BCM2835_GPIO_FSEL_OUTP);// bcm2835_gpio_write(SPICS, HIGH); //Write channel buffer Write_DAC8532( ((char[]){CHANNEL_0, CHANNEL_1})[channel], Voltage_Convert(voltage) ); // close down bcm2835_spi_end(); bcm2835_close(); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <malloc.h> #include "../kp_6/data.h" #include "../kp_6/output.h" #include "../kp_6/re_builder.h" const int N = 12; void best (info_stud *tmp) { int markss[12] = {0}; int students[12] = {0}; while (tmp) { if (tmp->sex_stud == 'F') { markss[tmp->group_num] += tmp->mks.ez.ma; markss[tmp->group_num] += tmp->mks.ez.hi; markss[tmp->group_num] += tmp->mks.ez.dm; markss[tmp->group_num] += tmp->mks.ez.cs; students[tmp->group_num] += 1; } tmp = tmp->next; } float max_marks = 0; int max_gr; for (int i = 1; i <= N; i++) { if (students[i] > 0) { if (markss[i]/students[i] > max_marks) { max_marks = markss[i]/students[i]; max_gr = i; } } } if (max_marks == 0) { printf ("%s\n", "Didn't found students"); } else { printf ("%d\n", max_gr); } }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_2__ TYPE_1__ ; /* Type definitions */ typedef int u32 ; struct clksel_rate {int div; int flags; } ; struct clksel {struct clksel_rate* rates; } ; struct clk {int name; TYPE_1__* parent; } ; struct TYPE_2__ {unsigned long rate; int /*<<< orphan*/ name; } ; /* Variables and functions */ int cpu_mask ; struct clksel* omap2_get_clksel_by_parent (struct clk*,TYPE_1__*) ; int /*<<< orphan*/ pr_debug (char*,int,unsigned long) ; int /*<<< orphan*/ pr_err (char*,unsigned long,...) ; u32 omap2_clksel_round_rate_div(struct clk *clk, unsigned long target_rate, u32 *new_div) { unsigned long test_rate; const struct clksel *clks; const struct clksel_rate *clkr; u32 last_div = 0; pr_debug("clock: clksel_round_rate_div: %s target_rate %ld\n", clk->name, target_rate); *new_div = 1; clks = omap2_get_clksel_by_parent(clk, clk->parent); if (!clks) return ~0; for (clkr = clks->rates; clkr->div; clkr++) { if (!(clkr->flags & cpu_mask)) continue; /* Sanity check */ if (clkr->div <= last_div) pr_err("clock: clksel_rate table not sorted " "for clock %s", clk->name); last_div = clkr->div; test_rate = clk->parent->rate / clkr->div; if (test_rate <= target_rate) break; /* found it */ } if (!clkr->div) { pr_err("clock: Could not find divisor for target " "rate %ld for clock %s parent %s\n", target_rate, clk->name, clk->parent->name); return ~0; } *new_div = clkr->div; pr_debug("clock: new_div = %d, new_rate = %ld\n", *new_div, (clk->parent->rate / clkr->div)); return (clk->parent->rate / clkr->div); }
C
#include <tertium/cpu.h> #include <tertium/std.h> #define STRCPY(a, b) c_mem_cpy((a), sizeof((b)), (b)) char * c_gen_dirname(char *s) { usize n; if (!s) return nil; if (!*s) return STRCPY(s, "."); n = c_str_len(s, -1) - 1; for (; s[n] == '/'; --n) if (!n) return STRCPY(s, "/"); for (; s[n] != '/'; --n) if (!n) return STRCPY(s, "."); for (; s[n] == '/'; --n) if (!n) return STRCPY(s, "/"); s[n+1] = 0; return s; }
C
#include "stdio.h" int main() { struct { int a; int b; }x,y; x.a = 10; y = x; printf("%d\n",y.a); return 0; }
C
/****************************************** * task name: oledDisplay * task inputs: void* pointer to a DisplayData struct (see tasks.h) * task outputs: Text to OLED display * task description: Takes strings from the displayData struct and outputs them to an OLED display * author: Ryan McDaniel ******************************************/ #include "tasks.h" #include "schedule.h" #include "drivers/rit128x96x4.h" #define CLEAR " " #define LINE 8 #define CNTRST 15 #define L_ALLIGN 0 #define R_ALLIGN 65 #define C_ALLIGN 40 #define MAX_LINES 12 #define NUM_OPTS 4 void clearOLED(int numLines); typedef enum {BLOOD, TEMP, PULSE, BATT} measurement; typedef enum {NORMAL, ANNUNCIATE} displayMode; extern unsigned long globalTime; void oledDisplaySetup() { // Initialize the OLED Display RIT128x96x4Init(10000000); } // print out the current readings void oledDisplay(void* taskDataPtr) { if(globalTime % MAJORCYCLECOUNT == 0) { // Grab all the data from the structure DisplayData* displayDataPtr = (DisplayData*) taskDataPtr; char* temperaturePtr = displayDataPtr->tempCorrectedBuf->headPtr; char* pulseRatePtr = displayDataPtr->prCorrectedBuf->headPtr; char* batteryPtr = displayDataPtr->battCorrected->headPtr; char* systolicPressPtr = displayDataPtr->systolicPressCorrectedBuf->headPtr; char* diatolicPressPtr = displayDataPtr->diastolicPressCorrectedBuf->headPtr; unsigned short* myScroll = displayDataPtr->scroll; // Controlling display modes static displayMode lastMode = NORMAL; measurement myMeasurement = (measurement) *(displayDataPtr->measurementSelection); displayMode currentMode = (displayMode) *(displayDataPtr->mode); // Clear everything if the mode changes if (currentMode != lastMode) { clearOLED(MAX_LINES); } if (currentMode == ANNUNCIATE) { // Ignore scroll changes if (*(myScroll) == 1) *(myScroll) = 0; // Blood pressures RIT128x96x4StringDraw("Systolic", L_ALLIGN, LINE*0, CNTRST); RIT128x96x4StringDraw("Diastolic", R_ALLIGN, LINE*0, CNTRST); RIT128x96x4StringDraw(CLEAR, L_ALLIGN, LINE*1, CNTRST); // Print Systolic pressure, and the units around 38 pixels after RIT128x96x4StringDraw(systolicPressPtr, L_ALLIGN, LINE*1, CNTRST); RIT128x96x4StringDraw("mmHg", L_ALLIGN + 38, LINE*1, CNTRST); // Print Diastolic pressure, and the units around 35 pixels after RIT128x96x4StringDraw(diatolicPressPtr, R_ALLIGN, LINE*1, CNTRST); RIT128x96x4StringDraw("mmHg", R_ALLIGN + 35, LINE*1, CNTRST); // Print pulse and temperature RIT128x96x4StringDraw("Pulse:", L_ALLIGN, LINE*2, CNTRST); RIT128x96x4StringDraw("Temp:", R_ALLIGN, LINE*2, CNTRST); RIT128x96x4StringDraw(CLEAR, L_ALLIGN, LINE*3, CNTRST); // Print Pulse rate, and the units around 38 pixels after RIT128x96x4StringDraw(pulseRatePtr, L_ALLIGN, LINE*3, CNTRST); RIT128x96x4StringDraw("BPM", L_ALLIGN + 38, LINE*3, CNTRST); // Print the Temperature, and the units around 35 units after RIT128x96x4StringDraw(temperaturePtr, R_ALLIGN, LINE*3, CNTRST); RIT128x96x4StringDraw("C", R_ALLIGN + 35, LINE*3, CNTRST); // Print the battery reading, centered a few lines further down RIT128x96x4StringDraw("Battery:", C_ALLIGN, LINE*9, CNTRST); RIT128x96x4StringDraw(CLEAR, L_ALLIGN, LINE*10, CNTRST); // Print battery percent, units around 40 pixels after the reading RIT128x96x4StringDraw(batteryPtr, C_ALLIGN, LINE*10, CNTRST); RIT128x96x4StringDraw("%", C_ALLIGN + 40, LINE*10, CNTRST); // Directions for changing views RIT128x96x4StringDraw("'D' to change Display", L_ALLIGN, LINE*11, CNTRST); } else if (currentMode == NORMAL) { // Display the normal menu RIT128x96x4StringDraw("0 Blood Pressure ", L_ALLIGN, LINE*0, CNTRST); RIT128x96x4StringDraw("1 Temperature", L_ALLIGN, LINE*2, CNTRST); RIT128x96x4StringDraw("2 Pulse Rate", L_ALLIGN, LINE*4, CNTRST); RIT128x96x4StringDraw("3 Battery", L_ALLIGN, LINE*6, CNTRST); RIT128x96x4StringDraw("'D' to change Display", L_ALLIGN, LINE*9, CNTRST); RIT128x96x4StringDraw("'9' to scroll", L_ALLIGN, LINE*10, CNTRST); // Clear all measurement lines in case selected measurement changes RIT128x96x4StringDraw(CLEAR, L_ALLIGN, LINE*1, CNTRST); RIT128x96x4StringDraw(CLEAR, L_ALLIGN, LINE*3, CNTRST); RIT128x96x4StringDraw(CLEAR, L_ALLIGN, LINE*5, CNTRST); RIT128x96x4StringDraw(CLEAR, L_ALLIGN, LINE*7, CNTRST); // Handle scrolling if (*(myScroll) == 1) { myMeasurement = (measurement)(((int)myMeasurement + 1) % NUM_OPTS); *(myScroll) = 0; } // Display Blood pressure measurements if (myMeasurement == BLOOD) { RIT128x96x4StringDraw(CLEAR, L_ALLIGN, LINE*0, CNTRST); RIT128x96x4StringDraw("Systolic", L_ALLIGN, LINE*0, CNTRST); RIT128x96x4StringDraw("Diastolic", R_ALLIGN, LINE*0, CNTRST); RIT128x96x4StringDraw(systolicPressPtr, L_ALLIGN, LINE*1, CNTRST); RIT128x96x4StringDraw("mmHg", L_ALLIGN + 38, LINE*1, CNTRST); RIT128x96x4StringDraw(diatolicPressPtr, R_ALLIGN, LINE*1, CNTRST); RIT128x96x4StringDraw("mmHg", R_ALLIGN + 35, LINE*1, CNTRST); } // Display Temperature measurements else if (myMeasurement == TEMP) { RIT128x96x4StringDraw(temperaturePtr, L_ALLIGN, LINE*3, CNTRST); RIT128x96x4StringDraw("C", L_ALLIGN + 38, LINE*3, CNTRST); } // Display Pulse measurements else if (myMeasurement == PULSE) { RIT128x96x4StringDraw(pulseRatePtr, L_ALLIGN, LINE*5, CNTRST); RIT128x96x4StringDraw("BPM", L_ALLIGN + 38, LINE*5, CNTRST); } // Display Battery measurements else if (myMeasurement == BATT) { RIT128x96x4StringDraw(batteryPtr, L_ALLIGN, LINE*7, CNTRST); RIT128x96x4StringDraw("%", L_ALLIGN + 38, LINE*7, CNTRST); } } lastMode = currentMode; *(displayDataPtr->measurementSelection) = (unsigned short) myMeasurement; removeFlags[TASK_DISPLAY] = 1; } } // Clears all the lines used by the program void clearOLED(int numLines) { int i = 0; for (i = 0; i < numLines; i++) { RIT128x96x4StringDraw(CLEAR, L_ALLIGN, LINE*i, CNTRST); } }
C
#ifndef __SLIST_H__ #define __SLIST_H__ typedef struct slist slist_t; slist_t *slist_alloc(void (*free)(void *)); void slist_free(slist_t *list); void slist_clear(slist_t *list); size_t slist_size(slist_t *list); void slist_reverse(slist_t *list); void slist_sort(slist_t *list, int(*compare)(void *, void *)); void slist_push_back(slist_t *list, void *data); void slist_push_front(slist_t *list, void *data); void slist_push_at(slist_t *list, void *data, int n); void *slist_pop_back(slist_t *list); void *slist_pop_front(slist_t *list); void *slist_pop_at(slist_t *list, int n); void *slist_front(slist_t *list); void *slist_back(slist_t *list); void *slist_begin(slist_t *list); void *slist_at(slist_t *list, int n); void *slist_next(slist_t *list); void *slist_end(slist_t *list); void slist_foreach(slist_t *list, int(*cb)(void *, void *), void *arg); #endif
C
/* ** EPITECH PROJECT, 2019 ** Projet tek1 ** File description: ** lib function */ #include "../include/my.h" char *my_array_strcpy(char *str) { char *str1 = malloc(sizeof(char) * my_strlen(str)); int y = 0; for (; str[y] != 0; y++) str1[y] = str[y]; return (str1); }
C
#include <assert.h> #include <stdio.h> #include <unistd.h> #include <cutils/time.h> #include <cutils/timeout_list.h> // Test a timeout-list where retrieved entries are not older than 100ms #define TIMEOUT_MS 100 int main(void) { int err = 0; // Init a timeout-list with entry size of 8 bytes tolist_ctx_t *tolctx = timout_list_init(TIMEOUT_MS, sizeof(uint64_t)); // Push an entry uint64_t ts0 = gettsc(); err = timout_list_put(tolctx, &ts0); assert(err == 0); usleep(TIMEOUT_MS * 1000); // Push second entry // By this time first entry will be obsolete due to sleep above uint64_t ts1 = gettsc(); err = timout_list_put(tolctx, &ts1); assert(err == 0); // Verify that the list returns only one entry and that's the second one uint64_t buf[2] = { 0 }; err = timout_list_get(tolctx, buf, sizeof(buf)); assert(err == sizeof(ts1) && buf[0] == ts1); // Destroy the timeout-list timeout_list_fini(tolctx); // Gets here only if above test passes printf("PASSED\n"); return 0; }
C
#include "head.h" //使用多进程,实现多个客户端通信 int main() { pchild p =(pchild)calloc(NUMCLIENT,sizeof(child));//动态分配内存,初始化为零 create_child(p); int sfd = tcp_init(); int epfd = epoll_create(1); struct epoll_event* evs = (struct epoll_event*)calloc(NUMCLIENT+1,sizeof(struct epoll_event)); epfd_add(sfd,epfd); int i; for(i = 0; i < NUMCLIENT; i++) //子进程注册epolll { epfd_add(p[i].fds,epfd);//socketpair的另一端注册,父进程获取相应子进程的状态 } int ret; int new_fd; int j; int flag; while(1) { memset(evs,0,(NUMCLIENT+1)*sizeof(struct epoll_event)); ret = epoll_wait(epfd,evs,NUMCLIENT+1,-1); if(ret > 0) { for(i = 0; i < ret; i++) { if(evs[i].data.fd == sfd) //监听客户端请求 { new_fd = tcp_accept(sfd); //连接客户端 for(j = 0; j < NUMCLIENT; j++) //寻找空闲的子进程 { if(p[j].busy == 0) break; } send_fd(p[j].fds,new_fd); //向子进程发送fd p[j].busy = 1; } for(j = 0; j < NUMCLIENT; j++)//判断子进程是否空闲 { if(evs[j].data.fd == p[j].fds) //当对应子进程fds可读时,子进程不忙碌 { read(p[j].fds,&flag,sizeof(flag)); p[j].busy =0; } } } } } }
C
/* * probotype.c Jim Piper 17-10-86 * * * Use simple tests to decide probable type of object, * currently: NOISE, CHROMOSOME or COMPOSITE on basis of size * * Modifications * 30 Oct 1989 dcb/GJP/CAS Set plist->otype for CHROMOSOME as well as * returning the value */ #include <stdio.h> #include <wstruct.h> #include <chromanal.h> probotype(obj) struct chromosome *obj; { struct chromplist *plist = obj->plist; /* * Otype already set with high confidence ?? * In which case, the type of guessing done * here is NOT required !! */ if (plist->Cotype != 0 || plist->otconf == 100) return(0); /* * Area known ? */ if (plist->area == 0) plist->area = area(obj); /* * use area to guess type */ if (plist->area < 100) { plist->otype = NOISE; plist->otconf = 20; return(NOISE); } else if (plist->area > 2000) { plist->otype = COMPOSITE; plist->otconf = 20; return(COMPOSITE); } else { plist->otype = CHROMOSOME; plist->otconf = 20; return(CHROMOSOME); /* the default */ } }
C
#pragma once #include <brutal/base/macros.h> #include <brutal/base/std.h> #include <brutal/mem.h> struct alloc; void alloc_no_op(struct alloc *self, void *ptr); typedef void *alloc_acquire_t(struct alloc *self, size_t size); typedef void alloc_commit_t(struct alloc *self, void *ptr); typedef void alloc_decommit_t(struct alloc *self, void *ptr); typedef void alloc_release_t(struct alloc *self, void *ptr); struct alloc { alloc_acquire_t *acquire; alloc_commit_t *commit; alloc_decommit_t *decommit; alloc_release_t *release; }; #define alloc_acquire(self, size) \ ((self)->acquire((self), size)) #define alloc_commit(self, ptr) \ ((self)->commit((self), ptr)) #define alloc_make(self, T) ( \ { \ T *ptr = alloc_acquire(self, sizeof(T)); \ alloc_commit(self, ptr); \ mem_set(ptr, 0, sizeof(T)); \ ptr; \ }) #define alloc_make_array(self, T, count) ( \ { \ T *ptr = alloc_acquire(self, sizeof(T) * count); \ alloc_commit(self, ptr); \ mem_set(ptr, 0, sizeof(T) * count); \ ptr; \ }) #define alloc_decommit(self, ptr) \ ((self)->decommit((self), ptr)) #define alloc_release(self, ptr) \ ((self)->commit((self), ptr))
C
// Lossy Scheme: parser. // // Copyright 2013 Martin Pool #include <assert.h> #include "loss.h" lossobj *loss_cons_new(void) { lossobj *obj = calloc(1, sizeof *obj); assert(obj); obj->type = CONS; return obj; } lossobj *loss_cons_new_pair(lossobj *hd, lossobj *tl) { lossobj *c = loss_cons_new(); c->val.cons.hd = hd; c->val.cons.tl = tl; return c; } // Append a to the list in o. *o must be a cons cell at the start of a // proper (possibly empty) list. void loss_list_append(lossobj *o, lossobj *a) { again: assert(o->type == CONS); lossobj *hd = o->val.cons.hd, *tl = o->val.cons.tl; if (!hd) { // First item in an empty list assert(tl == NULL); o->val.cons.hd = a; return; } else if (tl) { // Continue down the list o = tl; goto again; } else { // We're on the last occupied cell; we need to insert a new // cell and then put the value in there. o = o->val.cons.tl = loss_cons_new(); goto again; } } lossobj *loss_list_nth(lossobj *l, int n) { while (n > 0) { assert(l); assert(l->type == CONS); l = l->val.cons.tl; n--; } return l->val.cons.hd; } int loss_list_len(lossobj *l) { int i = 0; while (l) { assert(l->type == CONS); i++; l = l->val.cons.tl; } return i; }
C
#include <stdio.h> int main (int argc, char*argv[]) { FILE * pFile; char c; pFile=fopen(argv[1],"wt"); if (pFile==NULL) perror("fopen error"); for (c = 'A' ; c <= 'Z' ; c++) { putc (c , pFile); } putc('\n',pFile); fclose (pFile); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sastantua.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rfrancal <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/08/13 11:10:54 by rfrancal #+# #+# */ /* Updated: 2017/08/14 11:26:11 by rfrancal ### ########.fr */ /* */ /* ************************************************************************** */ void ft_putchar(char c); int find_offset(int size) { int offset; int count; int index; count = 0; if ((offset = 3) && (size == 1)) return (offset); while (size >= offset) { offset++; } if ((size > 1) && (size < 5)) { return (offset * offset); } else { count++; index = 5; while (index < size) { if (index % 2 == 1) { count += count; } index++; } } return ((offset * offset) - count); } int stars(int size, int row, int prev, int flag) { if ((row == 0) && (size == 0)) { return (1); } else if (size == 0) { return (row * 2 + 1); } else if (size == 1) { return ((row * 2 + 1) + 10); } else if (flag == 0) return (prev + (((size / 2) + 2) * 2)); else return (prev + 2); } void sastantua(int size) { int row; int col; int magnitude; int spaces; int i; int star; int prev; int flag; spaces = find_offset(size); magnitude = 0; row = 0; star = 0; while (magnitude < size) { flag = 0; row = 0; while (row < (magnitude + 3)) { col = 0; i = 0; prev = star; star = stars(magnitude, row, prev, flag); flag = 1; while (i < (spaces - ((star - 1) / 2))) { ft_putchar(' '); i++; } ft_putchar('/'); while (col < star) { ft_putchar('*'); col++; } ft_putchar('\\'); ft_putchar('\n'); row++; } magnitude++; } } int main(void) { sastantua(5); }
C
#include <stdio.h> #include <stdlib.h> #define MaxVertexNum 100 #define INFINITY 65535 typedef int Vertex; typedef int WeightType; typedef char DataType; typedef struct GNode * PtrToGNode; struct GNode { int Nv; int Ne; WeightType G[MaxVertexNum][MaxVertexNum]; DataType Data[MaxVertexNum]; // there are data in vertex }; typedef PtrToGNode MGraph; // matrix graph // edge definition typedef struct ENode * PtrToENode; struct ENode { Vertex V1, V2; // <V1, V2> WeightType Weight; }; typedef PtrToENode Edge; MGraph CreateGraph(int VertexNum) // create a graph with VertexNum vertex, no edge { Vertex V, W; MGraph Graph; Graph = (MGraph) malloc(sizeof(struct GNode)); Graph->Nv = VertexNum; Graph->Ne = 0; for(V=0; V<Graph->Nv; V++) { // initialization for(W=0; W<Graph->Nv; W++) { Graph->G[V][W] = INFINITY; } } return Graph; } void InsertEdge(MGraph Graph, Edge E) { Graph->G[E->V1][E->V2] = E->Weight; Graph->G[E->V2][E->V1] = E->Weight; // if no direction graph } MGraph BuildGraph() { MGraph Graph; Edge E; Vertex V; int Nv, i; scanf("%d", &Nv); // num of vertex Graph = CreateGraph(Nv); scanf("%d", &(Graph->Ne)); if(Graph->Ne != 0) { E = (Edge) malloc(sizeof(struct ENode)); for(i=0; i<Graph->Ne; i++) { scanf("%d %d %d", &E->V1, &E->V2, &E->Weight); InsertEdge(Graph, E); } } // if there are data scanf("\n"); for(V=0; V<Graph->Nv; V++) { if (V<Graph->Nv-1) { scanf("%c ", &Graph->Data[V]); } else { scanf("%c", &Graph->Data[V]); } } return Graph; } void PrintGraph(MGraph Graph) { printf("Num of vertex: %d\n", Graph->Nv); printf("Num of edge: %d\n", Graph->Ne); int i, j; // print data for(i=0; i<Graph->Nv; i++) { printf("%c\t", Graph->Data[i]); } printf("\n"); // print weight for(i=0; i<Graph->Nv; i++) { for(j=0; j<Graph->Nv; j++) { printf("%d\t", Graph->G[i][j]); } printf("\n"); } } int main(void) { MGraph G; G = BuildGraph(); PrintGraph(G); return 0; } /* ### test input: ### 5 3 0 1 -2 2 3 -4 0 4 -10 A B C D E ### output: ### Num of vertex: 5 Num of edge: 3 A B C D E 65535 -2 65535 65535 -10 -2 65535 65535 65535 65535 65535 65535 65535 -4 65535 65535 65535 -4 65535 65535 -10 65535 65535 65535 65535 */
C
/* ************************************************************************** */ /* */ /* :::::::: */ /* utils.c :+: :+: */ /* +:+ */ /* By: Xiaojing <[email protected]> +#+ */ /* +#+ */ /* Created: 2021/09/05 19:49:00 by Xiaojing #+# #+# */ /* Updated: 2021/09/15 14:26:54 by Xiaojing ######## odam.nl */ /* */ /* ************************************************************************** */ #include "philo.h" void print_msg(struct timeval *start, int n, char *str, t_philo *philo) { struct timeval now; long time_elapse; gettimeofday(&now, NULL); time_elapse = calculate_time(start, &now); if (!philo->data->death && philo->data->status_data == active) { pthread_mutex_lock(&(philo->data->print_mutex)); printf("%ld %d %s\n", time_elapse, n, str); pthread_mutex_unlock(&(philo->data->print_mutex)); } } long calculate_time(struct timeval *start, struct timeval *end) { long time_taken; time_taken = end->tv_sec - start->tv_sec; time_taken = time_taken * 1e3 + (end->tv_usec - start->tv_usec) * 1e-3; return (time_taken); } void mutex_destroy(pthread_mutex_t *fork, int n) { while (n > 0) { pthread_mutex_destroy(&(fork[n - 1])); n--; } } int ft_strcmp(char *a, char *b) { int i; i = 0; while (a[i] != '\0' || b[i] != '\0') { if (a[i] != b[i]) return ((unsigned char)a[i] - (unsigned char)b[i]); i++; } return (0); }
C
#include "books.h" #include "inttypes.h" #include "stdlib.h" #define COVER 1 #define INDEX COVER<<1 #define MISS_PAGES COVER<<2 #define BAR_CODE COVER<<3 #define SPINE COVER<<4 #define STAINED_PAGES COVER<<5 static char * zone[]={(char*)"KIDS", (char*)"HIGHSCHOOL", (char*)"ADULT", (char*)"COMICS", (char*)"DOCUMENTARY"}; static char *erro[]={(char*)"E_OK", (char*)"E_IS_BORROWED", (char*)"E_ALREADY_IN_LIBRARY",(char*)"E_BAD_INDEX",(char*)"E_THIS_BOOK_DIDNT_FOUND"}; static char *problems[]={"COVER","INDEX","MISS_PAGES","BAR_CODE","SPINE","STAINED_PAGES"}; static char *boolen[]={"false","true"}; char * get_zone_name(Zone z) { return zone[z]; } char * get_error_name(ErrorCode z) { return erro[z]; } char * get_boolen(bool r) { return boolen[r]; } void print_Book(Book * b1) { printf("the name is: %s \n",b1->name); printf("the internal number is: %ld \n" ,b1->internal_num); printf("the promotion is %d \n",b1->promotion); printf("the zone is %s \n" ,get_zone_name(b1->z)); printf("************* \n"); } void print_copy(BookCopy *b1) { int i; printf("the internal number is: %ld \n" ,b1->internal_num); printf("the serial number is: %ld \n" ,b1->serial_num); printf("is borrowed: %d \n" ,b1->is_borrowed); printf("borrowing_times: %ld \n" ,b1->borrowing_times); for(i=0;i<6;i++) { if(((b1->problem)&(1<<i))!=0) printf("%s \n", problems[i]); } printf("************* \n"); } ErrorCode error=E_OK; ErrorCode borrow_copy(BookCopy *b1,bool is_borrowing) { error=E_OK; if(is_borrowing==true) { if(b1->is_borrowed==true) { error=E_IS_BORROWED; return error; } else { b1->is_borrowed=true; } } else { if(b1->is_borrowed==true) { b1->is_borrowed=false; } else { error=E_ALREADY_IN_LIBRARY; return error; } } b1->borrowing_times++; return error; } void init_copy(BookCopy *b1,size_t internal) { static size_t serial=10000; b1->internal_num=internal; b1->serial_num=serial; serial++; b1->is_borrowed=false; b1->borrowing_times=0; b1->problem=1; } bool is_librarian_required(BookCopy *b1) { if ((((b1->problem) & (COVER))!=0) || ((INDEX) & (b1->problem))!=0 || ((BAR_CODE) & (b1->problem))!=0) { return true; } return false; } bool is_bookbinder_required(BookCopy *b1) { if ((((MISS_PAGES )&(b1->problem))!=0) || ((STAINED_PAGES) & (b1->problem))!=0 || ((SPINE) & (b1->problem))!=0) { return true; } return false; } bool is_ok(BookCopy *b1) { if (b1->problem!=0) { return false; } return true; } bool is_unless(BookCopy *b1) { int i,count=0; for(i=0;i<6;i++) { if(((1<<i) & b1->problem)!=0) { count++; } if(count==4) return true; } return false; } bool are_in_same_condition(BookCopy *b1,BookCopy *b2) { if(b1->problem==b2->problem) return true; return false; } BookCopy * create_copy(size_t internal) { BookCopy * new_ptr; new_ptr=malloc(sizeof(BookCopy)); init_copy(new_ptr,internal); return new_ptr; }
C
#include "header.h" void insert (node **front, node **rear, node *temp) { if (*rear) { (*rear) -> next = temp; *rear = (*rear) -> next; } else { *rear = temp; } if (NULL == (*front)) { *front = *rear; } }
C
// // schurNumberSaving.h // SchurNumber // // Created by rubis on 14/03/2020. // Copyright © 2020 rubis. All rights reserved. // // Ce fichier déclare les fonctions permettant la sauvegarde des résultats intermédiaires dans un fichier temporaire #ifndef schurNumberSaving_h #define schurNumberSaving_h #include <stdio.h> #include <unistd.h> #include <pthread.h> #include "schurNumberIO.h" #include "schurNumberPartitionStruc.h" #define SCHUR_NUMBER_SAVE_FREQUENCY 4294967296 struct schur_number_save_file_struc { int fd; // Descripteur du fichier où effectuer les sauvegardes intermédiaires char *filename; // Nom du fichier temporaire off_t irem_offset; // Incrément repérant la position où écrire iremainding off_t iternum_offset; // Incrément repérant la position où écrire estimated_iternum off_t percentage_offset; // Incrément repérant la position où écrire le pourcentage de progression off_t nbest_offset; // Incrément repérant la position où écrire nbest }; typedef struct schur_number_save_file_struc schur_number_save_file_t; struct schur_number_intermediate_save_struc { unsigned long p; // Nombre d'ensembles par partition unsigned long n0; // Taille de la partition initiale unsigned long nbest; // Plus grande taille de partition trouvée mp_limb_t **best_partition; // Partition réalisant cet optimum char toprint; // Booléen spécifiant si cette partition doit être affichée unsigned long nbest_estimated; // Plus grande taille de partition estimée mpz_t estimated_iternum; // Nombre estimé d'itérations restant à effectuer mpz_t total_estimated_iternum; // Estimation du nombre total d'itérations size_t iremainding; // Nombre de partitions initiales restant à explorer mpz_t branch_estimated_iternum; // Nombre estimé d'itérations pour chaque branche pthread_key_t key; // Clé indiquant à chaque thread le nombre d'itération lui restant sur sa branche unsigned char tick; // Compteur modulo 8 permettant de savoir si une sauvegarde doit être faite dans le fichier temporaire schur_number_save_file_t file; // Fichier où effectuer les sauvegardes intermédiaires pthread_rwlock_t lock_s; // Verrou protégeant l'accès à la variable nbest }; typedef struct schur_number_intermediate_save_struc schur_number_intermediate_save_t; int schur_number_save_alloc(schur_number_intermediate_save_t *save, unsigned long p, unsigned long n0); void schur_number_save_dealloc(schur_number_intermediate_save_t *save); void schur_number_save_thread_register(schur_number_intermediate_save_t *save); void schur_number_save_partition_pool_register(schur_number_intermediate_save_t *save, size_t part_pool_count, unsigned long n0); void schur_number_save_newexploration_register(schur_number_intermediate_save_t *save); unsigned long schur_number_save_get_best_global(schur_number_intermediate_save_t *save); unsigned long schur_number_save_best_upgrade(schur_number_intermediate_save_t *save, unsigned long n, mp_limb_t **partition); unsigned long schur_number_save_progression_update(schur_number_intermediate_save_t *save, unsigned long n, mp_limb_t **partition); #endif /* schurNumberSaving_h */
C
#include "polinomio.h" /** * Funcao retorna um nodo do polinomio inicializado * com zero e ponteiro NULL * @return nodo */ p_nodo *getNodo(float coef, int expo) { p_nodo *nodo = (p_nodo*) malloc(sizeof(p_nodo)); nodo->coeficiente = coef; nodo->expoente = expo; nodo->proximo = NULL; return nodo; } l_polinomio *getPolinomio(){ l_polinomio *pol = (l_polinomio*) malloc(sizeof(l_polinomio)); pol->primeiro = NULL; return pol; } void inserir_nodo (l_polinomio *pol, float coef, int expo){ p_nodo *nodo = getNodo(coef, expo); p_nodo *ptr; // If the poli is empty then poli pointer to nodo if (pol->primeiro == NULL) { pol->primeiro = nodo; printf("not null"); } else { // If not add nodo in the begin of poli // we pointer the next of nodo to the old first-nodo in poli // so the old first-nodo becomes the second element of the poli // and the inserted nodo the first element (pointing the poli structure to it) ptr = busca(pol, expo); printf("ptr: %i", ptr->expoente); if ( ptr != NULL) { ptr->coeficiente = ptr->coeficiente + coef; } else { nodo->proximo = pol->primeiro; pol->primeiro = nodo;} } } p_nodo* busca (l_polinomio *pol, int expo){ p_nodo* ptr; ptr = pol->primeiro; while (ptr != NULL && ptr->expoente != expo){ ptr = ptr->proximo; } return ptr; } void imprime_polinomio (l_polinomio *pol, char n) { p_nodo *ptr; ptr = pol->primeiro; if (ptr == NULL){ printf("p(X) = "); } while (ptr != NULL) { if (ptr->coeficiente < 0){ printf("-%f*X^%i", ptr->coeficiente, ptr->expoente); } else { printf("-%f*X^%i", ptr->coeficiente, ptr->expoente); } ptr = ptr->proximo; } printf("\n\n"); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/wait.h> #include <signal.h> #include <sys/shm.h> #include <sys/sem.h> #include <sys/types.h> #include <sys/ipc.h> #include <unistd.h> #include <pthread.h> #include <msg.h> #define LEER 0 #define ESCRIBIR 1; #define ERROR -1 /** * @brief Definicion de la clave */ #define KEY 1300 /** * @brief Definicion de la clave de fichero */ #define FILEKEY "/bin/cat" /** * @brief Definicion de la clabe del semaforo */ #define SEMKEY 75798 /** * @brief Numero de semaforos a crear */ #define N_SEMAFOROS 1 typedef struct _Apuesta{ long id; /*!<Tipo de mensaje*/ /*Informacion a transmitir en el mensaje*/ char[20] nombre; int numCaballo; double cuantia; } apuesta; typedef struct _Caballo{ int id; /*!<Identificador del caballo*/ double totalapostado; /*!<Total Dinero apostado al caballo*/ double cotizacion; /*!<Cotizacion del caballo*/ } caballo; void ventanilla(void* arg); /* Hilo de las ventanillas */ void pantalla(void* args); /* Hilo del monitor */ void gestor(int numApostadores); /* Funcion que ejecuta el proceso hijo gestor de apuestas. Crea la cola de mensajes y un proceso hijo apostador ejecuta la funcion apostador */ void apostador(int msgid, int numApostadores, int numCaballos); /* Funcion que ejecuta el proceso apostador. Recibe el id de la cola de mensajes */ /* Funcion ejecutada por cada hijo caballo. Devuelve la tirada */ int caballo(int pos, int maxpos){ if(pos > maxpos || pos <= 0){ return ERROR; } if(pos == 1){ return rand()%7+1; } if(pos == maxpos){ return rand()%12+1; } return rand()%6+1; } void main(int argc, char* argv[]){ int i; int numCaballos; int longitud; int apostadores; int ventanillas; int pid; int* caballos; int estado; int* cpids; int padre[2]; int padre_status; int hijo[2]; int hijo_status; if(argc != 4){ printf("Se deben introducir cuatro parámetros enteros positivos:\nNúmero de caballos participantes (máximo 10)\n"); printf("Longitud de la carrera\n, Número de apostadores (máximo 10)\n, Número de ventanillas\n"); exit(EXIT_FAILURE); } if((numCaballos = atoi(argv[1]) <= 0 || numCaballos > 10){ printf("El primer parámetro indica el número de caballos. Debe ser un número entero positivo menor o igual a diez\n"); exit(EXIT_FAILURE); } if((longitud = atoi(argv[2]) <= 0){ printf("El segundo parámetro indica la longitud de la carrera. Debe ser un número entero positivo\n"); exit(EXIT_FAILURE); } if((apostadores = atoi(argv[3]) <= 0 || apostadores > 10){ printf("El tercer parámetro indica el número de apostadores. Debe ser un número entero positivo menor o igual a diez\n"); exit(EXIT_FAILURE); } if((ventanillas = atoi(argv[4]) <= 0){ printf("El cuarto parámetro indica el número de ventanillas. Debe ser un número entero positivo\n"); exit(EXIT_FAILURE); } padre_status = pipe(fd); if(padre_status == ERROR){ perror("Error creando la tubería\n"); exit(EXIT_FAILURE); } hijo_status = pipe(fd); if(hijo_status == ERROR){ perror("Error creando la tubería\n"); exit(EXIT_FAILURE); } cpids = (int*)malloc(sizeof(int)*numCaballos); if(!cpids){ printf("Error al reservar memoria"); exit(EXIT_FAILURE); } if((pid = fork()) == ERROR){ printf("Error al crear el monitor\n"); exit(EXIT_FAILURE); } if(pid == 0){ /*MONITOR*/ } if((pid = fork()) == ERROR){ printf("Error al crear el gestor de apuestas\n"); exit(EXIT_FAILURE); } if(pid == 0){ /*GESTOR*/ } for(i = 0; i < numCaballos; i++){ if((cpids[i] = fork()) == ERROR){ printf("Error al crear el gestor de \n"); exit(EXIT_FAILURE); } } if(cpid[i] == 0){ char[100] pos; char[100] tiro; pause(); close(padre[ESCRIBIR]); read(padre[LEER], pos, sizeof(pos)); int tirada = caballo(atoi(pos), numCaballos); close(hijo[LEER]); sprintf(tiro, "%d", tirada); write(hijo[ESCRIBIR], tiro, strlen(tiro)); } else { for(i = 0; i < numCaballos; i++){ kill(SIGUSR1, cpids[i]); } } sleep(15); } void ventanilla(void* arg); /* Hilo de las ventanillas */ void pantalla(void* args); /* Hilo del monitor */ void gestor(int numApostadores, int numCaballos){ int msqid; int ret; key_t key; pthread_t h; int i,j; int sem_id; /* ID de la lista de semáforos */ struct sembuf sem_oper; /* Para operaciones up y down sobre semáforos */ union semun { int val; struct semid_ds *semstat; unsigned short *array; } arg; caballo** caballos; apuesta amsg; apuesta[150] aps; caballos = (caballo**)malloc(numCaballos*sizeof(caballo*)); if(!caballos){ perror("Error al reservar memoria"); exit(EXIT_FAILURE); } /* Obtenemos la clave para poder crear la cola de mensajes */ key = ftok(FILEKEY, KEY); if(key == -1){ perror("Error al obtener key\n"); exit(EXIT_FAILURE); } /* Creacion de la cola de mensajes */ msqid = msgget(key, IPC_CREAT | IPC_EXCL | SHM_R | SHM_W); if(msqid == -1){ msqid = msgget(key, IPC_CREAT | SHM_R | SHM_W); if(msqid == -1){ perror("Error al crear la cola de mensajes\n"); exit(EXIT_FAILURE); } } /* Creacion de semaforos */ semid = semget(SEMKEY, N_SEMAFOROS,IPC_CREAT | IPC_EXCL | SHM_R | SHM_W); if((semid == -1) && errno == EEXIST) semid = semget(SEMKEY,N_SEMAFOROS,SHM_R|SHM_W); if(semid==-1){ perror("semget"); exit(errno); } /* Inicializamos los semáforos */ arg.array = (unsigned short *)malloc(sizeof(short)*N_SEMAFOROS); arg.array [0] = 1; semctl (semid, N_SEMAFOROS, SETALL, arg); /* Inicializamos las apuestas */ for (i=0; i < numCaballos; i++){ caballos[i] = (caballo*)malloc(sizeof(caballo)); if(!caballos[i]){ for(j=0;j<i;j++){ free(caballos[j]); } free(caballos); perror("Error al reservar memoria"); exit(EXIT_FAILURE); } caballos[i].id = i+1; caballos[i].totalapostado = 1.0; caballos[i].cotizacion = numCaballos; } /*/* Falta dinero a pagar a cada apostador para cada caballo */ /*Inicializa los threads de las ventanillas*/ for(i=0; i<numVentanillas; i++){ ret = pthread_create(&h, NULL, ventanilla, (void*) aps); if(ret){ printf("Error al crear el hilo %d\n", i+1); exit(EXIT_FAILURE); } pthread_join(h,NULL); pthread_cancel(h); } if((pid = fork()) == ERROR){ printf("Error al crear el apostador\n"); exit(EXIT_FAILURE); } if(pid > 0){ /* Gestor*/ msgrcv (msqid, (struct msgbuf *) &amsg, sizeof(apuesta) - sizeof(long), 1, 0); } else{ apostador(msqid,numApostadores,numCaballos); } } void apostador(int msgid, int numApostadores, int numCaballos){ int aleat; aleat = randint() % numApostadores+1; apuesta msg; msg. }
C
#include <stdio.h> #include <stdlib.h> #include "farey_seq.h" int main() { int n; printf("Please enter n: "); scanf("%d", &n); node * head; head = farey_seq(n); if(head == NULL) printf("The linked list is empty"); delete_list(head); } node * farey_seq(int n) { /*You code goes here*/ } void print_list(node * head, int n) { if(head == NULL) return; printf("level %d: ", n); while(head != NULL) { printf("%d/%d ", head->numerator, head->denominator); head = head->next; } printf("\n"); } void delete_list(node * head) { node * temp; while(head != NULL){ temp = head->next; free(head); head = temp; } }
C
#define TamP 100 typedef int elem; typedef struct { int topo, total; elem itens[TamP]; } Pilha; // Cria uma pilha P void Create(Pilha *); // Esvazia uma pilha P void Empty(Pilha *); //Insere o elemento X na pilha P. Retorna 0 se no houver erro, Retorna 1 se algum erro acontecer int Push(Pilha *, elem *); //Remove o elemento X da pilha P. Retorna 0 se no houver erro, Retorna 1 se algum erro acontecer int Pop(Pilha *, elem *); //Retorn a 1 se a pilha estiver vazia, 0 se a pilha tiver conteudo int IsEmpty(Pilha *P); //Retorn a 1 se a pilha estiver cheia, 0 se a pilha tiver conteudo ou vazia int IsFull(Pilha *P);
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef int /*<<< orphan*/ FILE ; /* Variables and functions */ scalar_t__ EOF ; int /*<<< orphan*/ fclose (int /*<<< orphan*/ *) ; int /*<<< orphan*/ * fopen (char const*,char*) ; scalar_t__ fputs (char*,int /*<<< orphan*/ *) ; int /*<<< orphan*/ free (char*) ; scalar_t__ getline (char**,size_t*,int /*<<< orphan*/ *) ; __attribute__((used)) static int slow_copyfile(const char *from, const char *to) { int err = 0; char *line = NULL; size_t n; FILE *from_fp = fopen(from, "r"), *to_fp; if (from_fp == NULL) goto out; to_fp = fopen(to, "w"); if (to_fp == NULL) goto out_fclose_from; while (getline(&line, &n, from_fp) > 0) if (fputs(line, to_fp) == EOF) goto out_fclose_to; err = 0; out_fclose_to: fclose(to_fp); free(line); out_fclose_from: fclose(from_fp); out: return err; }
C
#include "task2.h" int GetCellMax(DP_cell* cell) { int max = cell->substitutionScore; if (cell->deletionScore > max) max = cell->deletionScore; if (cell->insertionScore > max) max = cell->insertionScore; return max; } DP_cell* FillInCell(int row, int col, int subScore, int delScore, int insScore, DP_cell* table[]) { table[row][col].substitutionScore = subScore; table[row][col].deletionScore = delScore; table[row][col].insertionScore = insScore; table[row][col].isSet = true; return &table[row][col]; } DP_cell* CalculateCell(int row, int col, int h, int g, int match, int mismatch, DP_cell** table, char* s1, char* s2) { int minValue = INT_MIN - h - g + 1; if (row == 0 && col == 0) return FillInCell(row, col, 0, minValue, minValue, table); if (row == 0) return FillInCell(row, col, minValue, h + col * g, minValue, table); if (col == 0) return FillInCell(row, col, minValue, minValue, h + row * g, table); int subScore = GetMaxSubScore(row, col, h, g, match, mismatch, table, s1, s2); int delScore = GetMaxDeletionScore(row, col, h, g, match, mismatch, table, s1, s2); int insScore = GetMaxInsertionScore(row, col, h, g, match, mismatch, table, s1, s2); return FillInCell(row, col, subScore, delScore, insScore, table); } DP_cell* GetCalculatedCell(int row, int col, int h, int g, int match, int mismatch, DP_cell** table, char* s1, char* s2) { DP_cell* cell = &table[row][col]; if (cell == NULL) cell = CalculateCell(row, col, h, g, match, mismatch, table, s1, s2); return cell; } int GetMaxSubScore(int row, int col, int h, int g, int match, int mismatch, DP_cell** table, char* s1, char* s2) { int matchScore = mismatch; if (s1[row - 1] == s2[col - 1]) matchScore = match; DP_cell* diagCell = GetCalculatedCell(row - 1, col - 1, h, g, match, mismatch, table, s1, s2); while (!diagCell->isSet) { } return GetCellMax(diagCell) + matchScore; } int GetMaxDeletionScore(int row, int col, int h, int g, int match, int mismatch, DP_cell** table, char* s1, char* s2) { DP_cell* upCell = GetCalculatedCell(row - 1, col, h, g, match, mismatch, table, s1, s2); while (!upCell->isSet) { } int max = upCell->deletionScore + g; if (upCell->insertionScore + h + g > max) max = upCell->insertionScore + h + g; if (upCell->substitutionScore + h + g > max) max = upCell->substitutionScore + h + g; return max; } int GetMaxInsertionScore(int row, int col, int h, int g, int match, int mismatch, DP_cell** table, char* s1, char* s2) { DP_cell* leftCell = GetCalculatedCell(row, col - 1, h, g, match, mismatch, table, s1, s2); while (!leftCell->isSet) { } int max = leftCell->deletionScore + h + g; if (leftCell->insertionScore + g > max) max = leftCell->insertionScore + g; if (leftCell->substitutionScore + h + g > max) max = leftCell->substitutionScore + h + g; return max; } int GetAlignmentValue(char* s1, int s1Length, char* s2, int s2Length, int h, int g, int match, int mismatch) { DP_cell** table = (DP_cell**)malloc(sizeof(DP_cell*) * (s1Length + 1)); for (int i = 0; i < s1Length + 1; i++) table[i] = (DP_cell*)malloc(sizeof(DP_cell) * (s2Length + 1)); for (int row = 0; row <= s1Length; row++) for (int col = 0; col <= s2Length; col++) CalculateCell(row, col, h, g, match, mismatch, table, s1, s2); //PrintTable(table, s1Length + 1, s2Length + 1); int value = TraceBackGlobal(s1Length, s2Length,s1, s2, table, h); for (int i = 0; i < s1Length + 1; i++) { free(table[i]); } return value; } int GetAlignmentValueParallel(char* s1, int s1Length, char* s2, int s2Length, int h, int g, int match, int mismatch, int threads) { DP_cell** table = (DP_cell**)malloc(sizeof(DP_cell*) * (s1Length + 1)); for (int i = 0; i < s1Length + 1; i++) { table[i] = (DP_cell*)malloc(sizeof(DP_cell) * (s2Length + 1)); for (int j = 0; j < s2Length + 1; j++) { table[i][j].isSet = false; } } omp_set_num_threads(threads); #pragma omp parallel for schedule(dynamic, 1) for (int row = 0; row < s1Length+1; row++) { for (int col = 0; col <= s2Length; col++) { CalculateCell(row, col, h, g, match, mismatch, table, s1, s2); } } int value = TraceBackGlobal(s1Length, s2Length, s1, s2, table, h); for (int i = 0; i < s1Length + 1; i++) { free(table[i]); } return value; } void PrintTable(DP_cell** table, int rows, int cols) { printf("\n"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { DP_cell cell = table[i][j]; printf("(%d)-(%d)-(%d)\t", cell.insertionScore, cell.substitutionScore, cell.deletionScore); } printf("\n"); } } FullCellList* GetMaxAdjacentCells(int row, int col, enum Direction prevDirection, DP_cell** table, int h) { FullCellList* maxAdjacentSquares = init_full_cell_list(); DP_cell* cell = (DP_cell *)malloc(sizeof(DP_cell)); cell->deletionScore = table[row][col].deletionScore; cell->insertionScore = table[row][col].insertionScore; cell->substitutionScore = table[row][col].substitutionScore; cell->isSet = table[row][col].isSet; if (prevDirection == left) { cell->deletionScore += h; cell->substitutionScore += h; } if (prevDirection == up) { cell->insertionScore += h; cell->substitutionScore += h; } int max = GetCellMax(cell); if (row == 0 && col == 0) return init_full_cell_list(); if (row == 0) { DP_CellFull* cell = malloc(sizeof(DP_CellFull)); cell->cell = &table[row][col - 1]; cell->col = col - 1; cell->row = row; cell->max = GetCellMax(cell->cell); insert_cell(maxAdjacentSquares, cell); return maxAdjacentSquares; } if (col == 0) { DP_CellFull* cell = malloc(sizeof(DP_CellFull)); cell->cell = &table[row - 1][col]; cell->col = col; cell->row = row - 1; cell->max = GetCellMax(cell->cell); insert_cell(maxAdjacentSquares, cell); return maxAdjacentSquares; } if (cell->deletionScore == max) { DP_CellFull* cell = malloc(sizeof(DP_CellFull)); cell->cell = &table[row - 1][col]; cell->col = col; cell->row = row - 1; cell->max = GetCellMax(cell->cell); insert_cell(maxAdjacentSquares, cell); } if (cell->insertionScore == max) { DP_CellFull* cell = malloc(sizeof(DP_CellFull)); cell->cell = &table[row][col - 1]; cell->col = col - 1; cell->row = row; cell->max = GetCellMax(cell->cell); insert_cell(maxAdjacentSquares, cell); } if (cell->substitutionScore == max) { DP_CellFull* cell = malloc(sizeof(DP_CellFull)); cell->cell = &table[row - 1][col - 1]; cell->col = col - 1; cell->row = row - 1; cell->max = GetCellMax(cell->cell); insert_cell(maxAdjacentSquares, cell); } return maxAdjacentSquares; } int TraceBackGlobal(int row, int col, char* s1, char* s2, DP_cell** table, int h) { if (row <= 0 || col <= 0) return 0; DP_CellFull* mainMaxCell = malloc(sizeof(DP_CellFull)); mainMaxCell->max = INT_MIN; int maxCellSubs = 0; enum Direction prevDirection = diag; do { const DP_CellFull* maxCell = GetMaxAdjacentCells(row, col, prevDirection, table, h)->pHead; if (maxCell->max > mainMaxCell->max) { mainMaxCell = maxCell; maxCellSubs = 0; } if (maxCell->row < row && maxCell->col < col) { prevDirection = diag; if (s1[row - 1] == s2[col - 1]) maxCellSubs++; } else if (maxCell->row < row) { prevDirection = up; } else { prevDirection = left; } row = maxCell->row; col = maxCell->col; } while (row > 0 || col > 0); return maxCellSubs; }
C
a#include<stdio.h> #include<stdlib.h> #define size 30 typedef struct stack { int top; int a[size]; }STACK; int push(STACK*,int); int pop(STACK*); int peek(STACK); int empty(STACK); int preceed(char); int main() { STACK s; s.top=-1; int i,j=0; char str[20],post[20],c; printf("enter the infix exprssion to get the post fix expression\n"); scanf("%s",str); for(i=0;str[i];i++) { if(str[i]>='a'&&str[i]<='z') post[j++]=str[i]; else if(empty(s)||str[i]=='('||str[i]=='^'||preceed((char)str[i])>preceed((char)s.a[s.top])) push(&s,str[i]); else { if(str[i]==')') { while((c=pop(&s))!='(') post[j++]=c; } if(preceed((char)str[i])<=preceed((char)s.a[s.top])) { post[j++]=pop(&s); push(&s,str[i]); } } } while(!empty(s)) { post[j++]=pop(&s); } post[j]='\0'; printf("the post fix expression is %s\n",post); } int push(STACK*p,int v) { if(p->top==size-1) return 0; else { p->a[++p->top]=v; return 1; } } int pop(STACK*p) { if(p->top==-1) return 0; else return p->a[p->top--]; } int peek(STACK p) { if(p.top==-1) return 0; else return p.a[p.top]; } int empty(STACK p) { return (p.top==-1); } int preceed(char ch) { switch(ch) { case '^': case '&': return 4; case '*': case '/': case '%': return 3; case '+': case '-': return 2; default: return 1; } }
C
#include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <sys/types.h> #include <sys/wait.h> #define CHAR_LENGTH 256 typedef struct { char parent[CHAR_LENGTH]; char name[CHAR_LENGTH]; int priority; int memory; }proc; typedef struct node{ proc * process; struct node * left; struct node * right; } node_t; void insert(node_t * tree, proc * process) { if(tree->process == NULL){ tree->process = process; }else if(strcmp(process->parent,tree->process->name) == 0){ if(tree->left == NULL){ tree->left = malloc(sizeof(node_t)); tree->left->process = process; } else if(tree->right == NULL){ tree->right = malloc(sizeof(node_t)); tree->right->process = process; } else { fprintf(stderr, "Unable to add process to tree: Parent process already has 2 children."); } } else { if(tree->left != NULL){ insert(tree->left, process); } if(tree->right != NULL){ insert(tree->right, process); } } } void print_tree(node_t * tree){ if(tree != NULL){ printf("%s ", tree->process->name); if(tree->left != NULL){ printf("L:%s ", tree->left->process->name); } if(tree->right != NULL){ printf("R:%s", tree->right->process->name); } printf("\n"); if(tree->left != NULL){ print_tree(tree->left); } if(tree->right != NULL){ print_tree(tree->right); } } } int main(void) { node_t * process_tree = malloc(sizeof(node_t)); char filename[] = "processes_tree.txt"; FILE *in_file = fopen(filename, "r"); if(in_file == NULL){ fprintf(stderr, "Unable to open file '%s'.\n", filename); return 1; } char buffer[CHAR_LENGTH]; char token[] = ", "; while(fgets(buffer, CHAR_LENGTH, in_file) != NULL) { char *parent = strtok(buffer, token); char *name = strtok(NULL, token); char *priority = strtok(NULL, token); char *memory = strtok(NULL, "\n"); proc *new_process = malloc(sizeof(proc)); strcpy(new_process->parent, parent); strcpy(new_process->name, name); new_process->priority = atoi(priority); new_process->memory = atoi(memory); insert(process_tree, new_process); } fclose(in_file); print_tree(process_tree); free(process_tree); }
C
/* * GccApplication2.c * * Created: 4/20/2016 6:25:00 PM * Author : Andrew Kim Josh Alpert */ #include "avr.h" #include "lcd.h" #define DDR DDRB #define PORT PORTB #define RS_PIN 0 #define RW_PIN 1 #define EN_PIN 2 #define XTAL_FRQ 8000000lu #define SET_BIT(p,i) ((p) |= (1 << (i))) #define CLR_BIT(p,i) ((p) &= ~(1 << (i))) #define GET_BIT(p,i) ((p) & (1 << (i))) #define WDR() asm volatile("wdr"::) #define NOP() asm volatile("nop"::) #define RST() for(;;); void ini_lcd(void); void clr_lcd(void); void pos_lcd(unsigned char r, unsigned char c); void put_lcd(char c); void puts_lcd1(const char *s); void puts_lcd2(const char *s); void ini_avr(void); void wait_avr(unsigned short msec); void ini_avr(void) { WDTCR = 15; } void wait_avr(unsigned short msec) { TCCR0 = 3; while (msec--) { TCNT0 = (unsigned char)(256 - (XTAL_FRQ / 64) * 0.001); SET_BIT(TIFR, TOV0); WDR(); while (!GET_BIT(TIFR, TOV0)); } TCCR0 = 0; } static inline void set_data(unsigned char x) { PORTD = x; DDRD = 0xff; } static inline unsigned char get_data(void) { DDRD = 0x00; return PIND; } static inline void sleep_700ns(void) { NOP(); NOP(); NOP(); } static unsigned char top(unsigned char rs) { unsigned char d; if (rs) SET_BIT(PORT, RS_PIN); else CLR_BIT(PORT, RS_PIN); SET_BIT(PORT, RW_PIN); get_data(); SET_BIT(PORT, EN_PIN); sleep_700ns(); d = get_data(); CLR_BIT(PORT, EN_PIN); return d; } static void output(unsigned char d, unsigned char rs) { if (rs) SET_BIT(PORT, RS_PIN); else CLR_BIT(PORT, RS_PIN); CLR_BIT(PORT, RW_PIN); set_data(d); SET_BIT(PORT, EN_PIN); sleep_700ns(); CLR_BIT(PORT, EN_PIN); } static void write(unsigned char c, unsigned char rs) { while (top(0) & 0x80); output(c, rs); } void ini_lcd(void) { SET_BIT(DDR, RS_PIN); SET_BIT(DDR, RW_PIN); SET_BIT(DDR, EN_PIN); wait_avr(16); output(0x30, 0); wait_avr(5); output(0x30, 0); wait_avr(1); write(0x3c, 0); write(0x0c, 0); write(0x06, 0); write(0x01, 0); } void clr_lcd(void) { write(0x01, 0); } void pos_lcd(unsigned char r, unsigned char c) { unsigned char n = r * 40 + c; write(0x02, 0); while (n--) { write(0x14, 0); } } void put_lcd(char c) { write(c, 1); } void puts_lcd1(const char *s) { char c; while ((c = pgm_read_byte(s++)) != 0) { write(c, 1); } } void puts_lcd2(const char *s) { char c; while ((c = *(s++)) != 0) { write(c, 1); } } void inc_time() { //assert(!"The method or operation is not implemented."); } //returns how many days in the month unsigned short convert_num(unsigned short str[], int sizeOfArray){ unsigned short k = sizeOfArray; unsigned short expo = 0; unsigned short num = 0; unsigned short temp = 0; for(unsigned short i = 0; i < sizeOfArray; i++, k--){ for(unsigned short j = 0; j < k; j++){ if(expo != 0) expo = (expo * (10)); else expo = 1; } temp = str[i]; num += (expo * (temp - 48)); expo = 0; } return num; } void check_date(unsigned short month, unsigned short year, unsigned short* dd) { unsigned short **days= &dd; if(month <= 7){ if(month == 2){ (*days)[0] = 50; //leap year if((year%4) == 0){ (*days)[1] = 57; }else{ (*days)[1] = 56; } }else if((month%2) == 0){ (*days)[0] = 51; (*days)[1] = 48; }else{ (*days)[0] = 51; (*days)[1] = 49; } }else{ if((month%2) == 0){ (*days)[0] = 51; (*days)[1] = 49; }else{ (*days)[0] = 51; (*days)[1] = 48; } } } unsigned char sizeOf(char* string){ unsigned char count = 0; for(; string[count++] != '\0';){} return --count; } int pressed(unsigned char r, unsigned char c){ DDRC = 0x00; PORTC = 0xFF; SET_BIT(DDRC, r); CLR_BIT(PORTC, r); wait_avr(1); if(GET_BIT(PINC, c + 4)) return 0; return 1; } int somethingPressed() { unsigned char r,c; //Jaysus says nuffin pressed for(r = 0; r < 4; ++r){ for(c = 0; c < 4; ++c){ if(pressed(r,c)){ return 1; } } } return 0; } unsigned char get_key(){ unsigned char r; unsigned char c; // If A to D pressed for(r = 0; r < 4; ++r){ if(pressed(r,3)) { return 65+r; } } // 1 to 9 Pressed for(r = 0; r < 3; ++r){ for(c = 0; c < 3; ++c){ if(pressed(r,c)){ return ((r*3)+c+1)+48; } } } //If zero pressed if(pressed(3,1)){ return '0'; } // If * pressed else if(pressed(3,0)){ return 42; } // If # pressed else if(pressed(3,2)){ return 35; } return '~'; } int main() { ini_lcd(); unsigned char top[] = "11:59:40 PM "; unsigned char bot[] = "09/30/2016 "; unsigned short mm[2] = {48,57}; unsigned short dd[2] = {51,48}; unsigned short yy[4] = {50,48,49,54}; puts_lcd2(top); pos_lcd(1,0); puts_lcd2(bot); unsigned short hr[2] = {49,49}; unsigned short min[2] = {53,57}; unsigned short sec[2] = {52,48}; unsigned char *place=bot; char i=0; while(1){ unsigned char key=get_key(); if(key =='~') { if(sec[1] != '9'){ sec[1]++; top[7] = sec[1]; }else if((sec[0] != '5')&&(sec[1] == '9')){ sec[0]++; sec[1] = '0'; top[6] = sec[0]; top[7] = sec[1]; }else if((sec[0] == '5')&&(sec[1] == '9')&&(min[1] != '9')){ sec[0] = '0'; sec[1] = '0'; min[1]++; top[4] = min[1]; top[6] = '0'; top[7] = '0'; }else if((min[0] != '5') && (min[1] == '9')){ sec[0] = '0'; sec[1] = '0'; min[0]++; min[1] = '0'; top[3] = min[0]; top[4] = '0'; top[6] = '0'; top[7] = '0'; }else if((min[0] == '5')&&(min[1] == '9')&&(hr[0] != '1')){ sec[0] = '0'; sec[1] = '0'; min[0] = '0'; min[1] = '1'; if(hr[1] == '9') hr[0] = '1'; else hr[1]++; top[1] = hr[1]; top[3] = '0'; top[4] = '0'; top[6] = '0'; top[7] = '0'; }else if ((hr[0] == '1') && (hr[1] != '2')){ if(hr[1]=='1') { //TODO: Make sure to add functionality to inc days in date if(top[9]=='A') { top[9]='P'; } else { inc_time(); top[9]='A'; unsigned short temp[2] = {48,49}; check_date(convert_num(mm,2), convert_num(yy,4), temp); if(convert_num(dd, 2) == convert_num(temp,2)){ //(convert_num(dd, 2) == 31){ //last day of the month if((mm[0] == '1')&&(mm[1] == '2')){ //last day of the year if(yy[3] != '9') yy[3]++; else if(yy[2] != '9'){ yy[2]++; yy[3] = '0'; }else if(yy[1] != '9'){ yy[1]++; yy[2] = '0'; yy[3] = '0'; }else{ yy[0]++; yy[1] = '0'; yy[2] = '0'; yy[3] = '0'; } mm[0] = '0'; mm[1] = '1'; dd[0] = '0'; dd[1] = '1'; }else{ if((mm[0] != '1')&&(mm[1] != '9')) mm[1]++; else if((mm[0] == '1')&&(mm[1] != '2')) mm[1]++; else if(mm[1] == '9'){ mm[0] ='1'; mm[1] ='0'; }else{ mm[0] = '0'; mm[1] = '1'; } dd[0] = '0'; dd[1] = '1'; } }else{ if(dd[1] != '9') dd[1]++; else{ dd[0]++; dd[1] = '0'; } } } } sec[0] = '0'; sec[1] = '0'; min[0] = '0'; min[1] = '0'; hr[1]++; top[1] = hr[1]; top[3] = '0'; top[4] = '0'; top[6] = '0'; top[7] = '0'; }else{ sec[0] = '0'; sec[1] = '0'; min[0] = '0'; min[1] = '0'; hr[0] = '0'; hr[1] = '1'; top[0] = hr[0]; top[1] = '1'; top[3] = '0'; top[4] = '0'; top[6] = '0'; top[7] = '0'; } wait_avr(1000); clr_lcd(); puts_lcd2(top); pos_lcd(1,0); bot[0] = mm[0]; bot[1] = mm[1]; bot[3] = dd[0]; bot[4] = dd[1]; bot[6] = yy[0]; bot[7] = yy[1]; bot[8] = yy[2]; bot[9] = yy[3]; puts_lcd2(bot); }else { unsigned char change_time = 0; unsigned char change_date = 0; unsigned char new_text[16] = " : : 14A 24P"; unsigned char new_date[16] = " / / "; *place = new_text; while(1){ key = get_key(); if(key !='~') { if(key == '*'){ change_time = 1; change_date = 0; } if(change_time == 1){ if(key != '*'){ new_text[i] = key; if(i < 2){ hr[i] = new_text[i]; top[i] = hr[i]; if(i == 1){ if((convert_num(hr,2) > 12)||(convert_num(hr,2) == 0)) i = -1; } } else if(i < 5){ min[i-3] = new_text[i]; top[i] = min[i-3]; if(i == 4){ if(convert_num(min,2) > 59) i = 2; } } else if(i < 8){ sec[i-6] = new_text[i]; top[i] = sec[i-6]; if(i == 7){ if(convert_num(sec,2) > 59) i = 5; } }else if(i == 9){ if(key == '1'){ top[9] = 'A'; }else if(key == '2'){ top[9] = 'P'; }else{ //need to reinput --i; } } ++i; if((i == 2) ||(i == 5)){ top[i] = ':'; ++i; } if(i==8){ top[i] = ' '; ++i; } if(i ==10){ top[i] = 'M'; ++i; } new_text[i] = '_'; } clr_lcd(); pos_lcd(0,0); puts_lcd2(top); pos_lcd(1,0); puts_lcd2(new_text); if(i >= 10){ i = 0; change_time = 0; break; } while(somethingPressed()==1){} } if(key == '#'){ change_date = 1; change_time = 0; } if(change_date == 1){ if(key != '#'){ new_date[i] = key; if(i < 2){ mm[i] = new_date[i]; bot[i] = mm[i]; if(i == 1){ if((convert_num(mm,2) > 12) || (convert_num(mm,2) == 0)) i = -1; } } else if(i < 5){ dd[i-3] = key; bot[i] = dd[i-3]; if(convert_num(dd,2) == 0) i = 2; } else if(i < 10){ yy[i-6] = key; bot[i] = yy[i-6]; unsigned short temp2[2] = {48,49}; check_date(convert_num(mm,2), convert_num(yy,4), temp2); if(i == 9){ if(convert_num(dd, 2) > convert_num(temp2,2)) i = 2; } } ++i; if((i == 2) ||(i == 5)){ bot[i] = '/'; ++i; } } clr_lcd(); pos_lcd(0,0); puts_lcd2(new_date); pos_lcd(1,0); puts_lcd2(bot); if(i == 10){ i = 0; change_date = 0; puts_lcd2(bot); break; } while(somethingPressed()==1){} } else if((change_date == 0)&&(change_time == 0)) break; key='~'; } } } } return 0; }
C
#include <stdio.h> #include <ctype.h> int main() { char caractere; while (1) { scanf("%c", &caractere); if (caractere == '@') { break; } else if (!isalpha(caractere)) { continue; } else { printf("%c ", caractere ^ 32); } } return 0; }
C
#include "log_space.h" double get_p(log_space ls) { if ( isfinite(ls) ) return exp(ls); else return 0; } log_space get_ls(double p) { if (p == 0) return -INFINITY; else return log(p); } // x*y log_space ls_multiply(log_space x, log_space y) { return (log_space)(x + y); } // x/y log_space ls_divide(log_space x, log_space y) { return (log_space)(x - y); } // x + y log_space ls_add(log_space x, log_space y) { if (isinf(x)) return y; if (isinf(y)) return x; if (x == 0 || y == 0) return 0; log_space tmp; if (x < y) { tmp = y; y = x; x = y; } return x + log(1 + exp(y - x)); }
C
/* *Kory Bartlett *Atkinson 10:30 *Project 1: Counting the Number of Words *Thursday 2:15 *3 April 2014 * * *Program to read words from a text file and count the number of words in the text file */ #include<stdio.h> #include<stdlib.h> #define MAX_WORD_LENGTH 30 int main( int argc, char*argv[])//recieves arguements from comand line { FILE *fp; int word_counter = 0; char buffer [MAX_WORD_LENGTH]; if( argc != 2)//checks to make sure that comand line passes two arguements { printf("Insuffiecient number of arguments used\n"); return 0; } fp = fopen(argv[1],"r");//opens the text file in the argv[1] slot and sets it to be read if(fp == NULL)//checks text file to make sure it has content { printf("File could not be opened\n"); return 0; } while(fscanf(fp,"%s", buffer)!=EOF)//reads a string from text file into buffer. the function runs until it reaches the end of the file { word_counter++; } printf("%d total words\n", word_counter); fclose(fp); return 1; }
C
#include <stdio.h> #include <stdlib.h> int thirdBits(void) { int a = 0x49; int b = (a << 9); int c = b + a; return (c << 18) + c; // Steps 4 and 5 } int isTmin(int x) { return !(x+x)&!!(x); } int isNotEqual(int x, int y) { return(!!(x ^ y)); } int anyOddBit(int x) { return !!((x | (x >> 8) | (x >> 16) | (x >> 24)) & 0xaa); } int negate(int x) { return ~x + 1; } int conditional(int x, int y, int z) { /* *if x!=0,mask=0x00000000,so y&~mask==y and z&mask==0 *if x==0,mask=0xffffffff,so y&~mask = y&0 =0; z&mask=z */ int mask= ~!x+1; return (y & ~mask)|(z & mask); } int subOK(int x, int y) { int res = ~y + 1 + x; int sameSign = (x ^ y) >> 31; int resSign = (res ^ x) >> 31; return !(sameSign & resSign); } int isGreater(int x, int y) { int sign_x = x >> 31; int sign_y = y >> 31; int sameSign = !(sign_x ^ sign_y); int diffSign = !sameSign; int resSign = (~y + x) >> 31; return (sameSign & !resSign) | (diffSign & !sign_x); } int main(int argc, char const *argv[]) { int a = isGreater(-3, 4); int b = isGreater(-5, -3); int c = isGreater(5, -5); printf("%d%d%d", a, b, c); return 0; }
C
#include <pthread_extra.h> #include <time.h> #include <stdio.h> #include <stdbool.h> /* //This is first prototype for two mutexes only, it is useful in order to understand how this all works //Currently it was replaced by macro with the same name int pthread_mutex_timedlock_two(pthread_mutex_t *a, pthread_mutex_t *b, const struct timespec *restrict abs_timeout) { int ret; while(1) { //Wait for the first mutex ret = (abs_timeout==NULL ? pthread_mutex_lock(a) : pthread_mutex_timedlock(a, abs_timeout)); if(ret) return ret; //Something is fishy about this mutex. Abort! //Try to lock the second mutex ret = pthread_mutex_trylock(b); if(!ret) return ret; //Locked BOTH Hooray! //Unlock first if second failed to prevent deadlocks pthread_mutex_unlock(a); //Swap mutexes, so we will try to block on the second mutex next time: pthread_mutex_swap(a, b); //printf("Retry!\n"); } } */ int pthread_mutex_timedlock_multi_generic(pthread_mutex_t **lck, int cnt, bool block, const struct timespec *restrict abs_timeout) { int ret, locked; while(1) { //Try to lock all mutexes for(int i = 0; i<cnt; i++) { //Block only on the first one if(block && i==0) { ret = (abs_timeout==NULL ? pthread_mutex_lock(lck[i]) : pthread_mutex_timedlock(lck[i], abs_timeout)); if(ret) return ret; //Something went wrong continue; } //Then try if we can lock the rest ret = pthread_mutex_trylock(lck[i]); if(ret) { //Cannot lock this one locked = i; printf("Cannot lock #%d!\n", i); break; } locked = i; } //Check if we managed to lock all locks if(locked == cnt) return 0; //Unlock all mutexes that we managed to lock so far for(int i = 0;i<locked;i++) { printf("Unlocking #%d\n", i); pthread_mutex_unlock(lck[i]); } if(!block) return ret; //We do not want to block, just trying //Try to block on locked mutex in next round pthread_mutex_swap(lck[0],lck[locked]); } }
C
#include <stdio.h> #include <math.h> struct points { int x; int y; } two; float dist(struct points two){ return (sqrt(pow(two.x, 2) + pow(two.y, 2))); }; int main() { printf("Enter 1st coordinate points : "); scanf("%d %d", &two.x,&two.y); printf("\nThe distance between the points and origin is: %.2f units.",dist(two)); }
C
#include "Node.h" #define End -1 //处理输入文件中结尾 enum //默认构造整型变量 failed=0,success=1,startPoint=2 { failed, success }; /* @param all:保存所有节点的数组 start:为引用,入口节点id @function 初始化迷宫,并把出口信息标记在出口节点上 */ void initialMaze(vector<Node *> &all, int &start); /* @param cur:开始dfs的节点 all:保存所有节点的数组 @return 若找到出口返回success,否则返回failed @function 深度优先搜索,若找到出口则立即返回,通过对返回值的判断使递归立即停止;对搜索过的节点标记,防止再次搜索 */ bool dfs(Node *cur, vector<Node *> &all); /* @param start:开始dfs的节点 all:保存所有节点的数组 @function 广度优先搜索,利用队列特性,在这种情况下第一个找到的出口一定是最近的出口,并且路径长度也是从入口到这个出口中最近的(解决补充的两个问题);对搜索过的节点标记,防止再次搜索 */ void bfs(Node *start, vector<Node *> &all); /* @param end:出口 all:保存所有节点的数组 @function 从出口开始逆向输出路径,并统计长度 */ void CountNShowPath(Node *end, vector<Node *> &all);
C
#include <stdio.h> typedef unsigned int uint; struct list{ uint p; struct list * next; } struct lh{ struct list * next; } void list_add(struct lh *lh, struct list * list){ struct **nl; nl = &((*lh)->next); while(!(*nl)){ if((*nl)->p >= list->p) break; nl = &((*nl)->next); } list -> next = *nl; *nl = list; } struct list* init_list(uint p){struct list* list = malloc(sizeof(struct list)); list->p = p; list->next = NULL; return list;} struct lh lh; int main(void){ int n, l; scanf("%d %d", &n, &l); lh.next = NULL; for(int i = 0; i < n; i++){ uint p; scanf("%u", &p); list_add(init_list(p)); } return 0; }
C
#include <stdio.h> #define MAXS 200 #define DIMFN 80 int main(int argc, char* argv[]){ char fn[DIMFN+1]; char c; FILE* fp; int i, maxN, minN, n, cRighe, cFrasi; scanf("%s", fn); fp = fopen(fn, "r"); if(fp){ maxN = n = cRighe = cFrasi = 0; minN = DIMFN; fscanf(fp, "%c", &c); while(!feof(fp)){ if(c == '.'){ cFrasi++; if(n > maxN) maxN = n; else if(n < minN) minN = n; n = 0; } else if(c == '\n'){ cRighe++; } else if(c != ' '){ n++; } fscanf(fp, "%c", &c); } printf("Max: %d\nMin: %d\nRighe: %d\nFrasi: %d\n", maxN, minN, cRighe, cFrasi); fclose(fp); }else{ printf("Errore nell'apertura del file\n"); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_makestr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rcaraway <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/28 17:22:59 by rcaraway #+# #+# */ /* Updated: 2020/11/30 16:06:00 by rcaraway ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include "ft_printf.h" char *getpointer(void *s) { uintptr_t tmp; char *s1; tmp = (uintptr_t)s; s1 = ft_itoap(tmp, 0); return (s1); } int makearg2(char c, va_list **lst, t_arg **arg) { if (c == 'd' || c == 'i') { if (!((*arg)->arg = ft_itoa(va_arg(**lst, int)))) { free(*arg); return (0); } } else if (c == 'u') { if (!((*arg)->arg = ft_itoau(va_arg(**lst, unsigned int)))) { free(*arg); return (0); } } return (makearg3(c, lst, arg)); } int makearg(char c, va_list **lst, t_arg **arg) { if (c == 'c') { if (!((*arg)->arg = malloc(2))) { free(*arg); return (0); } (*arg)->ffree = 1; (*arg)->arg[0] = va_arg(**lst, int); if ((*arg)->arg[0] == 0) (*arg)->fnul = 1; (*arg)->arg[1] = '\0'; (*arg)->fstr = 1; } else if (c == 'p') if (!((*arg)->arg = getpointer(va_arg(**lst, void *)))) { free(*arg); return (0); } return (makearg2(c, lst, arg)); } int printargstr(t_arg *arg) { int i; int j; i = 0; j = 0; if (arg->arg == 0) arg->arg = "(null)"; arg->minpos = arg->minpos == -2 ? ft_strlen(arg->arg) : arg->minpos; if (arg->fpos == 0) j += printargstr2(arg, i, j); else { while (((arg->arg[i] && i < arg->minpos) || arg->fnul) && ++j) { if (arg->arg[i] == 0 && arg->fnul) arg->fnul = 0; write(1, &(arg->arg[i++]), 1); } while (i++ < arg->pos && ++j) write(1, " ", 1); } if (arg->ffree) free(arg->arg); free(arg); return (j); }
C
/* Programa que concatena duas listas, a partir da lista l1. */ #include <stdio.h> #include <stdlib.h> typedef struct lista { int info; struct lista *prox; } TLSE; void imprimeLista(TLSE *l); TLSE* inicializa(void); TLSE* insereInicio(TLSE *l, int x); //Concatena L2 com L1. TLSE* junta_listas(TLSE *l1, TLSE *l2){ TLSE *p = l1; //Encontra o final de l1. while(p->prox) p = p->prox; p->prox = l2; return l1; } int main(void){ TLSE *l1 = inicializa(); TLSE *l2 = inicializa(); l1 = insereInicio(l1, 3); l1 = insereInicio(l1, 6); l2 = insereInicio(l2, 4); l2 = insereInicio(l2, 2); l1 = junta_listas(l1, l2); imprimeLista(l1); return 0; } //Inicializa uma lista vazia. TLSE* inicializa(void){ return NULL; } //Insere um elemento no início da lista. TLSE* insereInicio(TLSE *l, int x){ TLSE *novo = (TLSE *) malloc(sizeof(TLSE)); novo->info = x; novo->prox = l; return novo; } //Imprime a lista. void imprimeLista(TLSE *l){ if(!l) return; TLSE *p = l; while(p){ printf("%d\n", p->info); p = p->prox; } }