language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <linux/module.h> #include <linux/kernel.h> #include <linux/semaphore.h> #include <linux/fs.h> #include <linux/cdev.h> #include <asm/uaccess.h> #include <linux/sched.h> /* Taylor Okel Operating Systems Fall 2015 Lab 6 Credit: Prof Franco - Lab 6 description Kevin Farley - general ideas and direction, run and stop scripts */ MODULE_LICENSE("GPL"); #define FNAME "interface" //From lab6 assistance: struct cdev *kernel_cdev; dev_t dev_no; static int Major; wait_queue_head_t queue; // Suggested from K. Farley static int written, read; //written - sizeof area containing data //read - printing // struct rw_semaphore { // long count; // raw_spinlock_t wait_lock; // struct list_head wait_list; // } struct device { int array[100]; struct rw_semaphore rw_sema; } Device; //semaphore /********************************************************/ // void init_rwsem(struct rw_semaphore); //Init semaphore // // void down_read(struct rw_semaphore *sem); //Hold semahore for reading, sleep if not available // // void up_read(struct rw_semaphore *sem); // Release semaphore for reading // // void down_write(struct rw_semaphore *sem); //Hold semaphore for writing, sleep if not available // // void down_write_trylock(struct rw_semaphore *sem); // Hold semaphore for writing, error if not available // // void up_write(struct rw_semaphore *sem;) // Release semaphore for writing /********************************************************/ //Device interface /********************************************************/ ssize_t Read(struct file *filp, char *buff, size_t count, loff_t *offp){ unsigned long ret; printk("[lab6|read] Buffer (start) = %s\n", buff); down_read(&Device.rw_sema); printk("[lab6|read] Grabbed semaphore\n"); wait_event_timeout(queue, 0,20*HZ); // Chill in critical section printk("[lab6|read] Ding! Timer's up.\n"); ret = copy_to_user(buff, Device.array, count); printk("[lab6|read] Read successfully\n"); printk("[lab6|read] Read = %d, Written = %d, Count = %d\n", read, written, count); up_read(&Device.rw_sema); printk("[lab6|read] Released semaphore\n"); return count; } ssize_t write(struct file *filp, const char *buff, size_t count, loff_t *offp){ unsigned long ret; printk(KERN_INFO "[lab6|write] Begin Write\n"); down_write(&Device.rw_sema); printk("[lab6|write] Grabbed semaphore\n"); wait_event_timeout(queue, 0, 15*HZ); // Chill in critical section printk("[lab6|write] Ding! Timer's up.\n"); count = (count > 99) ? 99:count; ret = copy_from_user(Device.array, buff, count); written += count; printk("[lab6|write] Wrote successfully: %s\n", buff); printk("[lab6|write] Read = %d, Written = %d, Count = %d\n", read, written, (int)count); up_write(&Device.rw_sema); printk("[lab6|write] Released semaphore\n"); return count; } int open(struct inode *inode, struct file *filp){ printk(KERN_INFO "[lab6|open] Read = %d, Written = %d\n", read, written); read = written; return 0; } int release(struct inode *inode, struct file *filp) { //Deallocation happens in rmmod printk(KERN_INFO "[lab6|release] Read=%d, Written=%d\n", read, written); return 0; } // Now attach the operations: struct file_operations fops = { .owner = THIS_MODULE, .read = Read, .write = write, .open = open, .release = release }; /********************************************************/ int init_module(void) { printk(KERN_EMERG "[lab6] Loading module...\n"); int ret; kernel_cdev = cdev_alloc(); kernel_cdev->ops = &fops; kernel_cdev->owner = THIS_MODULE; ret = alloc_chrdev_region(&dev_no, 0,1, FNAME); if (ret < 0) { printk(KERN_EMERG "[lab6] Major number allocation has failed\n"); return ret; } Major = MAJOR(dev_no); printk(KERN_EMERG "[lab6] Major number: %d, %d\nRet: %d", dev_no, Major, ret); if(MKDEV(Major, 0) != dev_no) printk(KERN_INFO "An error occured.\n"); ret = cdev_add(kernel_cdev, dev_no, 1); if (ret < 0) { printk(KERN_INFO "unable to allocate cdev\n"); return ret; } init_rwsem(&Device.rw_sema); init_waitqueue_head(&queue); return 0; } void cleanup_module(void){ printk(KERN_EMERG"[lab6] in cleanup\n"); cdev_del(kernel_cdev); unregister_chrdev_region(dev_no, 1); unregister_chrdev(Major, FNAME); printk(KERN_EMERG "[lab6] Module unloaded.\n"); }
C
#include <stdio.h> #include <stdlib.h> #include "circular_list.h" main() { LIST_PTR list; elem temp; CL_init(&list); CL_insert_start(&list, 1); CL_print(list); printf("\n"); CL_insert_start(&list, 2); CL_print(list); printf("\n"); CL_insert_after(list->next, 3); CL_print(list); printf("\n"); CL_insert_after(list, 4); CL_print(list); printf("\n"); CL_delete_start(&list, &temp); CL_print(list); printf("\n"); CL_delete_after(list->next, &temp); CL_print(list); printf("\n"); CL_delete_start(&list, &temp); CL_print(list); printf("\n"); CL_delete_start(&list, &temp); CL_print(list); printf("\n"); CL_destroy(&list); }
C
/* this file contains basic singly linked list operations. create = creates a linked list with user inputs. stops when -999 is given as input insertAfter = inserts a number after a particular node in the list insertBefore = inserts a number before a particular node in the list delete = deletes a node printList = prints the list middleNode = returns the middle node in a list containing odd number of nodes */ //many of the functions here use recursion #include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }; typedef struct node list; void create(list **q); void insertAfter(list **q,int a, int b); void insertBefore(list **q, int a, int b); void delete(list **q,int a); void printList(list *q); int middleNode(list *q); int main() { int a,b; list *head,*p; head=malloc(sizeof(list)); p=head; create(&p); printList(head); printf("enter after which no, to add and what to add:\n"); scanf("%d %d",&a,&b); insertAfter(&head,a,b); printList(head); printf("enter before which no, to add and what to add:\n"); scanf("%d %d",&a,&b); insertBefore(&head,a,b); printList(head); printf("enter no to delete"); scanf("%d",&a); delete(&head,a); printList(head); b=middleNode(head); printf("middle node is: %d\n",b); return 0; } //creates a list. takes the pointer to the list pointer void create(list **p) { int temp; scanf("%d",&temp); if(temp==-999) { (*p)=NULL; } else { (*p)->data=temp; (*p)->next=malloc(sizeof(list)); create(&((*p)->next)); } return; } //inserts after a particulare node. //the parameters are pointer to the list pointer, new number and the node after which it //to insert the new data void insertAfter(list **p, int a, int b) { list *temp; if((*p)==NULL) { printf("number not found\n"); return; } if((*p)->data==a) { temp=(*p)->next; (*p)->next=malloc(sizeof(list)); (*p)->next->data=b; (*p)->next->next=temp; return; } else { insertAfter(&((*p)->next),a,b); } return; } //inserts before a particulare node. //the parameters are pointer to the list pointer, new number and the node before which it //to insert the new data void insertBefore(list **p,int a,int b) { list *temp; if((*p)==NULL) { printf("number not found\n"); return; } if((*p)->data==a) { temp=(*p); (*p)=malloc(sizeof(list)); (*p)->data=b; (*p)->next=temp; return; } else { insertBefore(&((*p)->next),a,b); } return; } //deletes a particular node. void delete(list **p, int a) { list *temp; if((*p)->data==a) { temp=(*p)->next; free(*p); (*p)=temp; return; } else { delete(&((*p)->next),a); } return; } //prints the list from the pointer passed. void printList(list *p) { while(p!=NULL) { printf("%d ",p->data ); p=p->next; } printf("\n"); } //finds the middle node of the list 'p' int middleNode(list *p) { list *r,*q; r=p;q=p; while(1) { if(r->next==NULL ||r->next->next==NULL) break; r=r->next; r=r->next; q=q->next; } return q->data; }
C
#ifndef DIFFERENCE_H #define DIFFERENCE_H #include "color.h" // Math shamelessly taken from https://en.wikipedia.org/wiki/Color_difference // Finds the difference between the two colors using the deltaE 2000 method by CIE // Note: this function is quasimetric // You may get a different result by plugging in (x, y) than you would get plugging // in (y, x). I recommend passing the "reference" color first, meaning the color that // you would consider the more "accurate" color double deltaE00Difference(Color color1, Color color2); #endif
C
#pragma once #include<stdio.h> #include<stdlib.h> typedef char BTDataType; typedef struct BinaryTreeNode{ BTDataType _data; struct BinaryTreeNode* lchild; struct BinaryTreeNode* rchild; }BTNode; // ͨǰ"ABD##E#H##CF##G##" BTNode* BinaryTreeCreate_(BTDataType* a, int* s_n); BTNode* BinaryTreeCreate(BTDataType* a); void BinaryTreeDestory(BTNode* root); int BinaryTreeSize(BTNode* root);//ڵ int BinaryTreeLeafSize(BTNode* root);//ҶӸ int BinaryTreeLevelKSize(BTNode* root, int k);//kĽڵ BTNode* BinaryTreeFind(BTNode* root, BTDataType x);// // void BinaryTreePrevOrder(BTNode* root); void BinaryTreeInOrder(BTNode* root); void BinaryTreePostOrder(BTNode* root); // ǵݹ // void BinaryTreeLevelOrder(BTNode* root);//,ö // ж϶Ƿȫ int BinaryTreeComplete(BTNode* root); void BinaryTreePrevOrderNonR(BTNode* root); void BinaryTreeInOrderNonR(BTNode* root); void BinaryTreePostOrderNonR(BTNode* root); void TestBinaryTree();
C
#include <stdio.h> int main() { //exercice1 int entier1 = 0; printf("Entrez un entier : \n", entier1); scanf("%d", &entier1); int entier2 = 0; printf("Entrez un deuxieme entier : \n", entier2); scanf("%d", &entier2); if (entier1<entier2) { printf ("L'entier le plus grand des deux est %d.\n", entier2); } else if (entier2<entier1) { printf("L'entier le plus grand des deux est %d.\n", entier1); } else { printf("Vous avez mis deux meme entiers.\n"); } //exercice2 int largeur = 0; int longueur = 0; printf("Saisissez la largeur du rectangle :\n"); scanf("%d", &largeur); printf("Saisissez la longueur du rectangle :\n"); scanf("%d", &longueur); int perimetre = (longueur + largeur)* 2; printf("Le perimetre de votre rectangle est %d.\n", perimetre); int aire = longueur * largeur; printf("L'aire de votre rectangle est %d.\n", aire); //exercice3 const int constante = 3; int entier3 = 0; printf("Saisissez un entier au clavier : \n"); scanf("%d", &entier3); if (entier3 % constante == 0) { printf("Votre entier est un multiple de 3\n"); } else { printf("Votre entier n'est pas un multiple de 3\n"); } if (entier3 >= 10) { printf("Votre entier est superieur ou egal à 10.\n"); } else { printf("Votre entier est inferieur à 10.\n"); } //exercice 4 #define AGEENFANT 12 #define AGEJEUNE 17 #define AGEETUDIANT 27 int ageDuClient = 0; int prix = 9; int bool = 0; printf("\nLe plein tarif est de %ieuros.", prix); printf("Entrez votre age pour savoir si vous bénéficiez d'une réduction :\n"); scanf("%i", &ageDuClient ); if (ageDuClient <= AGEENFANT ) { prix = 4; printf("Vous beneficiez du tarif enfant, cela vous fera %ieuros.\n", prix); } else if(ageDuClient <= AGEJEUNE ) { prix = 6; printf("Vous beneficiez du tarif jeune, cela vous fera %ieuros.\n", prix); } else if (ageDuClient <= AGEETUDIANT) { printf("Etes vous étudiant ?Répondez par 0 pour Oui et 1 pour Non.\n"); scanf("%i", &bool); if (bool == 0) { prix = 6; printf("Vous beneficiez du tarif étudiant, cela vous fera %ieuros.\n", prix); } else { prix = 9; printf("Vous ne beneficiez pas du tarif étudiant, cela vous fera %ieuros.\n", prix); } } else { prix = 6; printf("Vous beneficiez du tarif sénior, cela vous fera %ieuros.\n", prix); } //exercice 5 int distributeur = 0; printf("Entrez le numero de la boisson:\n"); scanf("%i", &distributeur); if (distributeur == 1) { printf("La boisson numero 1 est du Coca-cola.\n"); } else if (distributeur == 2) { printf("La boisson numero 2 est du Ice Tea Lipton.\n"); } else if (distributeur == 3) { printf("La boisson numero 3 est du Sprite.\n"); } else if (distributeur == 10) { printf("La boisson numero 10 est du Chocolat chaud.\n"); } else if (distributeur == 11) { printf("La boisson numero 11 est du Café.\n"); } else { printf("Erreur. Ce numero ne correspond à aucune boisson.\n"); } //exercice6 float note1 = 0.0f; float note2 = 0.0f; float note3 = 0.0f; float moyenne = 0.0f; printf("Entrez une note sur 20:\n"); scanf("%f", &note1); if (note1<0 && note1>20) { printf("Recommencez.\n"); } else { printf("Entrez une deuxième note sur 20:\n"); scanf("%f", &note2); if (note2<0 && note2>20) { printf("Recommencez.\n"); } else { printf("Entrez une troisième note sur 20:\n"); scanf("%f", &note3); moyenne = (note1 + note2 + note3)/3; printf("La moyenne est conforme.\n La moyenne est de %f.\n", moyenne); } } //exercice 7 int nbClasseO = 0; int nbClasseC = 0; int nbEleves = 0; int totalEleves = 0; printf("Entrez le nombre de classes ouvertes:\n"); scanf("%i", &nbClasseO); printf("Entrez le nombre de classes créées:\n"); scanf("%i", &nbClasseC); for (int i = 0;i < nbClasseC;i++) { printf("Entrez le nombre d'eleves dans cette classe crée:\n"); scanf("%i", &nbEleves); totalEleves = totalEleves + nbEleves; } printf("Le nombre total d'eleves est %i.\n", totalEleves); //exercice 8 int nb = 0; printf("Saisissez un nombre entier:\n"); scanf("%i", &nb); while ( nb % 2 != 0) { printf("Saisissez un autre nombre entier:\n"); scanf("%i", &nb); } printf("Le nombre est un multiple de 2.\n"); while (nb % 7 != 0) { printf("Saisissez un autre nombre entier:\n"); scanf("%i", &nb); } printf("Le nombre est un multiple de 7.\n"); //exercice 9 int nbPierre = 0; int pourpyramide = 0; printf("Indiquez le nombre de pierres que vous avez:\n"); scanf("%i", &nbPierre); pourpyramide = nbPierre * nbPierre; //exercice 10 float nbPositif = 0.0f; float ttNbPositif = 0.0f; float moyennePositive = 0.0f; float i = 1.0f; printf("Saisissez un nombre entier positif:\n"); scanf("%f", &nbPositif); while (nbPositif >= 0.0f) { printf("Saisissez un nombre entier positif. Mettez un nombre negatif pour arreter.\n"); scanf("%f", &nbPositif); ttNbPositif = ttNbPositif + nbPositif; moyennePositive = ttNbPositif / i; i = i + 1.0f; } printf("La moyenne des nombres saisis vaut %f.", moyennePositive); return 0; }
C
#include<stdio.h> void main() { int input,i,value,j,fact=1,sum=0; printf("enter the number for factorial"); printf("\nsum of series type1\n\n"); scanf("%d",&input); printf("\n\n"); for(i=1;i<=input;i++) { value=i; for(j=1;j<=value;j++) { fact=fact*j; } sum=sum+fact; fact=1; } printf("The result of the following operation is: %d",sum); }
C
#include "nmqueue.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #define NMQUEUE_INVARIANT(queue)\ assert( queue->queue != NULL );\ assert( queue->readPosition < queue->length );\ assert( queue->writePosition < queue->length ); static const char* errors[] = { "No Error", "Mutex initialize failed", "Conditional variable initialize failed", "Out of memory", "Abort signal catched"}; static const char* invalidError = "Invalid error"; const char* nmqueue_error_to_string(int err) { if( err<0 || err>NMQUEUEERROR_MAX ) { return invalidError; } return errors[err]; } void nmqueue_abort(nmqueue_t* queue, void* threadId) { assert( queue != NULL ); NMQUEUE_INVARIANT( queue ) pthread_mutex_lock( &queue->mutex ); queue->abort = threadId; /* Wakeup both sending and receiving threads */ pthread_cond_broadcast( &queue->writtenCond ); pthread_cond_broadcast( &queue->readCond ); pthread_mutex_unlock( &queue->mutex ); } int nmqueue_initialize(nmqueue_t* queue, size_t length) { assert( queue != NULL ); assert( length != 0 ); queue->writePosition = 0; queue->readPosition = 0; queue->length = length; queue->queue = (struct nmqueue_message_s*)malloc( length*sizeof(struct nmqueue_message_s) ); queue->abort = (void*)(1); if( queue->queue == NULL ) { return NMQUEUEERROR_OUTOFMEMORY; } /* Initialize mutex and conditional variables for both read and written */ { int error; if ( pthread_mutex_init( &queue->mutex, NULL ) == 0 ) { if ( pthread_cond_init( &queue->writtenCond, NULL ) == 0 ) { if ( pthread_cond_init( &queue->readCond, NULL ) == 0 ) { NMQUEUE_INVARIANT(queue); return NMQUEUEERROR_NOERROR; } error = NMQUEUEERROR_CONDVAR_INITIALIZE_FAILED; pthread_cond_destroy( &queue->writtenCond ); } else { error = NMQUEUEERROR_CONDVAR_INITIALIZE_FAILED; } pthread_mutex_destroy( &queue->mutex ); } else { error = NMQUEUEERROR_MUTEX_INITIALIZE_FAILED; } free( queue->queue ); return error; } } void nmqueue_finalize(nmqueue_t* queue) { /* Carefull, threads active? TODO*/ assert( queue != NULL); NMQUEUE_INVARIANT( queue ); pthread_cond_destroy( &queue->writtenCond ); pthread_cond_destroy( &queue->readCond ); pthread_mutex_destroy( &queue->mutex ); /* Actually the queue shouldn't be freed if there is still data to be processed, but in case there still is, at least the entries are deleted. It is impossible to make assumptions about the data pointers since they may not be allocated or may not even be used as pointers. => LEAK WARNING*/ free( queue->queue ); } int nmqueue_send(nmqueue_t* queue, source_t source, void* data, size_t dataSize, void* threadId) { assert( queue != NULL ); NMQUEUE_INVARIANT( queue ); pthread_mutex_lock( &queue->mutex ); /* aborted thread? */ if( queue->abort == threadId ) { printf("ABB:%p\n",queue->abort); queue->abort = NULL; pthread_mutex_unlock(&queue->mutex); return NMQUEUEERROR_ABORT; } /* Wait until writting is possible */ while ((queue->writePosition+1) % queue->length == queue->readPosition) { pthread_cond_wait(&queue->readCond, &queue->mutex); /* aborted thread? */ if( queue->abort == threadId ) { queue->abort = NULL; pthread_mutex_unlock(&queue->mutex); return NMQUEUEERROR_ABORT; } } /* Write message */ { struct nmqueue_message_s* message = &queue->queue[ queue->writePosition ]; message->source = source; message->data = data; message->dataSize = dataSize; } queue->writePosition = (queue->writePosition+1) % queue->length; NMQUEUE_INVARIANT( queue ); pthread_cond_signal(&queue->writtenCond); pthread_mutex_unlock(&queue->mutex); return NMQUEUEERROR_NOERROR; } int nmqueue_receive(nmqueue_t* queue, source_t* source, void** data, size_t* dataSize, void* threadId) { assert( queue != NULL ); assert( source != NULL ); assert( data != NULL ); assert( dataSize != NULL ); NMQUEUE_INVARIANT( queue ); pthread_mutex_lock( &queue->mutex ); /* aborted thread? */ if( queue->abort == threadId) { queue->abort = NULL; pthread_mutex_unlock(&queue->mutex); return NMQUEUEERROR_ABORT; } /* Wait until reading is possible */ while( queue->readPosition == queue->writePosition ) { pthread_cond_wait( &queue->writtenCond, &queue->mutex ); /* aborted thread? */ if( queue->abort == threadId ) { queue->abort = NULL; pthread_mutex_unlock(&queue->mutex); return NMQUEUEERROR_ABORT; } } /* Read message */ { struct nmqueue_message_s* message = &queue->queue[ queue->readPosition ]; *source = message->source; *data = message->data; *dataSize = message->dataSize; queue->readPosition = (queue->readPosition+1) % queue->length; NMQUEUE_INVARIANT( queue ); pthread_cond_signal(&queue->readCond); } pthread_mutex_unlock(&queue->mutex); return NMQUEUEERROR_NOERROR; }
C
#include <stdio.h> #include <stdarg.h> #include <X11/Xlib.h> #include <X11/extensions/security.h> int total_error_count = 0; /* total # of errors during entire run */ /* A testset is a group of logically related tests, e.g., all the tests * for a certain protocol request. */ char *testsetname; /* string name of current testset */ int errs_this_testset; /* number of errors that have occured this testset */ /* A test tries to validate a specific statement in the spec. Roughly * equivalent to an IC (invocable component) in the TET framework. */ char *testname; /* string name of current test */ int errs_this_test; /* number of errors that have occured this test */ int total_tests = 0; /* total number of tests executed */ int expected_protocol_error; int received_protocol_error; int security_majorop; /* opcode for SECURITY */ int security_event, security_error; /* event and error base for SECURITY */ char *display_env = NULL; /* -display argument */ /* some utilities for handling errors and demarcating start/end of * test modules */ /* Call this when an error occurs, passing a string that describes the error.*/ void report_error(char *err_fmt, ...) { va_list an; fprintf(stderr, "Error: %s %s: ", testsetname, testname); va_start(an, err_fmt); vfprintf(stderr, err_fmt, an); va_end(an); fprintf(stderr, "\n"); fflush(stderr); errs_this_test++; } /* When you're not expecting a protocol error, make sure this is installed * via XSetErrorHandler. */ int protocol_error_unexpected(dpy, errevent) Display *dpy; XErrorEvent *errevent; { char buf[80]; XGetErrorText(dpy, errevent->error_code, buf, sizeof (buf)); report_error(buf); return 1; } /* When you *are* expecting a protocol error, make sure this is installed * via XSetErrorHandler. You can check the global protocol_error to see * if the expected error actually occured. */ int protocol_error_expected(dpy, errevent) Display *dpy; XErrorEvent *errevent; { char buf[80]; XGetErrorText(dpy, errevent->error_code, buf, sizeof (buf)); if (expected_protocol_error != errevent->error_code) report_error("wrong error %d (%s), wanted %d\n", errevent->error_code, buf, expected_protocol_error); received_protocol_error = errevent->error_code; return 1; } void expect_protocol_error(err) int err; { expected_protocol_error = err; received_protocol_error = 0; XSetErrorHandler(protocol_error_expected); } void verify_error_received() { if (received_protocol_error == 0) report_error("error %d never received", expected_protocol_error); XSetErrorHandler(protocol_error_unexpected); } /* Call this at the start of a test with a short string description of * the test. */ void begin_test(char *t) { testname = t; errs_this_test = 0; XSetErrorHandler(protocol_error_unexpected); } /* Call this at the end of a test. */ void end_test() { if (errs_this_test) { printf("End test %s with %d errors\n\n", testname, errs_this_test); fflush(stdout); } errs_this_testset += errs_this_test; total_tests++; } /* Call this at the start of a testset with a short string description of the * testset. */ void begin_test_set(tn, tc, uc) char *tn; Display **tc; /* trusted connection */ Display **uc; /* untrusted connection */ { Display *dpy; int major_version, minor_version; XSecurityAuthorization id_return; int status; Xauth *auth_in, *auth_return; testsetname = tn; errs_this_testset = 0; printf("Start testset %s\n", testsetname); fflush(stdout); XSetAuthorization(NULL, 0, NULL, 0); /* use default auth */ *tc = XOpenDisplay(display_env); if (!*tc) { report_error("Failed to open trusted connection\n"); exit(1); } XSynchronize(*tc, True); /* so we get errors at convenient times */ XSetErrorHandler(protocol_error_unexpected); if (!XQueryExtension(*tc, "SECURITY", &security_majorop, &security_event, &security_error)) { report_error("Failed to find SECURITY extension"); exit(1); } /* now make untrusted connection */ status = XSecurityQueryExtension(*tc, &major_version, &minor_version); if (!status) { report_error("%s: couldn't query Security extension"); exit (1); } auth_in = XSecurityAllocXauth(); auth_in->name = "MIT-MAGIC-COOKIE-1"; auth_in->name_length = strlen(auth_in->name); auth_return = XSecurityGenerateAuthorization(*tc, auth_in, 0, NULL, &id_return); if (!auth_return) { report_error("couldn't generate untrusted authorization\n"); exit (1); } XSetAuthorization(auth_return->name, auth_return->name_length, auth_return->data, auth_return->data_length); *uc = XOpenDisplay(display_env); if (!*uc) { report_error("Failed to open untrusted connection\n"); exit(1); } XSynchronize(*uc, True); /* so we get errors at convenient times */ XSecurityFreeXauth(auth_in); XSecurityFreeXauth(auth_return); } /* Call this at the end of a testset. */ void end_test_set(tc, uc) Display *tc, *uc; { printf("End testset %s with %d errors\n\n", testsetname, errs_this_testset); fflush(stdout); total_error_count += errs_this_testset; XCloseDisplay(tc); XCloseDisplay(uc); } void window_resource_tests() { Window tw, uw, root; Display *tc, *uc; XSetWindowAttributes swa; int screen; Visual *visual; int depth; XImage *image; XID id; GC gc, tgc, ugc; Colormap *pcm; int num; Atom *pa; begin_test_set("Window resource access", &tc, &uc); root = DefaultRootWindow(tc); screen = DefaultScreen(tc); visual = DefaultVisual(tc, screen); depth = DefaultDepth(tc, screen); swa.override_redirect = True; tw = XCreateWindow(tc, root, 0, 0, 10, 10, 1, depth, InputOutput, visual, CWOverrideRedirect, &swa); XMapWindow(tc, tw); uw = XCreateWindow(uc, root, 20, 20, 10, 10, 1, depth, InputOutput, visual, CWOverrideRedirect, &swa); XMapWindow(uc, uw); tgc = DefaultGC(tc, screen); ugc = DefaultGC(uc, screen); begin_test("GetImage"); image = XGetImage(tc, tw, 0, 0, 10, 10, ~0, ZPixmap); image = XGetImage(tc, uw, 0, 0, 10, 10, ~0, ZPixmap); image = XGetImage(tc, root, 0, 0, 10, 10, ~0, ZPixmap); image = XGetImage(uc, uw, 0, 0, 10, 10, ~0, ZPixmap); expect_protocol_error(BadDrawable); image = XGetImage(uc, tw, 0, 0, 10, 10, ~0, ZPixmap); verify_error_received(); expect_protocol_error(BadDrawable); image = XGetImage(uc, root, 0, 0, 10, 10, ~0, ZPixmap); verify_error_received(); end_test(); begin_test("CreateColormap"); id = XCreateColormap(tc, root, visual, AllocNone); id = XCreateColormap(tc, tw, visual, AllocNone); id = XCreateColormap(tc, uw, visual, AllocNone); id = XCreateColormap(uc, root, visual, AllocNone); id = XCreateColormap(uc, uw, visual, AllocNone); expect_protocol_error(BadWindow); id = XCreateColormap(uc, tw, visual, AllocNone); verify_error_received(); end_test(); begin_test("CreateGC"); gc = XCreateGC(tc, root, 0, NULL); gc = XCreateGC(tc, tw, 0, NULL); gc = XCreateGC(tc, uw, 0, NULL); gc = XCreateGC(uc, root, 0, NULL); gc = XCreateGC(uc, uw, 0, NULL); expect_protocol_error(BadDrawable); gc = XCreateGC(uc, tw, 0, NULL); verify_error_received(); end_test(); begin_test("CreatePixmap"); id = XCreatePixmap(tc, root, 10, 10, depth); id = XCreatePixmap(tc, tw, 10, 10, depth); id = XCreatePixmap(tc, uw, 10, 10, depth); id = XCreatePixmap(uc, root, 10, 10, depth); id = XCreatePixmap(uc, uw, 10, 10, depth); expect_protocol_error(BadDrawable); id = XCreatePixmap(uc, tw, 10, 10, depth); verify_error_received(); end_test(); begin_test("CreateWindow"); id = XCreateSimpleWindow(tc, root, 0,0,1,1,1,0,0); id = XCreateSimpleWindow(tc, tw, 0,0,1,1,1,0,0); id = XCreateSimpleWindow(tc, uw, 0,0,1,1,1,0,0); id = XCreateSimpleWindow(uc, root, 0,0,1,1,1,0,0); id = XCreateSimpleWindow(uc, uw, 0,0,1,1,1,0,0); expect_protocol_error(BadWindow); id = XCreateSimpleWindow(uc, tw, 0,0,1,1,1,0,0); verify_error_received(); end_test(); begin_test("ListInstalledColormaps"); pcm = XListInstalledColormaps(tc, root, &num); pcm = XListInstalledColormaps(tc, tw, &num); pcm = XListInstalledColormaps(tc, uw, &num); expect_protocol_error(BadWindow); pcm = XListInstalledColormaps(uc, root, &num); verify_error_received(); pcm = XListInstalledColormaps(uc, uw, &num); expect_protocol_error(BadWindow); pcm = XListInstalledColormaps(uc, tw, &num); verify_error_received(); end_test(); begin_test("ListProperties"); pa = XListProperties(tc, root, &num); pa = XListProperties(tc, tw, &num); pa = XListProperties(tc, uw, &num); pa = XListProperties(uc, root, &num); pa = XListProperties(uc, uw, &num); expect_protocol_error(BadWindow); pa = XListProperties(uc, tw, &num); verify_error_received(); end_test(); begin_test("DrawPoint"); XDrawPoint(tc, root, tgc, 1, 1); XDrawPoint(tc, tw, tgc, 1, 1); XDrawPoint(tc, uw, tgc, 1, 1); expect_protocol_error(BadDrawable); XDrawPoint(uc, root, ugc, 1, 1); verify_error_received(); XDrawPoint(uc, uw, ugc, 1, 1); expect_protocol_error(BadDrawable); XDrawPoint(uc, tw, ugc, 1, 1); verify_error_received(); end_test(); end_test_set(tc, uc); } /* window_resource_tests */ pixmap_resource_tests() { Window root; Pixmap tp, up; Display *tc, *uc; int screen; Visual *visual; int depth; XImage *image; XID id; int num; GC tgc, ugc; begin_test_set("Pixmap resource access", &tc, &uc); root = DefaultRootWindow(tc); screen = DefaultScreen(tc); visual = DefaultVisual(tc, screen); depth = DefaultDepth(tc, screen); tp = XCreatePixmap(tc, root, 10, 10, depth); up = XCreatePixmap(uc, root, 10, 10, depth); tgc = DefaultGC(tc, screen); ugc = DefaultGC(uc, screen); begin_test("DrawPoint"); XDrawPoint(tc, tp, tgc, 1, 1); XDrawPoint(tc, up, tgc, 1, 1); XDrawPoint(uc, up, ugc, 1, 1); expect_protocol_error(BadDrawable); XDrawPoint(uc, tp, ugc, 1, 1); verify_error_received(); end_test(); end_test_set(tc, uc); } /* pixmap_resource_tests */ font_resource_tests() { Window root; Font tf, uf; Display *tc, *uc; int screen; Visual *visual; int depth; XImage *image; XID id; int num; XGCValues gcvals; GC gc; begin_test_set("Font resource access", &tc, &uc); root = DefaultRootWindow(tc); screen = DefaultScreen(tc); visual = DefaultVisual(tc, screen); depth = DefaultDepth(tc, screen); tf = XLoadFont(tc, "fixed"); uf = XLoadFont(uc, "fixed"); /* hard to test this because Xlib eats BadFont errors */ #if 0 begin_test("CreateGC"); gcvals.font = tf; gc = XCreateGC(tc, root, GCFont, &gcvals); gcvals.font = uf; gc = XCreateGC(tc, root, GCFont, &gcvals); expect_protocol_error(BadFont); gcvals.font = tf; gc = XCreateGC(uc, root, GCFont, &gcvals); verify_error_received(); gcvals.font = uf; gc = XCreateGC(uc, root, GCFont, &gcvals); end_test(); #endif end_test_set(tc, uc); } /* font_resource_tests */ cursor_resource_tests() { Window root; Cursor tcr, ucr; Display *tc, *uc; int screen; Visual *visual; int depth; XImage *image; XID id; int num; XGCValues gcvals; GC gc; XColor c; begin_test_set("Cursor resource access", &tc, &uc); root = DefaultRootWindow(tc); screen = DefaultScreen(tc); visual = DefaultVisual(tc, screen); depth = DefaultDepth(tc, screen); tcr = XCreateFontCursor(tc, 0); ucr = XCreateFontCursor(uc, 0); begin_test("RecolorCursor"); XRecolorCursor(tc, tcr, &c, &c); XRecolorCursor(tc, ucr, &c, &c); expect_protocol_error(BadCursor); XRecolorCursor(uc, tcr, &c, &c); verify_error_received(); XRecolorCursor(uc, ucr, &c, &c); end_test(); end_test_set(tc, uc); } /* cursor_resource_tests */ gc_resource_tests() { Window root; GC tgc, ugc; Pixmap up; Display *tc, *uc; int screen; Visual *visual; int depth; XID id; int num; XGCValues gcvals; begin_test_set("GC resource access", &tc, &uc); root = DefaultRootWindow(tc); screen = DefaultScreen(tc); visual = DefaultVisual(tc, screen); depth = DefaultDepth(tc, screen); tgc = XCreateGC(tc, root, 0, NULL); ugc = XCreateGC(uc, root, 0, NULL); up = XCreatePixmap(uc, root, 10, 10, depth); begin_test("DrawPoint"); XDrawPoint(tc, up, tgc, 1, 1); XDrawPoint(tc, up, ugc, 1, 1); expect_protocol_error(BadGC); XDrawPoint(uc, up, tgc, 1, 1); verify_error_received(); XDrawPoint(uc, up, ugc, 1, 1); end_test(); end_test_set(tc, uc); } /* gc_resource_tests() */ colormap_resource_tests() { Window root; Colormap tcm, ucm; Display *tc, *uc; int screen; Visual *visual; int depth; XColor color; begin_test_set("Colormap resource access", &tc, &uc); root = DefaultRootWindow(tc); screen = DefaultScreen(tc); visual = DefaultVisual(tc, screen); depth = DefaultDepth(tc, screen); tcm = XCreateColormap(tc, root, visual, AllocNone); ucm = XCreateColormap(uc, root, visual, AllocNone); begin_test("AllocColor"); color.pixel = color.red = color.green = color.blue = 0; XAllocColor(tc, tcm, &color); XAllocColor(tc, ucm, &color); expect_protocol_error(BadColor); XAllocColor(uc, tcm, &color); verify_error_received(); XAllocColor(uc, ucm, &color); end_test(); end_test_set(tc, uc); } /* colormap_resource_tests */ int main(argc, argv) int argc; char **argv; { if (argc >= 2 && strcmp(argv[1], "-display") == 0) display_env = argv[2]; window_resource_tests(); pixmap_resource_tests(); font_resource_tests(); cursor_resource_tests(); gc_resource_tests(); colormap_resource_tests(); printf("total tests: %d, total errors: %d, errors/test: %f\n", total_tests, total_error_count, (float)total_error_count / total_tests); return total_error_count; }
C
/* * ---------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * Jeroen Domburg <[email protected]> wrote this file. As long as you retain * this notice you can do whatever you want with this stuff. If we meet some day, * and you think this stuff is worth it, you can buy me a beer in return. * ---------------------------------------------------------------------------- */ #include <esp8266.h> #include <uart.h> #include <uart_register.h> #include "limits.h" static int ICACHE_FLASH_ATTR Stdout_s32IsUpper(char c) { return (c >= 'A' && c <= 'Z'); } static int ICACHE_FLASH_ATTR Stdout_s32IsAlpha(char c) { return ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')); } static int ICACHE_FLASH_ATTR Stdout_s32IsDigit(char c) { return (c >= '0' && c <= '9'); } int32 ICACHE_FLASH_ATTR Stdout_s32Strtol(const char *nptr, char **endptr, int base) { const char *s = nptr; unsigned long acc; int c; unsigned long cutoff; int neg = 0, any, cutlim; /* * Skip white space and pick up leading +/- sign if any. * If base is 0, allow 0x for hex and 0 for octal, else * assume decimal; if base is already 16, allow 0x. */ do { c = *s++; } while (Stdout_s32IsAlpha(c)); if (c == '-') { neg = 1; c = *s++; } else if (c == '+') { c = *s++; } if ((base == 0 || base == 16) && c == '0' && (*s == 'x' || *s == 'X')) { c = s[1]; s += 2; base = 16; } else if ((base == 0 || base == 2) && c == '0' && (*s == 'b' || *s == 'B')) { c = s[1]; s += 2; base = 2; } if (base == 0) { base = c == '0' ? 8 : 10; } /* * Compute the cutoff value between legal numbers and illegal * numbers. That is the largest legal value, divided by the * base. An input number that is greater than this value, if * followed by a legal input character, is too big. One that * is equal to this value may be valid or not; the limit * between valid and invalid numbers is then based on the last * digit. For instance, if the range for longs is * [-2147483648..2147483647] and the input base is 10, * cutoff will be set to 214748364 and cutlim to either * 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated * a value > 214748364, or equal but the next digit is > 7 (or 8), * the number is too big, and we will return a range error. * * Set any if any `digits' consumed; make it negative to indicate * overflow. */ cutoff = neg ? -(unsigned long) LONG_MIN : LONG_MAX; cutlim = cutoff % (unsigned long) base; cutoff /= (unsigned long) base; for (acc = 0, any = 0;; c = *s++) { if (Stdout_s32IsDigit(c)) c -= '0'; else if (Stdout_s32IsAlpha(c)) c -= Stdout_s32IsUpper(c) ? 'A' - 10 : 'a' - 10; else break; if (c >= base) break; if (any < 0 || acc > cutoff || acc == cutoff && c > cutlim) any = -1; else { any = 1; acc *= base; acc += c; } } if (any < 0) { acc = neg ? LONG_MIN : LONG_MAX; // errno = ERANGE; } else if (neg) acc = -acc; if (endptr != 0) *endptr = (char*) (any ? s - 1 : nptr); return (acc); } static void ICACHE_FLASH_ATTR stdoutUartTxd(char c) { //Wait until there is room in the FIFO while (((READ_PERI_REG(UART_STATUS(0)) >> UART_TXFIFO_CNT_S) & UART_TXFIFO_CNT) >= 126); //Send the character WRITE_PERI_REG(UART_FIFO(0), c); } static void ICACHE_FLASH_ATTR stdoutPutchar(char c) { //convert \n -> \r\n if (c == '\n') stdoutUartTxd('\r'); stdoutUartTxd(c); } void ICACHE_FLASH_ATTR stdoutInit() { //Enable TxD pin PIN_PULLUP_DIS(PERIPHS_IO_MUX_U0TXD_U); PIN_FUNC_SELECT(PERIPHS_IO_MUX_U0TXD_U, FUNC_U0TXD); //Set baud rate and other serial parameters to 115200,n,8,1 uart_div_modify(0, UART_CLK_FREQ / BIT_RATE_115200); WRITE_PERI_REG(UART_CONF0(0), (STICK_PARITY_DIS)|(ONE_STOP_BIT << UART_STOP_BIT_NUM_S)| (EIGHT_BITS << UART_BIT_NUM_S)); //Reset tx & rx fifo SET_PERI_REG_MASK(UART_CONF0(0), UART_RXFIFO_RST|UART_TXFIFO_RST); CLEAR_PERI_REG_MASK(UART_CONF0(0), UART_RXFIFO_RST|UART_TXFIFO_RST); //Clear pending interrupts WRITE_PERI_REG(UART_INT_CLR(0), 0xffff); //Install our own putchar handler os_install_putc1((void*) stdoutPutchar); }
C
/** * \file affichage.h * * \brief Fichier contenant le code nécessaire à l'affichage graphique (SDL2) du programme * * \author JENNY Thibaud * \version 1.0 * \date 27/03/2020 * * Dans ce fichier ce trouvent le code des fonctions servant à afficher le programme graphique */ #ifndef AFFICHAGE_GRAPHIQUE_H #define AFFICHAGE_GRAPHIQUE_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <SDL2/SDL.h> #include <SDL2/SDL_ttf.h> #include "../Modele/tuile.h" #include "../Modele/partie.h" #define DELAY 7000 #define HEIGHT 1024 #define WIDTH 1280 int affichage_init(int flag); SDL_Window* createWindow(char* titre, int flag1, int flag2,int hauteur,int largeur,int flag3); SDL_Renderer* createRenderer(SDL_Window* window,int index,int flag); void affichage_pause(int delay); SDL_Texture* loadImage(SDL_Renderer* renderer,char* image); SDL_Texture* loadTuilefromData(Tuile * t,int x,int y,int taille, SDL_Renderer* renderer); void splashscreen(SDL_Renderer *renderer); int initialisation_TTF(void); SDL_Texture* createTexture(SDL_Renderer* renderer,SDL_Surface* surface); TTF_Font* setPolice(char* font, int tailledepolice); int writeThis(SDL_Renderer* renderer,SDL_Texture* textureTexte,TTF_Font *police, char* texte, SDL_Color couleurTexte, SDL_Rect* encadrementtexte); SDL_Rect createFraming(int width, int height, int x,int y); void affichageScore(SDL_Renderer* renderer,Partie *p); void affichageScore_demo(SDL_Renderer* renderer,Partie *p); //Affiche score optimise pour 4 joueurs max void affichageEcran(SDL_Renderer* renderer,char* imagedefond); void affichage_sac(SDL_Renderer *renderer,Partie *p); void affiche_plateau_17x17(SDL_Renderer *renderer,Partie *partie,int xoff,int yoff,SDL_bool clearTiles); void affiche_tuiles_provisoires_17x17(SDL_Renderer *renderer,Partie *partie,int tabtuilesprovisoires[6],int xoff,int yoff,SDL_bool clearTiles); void affiche_main_joueur_courant(SDL_Renderer *renderer,Partie *partie); void affichageJoueurCourant(SDL_Renderer *renderer,Partie *partie); void affichageJoueurCourant_demo(SDL_Renderer *renderer,Partie *partie);//Affichejoueurcourant optimisé pour 4 joueurs max void affichageFin(SDL_Renderer* renderer,Partie* p); void affichageFinTour(SDL_Renderer * renderer, Partie *p); void affiche_bouton_OK(SDL_Renderer *renderer); void supprime_bouton_OK(SDL_Renderer *renderer); void affiche_bouton_fin_du_tour(SDL_Renderer *renderer); void supprime_bouton_fin_du_tour(SDL_Renderer *renderer); void affiche_bouton_retour(SDL_Renderer *renderer); void supprime_bouton_retour(SDL_Renderer *renderer); void affiche_poser(SDL_Renderer *renderer); void affiche_piocher(SDL_Renderer *renderer); void supprime_piocher(SDL_Renderer *renderer); void supprime_poser(SDL_Renderer *renderer); void affiche_passer_son_tour(SDL_Renderer *renderer); void affichage_selection_tuiles(SDL_Renderer * renderer,int j); void affichage_selection_tuiles_finales(SDL_Renderer * renderer,int j); void supprime_selection_tuiles(SDL_Renderer * renderer,int j); void affichage_fleches_plateau(SDL_Renderer* renderer); //LES MESSAGES void affichage_isregleok(SDL_Renderer *renderer,SDL_bool regleok,SDL_bool showmessage); void affiche_Tisok_message(SDL_Renderer *renderer,int i,SDL_bool showmessage); void affichage_trackingerror(SDL_Renderer *renderer,SDL_bool iswordokaligned,SDL_bool showmessage); void affichage_message(SDL_Renderer *renderer,SDL_Color couleur,SDL_Rect *background,char* message); void supprime_zonemessage(SDL_Renderer *renderer,SDL_Rect *background); #endif // AFFICHAGE_GRAPHIQUE_H
C
// work-stealing deque based on the Chase-Lev paper #include <stdbool.h> #include <malloc.h> #include <glib.h> #include "chase_lev.h" circular_array * ca_build(unsigned long int log_size) { circular_array* ca = (circular_array*) malloc(sizeof(circular_array)); ca->log_size = log_size; long int real_size = 1 << log_size; ca->segment = (void*) malloc(real_size * sizeof(void *)); for(long int i = 0; i< real_size; i++) { ca->segment[i] = (void*) 1000000000000; } return ca; } void * ca_get(circular_array *a, long int i) { void ** segment = a->segment; long int index = i % ca_size(a); void *res = ((void**)segment)[index]; return res; } void ca_put(circular_array *a, long int i, void *o) { volatile void *segment = a->segment; ((void**)segment)[i % ca_size(a)] = o; } circular_array * ca_grow(circular_array *a, long int b, long int t) { circular_array *na = ca_build(a->log_size + 1); for (long int i = t; i < b; i++) { ca_put(na, i, ca_get(a, i)); } return na; } long ca_size(circular_array *a) { return (1 << a->log_size); } ws_deque * ws_queue_build() { ws_deque *q = (ws_deque*) malloc(sizeof(ws_deque)); q->bottom = 0; g_atomic_pointer_set(&(q->top), (long int) 0); q->active_array = ca_build(LOG_INITIAL_SIZE); return q; } void push_bottom(ws_deque *q, void *value) { long int b = q->bottom; long int t = (long int) g_atomic_pointer_get(&(q->top)); circular_array *a = q->active_array; long int a_size = ca_size(a); long int size = b - t; if(size >= (a_size - 1)) { a = ca_grow(a, b, t); q->active_array = a; } ca_put(a, b, value); q->bottom = b + 1; } void * pop_bottom(ws_deque *q) { long int b = q->bottom; circular_array *a = q->active_array; b = b - 1; q->bottom = b; long int t = (long int) g_atomic_pointer_get(&(q->top)); long int size = b - t; long int zero = 0; if(size < zero) { q->bottom = t; return NULL; } void *value = ca_get(a, b); if(size > 0) { return value; } // this is the case for exactly one element, this is now the top so act accordingly long int new_t = t+1; gboolean cas = g_atomic_pointer_compare_and_exchange((void * volatile*)&(q->top), (void*)t, (void*)new_t); if( !cas ) { value = NULL; } q->bottom = t+1; return value; } // THIS FUNCTION IS NOT SAFE // IT CAN ONLY BE CALLED BY OWNER AND // IT CAN BE INCORRECT int is_empty(ws_deque *q) { long int t = (long int) g_atomic_pointer_get(&(q->top)); long int b = q->bottom; return ((b - t) == 0); } void * steal(ws_deque *q) { long int t = (long int) g_atomic_pointer_get(&(q->top)); long int b = q->bottom; circular_array * a = q->active_array; long int size = b - t; if( size <= 0 ) { return NULL; } void *value = ca_get(a, t); long int new_t = t + 1; // top stuff gboolean cas = g_atomic_pointer_compare_and_exchange((void * volatile*)&(q->top), (void*)t, (void*)new_t); if( !cas ) { return NULL; } return value; }
C
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<sys/types.h> #include<sys/wait.h> void quit(){ //收到信号SIGINT后,结束进程 printf("Process %d received SIGINT,will exit\n",getpid()); exit(0); } int main(){ int ret; if(ret=fork()){ //父进程睡眠秒后向子进程发送信号SIGINT printf("Parent:%d\n",getpid()); sleep(3); kill(ret,SIGINT); printf("Parent %d sent SIGINT to child %d\n",getpid(),ret); //父进程等待子进程结束执行ps wait(0); printf("Parent exec ps and then exit\n"); execlp("ps","ps",NULL); }else{ //设置子进程收到信号SIGINT的处理函数 printf("Child:%d\n",getpid()); signal(SIGINT,quit); //无限循环 for(;;){} } }
C
#include<stdio.h> #include<stdlib.h> struct stack{ int capacity; int top; int *array; }; struct stack* createStack(int capa){ struct stack *newstack=(struct stack*)malloc(sizeof(struct stack)); newstack->top=-1; newstack->capacity=capa; newstack->array=(int *)malloc(newstack->capacity*sizeof(int)); return newstack; } void push(struct stack *full,int data){ if(isfull(full))return; full->array[++full->top]=data; } void printstack(struct stack *dis){ if(isempty(dis))return ; while(dis->top>-1){ printf("%d\n",dis->array[dis->top]); dis->top--; } } int isfull(struct stack *check){ return check->top==check->capacity-1; } int isempty(struct stack *check){ return check->top==-1; } int main(){ struct stack *n=createStack(2); push(n,1); push(n,2); push(n,3); printstack(n); return 0; }
C
/* * This file implements elementary operations in finite field GF(2^255-MQ), * with no inline assembly. The _addcarry_u64() and _subborrow_u64() * intrinsics are used to get 64-bit additions and subtractions with * carries; for 64x64->128 multiplications, the 'unsigned __int128' type * or the _umul128() intrinsic are used, depending on the local compiler * (MSVC does not support 'unsigned __int128'). * * It is not meant to be compiled by itself, but included in an outer * file. The outer file must provide the following: * * MQ macro that evaluates to a literal constant * GF_INVT508 value 1/2^508 mod 2^255-MQ * * Moreover, the common header "do255.h" must have already been included. * Value GF_INVT508 is a 'struct do255_int256_w64' and the value is * represented in four 64-bit limbs (v0 is lowest limb, v3 is highest). */ #include <immintrin.h> typedef struct do255_int256_w64 gf; /* * Constants below need not be modified if MQ is changed. */ static const gf GF_ZERO = { 0, 0, 0, 0 }; static const gf GF_ONE = { 1, 0, 0, 0 }; static const gf GF_TWO = { 2, 0, 0, 0 }; static const gf GF_SEVEN = { 7, 0, 0, 0 }; static const gf GF_P = { (uint64_t)-MQ, (uint64_t)-1, (uint64_t)-1, (uint64_t)-1 >> 1 }; /* * Helpful macro to convert expressions to strings, for inline assembly. */ #define ST(x) ST_(x) #define ST_(x) #x #if defined __GNUC__ || defined __clang__ #define UMUL64(lo, hi, x, y) do { \ unsigned __int128 umul64_tmp; \ umul64_tmp = (unsigned __int128)(x) * (unsigned __int128)(y); \ (lo) = (uint64_t)umul64_tmp; \ (hi) = (uint64_t)(umul64_tmp >> 64); \ } while (0) #define UMUL64x2(lo, hi, x1, y1, x2, y2) do { \ unsigned __int128 umul64_tmp; \ umul64_tmp = (unsigned __int128)(x1) * (unsigned __int128)(y1) \ + (unsigned __int128)(x2) * (unsigned __int128)(y2); \ (lo) = (uint64_t)umul64_tmp; \ (hi) = (uint64_t)(umul64_tmp >> 64); \ } while (0) #define UMUL64x2_ADD(lo, hi, x1, y1, x2, y2, z3) do { \ unsigned __int128 umul64_tmp; \ umul64_tmp = (unsigned __int128)(x1) * (unsigned __int128)(y1) \ + (unsigned __int128)(x2) * (unsigned __int128)(y2) \ + (unsigned __int128)(z3); \ (lo) = (uint64_t)umul64_tmp; \ (hi) = (uint64_t)(umul64_tmp >> 64); \ } while (0) #else #define UMUL64(lo, hi, x, y) do { \ uint64_t umul64_hi; \ (lo) = _umul128((x), (y), &umul64_hi); \ (hi) = umul64_hi; \ } while (0) #define UMUL64x2(lo, hi, x1, y1, x2, y2) do { \ uint64_t umul64_lo1, umul64_lo2, umul64_hi1, umul64_hi2; \ unsigned char umul64_cc; \ umul64_lo1 = _umul128((x1), (y1), &umul64_hi1); \ umul64_lo2 = _umul128((x2), (y2), &umul64_hi2); \ umul64_cc = _addcarry_u64(0, \ umul64_lo1, umul64_lo2, &umul64_lo1); \ (void)_addcarry_u64(umul64_cc, \ umul64_hi1, umul64_hi2, &umul64_hi1); \ (lo) = umul64_lo1; \ (hi) = umul64_hi1; \ } while (0) #define UMUL64x2_ADD(lo, hi, x1, y1, x2, y2, z3) do { \ uint64_t umul64_lo1, umul64_lo2, umul64_hi1, umul64_hi2; \ unsigned char umul64_cc; \ umul64_lo1 = _umul128((x1), (y1), &umul64_hi1); \ umul64_lo2 = _umul128((x2), (y2), &umul64_hi2); \ umul64_cc = _addcarry_u64(0, \ umul64_lo1, umul64_lo2, &umul64_lo1); \ (void)_addcarry_u64(umul64_cc, \ umul64_hi1, umul64_hi2, &umul64_hi1); \ umul64_cc = _addcarry_u64(0, umul64_lo1, (z3), &umul64_lo1); \ (void)_addcarry_u64(umul64_cc, umul64_hi1, 0, &umul64_hi1); \ (lo) = umul64_lo1; \ (hi) = umul64_hi1; \ } while (0) #endif /* * A field element is represented as four limbs, in base 2^64. Operands * and result may be up to 2^256-1. * A _normalized_ value is in 0..p-1. gf_normalize() ensures normalization; * it is called before encoding, and also when starting inversion. */ /* d <- a + b */ UNUSED static void gf_add(gf *d, const gf *a, const gf *b) { unsigned long long d0, d1, d2, d3; unsigned char cc; /* * Compute sum over 256 bits + carry. */ cc = _addcarry_u64(0, a->v0, b->v0, &d0); cc = _addcarry_u64(cc, a->v1, b->v1, &d1); cc = _addcarry_u64(cc, a->v2, b->v2, &d2); cc = _addcarry_u64(cc, a->v3, b->v3, &d3); /* * If there is a carry, subtract 2*p, i.e. add 2*MQ and * (implicitly) subtract 2^256. */ cc = _addcarry_u64(0, d0, -(unsigned long long)cc & (2 * MQ), &d0); cc = _addcarry_u64(cc, d1, 0, (unsigned long long *)&d->v1); cc = _addcarry_u64(cc, d2, 0, (unsigned long long *)&d->v2); cc = _addcarry_u64(cc, d3, 0, (unsigned long long *)&d->v3); /* * Usually, there won't be an extra carry here, and the * implicit subtraction of 2^256 is enough. However, if the * the original sum was at least 2^257 - 2*MQ, then this * will show up as an extra carry here. In that case, the * low limb (d0) is necessarily less than 2*MQ, and thus adding * back 2*MQ to it will not trigger any carry. */ (void)_addcarry_u64(0, d0, -(unsigned long long)cc & (2 * MQ), (unsigned long long *)&d->v0); } /* d <- a - b */ UNUSED static void gf_sub(gf *d, const gf *a, const gf *b) { unsigned long long d0, d1, d2, d3, e; unsigned char cc; /* * Compute subtraction over 256 bits. */ cc = _subborrow_u64(0, a->v0, b->v0, &d0); cc = _subborrow_u64(cc, a->v1, b->v1, &d1); cc = _subborrow_u64(cc, a->v2, b->v2, &d2); cc = _subborrow_u64(cc, a->v3, b->v3, &d3); /* * If the result is negative, add back 2*p = 2^256 - 2*MQ (which * we do by subtracting 2*MQ). */ e = -(unsigned long long)cc; cc = _subborrow_u64(0, d0, e & (2 * MQ), &d0); cc = _subborrow_u64(cc, d1, 0, (unsigned long long *)&d->v1); cc = _subborrow_u64(cc, d2, 0, (unsigned long long *)&d->v2); cc = _subborrow_u64(cc, d3, 0, (unsigned long long *)&d->v3); /* * If there is still a carry, then we must add 2*p again. In that * case, subtracting 2*MQ from the low limb won't trigger a carry. */ d->v0 = d0 - (-(unsigned long long)cc & (2 * MQ)); } /* d <- -a */ UNUSED static void gf_neg(gf *d, const gf *a) { unsigned long long d0, d1, d2, d3, e; unsigned char cc; /* * Compute 2*p - a over 256 bits. */ cc = _subborrow_u64(0, (unsigned long long)-(2 * MQ), a->v0, &d0); cc = _subborrow_u64(cc, (unsigned long long)-1, a->v1, &d1); cc = _subborrow_u64(cc, (unsigned long long)-1, a->v2, &d2); cc = _subborrow_u64(cc, (unsigned long long)-1, a->v3, &d3); /* * If the result is negative, add back p = 2^255 - MQ. */ e = -(unsigned long long)cc; cc = _addcarry_u64(0, d0, e & -MQ, (unsigned long long *)&d->v0); cc = _addcarry_u64(cc, d1, e, (unsigned long long *)&d->v1); cc = _addcarry_u64(cc, d2, e, (unsigned long long *)&d->v2); (void)_addcarry_u64(cc, d3, e >> 1, (unsigned long long *)&d->v3); } /* If ctl = 1, then d <- -a If ctl = 0, then d is unchanged ctl MUST be 0 or 1 */ UNUSED static void gf_condneg(gf *d, const gf *a, uint64_t ctl) { gf t; gf_neg(&t, a); d->v0 = a->v0 ^ (-ctl & (a->v0 ^ t.v0)); d->v1 = a->v1 ^ (-ctl & (a->v1 ^ t.v1)); d->v2 = a->v2 ^ (-ctl & (a->v2 ^ t.v2)); d->v3 = a->v3 ^ (-ctl & (a->v3 ^ t.v3)); } /* d <- a - b - c */ UNUSED static void gf_sub2(gf *d, const gf *a, const gf *b, const gf *c) { /* TODO: see if this can be optimized a bit */ gf t; gf_sub(&t, a, b); gf_sub(d, &t, c); } /* d <- a/2 */ UNUSED static void gf_half(gf *d, const gf *a) { unsigned long long d0, d1, d2, d3, tt; unsigned char cc; d0 = (a->v0 >> 1) | (a->v1 << 63); d1 = (a->v1 >> 1) | (a->v2 << 63); d2 = (a->v2 >> 1) | (a->v3 << 63); d3 = (a->v3 >> 1); tt = -(a->v0 & 1); cc = _addcarry_u64(0, d0, tt & (uint64_t)-((MQ - 1) >> 1), (unsigned long long *)&d->v0); cc = _addcarry_u64(cc, d1, tt, (unsigned long long *)&d->v1); cc = _addcarry_u64(cc, d2, tt, (unsigned long long *)&d->v2); (void)_addcarry_u64(cc, d3, tt >> 2, (unsigned long long *)&d->v3); } /* If ctl = 1, then d <- a If ctl = 0, then d <- b ctl MUST be 0 or 1 */ UNUSED static inline void gf_sel2(gf *d, const gf *a, const gf *b, uint64_t ctl) { d->v0 = b->v0 ^ (-ctl & (a->v0 ^ b->v0)); d->v1 = b->v1 ^ (-ctl & (a->v1 ^ b->v1)); d->v2 = b->v2 ^ (-ctl & (a->v2 ^ b->v2)); d->v3 = b->v3 ^ (-ctl & (a->v3 ^ b->v3)); } /* * Set d to a, b or c, depending on flags: * - if fa = 1, then set d to a * - otherwise, if fb = 1, then set d to b * - otherwise, set d to c * Flags fa and fb MUST have value 0 or 1. If both are 1, fa takes * precedence (c is set to a). */ UNUSED static void gf_sel3(gf *d, const gf *a, const gf *b, const gf *c, uint64_t fa, uint64_t fb) { uint64_t ma, mb, mc; ma = -fa; mb = -fb & ~ma; mc = ~(ma | mb); d->v0 = (a->v0 & ma) | (b->v0 & mb) | (c->v0 & mc); d->v1 = (a->v1 & ma) | (b->v1 & mb) | (c->v1 & mc); d->v2 = (a->v2 & ma) | (b->v2 & mb) | (c->v2 & mc); d->v3 = (a->v3 & ma) | (b->v3 & mb) | (c->v3 & mc); } /* d <- 2*a */ UNUSED static void gf_mul2(gf *d, const gf *a) { unsigned long long d0, d1, d2, d3, tt; unsigned char cc; d0 = (a->v0 << 1); d1 = (a->v1 << 1) | (a->v0 >> 63); d2 = (a->v2 << 1) | (a->v1 >> 63); d3 = (a->v3 << 1) | (a->v2 >> 63); tt = (*(int64_t *)&a->v3 >> 63) & (uint64_t)(2 * MQ); cc = _addcarry_u64(0, d0, tt, &d0); cc = _addcarry_u64(cc, d1, 0, (unsigned long long *)&d->v1); cc = _addcarry_u64(cc, d2, 0, (unsigned long long *)&d->v2); cc = _addcarry_u64(cc, d3, 0, (unsigned long long *)&d->v3); d->v0 = d0 + (-(unsigned long long)cc & (2 * MQ)); } /* d <- 4*a */ UNUSED static void gf_mul4(gf *d, const gf *a) { unsigned long long d0, d1, d2, d3, tt; unsigned char cc; d0 = (a->v0 << 2); d1 = (a->v1 << 2) | (a->v0 >> 62); d2 = (a->v2 << 2) | (a->v1 >> 62); d3 = (a->v3 << 2) | (a->v2 >> 62); tt = (a->v3 >> 62) * (uint64_t)(2 * MQ); cc = _addcarry_u64(0, d0, tt, &d0); cc = _addcarry_u64(cc, d1, 0, (unsigned long long *)&d->v1); cc = _addcarry_u64(cc, d2, 0, (unsigned long long *)&d->v2); cc = _addcarry_u64(cc, d3, 0, (unsigned long long *)&d->v3); d->v0 = d0 + (-(unsigned long long)cc & (2 * MQ)); } /* d <- 8*a */ UNUSED static void gf_mul8(gf *d, const gf *a) { unsigned long long d0, d1, d2, d3, tt; unsigned char cc; d0 = (a->v0 << 3); d1 = (a->v1 << 3) | (a->v0 >> 61); d2 = (a->v2 << 3) | (a->v1 >> 61); d3 = (a->v3 << 3) | (a->v2 >> 61); tt = (a->v3 >> 61) * (uint64_t)(2 * MQ); cc = _addcarry_u64(0, d0, tt, &d0); cc = _addcarry_u64(cc, d1, 0, (unsigned long long *)&d->v1); cc = _addcarry_u64(cc, d2, 0, (unsigned long long *)&d->v2); cc = _addcarry_u64(cc, d3, 0, (unsigned long long *)&d->v3); d->v0 = d0 + (-(unsigned long long)cc & (2 * MQ)); } /* d <- 32*a */ UNUSED static void gf_mul32(gf *d, const gf *a) { unsigned long long d0, d1, d2, d3, tt; unsigned char cc; d0 = (a->v0 << 5); d1 = (a->v1 << 5) | (a->v0 >> 59); d2 = (a->v2 << 5) | (a->v1 >> 59); d3 = (a->v3 << 5) | (a->v2 >> 59); tt = (a->v3 >> 59) * (uint64_t)(2 * MQ); cc = _addcarry_u64(0, d0, tt, &d0); cc = _addcarry_u64(cc, d1, 0, (unsigned long long *)&d->v1); cc = _addcarry_u64(cc, d2, 0, (unsigned long long *)&d->v2); cc = _addcarry_u64(cc, d3, 0, (unsigned long long *)&d->v3); d->v0 = d0 + (-(unsigned long long)cc & (2 * MQ)); } /* d <- a*b, with b < 2^32 */ UNUSED static void gf_mul_small(gf *d, const gf *a, uint64_t b) { unsigned long long d0, d1, d2, d3, d4, lo, hi; unsigned char cc; /* Multiplication into d0..d4 */ UMUL64(d0, d1, a->v0, b); UMUL64(d2, d3, a->v2, b); UMUL64(lo, hi, a->v1, b); cc = _addcarry_u64(0, d1, lo, &d1); cc = _addcarry_u64(cc, d2, hi, &d2); UMUL64(lo, d4, a->v3, b); cc = _addcarry_u64(cc, d3, lo, &d3); (void)_addcarry_u64(cc, d4, 0, &d4); /* Fold upper bits. */ d4 = (d4 << 1) | (d3 >> 63); d3 &= 0x7FFFFFFFFFFFFFFF; d4 *= MQ; cc = _addcarry_u64(0, d0, d4, (unsigned long long *)&d->v0); cc = _addcarry_u64(cc, d1, 0, (unsigned long long *)&d->v1); cc = _addcarry_u64(cc, d2, 0, (unsigned long long *)&d->v2); (void)_addcarry_u64(cc, d3, 0, (unsigned long long *)&d->v3); } /* d <- a*b (always inlined) */ FORCE_INLINE static inline void gf_mul_inline(gf *d, const gf *a, const gf *b) { unsigned long long e0, e1, e2, e3, e4, e5, e6, e7; unsigned long long h0, h1, h2, h3; unsigned long long lo, hi, lo2, hi2; unsigned char cc; UMUL64(e0, e1, a->v0, b->v0); UMUL64(e2, e3, a->v1, b->v1); UMUL64(e4, e5, a->v2, b->v2); UMUL64(e6, e7, a->v3, b->v3); UMUL64(lo, hi, a->v0, b->v1); cc = _addcarry_u64(0, e1, lo, &e1); cc = _addcarry_u64(cc, e2, hi, &e2); UMUL64(lo, hi, a->v0, b->v3); cc = _addcarry_u64(cc, e3, lo, &e3); cc = _addcarry_u64(cc, e4, hi, &e4); UMUL64(lo, hi, a->v2, b->v3); cc = _addcarry_u64(cc, e5, lo, &e5); cc = _addcarry_u64(cc, e6, hi, &e6); (void)_addcarry_u64(cc, e7, 0, &e7); UMUL64(lo, hi, a->v1, b->v0); cc = _addcarry_u64(0, e1, lo, &e1); cc = _addcarry_u64(cc, e2, hi, &e2); UMUL64(lo, hi, a->v3, b->v0); cc = _addcarry_u64(cc, e3, lo, &e3); cc = _addcarry_u64(cc, e4, hi, &e4); UMUL64(lo, hi, a->v3, b->v2); cc = _addcarry_u64(cc, e5, lo, &e5); cc = _addcarry_u64(cc, e6, hi, &e6); (void)_addcarry_u64(cc, e7, 0, &e7); UMUL64(lo, hi, a->v0, b->v2); cc = _addcarry_u64(0, e2, lo, &e2); cc = _addcarry_u64(cc, e3, hi, &e3); UMUL64(lo, hi, a->v1, b->v3); cc = _addcarry_u64(cc, e4, lo, &e4); cc = _addcarry_u64(cc, e5, hi, &e5); cc = _addcarry_u64(cc, e6, 0, &e6); (void)_addcarry_u64(cc, e7, 0, &e7); UMUL64(lo, hi, a->v2, b->v0); cc = _addcarry_u64(0, e2, lo, &e2); cc = _addcarry_u64(cc, e3, hi, &e3); UMUL64(lo, hi, a->v3, b->v1); cc = _addcarry_u64(cc, e4, lo, &e4); cc = _addcarry_u64(cc, e5, hi, &e5); cc = _addcarry_u64(cc, e6, 0, &e6); (void)_addcarry_u64(cc, e7, 0, &e7); UMUL64(lo, hi, a->v1, b->v2); UMUL64(lo2, hi2, a->v2, b->v1); cc = _addcarry_u64(0, lo, lo2, &lo); cc = _addcarry_u64(cc, hi, hi2, &hi); (void)_addcarry_u64(cc, 0, 0, &hi2); cc = _addcarry_u64(0, e3, lo, &e3); cc = _addcarry_u64(cc, e4, hi, &e4); cc = _addcarry_u64(cc, e5, hi2, &e5); cc = _addcarry_u64(cc, e6, 0, &e6); (void)_addcarry_u64(cc, e7, 0, &e7); UMUL64(lo, h0, e4, 2 * MQ); cc = _addcarry_u64(0, e0, lo, &e0); UMUL64(lo, h1, e5, 2 * MQ); cc = _addcarry_u64(cc, e1, lo, &e1); UMUL64(lo, h2, e6, 2 * MQ); cc = _addcarry_u64(cc, e2, lo, &e2); UMUL64(lo, h3, e7, 2 * MQ); cc = _addcarry_u64(cc, e3, lo, &e3); (void)_addcarry_u64(cc, 0, h3, &h3); h3 = (h3 << 1) | (e3 >> 63); e3 &= 0x7FFFFFFFFFFFFFFF; cc = _addcarry_u64(0, e0, h3 * MQ, &e0); cc = _addcarry_u64(cc, e1, h0, &e1); cc = _addcarry_u64(cc, e2, h1, &e2); (void)_addcarry_u64(cc, e3, h2, &e3); d->v0 = e0; d->v1 = e1; d->v2 = e2; d->v3 = e3; } /* d <- a*b (never inlined) */ NO_INLINE UNUSED static void gf_mul(gf *d, const gf *a, const gf *b) { gf_mul_inline(d, a, b); } /* d <- a^2 (always inlined) */ FORCE_INLINE static inline void gf_sqr_inline(gf *d, const gf *a) { unsigned long long e0, e1, e2, e3, e4, e5, e6, e7; unsigned long long h0, h1, h2, h3; unsigned long long lo, hi; unsigned char cc; UMUL64(e1, e2, a->v0, a->v1); UMUL64(e3, e4, a->v0, a->v3); UMUL64(e5, e6, a->v2, a->v3); UMUL64(lo, hi, a->v0, a->v2); cc = _addcarry_u64(0, e2, lo, &e2); cc = _addcarry_u64(cc, e3, hi, &e3); UMUL64(lo, hi, a->v1, a->v3); cc = _addcarry_u64(cc, e4, lo, &e4); cc = _addcarry_u64(cc, e5, hi, &e5); (void)_addcarry_u64(cc, e6, 0, &e6); UMUL64(lo, hi, a->v1, a->v2); cc = _addcarry_u64(0, e3, lo, &e3); cc = _addcarry_u64(cc, e4, hi, &e4); cc = _addcarry_u64(cc, e5, 0, &e5); (void)_addcarry_u64(cc, e6, 0, &e6); /* There cannot be extra carry here because the partial sum is necessarily lower than 2^448 at this point. */ e7 = e6 >> 63; e6 = (e6 << 1) | (e5 >> 63); e5 = (e5 << 1) | (e4 >> 63); e4 = (e4 << 1) | (e3 >> 63); e3 = (e3 << 1) | (e2 >> 63); e2 = (e2 << 1) | (e1 >> 63); e1 = e1 << 1; UMUL64(e0, hi, a->v0, a->v0); cc = _addcarry_u64(0, e1, hi, &e1); UMUL64(lo, hi, a->v1, a->v1); cc = _addcarry_u64(cc, e2, lo, &e2); cc = _addcarry_u64(cc, e3, hi, &e3); UMUL64(lo, hi, a->v2, a->v2); cc = _addcarry_u64(cc, e4, lo, &e4); cc = _addcarry_u64(cc, e5, hi, &e5); UMUL64(lo, hi, a->v3, a->v3); cc = _addcarry_u64(cc, e6, lo, &e6); (void)_addcarry_u64(cc, e7, hi, &e7); /* Reduction */ UMUL64(lo, h0, e4, 2 * MQ); cc = _addcarry_u64(0, e0, lo, &e0); UMUL64(lo, h1, e5, 2 * MQ); cc = _addcarry_u64(cc, e1, lo, &e1); UMUL64(lo, h2, e6, 2 * MQ); cc = _addcarry_u64(cc, e2, lo, &e2); UMUL64(lo, h3, e7, 2 * MQ); cc = _addcarry_u64(cc, e3, lo, &e3); (void)_addcarry_u64(cc, 0, h3, &h3); h3 = (h3 << 1) | (e3 >> 63); e3 &= 0x7FFFFFFFFFFFFFFF; cc = _addcarry_u64(0, e0, h3 * MQ, &e0); cc = _addcarry_u64(cc, e1, h0, &e1); cc = _addcarry_u64(cc, e2, h1, &e2); (void)_addcarry_u64(cc, e3, h2, &e3); d->v0 = e0; d->v1 = e1; d->v2 = e2; d->v3 = e3; } /* d <- a^2 (never inlined) */ NO_INLINE UNUSED static void gf_sqr(gf *d, const gf *a) { gf_sqr_inline(d, a); } /* d <- a^(2^num) (repeated squarings, always inlined) */ FORCE_INLINE static void gf_sqr_x_inline(gf *d, const gf *a, long num) { gf t; t = *a; do { gf_sqr_inline(&t, &t); } while (-- num > 0); *d = t; } /* d <- a^(2^num) (repeated squarings, never inlined) */ NO_INLINE UNUSED static void gf_sqr_x(gf *d, const gf *a, long num) { gf_sqr_x_inline(d, a, num); } /* * Normalize a value to 0..p-1. */ UNUSED static void gf_normalize(gf *d, const gf *a) { unsigned long long d0, d1, d2, d3, e; unsigned char cc; /* * If top bit is set, propagate it. */ e = -(unsigned long long)(a->v3 >> 63); cc = _addcarry_u64(0, a->v0, e & MQ, &d0); cc = _addcarry_u64(cc, a->v1, 0, &d1); cc = _addcarry_u64(cc, a->v2, 0, &d2); (void)_addcarry_u64(cc, a->v3, e << 63, &d3); /* * Value is now at most 2^255+MQ-1. Subtract p, and add it back * if the result is negative. */ cc = _subborrow_u64(0, d0, (unsigned long long)-MQ, &d0); cc = _subborrow_u64(cc, d1, (unsigned long long)-1, &d1); cc = _subborrow_u64(cc, d2, (unsigned long long)-1, &d2); cc = _subborrow_u64(cc, d3, (unsigned long long)-1 >> 1, &d3); e = -(unsigned long long)cc; cc = _addcarry_u64(0, d0, e & -MQ, (unsigned long long *)&d->v0); cc = _addcarry_u64(cc, d1, e, (unsigned long long *)&d->v1); cc = _addcarry_u64(cc, d2, e, (unsigned long long *)&d->v2); (void)_addcarry_u64(cc, d3, e >> 1, (unsigned long long *)&d->v3); } /* * Compare 'a' with zero; returned value is 1 if the value is zero (as * a field element), 0 otherwise. */ UNUSED static uint64_t gf_iszero(const gf *a) { unsigned long long t0, t1, t2; /* * Since values are over 256 bits, there are three possible * representations for 0: 0, p and 2*p. */ t0 = a->v0 | a->v1 | a->v2 | a->v3; t1 = (a->v0 + MQ) | ~a->v1 | ~a->v2 | (a->v3 ^ 0x7FFFFFFFFFFFFFFF); t2 = (a->v0 + (2 * MQ)) | ~a->v1 | ~a->v2 | ~a->v3; /* * Value is zero if and only if one of t0, t1 or t2 is zero. */ return 1 - (((t0 | -t0) & (t1 | -t1) & (t2 | -t2)) >> 63); } /* * Compare two values as field elements; returned value is 1 on equality, * 0 otherwise. */ UNUSED static uint64_t gf_eq(const gf *a, const gf *b) { gf t; gf_sub(&t, a, b); return gf_iszero(&t); } /* * Compute (a*f+v*g)/2^31. Parameters f and g are provided with an * unsigned type, but they are signed integers in the -2^31..+2^31 range. * Values a, b and d are not field elements, but 255-bit integers (value * is in 0..2^255-1, top bit is zero). The division by 2^31 is assumed to * be exact (low 31 bits of a*f+v*g are dropped). The result is assumed to * fit in 256 bits in signed two's complement notation (truncation is * applied on higher bits). * * If the result turns out to be negative, then it is negated. Returned * value is 1 if the result was negated, 0 otherwise. */ static uint64_t s256_lin_div31_abs(gf *d, const gf *a, const gf *b, unsigned long long f, unsigned long long g) { gf ta, tb; unsigned long long sf, sg, d0, d1, d2, d3, t; unsigned char cc; /* * If f < 0, replace f with -f but keep the sign in sf. * Similarly for g. */ sf = f >> 63; f = (f ^ -sf) + sf; sg = g >> 63; g = (g ^ -sg) + sg; /* * Apply signs sf and sg to a and b, respectively. */ cc = _addcarry_u64(0, a->v0 ^ -sf, sf, (unsigned long long *)&ta.v0); cc = _addcarry_u64(cc, a->v1 ^ -sf, 0, (unsigned long long *)&ta.v1); cc = _addcarry_u64(cc, a->v2 ^ -sf, 0, (unsigned long long *)&ta.v2); cc = _addcarry_u64(cc, a->v3 ^ -sf, 0, (unsigned long long *)&ta.v3); cc = _addcarry_u64(0, b->v0 ^ -sg, sg, (unsigned long long *)&tb.v0); cc = _addcarry_u64(cc, b->v1 ^ -sg, 0, (unsigned long long *)&tb.v1); cc = _addcarry_u64(cc, b->v2 ^ -sg, 0, (unsigned long long *)&tb.v2); cc = _addcarry_u64(cc, b->v3 ^ -sg, 0, (unsigned long long *)&tb.v3); /* * Now that f and g are nonnegative, compute a*f+b*g into * d0:d1:d2:d3:t. Since f and g are at most 2^31, we can * add two 128-bit products with no overflow (they are actually * 95 bits each at most). */ UMUL64x2(d0, t, ta.v0, f, tb.v0, g); UMUL64x2_ADD(d1, t, ta.v1, f, tb.v1, g, t); UMUL64x2_ADD(d2, t, ta.v2, f, tb.v2, g, t); UMUL64x2_ADD(d3, t, ta.v3, f, tb.v3, g, t); /* * Don't forget the signs: if a < 0, then the result is * overestimated by 2^256*f; similarly, if b < 0, then the * result is overestimated by 2^256*g. We thus must subtract * 2^256*(sa*f+sb*g), where sa and sb are the signs of a and b, * respectively (1 if negative, 0 otherwise). */ t -= -(unsigned long long)(ta.v3 >> 63) & f; t -= -(unsigned long long)(tb.v3 >> 63) & g; /* * Apply the shift. */ d0 = (d0 >> 31) | (d1 << 33); d1 = (d1 >> 31) | (d2 << 33); d2 = (d2 >> 31) | (d3 << 33); d3 = (d3 >> 31) | (t << 33); /* * Perform conditional negation, if the result is negative. */ t >>= 63; cc = _addcarry_u64(0, d0 ^ -t, t, (unsigned long long *)&d->v0); cc = _addcarry_u64(cc, d1 ^ -t, 0, (unsigned long long *)&d->v1); cc = _addcarry_u64(cc, d2 ^ -t, 0, (unsigned long long *)&d->v2); (void)_addcarry_u64(cc, d3 ^ -t, 0, (unsigned long long *)&d->v3); return t; } /* * Compute u*f+v*g (modulo p). Parameters f and g are provided with * an unsigned type, but they are signed integers in the -2^62..+2^62 range. */ static void gf_lin(gf *d, const gf *u, const gf *v, unsigned long long f, unsigned long long g) { gf tu, tv; unsigned long long sf, sg, d0, d1, d2, d3, t, lo, hi; unsigned char cc; /* * If f < 0, replace f with -f but keep the sign in sf. * Similarly for g. */ sf = f >> 63; f = (f ^ -sf) + sf; sg = g >> 63; g = (g ^ -sg) + sg; /* * Apply signs sf and sg to u and v. */ gf_condneg(&tu, u, sf); gf_condneg(&tv, v, sg); /* * Since f <= 2^62 and g <= 2^62, we can add 128-bit products: they * fit on 126 bits each. */ UMUL64x2(d0, t, tu.v0, f, tv.v0, g); UMUL64x2_ADD(d1, t, tu.v1, f, tv.v1, g, t); UMUL64x2_ADD(d2, t, tu.v2, f, tv.v2, g, t); UMUL64x2_ADD(d3, t, tu.v3, f, tv.v3, g, t); /* * Upper word t can be up to 63 bits. */ UMUL64(lo, hi, t, 2 * MQ); cc = _addcarry_u64(0, d0, lo, &d0); cc = _addcarry_u64(cc, d1, hi, &d1); cc = _addcarry_u64(cc, d2, 0, &d2); cc = _addcarry_u64(cc, d3, 0, &d3); /* * There could be a carry, but in that case, the folding won't * propagate beyond the second limb. */ cc = _addcarry_u64(0, d0, -(unsigned long long)cc & (2 * MQ), &d0); (void)_addcarry_u64(cc, d1, 0, &d1); d->v0 = d0; d->v1 = d1; d->v2 = d2; d->v3 = d3; } /* * Inversion in the field: d <- 1/y * If y = 0, then d is set to zero. * Returned value is 1 if the value was invertible, 0 otherwise. */ UNUSED static uint64_t gf_inv(gf *d, const gf *y) { gf a, b, u, v; unsigned long long f0, f1, g0, g1, xa, xb, fg0, fg1; unsigned long long nega, negb; int i, j; /* * Extended binary GCD: * * a <- y * b <- q * u <- 1 * v <- 0 * * a and b are nonnnegative integers (in the 0..q range). u * and v are integers modulo q. * * Invariants: * a = y*u mod q * b = y*v mod q * b is always odd * * At each step: * if a is even, then: * a <- a/2, u <- u/2 mod q * else: * if a < b: * (a, u, b, v) <- (b, v, a, u) * a <- (a-b)/2, u <- (u-v)/2 mod q * * At one point, value a reaches 0; it will then stay there * (all subsequent steps will only keep a at zero). The value * of b is then GCD(y, p), i.e. 1 if y is invertible; value v * is then the inverse of y modulo p. * * If y = 0, then a is initially at zero and stays there, and * v is unchanged. The function then returns 0 as "inverse" of * zero, which is the desired behaviour; therefore, no corrective * action is necessary. * * It can be seen that each step will decrease the size of one of * a and b by at least 1 bit; thus, starting with two values of * at most 255 bits each, 509 iterations are always sufficient. * * * In practice, we optimize this code in the following way: * - We do iterations by group of 31. * - In each group, we use _approximations_ of a and b that * fit on 64 bits each: * Let n = max(len(a), len(b)). * If n <= 64, then xa = na and xb = nb. * Otherwise: * xa = (a mod 2^31) + 2^31*floor(a / 2^(n - 33)) * xb = (b mod 2^31) + 2^31*floor(b / 2^(n - 33)) * I.e. we keep the same low 31 bits, but we remove all the * "middle" bits to just keep the higher bits. At least one * of the two values xa and xb will have maximum length (64 bits) * if either of a or b exceeds 64 bits. * - We record which subtract and swap we did into update * factors, which we apply en masse to a, b, u and v after * the 31 iterations. * * Since we kept the correct low 31 bits, all the "subtract or * not" decisions are correct, but the "swap or not swap" might * be wrong, since these use the difference between the two * values, and we only have approximations thereof. A consequence * is that after the update, a and/or b may be negative. If a < 0, * we negate it, and also negate u (which we do by negating the * update factors f0 and g0 before applying them to compute the * new value of u); similary for b and v. * * It can be shown that the 31 iterations, along with the * conditional negation, ensure that len(a)+len(b) is still * reduced by at least 31 bits (compared with the classic binary * GCD, the use of the approximations may make the code "miss one * bit", but the conditional subtraction regains it). Thus, * 509 iterations are sufficient in total. As explained later on, * we can skip the final iteration as well. */ gf_normalize(&a, y); b = GF_P; u = GF_ONE; v = GF_ZERO; /* * Generic loop first does 15*31 = 465 iterations. */ for (i = 0; i < 15; i ++) { unsigned long long m1, m2, m3, tnz1, tnz2, tnz3; unsigned long long tnzm, tnza, tnzb, snza, snzb; unsigned long long s, sm; gf na, nb, nu, nv; /* * Get approximations of a and b over 64 bits: * - If len(a) <= 64 and len(b) <= 64, then we just * use the value (low limb). * - Otherwise, with n = max(len(a), len(b)), we use: * (a mod 2^31) + 2^31*(floor(a / 2^(n-33))) * (b mod 2^31) + 2^31*(floor(b / 2^(n-33))) * I.e. we remove the "middle bits". */ m3 = a.v3 | b.v3; m2 = a.v2 | b.v2; m1 = a.v1 | b.v1; tnz3 = -((m3 | -m3) >> 63); tnz2 = -((m2 | -m2) >> 63) & ~tnz3; tnz1 = -((m1 | -m1) >> 63) & ~tnz3 & ~tnz2; tnzm = (m3 & tnz3) | (m2 & tnz2) | (m1 & tnz1); tnza = (a.v3 & tnz3) | (a.v2 & tnz2) | (a.v1 & tnz1); tnzb = (b.v3 & tnz3) | (b.v2 & tnz2) | (b.v1 & tnz1); snza = (a.v2 & tnz3) | (a.v1 & tnz2) | (a.v0 & tnz1); snzb = (b.v2 & tnz3) | (b.v1 & tnz2) | (b.v0 & tnz1); /* * If both len(a) <= 64 and len(b) <= 64, then: * tnzm = 0 * tnza = 0, snza = 0, tnzb = 0, snzb = 0 * Otherwise: * tnzm != 0, length yields value of n * tnza contains the top limb of a, snza the second limb * tnzb contains the top limb of b, snzb the second limb * * We count the number of leading zero bits in tnzm: * - If s <= 31, then the top 31 bits can be extracted * from tnza and tnzb alone. * - If 32 <= s <= 63, then we need some bits from snza * as well. * * We rely on the fact shifts don't reveal the shift count * through side channels. This would not have been true on * the Pentium IV, but it is true on all known x86 CPU that * have 64-bit support and implement the LZCNT opcode. */ s = _lzcnt_u64(tnzm); sm = -(unsigned long long)(s >> 5); tnza ^= sm & (tnza ^ ((tnza << 32) | (snza >> 32))); tnzb ^= sm & (tnzb ^ ((tnzb << 32) | (snzb >> 32))); s &= 31; tnza <<= s; tnzb <<= s; /* * At this point: * - If len(a) <= 64 and len(b) <= 64, then: * tnza = 0 * tnzb = 0 * tnz1 = tnz2 = tnz3 = 0 * - Otherwise, we need to use the top 33 bits of tnza * and tnzb in combination with the low 31 bits of * a.v0 and b.v0, respectively. */ tnza |= a.v0 & ~(tnz1 | tnz2 | tnz3); tnzb |= b.v0 & ~(tnz1 | tnz2 | tnz3); xa = (a.v0 & 0x7FFFFFFF) | (tnza & 0xFFFFFFFF80000000); xb = (b.v0 & 0x7FFFFFFF) | (tnzb & 0xFFFFFFFF80000000); /* * We can now run the binary GCD on xa and xb for 31 * rounds. */ fg0 = (uint64_t)1; fg1 = (uint64_t)1 << 32; for (j = 0; j < 31; j ++) { uint64_t a_odd, swap; unsigned long long t; a_odd = -(uint64_t)(xa & 1); swap = a_odd & -(uint64_t)_subborrow_u64(0, xa, xb, &t); t = swap & (xa ^ xb); xa ^= t; xb ^= t; t = swap & (fg0 ^ fg1); fg0 ^= t; fg1 ^= t; xa -= a_odd & xb; fg0 -= a_odd & fg1; xa >>= 1; fg1 <<= 1; } fg0 += 0x7FFFFFFF7FFFFFFF; fg1 += 0x7FFFFFFF7FFFFFFF; f0 = (fg0 & 0xFFFFFFFF) - (uint64_t)0x7FFFFFFF; g0 = (fg0 >> 32) - (uint64_t)0x7FFFFFFF; f1 = (fg1 & 0xFFFFFFFF) - (uint64_t)0x7FFFFFFF; g1 = (fg1 >> 32) - (uint64_t)0x7FFFFFFF; /* * We now need to propagate updates to a, b, u and v. */ nega = s256_lin_div31_abs(&na, &a, &b, f0, g0); negb = s256_lin_div31_abs(&nb, &a, &b, f1, g1); f0 = (f0 ^ -nega) + nega; g0 = (g0 ^ -nega) + nega; f1 = (f1 ^ -negb) + negb; g1 = (g1 ^ -negb) + negb; gf_lin(&nu, &u, &v, f0, g0); gf_lin(&nv, &u, &v, f1, g1); a = na; b = nb; u = nu; v = nv; } /* * At that point, if y is invertible, then the final GCD is 1, * and len(a) + len(b) <= 45, so it is known that the values * fully fit in a single register each. We can do the remaining * 44 iterations in one go (they are exact, no approximation * here). In fact, we can content ourselves with 43 iterations, * because when arriving at the last iteration, we know that a = 0 * or 1 and b = 1 (the final state of the algorithm is that a = 0 * and b is the GCD of y and q), so there would be no swap. Since * we only care about the update factors f1 and g1, we can simply * avoid the final iteration. * * The update values f1 and g1, for v, will be up to 2^43 (in * absolute value) but this is supported by gf_lin(). * * If y is zero, then none of the iterations changes anything * to b and v, and therefore v = 0 at this point, which is the * value we want to obtain in that case. */ xa = a.v0; xb = b.v0; /* * We first do the first 31 iterations with two update factors * paired in the same variable. */ fg0 = (uint64_t)1; fg1 = (uint64_t)1 << 32; for (j = 0; j < 31; j ++) { uint64_t a_odd, swap; unsigned long long t; a_odd = -(uint64_t)(xa & 1); swap = a_odd & -(uint64_t)_subborrow_u64(0, xa, xb, &t); t = swap & (xa ^ xb); xa ^= t; xb ^= t; t = swap & (fg0 ^ fg1); fg0 ^= t; fg1 ^= t; xa -= a_odd & xb; fg0 -= a_odd & fg1; xa >>= 1; fg1 <<= 1; } /* * Pairing the update factors in the same variable works only for * up to 31 iterations; we split them into separate variables * to finish the work with 12 extra iterations. */ fg0 += 0x7FFFFFFF7FFFFFFF; f0 = (fg0 & 0xFFFFFFFF) - (uint64_t)0x7FFFFFFF; g0 = (fg0 >> 32) - (uint64_t)0x7FFFFFFF; fg1 += 0x7FFFFFFF7FFFFFFF; f1 = (fg1 & 0xFFFFFFFF) - (uint64_t)0x7FFFFFFF; g1 = (fg1 >> 32) - (uint64_t)0x7FFFFFFF; for (j = 0; j < 12; j ++) { uint64_t a_odd, swap; unsigned long long t; a_odd = -(uint64_t)(xa & 1); swap = a_odd & -(uint64_t)_subborrow_u64(0, xa, xb, &t); t = swap & (xa ^ xb); xa ^= t; xb ^= t; t = swap & (f0 ^ f1); f0 ^= t; f1 ^= t; t = swap & (g0 ^ g1); g0 ^= t; g1 ^= t; xa -= a_odd & xb; f0 -= a_odd & f1; g0 -= a_odd & g1; xa >>= 1; f1 <<= 1; g1 <<= 1; } gf_lin(&v, &u, &v, f1, g1); /* * We did 31*15+43 = 508 iterations, and each injected a factor 2, * thus we must divide by 2^508 (mod q). * * Result is correct if source operand was invertible, i.e. * distinct from zero (since all non-zero values are invertible * modulo a prime integer); the inverse is then also non-zero. * If the source was zero, then the result is zero as well. We * can thus test d instead of a. */ gf_mul_inline(d, &v, &GF_INVT508); return gf_iszero(d) ^ 1; } /* * Legendre symbol computation. Return value: * 1 if y != 0 and is a quadratic residue * -1 if y != 0 and is not a quadratic residue * 0 if y == 0 */ UNUSED static int64_t gf_legendre(const gf *y) { /* * Algorithm is basically the same as the binary GCD, with the * following differences: * * - We do not keep track or update the 'u' and 'v' values. * - In the inner loop, we need to access the three bottom bits * of 'b'; the last two iterations do not necessarily have * these values available, so we must compute the updated a * and b (low words only) at some point to get the correct bits. */ gf a, b; unsigned long long f0, f1, g0, g1, xa, xb, fg0, fg1, ls, a0, b0; unsigned long long nega; int i, j; gf_normalize(&a, y); b = GF_P; ls = 0; /* * Generic loop first does 15*31 = 465 iterations. */ for (i = 0; i < 15; i ++) { unsigned long long m1, m2, m3, tnz1, tnz2, tnz3; unsigned long long tnzm, tnza, tnzb, snza, snzb; unsigned long long s, sm; gf na, nb; /* * Get approximations of a and b over 64 bits: * - If len(a) <= 64 and len(b) <= 64, then we just * use the value (low limb). * - Otherwise, with n = max(len(a), len(b)), we use: * (a mod 2^31) + 2^31*(floor(a / 2^(n-33))) * (b mod 2^31) + 2^31*(floor(b / 2^(n-33))) * I.e. we remove the "middle bits". */ m3 = a.v3 | b.v3; m2 = a.v2 | b.v2; m1 = a.v1 | b.v1; tnz3 = -((m3 | -m3) >> 63); tnz2 = -((m2 | -m2) >> 63) & ~tnz3; tnz1 = -((m1 | -m1) >> 63) & ~tnz3 & ~tnz2; tnzm = (m3 & tnz3) | (m2 & tnz2) | (m1 & tnz1); tnza = (a.v3 & tnz3) | (a.v2 & tnz2) | (a.v1 & tnz1); tnzb = (b.v3 & tnz3) | (b.v2 & tnz2) | (b.v1 & tnz1); snza = (a.v2 & tnz3) | (a.v1 & tnz2) | (a.v0 & tnz1); snzb = (b.v2 & tnz3) | (b.v1 & tnz2) | (b.v0 & tnz1); /* * If both len(a) <= 64 and len(b) <= 64, then: * tnzm = 0 * tnza = 0, snza = 0, tnzb = 0, snzb = 0 * tnzm = 0 * Otherwise: * tnzm != 0, length yields value of n * tnza contains the top limb of a, snza the second limb * tnzb contains the top limb of b, snzb the second limb * * We count the number of leading zero bits in tnzm: * - If s <= 31, then the top 31 bits can be extracted * from tnza and tnzb alone. * - If 32 <= s <= 63, then we need some bits from snza * as well. * * We rely on the fact shifts don't reveal the shift count * through side channels. This would not have been true on * the Pentium IV, but it is true on all known x86 CPU that * have 64-bit support and implement the LZCNT opcode. */ s = _lzcnt_u64(tnzm); sm = -((unsigned long long)(31 - s) >> 63); tnza ^= sm & (tnza ^ ((tnza << 32) | (snza >> 32))); tnzb ^= sm & (tnzb ^ ((tnzb << 32) | (snzb >> 32))); s -= 32 & sm; tnza <<= s; tnzb <<= s; /* * At this point: * - If len(a) <= 64 and len(b) <= 64, then: * tnza = 0 * tnzb = 0 * tnz1 = tnz2 = tnz3 = 0 * - Otherwise, we need to use the top 33 bits of tnza * and tnzb in combination with the low 31 bits of * a.v0 and b.v0, respectively. */ tnza |= a.v0 & ~(tnz1 | tnz2 | tnz3); tnzb |= b.v0 & ~(tnz1 | tnz2 | tnz3); xa = (a.v0 & 0x7FFFFFFF) | (tnza & 0xFFFFFFFF80000000); xb = (b.v0 & 0x7FFFFFFF) | (tnzb & 0xFFFFFFFF80000000); /* * We can now run the binary GCD on xa and xb for 29 * rounds. */ fg0 = (uint64_t)1; fg1 = (uint64_t)1 << 32; for (j = 0; j < 29; j ++) { uint64_t a_odd, swap; unsigned long long t; a_odd = -(uint64_t)(xa & 1); swap = a_odd & -(uint64_t)_subborrow_u64(0, xa, xb, &t); ls += swap & ((xa & xb) >> 1); t = swap & (xa ^ xb); xa ^= t; xb ^= t; t = swap & (fg0 ^ fg1); fg0 ^= t; fg1 ^= t; xa -= a_odd & xb; fg0 -= a_odd & fg1; xa >>= 1; fg1 <<= 1; ls += (xb + 2) >> 2; } /* * For the last two iterations, we need to recompute the * updated a and b (low words only) to get their low bits. */ f0 = ((fg0 + 0x7FFFFFFF7FFFFFFF) & 0xFFFFFFFF) - (uint64_t)0x7FFFFFFF; g0 = ((fg0 + 0x7FFFFFFF7FFFFFFF) >> 32) - (uint64_t)0x7FFFFFFF; f1 = ((fg1 + 0x7FFFFFFF7FFFFFFF) & 0xFFFFFFFF) - (uint64_t)0x7FFFFFFF; g1 = ((fg1 + 0x7FFFFFFF7FFFFFFF) >> 32) - (uint64_t)0x7FFFFFFF; a0 = (a.v0 * f0 + b.v0 * g0) >> 29; b0 = (a.v0 * f1 + b.v0 * g1) >> 29; for (j = 0; j < 2; j ++) { uint64_t a_odd, swap; unsigned long long t; a_odd = -(uint64_t)(xa & 1); swap = a_odd & -(uint64_t)_subborrow_u64(0, xa, xb, &t); ls += swap & ((a0 & b0) >> 1); t = swap & (xa ^ xb); xa ^= t; xb ^= t; t = swap & (fg0 ^ fg1); fg0 ^= t; fg1 ^= t; t = swap & (a0 ^ b0); a0 ^= t; b0 ^= t; xa -= a_odd & xb; fg0 -= a_odd & fg1; a0 -= a_odd & b0; xa >>= 1; fg1 <<= 1; a0 >>= 1; ls += (b0 + 2) >> 2; } fg0 += 0x7FFFFFFF7FFFFFFF; fg1 += 0x7FFFFFFF7FFFFFFF; f0 = (fg0 & 0xFFFFFFFF) - (uint64_t)0x7FFFFFFF; g0 = (fg0 >> 32) - (uint64_t)0x7FFFFFFF; f1 = (fg1 & 0xFFFFFFFF) - (uint64_t)0x7FFFFFFF; g1 = (fg1 >> 32) - (uint64_t)0x7FFFFFFF; /* * We now need to propagate updates to a and b. */ nega = s256_lin_div31_abs(&na, &a, &b, f0, g0); s256_lin_div31_abs(&nb, &a, &b, f1, g1); ls += nega & (nb.v0 >> 1); a = na; b = nb; } /* * At that point, if y is invertible, then the final GCD is 1, * and len(a) + len(b) <= 45, so it is known that the values * fully fit in a single register each. We can do the remaining * 44 iterations in one go. We do not need to compute update * factors. Since values are exact, we always have the proper * bit values. We can even stop at 43 iterations, because at the * last iteration, b = 1 and a = 0 or 1; in either case, no * modification of the Legendre symbol will happen. */ xa = a.v0; xb = b.v0; for (j = 0; j < 43; j ++) { uint64_t a_odd, swap; unsigned long long t; a_odd = -(uint64_t)(xa & 1); swap = a_odd & -(uint64_t)_subborrow_u64(0, xa, xb, &t); ls += swap & ((xa & xb) >> 1); t = swap & (xa ^ xb); xa ^= t; xb ^= t; xa -= a_odd & xb; xa >>= 1; ls += (xb + 2) >> 2; } /* * At this point, if y != 0, then the low bit of ls contains the * QR status (0 = square, 1 = non-square). If y == 0, then we * replace the output value with zero, as per the API. */ return (int64_t)((uint64_t)(1 - ((int64_t)(ls & 1) << 1)) & (gf_iszero(y) - 1)); } static unsigned long long dec64le(const uint8_t *buf) { return (unsigned long long)buf[0] | ((unsigned long long)buf[1] << 8) | ((unsigned long long)buf[2] << 16) | ((unsigned long long)buf[3] << 24) | ((unsigned long long)buf[4] << 32) | ((unsigned long long)buf[5] << 40) | ((unsigned long long)buf[6] << 48) | ((unsigned long long)buf[7] << 56); } static void enc64le(uint8_t *buf, unsigned long long x) { buf[0] = (uint8_t)x; buf[1] = (uint8_t)(x >> 8); buf[2] = (uint8_t)(x >> 16); buf[3] = (uint8_t)(x >> 24); buf[4] = (uint8_t)(x >> 32); buf[5] = (uint8_t)(x >> 40); buf[6] = (uint8_t)(x >> 48); buf[7] = (uint8_t)(x >> 56); } /* * Decode a value from 32 bytes. Decoding always succeeds. Returned value * is 1 if the value was normalized (in the 0..p-1 range), 0 otherwise. */ UNUSED static uint64_t gf_decode(gf *d, const void *src) { const uint8_t *buf; unsigned long long t; unsigned char cc; buf = src; d->v0 = dec64le(buf); d->v1 = dec64le(buf + 8); d->v2 = dec64le(buf + 16); d->v3 = dec64le(buf + 24); cc = _subborrow_u64(0, d->v0, GF_P.v0, &t); cc = _subborrow_u64(cc, d->v1, GF_P.v1, &t); cc = _subborrow_u64(cc, d->v2, GF_P.v2, &t); cc = _subborrow_u64(cc, d->v3, GF_P.v3, &t); return (uint64_t)cc; } /* * Decode a value from bytes, with modular reduction. */ UNUSED static void gf_decode_reduce(gf *d, const void *src, size_t len) { const uint8_t *buf; unsigned long long d0, d1, d2, d3; buf = src; if (len == 0) { d->v0 = 0; d->v1 = 0; d->v2 = 0; d->v3 = 0; return; } else if ((len & 31) != 0) { uint8_t tmp[32]; size_t n; n = len & 31; len -= n; memcpy(tmp, buf + len, n); memset(tmp + n, 0, (sizeof tmp) - n); d0 = dec64le(tmp); d1 = dec64le(tmp + 8); d2 = dec64le(tmp + 16); d3 = dec64le(tmp + 24); } else { len -= 32; d0 = dec64le(buf + len); d1 = dec64le(buf + len + 8); d2 = dec64le(buf + len + 16); d3 = dec64le(buf + len + 24); } while (len > 0) { unsigned long long e0, e1, e2, e3; unsigned long long h0, h1, h2, h3; unsigned char cc; len -= 32; e0 = dec64le(buf + len); e1 = dec64le(buf + len + 8); e2 = dec64le(buf + len + 16); e3 = dec64le(buf + len + 24); UMUL64(d0, h0, d0, 2 * MQ); cc = _addcarry_u64(0, d0, e0, &d0); UMUL64(d1, h1, d1, 2 * MQ); cc = _addcarry_u64(cc, d1, e1, &d1); UMUL64(d2, h2, d2, 2 * MQ); cc = _addcarry_u64(cc, d2, e2, &d2); UMUL64(d3, h3, d3, 2 * MQ); cc = _addcarry_u64(cc, d3, e3, &d3); (void)_addcarry_u64(cc, 0, h3, &h3); h3 = (h3 << 1) | (d3 >> 63); d3 &= 0x7FFFFFFFFFFFFFFF; cc = _addcarry_u64(0, d0, h3 * MQ, &d0); cc = _addcarry_u64(cc, d1, h0, &d1); cc = _addcarry_u64(cc, d2, h1, &d2); (void)_addcarry_u64(cc, d3, h2, &d3); } d->v0 = d0; d->v1 = d1; d->v2 = d2; d->v3 = d3; } /* * Encode a value into 32 bytes. Encoding is always normalized; a * consequence is that the highest bit of the last byte is always 0. */ UNUSED static void gf_encode(void *dst, const gf *a) { gf t; uint8_t *buf; gf_normalize(&t, a); buf = dst; enc64le(buf, t.v0); enc64le(buf + 8, t.v1); enc64le(buf + 16, t.v2); enc64le(buf + 24, t.v3); }
C
// Scott Giorlando // Assignment 1 // need these include files #include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <sys/resource.h> typedef union { int exit_status; struct { unsigned sig_num: 7; unsigned core_dmp: 1; unsigned exit_num: 8; } parts; } LE_Wait_Status; int counter = 0, counter_2G = 0; void sig_handler(int signum) { printf("\nCHILD PROCESS: Awake in handler.\n"); if (execl("A1", "", (char*)NULL) == -1) { perror("\nError: Execl() failure!\n\n"); exit(7); } } int main(void) { // some local variables LE_Wait_Status exit_union; pid_t pid, ppid, pid_child; int ruid, rgid, euid, egid; int priority; char msg_buf[100]; int msg_pipe[2]; char str_buf[] = "Test String\n"; // use the pipe() system call to create the pipe if(pipe(msg_pipe) == -1) { perror("Error: Failed in Parent pipe creation:"); exit(7); } // use various system calls to collect and print process details printf("\nThis is the Parent process report:\n"); pid = getpid(); ppid = getppid(); ruid = getuid(); euid = geteuid(); rgid = getgid(); egid = getegid(); priority = getpriority(PRIO_PROCESS, 0); //Prints out the parent program ID's printf("\nPARENT PROG: Process ID is:\t\t%d\n", pid); printf("PARENT PROC: Process parent ID is:\t%d\n", ppid); printf("PARENT PROC: Real UID is:\t\t%d\n", ruid); printf("PARENT PROC: Real GID is:\t\t%d\n", rgid); printf("PARENT PROC: Effective UID is:\t\t%d\n", euid); printf("PARENT PROC: Effective GID is:\t\t%d\n", egid); printf("PARENT PROC: Process priority is:\t%d\n", priority); printf("\nPARENT PROC: will now create child, write pipe,\n \ and do a normal termination\n"); sprintf(msg_buf, "This is the pipe message from the parent with PID %d", pid); switch (pid_child = fork()) { case -1: perror("Failed in fork call/creation of child: "); exit(1); case 0: { sigset_t mask, proc_mask; struct sigaction new_action; sigemptyset(&proc_mask); sigprocmask(SIG_SETMASK, &proc_mask, NULL); sigemptyset(&mask); new_action.sa_mask = mask; new_action.sa_handler = sig_handler; new_action.sa_flags = 0; if(sigaction(SIGTERM, &new_action, NULL) == -1) { perror("\nError: Sigaction failure\n"); exit(7); } printf("\nThis is the Child process report:\n"); pid = getpid(); ppid = getppid(); ruid = getuid(); euid = geteuid(); rgid = getgid(); egid = getegid(); priority = getpriority(PRIO_PROCESS, 0); printf("\nCHILD PROC: Process ID is:\t\t%d\n", pid); printf("CHILD PROC: Process parent ID is:\t%d\n", ppid); printf("CHILD PROC: Real UID is:\t\t%d\n", ruid); printf("CHILD PROC: Real GID is:\t\t%d\n", rgid); printf("CHILD PROC: Effective UID is:\t\t%d\n", euid); printf("CHILD PROC: Effective GID is:\t\t%d\n", egid); printf("CHILD PROC: Process priority is:\t%d\n", priority); close(msg_pipe[0]); if(write(msg_pipe[1], str_buf, (strlen(str_buf) + 1)) == - 1) { perror("\nError: Write failure\n"); exit(7); } while (counter_2G < 10) { counter++; if(counter < 0) { counter = 0; counter_2G++; } } write(1, "CHILD: Timed out after 20 Billion iterations\n", 51); exit(7); } default: close(msg_pipe[1]); if(read(msg_pipe[0], msg_buf, sizeof(msg_buf)) == -1) { perror("\nError: Read failure\n"); exit(7); } if(kill(pid_child, SIGTERM) == -1) { perror("\nError: Kill failure\n"); exit(7); } if((pid = wait(&exit_union.exit_status)) == -1) { perror("\nError: Wait failure\n"); exit(7); } printf("Child %d terminated with: ", pid); if(exit_union.parts.sig_num == 0) { printf("exit code %d and ", exit_union.parts.exit_num); } else { printf("signal code %d and ", exit_union.parts.sig_num); } if(exit_union.parts.core_dmp == 0) { printf("no core dump generated.\n"); } else { printf("generated a core dump.\n"); } } return; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_print_float.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rtroll <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/05 12:59:32 by rtroll #+# #+# */ /* Updated: 2019/01/15 22:35:53 by rtroll ### ########.fr */ /* */ /* ************************************************************************** */ #include <ft_printf.h> static char *ft_alloc_zero(int prec) { char *ptr; if (prec == -2) { ptr = ft_strnew(1); ft_memset(ptr, '0', 1); } else { ptr = ft_strnew((size_t)prec + 1); ft_memset(ptr, '0', (size_t)prec + 1); } return (ptr); } static char *ft_itoa_u(unsigned long long n, int prec) { char *ptr; size_t i; unsigned long long result; if (n == 0) return (ft_alloc_zero(prec)); result = n; ptr = ft_strnew(19 + 1); if (ptr == NULL) return (NULL); i = 0; while (result != 0) { ptr[i++] = (char)(result % 10 + '0'); result /= 10; prec--; } while (prec-- > -1) ptr[i++] = '0'; return (ft_strrev(ptr)); } static unsigned long long ft_find_prec(int prec) { unsigned long long result; if (prec == 0) return (1); result = 10; return (ft_find_prec(prec - 1) * result); } static char *ft_itoa_f(double arg, t_data data) { char *str; unsigned long integer; unsigned long fraction; char *tmp; double mod_arg; mod_arg = arg < 0 ? arg * -1 : arg; integer = (uint64_t)mod_arg; str = ft_itoa_u(integer, -2); if (*((uint64_t*)&arg) >> 63 == 1) { tmp = ft_strjoin("-", str); ft_strdel(&str); str = tmp; } fraction = ft_find_prec(data.prec + 1); fraction = (unsigned long)((mod_arg - (long double)integer) * fraction); tmp = ft_strjoin(str, "."); ft_strdel(&str); str = tmp; tmp = ft_strjoin(str, ft_itoa_u(fraction, data.prec)); ft_round(&tmp); ft_strdel(&str); return (tmp); } int ft_print_float(va_list ap, t_data data) { double arg; char *str; int size; arg = va_arg(ap, double); if (data.prec == -1) data.prec = 6; str = ft_itoa_f(arg, data); str = ft_change_format_f(str, data); ft_putstr(str); size = ft_strlen(str); ft_strdel(&str); return (size); }
C
#define _XOPEN_SOURCE #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <cs50.h> #define SALT_LEN 2 #define MAX_PW_LEN 8 #define DICTIONARY_PATH "/usr/share/dict/words" typedef uint8_t BYTE; bool compare_PW(char * POTENTIAL_PW, const char * CIPHERED_PW); void brute(const char * CIPHERED_PW, bool * cracked, char * SALT); int main(int argc, string argv[]) { const char * CIPHERED_PW = argv[1]; char * SALT = malloc( ((SALT_LEN)+1) * sizeof(char)); SALT[0] = CIPHERED_PW[0]; SALT[1] = CIPHERED_PW[1]; SALT[2] = '\0'; bool cracked = false; // printf("%s\n", SALT); // printf("%s\n", CIPHERED_PW); //check for correct arguments if(argc != 2) { printf("ERROR 1: please enter ONE command-line argument\n"); return 1; } /* //dictionary attack FILE * DICTIONARY = fopen(DICTIONARY_PATH, "r"); char buffer[MAX_PW_LEN+1]; if(DICTIONARY == NULL) { printf("ERROR 2: dictionary file does not exist\n"); return 2; } while(fgets(buffer, sizeof(buffer), DICTIONARY) != NULL) { if(buffer[strlen(buffer)-1] == '\n') buffer[strlen(buffer)-1] = '\0'; if(compare_PW(crypt(buffer, SALT), CIPHERED_PW)) { printf("%s\n", buffer); cracked = true; break; } } fclose(DICTIONARY); */ // brute force attack brute(CIPHERED_PW, &cracked, SALT); if(cracked == false) printf("Crack was unsuccessful\n"); else printf("Crack successful\n"); return 0; } bool compare_PW(char * POTENTIAL_PW, const char * CIPHERED_PW) { if(strcmp(POTENTIAL_PW, CIPHERED_PW) == 0) return true; else return false; } void brute(const char * CIPHERED_PW, bool * cracked, char * SALT) { char s[MAX_PW_LEN] = {0}; int upBound = 122; //"a" to "b": 97 to 122 int lowBound = 97; // all printable ASCII characters: 32 to 126 for(int int8 = lowBound; int8 <= upBound; int8++) { for(int int7 = lowBound; int7 <= upBound; int7++) { for(int int6 = lowBound; int6 <= upBound; int6++) { for(int int5 = lowBound; int5 <= upBound; int5++) { for(int int4 = lowBound; int4 <= upBound; int4++) { for(int int3 = lowBound; int3 <= upBound; int3++) { for(int int2 = lowBound; int2 <= upBound; int2++) { for(int int1 = lowBound; int1 <= upBound; int1++) { s[0] = (char)int1; //char * s = "crimson"; if(compare_PW(crypt(s, SALT), CIPHERED_PW)) { printf("%s\n",s); *cracked = true; break; } } if (*cracked == true) break; s[1] = (char)int2; } s[2] = (char)int3; if (*cracked == true) break; } s[3] = (char)int4; if (*cracked == true) break; } s[4] = (char)int5; if (*cracked == true) break; } s[5] = (char)int6; if (*cracked == true) break; } s[6] = (char)int7; if (*cracked == true) break; } s[7] = (char)int8; if (*cracked == true) break; } }
C
/** Agenda * - Exercise 3 (medium): * Write a program that counts all letters from a-z (treat a-z and A-Z as same), store their occurrences in an Array and print them out using printf(). **/ #include<stdio.h> void main() { int c, i; int letters[26] = {0}; // init all array values with 0 while( (c = getchar()) != EOF ) { if( c >= 'a' && c <= 'z' ) letters[(c - 'a')]++; if( c >= 'A' && c <= 'Z' ) letters[(c - 'A')]++; } printf("Letter count:\n"); for(i = 0; i < 26; i++) printf("Letter %c occurs %d times.\n", i+'a', letters[i] ); }
C
#include <stdio.h> #include <stdlib.h> ///bu kodun amac ýtek yollu bir labirentte gidilecek yollarýn koordinatlarýný yazmaktýr. struct n { struct n *next; int x; int y; char eleman; }; typedef struct n node; int main() { FILE *dosya=fopen("labirent.txt","r"); if(dosya==NULL) printf("Dosya bulunamadi.\n"); char dizi[12][15]; int i=0,j=13; fgets(dizi[i],15,dosya); dizi[i][13]='\0'; while(!feof(dosya)) { i++; fgets(dizi[i],15,dosya); dizi[i][13]='\0'; } int sayac2=0; printf(" LABIRENT\n"); for(i=0; i<12; i++) { for(j=0; dizi[i][j]!='\0'; j++) { printf("%c",dizi[i][j]); if(dizi[i][j]!='\n') printf(" "); if(dizi[i][j]=='0')sayac2++; } } node *root=(node*)malloc(sizeof(node)); node *bas_son=(node*)malloc(sizeof(node)); int sayac=0; for(i=0;i<12;i++) { for(j=0;dizi[i][j]!='\0';j++) { if(dizi[i][j]=='2') { bas_son->x=i; bas_son->y=j; bas_son->eleman=dizi[i][j]; bas_son->next=NULL; if(dizi[i-1][j]=='0') { root->eleman='4'; root->x=i-1; root->y=j; root->next=NULL; sayac++; break; } else if(dizi[i+1][j]=='0') { root->eleman='4'; root->x=i+1; root->y=j; root->next=NULL; sayac++; break; } else if(dizi[i][j-1]=='0') { root->eleman='4'; root->x=i; root->y=j-1; root->next=NULL; sayac++; break; } else if(dizi[i][j+1]=='0') { root->eleman='4'; root->x=i; root->y=j+1; root->next=NULL; sayac++; break; } } } if(sayac==1) break; } printf("Baslangic Noktasi:(%d,%d)\n",bas_son->x+1,bas_son->y+1); node *yigin=NULL; yigin=(node*)malloc(sizeof(node)); yigin->eleman=root->eleman; yigin->x=root->x; yigin->y=root->y; dizi[yigin->x][yigin->y]='4'; yigin->next=NULL; node* yigin2=yigin; int sayac3=1; while(1) { sayac=0; for(i=0;i<12;i++) { for(j=0;dizi[i][j]!='\0';j++) { if(dizi[i][j]=='4') { if(dizi[i-1][j]=='0') { root->eleman='4'; root->x=i-1; root->y=j; root->next=NULL; sayac++; break; } else if(dizi[i+1][j]=='0') { root->eleman='4'; root->x=i+1; root->y=j; root->next=NULL; sayac++; break; } else if(dizi[i][j-1]=='0') { root->eleman='4'; root->x=i; root->y=j-1; root->next=NULL; sayac++; break; } else if(dizi[i][j+1]=='0') { root->eleman='4'; root->x=i; root->y=j+1; root->next=NULL; sayac++; break; } } } if(sayac==1) break; } for(i=0;i<12;i++) { for(j=0;dizi[i][j]!='\0';j++) { if(dizi[i][j]=='3') { bas_son->x=i; bas_son->y=j; } } } yigin->next=(node*)malloc(sizeof(node)); yigin=yigin->next; yigin->eleman=root->eleman; yigin->x=root->x; yigin->y=root->y; dizi[yigin->x][yigin->y]='4'; yigin->next=NULL; sayac3++; if(sayac2==sayac3)break; } free(root); while(yigin2!=NULL) { printf("(%d,%d)\n",yigin2->x+1,yigin2->y+1); yigin2=yigin2->next; } printf("Bitis Noktasi:(%d,%d)\n",bas_son->x+1,bas_son->y+1); free(bas_son); return 0; }
C
#include <stdlib.h> #include "hw1.h" #include "debug.h" #include "const.h" #include "polybius.h" #include "morse.h" #ifdef _STRING_H #error "Do not #include <string.h>. You will get a ZERO." #endif #ifdef _STRINGS_H #error "Do not #include <strings.h>. You will get a ZERO." #endif #ifdef _CTYPE_H #error "Do not #include <ctype.h>. You will get a ZERO." #endif int main(int argc, char **argv) { unsigned short mode; mode = validargs(argc, argv); debug("Mode: 0x%X", mode); // help menu if (mode & 0x8000) { USAGE(*argv, EXIT_SUCCESS); } // error else if (!mode) { USAGE(*argv, EXIT_FAILURE); } // morse else if (mode & 0x4000) { create_morse_key(); if (mode & 0x2000) { debug("%s", "morse decryption"); return morse_decrypt(); } else { debug("%s", "morse encryption"); return morse_encrypt(); } } // polybius else { unsigned char rows = (mode & 0x00F0) >> 4; unsigned char cols = mode & 0x000F; create_polybius_table(rows, cols); if (mode & 0x2000) { debug("%s", "polybius decryption"); return polybius_decrypt(rows, cols); } else { debug("%s", "polybius encryption"); return polybius_encrypt(rows, cols); } } return EXIT_SUCCESS; } /* * Just a reminder: All non-main functions should * be in another file not named main.c */
C
#include <stdio.h> // program to check whether the character is upper case or not int main(int argc, char *argv[]) { char ch; printf("Enter one character"); scanf("%c",&ch); if(ch>='A' && ch <=90) //A=65 printf("Upper case letter"); else printf("Not Upper case"); return 0; printf("finish\n", ); }
C
/* Andreas Polze 08-jan-05 */ /* mytime.c */ /* Example solution to assignment 4.4.3 */ /* Windows Operating System Internals */ # include <windows.h> # include <stdio.h> int main(int argc, char* argv[]) { STARTUPINFO si; PROCESS_INFORMATION pi; SYSTEMTIME ElTiSys, StartTSys, ExitTSys; union { FILETIME ft; LONGLONG lt; } CreateT, ExitT, ElapsedT; if (argc < 1) { printf("usage: mytime <command>\n"); return -1; } GetSystemTime(&StartTSys); ZeroMemory(&si, sizeof(si)); if (!CreateProcess(NULL, argv[1], NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { printf("process creation failed, code %i\n", GetLastError()); return -2; } WaitForSingleObject(pi.hProcess, INFINITE); GetSystemTime(&ExitTSys); SystemTimeToFileTime(&StartTSys, &CreateT.ft); SystemTimeToFileTime(&ExitTSys, &ExitT.ft); /* - 64bit arithmetic on FILETIME - */ ElapsedT.lt = ExitT.lt - CreateT.lt; FileTimeToSystemTime(&ElapsedT.ft, &ElTiSys); printf("Real Time: %02d:%02d:%02d:%03d\n", ElTiSys.wHour, ElTiSys.wMinute, ElTiSys.wSecond, ElTiSys.wMilliseconds); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); return 0; }
C
/* ** echo.c for 42sh in /home/regisb/Semestre_2/prog_shell/42sh/test ** ** Made by Régis Berthelot ** Login <[email protected]> ** ** Started on Thu May 11 15:51:47 2017 Régis Berthelot ** Last update Sun May 21 11:34:35 2017 Régis Berthelot */ #include "42sh.h" static void muh_putstring(char *str) { int i; i = 0; while (str[i] != '\0') { if (str[i] != '"') write(1, &str[i], 1); ++i; } } int shell_echo(char **args_tab) { int i; int noline; if (args_tab[1] == NULL) { printf("\n"); return (0); } i = 1; noline = strcmp(args_tab[1], "-n"); if (noline == 0) i = 2; while (args_tab[i] != NULL) { muh_putstring(args_tab[i]); if (args_tab[i++ + 1] != NULL) printf(" "); } if (noline != 0) printf("\n"); return (0); }
C
#include <gtk/gtk.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> /* strlen, strcmp */ #include <ctype.h> #include<sys/socket.h> //socket #include<arpa/inet.h> //inet_addr GtkWidget *resultat; int sock; struct sockaddr_in server; char message[1000] , server_reply[2000],server_reply2[200]; int tab[2] = {}; int main(int argc, char *argv[]) { GtkBuilder *builder; GtkWidget *window; sock = socket(AF_INET , SOCK_STREAM , 0); if (sock == -1) { printf("Could not create socket"); } puts("Socket created"); server.sin_addr.s_addr = inet_addr("127.0.0.1"); server.sin_family = AF_INET; server.sin_port = htons( 8888 ); if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0) { perror("connect failed. Error"); return 1; } puts("vien de me connecter\n"); gtk_init(&argc, &argv); builder = gtk_builder_new(); gtk_builder_add_from_file (builder, "test.glade", NULL); window = GTK_WIDGET(gtk_builder_get_object(builder, "window_main")); gtk_builder_connect_signals(builder, NULL); resultat = GTK_WIDGET(gtk_builder_get_object(builder,"resultat")); g_object_unref(builder); gtk_widget_show(window); gtk_main(); return 0; } // called when window is closed void on_window_main_destroy() { close(sock); printf("fin parte\n"); gtk_main_quit(); } void on_ciseau_clicked(){ tab[1]=1; if( send(sock , tab , sizeof(tab) , 0) < 0) { puts("Send failed"); } if( recv(sock , server_reply , 2000 , 0) < 0) { puts("recv failed"); } printf("ciseau\n"); printf("%s\n",server_reply); gtk_label_set_text(GTK_LABEL(resultat), (const gchar*) server_reply); } void on_feuille_clicked(){ tab[1]=2; if( send(sock , tab , sizeof(tab) , 0) < 0) { puts("Send failed"); } if( recv(sock , server_reply , 2000 , 0) < 0) { puts("recv failed"); } printf("feuille\n"); printf("%s\n",server_reply); gtk_label_set_text(GTK_LABEL(resultat), (const gchar*) server_reply); } void on_pierre_clicked(){ tab[1]=3; if( send(sock , tab , sizeof(tab) , 0) < 0) { puts("Send failed"); } if( recv(sock , server_reply , 2000 , 0) < 0) { puts("recv failed"); } printf("feuille\n"); printf("%s\n",server_reply); gtk_label_set_text(GTK_LABEL(resultat), (const gchar*) server_reply); } void on_Select_changed(GtkComboBox *c){ printf("Commmencer\n"); } void on___glade_unnamed_5_changed(GtkEntry *e){ char tmp[128]; sprintf(tmp,"%s",gtk_entry_get_text(e)); if(strcmp(tmp, "joueur2")!=0){ tab[0]=2; }else{ tab[0]=1; } printf(tmp); }
C
#include <stdio.h> #include <stdlib.h> int main() { //captura de dados float base, lado1, lado2; printf("CLASSIFICACAO DE TRIANGULOS"); printf("\n\nDigite o comprimento da base: "); scanf("%f", & base); printf("Digite o comprimento do lado: "); scanf("%f", & lado1); printf("Digite o comprimento do lado: "); scanf("%f", & lado2); //condioes if(base == lado1 && base == lado2 && lado1 == lado2 && lado2 == lado1 && lado1 == base && lado2 == base) printf("\nTriangulo Equilatero"); else if(base == lado1 || base == lado2 || lado1 == lado2 || lado2 == lado1 || lado1 == base || lado2 == base) printf("\nTriangulo Isosceles"); else if(base != lado1 && base != lado2 && lado1 != base && lado1 != lado2 && lado2 != base && lado2 != lado1) printf("\nTriangulo Escaleno"); //finalizao printf("\n\n\n"); system("PAUSE"); return 0; }
C
#include <stdio.h> #include <semaphore.h> #include <sys/shm.h> #include <fcntl.h> #include <string.h> #include <ctype.h> #include <sys/msg.h> #include <stdio.h> #include <semaphore.h> #include <sys/shm.h> #include <fcntl.h> #define NUMERO_PALABRAS 10 #define LONGITUD_MAX 15 #define TAM 200 struct Palabras { char palabra1[LONGITUD_MAX]; char palabra2[LONGITUD_MAX]; char palabra3[LONGITUD_MAX]; char palabra4[LONGITUD_MAX]; char palabra5[LONGITUD_MAX]; char palabra6[LONGITUD_MAX]; char palabra7[LONGITUD_MAX]; char palabra8[LONGITUD_MAX]; char palabra9[LONGITUD_MAX]; char palabra10[LONGITUD_MAX]; int posicion; }; int main(){ /* Inicializamos las variables */ sem_t *semH = NULL; struct Palabras * palabras_ptr; int shmid = 0; key_t clave; clave=ftok(".",'X'); int msg; //lista palabras memoria cmpartida /* Creamos los semaforos */ semH = sem_open("palabra",O_CREAT,0600,1); if ((msg = msgget(clave,IPC_CREAT|IPC_EXCL|0600)) == -1) { printf("Error al crear cola\n"); } else{ printf("Cola creada\n"); } if (semH != NULL){ sem_close(semH); } /* Creamos la zona de memoria compartida */ if ((shmid = shmget(clave, TAM, IPC_CREAT|IPC_EXCL|0600)) != -1){ printf("Segmento de memoria compartida creado correctamente.\n"); //printf("%s\n",strs[0]); /* Inicializamos el buffer */ palabras_ptr = shmat(shmid, NULL, 0); strcpy(palabras_ptr->palabra1, "perro"); strcpy(palabras_ptr->palabra2, "gato"); strcpy(palabras_ptr->palabra3, "elefante"); strcpy(palabras_ptr->palabra4, "cocodrilo"); strcpy(palabras_ptr->palabra5, "jirafa"); strcpy(palabras_ptr->palabra6, "avestruz"); strcpy(palabras_ptr->palabra7, "ferrari"); strcpy(palabras_ptr->palabra8, "prueba"); strcpy(palabras_ptr->palabra9, "langostinos"); strcpy(palabras_ptr->palabra10, "estupefacto"); palabras_ptr->posicion = 0; printf("%s\n",palabras_ptr->palabra1 ); printf("%s\n",palabras_ptr->palabra2 ); printf("%s\n",palabras_ptr->palabra3 ); printf("%s\n",palabras_ptr->palabra4 ); printf("%s\n",palabras_ptr->palabra5 ); printf("%s\n",palabras_ptr->palabra6 ); printf("%s\n",palabras_ptr->palabra7 ); printf("%s\n",palabras_ptr->palabra8 ); printf("%s\n",palabras_ptr->palabra9 ); printf("%s\n",palabras_ptr->palabra10 ); shmdt(palabras_ptr); }else{ printf("ERROR: El segmento de memoria no se pudo crear, puede que ya este creado.\n"); } return 0; }
C
#include "kernel_parser.h" #include <elf.h> #include <stdbool.h> #include "screen.h" #include "utils.h" bool verify_kernel_elf(Elf64_Ehdr *header); void load_segments(void *kernel_file, Elf64_Phdr *pheader, unsigned int num_of_pheaders, boot_info_mem *mmap); void *load_kernel(boot_info *info) { void *kernel_file = (void *)info->kernel_module.start_addr; Elf64_Ehdr *header = (Elf64_Ehdr *)kernel_file; // Verify the kernel's elf if (!verify_kernel_elf(header)) { return 0; } printf("Loading Kernel's Segments..\n"); load_segments(kernel_file, (Elf64_Phdr *)((char *)kernel_file + header->e_phoff), header->e_phnum, &info->memory); return (void *)header->e_entry; } bool verify_kernel_elf(Elf64_Ehdr *header) { // Verify ELF Magic Number printf("Verifying Kernel's ELF Magic Number..\n"); if (header->e_magic0 != ELFMAG0 || header->e_magic1 != ELFMAG1 || header->e_magic2 != ELFMAG2 || header->e_magic3 != ELFMAG3) { printf("Kernel's ELF Magic Number is invalid\n"); return false; } // Verify ELF class printf("Verifying Kernel's ELF is 64-bit..\n"); if (header->e_class != ELFCLASS64) { printf("Kernel's ELF isn't 64-bit\n"); return false; } // Verify ELF arch printf("Verifying Kernel's ELF Arch..\n"); if (header->e_machine != 0x3E) { printf("Kernel's ELF Arch isn't x86_64\n"); return false; } return true; } void load_segments(void *kernel_file, Elf64_Phdr *pheader, unsigned int num_of_pheaders, boot_info_mem *mmap) { Elf64_Phdr *header; for (unsigned int i = 0; i < num_of_pheaders; i++) { header = pheader + i; printf( "ELF Program Header: type = 0x%x, offset = 0x%lx, vaddr = 0x%lx, filesz = 0x%lx, memsz " "= " "0x%lx\n", header->p_type, header->p_offset, header->p_vaddr, header->p_filesz, header->p_memsz); // If the program header type is to load data if (header->p_type == PT_LOAD) { // Copy the data to the wanted location memcpy((uint8_t *)((char *)kernel_file + header->p_offset), (uint8_t *)header->p_vaddr, header->p_filesz); // Set all 0s in the remaining data memset((uint8_t *)(header->p_vaddr + header->p_filesz), 0, header->p_memsz - header->p_filesz); // Add kernel memory entry add_kernel_memory_entry(mmap, header->p_vaddr - KERNEL_VIRTUAL_ADDRESS, header->p_memsz); } } } void add_kernel_memory_entry(boot_info_mem *mmap, uint64_t base_addr, uint64_t size) { boot_info_mem new_mmap = {0}; boot_info_mem_entry *entry = 0; range kernel_entry_range = {.start = base_addr, .end = base_addr + size}; range entry_range; range entry_intersection = {0}; // For each original entry, check if it conflicts with the kernel entry for (uint16_t i = 0; i < mmap->entry_count; i++) { entry = (boot_info_mem_entry *)mmap->entries + i; entry_range = (range){.start = entry->base_addr, .end = entry->base_addr + entry->size}; // Check if there is an intersection between the kernel entry and the entry entry_intersection = find_range_intersection(entry_range, kernel_entry_range); // If there isn't an entry intersection, just add the entry if (entry_intersection.end <= entry_intersection.start) { new_mmap.entries[new_mmap.entry_count++] = *entry; } else { // If the intersection starts where the entry starts if (entry_intersection.start == entry_range.start) { // If the intersection is the entire entry, just add the kernel entry instead if (entry_intersection.end == (entry->base_addr + entry->size)) { new_mmap.entries[new_mmap.entry_count++] = (boot_info_mem_entry){ .base_addr = entry->base_addr, .size = entry->size, .type = KERNEL}; } else { // Add the kernel entry new_mmap.entries[new_mmap.entry_count++] = (boot_info_mem_entry){ .base_addr = entry->base_addr, .size = entry_intersection.end - entry_intersection.start, .type = KERNEL}; // Add the rest of the entry new_mmap.entries[new_mmap.entry_count++] = (boot_info_mem_entry){ .base_addr = entry_intersection.end, .size = entry->size - (entry_intersection.end - entry_intersection.start), .type = entry->type}; } } // If the intersection starts in the middle of the entry else if (entry_intersection.start > entry_range.start) { // If the intersection ends in the end of the entry if (entry_intersection.end == (entry->base_addr + entry->size)) { // Add the rest of the entry new_mmap.entries[new_mmap.entry_count++] = (boot_info_mem_entry){ .base_addr = entry->base_addr, .size = entry->size - (entry_intersection.end - entry_intersection.start), .type = entry->type}; // Add the kernel entry new_mmap.entries[new_mmap.entry_count++] = (boot_info_mem_entry){ .base_addr = entry_intersection.start, .size = entry_intersection.end - entry_intersection.start, .type = KERNEL}; } else { // Add the start of the entry new_mmap.entries[new_mmap.entry_count++] = (boot_info_mem_entry){ .base_addr = entry->base_addr, .size = entry_intersection.start - entry->base_addr, .type = entry->type}; // Add the kernel entry new_mmap.entries[new_mmap.entry_count++] = (boot_info_mem_entry){ .base_addr = entry_intersection.start, .size = entry_intersection.end - entry_intersection.start, .type = KERNEL}; // Add the end of the entry new_mmap.entries[new_mmap.entry_count++] = (boot_info_mem_entry){ .base_addr = entry_intersection.end, .size = entry->base_addr + entry->size - entry_intersection.end, .type = entry->type}; } } } } // Set the new memory map *mmap = new_mmap; }
C
#include<stdio.h> int main() { int n, x[100002]={0}, s, i, max; scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&s); x[s]++; } max = 0; for(i=0;i<=100000;i++) { s=x[i]+x[i+1]+x[i+2]; if(s>max ) { max = s; } } printf("%d\n", max); return 0; } ./Main.c: In function main: ./Main.c:5:1: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%d",&n); ^ ./Main.c:8:3: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%d",&s); ^ ./Main.c:14:18: warning: iteration 100000u invokes undefined behavior [-Waggressive-loop-optimizations] s=x[i]+x[i+1]+x[i+2]; ^ ./Main.c:12:1: note: containing loop for(i=0;i<=100000;i++) ^
C
/* * main.c * * Created on: Feb 26, 2015 * Author: skynet */ #include <stdio.h> #include "triunghi.h" int main(void) { unsigned int a, b, c; int valid; printf("Dati laturile triunghiului:\n"); //citim laturile triunghiului printf("a="); scanf("%d", &a); printf("b="); scanf("%d", &b); printf("c="); scanf("%d", &c); valid=validare(a, b, c); //validam dimensiunile citite, rezultatul se stocheaza in variabila valid (1 sau 0) if (valid==1) //daca dimensiunile sunt valide verificam tipul triunghiului folosind functiile create { if (echilateral(a, b, c))//am testat intai daca triunghiul este echilateral, si apoi isoscel, deoarece in cazul unui triunghi echilateral, functia isoscel() ar fi returnat un rezultat pozitiv! { printf("Triunghiul este echilateral.\n"); } else if (isoscel(a, b, c)) { printf("Triunghiul este isoscel.\n"); } else if (dreptunghic(a, b, c)) { printf("Triunghiul este dreptunghic.\n"); } else { //daca triunghiul nu se incadreaza in niciun tip de mai sus, atunci el este oarecare (scalen) printf("Triunghiul este scalen.\n"); } } else { //daca dimensiunile nu sunt valide, afisam un mesaj in acest sens printf("%d, %d si %d nu pot reprezenta laturile unui triunghi.\n", a, b, c); } return 0; }
C
/*--------------------------------------------------------------------------------- Simple effect sound demo /*\ WARNING effects must be 1st IT file in convertion all musics must be after IT file each combination of a music + effect must be lower than 60K -- alekmaul ---------------------------------------------------------------------------------*/ #include <snes.h> #include "res/soundbank.h" extern char snesfont, snespal; extern char SOUNDBANK__; u8 i, keyapressed = 0,keylpressed = 0,keyrpressed = 0; //--------------------------------------------------------------------------------- int main(void) { // Initialize sound engine (take some time) spcBoot(); // Initialize SNES consoleInit(); // Initialize text console with our font consoleSetTextVramBGAdr(0x6800); consoleSetTextVramAdr(0x3000); consoleSetTextOffset(0x0100); consoleInitText(0, 16 * 2, &snesfont, &snespal); // Set give soundbank spcSetBank(&SOUNDBANK__); // Init background bgSetGfxPtr(0, 0x2000); bgSetMapPtr(0, 0x6800, SC_32x32); // Now Put in 16 color mode and disable Bgs except current setMode(BG_MODE1, 0); bgSetDisable(1); bgSetDisable(2); // Load all effects spcStop(); for (i=0;i<5;i++) { spcLoadEffect(i); } // Draw a wonderfull text :P consoleDrawText(5, 10, "Press A to play effect !"); consoleDrawText(5, 11, "Press L and R to change !"); // Wait for nothing :P setScreenOn(); // Wait for nothing :D ! i=0; consoleDrawText(7, 14, "Effect: tada"); while (1) { // Refresh pad values and test key a (without repeating sound if still pressed) scanPads(); if (padsCurrent(0) & KEY_A) { if (keyapressed == 0) { keyapressed = 1; // Play effect spcEffect(8,i,15*16+8); // (u16 pitch,u16 sfxIndex, u8 volpan); pitch=1=4Khz , 2=8khz, 8=32Khz } } else keyapressed = 0; if (padsCurrent(0) & KEY_LEFT) { if (keylpressed == 0) { keylpressed = 1; if (i>0) i--; if (i==0) consoleDrawText(7, 14, "Effect: tada "); else if (i==1) consoleDrawText(7, 14, "Effect: Hall Strings "); else if (i==2) consoleDrawText(7, 14, "Effect: Honky Tonk Piano"); else if (i==3) consoleDrawText(7, 14, "Effect: Marimba 1 "); else if (i==4) consoleDrawText(7, 14, "Effect: Cowbell "); } } else keylpressed = 0; if (padsCurrent(0) & KEY_RIGHT) { if (keyrpressed == 0) { keyrpressed = 1; if (i<5) i++; if (i==0) consoleDrawText(7, 14, "Effect: tada "); else if (i==1) consoleDrawText(7, 14, "Effect: Hall Strings "); else if (i==2) consoleDrawText(7, 14, "Effect: Honky Tonk Piano"); else if (i==3) consoleDrawText(7, 14, "Effect: Marimba 1 "); else if (i==4) consoleDrawText(7, 14, "Effect: Cowbell "); } } else keyrpressed = 0; // Update music / sfx stream and wait vbl spcProcess(); WaitForVBlank(); } return 0; }
C
#include <stdio.h> int lower_one_mask(int n) { int size = sizeof(int); unsigned x = ~0; x >>= ((size << 3) - n); return x; } int main() { printf("%.8x\n", lower_one_mask(6)); printf("%.8x\n", lower_one_mask(17)); return 0; }
C
#include <pebble.h> #define HABIT_STRING_MAX_LENGTH 50 #define NUM_OF_HABITS 5 #define MINUTES_BETWEEN_ROTATION 5 #define HABIT1_PERSIST_KEY 0 #define HABIT2_PERSIST_KEY 1 #define HABIT3_PERSIST_KEY 2 #define HABIT4_PERSIST_KEY 3 #define HABIT5_PERSIST_KEY 4 #define PLACEHOLDER_HABIT "Add custom text here using the Pebble app" static Window *s_main_window; static TextLayer *s_battery_layer; static TextLayer *s_time_layer; static TextLayer *s_habit_layer; static TextLayer *s_date_layer; static uint8_t s_current_habit = HABIT1_PERSIST_KEY; // Tracks storage index of current habit static uint8_t s_minutes_since_rotation = 0; // Tracks minutes since last habit change static void update_time(struct tm *tick_time) { // Write hours and minutes into a buffer static char s_buffer[8]; strftime(s_buffer, sizeof(s_buffer), clock_is_24h_style() ? "%H:%M" : "%I:%M", tick_time); // Display this time on the TextLayer text_layer_set_text(s_time_layer, s_buffer); } static void update_date(struct tm *tick_time) { // Write hours and minutes into a buffer static char s_buffer[8]; strftime(s_buffer, sizeof(s_buffer), "%b %d ", tick_time); // Display this time on the TextLayer text_layer_set_text(s_date_layer, s_buffer); } static void rotate_habit() { // Intermediary buffer to hold new habit string static char new_habit[HABIT_STRING_MAX_LENGTH]; s_minutes_since_rotation = 0; // Reset rotation timing // Find next set habit, treating storage as circular buffer int i = s_current_habit; do { s_current_habit = (s_current_habit + 1) % NUM_OF_HABITS; if (persist_exists(s_current_habit)) { // Write habit to watchface persist_read_string(s_current_habit, new_habit, sizeof(new_habit)); text_layer_set_text(s_habit_layer, new_habit); return; } } while (s_current_habit != i); // If nothing found, set to placeholder text text_layer_set_text(s_habit_layer, PLACEHOLDER_HABIT); } static void hide_battery_level(void* context) { layer_set_hidden((Layer*) s_battery_layer, true); } static void display_battery_level() { BatteryChargeState battery_state = battery_state_service_peek(); uint8_t battery_level = battery_state.charge_percent; bool battery_plugged = battery_state.is_plugged; static char s_buffer[14]; if (battery_plugged) { snprintf(s_buffer, sizeof(s_buffer), "Plugged in"); } else { snprintf(s_buffer, sizeof(s_buffer), "Battery: %d%%", battery_level); } // Set battery info text_layer_set_text(s_battery_layer, s_buffer); // Show battery info layer_set_hidden((Layer*) s_battery_layer, false); // Set timer to hide battery info app_timer_register(3000, hide_battery_level, NULL); } static void tick_handler(struct tm *tick_time, TimeUnits units_changed) { update_time(tick_time); update_date(tick_time); s_minutes_since_rotation = (s_minutes_since_rotation + 1) % MINUTES_BETWEEN_ROTATION; if (s_minutes_since_rotation == 0) rotate_habit(); } static void tap_handler(AccelAxisType axis, int32_t direction) { display_battery_level(); } static void main_window_load(Window *window) { // Get information about the Window Layer *window_layer = window_get_root_layer(window); GRect bounds = layer_get_bounds(window_layer); int window_width = bounds.size.w; // Create and position TextLayer elements s_battery_layer = text_layer_create(GRect(0, 0, window_width, 18)); s_time_layer = text_layer_create(GRect(0, PBL_IF_ROUND_ELSE(30, 20), window_width, 65)); s_habit_layer = text_layer_create(GRect(5, PBL_IF_ROUND_ELSE(75, 65), (window_width - 10), 65)); s_date_layer = text_layer_create(GRect(0, 135, window_width, 30)); // Set background colors text_layer_set_background_color(s_battery_layer, GColorWhite); text_layer_set_background_color(s_time_layer, GColorClear); text_layer_set_background_color(s_habit_layer, GColorClear); text_layer_set_background_color(s_date_layer, GColorClear); // Set text colors text_layer_set_text_color(s_battery_layer, GColorBlack); text_layer_set_text_color(s_time_layer, GColorWhite); text_layer_set_text_color(s_habit_layer, GColorWhite); text_layer_set_text_color(s_date_layer, GColorWhite); // Set fonts text_layer_set_font(s_battery_layer, fonts_get_system_font(FONT_KEY_GOTHIC_14_BOLD)); text_layer_set_font(s_time_layer, fonts_get_system_font(FONT_KEY_LECO_38_BOLD_NUMBERS)); text_layer_set_font(s_habit_layer, fonts_get_system_font(FONT_KEY_GOTHIC_18_BOLD)); text_layer_set_font(s_date_layer, fonts_get_system_font(FONT_KEY_GOTHIC_24_BOLD)); // Center all text text_layer_set_text_alignment(s_battery_layer, GTextAlignmentCenter); text_layer_set_text_alignment(s_time_layer, GTextAlignmentCenter); text_layer_set_text_alignment(s_habit_layer, GTextAlignmentCenter); text_layer_set_text_alignment(s_date_layer, GTextAlignmentCenter); // Default text on habit layer text_layer_set_text(s_habit_layer, PLACEHOLDER_HABIT); // Add it as a child layer to the Window's root layer layer_add_child(window_layer, text_layer_get_layer(s_battery_layer)); layer_add_child(window_layer, text_layer_get_layer(s_time_layer)); layer_add_child(window_layer, text_layer_get_layer(s_habit_layer)); layer_add_child(window_layer, text_layer_get_layer(s_date_layer)); // Hide battery level bar initially hide_battery_level(NULL); // Get and display current time and date at load time_t temp = time(NULL); struct tm *tick_time = localtime(&temp); update_time(tick_time); update_date(tick_time); // Subscribe to tick timer for future time updates tick_timer_service_subscribe(MINUTE_UNIT, tick_handler); // Subscribe to accel tap service to detect shakes accel_tap_service_subscribe(tap_handler); // Display habits starting at first one at load s_current_habit = HABIT1_PERSIST_KEY; rotate_habit(); } static void main_window_unload(Window *window) { text_layer_destroy(s_time_layer); text_layer_destroy(s_habit_layer); } static void inbox_received_callback(DictionaryIterator *iterator, void *context) { // Catch and persist user's habit strings // Takes all empty fields and deletes from storage, because it is assumed that // any unedited habits will be saved in localStorage and re-sent from JavaScript Tuple *h1 = dict_find(iterator, MESSAGE_KEY_Habit1); if (strlen(h1->value->cstring) > 0) { persist_write_string(HABIT1_PERSIST_KEY, h1->value->cstring); } else { persist_delete(HABIT1_PERSIST_KEY); } Tuple *h2 = dict_find(iterator, MESSAGE_KEY_Habit2); if (strlen(h2->value->cstring) > 0) { persist_write_string(HABIT2_PERSIST_KEY, h2->value->cstring); } else { persist_delete(HABIT2_PERSIST_KEY); } Tuple *h3 = dict_find(iterator, MESSAGE_KEY_Habit3); if (strlen(h3->value->cstring) > 0) { persist_write_string(HABIT3_PERSIST_KEY, h3->value->cstring); } else { persist_delete(HABIT3_PERSIST_KEY); } Tuple *h4 = dict_find(iterator, MESSAGE_KEY_Habit4); if (strlen(h4->value->cstring) > 0) { persist_write_string(HABIT4_PERSIST_KEY, h4->value->cstring); } else { persist_delete(HABIT4_PERSIST_KEY); } Tuple *h5 = dict_find(iterator, MESSAGE_KEY_Habit5); if (strlen(h5->value->cstring) > 0) { persist_write_string(HABIT5_PERSIST_KEY, h5->value->cstring); } else { persist_delete(HABIT5_PERSIST_KEY); } // Rotate habits to prevent an old one from persisting until next rotation s_current_habit = HABIT5_PERSIST_KEY; // Hacky way to cycle habits in order rotate_habit(); } static void init() { // Prep main window s_main_window = window_create(); window_set_background_color(s_main_window, GColorBlack); window_set_window_handlers(s_main_window, (WindowHandlers) { .load = main_window_load, .unload = main_window_unload, }); window_stack_push(s_main_window, true); // Largest expected inbox and outbox message sizes const uint32_t inbox_size = 250; const uint32_t outbox_size = 0; // Open AppMessage app_message_open(inbox_size, outbox_size); // Prep AppMessage receive app_message_register_inbox_received(inbox_received_callback); } static void deinit() { window_destroy(s_main_window); } int main(void) { init(); app_event_loop(); deinit(); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* util.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: marvin <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/06/28 01:41:39 by donglee #+# #+# */ /* Updated: 2020/07/06 16:23:19 by donglee ### ########.fr */ /* */ /* ************************************************************************** */ #include "../cub3d.h" /* ** delete a node from a list */ void ft_lstmapdelone(t_map *node) { if (node) { free(node->row); node->row = NULL; free(node); node = NULL; } } /* ** clear the list of map */ void ft_lstmapclear(t_map **lst) { t_map *tmp; if (lst && *lst) { while (*lst) { tmp = (*lst)->next; ft_lstmapdelone(*lst); (*lst) = tmp; } *lst = NULL; } } /* ** returns -1(ERROR) and outputs the string of 'str' */ int error_msg(char *str) { write(1, str, ft_strlen(str)); write(1, "\n", 1); return (ERROR); } int ft_isspace(char c) { if ((c >= 9 && c <= 13) || c == ' ') return (TRUE); return (FALSE); } int free_2d_char(char **ret, int flag) { int i; i = 0; while (ret[i]) { free(ret[i]); i++; } free(ret); ret = NULL; return (flag); }
C
/* HashManager.c * Group 6 * Hash Manager * * Chris Huang * Cory Sherman */ #include "WebsiteCatalog.h" #include <string.h> #include <stdio.h> static const int DEFAULT_BUCKET_SIZE = 3; /******************************************************************************* * HashManager Private Prototypes ******************************************************************************/ static int _primeAtLeast(int val); static bool _isPrime(int val); static int _hashString(const char *val); /******************************************************************************* * Creates a hashtable for the specified ListHead * * Pre: pList points to a list with no hashtable. * pList->bucketSize is initialized. * numLines is not negative. * * Post: The hashtable has been created and is pointed to by pList->pHash. * Its length is the first prime number at least numLines * 2 * Its length is stored to pList->aryLength; * * Return: -- ******************************************************************************/ void hashCreate(ListHead *pList, int numLines) { pList->arySize = _primeAtLeast(numLines * 2); pList->bucketSize = DEFAULT_BUCKET_SIZE; pList->pHash = validate(calloc(pList->arySize * pList->bucketSize, sizeof(HashNode))); } static int _primeAtLeast(int val) { if(val < 0) val = -val; if(val <= 2) return 2; //if val is even if((val & 1) == 0) val++; while(!_isPrime(val)) { val += 2; } return val; } static bool _isPrime(int val) { int i; int endi; if(val < 0) val = -val; if(val < 2) return false; if(val == 2) return true; //if val is even if((val & 1) == 0) return false; //could be optimized to endi = sqrt(val) endi = val / 2; for(i = 3; i < endi; i += 2) { if(val % i == 0) return false; } return true; } /******************************************************************************* * Attempts to insert Website into a hashtable. * * Pre: pList points to a list which is initialized and has a valid hashtable. * pWebsite points to a valid website. * * Post: If the hashtable has room for the website and does not contain * an entry with the same URL, it is inserted. * Otherwise, a warning is printed to the screen and the pointer is discarded. * * Return: true if the website was successfully inserted. * false if the hashtable already contained an entry for the url, * or if the bucket was full. ******************************************************************************/ bool hashInsert(ListHead *pList, Website *pWebsite) { int i; int index; if(!hashSearch(pList, pWebsite->url)) { index = ((unsigned int)_hashString(pWebsite->url) % (unsigned int)pList->arySize) * pList->bucketSize; for(i = 0; i < pList->bucketSize; i++) { if(!pList->pHash[index].key) { pList->pHash[index+i].key = pWebsite->url; pList->pHash[index+i].site = pWebsite; return true; } } printf("Bucket full, unable to insert!\n"); return false; } printf("Website \"%s\" already exsits\n", pWebsite->url); return false; } /******************************************************************************* * Searches a hashtable for the specified url. * * Pre: pList points to a list which is initialized and has a valid hashtable. * url is the url of the website * * Post: Nothing is modified, the hashtable has been searched. * * Return: The website found, or NULL if one was not found. ******************************************************************************/ Website *hashSearch(ListHead *pList, const char *url) { int i; int index; index = ((unsigned int)_hashString(url) % (unsigned int)pList->arySize) * pList->bucketSize; for(i = 0; i < pList->bucketSize; i++) { if(pList->pHash[index + i].key && strcmp(pList->pHash[index + i].key, url)) return pList->pHash[index + i].site; } return NULL; } /******************************************************************************* * Searches a hashtable for the specified url, and removes the found website * from the hashtable. * * Pre: pList points to a list which is initialized and has a valid hashtable. * url is the url of the website * * Post: If the hashtable contained the url, it is removed from the hashtable. * * Return: The website removed, or NULL if one was not found. ******************************************************************************/ Website *hashRemove(ListHead *pList, const char *url) { Website *target; int index; int i = 0; int j = pList->bucketSize-1; target = hashSearch(pList, url); if(target) { index = ((unsigned int)_hashString(url) % (unsigned int)pList->arySize) * pList->bucketSize; while(strcmp(pList->pHash[index+i].key, url)); i++; pList->pHash[index+i].key = NULL; pList->pHash[index+i].site = NULL; if(i != j) { while(!pList->pHash[index+j].key) j--; pList->pHash[index+i].key = pList->pHash[index+j].key; pList->pHash[index+i].site = pList->pHash[index+j].site; } return target; } return NULL; } /******************************************************************************* * Frees a hashtable from the specified ListHead * * Pre: pList points to a list with a valid hashtable * * Post: The hashtable is freed. * pList->arySize is set to 0 * pList->pHash is set to NULL * * Return: -- ******************************************************************************/ void hashFree(ListHead *pList) { free(pList->pHash); pList->arySize = 0; pList->pHash = NULL; return; } /******************************************************************************* * Prints the efficiency of a hashtable. * * Pre: pList points to a list with a valid hashtable * * Post: The efficiency has been calculated and printed. * * Return: -- ******************************************************************************/ void printEfficiency(ListHead *pList) { double nodesFilled = 0; double loadFactor; double arySize; int i; int j; int collision = 0; int longestBucket = 0; for(i = 0; i < (pList->arySize * pList->bucketSize); i+=pList->bucketSize) { if(pList->pHash[i].key) { nodesFilled++; for(j = 1; j < pList->bucketSize; j++) { if(pList->pHash[i+j].key) collision++; } if(longestBucket < j) longestBucket = j; } } longestBucket++; arySize = pList->arySize; loadFactor = (nodesFilled / arySize) * 100; printf("The load factor is %.2f%%\n", loadFactor); printf("Number of collisions: %d\n", collision); printf("Longest Bucket: %d\n", longestBucket); return; } /******************************************************************************* * Lists the contents of a hashtable's buckets. * * Pre: pList points to a list with a valid hashtable * * Post: The data has been printed to stdout. * * Return: -- ******************************************************************************/ void hashPrintList(ListHead *pList) { int bucket; int elem; for(bucket = 0; bucket < pList->arySize; ++bucket) { HashNode *bucketOffset = &pList->pHash[bucket * pList->bucketSize]; printf("bucket (%d)\n", bucket); for(elem = 0; elem < pList->bucketSize; ++elem) { if(bucketOffset[elem].site) { printf(" "); websitePrint(bucketOffset[elem].site); } } } } static int _hashString(const char *key) { int h = 0; const char *w; for(w = key; *w != '\0'; w++) { h = 31*h + *w; } return h; }
C
/** * verify.h * * Ce fichier contient les prototypes de fonctions vérifiant d'autres fonctions * * @author: Dumoulin Peissone S193957 * @date: 21/03/21 * @projet: INFO0030 Projet 2 */ /* * Include guard (pour éviter les problèmes d'inclusions multiples * Bonne pratique: toujours encadrer un header avec un include guard */ #ifndef __VERIFY__ #define __VERIFY__ /** * \file verify.h * \brief Librairie de vérification de fonctions * \author Peissone Dumoulin - Université de Liège * \version 1.0 * \date 16/03/2021 */ /** * \fn int manage_comments(FILE *fp) * \brief Permet de gérer une ligne pour savoir si on doit l'ignorer * (celles commençant par '#') * \param fp un pointeur sur FILE * * \pre: fp != NULL * \post: la ligne est correctement ignorée * * \return: * 0 Succès * -1 Echec */ int manage_comments(FILE *fp); /** * \fn int manage_format_input(PNM *image, char *format, char *input) * \brief Gère si le format correspond au format de l'input * * \param image un pointeur sur PNM * \param format le format du fichier * \param input le nom du fichier en entrée * * \pre: image != NULL, format != NULL, input != NULL * \post: format du fichier géré correctement * * \return: * 0 Succès * -1 Mauvais format passé en argument */ int manage_format_input(PNM *image, char *format, char *input); /** * \fn int verify_output(char *output) * \brief Vérifie si l'output contient des caractères spéciaux interdits * * \param output le nom du fichier en sortie * * \pre: output != NULL * \post: output géré correctement * * \return: * 0 Succès * -1 Caractère invalide dans le nom du fichier */ int verify_output(char *output); /** * \fn verify_seed(char *seed) * \brief Vérifie si la graine contient autre chose que des 0 ou des 1 * * \param seed une chaine de caractères représentant la graine * * \pre: seed != NULL * \post: seed géré correctement * * \return: * 0 Succès * -1 Caractère invalide dans la graine */ int verify_seed(char *seed); /** * \fn verify_tap(char *tap) * \brief Vérifie si le tap contient autre chose que des 0 ou des 1 * * \param tap une chaine de caractères représentant le tap * * \pre: tap != NULL * \post: tap géré correctement * * \return: * 0 Succès * -1 Caractère invalide dans le tap */ int verify_tap(char *tap); /** * \fn int verify_password(char *password) * \brief Vérifie si le mot de passe contient un autre caractère que ceux autorisés * * \param password une chaine de caractères représentant le mot de passe * * \pre: password != NULL * \post: mot de passe géré correctement * * \return: * 0 Succès * -1 Caractère invalide dans le mot de passe */ int verify_password(char *password); #endif // __verify__
C
/* * main.c * * Created on: Aug 12, 2017 * Author: Mahmoud Ewaisha */ #include "string.h" #include "types.h" #include "utils.h" #include "DIO_Interface.h" #include "DIO.h" #include "DIO_Config.h" #include "DELAY.h" #include "Keypad.h" #include "LCD.h" #include "External_Interrupts.h" #include "Timer.h" extern flag; extern temp; extern light; u8 welcome1[] = "Welcome Mahmoud"; u8 welcome2[] = "Welcome Peter"; u8 welcome3[] = "Welcome Shady"; u8 wrong [] = "WRONG PASSWORD"; u8 pass1 [] = "123"; u8 pass2 [] = "456"; u8 pass3 [] = "789"; u8 last1[] = "Last Entered: Mahmoud"; u8 last2[] = "Last Entered: Shady"; u8 last3[] = "Last Entered: peter"; void main(void) { u8 i, x, counter = 0; /* Interrupts (0&1) INIT */ Interrupt_Init(); /* UART INIT */ UART_Init(); /* LCD initialization */ LCD_Init(); /* KEYPAD INIT */ Keypad_Init(); DIO_voidSetPinDirection(DIO_PIN8,DIO_OUTPUT); //LED DIO_voidSetPinDirection(DIO_PIN23,DIO_OUTPUT); //buzzer /**/ DIO_voidSetPinDirection(DIO_PIN13,DIO_OUTPUT); DIO_voidSetPinDirection(DIO_PIN14,DIO_OUTPUT); DIO_voidSetPinDirection(DIO_PIN15,DIO_OUTPUT); /* Timer INIT */ timer1_voidInitializeTime(); DIO_voidSetPinDirection(DIO_PIN11,DIO_OUTPUT); u8 str_in[4]; u8 password[] = "Password: "; OCR0 = 255; while(1) { while (1) //while loop for password , if the entered pass is correct, break to the main while loop { LCD_WriteCommand (0x01); for(i=0; i<strlen(password); i++) { LCD_WriteData(password[i]); } for(i=0; i<3; i++) { x = scankp(); str_in[i] = x; LCD_WriteData('*'); } if(string_cmp(str_in, pass1, strlen(str_in), strlen(pass1))) { LCD_WriteCommand(0xC0); for(i=0; i<strlen(welcome1); i++) { LCD_WriteData(welcome1[i]); } break; } else if(string_cmp(str_in, pass2, strlen(str_in), strlen(pass2))) { LCD_WriteCommand(0xC0); for(i=0; i<strlen(welcome2); i++) { LCD_WriteData(welcome2[i]); } break; } else if(string_cmp(str_in, pass3, strlen(str_in), strlen(pass3))) { LCD_WriteCommand(0xC0); for(i=0; i<strlen(welcome3); i++) { LCD_WriteData(welcome3[i]); } break; } else { counter++; if(counter == 3) { LCD_WriteCommand(0xC0); for(i=0; i<strlen(wrong); i++) { LCD_WriteData(wrong[i]); } DIO_voidWritePin(DIO_PIN23,DIO_HIGH); UART_Send(0xFF); //trigger buzzer in second led Delay(23000); //10 sec delay DIO_voidWritePin(DIO_PIN23,DIO_LOW); counter = 0; } else { LCD_WriteCommand(0xC0); for(i=0; i<strlen(wrong); i++) { LCD_WriteData(wrong[i]); } Delay(3500); } } } flag = 2; // 2 = access UART_Send(flag); while(flag != 3) //main loop, it'll be 3 in the interrupt associated with a switch { OCR0 = temp; if (light < 20) { DIO_voidWritePin(DIO_PIN13 , DIO_LOW); DIO_voidWritePin(DIO_PIN14 , DIO_LOW); DIO_voidWritePin(DIO_PIN15 , DIO_LOW); } else if (light >= 20 && light < 100) { DIO_voidWritePin(DIO_PIN13 , DIO_HIGH); DIO_voidWritePin(DIO_PIN14 , DIO_LOW); DIO_voidWritePin(DIO_PIN15 , DIO_LOW); } else if (light >= 100 && light < 190) { DIO_voidWritePin(DIO_PIN13 , DIO_HIGH); DIO_voidWritePin(DIO_PIN14 , DIO_HIGH); DIO_voidWritePin(DIO_PIN15 , DIO_LOW); } else if (light >= 190) { DIO_voidWritePin(DIO_PIN13 , DIO_HIGH); DIO_voidWritePin(DIO_PIN14 , DIO_HIGH); DIO_voidWritePin(DIO_PIN15 , DIO_HIGH); } } OCR0 = 255; DIO_voidWritePin(DIO_PIN13 , DIO_LOW); DIO_voidWritePin(DIO_PIN14 , DIO_LOW); DIO_voidWritePin(DIO_PIN15 , DIO_LOW); } }
C
// Helper functions for music #include <cs50.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <stdio.h> #include "helpers.h" // Converts a fraction formatted as X/Y to eighths int duration(string fraction) { // Numerator char numStr[1]; numStr[0] = fraction[0]; float num = atoi(numStr); // Denominator char denStr[1]; denStr[0] = fraction[2]; float den = atoi(denStr); // Calculate absolute note length float note = num / den; // Return number of eighths return (float) note / 0.125; } // Calculates frequency (in Hz) of a note int frequency(string note) { string NOTES[] = {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" }; int acc = 0; bool isNoteSharp = false; bool isNoteFlat = false; bool isNoteNat = false; char octStr[1]; int oct; int aIndex = 9; char letter = note[0]; if (note[1] == '#') { acc = 1; isNoteSharp = true; octStr[0] = note[2]; oct = atoi(octStr); } else if (note[1] == 'b') { acc = -1; isNoteFlat = true; octStr[0] = note[2]; oct = atoi(octStr); } else { isNoteNat = true; octStr[0] = note[1]; oct = atoi(octStr); } char natNote[1]; char sharpNote[2]; char flatNote[2]; // Create abs note string if (acc == 0) { sprintf(natNote, "%c", letter); } else if (acc == 1) { sprintf(sharpNote, "%c%c", letter, '#'); } else { sprintf(flatNote, "%c%c", letter, 'b'); } // Get index of current note int noteIndex = 0; if (isNoteSharp) { for (int i = 0, n = sizeof(NOTES) / sizeof(string); i < n; i++) { if ( strcmp(NOTES[i], sharpNote) == 0 ) { noteIndex = i; } } } else if (isNoteNat) { for (int i = 0, n = sizeof(NOTES) / sizeof(string); i < n; i++) { if ( strcmp(NOTES[i], natNote) == 0 ) { noteIndex = i; } } } else { for (int i = 0, n = sizeof(NOTES) / sizeof(string); i < n; i++) { if ( NOTES[i][0] == flatNote[0] ) { noteIndex = i - 1; break; } } } // Work out semitone difference including octave (n) double semitoneDiff = ((oct - 4) * 12) + (noteIndex - aIndex); // 2^n/12 * 440 where n is semitones to a4 double freq = round(pow(2, (semitoneDiff / 12)) * 440); return (int) freq; } // Determines whether a string represents a rest bool is_rest(string s) { string test = ""; // TODO if (strcmp(s, test) == 0) { return true; } else { return false; } }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> int main01(void) { int a[]={10,7,1,9,4,6,7,3,2,0}; int n; int i=0; int j=0; int tmp=0; n=sizeof(a)/sizeof(a[0]);//Ԫظ printf("ǰ\n"); for(i=0;i<n;i++) { printf("%d",a[i]); } printf("\n"); //ѡ for(i=0;i<n-1;i++) { for(j=i+1;j<n;j++) { if(a[i]>a[j])// { tmp=a[i]; a[i]=a[j]; a[j]=tmp; } } } printf("\n"); for (i=0;i<n;i++) { printf("%d",a[i]); } printf("\n"); //ο㷨ij /* 1 2ÿ书 3 4 5ģ¸ 6д */ printf("\n"); system("pause"); return 0; } //Ϊβ˻λָ //void print_array(int a[1],int n) //void print_array(int a[],int n) void print_array(int *a,int n) { //a,ָãָͣ32λ4ֽ n=sizeof(a)/sizeof(a[0]);//Ԫظ printf("print_array:n=%d\n",n); int i=0; for (i=0;i<n;i++) { printf("%d",a[i]); } printf("\n"); } void sort_array(int a[10],int n) { int i,j,tmp; //ѡ for (i=0;i<n-1;i++) { for (j=i+1;j<n;j++) { if(a[i]>a[j])// { tmp=a[i]; a[i]=a[j]; a[j]=tmp; } } } int main(void) { int a[]={10,7,1,9,4,6,7,3,2,0}; int n; int i=0; int j=0; int tmp=0; n=sizeof(a)/sizeof(a[0]);//Ԫظ printf("n=%d\n",n); printf("ǰ\n"); print_array(a,n); sort_array(a,n); printf("\n"); print_array(a,n); printf("\n"); system("pause"); return 0; }
C
#include "FIFO.h" #include "UART.h" #include "BrailleConverter.h" #include "BrailleReaderMain.h" #include "ZigBee.h" #include "ST7735.h" #define STRINGMAX 100 BrailleString waitForString(void) { char string[STRINGMAX]; int size = UART_InString(string, STRINGMAX); BrailleString bstring = createBrailleString(string,size); return bstring; } BrailleString getUARTString(void) { BrailleString string; char toprint[STRINGMAX]; char i = 0; char size = 0; char done = 0; while(!done) { XBeeFrame frame = XBee_ReceiveFrame(); char char1 = frame.frame[8]; char char2 = frame.frame[9]; toprint[i++] = char1; toprint[i++] = char2; if(char1==0) { done=1; size=i-1; } if(char2==0) { done=1; size = i; } } i=0; while(toprint[i]!=0) { toprint[i] = toprint[i]; i++; } size = i; string = createBrailleString(toprint,size); return string; } BrailleString printUARTString(void) { BrailleString string; char toprint[STRINGMAX]; char i = 0; char size = 0; char done = 0; while(!done) { XBeeFrame frame = XBee_ReceiveFrame(); char char1 = frame.frame[8]; char char2 = frame.frame[9]; toprint[i++] = char1; toprint[i++] = char2; if(char1==0) { done=1; size=i-1; } if(char2==0) { done=1; size = i; } } i=0; while(toprint[i]!=0) { toprint[i] = toprint[i]; i++; } size = i; int y; for(y=0;y<size;y++) { ST7735_OutChar(toprint[y]); } string = createBrailleString(toprint,size); return string; } void communicationInit() { UART_Init(); XBee_Init_Receive(); } void OutCRLF(void){ UART_OutChar(CR); UART_OutChar(LF); }
C
/* * Autor : Leonardo Maldonado Pagnez * RA : 172017 */ #include "montador.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #define LOADMQ 0x0A #define LOADMQMX 0x09 #define STORMX 0x21 #define LOADMX 0x01 #define LOADminusMX 0x02 #define LOADmodMX 0x03 #define JUMPMX 0x0D #define JUMPM_dir 0x0E #define JUMPplus 0x0F #define JUMPplus_dir 0x10 #define ADDMX 0x05 #define ADDmodMX 0x07 #define SUBMX 0x06 #define SUBmodMX 0x08 #define MULmx 0x0B #define DIVmx 0x0C #define LSH 0x14 #define RSH 0x15 #define STORpar 0x12 #define STORpar_dir 0x13 #define org 1 #define align 2 #define wfill 3 #define set 4 #define word 5 /* Retorna: * 1 caso haja erro na montagem; * 0 caso nao haja erro. */ unsigned int count(unsigned int i) { unsigned int ret=1; while (i/=16) ret++; return ret; } unsigned checkDir(char *palavra){ char strs [] = ".org"; char strs1 [] = ".align"; char strs2 [] = ".wfill"; char strs3 [] = ".set"; if( (strcmp(palavra, strs) == 0)) return org; else if( ( strcmp(palavra, strs1) == 0) )return align; else if( (strcmp(palavra, strs2) == 0)) return wfill; else if( (strcmp(palavra, strs3) == 0) ) return set; return word; } int checkInstr(char* palavra){ char strsL1 [] = "LOAD"; char strsL2 [] = "LOAD-"; char strsL3 [] = "LOAD|"; char strsL4 [] = "LOADmq"; char strsL5 [] = "LOADmq_mx"; char strsS1 [] = "STOR"; char strsS2 [] = "STORA"; char strsJ1 [] = "JUMP"; char strsJ2 [] = "JMP+"; char strsA1 [] = "ADD"; char strsA2 [] = "ADD|"; char strsSu1 [] = "SUB"; char strsSu2 [] = "SUB|"; char strsM1 [] = "MUL"; char strsD1 [] = "DIV"; char strsL [] = "LSH"; if( (strcmp(palavra, strsL1) == 0)){ return LOADMX; } else if( ( strcmp(palavra, strsL2) == 0) ){ return LOADminusMX; } else if( (strcmp(palavra, strsL3) == 0)){ return LOADmodMX; } else if( ( strcmp(palavra, strsL4) == 0) ){ return LOADMQ; } else if( (strcmp(palavra, strsL5) == 0) ){ return LOADMQMX; } else if( (strcmp(palavra, strsS1) == 0) ){ return STORMX; } else if( ( strcmp(palavra, strsS2) == 0) ){ return STORpar; } else if( (strcmp(palavra, strsJ1) == 0) ){ return JUMPMX; } else if( (strcmp(palavra, strsJ2) == 0) ){ return JUMPplus; } else if( (strcmp(palavra, strsA1) == 0) ){ return ADDMX; } else if( (strcmp(palavra, strsA2) == 0) ){ return ADDmodMX; } else if( (strcmp(palavra, strsSu1) == 0) ){ return SUBMX; } else if( (strcmp(palavra, strsSu2) == 0) ){ return SUBmodMX; } else if( (strcmp(palavra, strsM1) == 0) ){ return MULmx; } else if( (strcmp(palavra, strsD1) == 0) ){ return DIVmx; } else if( (strcmp(palavra, strsL) == 0)){ return LSH; } return RSH; } unsigned int tipoDePuloOuStor(char* palavra, int pos){ char strsS2 [] = "STORA"; char strsJ1 [] = "JUMP"; char strsJ2 [] = "JMP+"; if( ( strcmp(palavra, strsS2) == 0) ){ if(pos) return 0x12; return 0x13; } else if( (strcmp(palavra, strsJ1) == 0) ){ if(pos) return 0x0D; return 0x0E; } else if( (strcmp(palavra, strsJ2) == 0) ){ if(pos) return 0x0F; return 0x10; } return 0; } unsigned retirarDuploPonto(char* palavra){ for(unsigned i = 0; palavra[i] != '\0'; i++){ if(i == 0 && palavra[i] == ':'){ for(unsigned j = 0; palavra[j] != '\0'; j++) palavra[j] = palavra[j+1]; } if(palavra[i+1] == '\0' && palavra[i] == ':'){ palavra[i] = palavra[i+1]; break; } } return 1; } /*Objetivo do Algoritmo: * 1. Ler os tokens do vetor * 2. Transforma-los apropriamente em codigo binario */ int emitirMapaDeMemoria(){ /*matrizes que guardam as palavras dos nomes (rotulos e simbolos)*/ char *matrizPalavras[4096], *matrizSimbolos[4096]; // variaveis unsigneds de controle do sistema unsigned sizeTokens, sizeDefRots = 0, sizePosDefRots = 0, currLinha = 0, dir, dirOuEsq = 0, sizeDefSimbs =0, ctrl =0, count = 0, count2 = 0, instr; //matrizes que guardam os valores/ posicoes que cada simbolo/ rotulo possui dentro do mapa unsigned *pos, *DirOuEsq, *SimbsValor; //token auxiliar que possui todos os tokens capturados na parte i Token TokenAdd[4096]; //Alocando memoria para as matrizes for(int i =0; i < 4096; i++) matrizPalavras[i] = (char *) malloc(sizeof(char) * 4096); for(int i =0; i < 4096; i++) matrizSimbolos[i] = (char *) malloc(sizeof(char) * 4096); pos = (unsigned *) malloc(sizeof(unsigned) * 4096); DirOuEsq = (unsigned *) malloc(sizeof(unsigned) * 4096); SimbsValor = (unsigned *) malloc(sizeof(unsigned) * 4096); //Leitura do vetor de Tokens para : Encontrar todos os rotulos sizeTokens = getNumberOfTokens(); //Recuperando os tokens encontrados na Parte 1 for(int i =0; i < sizeTokens; i++){ TokenAdd[i] = recuperaToken(i); } //Procurando todas as definicoes de Tokens, retirando o ':' for (int i = 0; i < sizeTokens; i++){ if (TokenAdd[i].tipo == DefRotulo){ strcpy(matrizPalavras[sizeDefRots], TokenAdd[i].palavra); retirarDuploPonto(matrizPalavras[sizeDefRots++]); } } //Funca subprincipal: Preenche todas as posicoes dos rotulos e preenche todos os valores do simbolos encontrados for (int j = 0; j < sizeTokens; j++){ switch(TokenAdd[j].tipo){ case DefRotulo: pos[sizePosDefRots] = currLinha; DirOuEsq[sizePosDefRots++] = dirOuEsq; break; case Diretiva: dir = checkDir(TokenAdd[j].palavra); if(dir == org){ if(TokenAdd[j+1].tipo == Decimal) currLinha = atoi(TokenAdd[j+1].palavra); else if(TokenAdd[j+1].tipo == Hexadecimal) currLinha = (unsigned) strtol(TokenAdd[j+1].palavra, NULL, 0); } else if(dir == align){ if(dirOuEsq){ dirOuEsq = 0; currLinha++; } } else if(dir == wfill){ currLinha = currLinha + atoi(TokenAdd[j+1].palavra); } else if(dir == word) currLinha++; else if(dir == set){ strcpy(matrizSimbolos[sizeDefSimbs], TokenAdd[j+1].palavra); if(TokenAdd[j+2].tipo == Decimal) SimbsValor[sizeDefSimbs++] = atoi(TokenAdd[j+2].palavra); else if(TokenAdd[j+2].tipo == Hexadecimal) SimbsValor[sizeDefSimbs++] = (unsigned) strtol(TokenAdd[j+2].palavra, NULL, 0); } break; case Instrucao: if(dirOuEsq){ currLinha++; dirOuEsq = 0; } else dirOuEsq = 1; break; default: break; } } //Prepara-se para poercorrer os tokens novamente currLinha = 0; dirOuEsq = 0; //Funcao principal: percorre os tokens e encontra todas as informacoes que preenchem o mapa: diretivas e instrucoes // simbolos, rotulos, hexadecimais e decimais sao tokens de auxilio para preencher a instrucao e encontrar o endereco a ser retornado for(int i = 0; i < sizeTokens; i++){ //Switch que difere instrucoes das diretivas switch(TokenAdd[i].tipo){ case Diretiva: //Identifica a diretiva encontrada dir = checkDir(TokenAdd[i].palavra); //Diretiva encontrada org => pula para o endereco requisitado no token a frente if(dir == org){ if(TokenAdd[i+1].tipo == Decimal) currLinha = atoi(TokenAdd[i+1].palavra); else if(TokenAdd[i+1].tipo == Hexadecimal) currLinha = (unsigned) strtol(TokenAdd[i+1].palavra, NULL, 0); } //Diretiva encontrada align => se o ponteiro estiver encontrado apos uma instrucao a esquerda, alinha e preenche com 00 000 o resto a direita else if(dir == align){ if(dirOuEsq){ printf("00 000\n"); currLinha++; dirOuEsq = 0; } } //Diretiva encontra wfill => preenche os enderecos selecionados com o valor encontrado no token a seguir else if(dir == wfill){ count = 0; count2 = 0; while(ctrl < atoi(TokenAdd[i+1].palavra) ){ if(TokenAdd[i+2].tipo == Nome){ while ( count < sizeDefRots && strcmp(matrizPalavras[count], TokenAdd[i+2].palavra) != 0 ) count++; while( count2 < sizeDefSimbs && strcmp(matrizSimbolos[count2], TokenAdd[i+2].palavra) != 0 ){ count2++; } if(!(count < sizeDefRots) && !(strcmp(matrizPalavras[count], TokenAdd[i+2].palavra) != 0)){ printf("Imposs�vel montar o c�digo!\n"); return 0; } else if(strcmp(matrizPalavras[count], TokenAdd[i+2].palavra) == 0 ) printf("%03X 00 000 00 %03X\n", currLinha++, pos[count] ); else if(!(count2 < sizeDefSimbs) && !(strcmp(matrizSimbolos[count2], TokenAdd[i+2].palavra) != 0)){ printf("Imposs�vel montar o c�digo!\n"); return 0; } else printf("%03X 00 000 00 %03X\n", currLinha++, SimbsValor[count2]); } else if(TokenAdd[i+2].tipo == Decimal){ printf("%03X 00 000 00 %03X\n", currLinha++, atoi(TokenAdd[i+2].palavra)); } else if(TokenAdd[i+2].tipo == Hexadecimal){ printf("%03X 00 000 00 %03X\n", currLinha++, (unsigned)strtol(TokenAdd[i+2].palavra, NULL, 0)); } ctrl++; } ctrl = 0; } //Diretiva encontrada word => preenche uma palavra na memoria else if(dir == word){ count = 0; count2 = 0; if(i+1 > sizeTokens ){ printf("Imposs�vel montar o c�digo!\n"); return 1; } if(TokenAdd[i+1].tipo == Nome){ while ( count < sizeDefRots && strcmp(matrizPalavras[count], TokenAdd[i+1].palavra) != 0 ) count++; while( count2 < sizeDefSimbs && strcmp(matrizSimbolos[count2], TokenAdd[i+1].palavra) != 0 ){ count2++; } if(strcmp(matrizPalavras[count], TokenAdd[i+1].palavra) == 0 ) printf("%03X 00 000 00 %03X\n", currLinha++, pos[count] ); else if( (count2 + 1 > sizeDefSimbs) && (strcmp(matrizSimbolos[count2], TokenAdd[i+1].palavra) != 0)){ printf("USADO MAS N�O DEFINIDO: %s!\n", TokenAdd[i+1].palavra); return 0; } else if(!(count2 < sizeDefSimbs) && !(strcmp(matrizSimbolos[count2], TokenAdd[i+1].palavra) != 0)){ printf("USADO MAS N�O DEFINIDO: %s!\n", TokenAdd[i+1].palavra); return 0; } else printf("%03X 00 000 00 %03X\n", currLinha++, SimbsValor[count2]); } else if(TokenAdd[i+1].tipo == Decimal){ printf("%03X 00 000 00 %03X\n", currLinha++, atoi(TokenAdd[i+1].palavra)); } else if(TokenAdd[i+1].tipo == Hexadecimal){ printf("%03X 00 000 00 %03X\n", currLinha++, (unsigned) strtol(TokenAdd[i+1].palavra, NULL, 0)); } } break; //Identificada uma instrucao case Instrucao: //Descobre qual instrucao instr = checkInstr(TokenAdd[i].palavra); //Descobre se o ponteiro esta a esquerda ou a direita na posicao atual da memoria if(dirOuEsq){ if(instr == LSH || instr == RSH) printf("%02X 000\n", instr); else if( instr == JUMPMX || instr == JUMPplus || instr == STORpar){ if(TokenAdd[i+1].tipo == Decimal) printf("%02X %03X\n", instr + 1, atoi(TokenAdd[i+1].palavra)); else if(TokenAdd[i+1].tipo == Hexadecimal) printf("%02X %03X\n", instr + 1, (unsigned)strtol(TokenAdd[i+1].palavra, NULL, 0)); else if(TokenAdd[i+1].tipo == Nome){ count = 0; while( count < sizeDefRots && strcmp(matrizPalavras[count], TokenAdd[i+1].palavra) != 0 ) count++; if(!(count < sizeDefRots) && !(strcmp(matrizPalavras[count], TokenAdd[i+1].palavra) != 0)){ printf("USADO MAS N�O DEFINIDO: %s!\n", TokenAdd[i+1].palavra); return 0; } else printf("%02X %03X\n", instr+1, pos[count] ); count = 0; } } else{ if(TokenAdd[i+1].tipo == Nome){ count = 0; while( count < sizeDefRots && strcmp(matrizPalavras[count], TokenAdd[i+1].palavra) != 0 ) count++; if(!(count < sizeDefRots) && !(strcmp(matrizPalavras[count], TokenAdd[i+1].palavra) != 0)){ printf("USADO MAS N�O DEFINIDO: %s!\n", TokenAdd[i+1].palavra); return 0; } else printf("%02X %03X\n", instr, pos[count] ); count = 0; } else if(TokenAdd[i+1].tipo == Decimal) printf("%02X %03X\n", instr, atoi(TokenAdd[i+1].palavra)); else if(TokenAdd[i+1].tipo == Hexadecimal) printf("%02X %03X\n", instr, (unsigned) strtol(TokenAdd[i+1].palavra, NULL, 0)); } dirOuEsq = 0; currLinha++; } else{ if(instr == LSH || instr ==RSH) printf("%03X %02X 000 ", currLinha, instr); else if(TokenAdd[i+1].tipo == Nome){ count = 0; while( count < sizeDefRots && strcmp(matrizPalavras[count], TokenAdd[i+1].palavra) != 0 ) count++; if(!(count < sizeDefRots) && !(strcmp(matrizPalavras[count], TokenAdd[i+1].palavra) != 0)){ printf("USADO MAS N�O DEFINIDO: %s!\n", TokenAdd[i+1].palavra); return 0; } else printf("%03X %02X %03X ", currLinha, instr, pos[count] ); count = 0; } else if(TokenAdd[i+1].tipo == Decimal) printf("%03X %02X %03X ", currLinha, instr, atoi(TokenAdd[i+1].palavra)); else if(TokenAdd[i+1].tipo == Hexadecimal) printf("%03X %02X %03X ", currLinha, instr, (unsigned) strtol(TokenAdd[i+1].palavra, NULL, 0)); dirOuEsq = 1; } break; default: break; } } //preenchimento final caso ultimo token seja uma instrucao a esquerda if(dirOuEsq) printf("00 000\n"); //Liberacao de memoria for(int i = 0; i < 4096; i++) free(matrizPalavras[i]); for(int i = 0; i < 4096; i++) free(matrizSimbolos[i]); free(pos); free(DirOuEsq); free(SimbsValor); return 0; }
C
#include <stdio.h> int main(){ int n; scanf("%d",&n); long x[n]; int i=0; int j=0; int c=0; long y[n]; int a=0; int k=0; int ad=0; for(i=0;i<n;i++){ scanf("%ld",&x[i]); } i=0; while(c!=-1 && i<n){ j=0; c=0; if(i==0){ y[a]=x[i]; a++; }else{ ad=0; k=0; while(k<a && ad!=1){ if(y[k]==x[i]){ ad=1; } k++; } if(ad!=1){ y[a]=x[i]; a++; } } j=0; while(c!=-1 && j<n){ if(x[i]==x[j]){ c++; if(c>x[i]){ c=-1; } } j++; } i++; } long sum=0; if(c!=-1){ for(i=0;i<a;i++){ sum+=y[i]; } printf("%ld\n",sum); }else{ printf("-1\n"); } return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include "sequencial_linear_list.h" void inicialize_list(List *l){ l->n = 0; } int size(List *l){ return l->n; } void print_list(List *l){ for(int i=0; i < l->n; i++){ printf("Name:%s | ", l->D[i].name); printf("Phone:%s | ", l->D[i].phone); printf("Address:%s\n", l->D[i].address); } } int insert_new_data(List *l, Data d){ if(l->n == 50){ return -1; } l->D[l->n] = d; l->n = l->n+1; } int sequencial_search(List *l, char* c){ int i = 0; while(i < l->n){ if(strcmp(c, l->D[i].name) == 0 || strcmp(c, l->D[i].phone) == 0 || strcmp(c, l->D[i].address) == 0){ printf("Name:%s | ", l->D[i].name); printf("Phone:%s | ", l->D[i].phone); printf("Address:%s\n", l->D[i].address); return i; } else i++; } return -1; } bool delete_element(List *l, char* c){ int pos, j; pos = sequencial_search(l, c); if(pos == -1) return false; for(j = pos; j < l->n-1; j++){ l->D[j] = l->D[j+1]; } l->n--; return true; } void order_names(List* l){ Data aux; for (int k = 0; k < l->n-1; k++){ if(strncmp(l->D[k].name, l->D[k+1].name, 4) > 0){ // printf("%s\n", l->D[k+1].name); aux = l->D[k]; l->D[k] = l->D[k+1]; l->D[k+1] = aux; order_names(l); //Aqui é feita uma recursão para garantir //que todos os itens serão corretamente ordenados } } } void reset(List* l){ l->n = 0; }
C
#include <stdio.h> int main(int argc, char *argv[]) { int i = 5; int *pi = &i; printf("i: %d, pi: %p\n", i, pi); return 0; }
C
#include "headers.h" void pinfo(char arg[]) { int id; if (arg != NULL) sscanf(arg, "%d", &id); else id = getpid(); char pidstat[500]; strcpy(pidstat, "/proc/"); char idchar[500]; sprintf(idchar, "%d", id); strcat(pidstat, idchar); char execstat[500]; strcpy(execstat, pidstat); strcat(pidstat, "/stat"); strcat(execstat, "/exe"); int printerr = 0; int fd = open(pidstat, O_RDONLY); if (fd < 0) { red(); printf("Process doesnt exist\n"); reset(); printerr = 1; } else { char statbuff[10000]; read(fd, statbuff, 10000); char *pinfoarg = strtok(statbuff, " "); printf("pid -- %s\n", pinfoarg); pinfoarg = strtok(NULL, " "); pinfoarg = strtok(NULL, " "); printf("Process Status -- %s\n", pinfoarg); for (int i = 0; i < 20; i++) pinfoarg = strtok(NULL, " "); printf("Memory -- %s\n", pinfoarg); } char execbuff[10000]; int t = readlink(execstat, execbuff, 10000); if (t < 0) { if (printerr == 0) { red(); printf("Readlink error\n"); reset(); } } else printf("Executable path -- %s\n", execbuff); close(fd); }
C
#ifndef Py_TUPLEOBJECT_H #define Py_TUPLEOBJECT_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* Another generally useful object type is a tuple of object pointers. For Python, this is an immutable type. C code can change the tuple items (but not their number), and even use tuples are general-purpose arrays of object references, but in general only brand new tuples should be mutated, not ones that might already have been exposed to Python code. *** WARNING *** PyTuple_SetItem does not increment the new item's reference count, but does decrement the reference count of the item it replaces, if not nil. It does *decrement* the reference count if it is *not* inserted in the tuple. Similarly, PyTuple_GetItem does not increment the returned item's reference count. */ #ifndef Py_LIMITED_API typedef struct { PyObject_VAR_HEAD PyObject *ob_item[1]; /* ob_item contains space for 'ob_size' elements. * Items must normally not be NULL, except during construction when * the tuple is not yet visible outside the function that builds it. */ } PyTupleObject; #endif extern PyTypeObject PyTuple_Type; extern PyTypeObject PyTupleIter_Type; #define PyTuple_Check(op) \ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TUPLE_SUBCLASS) #define PyTuple_CheckExact(op) (Py_TYPE(op) == &PyTuple_Type) PyObject * PyTuple_New(Py_ssize_t); Py_ssize_t PyTuple_Size(PyObject *); PyObject * PyTuple_GetItem(PyObject *, Py_ssize_t); int PyTuple_SetItem(PyObject *, Py_ssize_t, PyObject *); PyObject * PyTuple_GetSlice(PyObject *, Py_ssize_t, Py_ssize_t); #ifndef Py_LIMITED_API int _PyTuple_Resize(PyObject **, Py_ssize_t); #endif PyObject *PyTuple_Pack(Py_ssize_t, ...); #ifndef Py_LIMITED_API void _PyTuple_MaybeUntrack(PyObject *); #endif /* Macro, trading safety for speed */ #ifndef Py_LIMITED_API #define PyTuple_GET_ITEM(op, i) (((PyTupleObject *)(op))->ob_item[i]) #define PyTuple_GET_SIZE(op) Py_SIZE(op) /* Macro, *only* to be used to fill in brand new tuples */ #define PyTuple_SET_ITEM(op, i, v) (((PyTupleObject *)(op))->ob_item[i] = v) #endif int PyTuple_ClearFreeList(void); #ifndef Py_LIMITED_API void _PyTuple_DebugMallocStats(FILE *out); #endif /* Py_LIMITED_API */ COSMOPOLITAN_C_END_ #endif /* !Py_TUPLEOBJECT_H */
C
//******************************************************* // R O O M A D V E N T U R E // adventure.c // CS 344 // ku3nsting // May 10, 2017 //******************************************************* //includes: #include <stdio.h> //gives us basic file i/o and stuff #include <stdlib.h> //gives us all standard library functions #include <time.h> //gives us foundation for random numbers and time output #include <string.h> //necessary for strcpy to work #include <dirent.h> //lets us use directory as a type #include <sys/types.h> #include <unistd.h> //lets us access the process ID #include <sys/stat.h> //needed for mkdir according to http://www.gnu.org/software/libc/manual/html_node/Creating-Directories.html #include <pthread.h> //for mutex //exit codes #define SOMETHING_WENT_WRONG 1 #define ITS_ALL_GRAVY 0 //8 rooms this time to sync with filenames. Room 0 does not exist in game. #define NUMBER_OF_ROOMS 8 pthread_mutex_t annoyingMutex = PTHREAD_MUTEX_INITIALIZER; pthread_t game; pthread_t mtime; int notGame; int notTime; //Variables. Figure out how to use this info from files char newestDirName[64]; //use an enum to describe the type of each room enum type { START_ROOM, MID_ROOM, END_ROOM }; // Struct to define the room object itself struct room { enum type typeOfRoom; char roomName[16]; int number; int numberOfDoors; char doorNames[6][16]; }; //array of all rooms in the game struct room arrayOfRooms[NUMBER_OF_ROOMS]; //array of all room names in order char nameArray[NUMBER_OF_ROOMS][16]; //active room for game loop struct room currentRoom; //index of start room (found during struct creation) int startingRoom; //index of current active room int current; void initStrArray(char array[6][16]){ int y; for(y = 0; y < 6; y++){ strcpy(array[y], NULL); } } //code borrowed from 2.4 Manipulating Directories in tophat void manipDir(){ int newestDirTime = -1; // Modified timestamp of newest subdir examined char targetDirPrefix[20] = "kuenstir.rooms."; // Prefix we're looking for memset(newestDirName, '\0', sizeof(newestDirName)); DIR* dirToCheck; // Holds the directory we're starting in struct dirent *fileInDir; // Holds the current subdir of the starting dir struct stat dirAttributes; // Holds information we've gained about subdir dirToCheck = opendir("."); // Open up the directory this program was run in if (dirToCheck > 0) // Make sure the current directory could be opened { while ((fileInDir = readdir(dirToCheck)) != NULL) // Check each entry in dir { if (strstr(fileInDir->d_name, targetDirPrefix) != NULL) // If entry has prefix { // printf("Found the prefix: %s\n", fileInDir->d_name); stat(fileInDir->d_name, &dirAttributes); // Get attributes of the entry if ((int)dirAttributes.st_mtime > newestDirTime) // If this time is bigger { newestDirTime = (int)dirAttributes.st_mtime; memset(newestDirName, '\0', sizeof(newestDirName)); strcpy(newestDirName, fileInDir->d_name); //printf("Newer subdir: %s, new time: %d\n", // fileInDir->d_name, newestDirTime); } } } } closedir(dirToCheck); // Close the directory we opened //printf("Newest entry found is: %s\n", newestDirName); } int countLines(FILE* filePointer){ char placeholder; int lines; while(!feof(filePointer)){ placeholder = fgetc(filePointer); if(placeholder == '\n'){ lines++; } } return lines; } void rebuildAllRooms(){ //find the most recently made file in the directory chdir(newestDirName); //printf("\nNEWEST: %s \n", newestDirName); //printf("\nENTERED DIRECTORY!"); char* line = NULL; size_t len = 0; ssize_t read; int i; //open all files! for(i = 1; i<8; i++){ char roomName[10]; //define file name sprintf(roomName, "room_%d", i); //printf("%s \n", roomName); FILE *filePointer; //open the file! filePointer = fopen(roomName, "r"); //make sure file is real if (filePointer == NULL){ printf("GET OUTTA HEAH\n"); exit(SOMETHING_WENT_WRONG); } //else{ //printf("FILE OPENED!\n"); //} //initialize empty room strcpy(arrayOfRooms[0].roomName, "*"); //count the lines in the file int numLines = countLines(filePointer); //skip 11 bits to get to room name string fseek(filePointer, 11, SEEK_SET); char roomNameFile[20]; //use getline to store remainder of line read = getline(&line, &len, filePointer); //snap the newline character off the end of the input (thanks, stackoverflow!) strtok(line, "\n"); strtok(line, " "); sprintf(roomNameFile, "%s", line); //printf("###ROOM NAME: %s \n", roomNameFile); strcpy(arrayOfRooms[i].roomName, roomNameFile); strcpy(nameArray[i-1], roomNameFile); //assign numberofDoors variable arrayOfRooms[i].numberOfDoors = 0; //printf("TEST THE STRUCT: %s", arrayOfRooms[i].roomName); //make array of string to hold all doors for this room char doorName[6][16]; sprintf(doorName[0], "*"); sprintf(doorName[1], "*"); sprintf(doorName[2], "*"); sprintf(doorName[3], "*"); sprintf(doorName[4], "*"); sprintf(doorName[5], "*"); int y; //TEST THAT ARRAY WAS PROPERLY CLEANED //for(y = 0; y < 6; y++){ // printf("TEST original DOORNAME ARRAY: %s\n", doorName[y]); // } //use file contents to populate array of rooms int x = 0; fseek(filePointer, 0, SEEK_SET); //rewind back to start of file read = getline(&line, &len, filePointer); //Go to end of first line while ((read = getline(&line, &len, filePointer)) != -1) { //as long as there's something in the file to read //snap the newline character off the end of the input (thanks, stackoverflow!) strtok(line, "\n"); //grab line from file char subString[16]; char supString[40]; char typeCheck[16]; strcpy(supString, line); //printf("CHECK LINE: %s", line); //Make sure it's really room data if(line[0] == 'R'){ //then we're looking at a room type, not a door name sprintf(typeCheck, "%.*s", 12, supString + 10); //printf("PRE LOOP TC: %s \n", typeCheck); //printf("PRE LOOP TC0: %c \n", typeCheck[0]); //printf("PRE LOOP TC1: %c \n", typeCheck[1]); if(typeCheck[1] == 'S'){ //printf("CONDITIONAL CHECK: %c \n", typeCheck[0]); arrayOfRooms[i].typeOfRoom = START_ROOM; startingRoom = i; } else if(typeCheck[1] == 'E'){ //printf("CONDITIONAL CHECK: %c \n", typeCheck[0]); arrayOfRooms[i].typeOfRoom = END_ROOM; } else{ //printf("CONDITIONAL CHECK: %c \n", typeCheck[0]); arrayOfRooms[i].typeOfRoom = MID_ROOM; } //printf("###ROOM TYPE: %s \n", typeCheck); //printf("CHECK STRUCT: %d \n", arrayOfRooms[i].typeOfRoom); } else{ int i; sprintf(subString, "%.*s", 12, supString + 15); /* //Make sure it's really room data if(subString[2] == 'D' || subString[2] == 'A'){ //then we're looking at a room type, not a door name strcpy(doorName[x], subString); printf("###DOOR NAME: %s \n", doorName[x]); } */ if(subString[0] != ' ' && subString[0] != 'r'){ strcpy(doorName[x], subString); //printf("###DOOR NAME: %s \n", doorName[x]); } //strcpy(arrayOfRooms[i].doorNames[x], doorName[x]); //build an array of all room names in index order //give each room an array of room numbers it can access //int y; //for(y = 0; y < NUMBER_OF_ROOMS; y++){ // if(strcmp(doorName[x], nameArray[y]) == 0){ // arrayOfRooms[i].doors[y] = y; //puts(arrayOfRooms[i].doorNames[x]); x++; } } //TEST THAT ASSIGNMENT WORKED //for(y = 0; y < 6; y++){ // if(strcmp(doorName[y], "*") != 0) { // printf("$$TEST DOORNAME AFTER ASSIGNMENT: %s\n", doorName[y]); // } //} //int y; sprintf(arrayOfRooms[i].doorNames[0], "*"); sprintf(arrayOfRooms[i].doorNames[1], "*"); sprintf(arrayOfRooms[i].doorNames[2], "*"); sprintf(arrayOfRooms[i].doorNames[3], "*"); sprintf(arrayOfRooms[i].doorNames[4], "*"); sprintf(arrayOfRooms[i].doorNames[5], "*"); //printf("\n ITERATION: %d\n", i); for(y = 0; y < 6; y++){ if(strcmp(doorName[y], "*") != 0) { strcpy(arrayOfRooms[i].doorNames[y], doorName[y]); arrayOfRooms[i].numberOfDoors++; //printf("TEST NAMES in ROOM ARRAY: %s\n", arrayOfRooms[i].doorNames[y]); } } } } //initially set this to whatever room has type START_ROOM struct room currentRoom; //increment for every step taken int steps = 0; //controller for game loop int gameOn = 1; //array to hold steps taken char stepsArray[20][16]; //use strcpy(stepsTaken[index], "string") to write to this array int hereNow(){ //printf("TEST CURRENT ROOM: %s", currentRoom.roomName); if(currentRoom.typeOfRoom == END_ROOM){ printf("\nYOU HAVE FOUND THE END ROOM, CONGRATULATIONS!\n"); printf("\nYOU TOOK %d STEPS. YOUR PATH TO VICTORY WAS: \n", steps); //print stepsarray int i; for(i = 1; i <= steps; i++){ printf("%s",stepsArray[i]); if(i != (steps)){ printf(", "); } } printf("\n"); exit(ITS_ALL_GRAVY); } printf("\nCURRENT LOCATION: %s\n", currentRoom.roomName); printf("POSSIBLE CONNECTIONS: "); int x; for(x = 0; x < currentRoom.numberOfDoors; x++){ printf("%s", currentRoom.doorNames[x]); if(x != (currentRoom.numberOfDoors-1)){ printf(", "); } else{ printf("."); } } printf("\n"); return 1; } void* getTheTime(){ pthread_mutex_lock(&annoyingMutex); time_t systemTime; systemTime = time(NULL); printf("\n"); printf(ctime(&systemTime)); pthread_mutex_unlock(&annoyingMutex); return NULL; } int prompt(int current){ printf("WHERE TO? >"); char move[16]; scanf("%s", &move); if (strcmp(move, "time") == 0){ //print the time for the user pthread_mutex_unlock(&annoyingMutex); getTheTime(); pthread_mutex_lock(&annoyingMutex); return current; } else if (strcmp(move, "exit") == 0){ printf("Thanks for playing!"); exit(ITS_ALL_GRAVY); } else if(strcmp(move, "") != 0){ int i; for(i = 0; i < currentRoom.numberOfDoors; i++){ if(strcmp(move, currentRoom.doorNames[i]) != 0){ //printf("\nCHECK MOVE: %s", move); //find the room number with that name for(i = 0; i < NUMBER_OF_ROOMS; i++){ char checker[14]; sprintf(checker, "%s%c", arrayOfRooms[i].roomName, '\0'); //printf("\nCHECK CHECKER %d: %s", i, checker); //printf("\nCHECK MOVE %d: %s", i, move); if(strcmp(move, checker) == 0){ //printf("\nIT's A MATCH!\n"); //when found, make that the new currentRoom //printf("\nTESTING C ROOM BEFORE: %s\n", currentRoom.roomName); //currentRoom = arrayOfRooms[i]; //printf("TESTING move matched: %s\n", move); steps++; //add current room to stepsarray strcpy(stepsArray[steps], move); //strcpy(stepsArray[steps], move); return i; } } printf("HUH? SORRY, I DON'T UNDERSTAND THAT ROOM. TRY AGAIN.\n"); return current; } } } } void* doTheGame(){ pthread_mutex_lock(&annoyingMutex); notTime = pthread_create(&mtime, NULL, getTheTime, NULL); printf("\t* ******************** *\n"); printf("\t* *\n"); printf("\t* ADVENTURE GAME *\n"); printf("\t* *\n"); printf("\t* ******************** *\n"); //Get into the most recently created director manipDir(); //form an array of room objects with data from the files in the directory rebuildAllRooms(); //clean out stepsarrau sprintf(stepsArray[0], "*"); sprintf(stepsArray[1], "*"); sprintf(stepsArray[2], "*"); sprintf(stepsArray[3], "*"); sprintf(stepsArray[4], "*"); sprintf(stepsArray[5], "*"); //assign starting room currentRoom = arrayOfRooms[startingRoom]; current = startingRoom; //strcpy(stepsArray[0], arrayOfRooms[startingRoom].roomName); //make sure all rooms exist //int i; //for(i = 0; i < NUMBER_OF_ROOMS; i++){ // printf("%s, ",arrayOfRooms[i].roomName); //} while(gameOn == 1){ gameOn = hereNow(); if(gameOn == 1){ int newCur = prompt(current); //if(current != newCur){ // strcpy(stepsArray[steps], arrayOfRooms[current + 1].roomName); //} currentRoom = arrayOfRooms[newCur]; current = newCur; } } pthread_mutex_unlock(&annoyingMutex); return; } int main(){ notGame = pthread_create(&game, NULL, doTheGame, NULL); doTheGame(); pthread_join(game,NULL); return ITS_ALL_GRAVY; }
C
/** Copyright (c) 2011, University of Szeged * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * - Neither the name of University of Szeged nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Author: Andras Biro */ #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <linux/hiddev.h> #include <linux/input.h> #include <getopt.h> #include <string.h> #include <dirent.h> int main(int argc, char **argv){ #define M_ON 0 #define M_OFF 1 #define M_SPIKE 2 #define M_HOLE 3 char path[255]=""; char vid[8]=""; char pid[8]=""; char location[10]=""; int portnum=-1, mode=-1; struct option long_options[] = { {"devicefile", required_argument, 0, 'f'}, {"vid", required_argument, 0, 'v'}, {"pid", required_argument, 0, 'p'}, {"location", required_argument, 0, 'l'}, {"num", required_argument, 0, 'n'}, {"mode", required_argument, 0, 'm'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; char c; int option_index; while ((c = getopt_long (argc, argv, "hf:v:p:l:n:m:",long_options,&option_index)) != -1){ switch (c) { case 'h': printf("Usage: mcp2200gpio <arguments>\ \narguments:\ \n-h, --help Prints this help\ \n-f, --devicefile Selects the HID device to use\ \n-v, --vid Selects the vendor ID of the device to use\ \n-p, --pid Selects the product ID of the device to use\ \n-l, --location Selects the USB location of the device to use\ \n-n, --number Selects the GPIO port to manipulate (0..7)\ \n-m, --mode Selects the GPIO manipulation mode (on/off/spike/hole)\ \n example: mcp2200gpio -f /dev/usb/hiddev0 -n 4 -m hole\n"); exit(1); break; case 'f': strncpy(path,optarg,255); break; case 'v': strncpy(vid,optarg,8); break; case 'p': strncpy(pid,optarg,8); break; case 'l': strncpy(location,optarg,10); break; case 'n': portnum=atoi(optarg); break; case 'm': if(strcmp(optarg,"on")==0){ mode=M_ON; } else if(strcmp(optarg,"off")==0){ mode=M_OFF; } else if(strcmp(optarg,"spike")==0){ mode=M_SPIKE; } else if(strcmp(optarg,"hole")==0){ mode=M_HOLE; } else { perror("Invalid mode. Valid modes are: on/off/spike/hole\n"); exit(1); } break; } } if(strcmp(path,"")==0 && strcmp(vid,"")==0 && strcmp(location,"")==0){ fprintf(stderr,"No device selected\n"); exit(1); } if(portnum==-1){ fprintf(stderr,"No GPIO port selected\n"); exit(1); } if(mode==-1){ fprintf(stderr,"No mode selected\n"); exit(1); } if(strcmp(path,"")==0 ){//search for device DIR *d; struct dirent *dir; d = opendir("/dev/usb/"); if (d) { char temppath[255]; while ((dir = readdir(d)) != NULL) { if( strncmp(dir->d_name,"hiddev", 6)==0 ){ int fd=-1; strcpy(temppath, "/dev/usb/"); strcat(temppath, dir->d_name); fd=open(temppath, O_RDONLY); if(fd<0){ fprintf(stderr,"Can't open device: %s\n",temppath); exit(1); } struct hiddev_devinfo dinfo; ioctl(fd, HIDIOCGDEVINFO, &dinfo); close(fd); if(strcmp(vid, "") != 0){//check VID long vendor = strtoul(vid, NULL, 0); if( vendor != dinfo.vendor) continue; } if(strcmp(pid, "") != 0){//check PID long product = strtoul(pid, NULL, 0); if( product != dinfo.product) continue; } if(strcmp(location, "") != 0){//check location char* split; long loc = strtoul(location, &split, 0);; if( loc != dinfo.busnum) continue; split++;//jump over separator loc = strtoul(split, NULL, 0); if( loc != dinfo.devnum) continue; } if(strcmp(path, "") != 0){ fprintf(stderr, "Ambiguous match, please be more specific: %s and %s", path, temppath); exit(1); } strcpy(path, temppath); } } closedir(d); } } int fd=-1; fd=open(path, O_RDONLY); struct hiddev_report_info response; struct hiddev_usage_ref_multi command; response.report_type=HID_REPORT_TYPE_OUTPUT; response.report_id=HID_REPORT_ID_FIRST; response.num_fields=1; command.uref.report_type=HID_REPORT_TYPE_OUTPUT; command.uref.report_id=HID_REPORT_ID_FIRST; command.uref.field_index=0; command.uref.usage_index=0; command.num_values=16; command.values[0]=8; if(mode==M_ON||mode==M_SPIKE){ command.values[11]=1<<portnum; command.values[12]=0; }else{ command.values[11]=0; command.values[12]=1<<portnum; } ioctl(fd,HIDIOCSUSAGES, &command); ioctl(fd,HIDIOCSREPORT, &response); if(mode==M_HOLE||mode==M_SPIKE){ if(mode==M_HOLE){ command.values[11]=1<<portnum; command.values[12]=0; }else if(mode==M_SPIKE){ command.values[11]=0; command.values[12]=1<<portnum; } ioctl(fd,HIDIOCSUSAGES, &command); ioctl(fd,HIDIOCSREPORT, &response); } close(fd); return 0; }
C
/*Purpose: To declare 1.Functions used. 2.Non-primitive datatypes. 3.Global variable. Written by: P.Sai Srujan III B.Sc-Maths 171207 Written on: 20-03-2020 */ #include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct node { int cost; int quantity; struct node *right, *down; int r, c; int basic; int coeff; } node; typedef struct clos_path{ node *var; struct clos_path *next; } clos_path; typedef struct nonbasic{ node *var; struct nonbasic *next; } nonbasic; FILE *f; node* newNode(int d,int r,int c); void display(node *head); node* constructTableu(int m, int n); nonbasic* addNonb(node *g,nonbasic *head); void initialiseNW(node *head); int enterQuan(node *n,int r, int c); void iter_nFindSol(node *head); int findNum(int a[],int i,int j); node *findEnt(nonbasic *h); void findLeav(clos_path *h,node *ent,node *head); clos_path* addNodeCl(node *g,clos_path *head,int p); clos_path* findNbrs(node **t,clos_path *h,int c); clos_path* delNodeCl(node *h3,clos_path *h1); void Initialise(int *A,int *B,int n); int findNode(node *h,clos_path *h3); void nl(int k); void displayAns(node *head); void BalanceTableau(int *array,int *M,int *N,node *head);
C
#include "getopt_client.h" #include <getopt.h> #include <errno.h> #include <sys/types.h> #include <libgen.h> #include <stdlib.h> #include <stdio.h> ip_port getopt_client(int argc,char **argv) { ip_port ip_po_st; int ip_port; unsigned short port=0; char* ip; int c=0; const struct option longopts[]= { {"port", required_argument,0 ,'p'}, {"ip" , required_argument,0 ,'i'}, {"help", no_argument ,0 ,'h'}, {NULL , 0 ,NULL, 0 } }; while((c=getopt_long(argc,argv,"i:p:h",longopts,NULL))!=-1) { /*c必须放在while循环内*/ switch(c) { case 'p': ip_po_st.port=atoi(optarg); break; case 'i': ip_po_st.ip=optarg; break; case 'h': printf("端口:--p [args] \nIP地址:--i [args]\n帮助 h\n"); exit(0); } } ip_port=((!ip_po_st.ip) ||(!ip_po_st.port)); if(ip_port) { printf("请ip 、port同时输入!\n"); exit(0); } return ip_po_st; }
C
#include <pebble.h> #if PBL_IF_ROUND_ELSE(1, 0) == 1 #define PBL_ROUND 1 #else #define PBL_RECT 1 #endif #ifdef DBG #define log(...) APP_LOG(APP_LOG_LEVEL_DEBUG, __VA_ARGS__); #else #define log(...) ((void) 0) #endif typedef struct { GPoint origin; uint8_t radi; } circle_t; typedef enum {UP, DOWN, LEFT, RIGHT} direction; direction current_direction = RIGHT; Window* main_window; Layer* main_layer; TextLayer* text_layer; ActionBarLayer* action_bar; #ifdef PBL_ROUND static circle_t screen_bounds; #else static GRect screen_bounds; #endif static GRect label_bounds = { .size.h = PBL_IF_ROUND_ELSE(22,18) }; static GPoint line_start; static GPoint line_end; static int prev_points_count; static GPoint* prev_points; static bool draw_horizontally; static bool circle_contains_pt(circle_t *circle, GPoint *pt) { int16_t dx = circle->origin.x - pt->x; int16_t dy = circle->origin.y - pt->y; return dx * dx + dy * dy <= circle->radi * circle->radi; } static bool canvas_contains_pt(GPoint *pt) { bool contains = !grect_contains_point(&label_bounds, pt) && PBL_IF_ROUND_ELSE(circle_contains_pt, grect_contains_point)(&screen_bounds, pt); log("x=%d y=%d ret=%s", pt->x, pt->y, contains ? "true" : "false"); return contains; } static void reset_screen(GPoint point) { line_start = point; prev_points_count = 0; prev_points = NULL; } static void accel_tap_handler(AccelAxisType axis, int32_t direction) { free(prev_points); reset_screen(line_end); layer_mark_dirty(main_layer); } static void main_layer_update_callback(Layer* layer, GContext* context) { for (int count = 0; count < prev_points_count - 1; count++) { graphics_draw_line(context, prev_points[count], prev_points[count + 1]); } if (prev_points_count > 0) { graphics_draw_line(context, prev_points[prev_points_count - 1], line_start); } graphics_draw_line(context, line_start, line_end); } static void store_line() { GPoint* tmp_points = prev_points == NULL ? (int*)malloc(sizeof(GPoint)) : realloc(prev_points, ((prev_points_count + 1) * sizeof(GPoint))); if (tmp_points != NULL) { prev_points_count++; prev_points = tmp_points; prev_points[prev_points_count - 1] = line_start; line_start = line_end; } } static void move_right() { line_end.x++; if (canvas_contains_pt(&line_end)) { if (current_direction == LEFT) { store_line(); } current_direction = RIGHT; } else { line_end.x--; } } static void move_left() { line_end.x--; if (canvas_contains_pt(&line_end)) { if (current_direction == RIGHT) { store_line(); } current_direction = LEFT; } else { line_end.x++; } } static void move_up() { line_end.y--; if (canvas_contains_pt(&line_end)) { if (current_direction == DOWN) { store_line(); } current_direction = UP; } else { line_end.y++; } } static void move_down() { line_end.y++; if (canvas_contains_pt(&line_end)) { if (current_direction == UP) { store_line(); } current_direction = DOWN; } else { line_end.y--; } } static void up_click_handler(ClickRecognizerRef recognizer, void *context) { draw_horizontally ? move_left() : move_up(); layer_mark_dirty(main_layer); } static void down_click_handler(ClickRecognizerRef recognizer, void *context) { draw_horizontally ? move_right() : move_down(); layer_mark_dirty(main_layer); } static void select_click_handler(ClickRecognizerRef recognizer, void *context) { draw_horizontally = !draw_horizontally; char* text_layer_msg = draw_horizontally ? "Left/Right" : "Up/Down"; text_layer_set_text(text_layer, text_layer_msg); layer_mark_dirty((Layer*) text_layer); store_line(); } static void click_config_provider(void *context) { window_single_click_subscribe(BUTTON_ID_UP, up_click_handler); window_single_click_subscribe(BUTTON_ID_DOWN, down_click_handler); window_single_click_subscribe(BUTTON_ID_SELECT, select_click_handler); window_single_repeating_click_subscribe(BUTTON_ID_UP, 50, up_click_handler); window_single_repeating_click_subscribe(BUTTON_ID_DOWN, 50, down_click_handler); } static void window_load(Window *window) { } static void window_unload(Window *window) { } static void init_screen_bounds(GRect *bounds) { screen_bounds.origin = bounds->origin; #ifdef PBL_ROUND screen_bounds.origin.x += bounds->size.w / 2; screen_bounds.origin.y += bounds->size.h / 2; screen_bounds.radi = bounds->size.w / 2; #else screen_bounds.size = bounds->size; #endif #ifdef PBL_RECT log("w=%d h=%d", screen_bounds.size.w, screen_bounds.size.h); #else log("radi=%d", screen_bounds.radi); #endif } static void init_label_bounds(GRect *screen_bounds) { label_bounds.origin = screen_bounds->origin; label_bounds.origin.y += screen_bounds->size.h - label_bounds.size.h; label_bounds.size.w = screen_bounds->size.w; } static void init() { line_end = GPoint(20, 54); reset_screen(line_end); draw_horizontally = true; main_window = window_create(); window_set_window_handlers(main_window, (WindowHandlers) { .load = window_load, .unload = window_unload }); window_set_click_config_provider(main_window, click_config_provider); window_stack_push(main_window, true); Layer* window_layer = window_get_root_layer(main_window); GRect screen_rect = layer_get_bounds(window_layer); init_screen_bounds(&screen_rect); init_label_bounds(&screen_rect); main_layer = layer_create(screen_rect); layer_set_update_proc(main_layer, main_layer_update_callback); layer_add_child(window_layer, main_layer); text_layer = text_layer_create(label_bounds); text_layer_set_text(text_layer, "Left/Right"); text_layer_set_text_color(text_layer, GColorWhite); text_layer_set_background_color(text_layer, GColorBlack); text_layer_set_text_alignment(text_layer, GTextAlignmentCenter); layer_add_child(window_layer, (Layer*) text_layer); accel_tap_service_subscribe(accel_tap_handler); } static void deinit() { window_destroy(main_window); layer_destroy(main_layer); text_layer_destroy(text_layer); free(prev_points); } int main() { init(); app_event_loop(); deinit(); }
C
/*Ponteiros quando a varivel guarda o endereo ao invs do valor da varivel, muito til para quando necessrio quando implementa um programa que precisa de muitas funes, porque assim o valor continua salvo quando resgatar o valor em outra funo que invocou a outra. A engenharia usa programas que so complexos e que precisam de muitas funes, ento os ponteiros so teis nesses casos.*/
C
#include<iostream> using namespace std; int main() { int test; cin >> test; while(test--) { string str; cin >> str; int count=0, ans=1; for (int i=0; i<str.length()-1; i++) { if (str[i]!=str[i+1]) { ans *= pow(2, count); count = 0 } else if (i==str.length()-2) ans*=pow(2, count+1); else count+=1; } cout << ans << endl; } }
C
/************************************************************* * me06_3.c - Frequency Checker * programmed by Jaime Broñozo * * **************************************************************/ #include <stdio.h> int main(void) { char string[51], token; int instance = 0, index; printf("Input a string: "); fgets(string, sizeof(string), stdin); printf("Input a token: "); scanf("%c", &token); printf("The string was: %s\n", string); for(index = 0; string[index] != '\0'; index++) if(string[index] == token) instance++; printf("There are %d instances of '%c'.\n", instance, token); return 0; }
C
#include <unistd.h> #include <string.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "Interface.h" #include "argus.h" /** * @brief Lê, processa e comunica ao servidor um comando, proveniente de uma shell, a ser executado * * @param argc Nº de parametros do comando * @param argv Comando parametrizado * @return int 0 se conclui com sucesso, caso contrario devolve um outro numero */ int shell(int argc, char **argv) { //Validar formato da flag if (argc < 1 || argv[0][0] != '-' || argv[0][1] == '\0' || (argv[0][2] != '\0' && argv[0][1] != '-')) { write(2, "Comando Invalido\n", 18); return -2; } //Interpretar flag switch (argv[0][1]) { case 'i': argv[0] = "tempo-inatividade"; break; case 'm': argv[0] = "tempo-execucao"; break; case 'e': argv[0] = "executar"; break; case 'l': argv[0] = "listar"; break; case 't': argv[0] = "terminar"; break; case 'r': argv[0] = "historico"; break; case 'h': argv[0] = "ajuda"; break; case 'o': argv[0] = "output"; break; case '-': { if (strcmp(argv[0], "--serverstop") == 0) { execlp("pkill", "pkill", "argusd", NULL); return -1; } if (strcmp(argv[0], "--help") == 0) { char *out = "--help Flag List\n--serverstop Stop argusd Server \n-i Max Idle\n-m Max RunTime\n-e execute\n-l list tasks \n-t kill task\n-r history\n-h argus help\n-o task output\n"; write(1, out, strlen(out)); return 0; } } default: write(2, "Comando Invalido\n", 18); return -2; break; } int i,serverin, serverout; serverin = open(InputFIFOName, O_WRONLY, 0666); serverout = open(OutputFIFOName, O_RDONLY, 0666); if (serverin<0 || serverout<0) { write(2, "Error: Server Offline\n", 23); return -1; } //Concatenar argumentos char res[MaxLineSize]; res[0] = '\0'; for (i = 0; i < argc ; i++) { int bruh = MaxLineSize - strlen(res); strncat(res, argv[i], bruh); strncat(res, " ", bruh); } strncat(res, "\n",MaxLineSize - strlen(res)); //Enviar operação para o servidor write(serverin, res, strlen(res)); //Ler operação do servidor alarm(10); char buffer[ReadBufferSize]; if ((i = read(serverout, buffer, ReadBufferSize)) > 0) { write(1, buffer, i); } close(serverout); close(serverin); return 0; } /** * @brief Função de partida do progama */ int main(int argc, char *argv[]) { if (argc == 1) return argusRTE(); return shell(argc - 1, argv + 1); }
C
/* * @lc app=leetcode id=100 lang=c * * [100] Same Tree * * https://leetcode.com/problems/same-tree/description/ * * algorithms * Easy (51.66%) * Likes: 1610 * Dislikes: 49 * Total Accepted: 474.1K * Total Submissions: 917.5K * Testcase Example: '[1,2,3]\n[1,2,3]' * * Given two binary trees, write a function to check if they are the same or * not. * * Two binary trees are considered the same if they are structurally identical * and the nodes have the same value. * * Example 1: * * * Input: 1 1 * ⁠ / \ / \ * ⁠ 2 3 2 3 * * ⁠ [1,2,3], [1,2,3] * * Output: true * * * Example 2: * * * Input: 1 1 * ⁠ / \ * ⁠ 2 2 * * ⁠ [1,2], [1,null,2] * * Output: false * * * Example 3: * * * Input: 1 1 * ⁠ / \ / \ * ⁠ 2 1 1 2 * * ⁠ [1,2,1], [1,1,2] * * Output: false * * */ // @lc code=start /** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ bool isSameTree(struct TreeNode* p, struct TreeNode* q){ if(p == NULL || q == NULL) return p == q; //如果p == q == NULL 则return true; if(p->val != q->val) return false; if(isSameTree(p->left, q->left)) { return isSameTree(p->right, q->right); } else return false; } // @lc code=end
C
#include <string.h> #define MAXLEN 1000 /* max lenght of any input line */ #undef getline int getLine(char *, int); char *alloc(int); /* readlines: read input lines */ int readlines(char *lineptr[], int maxlines) { int len, nlines; char *p, line[MAXLEN]; nlines = 0; while ((len = getLine(line, MAXLEN)) > 0) if (nlines >= maxlines || (p = alloc(len)) == NULL) return -1; else { line[len-1] = '\0'; /* delete new line */ strcpy(p, line); lineptr[nlines++] = p; } return nlines; }
C
#include "dominion.h" #include "dominion_helpers.h" #include "stdio.h" #include "stdlib.h" #include "rngs.h" int testBuyCard(); int main(){ int x = testBuyCard(); if(x == 0){ return 0; }else{ printf("Error during testBuyCard() testing"); exit(200); } } int testBuyCard(){ struct gameState G; int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, tribute, smithy}; int numPlayers = 2; int player = 0; int seed = 1000; int supplyPos; initializeGame(numPlayers, k, seed, &G); supplyPos = 1; //Testing for normal functionality, perfect world scenario printf("testBuyCard() test: coins = %d, estate cost = %d (buy allowed)", G.coins, 2); buyCard(supplyPos, &G); if(G.hand[player][5] == 1){ printf("-- Test Passed \n"); }else if(G.hand[player][5] != 1){ printf("-- Test Failed \n"); } supplyPos = 3; //numBuys needs to be greater than 0 G.numBuys = 1; //Testing for buying card with not enough coins printf("testBuyCard() test: coins = %d, province cost = %d (buy not allowed)", G.coins, 8); int returnValue = buyCard(supplyPos, &G); if(returnValue == -1){ printf("-- Test Passed \n"); }else if(returnValue != -1){ printf("-- Test Failed \n"); } supplyPos = 11; G.coins = 5; //numBuys needs to be greater than 0 G.numBuys = 1; //Set mine cards to 0, should not be purchasable G.supplyCount[11] = 0; //Test to buy card that is no longer in the supply printf("testBuyCard() test: coins = %d, mine supply = %d (buy not allowed)", G.coins, G.supplyCount[11]); returnValue = buyCard(supplyPos, &G); if(returnValue == -1){ printf("-- Test Passed \n"); }else if(returnValue != -1){ printf("-- Test Failed \n"); } return 0; }
C
//Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures #include <stdio.h> #include <stdlib.h> #define NUM_OF_LETTERS 26 #define ASCII_OFFSET_A 65 int hash_char(char c) { return (c - ASCII_OFFSET_A)%NUM_OF_LETTERS; } int check_unique(char *input_string) { int char_hash_table[NUM_OF_LETTERS] = {0}; // hash table for each char (26 upper case only) if(input_string[0] == '\0') return 1; for(int i=0; input_string[i] != '\0'; i++) { int index = hash_char(input_string[i]); if(char_hash_table[index]) { // if we've already seen this char.. return false return -1; } char_hash_table[index]++; } return 1; } int main(void) { char string[] = "HELO"; int unique_result; unique_result = check_unique(string); printf("Unique: %d\n", unique_result); unique_result = check_unique("HELLO"); printf("Unique: %d\n", unique_result); unique_result = check_unique(""); printf("Unique: %d\n", unique_result); return 0; }
C
struct Node* copyRandomList(struct Node* head) { if (head == NULL) return NULL; ListNode* oldp = head; ListNode* newp = NULL; while (oldp != NULL) { newp = (ListNode*)malloc(sizeof(ListNode)); newp->val = oldp->val; newp->random = NULL; newp->next = oldp->next; oldp->next = newp; oldp = newp->next; } oldp = head; newp = oldp->next; while (oldp != NULL) { if (oldp->random != NULL) newp->random = oldp->random->next; oldp = newp->next; if (oldp == NULL) break; newp = oldp->next; } ListNode* newhead = head->next; oldp = head; newp = oldp->next; while (oldp != NULL) { oldp->next = newp->next; oldp = oldp->next; if (oldp == NULL) { newp->next = NULL; break; } newp->next = oldp->next; newp = newp->next; } return newhead; }
C
/** * @file tsqueue.h * @author Liam Powell * @date 2019-04-25 * * @brief Thread safe single-producer, multi-consumer FIFO queue. * * This is a thread safe single-producer, multi-consumer FIFO queue with the * following properties: * - Uses memory provided by the user for the queue itself, allowing the user * to ensure any alignment requirements. This memory may already contain * elements. * - Arbitrary queue element sizes. * - Supports pushing and popping multiple elements atomically. * - Leaves elements in the user provided memory after destroying the queue in * the order they would have been popped. */ #ifndef TSQUEUE_H #define TSQUEUE_H #include <stdbool.h> #include <stddef.h> #include <limits.h> /** Thread safe single-producer, multi-consumer FIFO queue. */ typedef struct tsqueue tsqueue; /** * @brief Create a new tsqueue. * * @param[out] queue The tsqueue, will be NULL if creation fails. * @param[in] data Array used to store queue elements, must not be used until * tsqueue_destroy() is called. * @param capacity The number of elements that @p data can hold. * @param elem_size The size of an element in @p data. * @param used The number of items already in @p data, these elements will be * accessible via tsqueue_pop(). The first element to be popped * will be the first element of @p data. * * @return Zero if the function succeeds, else a POSIX error number. */ int tsqueue_create(tsqueue **queue, void *data, size_t capacity, size_t elem_size, size_t used); /** * @brief Forces all tsqueue_put() and tsqueue_pop() functions using this * queue to exit and return TSQUEUE_CLOSED. * * Will block until all calls have exited. This function is intended to be * used before tsqueue_destroy as a way to signal to other threads that they * should stop reading from the queue. All future calls to tsqueue_put() and * tsqueue_pop() will also return TSQUEUE_CLOSED. * * @param[in] queue The tsqueue to close. */ void tsqueue_close(tsqueue *queue); /** * @brief Calls tsqueue_close() before freeing resources allocated by tsqueue * functions. * * Using a tsqueue while it is being destroyed or after it is destroyed will * cause undefined behaviour. tsqueue_close() and tsqueue_set_done() can be * useful for indicating to other threads that they should stop using the * queue. * * @param[in] queue The tsqueue to destroy. * @param[out] used The number of queue items left in the array provided to * tsqueue_create(). The first array element would have been * popped next. Can be NULL. */ void tsqueue_destroy(tsqueue *queue, size_t *used); /** * @brief Returns the capacity of the queue. * * @param[in] queue The tsqueue. * * @return The capacity of @p queue. */ size_t tsqueue_capacity(tsqueue *queue); /** * @brief Blocks until there are @p n_elems free spaces in the queue. * * @param[in] queue The tsqueue. * @param n_elems The number of elements to wait for. * * @return Zero if the function is successful. * * TSQUEUE_CLOSED if the queue is closed. * * TSQUEUE_TOO_MANY if @p n_elems is greater than the queue's * capacity. * * TSQUEUE_SINGLE_PRODUCER if a tsqueue_put() or * tsqueue_wait_for_space() call is already running. */ int tsqueue_wait_for_space(tsqueue *queue, size_t n_elems); /** * @brief Waits until there are @p n_elem free slots in the queue and then * adds all elements to the end of the queue. * * The first element in @p in will be popped first, after all elements already * in the queue. * * @param[in] queue The tsqueue. * @param n_elems The number of elements in @p in. * @param[in] in The items to insert in to the queue. * * @return Zero if the function is successful. * * TSQUEUE_CLOSED if the queue is closed. * * TSQUEUE_TOO_MANY if @p n_elems is greater than the queue's * capacity. * * TSQUEUE_SINGLE_PRODUCER if a a tsqueue_put() or * tsqueue_wait_for_space() call is already running. */ int tsqueue_put(tsqueue *queue, size_t n_elems, void *in); /** * @brief Retrieve elements from a tsqueue. * * Will block until there is n_elems elements unless the queue is closed or * `tsqueue_set_done(queue, true)` has been called. * * @param[in] queue The tsqueue. * @param[in,out] n_elems The maximum number of elements to place in @p * out. Will be set to the actual number of elements * retrieved. Will be set to zero if the queue is * closed or `tsqueue_set_done(queue, true)` has been * called. * @param[out] out Buffer to place the elements in. The first element was * first in the queue. * * @return Zero if the function is successful, including when zero elements * are retrieved. * * TSQUEUE_CLOSED if the queue is closed. */ int tsqueue_pop(tsqueue *queue, size_t *n_elems, void *out); /** * @brief Indicate that no more items will be placed in the queue. Can be * reversed. * * @param[in] queue The tsqueue. * @param done True to indicate that no more items will be placed in the * queue, false to reset to the normal state. */ void tsqueue_set_done(tsqueue *queue, bool done); enum { // The reason we use negative numbers is that POSIX errno // values are always positive. This allows us to return a POSIX error // value or a custom error value and differentiate between them. /** The queue was closed. */ TSQUEUE_CLOSED = INT_MIN, /** tsqueue_put() was called with more items than the queue can hold. */ TSQUEUE_TOO_MANY, /** A tsqueue_put() or tsqueue_wait_for_space() call was made while one * was already running. */ TSQUEUE_SINGLE_PRODUCER }; #endif /* TSQUEUE_H */
C
#include <stdlib.h> #include <string.h> #include "sortlist.h" typedef struct _sortlist { char **args; int maxarg; int curarg; } sortlist; static sortlist *sl; #define DEFMAXSL 8 void creatsl(void) { sl = malloc(sizeof(sortlist)); sl->args = malloc(DEFMAXSL * sizeof(char *)); sl->maxarg = DEFMAXSL; sl->curarg = 0; } void addtosl(char *arg) { if (sl->curarg == sl->maxarg) { sl->maxarg *= 2; sl->args = realloc(sl->args, sl->maxarg * sizeof(char *)); } sl->args[sl->curarg++] = strdup(arg); } static int cmpfunc(const void *a, const void *b) { const char **ia = (const char **) a; const char **ib = (const char **) b; return strcmp(*ia, *ib); } arguments* writesl(arguments *args) { qsort(sl->args, sl->curarg, sizeof(char *), cmpfunc); for (int i=0; i<sl->curarg; i++) args = addarg(args, sl->args[i]); return args; } void clearsl(void) { free(sl->args); free(sl); }
C
#pragma once #ifdef __cplusplus extern "C" { #endif #include <stdio.h> /// normalize the path format, converting all '\' to '/' and removing the trailing '/' void normalize_path( char *path ); /// check if a file/dir exists int exists( const char *path ); /// check if the given path is a file int is_file( const char *path ); /// check if the given path is a directory int is_dir( const char *path ); enum CreateDirResult { MKDIR_ERROR = 0, MKDIR_SUCCESS, MKDIR_EXISTS }; /// create a directory given its path. Returns a CreateDirResult value int create_dir( const char *path ); /// remove a directory given its path int remove_dir( const char *path ); /// open file using a path; it creates all the intermediate directories if needed; FILE* fopen_with_path( const char *path, const char *mode ); #ifdef __cplusplus } #endif
C
#include <msp432p401r.h> #include <stdio.h> #include <stdint.h> #include <helper.h> #include <uart.h> #include <lib_PAE2.h> // Funcion para que las ruedas puedan girar continuamente void wheelMode(void){ byte bID = BROADCASTING; // No obtenemos respuesta en este modo byte bInstruction = WRITE_DATA; byte bParameterLength = 5; byte bParameters[16]; // Empezamos por la direccin 0x06 (6) bParameters[0] = CW_ANGLE_LIMIT_L; // Datos a escribir bParameters[1] = 0; // CW_ANGLE_LIMIT_L = 0 bParameters[2] = 0; // CW_ANGLE_LIMIT_H = 0 bParameters[3] = 0; // CCW_ANGLE_LIMIT_L = 0 bParameters[4] = 0; // CCW_ANGLE_LIMIT_H = 0 // Enviamos los datos TxPacket(bID, bParameterLength, bInstruction, bParameters); } void moveWheel(byte ID, bool rotation, unsigned int speed) { struct RxReturn returnPacket; byte speed_H,speed_L; speed_L = speed; if(speed<1024){ // Velocidad max. 1023 if(rotation){ // Rotation == 1 speed_H = (speed >> 8)+4; // Mover a la derecha (CW) }else{ speed_H = speed >> 8; // Mover a la izquierda (CCW) } byte bInstruction = WRITE_DATA; byte bParameterLength = 3; byte bParameters[16]; // Empezamos por la direccin 0x20 (32) bParameters[0] = MOV_SPEED_L; // Escribimos la velocidad y la direccin bParameters[1] = speed_L; bParameters[2] = speed_H; TxPacket(ID, bParameterLength, bInstruction, bParameters); returnPacket = RxPacket(); } } void stop(void) { moveWheel(RIGHT_WHEEL, 0, 0); moveWheel(LEFT_WHEEL, 0, 0); } void turnLeft(unsigned int speed){ // Girar a la izquierda - Mover a la derecha todas las ruedas if(speed < 1024){ moveWheel(RIGHT_WHEEL, RIGHT, speed); moveWheel(LEFT_WHEEL, RIGHT, 0); } } void turnLeftD(unsigned int degree){ // Girar a la izquierda - Mover a la derecha todas las ruedas moveWheel(RIGHT_WHEEL, RIGHT, 300); moveWheel(LEFT_WHEEL, RIGHT, 0); delay_t(degree*28.5); stop(); } void turnOnItselfLeft(unsigned int speed) { // Girar a la izquierda - Mover a la derecha todas las ruedas if(speed < 1024){ moveWheel(RIGHT_WHEEL, RIGHT, speed); moveWheel(LEFT_WHEEL, RIGHT, speed); } } void turnRight(unsigned int speed) { // Girar a la derecha - Mover a la izquierda todas las ruedas if(speed < 1024){ moveWheel(RIGHT_WHEEL, LEFT, 0); moveWheel(LEFT_WHEEL, LEFT, speed); } } void turnRightD(unsigned int degree) { // Girar a la izquierda - Mover a la derecha todas las ruedas moveWheel(RIGHT_WHEEL, LEFT, 0); moveWheel(LEFT_WHEEL, LEFT, 300); delay_t(degree*28.5); stop(); } void turnOnItselfRight(unsigned int speed) { // Girar a la derecha - Mover a la izquierda todas las ruedas if(speed < 1024){ moveWheel(RIGHT_WHEEL, LEFT, speed); moveWheel(LEFT_WHEEL, LEFT, speed); } } void forward(unsigned int speed) { // Mover hacia delante if(speed < 1024){ moveWheel(RIGHT_WHEEL, RIGHT, speed); moveWheel(LEFT_WHEEL, LEFT, speed); } } void backward(unsigned int speed) { // Mover hacia atrs if(speed < 1024){ moveWheel(RIGHT_WHEEL, LEFT, speed); moveWheel(LEFT_WHEEL, RIGHT, speed); } } void motorLed(byte ID, bool status) { struct RxReturn returnPacket; byte bInstruction = WRITE_DATA; byte bParameterLength = 2; byte bParameters[16]; bParameters[0] = M_LED; bParameters[1] = status; TxPacket(ID, bParameterLength, bInstruction, bParameters); returnPacket = RxPacket(); } int readSensor(byte ID, byte sensor) { struct RxReturn returnPacket; byte bInstruction = READ_DATA; byte bParameterLength = 2; byte bParameters[16]; bParameters[0] = sensor; bParameters[1] = 1; TxPacket(ID, bParameterLength, bInstruction, bParameters); returnPacket = RxPacket(); return returnPacket.StatusPacket[5]; } void setCompareDistance(byte ID,unsigned int dist) { struct RxReturn returnPacket; byte bInstruction = WRITE_DATA; byte bParameterLength = 2; byte bParameters[16]; bParameters[0] = 0x14; //0x34 bParameters[1] = dist; TxPacket(ID, bParameterLength, bInstruction, bParameters); returnPacket = RxPacket(); } int getObstacleDetected(byte ID) { struct RxReturn returnPacket; byte bInstruction = READ_DATA; byte bParameterLength = 2; byte bParameters[16]; bParameters[0] = 0x20; bParameters[1] = 1; TxPacket(ID, bParameterLength, bInstruction, bParameters); returnPacket = RxPacket(); return returnPacket.StatusPacket[5]; } int readMaxDist(byte ID, byte position) { struct RxReturn returnPacket; byte bInstruction = READ_DATA; byte bParameterLength = 2; byte bParameters[16]; bParameters[0] = position; bParameters[1] = 1; TxPacket(ID, bParameterLength, bInstruction, bParameters); returnPacket = RxPacket(); return returnPacket.StatusPacket[5]; }
C
#include <curl/curl.h> #include <json-c/json.h> #include "global.h" /* holder for curl fetch */ struct curl_fetch_st { char *Payload; size_t Psize; }; struct curl_fetch_st curl_fetch; int json_object_count(struct json_object *jobj); char *URLString(char* u, char* s); CURLcode curl_fetch_url(CURL *ch, const char *_URL, const char *ref, struct curl_fetch_st *fetch); size_t curl_callback (void *contents, size_t size, size_t nmemb, void *userp); struct json_object * findobj(struct json_object *jobj, const char *key); void parse_json(char *res); /* insert path into url */ char *URLString(char* u, char* s) { char *buff = malloc((int)(strlen(u) + (int)strlen(s) + 1) * sizeof(char)); strcpy(buff,u); strcat(buff,s); return buff; } /* Curl and return json data */ int GetData(char EState[100]){ CURL *CHandle; CURLcode CCode; struct curl_fetch_st *CFetch = &curl_fetch; struct curl_slist *headers = NULL; if ((CHandle = curl_easy_init()) == NULL) { strcpy(EState,"Error 1: Failed to create curl handle in fetch_session"); return 1; } /* Set ref = URL if is empty */ if(ref == NULL) { ref = _URL; } char *URL_String = URLString(_URL, "/sync/maindata"); CCode = curl_fetch_url(CHandle, URL_String, ref, CFetch); /* fetch page and capture return code */ curl_easy_cleanup(CHandle); /* cleanup curl handle */ curl_slist_free_all(headers); if (CCode != CURLE_OK || CFetch->Psize < 1) { sprintf(EState,"Error 2: Failed to fetch %s", URL_String); free(URL_String); return 2; } if (CFetch->Payload != NULL) { free(URL_String); parse_json(CFetch->Payload); free(CFetch->Payload); /* free payload */ return 0; }else{ free(URL_String); strcpy(EState,"Failed to populate payload"); return 3; } } /* fetch and return url body via curl */ CURLcode curl_fetch_url(CURL *CHandle, const char *URL, const char *ref, struct curl_fetch_st *CFetch) { CURLcode CCode; /* curl result code */ CFetch->Payload = (char *) calloc(1, sizeof(CFetch->Payload)); /* init payload */ if (CFetch->Payload == NULL) { return CURLE_FAILED_INIT; } /* check payload */ CFetch->Psize = 0; /* init size */ curl_easy_setopt(CHandle, CURLOPT_URL, URL); /* set url to fetch */ curl_easy_setopt(CHandle, CURLOPT_WRITEFUNCTION, curl_callback); /* set calback function */ curl_easy_setopt(CHandle, CURLOPT_WRITEDATA, (void *) CFetch); /* pass fetch struct pointer */ curl_easy_setopt(CHandle, CURLOPT_USERAGENT, "libcurl-agent/1.0"); /* set default user agent */ curl_easy_setopt(CHandle, CURLOPT_TIMEOUT, 5); /* set timeout */ curl_easy_setopt(CHandle, CURLOPT_FOLLOWLOCATION, 1); /* enable location redirects */ curl_easy_setopt(CHandle, CURLOPT_MAXREDIRS, 1); /* set maximum allowed redirects */ curl_easy_setopt(CHandle, CURLOPT_REFERER, ref); /* set referer */ CCode = curl_easy_perform(CHandle); /* fetch the url */ return CCode; } /* call back for curl */ size_t curl_callback (void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; /* calculate buffer size */ struct curl_fetch_st *p = (struct curl_fetch_st *) userp; /* cast pointer to fetch struct */ p->Payload = (char *) realloc(p->Payload, p->Psize + realsize + 1); /* expand buffer */ if (p->Payload == NULL) { /* check buffer */ fprintf(stderr, "ERROR: Failed to expand buffer in curl_callback"); free(p->Payload); /* free buffer */ return -1; } memcpy(&(p->Payload[p->Psize]), contents, realsize); /* copy contents to buffer */ p->Psize += realsize; /* set new buffer size */ p->Payload[p->Psize] = 0; /* ensure null termination */ return realsize; /* return size */ } /* parse json object */ void parse_json(char *Data) { struct json_object *jdata,*data,*data2,*tmp; /* reset back to default value */ Max_Name_Length = Max_Name_Length_Default; Flag.Downloading = 0, Flag.Completed = 0; jdata = json_tokener_parse(Data); json_object_object_get_ex(jdata,"categories",&data); /* Parse categories list */ if(data != NULL) { categories = malloc(json_object_array_length(data) * sizeof(char*)); for(int i = 0; i < json_object_array_length(data); ++i) { tmp = json_object_array_get_idx(data,i); categories[i] = strdup(json_object_get_string(tmp)); categories_size = i + 1; Flag.Categories_Error = 0; } }else{ Flag.Categories_Error = 1; } /* Parse server status */ json_object_object_get_ex(jdata,"server_state",&data); if(data != NULL) { server = calloc((sizeof(srv_t)/sizeof(srv_t[0])), sizeof(char*)); FileSize(&server[0], Column_Width_Default, json_object_get_int64(findobj(data,"alltime_dl"))); FileSize(&server[1], Column_Width_Default, json_object_get_int64(findobj(data,"alltime_ul"))); Int2Str(&server[2], Column_Width_Default, (int)json_object_get_int(findobj(data,"dht_nodes"))); Dbl2Str(&server[3], Column_Width_Default, (double)json_object_get_double(findobj(data,"global_ratio")), 2); Flag.Server_Error = 0; }else{ Flag.Server_Error = 1; } /* Parse torrent */ json_object_object_get_ex(jdata,"torrents",&data); if(data != NULL) { torrent_size = json_object_count(data); /* Get torrent size */ if(torrent_size != 0) { hash = malloc(torrent_size * sizeof(char*)); name = malloc(torrent_size * sizeof(char*)); status = malloc(torrent_size * sizeof(char**)); info = malloc(torrent_size * sizeof(char**)); int j = 0; json_object_object_foreach(data, key2, val2) { hash[j] = strdup(key2); json_object_object_get_ex(data,key2,&data2); name[j] = strdup(json_object_get_string(findobj(data2,"name"))); Max_Name_Length = (strlen(name[j]) > Max_Name_Length) ? strlen(name[j]) : Max_Name_Length; status[j] = calloc((sizeof(sta_t)/sizeof(sta_t[0])), sizeof(char*)); Dbl2Str(&status[j][0], Column_Width_Default, (double)json_object_get_int(findobj(data2,"dlspeed"))/1000, 2); Dbl2Str(&status[j][1], Column_Width_Default, (double)json_object_get_int(findobj(data2,"upspeed"))/1000, 2); Dbl2Str(&status[j][2], Column_Width_Default, (float)json_object_get_double(findobj(data2,"progress")) * 100, 2); Dbl2Str(&status[j][3], Column_Width_Default, (double)json_object_get_double(findobj(data2,"ratio")), 3); /* info list - for multi dimensional array */ info[j] = calloc((sizeof(inf_t)/sizeof(inf_t[0])), sizeof(char*)); info[j][0] = strdup(json_object_get_string(findobj(data2,"state"))); Flag.Downloading = (strcmp(info[j][0],"downloading") == 0 && Flag.Downloading == 0) ? 1 : Flag.Downloading; Flag.Update = (HasChng(Flag.Downloading, Flag.Downloading_Ref) == 1 && Flag.Update == 0) ? 1 : 0; Flag.Completed = (strcmp(info[j][0],"uploading") == 0 || strcmp(info[j][0],"pausedUP") == 0 && Flag.Completed == 0) ? 1 : Flag.Completed; Flag.Update = (HasChng(Flag.Completed, Flag.Completed_Ref) == 1 && Flag.Update == 0) ? 1 : 0; FileSize(&info[j][1], Column_Width_Default, json_object_get_int64(findobj(data2,"total_size"))); FileSize(&info[j][2], Column_Width_Default, json_object_get_int64(findobj(data2,"amount_left"))); FileSize(&info[j][3], Column_Width_Default, json_object_get_int64(findobj(data2,"uploaded"))); Time2Str(&info[j][4], json_object_get_int64(findobj(data2,"eta"))); CombInt2Str(&info[j][5], json_object_get_int(findobj(data2,"num_seeds")), json_object_get_int(findobj(tmp,"num_complete"))); CombInt2Str(&info[j][6], json_object_get_int(findobj(data2,"num_leechs")), json_object_get_int(findobj(tmp,"num_incomplete"))); info[j][7] = strdup(json_object_get_string(findobj(data2,"category"))); j++; } } Flag.Torrent_Error = 0; }else{ Flag.Torrent_Error = 1; } json_object_put(jdata); } /* free all malloc */ void freeAll(void) { if(Flag.Categories_Error == 0 && categories_size != 0) { for(int i = 0; i < categories_size; ++i) { if(categories[i]) { free(categories[i]); } } free(categories); } if(Flag.Server_Error == 0 && (sizeof(srv_t)/sizeof(srv_t[0])) != 0) { for(int i = 0; i < (sizeof(srv_t)/sizeof(srv_t[0])); ++i) { if(server[i]) { free(server[i]); } } free(server); } if(Flag.Torrent_Error == 0 && torrent_size != 0) { for(int j = 0; j < torrent_size; ++j) { if(hash[j]) { free(hash[j]); } if(name[j]) { free(name[j]); } for(int s = 0; s < (sizeof(sta_t)/sizeof(sta_t[0])); ++s) { if(status[j][s]) { free(status[j][s]); } } if(status[j]) { free(status[j]); } for(int d = 0; d < (sizeof(inf_t)/sizeof(inf_t[0])); ++d) { if(info[j][d]) { free(info[j][d]); } } if(info[j]) { free(info[j]); } } if(hash) { free(hash); } if(name) { free(name); } if(status) { free(status); } if(info) { free(info); } } } /* find json object */ struct json_object * findobj(struct json_object *jobj, const char *key) { struct json_object *element; json_object_object_get_ex(jobj, key, &element); return element; } /* Return json object count */ int json_object_count(struct json_object *jobj) { int count = 0; json_object_object_foreach(jobj, key, val) { count++; } return count; } /* curl post pause*/ void post_pause(int Selected) { CURL *curl; CURLcode pcurl; char *post; curl = curl_easy_init(); char *url_string = URLString(_URL, "/command/pause"); curl_easy_setopt(curl, CURLOPT_URL, url_string); post = (char*)malloc((strlen(hash[Selected]) + 6) * sizeof(char)); sprintf(post,"hash=%s",hash[Selected]); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(post)); curl_easy_setopt(curl, CURLOPT_REFERER, ref); pcurl = curl_easy_perform(curl); if(pcurl != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(pcurl)); } curl_easy_cleanup(curl); if(url_string) { free(url_string); } if(post) { free(post); } } /* curl post pauseAll*/ void post_pauseAll() { CURL *curl; CURLcode pcurl; char *post; curl = curl_easy_init(); char *url_string = URLString(_URL, "/command/pauseAll"); curl_easy_setopt(curl, CURLOPT_URL, url_string); curl_easy_setopt(curl, CURLOPT_REFERER, ref); pcurl = curl_easy_perform(curl); if(pcurl != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(pcurl)); } curl_easy_cleanup(curl); if(url_string) { free(url_string); } } /* curl post resume*/ void post_resume(int Selected) { CURL *curl; CURLcode pcurl; char *post; curl = curl_easy_init(); char *url_string = URLString(_URL, "/command/resume"); curl_easy_setopt(curl, CURLOPT_URL, url_string); post = (char*)malloc((strlen(hash[Selected]) + 6) * sizeof(char)); sprintf(post,"hash=%s",hash[Selected]); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(post)); curl_easy_setopt(curl, CURLOPT_REFERER, ref); pcurl = curl_easy_perform(curl); if(pcurl != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(pcurl)); } curl_easy_cleanup(curl); free(url_string); if(post) { free(post); } } /* curl post resumeAll*/ void post_resumeAll() { CURL *curl; CURLcode pcurl; char *post; curl = curl_easy_init(); char *url_string = URLString(_URL, "/command/resumeAll"); curl_easy_setopt(curl, CURLOPT_URL, url_string); curl_easy_setopt(curl, CURLOPT_REFERER, ref); pcurl = curl_easy_perform(curl); if(pcurl != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(pcurl)); } curl_easy_cleanup(curl); free(url_string); } /* curl post category*/ int post_category(int choice, char *cat) { CURL *curl; CURLcode pcurl; char *post; curl = curl_easy_init(); char *url_string = URLString(_URL, "/command/setCategory"); curl_easy_setopt(curl, CURLOPT_URL, url_string); post = (char*)malloc((strlen(hash[choice]) + ((int)strlen(cat)) + 18) * sizeof(char)); sprintf(post,"hashes=%s&category=%s",hash[choice],cat); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(post)); curl_easy_setopt(curl, CURLOPT_REFERER, ref); pcurl = curl_easy_perform(curl); if(pcurl != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(pcurl)); } curl_easy_cleanup(curl); free(url_string); if(post) { free(post); } return 0; } /* curl post delete*/ int post_delete(int choice) { CURL *curl; CURLcode pcurl; char *post; curl = curl_easy_init(); char *url_string = URLString(_URL, "/command/delete"); curl_easy_setopt(curl, CURLOPT_URL, url_string); post = (char*)malloc((strlen(hash[choice]) + 6) * sizeof(char)); sprintf(post,"hashes=%s",hash[choice]); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(post)); curl_easy_setopt(curl, CURLOPT_REFERER, ref); pcurl = curl_easy_perform(curl); if(pcurl != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(pcurl)); } curl_easy_cleanup(curl); free(url_string); if(post) { free(post); } return 0; }
C
// 17/12/14 12:33 // Program to solve the problem Perfect Cubes on SPOJ #include<stdio.h> #include<stdlib.h> #include<math.h> #define MAX 101 #define int long int int bs(int*m,int,int,int); int main(){ int arr[MAX]; int i,a,b,c,d,diff=0; for(i=0;i<MAX;++i){ arr[i] = i*i*i; } for(a=2;a<MAX;++a){ for(b=2;b<a;++b){ for(c=b+1;c<a;++c){ diff = arr[a] - (arr[b]+arr[c]); d = bs(arr,0,MAX-1,diff); if(d && b<c && c<d){ printf("Cube = %ld, Triple = (%ld,%ld,%ld)\n",a,b,c,d); } } } } return 0; } int bs(int*arr,int l,int h,int num){ if(h>=l){ int mid = (l+h)/2; if(arr[mid] == num) return mid; if(arr[mid] > num) return bs(arr,l,mid-1,num); return bs(arr,mid+1,h,num); } return 0; }
C
#include <stdio.h> #include <string.h> #include <math.h> #include <assert.h> #include <sys/time.h> #include <sys/resource.h> #define MAX 200000000 void eratosthenes(char prime[], int n); void eratosthenes(char prime[], int n) { memset(prime, 1, n + 1); prime[0] = prime[1] = 0; int bound = round(sqrt(n)); for (int i = 2; i <= bound; ++i) { if (prime[i]) { for (int j = i * i; j <= n; j += i) prime[j] = 0; } } } void eratosthenes2(char prime[], int n); void eratosthenes2(char prime[], int n) { memset(prime, 1, n + 1); prime[0] = prime[1] = 0; int bound = round(sqrt(n)); for (int i = 2; i <= bound; ++i) { if (prime[i]) { for (int k = n / i, j = i * k; k >= i; --k, j -= i) if (prime[k]) prime[j] = 0; } } } void time_used(struct timeval *t); void time_used(struct timeval *t) { struct rusage ru; getrusage(RUSAGE_SELF, &ru); *t = ru.ru_utime; } char prime[MAX + 1], prime2[MAX + 1]; int main(void) { struct timeval t0, t1, t2, dt; time_used(&t0); eratosthenes(prime, MAX); time_used(&t1); timersub(&t1, &t0, &dt); printf("Ordinary method used %ld.%06d seconds\n", dt.tv_sec, dt.tv_usec); eratosthenes2(prime2, MAX); time_used(&t2); timersub(&t2, &t1, &dt); printf("Modified method used %ld.%06d seconds\n", dt.tv_sec, dt.tv_usec); for (int i = 1; i <= MAX; ++i) assert(prime[i] == prime2[i]); }
C
/* Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. The order of elements can be changed. It doesn't matter what you leave beyond the new length. Clarification: Confused why the returned value is an integer but your answer is an array? Note that the input array is passed in by reference, which means a modification to the input array will be known to the caller as well. Internally you can think of this: // nums is passed in by reference. (i.e., without making a copy) int len = removeElement(nums, val); // any modification to nums in your function would be known by the caller. // using the length returned by your function, it prints the first len elements. for (int i = 0; i < len; i++) {     print(nums[i]); } Example 1: Input: nums = [3,2,2,3], val = 3 Output: 2, nums = [2,2] Explanation: Your function should return length = 2, with the first two elements of nums being 2. It doesn't matter what you leave beyond the returned length. For example if you return 2 with nums = [2,2,3,3] or nums = [2,2,0,0], your answer will be accepted. Example 2: Input: nums = [0,1,2,2,3,0,4,2], val = 2 Output: 5, nums = [0,1,4,0,3] Explanation: Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length.   Constraints: 0 <= nums.length <= 100 0 <= nums[i] <= 50 0 <= val <= 100 */ #include <stdlib.h> #include <stdio.h> #include <string.h> int removeElement(int *nums, int numsSize, int val); int main(void) { int nums[] = {2,0,1,2,2,3,0,4,2,1}; int val = 2; int numsSize = sizeof(nums) / sizeof(nums[0]); int result; result = removeElement(nums, numsSize, val); printf("result = %d \n", result); } //using array int removeElement(int* nums, int numsSize, int val){ int i=0, j=numsSize-1, count = 0; int tmp; if ((numsSize == 0) || ((numsSize == 1) && (nums[0] != val))) return numsSize; while (i <= j) { if ((nums[i] != val) && (nums[j] != val)) { i++; } else if ((nums[i] == val) && (nums[j] != val)) { tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; i++; j--; } else if ((nums[i] != val) && (nums[j] == val)) { i++; j--; } else{ j--; } } return i; }
C
#pragma once #include <stdint.h> struct stack { uint8_t *elements; uint32_t count; uint32_t capacity; uint32_t elementSize; }; void stackInitialize(struct stack *stack, uint32_t elementSize); void stackFree(struct stack *stack); void *stackGet(struct stack *stack, uint32_t index); void *stackPop(struct stack *stack); void stackPush(struct stack *stack, void *data); void stackRemove(struct stack *stack, uint32_t index); void stackClear(struct stack *stack); uint32_t stackSize(struct stack *stack); int32_t stackIndexOf(struct stack *stack, void *element);
C
#include <stdlib.h> #include <string.h> #include <stdio.h> #include "lists.h" /** * list_len - print list elements *@h: pointer * Return: r */ size_t list_len(const list_t *h) { size_t r = 0; const list_t *temp; for (temp = h; temp != NULL; temp = temp->next) { r++; } return (r); }
C
#include<stdio.h> #define MAX 100001 int stack[MAX],ind=0,maxarr[MAX]; void push(int x) { stack[ind]=x; if(ind==0) maxarr[0]=stack[0]; else maxarr[ind]=stack[ind]>maxarr[ind-1]?stack[ind]:maxarr[ind-1]; ind++; } void pop() { ind--; } int main() { int n,x,ch; scanf("%d",&n); while(n--) { scanf("%d",&ch); if(ch==1) { scanf("%d",&x); push(x); } if(ch==2) pop(); if(ch==3) printf("%d\n",maxarr[ind-1]); } return 0; }
C
#ifndef LISTALINEAR #define LISTALINEAR #define MAX 10 typedef struct lista { int vet[MAX]; int ultimo; } Lista; int estaVazia(Lista *l); void criarLista(Lista *l); void inserirElemento(Lista *l, int v); void removerElemento(Lista *l, int i); void imprimeLista(Lista *l); #endif
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdbool.h> struct my_Interval { int start; int end; struct my_Interval* next; }; typedef struct { struct my_Interval* head; } RangeModule; RangeModule* rangeModuleCreate() { RangeModule* obj = malloc(sizeof(RangeModule)); obj->head = NULL; return obj; } void rangeModuleAddRange(RangeModule* obj, int left, int right) { struct my_Interval* ptr; struct my_Interval* new; struct my_Interval* prev; if (obj->head == NULL) { obj->head = malloc(sizeof(struct my_Interval)); obj->head->start = left; obj->head->end = right; obj->head->next = NULL; return; } ptr = obj->head; prev = NULL; new = malloc(sizeof(struct my_Interval)); // Find the first interval which has intersection with new interval while (ptr != NULL && left > ptr->end) { prev = ptr; ptr = ptr->next; } if (ptr == NULL) { // No intersection, append to the tier new->start = left; new->end = right; new->next = NULL; prev->next = new; } else { if (right < ptr->start) { // No intersection, become the new head or insert into list. new->start = left; new->end = right; new->next = ptr; if (prev == NULL) obj->head = new; else prev->next = new; } else { // Insert into list, and delete all intervals which has intersection with. new->start = left < ptr->start? left: ptr->start; new->end = right > ptr->end? right: ptr->end; if (prev == NULL) obj->head = new; else prev->next = new; while (ptr != NULL && new->end > ptr->end) { prev = ptr; ptr = ptr->next; free(prev); } if (ptr != NULL && new->end >= ptr->start) { new->end = ptr->end; new->next = ptr->next; free(ptr); } else { new->next = ptr; } } } return; } bool rangeModuleQueryRange(RangeModule* obj, int left, int right) { struct my_Interval* ptr = obj->head; while (ptr != NULL) { if (left >= ptr->start && right <= ptr->end) return true; ptr = ptr->next; } return false; } void rangeModuleRemoveRange(RangeModule* obj, int left, int right) { struct my_Interval* ptr; struct my_Interval* new; struct my_Interval* prev; struct my_Interval* tmp; if (obj->head == NULL) return; ptr = obj->head; prev = NULL; // Find the first interval which has intersection with deletion interval while (ptr != NULL && left > ptr->end) { prev = ptr; ptr = ptr->next; } // Have intersection with deletion interval if (ptr != NULL && right > ptr->start) { // If deletion within current interval, split it. if (left > ptr->start) { new = malloc(sizeof(struct my_Interval)); new->start = ptr->start; new->end = left; new->next = ptr; if (prev == NULL) obj->head = new; else prev->next = new; prev = new; } // Remove all intervals covered by deletion interval. while (ptr != NULL && right >= ptr->end) { tmp = ptr; ptr = ptr->next; free(tmp); } // The interval has partial intersection with deletion if (ptr != NULL && right > ptr->start) ptr->start = right; if (prev == NULL) obj->head = ptr; else prev->next = ptr; } return; } void rangeModuleFree(RangeModule* obj) { struct my_Interval* ptr = obj->head; struct my_Interval* prev; while (ptr != NULL) { prev = ptr; ptr = ptr->next; free(prev); } free(obj); } int main() { return 0; }
C
#ifndef PARSERS_C_ #define PARSERS_C_ static inline void ParsePHT2(uint32_t record, int * channel, uint64_t * timetag, uint64_t * oflcorrection); static inline void ParseHHT2_HH1(uint32_t record, int * channel, uint64_t * timetag, uint64_t * oflcorrection); static inline void ParseHHT2_HH2(uint32_t record, int * channel, uint64_t * timetag, uint64_t * oflcorrection); static inline void ParsePHT2(uint32_t record, int * channel, uint64_t * timetag, uint64_t * oflcorrection) { /* ProcessPHT2() reads the next records of a file until it finds a photon, and then returns. Inputs: filehandle FILE pointer with an open record file to read the photons oflcorrection pointer to an unsigned integer 64 bits. Will record the time correction in the timetags due to overflow (see output for details). buffer buffer from which to read the next record (file chunk read buffer) Outputs: filehandle FILE pointer with reader at the position of last analysed record oflcorrection offset time on the timetags read in the file, due to overflows. buffer buffer of the next chunk of records, containing for each a timetag and a channel number. If a photon is read, timetag of this photon. Otherwise, timetag == 0. It already includes the overflow correction so the value can be used directly. If a photon is read, channel of this photon. 0 will usually be sync and >= 1 other input channels. If the record is not a photon, channel == -1 for an overflow record, -2 for a marker record. */ /* FUNCTION TESTED QUICKLY */ const int T2WRAPAROUND = 210698240; union { unsigned int allbits; struct { unsigned time :28; unsigned channel :4; } bits; } Record; unsigned int markers; Record.allbits = record; if(Record.bits.channel == 0xF) //this means we have a special record { //in a special record the lower 4 bits of time are marker bits markers = Record.bits.time & 0xF; if(markers == 0) //this means we have an overflow record { *timetag = 0; *channel = -1; *oflcorrection += T2WRAPAROUND; // unwrap the time tag overflow } else //a marker { //Strictly, in case of a marker, the lower 4 bits of time are invalid //because they carry the marker bits. So one could zero them out. //However, the marker resolution is only a few tens of nanoseconds anyway, //so we can just ignore the few picoseconds of error. *timetag = *oflcorrection + Record.bits.time; *channel = -2; } } else { if((int)Record.bits.channel > 4) //Should not occur { *timetag = 0; *channel = -3; } else { *timetag = *oflcorrection + Record.bits.time; *channel = Record.bits.channel; } } } static inline void ParseHHT2_HH1(uint32_t record, int * channel, uint64_t * timetag, uint64_t * oflcorrection) { /* ProcessHHT2() reads the next records of a file until it finds a photon, and then returns. Inputs: filehandle FILE pointer with an open record file to read the photons HHVersion Hydrahard version 1 or 2. Depends on record type specification in the header. oflcorrection pointer to an unsigned integer 64 bits. Will record the time correction in the timetags due to overflow (see output for details). buffer buffer from which to read the next record (file chunk read buffer) Outputs: filehandle FILE pointer with reader at the position of last analysed record oflcorrection offset time on the timetags read in the file, due to overflows. buffer buffer of the next chunk of records, containing for each a timetag and a channel number. If a photon is read, timetag of this photon. Otherwise, timetag == 0. It already includes the overflow correction so the value can be used directly. If a photon is read, channel of this photon. 0 will usually be sync and >= 1 other input channels. If the record is not a photon, channel == -1 for an overflow record, -2 for a marker record. */ //FUNCTION TESTED const uint64_t T2WRAPAROUND_V1 = 33552000; union{ uint32_t allbits; struct{ unsigned timetag :25; unsigned channel :6; unsigned special :1; // or sync, if channel==0 } bits; } T2Rec; T2Rec.allbits = record; unsigned ch = T2Rec.bits.channel; unsigned sp = T2Rec.bits.special; unsigned tm = T2Rec.bits.timetag; // Negative Channels represent overflows or markers *oflcorrection += T2WRAPAROUND_V1 * (ch==0x3F); *channel = (!sp) * (ch + 1) - sp * ch; *timetag = *oflcorrection + tm; } static inline void ParseHHT2_HH2(uint32_t record, int *channel, uint64_t *timetag, uint64_t *oflcorrection) { /* ProcessHHT2() reads the next records of a file until it finds a photon, and then returns. Inputs: filehandle FILE pointer with an open record file to read the photons HHVersion Hydrahard version 1 or 2. Depends on record type specification in the header. oflcorrection pointer to an unsigned integer 64 bits. Will record the time correction in the timetags due to overflow (see output for details). buffer buffer from which to read the next record (file chunk read buffer) Outputs: filehandle FILE pointer with reader at the position of last analysed record oflcorrection offset time on the timetags read in the file, due to overflows. buffer buffer of the next chunk of records, containing for each a timetag and a channel number. If a photon is read, timetag of this photon. Otherwise, timetag == 0. It already includes the overflow correction so the value can be used directly. If a photon is read, channel of this photon. 0 will usually be sync and >= 1 other input channels. If the record is not a photon, channel == -1 for an overflow record, -2 for a marker record. */ /* FUNCTION TESTED */ const uint64_t T2WRAPAROUND_V2 = 33554432; union{ uint32_t allbits; struct{ unsigned timetag :25; unsigned channel :6; unsigned special :1; } bits; } T2Rec; T2Rec.allbits = record; unsigned ch = T2Rec.bits.channel; unsigned sp = T2Rec.bits.special; unsigned tm = T2Rec.bits.timetag; // Negative Channels represent overflows or markers // if(ch==0x3F) { //an overflow record // if(T2Rec.bits.timetag!=0) { // *oflcorrection += T2WRAPAROUND_V2 * T2Rec.bits.timetag * (ch==0x3F); // } // else { // if it is zero it is an old style single overflow // *oflcorrection += T2WRAPAROUND_V2; //should never happen with new Firmware! // } // } *oflcorrection += T2WRAPAROUND_V2 * tm * (ch==0x3F); *channel = ch + 1 - sp*(2*ch + 1); *timetag = *oflcorrection + tm; } #endif /* PARSERS_C_ */
C
/* *@author:lxf *@time:2017/5/15 14:39 *@title:os实验二第二题 *@subject:设计一个带参数的模块,其参数为某个进程的PID号, * 该模块的功能是列出改进程的家族信息,包括父进程, * 兄弟进程和子进程的的程序名、PID号 *@ps:因为带参数,加载模块时要指出参数,如 sudo insmod xfmodule_2.ko pid=xx */ #include<linux/init.h> #include<linux/module.h> #include<linux/kernel.h> #include<linux/sched.h> //有进程描述符task_struct #include<linux/moduleparam.h> //模块带参数 static int pid; //参数申明 module_param(pid,int,0644); //参数说明 MODULE_LICENSE("GPL"); static int __init xfmodule_2_init(void) { struct task_struct *p; struct task_struct *parent; struct task_struct *process; struct list_head *list; printk("xf's Process Begin!\n"); printk("Realitiont\t\tName\t\tPID\n"); //根据pid找到进程的地址 //p=find_task_by_vpid(pid); 这个函数现在不管用啦 p=pid_task(find_vpid(pid),PIDTYPE_PID); printk("Me\t\t\t%s\t\t%d\n",p->comm,p->pid); //输出自己的信息 parent=p->parent; //父进程 //特别注意children.next指向的是sibling成员,因此在使 //用list_entry()获得task_struct指针时, //参数要用sibling而不是children,更不是tasks成员 printk("father\t\t\t%s\t\t%d\n",parent->comm,parent->pid); list_for_each(list,&p->children) //~A~M~N~F~P~[~K { process=list_entry(list,struct task_struct,sibling); printk("Child\t\t\t%s\t\t%d\n",process->comm,process->pid); } // list= &parent->children; list_for_each(list,&parent->children) //遍历parent的children,即是他的sibling { process=list_entry(list,struct task_struct,sibling); if(process->pid!=pid) printk("Brother\t\t\t%s\t\t%d\n",process->comm,process->pid); } // list=&p->children; //子进程 list_for_each(list,&p->children) //遍历子进程 { process=list_entry(list,struct task_struct,sibling); printk("Child\t\t\t%s\t\t%d\n",process->comm,process->pid); } return 0; } static void __exit xfmodule_2_exit(void) { printk("xf's module_2_2 exit!\n"); } module_init(xfmodule_2_init); module_exit(xfmodule_2_exit);
C
#include<stdio.h> #include<limits.h> struct queue { unsigned int capacity; int front,rear,noe,*array; }; struct queue *makequeue(int capacity) { struct queue *q=(struct queue *)malloc(sizeof(struct queue)); q->capacity=capacity; q->front=0; q->rear=(capacity-1); q->noe=0; q->array=(int *)malloc(capacity*sizeof(int)); return q; } int isFull(struct queue *q) { return(q->noe==q->capacity); } int isEmpty(struct queue *q) { return(q->noe==0); } void enqueue(struct queue *q,int item) { if(isFull(q)) { printf("Queue is Overflow\n"); return ; } q->rear=(q->rear+1)%q->capacity; q->array[q->rear]=item; q->noe=q->noe+1; } int dequeue(struct queue *q) { if(isEmpty(q)) { printf("Underflow\n"); return INT_MIN; } int item=q->array[q->front]; q->front=(q->front+1)%q->capacity; q->noe=q->noe-1; return item; } int frontData(struct queue *q) { if(isEmpty(q)) { printf("Queue underflow \n"); return INT_MIN; } int item=q->array[q->front]; return item ; } int reartData(struct queue *q) { if(isEmpty(q)) { printf("Queue underflow \n"); return INT_MIN; } int item=q->array[q->rear]; return item ; } int main() { int capacity,data; printf("Enter capacity "); scanf("%d",&capacity); struct queue *q=makequeue(capacity); printf("Enter positive data\n"); scanf("%d",&data); while(data>=0) { enqueue(q,data); if(isFull(q)) { printf("Queue is Full\n"); break ; } scanf("%d",&data); } printf("Front data= %d\n",frontData(q)); printf("Rear data= %d\n",reartData(q)); printf("Deleting from queue \n"); while(!isEmpty(q)) { printf("%d\t",dequeue(q)); } }
C
/************************************************************************* > File Name: EP10.c > Author: > Mail: > Created Time: 2019年02月24日 星期日 15时11分07秒 ************************************************************************/ #include<stdio.h> #include<math.h> #define MAX_N 2000000 int Prime(long int j){ int i, k = 0; for(i = 2; i <= sqrt(j); ++i){ if(j % i == 0){ k++; break; } } if(k != 0){ return 0; } else{ return 1; } } int main(){ long int j = 1; long int sum = 0; while(j < MAX_N){ ++j; if(Prime(j) == 1) { sum += j; } } printf("%ld\n", sum); return 0; }
C
/* makes use of the trampoline technique, and a gcc extension to hold labels in variables > gcc -g example·trampoline.c > ./a.out mallocn succeded */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #define address_t_n UINT64_MAX #define address_t uint64_t #define continue_via_trampoline return typedef void **continuation; continuation mallocn(void **pt ,address_t n ,continuation success ,continuation fail){ if( n == address_t_n ) continue_via_trampoline fail; *pt = malloc(n+1); if(!*pt) continue_via_trampoline fail; continue_via_trampoline success; } int main(){ void *pt; goto *mallocn(&pt ,10 ,&&success ,&&fail); fail: fprintf(stderr, "mallocn failed \n"); return 1; success: fprintf(stderr, "mallocn succeded \n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct cliente { char nome0[100]; // nome do cliente char nome1[100]; // telefone do cliente char nome2[100]; // cpf char nome3[100]; // nome do produto char nome4[100]; // codigo do produto char nome5[100]; // preco do produto struct cliente *prox; }CLista; int validaCPF(char vetor[]){ int cpf, soma = 0, num = 10, resto, i,j; //verifica se todos caracteres sao iguais=invalido int iguais = 0; for(i=0;i<=10;i++){ if(vetor[0]==vetor[i]){ iguais++; } } if(iguais==11) return 0; if(strlen(vetor)==11){ //quantidade de numeros valido for (i = 0; i<=8; i++){ // 1 validacao cpf = vetor[i] - '0'; soma = soma + cpf*num; num--; } resto = (soma*10) % 11; cpf = vetor[9] - '0'; if(resto==cpf){ // 2 validacao soma = 0; num = 11; for (i = 0; i<=9; i++){ cpf = vetor[i] - '0'; soma = soma + cpf*num; num--; } resto = (soma*10) % 11; cpf = vetor[10] - '0'; if(resto==cpf){ return 1; //valido } }else{ return 0; // invalido } }else{ return 0; } } CLista* cadastro_cli(CLista *lst){ char cpf[12]; printf("CPF do Cliente: "); fflush(stdin); fgets(cpf, 12, stdin); int valido = validaCPF(cpf); if(valido!=1){ printf("CPF inválido!\n"); cadastro_cli(lst); return lst; } CLista *novo; novo = (CLista*)malloc(sizeof(CLista)); strcpy(novo->nome2,cpf); printf("Nome do Cliente: "); fflush(stdin); fgets(novo->nome0, 100, stdin); printf("Telefone do Cliente: "); fflush(stdin); fgets(novo->nome1, 100, stdin); printf("Nome do Produto: "); fflush(stdin); fgets(novo->nome3, 100, stdin); printf("Codigo do Produto: "); fflush(stdin); fgets(novo->nome4, 100, stdin); printf("Preco do Produto: "); fflush(stdin); fgets(novo->nome5, 100, stdin); novo->prox = NULL; if (lst==NULL) { // se lista de clientes estiver vazia lst = novo; } else { CLista *aux = lst; while(aux->prox!=NULL) aux = aux->prox; // procuro ultimo no aux->prox = novo; // ultimo cliente aponta para o novo } printf("Cliente cadastrado com sucesso!\n"); return lst; } void exibir_cli(CLista *lst){ if (lst==NULL) { printf("Nao ha clientes cadatrados!\n"); return; } char cpf[12]; system("cls"); printf("CPF do Cliente: "); fflush(stdin); fgets(cpf, 12, stdin); CLista *aux = lst; int valor = strcmp(aux->nome2,cpf); while(valor!=0 && aux!=NULL){ aux = aux->prox; if (aux!=NULL)valor = strcmp(aux->nome2,cpf); } if (aux==NULL && valor!=0){ printf("Usuario nao encontrado!\n"); return; } system("cls"); printf("Nome do Cliente: %s\n", aux->nome0); printf("Telefone do Cliente: %s\n", aux->nome1); printf("CPF do Cliente: %s\n", aux->nome2); printf("Nome do Produto: %s\n", aux->nome3); printf("Codigo do Produto: %s\n", aux->nome4); printf("Preco do Produto: R$%s\n", aux->nome5); return; } CLista* alterar_cli(CLista *lst, int op, char cpf[]){ CLista *aux = lst; int valor = strcmp(aux->nome2,cpf); while(valor!=0 && aux!=NULL){ aux = aux->prox; valor = strcmp(aux->nome2,cpf); } if (aux==NULL && valor!=0){ printf("Usuario nao encontrado!\n"); return lst; } switch(op){ case 1: system("cls"); printf("CADASTRO\n"); printf("Novo nome do Cliente: "); fflush(stdin); fgets(aux->nome0, 100, stdin); printf("Nome alterado com sucesso!\n\t\t"); system("pause"); break; case 2: system("cls"); printf("CADASTRO\n"); printf("Novo Telefone do Cliente: "); fflush(stdin); fgets(aux->nome1, 100, stdin); printf("Telefone alterado com sucesso!\n\t\t"); system("pause"); break; case 3: system("cls"); printf("CADASTRO\n\n"); printf("Novo CPF: "); fflush(stdin); fgets(aux->nome2, 100, stdin); printf("CPF alterado com sucesso!\n\t\t"); system("pause"); break; case 4: system("cls"); printf("CADASTRO\n\n"); printf("Novo nome do Produto: "); fflush(stdin); fgets(aux->nome3, 100, stdin); printf("Nome alterado com sucesso!\n\t\t"); system("pause"); break; case 5: system("cls"); printf("CADASTRO\n"); printf("Novo Codigo do Produto: "); fflush(stdin); fgets(aux->nome4, 100, stdin); printf("Codigo alterado com sucesso!\n\t\t"); system("pause"); break; case 6: system("cls"); printf("CADASTRO\n"); printf("Novo Preco do Produto: "); fflush(stdin); fgets(aux->nome5, 100, stdin); printf("Preço alterado com sucesso!\n\t\t"); system("pause"); break; } return lst; } CLista* remove_cli(CLista *lst){ // remove todos clientes alocados int op; printf("1 - Remover Cliente 2 - Remover todos os Clientes\n"); printf("Digite uma das alternativas acima: "); scanf("%d", &op); CLista *aux1 = lst; CLista *aux2; if(op==1){ system("cls"); char cpf[12]; printf("Digite o CPF do Cliente: "); scanf("%s", cpf); int compareString = strcmp(aux1->nome2,cpf); while (compareString!=0 && aux1!=NULL){ aux2 = aux1; aux1 = aux1->prox; compareString = strcmp(aux1->nome2,cpf); } if(compareString!=0){ // cpf nao encontrado na lista printf("Cliente nao encontrado!\n"); return lst; } if(aux1==lst){ // cliente se encontra no inicio da lista lst = lst->prox; free(aux1); } else if(aux1->prox==NULL) { // final da lista aux2->prox = NULL; free(aux1); } else { aux2->prox = aux1->prox; // meio da lista free(aux1); } printf("Cliente excluido com sucesso!\n"); } else if(op==2){ while(aux1!=NULL){ aux2 = aux1; aux1 = aux1->prox; free(aux2); } lst = NULL; printf("\nCadastros excluidos com sucesso!\n"); } else { printf("Opcao invalida!\n"); } return lst; } int main(void){ int op, op1, op2, op3, op4; char nome[100]; CLista *clientes = NULL; // criei uma lista vazia system("cls"); printf("Nome do Atendente: "); fflush(stdin); // limpa buffer do teclado scanf("%[^\n]s", nome); printf("Senha da Loja: "); scanf("%d", &op3); switch(op3) { case 123456: while(op!=5){ while(op2!=1){ system("color F4"); system("cls"); printf("--------------------------------------------------------------\n \n"); printf("\t Seja Bem Vindo, Atendente %s\n", nome); printf("_______________________________________________________________\n"); printf("1-Cadastrar\n"); printf("2-Exibir dados\n"); printf("3-Alterar\n"); printf("4-Excluir\n"); printf("5-Sair\n"); printf("--------------------------------------------------------------\n \n"); printf("Qual das opcoes deseja acessar? "); scanf("%d", &op); switch(op){ case 1: system("cls"); printf("\n\n\t\t\t INICIANDO CADASTRO\n"); printf("\t\t\t --------------------------\n\n"); clientes = cadastro_cli(clientes); printf("\n\n\t\t"); system("pause"); system("cls"); break; case 2: system("cls"); printf("\n\n\t\t\t EXIBIR CADASTRO\n"); printf("\t\t\t --------------------------\n\n"); exibir_cli(clientes); system("pause"); break; case 3: if (clientes!=NULL){ char cliente[100]; // cpf system("cls"); printf("--------------------------------------------------------------\n \n"); printf("CPF do Cliente: "); fflush(stdin); fgets(cliente, 100, stdin); printf("--------------------------------------------------------------\n \n"); printf("\n\n\t\t\t ALTERAR CADASTRO\n"); printf("\t\t\t --------------------------\n\n"); printf("1-Nome do Cliente\n"); printf("2-Telefone do Cliente\n"); printf("3-Nome do Produto\n"); printf("4-Codigo do Produto\n"); printf("5-Preco do Produto\n"); printf("Qual das opcoes deseja alterar? \n"); scanf("%d", &op1); clientes = alterar_cli(clientes,op1,cliente); } else { system("cls"); printf("Nao ha clientes cadastrados!\n"); } system("pause"); break; case 4: system("cls"); printf("\n\n\t\t\t EXCLUIR CADASTRO\n"); printf("\t\t\t --------------------------\n\n"); clientes = remove_cli(clientes); system("pause"); break; /* case 4: system("cls"); printf("\n\n\t\t\t EXCLUIR CADASTRO\n"); printf("\t\t\t --------------------------\n\n"); printf("1-Nome do Cliente\n"); printf("2-Telefone do Cliente\n"); printf("3-Nome do Produto\n"); printf("4-Codigo do Produto\n"); printf("5-Preco do Produto\n"); printf("6-Excluir todos os dados\n"); printf("Qual opcao voce deseja acessar?\n"); scanf("%d", &op4); switch(op4){ case 1: system("cls"); memset(&CA[contador].nome0, 0 , sizeof(CA[contador].nome0)); printf("Nome do Cliente Excluido!\n"); system("pause"); break; case 2: system("cls"); memset(&CA[contador].nome1, 0 , sizeof(CA[contador].nome1)); printf("Telefone do Cliente Excluido!\n"); system("pause"); break; case 3: system("cls"); memset(&CA[contador].nome2, 0 , sizeof(CA[contador].nome2)); printf("Nome do Produto Excluido!\n"); system("pause"); break; case 4: system("cls"); memset(&CA[contador].nome3, 0 , sizeof(CA[contador].nome3)); printf("Código do Produto Excluido!\n"); system("pause"); break; case 5: system("cls"); memset(&CA[contador].nome4, 0 , sizeof(CA[contador].nome4)); printf("Preço do Produto Excluido!\n"); system("pause"); break; case 6: system("cls"); memset(&CA[contador].nome0, 0 , sizeof(CA[contador].nome0)); memset(&CA[contador].nome1, 0 , sizeof(CA[contador].nome1)); memset(&CA[contador].nome2, 0 , sizeof(CA[contador].nome2)); memset(&CA[contador].nome3, 0 , sizeof(CA[contador].nome3)); memset(&CA[contador].nome4, 0 , sizeof(CA[contador].nome4)); printf("Todos dados excluidos com sucesso!\n"); system("pause"); break; } break; */ case 5: system("cls"); printf("Voce Deseja Realmente Sair do Sistema?\n"); printf("1 - Sim 2 - Nao\n"); scanf("%d", &op2); switch(op2){ case 1: system("cls"); printf("Acesso Finalizado com Sucesso! Volte Sempre!\n"); system("pause"); return 0; break; } } } break; default: printf("Opcao Invalida!"); break; } } }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <time.h> int main(void) { FILE *f; char ops[3][2] = {"W", "R", "D"}; char *fileops [10][2]; //limit maximum 10 file requests int x; int y; for(x = 0; x < 10; x++){ for(y = 0; y < 2; y++) { fileops[x][y] = (char *)malloc(sizeof(char *) * 10); } } srand(time(NULL)); int requestfile; int before; int rops; //generate random number of requests int requests = rand() % 11; //0 to 10 if (requests == 0) { requests = 1; } printf("Requests generated = %d \n", requests); printf("Requested File: Operation:\n"); for(x = 0; x < requests; x++){ //for random number of requests, generate random requested file and operation requestfile = rand() % 6; if (requestfile == 0) { requestfile = 1; } while(requestfile == before){ //file requested cannot be the same file requested as previous requestfile = rand() % 6; //0 to 5 if (requestfile == 0) { requestfile = 1; } } before = requestfile; rops = rand() % 3; // 0 to 2 sprintf(fileops[x][0], "%d", requestfile); strcpy(fileops[x][1],ops[rops]); printf("%9s %12s \n", fileops[x][0], fileops[x][1]); } //write to file f = fopen("fileoperations.txt", "w"); for(x = 0; x < requests; x++){ fprintf(f, "%s %s \n", fileops[x][0], fileops[x][1]); } fclose(f); //================================================================================= int cba[400]; //400 blocks of contiguous block allocation int cbatable[6][2] = { {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0} }; //contiguous block allocation table, limit only 5 files, start at index 1 int i; char * fileops2 [10][2]; //limit 10 operations for(x = 0; x < 10; x++){ for(y = 0; y < 2; y++) { fileops2[x][y] = (char *)malloc(sizeof(char *) * 10); } } char * filelist[20][4]; //limit 19 files for(x = 0; x < 20; x++){ for(y = 0; y < 4; y++) { filelist[x][y] = (char *)malloc(sizeof(char *) * 20); } } char *token; char delimiter[1] = " "; char line[48]; int column = 0; int linecount = 1; //start at 1 for file list int linecount2 = 0; //start at 0 for file operations //initialize cba, 0 means it is free blocks for (i = 0; i < 400; i++){ cba[i] = 0; } printf("\n"); printf("Reading in data from filelist.txt\n"); //read in filelist data from file f = fopen("filelist.txt", "r"); if(f != NULL){ while(fgets(line, sizeof line, f) != NULL){ //read each line //printf("Line: %s", line); token = strtok(line, delimiter); column = 0; while(token != NULL){ //read each column in line //printf("Token: %s \n",token); //save each column strcpy(filelist[linecount][column],token); column++; token = strtok(NULL,delimiter); if(column == 4){ break; } } linecount++; } printf("File Number: Filename: Blocks: Size:\n"); for(i = 1; i < linecount; i++){ printf("%11s %12s %10s %10s \n", filelist[i][0], filelist[i][1], filelist[i][2], filelist[i][3]); } } else { perror("Error reading filelist.txt!"); } fclose(f); //reset variables column = 0; printf("\n"); printf("Reading in data from fileoperations.txt\n"); //read in file operations from file f = fopen("fileoperations.txt", "r"); if(f != NULL){ while(fgets(line, sizeof line, f) != NULL){ //read each line //printf("Line: %s", line); token = strtok(line, delimiter); column = 0; while(token != NULL){ //read each column in line //printf("Token: %s \n",token); //save each column strcpy(fileops2[linecount2][column],token); column++; token = strtok(NULL,delimiter); if(column == 2){ //used to remove \n and \0 character from data break; } } linecount2++; } printf("Requested File: Operation:\n"); for(i = 0; i < linecount2; i++){ printf("%9s %12s \n", fileops2[i][0], fileops2[i][1]); } } else { perror("Error reading fileoperations.txt!"); } fclose(f); printf("\n"); printf("File List Size: %d\n", linecount-1); printf("File Operations Size: %d\n", linecount2); //---------------------------------------------------------- int position = 0; int allocblocks; int freeblocks = 0; int z; int w; int intable = 0; int filenum = 0; int elements = linecount; int s; int r; int q; char filename[50]; int index; int flag; int rblock; srand(time(NULL)); int rsize; int byte = 512; char block[20]; char size[20]; FILE *fp; fp = fopen("resultslog.txt", "w"); int lost = 0; //for each file operations for (i = 0; i < linecount2; i++){ //find the requested file in filelist fprintf(fp, "\n============================================\n"); printf("\n============================================\n"); fprintf(fp, "Doing File Requested = %s Operation = %s\n", fileops2[i][0], fileops2[i][1]); printf("Doing File Requested = %s Operation = %s\n", fileops2[i][0], fileops2[i][1]); for(x = 1; x < elements; x++){ if(strcmp(fileops2[i][0],filelist[x][0]) == 0){ lost = 1; filenum = atoi(fileops2[i][0]); strcpy(filename, filelist[x][1]); allocblocks = atoi(filelist[x][2]); //find if memory already allocated for file, there is a entry in cba table for(w = 0; w < 5; w++){ if(cbatable[filenum][1] != 0){ intable = 1; } } if (intable == 1){ //memory has file fprintf(fp,"Starting position: %d\n", cbatable[filenum][1]); printf("Starting position: %d\n", cbatable[filenum][1]); fprintf(fp,"Block Length: %d \n", allocblocks); printf("Block Length: %d \n", allocblocks); //write operation if (strcmp(fileops2[i][1],"W") == 0){ fprintf(fp,"Status: File was written! \n"); printf("Status: File was written! \n"); } else if (strcmp(fileops[i][1],"R") == 0){ //read operation if( access( filename, F_OK ) != -1 ) { fprintf(fp,"Status: File was read! \n"); printf("Status: File was read! \n"); fprintf(fp,"File Number: %s \nFile Start Block: %d \nFile Blocks Length: %d \n", fileops2[i][0], cbatable[filenum][0], cbatable[filenum][1]); printf("File Number: %s \nFile Start Block: %d \nFile Blocks Length: %d \n", fileops2[i][0], cbatable[filenum][0], cbatable[filenum][1]); } else { fprintf(fp,"Status: Error! File does not exist. Cannot Read! \n"); printf("Status: Error! File does not exist. Cannot Read! \n"); } } else { //delete operation if( access( filename, F_OK ) != -1 ) { fprintf(fp,"Status: File was deleted! \n"); printf("Status: File was deleted! \n"); //remove entry from cba memory, cba table and filelist for(s = cbatable[filenum][0]; s <= allocblocks; s++){ cba[s] = 0; } cbatable[filenum][0] = 0; cbatable[filenum][1] = 0; for(r = 1; r <= elements; r++){ if(strcmp(filelist[r][1], filename) == 0){ //if is the deleted filename index = r; flag = remove(filelist[r][1]); } } //remove the record in filelist for (r = index; r <= elements -1; r++ ){ strcpy(filelist[r][0],filelist[r+1][0]); strcpy(filelist[r][1],filelist[r+1][1]); strcpy(filelist[r][2],filelist[r+1][2]); strcpy(filelist[r][3],filelist[r+1][3]); } elements--; } else { fprintf(fp,"Status: Error! File does not exist. Cannot delete! \n"); printf("Status: Error! File does not exist. Cannot delete! \n"); } } } else { //memory does not have file //find free blocks in contiguous block allocation for(y = 0; y < 400; y++){ if(cba[y] == 0){ freeblocks++; if(freeblocks == allocblocks){ //if enough free blocks position = y - freeblocks + 1; break; } } else { freeblocks = 0; } } if(freeblocks == allocblocks){ //have enough free blocks fprintf(fp,"Starting position: %d\n", position); printf("Starting position: %d\n", position); fprintf(fp,"Block Length: %d \n", allocblocks); printf("Block Length: %d \n", allocblocks); for(z = position; z < (position+allocblocks); z++) { //allocate blocks for file cba[z] = filenum; } //write to contiguous block allocation table cbatable[filenum][0] = position; cbatable[filenum][1] = allocblocks; //write operation if(strcmp(fileops2[i][1], "W") == 0){ fprintf(fp,"Status: File was written! \n"); printf("Status: File was written! \n"); //create file f = fopen(filename, "w"); fclose(f); strcpy(filelist[elements+1][1], filename); //generate random number of block rblock = rand() % 41; if (rblock == 0){ rblock = 1; } //store block to filelist sprintf(block, "%d", rblock); //strcpy(filelist[elements+1][2],block); //calculate size rsize = rblock * byte; sprintf(size, "%d", rsize); //store size to filelist //strcpy(filelist[elements+1][3], size); elements++; } else if(strcmp(fileops2[i][1], "R") == 0){ //read operation if( access( filename, F_OK ) != -1 ) { fprintf(fp,"Status: File was read! \n"); printf("Status: File was read! \n"); fprintf(fp,"File Number: %s \nFile Start Block: %d \nFile Blocks Length: %d \n", fileops2[i][0], cbatable[filenum][0], cbatable[filenum][1]); printf("File Number: %s \nFile Start Block: %d \nFile Blocks Length: %d \n", fileops2[i][0], cbatable[filenum][0], cbatable[filenum][1]); } else { fprintf(fp,"Status: Error! File does not exist. Cannot Read! \n"); printf("Status: Error! File does not exist. Cannot Read! \n"); for(s = cbatable[filenum][0]; s < (cbatable[filenum][0]+allocblocks); s++){ cba[s] = 0; } cbatable[filenum][0] = 0; cbatable[filenum][1] = 0; } } else { //delete operation if( access( filename, F_OK ) != -1 ) { fprintf(fp,"Status: File was deleted! \n"); printf("Status: File was deleted! \n"); //remove entry from memory, cba table and filelist for(s = cbatable[filenum][0]; s < (cbatable[filenum][0]+allocblocks); s++){ cba[s] = 0; } cbatable[filenum][0] = 0; cbatable[filenum][1] = 0; for(r = 1; r <= elements; r++){ if(strcmp(filelist[r][1], filename) == 0){ //if is the deleted filename index = r; flag = remove(filelist[r][1]); } } //remove the record in filelist for (r = index; r <= elements -1; r++ ){ strcpy(filelist[r][0],filelist[r+1][0]); strcpy(filelist[r][1],filelist[r+1][1]); strcpy(filelist[r][2],filelist[r+1][2]); strcpy(filelist[r][3],filelist[r+1][3]); } elements--; } else { fprintf(fp,"Status: Error! File does not exist. Cannot delete! \n"); printf("Status: Error! File does not exist. Cannot delete! \n"); for(s = cbatable[filenum][0]; s < (cbatable[filenum][0]+allocblocks); s++){ cba[s] = 0; } cbatable[filenum][0] = 0; cbatable[filenum][1] = 0; } } } else { fprintf(fp,"Status: Error! Cannot allocate memory for file %s!\n", filenum); printf("Status: Error! Cannot allocate memory for file %s!\n", filenum); } //reset variables freeblocks = 0; position = 0; } //reset variables intable = 0; filenum = 0; flag = 0; break; } } if(lost == 0){ printf("Status: Error! File does not exist. Cannot do operation! \n"); } lost = 0; } fprintf(fp,"\n====================================================================================================\n"); printf("\n====================================================================================================\n"); fprintf(fp,"Contiguous Block Allocation Memory: \n"); printf("Contiguous Block Allocation Memory: \n"); int display = 0; for(x = 0; x < 4; x++){ fprintf(fp,"Blocks %d to %d \n", display+1, display+100); printf("Blocks %d to %d \n", display+1, display+100); for(i = 0; i < 100; i++){ if(i == 50){ fprintf(fp,"\n"); printf("\n"); } fprintf(fp,"%d ", cba[display+i]); printf("%d ", cba[display+i]); } display = display + 100; fprintf(fp,"\n\n"); printf("\n\n"); } fclose(fp); }
C
/****************************** NAAUTIL3.C ************************************ "Numerical Analysis Algorithms in C" Utilities III v4.2 ******************************************************************************/ /* ** This file is very similar to "naautil.c". It contains less frequently ** used dynamic memory allocation routines to create very flexible complex ** vectors, matrices, and cubes. ** ** It contains the following procedures and functions: ** ** Return Procedure ** Type Name Description ** --------------------------------------------------------------------- ** fcomplex*** ccube - Allocates a 3-D array of fcomplex ** fcomplex** cmatrix - Allocates a 2-D array of fcomplex ** fcomplex* cvector - Allocates a 1-D array of fcomplex ** ** void free_ccube - Frees the allocated 3-D array memory ** void free_cmatrix - Frees the allocated 2-D array memory ** void free_cvector - Frees the allocated 1-D array memory ** ** These functions were derived from the text "Numerical Recipes in C". */ /***************** * INCLUDE FILES * *****************/ /* NOTE: Requires that "naautil.h" be included only once! */ #include "complex.c" /* Needed for complex arithmetic. */ /************************ * FUNCTION PROTOTYPING * ************************/ #if ANSI == TRUE /* Set this flag once in "naautil.h" */ /* ANSI STANDARD PROTOTYPING (Post-December 14, 1989) */ fcomplex*** ccube (int a, int b, int c, int d, int e, int f); fcomplex** cmatrix (int a, int b, int c, int d); fcomplex* cvector (int a, int b); void free_ccube (fcomplex ***m, int a, int b, int c, int d, int e, int f); void free_cmatrix (fcomplex **m, int a, int b, int c, int d); void free_cvector (fcomplex *v, int a, int b); #else /* OLDER STYLE PROTOTYPING (Pre-December 14, 1989) */ /* Placed here for compatibility with older C compilers. */ fcomplex*** ccube(); fcomplex** cmatrix(); fcomplex* cvector(); void free_ccube(); void free_cmatrix(); void free_cvector(); #endif /*************** * SUBROUTINES * ***************/ /*****************************************************************************/ /* ccube() - Allocates a complex cube with range [a..b][c..d][e..f]. */ /* Like cmatrix() but for three dimensional arrays. */ /*****************************************************************************/ fcomplex ***ccube(a,b,c,d,e,f) int a,b,c,d,e,f; { int i,j; fcomplex ***m; m=(fcomplex ***) calloc((unsigned) (b-a+1), sizeof(fcomplex **)); if (!m) naaerror("allocation failure 1 in ccube()"); m -= a; for (i=a;i<=b;i++) { m[i]=(fcomplex **) calloc((unsigned) (d-c+1), sizeof(fcomplex *)); if (!m[i]) naaerror("allocation failure 2 in ccube()"); m[i] -= c; } for (i=a;i<=b;i++) for (j=c;j<=d;j++) { m[i][j]=(fcomplex *) calloc((unsigned) (f-e+1), sizeof(fcomplex)); if (!m[i][j]) naaerror("allocation failure 3 in ccube()"); m[i][j] -= e; } return (m); /* return pointer to array of pointers to rows. */ } /*****************************************************************************/ /* cmatrix() - Allocates a complex matrix with range [a..b][c..d]. */ /*****************************************************************************/ fcomplex **cmatrix(a,b,c,d) int a,b,c,d; { int i; fcomplex **m; /* allocate pointers to rows. */ m=(fcomplex **) calloc((unsigned) (b-a+1), sizeof(fcomplex*)); if (!m) naaerror("allocation failure 1 in cmatrix()"); m -= a; /* allocate rows and set pointers to them. */ for (i=a;i<=b;i++) { m[i]=(fcomplex *) calloc((unsigned) (d-c+1), sizeof(fcomplex)); if (!m[i]) naaerror("allocation failure 2 in cmatrix()"); m[i] -= c; } return (m); /* return pointer to array of pointers to rows. */ } /*****************************************************************************/ /* cvector() - Allocates a complex vector with range [a..b]. */ /*****************************************************************************/ fcomplex *cvector(a,b) int a,b; { fcomplex *v; v = (fcomplex *) malloc((unsigned) (b-a+1) * sizeof(fcomplex)); if (!v) naaerror("allocation failure in cvector()"); return (v-a); } /*****************************************************************************/ /* free_ccube() - Frees a complex cube allocated with ccube(). */ /*****************************************************************************/ void free_ccube(m,a,b,c,d,e,f) fcomplex ***m; int a,b,c,d,e,f; /* (variable f is never used.) */ { int i, j; for(i=b;i>=a;i--) for(j=d;j>=c;j--) free((char *) (m[i][j]+e)); for(i=b;i>=a;i--) free((char *) (m[i]+c)); free((char *) (m+a)); } /*****************************************************************************/ /* free_cmatrix() - Frees a complex matrix allocated with cmatrix(). */ /*****************************************************************************/ void free_cmatrix(m,a,b,c,d) fcomplex **m; int a,b,c,d; /* (variable d is never used.) */ { int i; for(i=b;i>=a;i--) free((char *) (m[i]+c)); free((char *) (m+a)); } /*****************************************************************************/ /* free_cvector() - Frees a complex vector allocated by cvector(). */ /*****************************************************************************/ void free_cvector(v,a,b) fcomplex *v; int a,b; /* (variable b is never used.) */ { free((char *) (v+a)); } /****************************************************************************** * Written by: Harold A. Toomey, CARE-FREE SOFTWARE, 3Q 1991, v4.2 * * Copyright (C) 1988-1991, Harold A. Toomey, All Rights Reserved. * ******************************************************************************/
C
// usart_tx_task.h // Jeremiah Griffin <[email protected]> // Lab Section: 23 // // I acknowledge all content contained herein, excluding template or example // code, is my own original work. #ifndef CUSTOM_COMMON_USART_TX_TASK_H #define CUSTOM_COMMON_USART_TX_TASK_H #include "task.h" #include "usart.h" #include <stddef.h> #include <stdint.h> /// \brief Maximum number of bytes in the TX queue #define USART_TX_QUEUE_SIZE 1024 /// \brief Task for the USART transmitter driver extern task_t usart_tx_task; /// \brief Queue of bytes to transmit via USART extern uint8_t usart_tx_queue[USART_TX_QUEUE_SIZE]; /// \brief Number of bytes in the TX queue extern size_t usart_tx_queue_size; /// \brief Index of the head byte in the TX queue extern size_t usart_tx_queue_head; /// \brief Index of the tail byte in the TX queue extern size_t usart_tx_queue_tail; /// \brief Determines whether the TX queue is empty /// \return \c true if the TX queue is empty; \c false otherwise bool is_usart_tx_queue_empty(); /// \brief Determines whether the TX queue is full /// \return \c true if the TX queue is full; \c false otherwise bool is_usart_tx_queue_full(); /// \brief Pushes a byte into the USART transmitter queue /// \param data byte to transmit last /// \return \c true if the queue was not full and the push succeeded; \c false /// otherwise bool push_usart_tx_queue(uint8_t data); /// \brief Pushes an array of bytes into the USART transmitter queue /// \param data array of bytes to transmit last /// \param size number of bytes to push /// \return \c true if the queue was not full and the push succeeded; \c false /// otherwise /// /// If the number of bytes exceeds the available space in the queue, the push /// is not attempted. bool push_usart_tx_queue_array(const uint8_t *data, size_t size); /// \brief Pushes an array of bytes into the USART transmitter queue as a /// packet /// \param data array of bytes to transmit last as a packet /// \param size number of bytes in the packet data /// \return \c true if the queue was not full and the push succeeded; \c false /// otherwise /// \see pack_usart_packet /// /// If the number of bytes in the packet exceeds the available space in the /// queue, the push is not attempted. bool push_usart_tx_queue_packet(const uint8_t *data, size_t size); #endif // CUSTOM_COMMON_USART_TX_TASK_H
C
////////////////////////////////////////////////////////////////////////////// // // // Parentização de produto de Matrizes // // // // Sabemos que a multiplicação de matrizes é associativa, isto é // // ( A * B ) * C = A * ( B * C ) // // // // Porém, o custo, em multiplicações escalares, de cada uma das maneiras // // de realizar o produto varia de acordo com as dimensões das matrizes. // // // // Queremos uma sequência de produtos ótima que minimiza o custo de fazer // // essas multiplicações // // // // Recebe um número n de matrizes e uma lista de n + 1 dimensões dim, // // onde a matriz i tem dimensões dim[i] x dim[i + 1]. // // // // Devolve na saida padrão uma string com as matrizes e parenteses, // // indicando a ordem das operações. // // // // Algoritmo de programação dinâmica que consome O(n^3) unidades de tempo. // // E O(n^2) em espaço. // // Poderia melhorar as constantes, mas preferi a simplicidade do código // // // ////////////////////////////////////////////////////////////////////////////// #include <stdio.h> #include <stdlib.h> #define INF __INT_MAX__ int DEBUG = 0; // Função auxiliar pra printar a tabela (usada pra debugar) void printaTabela( int** m, int** track, int n) { for( int i = 0; i < n; i++) { for( int j = 0; j < n; j++) printf( "%d|%d\t", m[i][j], track[i][j]); printf( "\n"); } } // Função que percorre a tabela ao contrário para reconstruir o produto final void recuperaTrack( int** track, int n) { // Esse código exige um entendimento de como a tabela track // foi construida. Os índices aqui são meio mágicos. // Íncides da string construida int ini = 0, fim = 6 * n - 6; // Índices das matrizes das pontas da string int mIni = 0, mFim = n - 1; // Matriz que ficou de fora do resto do produto int prox = track[mIni][mFim]; // String de retorno char* s = malloc( (6 * n - 4) * sizeof( char)); // Enquanto não coloca todas as matrizes while (mFim > mIni) { // Coloca os parenteses em volta desse produto s[ini++] = '('; s[fim--] = ')'; s[ini++] = ' '; s[fim--] = ' '; // Coloca a matriz que ficou de fora do produto if (prox == mIni) { s[ini++] = 'A' + mIni; s[ini++] = ' '; mIni++; } else { s[fim--] = 'A' + mFim; s[fim--] = ' '; mFim--; } // Define a próxima matriz prox = track[mIni][mFim]; s[fim - 2]; } // Coloca a última matriz s[fim] = 'A' + mFim; // Imprime e libera printf( "%s\n", s); free( s); } // Recebe a o vetor das n + 1 dimensões das matrizes e printa // a melhor sequência de multiplicação delas. int melhorSequencia( int* dim, int n) { // A matriz m[i][j] guarda o custo da melhor multiplicação Ai...Aj // (Matriz de recorrência da PD) int** m = malloc( n * sizeof( int*)); // Inicializa a matriz e preenche a diagonal // m[i][i] = 0 (não multiplicamos uma só matriz) for (int i = 0; i < n; i++) { m[i] = malloc( n * sizeof( int)); m[i][i] = 0; } // Inicializa matriz de rastreio int** track = malloc( n * sizeof( int*)); for (int i = 0; i < n; i++) { track[i] = malloc( n * sizeof( int)); } // Começando a preencher a tabela: int i; // linha int j; // coluna int l; // diagonal int q; // custo dessa parametrização // Preenchendo pelas diagonais, de Noroeste para Sudeste for (int l = 1; l < n; l++) { for (int i = 0; i < n - l; i++) { // Com a linha e adiagonal, encontramos a coluna j = i + l; // Encontra o menor custo de m[i][j] m[i][j] = INF; // k é aonde vai os parênteses mais externos, que divide o produto em 2 // Testamos colocalo entre cada para entre i e j para achar o melhor for( int k = i; k < j; k++) { // Cálculo do custo m[i][j] se o parentes for em k // m_k[i][j] = Custo do primeiro produto m[i][k] + // Custo de multiplicar os dois produtos d[i]*d[k+1]*d[j+1] + // Custo do segundo produto m[k+1][j] q = m[i][k] + dim[i] * dim[k + 1] * dim[j + 1] + m[k + 1][j]; // Se encontrei um custo melhor que o atual, guarda ele e da onde veio if( q < m[i][j]) { track[i][j] = k; m[i][j] = q; } } } } // Agora que encontrei o melhor custo m[0][n - 1], recupera da onde ele veio if (DEBUG) printaTabela( m, track, n); recuperaTrack( track, n); // Retorna o custo return m[0][n - 1]; } int main( int argc, char* argv[]) { int n; int* dim; if (argc > 1) DEBUG = 1; // Le e aloca todos os dados scanf( "%d", &n); dim = malloc( (n + 1) * sizeof( int)); for (int i = 0; i <= n; i++) scanf( "%d", &dim[i]); // Roda o algoritmo int m = melhorSequencia (dim, n); printf ("Número de múltiplicações escalares = %d\n", m); return 0; }
C
/* * stm32f407xx_gpio.c * * Created on: May 21, 2019 * Author: dhilan22 * * GPIO Driver Source File */ #include "stm32f407xx_gpio.h" /************************************************************************ * @fn - GPIO_PeriCLKControl * * @brief - This function enables or disables peripheral clocks for GPIO ports * * @pGPIOx - Base address pointer to GPIO peripheral * @ENorDI - Enable or Disable macros * * @return - none * * @Note - none * */ void GPIO_PeriCLKControl(GPIO_RegDef_t *pGPIOx, uint8_t ENorDI) { if (ENorDI == ENABLE) { if (pGPIOx == GPIOA) { GPIOA_PCLK_EN(); } else if (pGPIOx == GPIOB) { GPIOB_PCLK_EN(); } else if (pGPIOx == GPIOC) { GPIOC_PCLK_EN(); } else if (pGPIOx == GPIOD) { GPIOD_PCLK_EN(); } else if (pGPIOx == GPIOE) { GPIOE_PCLK_EN(); } else if (pGPIOx == GPIOF) { GPIOF_PCLK_EN(); } else if (pGPIOx == GPIOG) { GPIOG_PCLK_EN(); } else if (pGPIOx == GPIOH) { GPIOH_PCLK_EN(); } else if (pGPIOx == GPIOI) { GPIOI_PCLK_EN(); } else if (pGPIOx == GPIOJ) { GPIOJ_PCLK_EN(); } else if (pGPIOx == GPIOK) { GPIOK_PCLK_EN(); } } else { if (pGPIOx == GPIOA) { GPIOA_PCLK_DI(); } else if (pGPIOx == GPIOB) { GPIOB_PCLK_DI(); } else if (pGPIOx == GPIOC) { GPIOC_PCLK_DI(); } else if (pGPIOx == GPIOD) { GPIOD_PCLK_DI(); } else if (pGPIOx == GPIOE) { GPIOE_PCLK_DI(); } else if (pGPIOx == GPIOF) { GPIOF_PCLK_DI(); } else if (pGPIOx == GPIOG) { GPIOG_PCLK_DI(); } else if (pGPIOx == GPIOH) { GPIOH_PCLK_DI(); } else if (pGPIOx == GPIOI) { GPIOI_PCLK_DI(); } else if (pGPIOx == GPIOJ) { GPIOJ_PCLK_DI(); } else if (pGPIOx == GPIOK) { GPIOK_PCLK_DI(); } } } /************************************************************************ * @fn - GPIO_Init * * @brief - This function initializes the appropriate GPIO ports / pins * * @pGPIOHandle - Pointer to handle access to different GPIO registers for configuration * * @return - none * * @Note - It is important to use bitwise OR to set the physical registers in * order to prevent affecting all the bits in the register * */ void GPIO_Init(GPIO_Handle_t *pGPIOHandle) { uint32_t temp = 0; // Enable the GPIO peripheral clock in the driver instead of the user application to avoid the user forgetting GPIO_PeriCLKControl(pGPIOHandle->pGPIOx, ENABLE); // 1. Configure Mode if (pGPIOHandle->GPIO_PinConfig.GPIO_PinMode <= GPIO_MODE_ANALOG) { // Non-interrupt Modes temp = (pGPIOHandle->GPIO_PinConfig.GPIO_PinMode << (2 * pGPIOHandle->GPIO_PinConfig.GPIO_PinNum) ); // The following will clear (reset) the bit field by negating binary 11 (represented by 0x3 in hexadecimal) in the two-bit field pGPIOHandle->pGPIOx->MODER &= ~(0x3 << pGPIOHandle->GPIO_PinConfig.GPIO_PinNum); // The following then sets the register's bit field to the value stored in temp pGPIOHandle->pGPIOx->MODER |= temp; } else { // Interrupt Modes if (pGPIOHandle->GPIO_PinConfig.GPIO_PinMode == GPIO_MODE_IT_FT) { // 1. Configure FTSR (falling trigger selection register) EXTI->FTSR |= ( 1 << pGPIOHandle->GPIO_PinConfig.GPIO_PinNum ); // Clear corresponding RTSR bit EXTI->RTSR &= ~( 1 << pGPIOHandle->GPIO_PinConfig.GPIO_PinNum ); } else if (pGPIOHandle->GPIO_PinConfig.GPIO_PinMode == GPIO_MODE_IT_RT) { // 1. Configure RTSR (rising trigger selection register) EXTI->RTSR |= ( 1 << pGPIOHandle->GPIO_PinConfig.GPIO_PinNum ); // Clear corresponding FTSR bit EXTI->FTSR &= ~( 1 << pGPIOHandle->GPIO_PinConfig.GPIO_PinNum ); } else if (pGPIOHandle->GPIO_PinConfig.GPIO_PinMode == GPIO_MODE_IT_RFT) { // 1. Configure RFTSR (i.e. set both) EXTI->RTSR |= ( 1 << pGPIOHandle->GPIO_PinConfig.GPIO_PinNum ); // Clear corresponding FTSR bit EXTI->FTSR |= ( 1 << pGPIOHandle->GPIO_PinConfig.GPIO_PinNum ); } // 2. Configure GPIO port selection in SYSCFG_EXTICR uint8_t temp1 = pGPIOHandle->GPIO_PinConfig.GPIO_PinNum / 4; // Get EXTICR number in array uint8_t temp2 = pGPIOHandle->GPIO_PinConfig.GPIO_PinNum % 4; // Get bit position for EXTIx uint8_t portCode = GPIO_BASEADDR_TO_CODE(pGPIOHandle->pGPIOx); // Get corresponding port code SYSCFG_PCLK_EN(); // Enable peripheral clock SYSCFG->EXTICR[temp1] = portCode << (temp2 *4); // Set the appropriate bit field of the EXTIx register // 3. Enable EXTI interrupt delivery using IMR EXTI->IMR |= 1 << pGPIOHandle->GPIO_PinConfig.GPIO_PinNum; } temp = 0; // 2. Configure Speed temp = (pGPIOHandle->GPIO_PinConfig.GPIO_PinSpeed << (2 * pGPIOHandle->GPIO_PinConfig.GPIO_PinNum) ); pGPIOHandle->pGPIOx->OSPEEDR &= ~(0x3 << pGPIOHandle->GPIO_PinConfig.GPIO_PinNum); pGPIOHandle->pGPIOx->OSPEEDR |= temp; temp = 0; // 3. Configure Pull-up / Pull-down temp = (pGPIOHandle->GPIO_PinConfig.GPIO_PinPuPdControl << (2 * pGPIOHandle->GPIO_PinConfig.GPIO_PinNum) ); pGPIOHandle->pGPIOx->PUPDR &= ~(0x3 << pGPIOHandle->GPIO_PinConfig.GPIO_PinNum); pGPIOHandle->pGPIOx->PUPDR |= temp; temp = 0; // 4. Configure OPType temp = (pGPIOHandle->GPIO_PinConfig.GPIO_PinOPType << pGPIOHandle->GPIO_PinConfig.GPIO_PinNum ); pGPIOHandle->pGPIOx->OTYPER &= ~(0x1 << pGPIOHandle->GPIO_PinConfig.GPIO_PinNum); pGPIOHandle->pGPIOx->OTYPER |= temp; temp = 0; // 5. Configure Alt. Functionality if (pGPIOHandle->GPIO_PinConfig.GPIO_PinMode <= GPIO_MODE_ALTFUN) { // Configure alt.function registers uint8_t temp1, temp2; temp1 = (pGPIOHandle->GPIO_PinConfig.GPIO_PinNum) / 8; temp2 = (pGPIOHandle->GPIO_PinConfig.GPIO_PinNum) % 8; // Reset 4-bit field by negating binary 1111, represented as 0xF in hexadecimal pGPIOHandle->pGPIOx->AFR[temp1] &= ~(0xF << (4 * temp2) ); pGPIOHandle->pGPIOx->AFR[temp1] |= (pGPIOHandle->GPIO_PinConfig.GPIO_AltFunMode << (4 * temp2) ); } } /************************************************************************ * @fn - GPIO_DeInit * * @brief - This function de-initializes the appropriate GPIO ports / pins * * @pGPIOHandle - * * @return - none * * @Note - none * */ void GPIO_DeInit(GPIO_RegDef_t *pGPIOx) { if (pGPIOx == GPIOA) { GPIOA_REG_RESET(); } else if (pGPIOx == GPIOB) { GPIOB_REG_RESET(); } else if (pGPIOx == GPIOC) { GPIOC_REG_RESET(); } else if (pGPIOx == GPIOD) { GPIOD_REG_RESET(); } else if (pGPIOx == GPIOE) { GPIOE_REG_RESET(); } else if (pGPIOx == GPIOF) { GPIOF_REG_RESET(); } else if (pGPIOx == GPIOG) { GPIOG_REG_RESET(); } else if (pGPIOx == GPIOH) { GPIOH_REG_RESET(); } else if (pGPIOx == GPIOI) { GPIOI_REG_RESET(); } else if (pGPIOx == GPIOJ) { GPIOJ_REG_RESET(); } else if (pGPIOx == GPIOK) { GPIOK_REG_RESET(); } } /************************************************************************ * @fn - GPIO_ReadPin * * @brief - This function reads data from the input pin * * @pGPIOx - Base address pointer to GPIO peripheral * @PinNum - Pin Number * * @return - 0 or 1 * * @Note - To read the value at the nth pin in the input data register (IDR), right shift the * bit position by n to bring it to the 0th position, and then mask all other bits and * return just the value at the 0th position (i.e. only 0th position will have a 1) * */ uint8_t GPIO_ReadPin(GPIO_RegDef_t *pGPIOx, uint8_t PinNum) { uint8_t value; value = (uint8_t)((pGPIOx->IDR >> PinNum) & 0x00000001); return value; } /************************************************************************ * @fn - GPIO_ReadPort * * @brief - This function reads data from the input port * * @pGPIOx - Base address pointer to GPIO peripheral * * @return - Value * * @Note - none * */ uint16_t GPIO_ReadPort(GPIO_RegDef_t *pGPIOx) { uint16_t value; value = (uint16_t)(pGPIOx->IDR); return value; } /************************************************************************ * @fn - GPIO_WritePin * * @brief - This function writes data to the ODR for the appropriate output pin * * @pGPIOx - Base address pointer to GPIO peripheral * @PinNum - Pin Number * @Value - Value to be written to pin (0 or 1) * * @return - none * * @Note - none * */ void GPIO_WritePin(GPIO_RegDef_t *pGPIOx, uint8_t PinNum, uint8_t Value) { if (Value == GPIO_PIN_SET) { pGPIOx->ODR |= (1 << PinNum); } // Write 1 else { pGPIOx->ODR &= ~(1 << PinNum); } // Write 0 } /************************************************************************ * @fn - GPIO_WritePort * * @brief - This function writes data to the ODR for the appropriate port * * @pGPIOx - Base address pointer to GPIO peripheral * @Value - Value to be written to port * * @return - none * * @Note - none * */ void GPIO_WritePort(GPIO_RegDef_t *pGPIOx, uint16_t Value) { pGPIOx->ODR = Value; } /************************************************************************ * @fn - GPIO_TogglePin * * @brief - This function toggles the required bit field for the corresponding pin * * @pGPIOx - Base address pointer to GPIO peripheral * @PinNum - Pin Number * * @return - none * * @Note - none * */ void GPIO_TogglePin(GPIO_RegDef_t *pGPIOx, uint8_t PinNum) { pGPIOx->ODR ^= (1 << PinNum); // XOR to toggle the bit state } /************************************************************************ * @fn - GPIO_IRQInterruptConfig * * @brief - This function configures the IRQ interrupt by either setting or clearing (ENorDI) it * * @IRQNum - IRQ Number * @ENorDI - Enable or Disable * * @return - none * * @Note - none * */ void GPIO_IRQInterruptConfig(uint8_t IRQNum, uint8_t ENorDI) { if (ENorDI==ENABLE) // If true, set the interrupt with ISE register { if (IRQNum <= 31) { // Program ISER0 register *NVIC_ISER0 |= (1 << IRQNum); // Set the appropriate bit field of the register corresponding to the IRQ number to 1 } else if (IRQNum > 31 && IRQNum < 64) { // Program ISER1 register *NVIC_ISER1 |= (1 << (IRQNum % 32)); } else if (IRQNum >= 64 && IRQNum < 95) { // Program ISER2 register (this is sufficient because the number of IRQ numbers implemented in this MCU is <90) *NVIC_ISER2 |= (1 << (IRQNum % 64)); } } else // // Else, clear the interrupt with ICE register { if (IRQNum <= 31) { // Program ICER0 register *NVIC_ICER0 |= (1 << IRQNum); } else if (IRQNum > 31 && IRQNum < 64) { // Program ICER1 register *NVIC_ICER1 |= (1 << (IRQNum % 32)); } else if (IRQNum >= 64 && IRQNum < 95) { // Program ICER2 register *NVIC_ICER2 |= (1 << (IRQNum % 64)); } } } /************************************************************************ * @fn - GPIO_IRQPriorityConfig * * @brief - This function configures the IRQ priority * * @IRQNum - IRQ Number * @IRQPriority - IRQ Priority * * @return - none * * @Note - none * */ void GPIO_IRQPriorityConfig(uint8_t IRQNum, uint32_t IRQPriority) { // 1. Find out the IPR Register uint8_t IPRx = IRQNum / 4; uint8_t IPRx_section = IRQNum % 4; uint8_t shift_amount = (8*IPRx_section) + (8-NO_PR_BITS_IMP); // In this MCU device, lower 4 bits of each section are not implemented so you must shift the bits by 4 *(NVIC_PR_BASE + IPRx) |= ( IRQPriority << shift_amount ); // LS jumps to appropriate register address, RS sets the correct section to the IRQ Priority } /************************************************************************ * @fn - GPIO_IRQHandling * * @brief - This function * * @PinNum - Pin Number * * @return - none * * @Note - none * */ void GPIO_IRQHandling(uint8_t PinNum) { // Clear the EXTI PR corresponding to the Pin Number if (EXTI->PR & (1 << PinNum)) { // Clear pending register bit EXTI->PR |= (1 << PinNum); } }
C
#include <stdio.h> float sum(float,float); int main(){ float varA, varB, res; puts("Ingrese los valores"); scanf("%f%f", &varA, &varB); res = sum(varA, varB); printf("Resultado : %f \n", res); return 0; } float sum(float a, float b){ float res; res = a+b; return res; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <assert.h> #include <math.h> #include <NestAPI.h> #define FIG_SEPAR ":" #define PRIM_SEPAR "" #define STATE_NEWFIG 0 #define STATE_PRIM 1 void trim(char *str) { int i; for (i = 0; i < strlen(str); i++) { if (iscntrl(str[i])) { str[i] = '\0'; } } } void ppos2file(char *path, struct Position *posits, int npos) { int i, j, k; FILE *file; if (!(file = fopen(path, "w+"))) { printf("error while creating file\n"); exit(1); } for (i = 0; i < npos; i++) { fprintf(file, "%lf\n", posits[i].fig.gcenter.x + posits[i].x); fprintf(file, "%lf\n", posits[i].fig.gcenter.y + posits[i].y); fprintf(file, "%lf\n", posits[i].fig.gcenter.x + posits[i].x); fprintf(file, "%lf\n", posits[i].fig.gcenter.y + posits[i].y); for (j = 0; j < posits[i].fig.nprims; j++) { for (k = 0; k < posits[i].fig.prims[j].npts - 1; k++) { fprintf(file, "%lf\n", posits[i].fig.prims[j].pts[k].x + posits[i].x); fprintf(file, "%lf\n", posits[i].fig.prims[j].pts[k].y + posits[i].y); fprintf(file, "%lf\n", posits[i].fig.prims[j].pts[k + 1].x + posits[i].x); fprintf(file, "%lf\n", posits[i].fig.prims[j].pts[k + 1].y + posits[i].y); } } } fclose(file); } void pfig(struct Figure fig) { int i, j; printf("quant=%d\n", fig.quant); printf("nprims=%d\n", fig.nprims); for (i = 0; i < fig.nprims; i++) { printf("npts=%d\n", fig.prims[i].npts); for (j = 0; j < fig.prims[i].npts; j++) { struct Point pt; pt = fig.prims[i].pts[j]; printf("%lf %lf\n", pt.x, pt.y); } printf("\n"); } } void pfig2file(struct Figure *figs, int nfigs) { int i, j, k; FILE *file; if (!(file = fopen("./drawout", "w+"))) { printf("error while creating file\n"); exit(1); } for (i = 0; i < nfigs; i++) { for (j = 0; j < figs[i].nprims; j++) { for (k = 0; k < figs[i].prims[j].npts - 1; k++) { fprintf(file, "%lf\n", figs[i].prims[j].pts[k].x); fprintf(file, "%lf\n", figs[i].prims[j].pts[k].y); fprintf(file, "%lf\n", figs[i].prims[j].pts[k + 1].x); fprintf(file, "%lf\n", figs[i].prims[j].pts[k + 1].y); } } } fclose(file); } static int figcmp(const void *a, const void *b) { double sqr1, sqr2; struct Figure *fig1, *fig2; fig1 = (struct Figure*)a; fig2 = (struct Figure*)b; sqr1 = fig1->corner.x * fig1->corner.y; sqr2 = fig2->corner.x * fig2->corner.y; if (sqr1 > sqr2) return 1; else if (sqr1 < sqr2) return -1; else return 0; } static int gencmp(const void *a, const void *b) { struct Individ *indiv1, *indiv2; indiv1 = (struct Individ*)a; indiv2 = (struct Individ*)b; if (indiv1->gensize < indiv2->gensize) return 1; else if (indiv1->gensize > indiv2->gensize) return -1; else if (indiv1->gensize == indiv2->gensize && indiv1->height > indiv2->height) return 1; else if (indiv1->gensize == indiv2->gensize && indiv1->height < indiv2->height) return -1; else return 0; } int main(int argc, char **argv) { int maxprims, maxfigs, maxpts, state, maxindivs, namelen; int nfigs, nprims, npts, setsize, iters; int ext; struct Individ *indivs, tmp; struct Figure *figs, *figset; char *str; ssize_t chread; size_t n; int i, j, k, m, nindivs; struct NestAttrs attrs; str = NULL; n = 0; maxfigs = 128; namelen = 2048; state = STATE_NEWFIG; nfigs = nprims = npts = 0; figs = (struct Figure*)xmalloc(sizeof(struct Figure) * maxfigs); while ((chread = getline(&str, &n, stdin)) != -1) { double x, y; trim(str); if (state == STATE_NEWFIG) { figs[nfigs].name = (char*)xmalloc(sizeof(char) * namelen); sscanf(str, "%s %d %d\n", figs[nfigs].name, &figs[nfigs].quant, &figs[nfigs].angstep); state = STATE_PRIM; maxpts = 2048; maxprims = 128; figs[nfigs].prims = (struct Primitive*)xmalloc(sizeof(struct Primitive) * maxprims); figs[nfigs].prims[nprims].pts = (struct Point*)xmalloc(sizeof(struct Point) * maxpts); // free(str); str = NULL; continue; } if (strcmp(str, FIG_SEPAR) == 0) { state = STATE_NEWFIG; figs[nfigs].prims[nprims].npts = npts; nprims++; figs[nfigs].id = nfigs; figs[nfigs].nprims = nprims; nfigs++; if (nfigs == maxfigs) { maxfigs *= 2; figs = (struct Figure*)xrealloc(figs, sizeof(struct Figure) * maxfigs); } nprims = 0; npts = 0; // free(str); str = NULL; continue; } if (strcmp(str, PRIM_SEPAR) == 0) { figs[nfigs].prims[nprims].npts = npts; nprims++; if (nprims == maxprims) { maxprims *= 2; figs[nfigs].prims = (struct Primitive*)xrealloc(figs[nfigs].prims, sizeof(struct Primitive) * maxprims); } maxpts = 2048; figs[nfigs].prims[nprims].pts = (struct Point*)xmalloc(sizeof(struct Point) * maxpts); npts = 0; // free(str); str = NULL; continue; } sscanf(str, "%lf %lf\n", &x, &y); figs[nfigs].prims[nprims].pts[npts].x = x; figs[nfigs].prims[nprims].pts[npts].y = y; npts++; if (npts == maxpts) { maxprims *= 2; figs[nfigs].prims[nprims].pts = (struct Point*)xrealloc(figs[nfigs].prims[nprims].pts, sizeof(struct Point) * maxpts); } // free(str); str = NULL; } for (i = 0; i < nfigs; i++) { figinit(&figs[i]); } attrs.width = atof(argv[1]); attrs.height = atof(argv[2]); attrs.type = ROTNEST_DEFAULT; attrs.logfile = fopen("./logfile", "w+"); figset = makeset(figs, nfigs, &setsize); qsort(figset, setsize, sizeof(struct Figure), figcmp); maxindivs = 1024; indivs = (struct Individ*)xmalloc(sizeof(struct Individ) * maxindivs); indivs[0].genom = (int*)xmalloc(sizeof(int) * setsize); indivs[0].gensize = 0; rotnest(figset, setsize, &indivs[0], &attrs); nindivs = 1; ext = 0; iters = atoi(argv[3]); for (i = 0; i < iters && !ext; i++) { int nnew = 0, equal = 0, oldn; printf("nindivs=%d\n", nindivs); for (j = 0; j < 1; j++) { printf("ind=%d height=%lf gensize=%d genom: ", i, indivs[j].height, indivs[j].gensize); for (k = 0; k < indivs[j].gensize; k++) { printf("%d ", indivs[j].genom[k]); } printf("\n"); } printf("\n"); oldn = nindivs; for (j = 0; j < oldn - 1 && nnew < 30; j++) { struct Individ heirs[2]; if (indivs[j].gensize == indivs[j + 1].gensize) { int res; res = crossover(&indivs[j], &indivs[j + 1], &heirs[0], setsize); crossover(&indivs[j + 1], &indivs[j], &heirs[1], setsize); if (res < 0) { break; } } else { break; } for (k = 0; k < 2; k++) { for (m = 0; m < nindivs; m++) { equal = gensequal(&heirs[k], &indivs[m]) || gensequal2(&heirs[k], &indivs[m], figset); if (equal) { break; } } if (!equal) { nnew++; rotnest(figset, setsize, &heirs[k], &attrs); indivs[nindivs] = heirs[k]; nindivs++; if (nindivs == maxindivs) { maxindivs *= 2; indivs = (struct Individ*)xrealloc(indivs, sizeof(struct Individ) * maxindivs); } } else { destrindiv(&heirs[k]); } } } equal = 0; while (nnew == 0) { int res; res = mutate(&indivs[0], &tmp, setsize); if (res < 0) { ext = 1; break; } equal = 0; for (j = 0; j < nindivs; j++) { equal = gensequal(&tmp, &indivs[j]) || gensequal2(&tmp, &indivs[j], figset); if (equal) { break; } } if (!equal) { nnew++; rotnest(figset, setsize, &tmp, &attrs); indivs[nindivs] = tmp; nindivs++; if (nindivs == maxindivs) { maxindivs *= 2; indivs = (struct Individ*)xrealloc(indivs, sizeof(struct Individ) * maxindivs); } } else { destrindiv(&tmp); } } qsort(indivs, nindivs, sizeof(struct Individ), gencmp); } for (i = 0; i < indivs[0].npos; i++) { double a, b, c, d, e, f; a = indivs[0].posits[i].fig.mtx[0][0]; b = indivs[0].posits[i].fig.mtx[1][0]; c = indivs[0].posits[i].fig.mtx[0][1]; d = indivs[0].posits[i].fig.mtx[1][1]; e = indivs[0].posits[i].fig.mtx[0][2]; f = indivs[0].posits[i].fig.mtx[1][2]; printf("%s\n", indivs[0].posits[i].fig.name); printf("matrix(%lf, %lf, %lf, %lf, %lf, %lf)\n:\n", a, b, c, d, e, f); } // ppos2file("./drawposits", indivs[0].posits, indivs[0].npos); return 0; }
C
#include <stdio.h> int main(){ int valores[6]; // pos 0 ate a 5 int i; for(i = 0; i < 6 ; i++){ // 0 ... 5 printf("Digite um valor para a pos %d: ", i); scanf("%d", &valores[i]); } for(i = 5; i >= 0; i--){ // 5 ... 0 printf("[%d] = %d\n", i, valores[i]); } return 0; }
C
/* Ejercicio 1 Una nueva actualización de Tinder permite encontrar el Match perfecto. Para aquellos que se inscriban a este nuevo feature, sus perfiles serán categorizados (automáticamente) para luego encontrar un Match perfecto con otra persona que tenga igual categoría. Hasta ahora se cuenta con un hash que tiene como clave el ID del usuario (cadena), y como valor asociado un código (también cadena) que responde a la categorización del perfil. Implementar una función en C que reciba dicho diccionario y que devuelva true si fue posible encontrarle pareja a todos los que participaron en esta actualización, false si por lo menos alguno quedó solo. Indicar y justificar el orden de la función. Aclaración: los Match perfectos son para parejas. Aún no se permite armar tríos o poliamor. */ static bool *agrupar_especialidades(hash_t *cuentas_y_categorias, hash_t *categorias) { hash_iter_t *cuentas_y_categorias_iter = hash_iter_crear(cuentas_y_categorias); if (cuentas_y_categorias_iter == NULL) { return false; } while (!hash_iter_al_final(cuentas_y_categorias_iter)) { char *id_actual = hash_iter_ver_actual(cuentas_y_categorias_iter); // O(1) char *categoria_actual = hash_obtener(cuentas_y_categorias, id_actual); // O(1) bool pertenece = hash_obtener(categorias, categoria_actual) != NULL; // O(1) if(!hash_guardar(categorias, categoria_actual, pertenece ? *(size_t *)hash_obtener(categorias, categoria_actual)+1 : 1)) { hash_iter_destruir(cuentas_y_categorias_iter); // O(1) return false; } // O(1) hash_iter_avanzar(cuentas_y_categorias_iter); // O(1) } // O(n) hash_iter_destruir(cuentas_y_categorias_iter); // O(1) return true; } static bool verificar_parejas(hash_t *categorias) { hash_iter_t *verificador_parejas = hash_iter_crear(categorias); bool parejas = true; while (!hash_iter_al_final(verificador_parejas)) { char *categoria_actual = hash_iter_ver_actual(verificador_parejas); // O(1) parejas &= *(size_t *)hash_obtener(categorias, categoria_actual) % 2 == 0; // O(1) if (!parejas) { break; } hash_iter_avanzar(verificador_parejas); // O(1) } // O(k) hash_iter_destruir(verificador_parejas); return parejas; } bool todos_felices(hash_t *cuentas_y_categorias) { hash_t *categorias = hash_crear(NULL); if (categorias == NULL) { return false; } if (!agrupar_especialidades(cuentas_y_categorias, categorias)) { hash_destruir(categorias); return false; } // O(n) if (!verificar_parejas(categorias)) { hash_destruir(categorias); return false; } // O(k) hash_destruir(categorias); return true; } /* Complejidad ejercicio 1 La función principal bool todos_felices(hash_t *cuentas_y_categorias) llama a la función agrupar_especialidades que cuesta O(n) siendo n la cantidad de usuarios en el diccionario original (porque crea un iterador para iterar al mismo y va incrementando un contador que significa la cantidad de usuarios pertenecientes a una categoría, en el diccionario de categorías creado por mi); Luego llama a la función verificar_parejas que cuesta O(k) siendo k la cantidad de categorías, además k es menor o igual a n (cantidad de usuarios, peor de los casos todos categorías distintas). Como conclusión, la complejidad total es: O(n) + O(k) = O(n+k) (O(2n) = O(n) si k = n). */ /*****************************************************************************/ /* Ejercicio 2 Implementar en C una primitiva para el ABB que nos permita obtener la segunda máxima clave del ABB, con firma const char* abb_segundo_maximo(const abb_t*). En caso de tener menos de dos elementos, devolver NULL. La primitiva debe ejecutar en O(log n). Justificar el orden del algoritmo propuesto. O O / \ O O */ static abb_nodo_t *buscar_maximo(abb_nodo_t *actual) { if (actual->der == NULL) { return actual; } return buscar_maximo(actual->der); // O(log n) } static char *_abb_segundo_maximo(abb_nodo_t *actual) { if (actual->der == NULL && actual->izq != NULL) { return buscar_maximo(actual->izq)->clave; // O(log n) } // O(log n) if (actual->der != NULL && actual->der->izq == NULL && actual->der->der == NULL) { return actual->clave; } return _abb_segundo_maximo(actual->der); // O(log n) } const char* abb_segundo_maximo(const abb_t*) { if (abb == NULL || abb->cantidad < 2) { return NULL; } return _abb_segundo_maximo(abb->raiz); // O(log n) } /* Complejidad ejercicio 2 La complejidad de esta función al final es O(log n), porque lo que hace es en el fondo una búsqueda binaria. La función wrapper se basa en dos casos base. El primero, si no tengo hijo derecho, pero si tengo hijo izquierdo, entonces hay 2 casos, o el segundo mayor es mi hizo izquierdo, o es el mayor desde mi hijo izquierdo; el segundo caso base es, si tengo hijo derecho, ya no me preocupo por el subárbol izquierdo, allí no voy a encontrar un segundo máximo, entonces pregunto por los "nietos" del actual, si no tiene, entonces significa que el hijo derecho del actual es el máximo, por lo tanto el actual el segundo máximo. El primer caso, hace una llamada a una función wrapper que busca el mayor, esta búsqueda también es O(log n) porque por el Teorema Maestro, A = 1 (una llamada recursiva), B = 2 (busco en un subárbol), C =(aprox.) 0 (por despeje de O(1)), entonces O(log n). En el peor de los casos es O(log n) + O(log n) = O(2log n) = O(log n) siendo n la cantidad de nodos del árbol. */ /*****************************************************************************/ /* Ejercicio 3 Realizar un seguimiento de aplicar RadixSort para ordenar el siguiente arreglo de fechas en formato DDMM, donde deben quedar primero ordenado por mes, y dentro del mismo mes, por día: 1806 - 2711 - 0707 - 1110 - 3004 - 3103 - 0107 - 1004 - 3003 - 1911 */ // Se ordena el arreglo teniendo en cuenta el primer valor menos // significativo que en este caso son los primeros dos dígitos (día) // 0107 - 0707 - 1004 - 1110 - 1806 - 1911 - 2711 - 3003 - 3004 - 3103 // Se ordena el arreglo teniendo en cuenta el valor más significativo, que // corresponde al tercer y cuarto dígito (mes): // 3003 - 3103 - 1004 - 3004 - 0107 - 0707 - 1110 - 1811 - 1911 - 2711 // Y asi queda ordenado primero por mes y despues por dia.
C
#include <stdio.h> #include <stdlib.h> #include <libconfig.h> #include "config.h" config_t *config; /*------------------------------------------------------------------- * Function : initConfig * Inputs : * Outputs : config_t config * * This uses the libconfig library to parse a user-modifiable config file. * The config structure can be accessed to obtain specific config settings. -------------------------------------------------------------------*/ void initConfig() { config_t *configInstance = malloc(sizeof(config_t)); config_init(configInstance); if (config_read_file(configInstance, "config.txt") == CONFIG_FALSE) { printf("Could not read config file! Please assure that config.txt is in the root directory and is formatted correctly.\n"); printf("Press ENTER to exit."); getchar(); exit(1); } config = configInstance; } const char *getConfigStr(char *str) { const char *temp; config_lookup_string(config, str, &temp); return temp; } int getConfigInt(char* str) { int temp; config_lookup_int(config, str, &temp); return temp; }
C
/** * @file ghost.c * @author Lukas Nejezchleb ([email protected]) * @brief Module where all the logic and movement of ghost is placed * @version 0.1 * @date 2021-05-04 * * @copyright Copyright (c) 2021 * */ #include "ghost.h" #include "data_structures.h" #include "draw_shapes.h" #include "map_from_template.h" #include "config.h" #include <stdbool.h> #include <stdlib.h> #include <stdio.h> bool ghost_move(ghost_type *ghost, map_data *map, pacman_type *pacman) { if ((pacman->location.x == ghost->location.x) && (pacman->location.y == ghost->location.y)) { if (ghost->scared) { ghost->location = map->ghost_spawn; ghost->scared = false; pacman->score += GHOST_SCORE_INCECREASE; } else { return true; } } if (ghost->scared == false) { if ((rand() % GHOST_SWITCH_TO_RANDOM == 0) && (ghost->moving_randomly == false)) { ghost->moving_randomly = true; } else if ((rand() % GHOST_SWITCH_TO_TARGET == 0) && (ghost->moving_randomly == true)) { ghost->moving_randomly = false; } } moves_costs_t possible_moves[4]; int possibilities = create_moves(possible_moves, ghost, map, pacman); change_direction(ghost, possibilities, possible_moves); ghost->location.x = ghost->location.x + ghost->direction.x; ghost->location.y = ghost->location.y + ghost->direction.y; if ((pacman->location.x == ghost->location.x) && (pacman->location.y == ghost->location.y)) { if (ghost->scared) { ghost->location = map->ghost_spawn; ghost->scared = false; pacman->score += GHOST_SCORE_INCECREASE; } else { return true; } } return false; } bool ghost_can_move(ghost_type *ghost, int dirx, int diry, map_data *map) { int pixel = map->board_arr[map->width * (ghost->location.y + diry) + ghost->location.x + dirx]; return (pixel != BLOCKED); } int create_moves(moves_costs_t *moves_arr, ghost_type *ghost, map_data *map, pacman_type *pacman) { // both 4 on next lines is ammount of directions and should not be changed coords dirs[4] = {{.x = 0, .y = -1}, {.x = 0, .y = 1}, {.x = 1, .y = 0}, {.x = -1, .y = 0}}; int ret = 0; for (int i = 0; i < 4; ++i) { if (ghost_can_move(ghost, dirs[i].x, dirs[i].y, map)) { if ((dirs[i].x != -ghost->direction.x) || (dirs[i].y != -ghost->direction.y)) { // add the direction moves_arr[ret].dir = dirs[i]; int cost = (pacman->location.x - ghost->location.x - dirs[i].x) * (pacman->location.x - ghost->location.x - dirs[i].x) + (pacman->location.y - ghost->location.y - dirs[i].y) * (pacman->location.y - ghost->location.y - dirs[i].y); moves_arr[ret].cost = cost; ret++; } } } return ret; // return ammount of valid options to move } void draw_ghost(fb_data *fb, ghost_type *ghost, map_data *map) { if (ghost->scared) { draw_ghost_shape(fb, ghost->location.x, ghost->location.y, map->max_object_diameter / 8, 0x1f); } else { draw_ghost_shape(fb, ghost->location.x, ghost->location.y, map->max_object_diameter / 8, ghost->color); } } ghost_type create_ghost(map_data *map, int ghost_nr) { ghost_type ghost; ghost.moving_randomly = true; ghost.scared = false; ghost.location = map->ghost_spawn; coords direction = {0, 0}; ghost.direction = direction; uint16_t color_pallete[] = {GHOST_COLORS}; ghost.color = color_pallete[ghost_nr % (GHOST_COLORS_AMMOUNT)]; return ghost; } void change_direction(ghost_type *ghost, int possibilities, moves_costs_t *moves_options) { if (possibilities == 0) { // host reached dead_end ghost->direction.x = -ghost->direction.x; ghost->direction.x = -ghost->direction.y; } else if (possibilities == 1) { // only one way possible, pick that one ghost->direction = moves_options[0].dir; } else if (ghost->moving_randomly) { ghost->direction = moves_options[rand() % possibilities].dir; } else { // pick direction with smallest cost int lowest_cost = moves_options[0].cost; int lowest_index = 0; for (int i = 1; i < possibilities; ++i) { if (lowest_cost > moves_options[i].cost) { lowest_cost = moves_options[i].cost; lowest_index = i; } } ghost->direction = moves_options[lowest_index].dir; } }
C
/************************************************************************* > File Name: ParentPipeChild.c > Author:yangkun > Mail:[email protected] > Created Time: Tue 12 Dec 2017 09:22:57 AM CST ************************************************************************/ #include<stdio.h> #include<unistd.h> #include<stdlib.h> #include<fcntl.h> #include<sys/stat.h> #include<sys/types.h> #include<wait.h> void test() { int pfd[2]; int suc=pipe(pfd); if(suc!=0) { perror("pipe"); exit(1); } printf("pipe is ok\n"); int ret=fork(); if(ret==0) { close(pfd[0]); while(1) { char bufofchild[1024]={0}; ssize_t sizeifreadstdin=read(0,bufofchild,sizeof(bufofchild)); if(sizeifreadstdin==0) { printf("end of stdin\n"); } else if(sizeifreadstdin<0) { perror("read"); exit(1); } ssize_t sizeofwritepipe=write(pfd[1],bufofchild,sizeof(bufofchild)); if(sizeofwritepipe<=0) { perror("write"); exit(1); } else { printf("writing in pipe is ok\n"); } } } else if(ret>0) { close(pfd[1]); int status; while(1) { printf("parent is ok\n"); char bufofparent[1024]; ssize_t sizeofreadpipe=read(pfd[0],bufofparent,sizeof(bufofparent)); if(sizeofreadpipe==0) { printf("end of pipe\n"); exit(1); } else if(sizeofreadpipe<0) { perror("read"); exit(1); } else { printf("child say:%s",bufofparent); } int waitret=waitpid(-1,&status,WNOHANG); if(waitret>0) { printf("waiting child is done"); exit(0); } if(waitret==-1) { perror("wait"); exit(1); } } } else { perror("fork"); exit(1); } } int main() { test(); return 0; }
C
#include <stdio.h> // Incluyo la libreria // Prototipos de funciones void pares(int*); void impares(int*); // Funcion principal int main(void){ int Pares = 0, Impares = 0; pares(&Pares); impares(&Impares); printf("La suma de los pares es %d\n", Pares); printf("La suma de los impares es %d\n", Impares); } // Desarrollando las funciones void pares(int* Pares){ for(int i = 1; i <= 200; i++){ if (i%2 == 0) { *Pares += i; } } } void impares(int* Impares){ for(int i = 1; i <= 200; i++){ if (i%2!= 0) { *Impares += i; } } }
C
/* ** get_next_line.c for in /home/fritsc_h//progelem ** ** Made by harold fritsch ** Login <[email protected]> ** ** Started on Mon Nov 19 14:19:17 2012 harold fritsch ** Last update Wed May 1 13:42:18 2013 harold fritsch */ #include <stdlib.h> #include <stdio.h> #include "get_next_line.h" char *mkstr(void) { char *str; if ((str = malloc(sizeof(str) * READ_SIZE + 1)) == NULL) return (NULL); return (str); } int next_char(char *buff, int i) { while (buff[i] == '\n' && buff[i + 1]) i++; return (i); } int str_cpy(char *buff, int i, int j, char *str) { while ((buff[i] != '\n') && buff[i]) str[j++] = buff[i++]; str[j] = '\0'; if (buff[i]) i++; return (i); } char *get_next_line(const int fd) { static int len = 0; static char buff[READ_SIZE + 1]; static int i = 0; char *str; int j; j = 0; if (READ_SIZE < 0) return (NULL); if (i >= len) { if ((len = read(fd, buff, READ_SIZE)) == 0) return (NULL); buff[len] = '\0'; i = 0; } if (len < 0) return (0); i = next_char(buff, i); if ((str = mkstr()) == NULL) return (NULL); i = str_cpy(buff, i, j, str); if (buff[i - 1] == '\0') return (NULL); return (str); }
C
#include <stdio.h> int iterativePower(int,int); int main() { int x,n; printf("enter the number and power:\n"); scanf("%d%d",&x,&n); printf("%d",iterativePower(x,n)); return 0; } int iterativePower(int x,int n) { int result=1; while(n>0) { result = result*x; n--; } return result; }
C
#include <stdio.h> int main() { int a; int* ptrtoa; ptrtoa = &a; a = 5; printf("The value of a is %d\n", a); *ptrtoa = 6; printf("The value of a is %d\n", a); printf("The value of ptrtoa is %d\n", ptrtoa); printf("It stores the value %d\n", *ptrtoa); printf("The address of a is %d\n", &a); float c; float d; float e; d = 1.23; e = 3.45; float* ptrtod = &d; float* ptrtoe = &e; printf("\nValue of float d = %f. Address of float d = %d.", d, ptrtod); printf("\nValue of float e = %f. Address of float e = %d.", e, ptrtoe); c = e; e = d; d = c; printf("\n\nNew value float d = %f. Address of float d = %d.", d, ptrtod); printf("\nNew value float e = %f. Address of float e = %d.\n", e, ptrtoe); }
C
// getPeaks.c // Written by Ashesh Mahidadia, December 2017 #include <stdlib.h> #include <stdio.h> #include <assert.h> #include "DLList.h" /* You will submit only this one file. Implement the function "getPeaks" below. Read the exam paper for detailed specification and description of your task. - DO NOT modify code in the file DLList.h . - You can add helper functions in this file. - DO NOT add "main" function in this file. */ DLList getPeaks(DLList L){ DLList peaksL = newDLList(); //assert(peaksL!=NULL); DLListNodeP cur; cur=L->first; while(cur->next->next !=NULL){ DLListNodeP temp; temp=cur->next; if(temp->value > cur->value && temp->value > temp->next->value){ if (peaksL->first==NULL && peaksL->last==NULL){ peaksL->first=peaksL->curr=peaksL->last=temp; } else if(peaksL->first==peaksL->last){ temp->prev=peaksL->last; peaksL->last->next=temp; peaksL->curr=peaksL->last; /*peaksL->first->next=temp; peaksL->last=temp; peaksL->curr=temp; peaksL->curr->prev=peaksL->first; peaksL->nitems++;*/ } else{ temp->prev=peaksL->curr; temp->next=peaksL->curr->next; peaksL->curr->next->prev=temp; peaksL->curr->next=temp; /*DLListNodeP temp3node; temp3node=peaksL->curr; peaksL->curr=temp; temp3node->next=peaksL->curr; peaksL->curr->prev=temp3node; peaksL->last=temp; peaksL->nitems++;*/ } peaksL->curr=temp; peaksL->nitems++; } } cur=cur->next; // your solution here ... return peaksL; }
C
/* * Output compare / PWM * * Pulse the onboard LED. */ #define F_CPU 16000000UL #include <avr/io.h> #include <util/delay.h> void config_timer0(void) { // With timer clock source freq = 16 MHz / 8, // our PWM frequency (which is the timer rollover // frequency) is 2 MHz / 256 = 19.5 KHz // Clock source: clk_i/o / 8 TCCR0B |= _BV(CS01); // Mode 3: Fast PWM, TOP=0xff TCCR0A |= _BV(WGM00) | _BV(WGM01); // Non-inverting mode: clear OC0A on compare match, // set OC0A at BOTTOM. TCCR0A |= _BV(COM0A1); OCR0A = 0; // Initial value } void config_gpio(void) { DDRB |= _BV(PB7); // LED/OC0A: output pin } int main(void) { uint8_t up = 1; config_timer0(); config_gpio(); while (1) { if (OCR0A == 0xff) up = 0; else if (OCR0A == 0) up = 1; if (up) OCR0A++; else OCR0A--; _delay_ms(3); } return 0; }
C
/** * \file dataservice/dataservice_decode_request_transaction_get_first.c * * \brief Decode transaction get first request. * * \copyright 2019 Velo Payments, Inc. All rights reserved. */ #include <arpa/inet.h> #include <agentd/status_codes.h> #include <cbmc/model_assert.h> #include <string.h> #include "dataservice_protocol_internal.h" /** * \brief Decode a transaction get first request. * * \param req The request payload to parse. * \param size The size of this request payload. * \param dreq The request structure into which this request is * decoded. * * \returns a status code indicating success or failure. * - AGENTD_STATUS_SUCCESS on success. * - AGENTD_ERROR_DATASERVICE_REQUEST_PACKET_INVALID_SIZE if the request * packet payload size is incorrect. */ int dataservice_decode_request_transaction_get_first( const void* req, size_t size, dataservice_request_transaction_get_first_t* dreq) { /* parameter sanity check. */ MODEL_ASSERT(NULL != req); MODEL_ASSERT(NULL != dreq); /* make working with the request more convenient. */ const uint8_t* breq = (const uint8_t*)req; /* initialize the request structure. */ return dataservice_request_init(&breq, &size, &dreq->hdr, sizeof(*dreq)); }
C
#include<stdio.h> #include<stdlib.h> typedef struct node{ int data; struct node * next; }NODE; typedef NODE * NODEPTR; NODEPTR newNode(int data) { NODEPTR temp = (NODEPTR)malloc(sizeof(NODE)); temp -> data = data; temp -> next = NULL; return temp; } NODEPTR push(NODEPTR head, int data) { NODEPTR temp = newNode(data); temp -> next = head; head = temp; return head; } void display(NODEPTR head) { if(head == NULL) { printf("List empty!\n"); return; } NODEPTR temp = head; while(temp != NULL) { printf("%d\n", temp -> data); temp = temp -> next; } } int length(NODEPTR head) { int c = 0; NODEPTR temp = head; while(temp != NULL) { c++; temp = temp -> next; } return c; } void intersection(NODEPTR head1, NODEPTR head2) { int x = length(head1); int y = length(head2); int diff, choice = 1; diff = x>y ? x-y : y-x; NODEPTR largest = x>y ? head1 : head2; NODEPTR smallest = x>y ? head2 : head1; while(diff > 0) { largest = largest -> next; diff--; } while(largest != NULL && smallest != NULL) { if(largest == smallest) { printf("Intersection!, value : %d\n", largest -> data); return; } largest = largest -> next; smallest = smallest -> next; } printf("No Intersection!\n"); } int main() { NODEPTR head = NULL; head = push(head, 6); head = push(head, 5); head = push(head, 4); head = push(head, 5); head = push(head, 6); NODEPTR head1 = NULL; head1 = push(head1, 7); head1 = push(head1, 8); head1 -> next -> next = head -> next -> next; intersection(head, head1); display(head1); return 0; }
C
#include<stdio.h> void even(int x) { if(x%2==0) printf("even\n"); else printf("odd\n"); } void main() { int num; printf("enter the nummber: "); scanf("%d",&num); even(num); }