language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <lxl_queue.h> int main(int argc, char *argv[]) { lxl_log_t *log; lxl_pool_t *pool; lxl_queue_t *queue; log = lxl_log_init(LXL_LOG_DEBUG, LXL_LOG_FLUSH); pool = lxl_pool_create(LXL_DEFAULT_POOL_SIZE, log); queue = lxl_queue_create(pool, 20, sizeof(int)); int i; int *elt; for (i = 0; i < 30; ++i) { elt = lxl_queue_in(queue); *elt = i + 50; } for (i = 0; i < 40; ++i) { elt = lxl_queue_out(queue); if (elt != NULL) { fprintf(stderr, "%d\n", *(int *)elt); } else { fprintf(stderr, "nil\n"); } } return 0; }
C
/* * File: avl.h * Author: Sangeet Dahal */ #ifndef AVL_H_ #define AVL_H_ typedef struct tnode* AVLTreeNodePtr; typedef struct tnode { void *data; AVLTreeNodePtr right; AVLTreeNodePtr left; AVLTreeNodePtr parent; int height; } Treenode; typedef struct tree* AVLTreePtr; typedef struct tree { AVLTreeNodePtr root; AVLTreeNodePtr NIL; } Tree; AVLTreeNodePtr avltree_node_allocate(AVLTreePtr tree); AVLTreePtr avltree_allocate(void); int get_height(AVLTreePtr tree, AVLTreeNodePtr node); void inorder_avl_tree_walk(AVLTreePtr tree, AVLTreeNodePtr root, char* (*get_string)(void *)); void preorder_avl_tree_walk(AVLTreePtr tree, AVLTreeNodePtr root, char* (*get_string)(void *)); void postorder_avl_tree_walk(AVLTreePtr tree, AVLTreeNodePtr root, char* (*get_string)(void *)); void bfs_avltree_walk(AVLTreePtr tree, char* (*get_string)(void*)); AVLTreeNodePtr avltree_search(AVLTreePtr tree, AVLTreeNodePtr root, char *data, int (*comp)(void *, void *)); AVLTreeNodePtr avltree_min(AVLTreePtr tree, AVLTreeNodePtr root); AVLTreeNodePtr avltree_max(AVLTreePtr tree, AVLTreeNodePtr root); AVLTreeNodePtr tree_successor(AVLTreePtr tree, AVLTreeNodePtr node); AVLTreeNodePtr tree_predecessor(AVLTreePtr tree, AVLTreeNodePtr node); void avltree_insert(AVLTreePtr tree, AVLTreeNodePtr node, int (*comp)(void *, void *)); void avl_transplant(AVLTreePtr tree, AVLTreeNodePtr current, AVLTreeNodePtr next); void avltree_delete(AVLTreePtr tree, AVLTreeNodePtr node); inline int max(int first, int second); void avlcalculate_height(AVLTreePtr tree, AVLTreeNodePtr node); #endif
C
#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int t; scanf("%d",&t); while(t--){ int n; scanf("%d",&n); int a[n]; int i; for(i=0;i<n;i++){ scanf("%d",&a[i]); } int j, temp; for(i=0;i<n;i++){ if(a[i]%2!=0){ for(j=n-1;j>i;j--){ if(a[j]%2==0){ temp=a[i]; a[i]=a[j]; a[j]=temp; break; } } } } printf("%d ",n); for(i=0;i<n;i++){ printf("%d ",a[i]); } printf("\n"); } return 0; } /* nnλʹżеǰ벿֣еĺ벿֡ עԼ롢ҵ㷨 Ҫ㷨ʱ临ӶΪO(n) Դt ÿݸʽ£ nn ÿݣ͵ 3 4 1 2 3 4 8 12 32 67 13 1 9 4 97 6 1 32 9 43 12 0 4 4 2 3 1 8 12 32 4 13 1 9 67 97 6 0 32 12 43 9 1 */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: flagoutt <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/03/13 16:38:47 by flagoutt #+# #+# */ /* Updated: 2015/03/21 19:51:11 by flagoutt ### ########.fr */ /* */ /* ************************************************************************** */ int tab[4] = {0, 0, 0, 0}; #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/stat.h> #include <fcntl.h> int ft_isalpha(int c); int ft_isdigit(int c); int ft_isalnum(int c); int ft_isascii(int c); int ft_isprint(int c); int ft_toupper(int c); int ft_tolower(int c); int ft_strlen(char *str); char *ft_strcat(char *s1, const char *s2); void ft_puts(const char *str); void *ft_memset(void *b, int c, int n); void *ft_memcpy(void *s1, const void *s2, int n); char *ft_strdup(const char *s1); char *ft_strndup(const char *s1, int n); void ft_bzero(void *s, int n); int ft_cat(int fd); int ft_isspace(int c); int main(void) { printf("\n \033[36m--- ft_isdigit ---\033[0m\n"); printf("Is 9 a digit ? %i\n", ft_isdigit('9')); printf("Is 0 a digit ? %i\n", ft_isdigit('0')); printf("Is / a digit ? %i\n", ft_isdigit('/')); printf("Is : a digit ? %i\n", ft_isdigit(':')); printf("\n \033[36m--- ft_isalpha ---\033[0m\n"); printf("Is A alpha ? %i\n", ft_isalpha('A')); printf("Is Z alpha ? %i\n", ft_isalpha('Z')); printf("Is a alpha ? %i\n", ft_isalpha('a')); printf("Is z alpha ? %i\n", ft_isalpha('z')); printf("Is { alpha ? %i\n", ft_isalpha('{')); printf("Is ' alpha ? %i\n", ft_isalpha('\'')); printf("Is [ alpha ? %i\n", ft_isalpha('[')); printf("Is @ alpha ? %i\n", ft_isalpha('@')); printf("\n \033[36m--- ft_isalnum ---\033[0m\n"); printf("Is 9 alnum ? %i\n", ft_isalnum('9')); printf("Is 0 alnum ? %i\n", ft_isalnum('0')); printf("Is / alnum ? %i\n", ft_isalnum('/')); printf("Is : alnum ? %i\n", ft_isalnum(':')); printf("Is A alnum ? %i\n", ft_isalnum('A')); printf("Is Z alnum ? %i\n", ft_isalnum('Z')); printf("Is a alnum ? %i\n", ft_isalnum('a')); printf("Is z alnum ? %i\n", ft_isalnum('z')); printf("Is { alnum ? %i\n", ft_isalnum('{')); printf("Is ' alnum ? %i\n", ft_isalnum('\'')); printf("Is [ alnum ? %i\n", ft_isalnum('[')); printf("Is @ alnum ? %i\n", ft_isalnum('@')); printf("\n \033[36m--- ft_isascii ---\033[0m\n"); printf("Is @ ascii ? %i\n", ft_isascii('@')); printf("Is { ascii ? %i\n", ft_isascii('{')); printf("Is ' ascii ? %i\n", ft_isascii('\'')); printf("Is [ ascii ? %i\n", ft_isascii('[')); printf("Is character -1 ascii ? %i\n", ft_isascii(-1)); printf("Is character 128 ascii ? %i\n", ft_isascii(128)); printf("\n \033[36m--- ft_isprint ---\033[0m\n"); printf("Is character 31(us) printable ? %i\n", ft_isprint(31)); printf("Is @ printable ? %i\n", ft_isprint('@')); printf("Is { printable ? %i\n", ft_isprint('{')); printf("Is ' printable ? %i\n", ft_isprint('\'')); printf("Is [ printable ? %i\n", ft_isprint('[')); printf("Is character -1 printable ? %i\n", ft_isprint(-1)); printf("Is character 128 printable ? %i\n", ft_isprint(128)); printf("\n \033[36m--- ft_toupper ---\033[0m\n"); printf("Is a becoming A ? %c\n", ft_toupper('a')); printf("Is z becoming Z ? %c\n", ft_toupper('z')); printf("Is { staying { ? %c\n", ft_toupper('{')); printf("Is ' staying ' ? %c\n", ft_toupper('\'')); printf("\n \033[36m--- ft_tolower ---\033[0m\n"); printf("Is A becoming a ? %c\n", ft_tolower('A')); printf("Is Z becoming z ? %c\n", ft_tolower('Z')); printf("Is @ staying @ ? %c\n", ft_tolower('@')); printf("Is [ staying [ ? %c\n", ft_tolower('[')); printf("\n\033[36m--- ft_bzero ---\033[0m"); int i = tab[0] + 3; char*real; char*test; real = strdup("Hello World!"), test = strdup("Hello World!"); printf("\nIs memcmp returning 0 after a bzero(13) on the string \"%s\"? ", test); bzero(real, 13); ft_bzero(test, 13); (!memcmp(real, test, 13)) ? printf("\033[1;32mYes\033[0m"), tab[0]++ : printf("\033[31mGODDAMMIT NO !\033[0m"); free(real), free(test); real = strdup("Hello World!"), test = strdup("Hello World!"); printf("\nIs memcmp returning 0 after a bzero(3) on the string \"%s\" ? ", test); bzero(real, 3); ft_bzero(test, 3); (!memcmp(real, test, 13)) ? printf("\033[1;32mYes\033[0m"), tab[0]++ : printf("\033[31mGODDAMMIT NO !\033[0m"); free(real), free(test); real = strdup("Hello World!"), test = strdup("Hello World!"); printf("\nIs memcmp returning 0 after a bzero(0) on the string \"%s\" ? ", test); bzero(real, 0); ft_bzero(test, 0); (!memcmp(real, test, 13)) ? printf("\033[1;32mYes\033[0m"), tab[0]++ : printf("\033[31mGODDAMMIT NO !\033[0m"); free(real), free(test); tab[2] = tab[2] + 3; tab[3]++; if (i == tab[0]) tab[1]++; printf("\n\n \033[36m--- ft_strlen ---\033[0m\n"); printf("Is \"Hello World\" 11 chars long ? %i\n", ft_strlen("Hello World")); printf("Is \"Oyo Crazy World!\" 17 chars long ? %i\n", ft_strlen("Oyo Crazy World!")); printf("Is \"HeyBro0123456789\" 16 chars long ? %i\n", ft_strlen("HeyBro0123456789")); printf("\n \033[36m--- ft_strcat ---\033[0m\n"); char *tamer; tamer = malloc(100); strcpy(tamer, "Hello"); ft_strcat(tamer, " World"); printf("Is \" World\" append to \"Hello\" ? %s\n", tamer); printf("\n \033[36m--- ft_puts ---\033[0m"); printf("\nIs (null) printed ? If not, it depends on the computer you are using, there is a problem with an Intel Assembler package that prevents you from storing more than a constant in the .data section of the assembler's ft_puts function. Them , you can either store the '\n' character or the \"(null)\",s string. Thats annoying, but you can test it by yourself."); ft_puts(NULL); printf("\nIs \"Hello Noob\" printed ? "); ft_puts("Hello Noob"); printf("\nIs \"Crappy crappy crappy crappy crappy\" printed ? "); ft_puts("Crappy crappy crappy crappy crappy"); printf("\n\n \033[36m--- ft_memset ---\033[0m\n"); bzero(tamer, 20); strcpy(tamer, "Oyo World!"); ft_memset(tamer, 'c', 9); printf("Is \"Oyo World!\" replaced by several 'c' ? %s", tamer); printf("\n\n \033[36m--- ft_memcpy ---\033[0m\n"); char str[20]; bzero(tamer, 20); strcpy(tamer, "Oyo World!"); ft_memcpy(str, tamer, 5); printf("Has %s been copied until the 5th char? %s", tamer, str); printf("\n\n \033[36m--- ft_strdup ---\033[0m\n"); char *ptr; ptr = ft_strdup(tamer); printf("\n\nADRESS : %p\n", ptr); printf("Has \"%s\" been duplicated ? %s", tamer, ptr); ptr = ft_strdup("\t\t\tOyo\nPloup\n"); printf("\n\nADRESS : %p\n", ptr); printf("Has \"\t\t\tOyo\nPloup\n\" been duplicated ? %s", ptr); printf("\n\n \033[36m--- ft_cat ---\033[0m\n"); int fd; fd = open(__FILE__, O_RDONLY); ft_cat(fd); printf("\n \033[32m###### BONUS TIME #####\033[0m\n"); printf("\n \033[36m--- ft_strndup ---\033[0m\n"); ptr = ft_strndup("Hello World", 5); printf("ADRESS : %p\n", ptr); printf("Has \"Hello World\" been duplicated into \"Hello\" ? %s\n", ptr); ptr = ft_strndup("OyoooPloup", 6); printf("ADRESS : %p\n", ptr); printf("Has \"OyoooPloup\" been duplicated into \"OyoooP\" ? %s\n", ptr); ptr = ft_strndup("OyoooPloup", 10); printf("ADRESS : %p\n", ptr); printf("Has \"OyoooPloup\" been duplicated ? %s\n", ptr); ptr = ft_strndup("Waazzzaaaaaaaaaaaaaaaaaaaa", 100); printf("ADRESS : %p\n", ptr); printf("Has \"Waazzzaaaaaaaaaaaaaaaaaaaa\" been duplicated ? %s\n", ptr); printf("\n \033[36m--- ft_isspace ---\033[0m"); printf("\nIs '\\t' = 9 a kind of space ?"); (ft_isspace('\t') ? printf("\033[1;32mYes\033[0m") : printf("\033[31mGODDAMMIT NO !\033[0m")); printf("\nIs '{' = 9 a kind of space ?"); (ft_isspace('a') ? printf("\033[1;32mYes\033[0m") : printf("\033[31mGODDAMMIT NO !\033[0m")); printf("\nIs '\\n' = 9 a kind of space ?"); (ft_isspace('\n') ? printf("\033[1;32mYes\033[0m") : printf("\033[31mGODDAMMIT NO !\033[0m")); printf("\nIs '\\r' = 9 a kind of space ?"); (ft_isspace('\r') ? printf("\033[1;32mYes\033[0m") : printf("\033[31mGODDAMMIT NO !\033[0m")); printf("\nIs '\\v' = 9 a kind of space ?"); (ft_isspace('\v') ? printf("\033[1;32mYes\033[0m") : printf("\033[31mGODDAMMIT NO !\033[0m")); printf("\nIs 'a' = 9 a kind of space ?"); (ft_isspace('a') ? printf("\033[1;32mYes\033[0m") : printf("\033[31mGODDAMMIT NO !\033[0m")); printf("\nIs ' ' = 9 a kind of space ?"); (ft_isspace(' ') ? printf("\033[1;32mYes\033[0m") : printf("\033[31mGODDAMMIT NO !\033[0m")); printf("\nIs '\\f' = 9 a kind of space ?"); (ft_isspace('\f') ? printf("\033[1;32mYes\033[0m") : printf("\033[31mGODDAMMIT NO !\033[0m")); return (1); }
C
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include "symtable.h" #include "quad.h" #define HASH_MULTIPLIER 65599 #define MAXSIZE 300 struct symtable { /* array of MAXSIZE positions, each one with a -pointer to- list node */ Node_T hashtable[MAXSIZE]; }; /* hash function: return a hash code for pcKey */ static unsigned int SymTable_hash(const char *pcKey){ size_t ui; unsigned int uiHash = 0U; for (ui = 0U; pcKey[ui] != '\0'; ui++) uiHash = uiHash * HASH_MULTIPLIER + pcKey[ui]; return uiHash; } /* SymTable_new: creates a new empty symbol table */ SymTable_T SymTable_new(void){ SymTable_T st; int i; st = malloc(sizeof(struct symtable)); if(st==NULL){ printf("malloc failed\n"); exit(EXIT_FAILURE); } for(i=0; i<MAXSIZE; i++){ st->hashtable[i]=NULL; } for(i=0; i<L_SIZE; i++){ ScopeLink[i] = NULL; } return st; } /* SymTable_getLength: returns the length of the symbol table */ unsigned int SymTable_getLength(SymTable_T oSymTable){ Node_T tmp; int i, count = 0; assert(oSymTable!=NULL); for(i=0; i<MAXSIZE; i++){ tmp = oSymTable->hashtable[i]; /* count nodes */ while(tmp != NULL){ count++; tmp = tmp->next; } } return count; } /* Symtable_insert: adds a new node at hashtable initialized with parameters */ int SymTable_insert(SymTable_T oSymTable, const char *name, Type type, unsigned int line, unsigned int scope){ Node_T tmp; char *copy; int bucket; assert(oSymTable!=NULL); if(name == NULL) return 0; /* katakermatismos -> apothikevo to index tou neou binding ston pinaka */ bucket = SymTable_hash(name)%MAXSIZE; /* Dimiourgia copy tou name */ copy = malloc(strlen(name)*sizeof(char)); strcpy(copy, name); /* Prosthiki tou neou binding */ tmp = malloc(sizeof(struct node)); if(tmp==NULL){ printf("malloc failed\n"); exit(EXIT_FAILURE); } printf("insert node\n"); tmp->name = malloc(strlen(copy)*sizeof(char)); strcpy(tmp->name, copy); tmp->type = type; tmp->line = line; tmp->scope = scope; tmp->isActive = 1; if(type == libfunc){ tmp->stype = libraryfunc_s; } tmp->next = oSymTable->hashtable[bucket]; oSymTable->hashtable[bucket] = tmp; /* insert to scopelink */ if(ScopeLink[scope] == NULL){ ScopeLink[scope] = oSymTable->hashtable[bucket]; /* header */ } else { tmp = ScopeLink[scope]; ScopeLink[scope] = oSymTable->hashtable[bucket]; oSymTable->hashtable[bucket]->scope_next = tmp; } printf("------------------------- name: %s, line: %d, scope: %d\n\n", ScopeLink[scope]->name, ScopeLink[scope]->line, ScopeLink[scope]->scope); return 1; } /* SymTable_lookup: returns the node with this name and scope */ Node_T SymTable_lookup(SymTable_T oSymTable, const char *name){ Node_T tmp; int i; assert(oSymTable!=NULL); if(name == NULL) return NULL; i=SymTable_hash(name)%MAXSIZE; tmp = oSymTable->hashtable[i]; while(tmp != NULL){ if(strcmp(tmp->name, name)==0) return tmp; tmp = tmp->next; } return NULL; } /* Scope_lookup: returns the node of a specific scope */ Node_T Scope_lookup(const char *name, Type type, unsigned int scope){ Node_T tmp = ScopeLink[scope]; /* elenxo gia function anamesa se dilwsi kai xrisi */ if(name == NULL){ printf("ELENXOS gia function anamesa se dilwsi kai xrisi\n"); if(type == userfunc){ while(tmp != NULL){ if( tmp->type == type && tmp->isActive == 1 ){ // isActive ?? printf("VRETHIKE FUNCTION ANAMESA: %s\n", tmp->name); return tmp; } tmp = tmp->scope_next; } }else return NULL; } if(tmp != NULL && type == unknown){ while(tmp != NULL){ if(!strcmp(tmp->name, name)) return tmp; tmp = tmp->scope_next; } } else { while(tmp != NULL){ if(!strcmp(tmp->name, name) && (tmp->type == type)) return tmp; tmp = tmp->scope_next; } } return NULL; } /* Symtable_hide: deactivation of a single scope variables */ void SymTable_hide(SymTable_T oSymTable, unsigned int scope){ Node_T tmp; assert(oSymTable!=NULL); tmp = ScopeLink[scope]; while(tmp != NULL){ tmp->isActive = 0; tmp = tmp->scope_next; } } /* prints the entire symbol table */ void SymTable_print(SymTable_T oSymTable) { Node_T tmp; int i; assert(oSymTable!=NULL); for(i=0; i<MAXSIZE; i++){ tmp = oSymTable->hashtable[i]; while(tmp != NULL){ printf("name: %s\n", tmp->name); tmp = tmp->next; } } return; } /* prints the nodes of a specific scope */ void Scope_print(SymTable_T oSymTable, unsigned int scope) { FILE *f = fopen("scopes.txt","a"); Node_T tmp; assert(oSymTable!=NULL); tmp = ScopeLink[scope]; fprintf(f,"\n--------- Scope #%u --------\n", scope); while(tmp != NULL){ fprintf(f,"\"%s\" [%s] (line %d) (scope %d)\n", tmp->name, enumtostr(tmp->type), tmp->line, tmp->scope); tmp = tmp->scope_next; } fclose(f); return; } /* search agrument list of funcName function for argument argName */ Arg_T ArgumentSearch(char *funcName, char *argName, unsigned int scope){ Arg_T tmparg = NULL; Node_T tmpnode; tmpnode = Scope_lookup(funcName, userfunc, scope-1); if(tmpnode) tmparg = tmpnode->arguments; while(tmparg != NULL){ if(!strcmp(tmparg->name, argName)){ return tmparg; } tmparg = tmparg->next; } return NULL; } /* inserts an argument to the list of arguments of function funcName */ void ArgumentInsert(char *funcName, char *argName, unsigned int scope, SymTable_T oSymTable){ printf("%s, %d\n",funcName,scope-1); struct argument *tmparg, *newArg; newArg = malloc(sizeof(struct argument)); Node_T tmpNode = malloc(sizeof(struct node)); //printf("name %s type %d\n",argName,userfunc); scope--; tmpNode = Scope_lookup(funcName,userfunc,scope); newArg->name = strdup(argName); // strdup den xreiazetai malloc newArg->next = NULL; if(tmpNode && tmpNode->arguments == NULL){ tmpNode->arguments = newArg; } else if(tmpNode) { tmparg = malloc(sizeof(struct argument)); tmparg = tmpNode->arguments; tmpNode->arguments = newArg; newArg = tmparg; } return; } /* returns the current maxScope */ int ScopelinkSize() { Node_T tmp; int i, maxScope = 0; for(i=0; i<L_SIZE; i++){ if(ScopeLink[i] != NULL){ maxScope++; } else break; } return maxScope; } /* Checks for any function in a certain range of scopes */ int FuncBetween(int start, int end){ int i; for (i=start; i<=end; i++){ if (Scope_lookup(NULL, userfunc, i)) return 1; } return 0; } /* Type enum to string */ char *enumtostr(Type type){ if(type==global) return "global"; else if(type==local) return "local"; else if(type==formal) return "formal"; else if(type==userfunc) return "userfunc"; else if(type==libfunc) return "libfunc"; return NULL; }
C
#ifndef BST_H #define BST_H typedef struct { int value; }Data; typedef struct node { Data data; struct node * left; struct node * right; struct node * parent; }Node; typedef struct { Node * root; }Tree; Node * createNode(Data d, Node * parent); Tree * createTree(); Data * insert(Tree *, Data); Data * search(Tree * bst, Data value); int compare(Tree *, Tree *); Tree * clone(Tree *t); void deleteTree(Tree * bst); void removeData(Tree * bst, Data value); Data * insertNode(Node * node, Data value); Node * searchNode(Node *n, Data d); void sort(Tree *, Data *); void sortInorder(Node * n, Data * data); Node * clonePreorder(Node *n); int compareEqual(Node *, Node *); void removeLeaf(Tree *, Node *); void shortCircuit(Tree *, Node *); void promotion(Tree *, Node *); Node * searchMin(Node *); void dealewithrootcase(Tree *, Node *); void deleteNode(Node *); #endif
C
/* * ServoCommand.c * Created: 20/06/2013 10:50:07 * Authors: kerhoas, ziad * [email protected] */ #include "ServoCommand.h" #include "asf.h" #include "conf_board.h" #include "conf_clock.h" #define SERVO_HIGH 0 #define SERVO_LOW 1 #define NUM_SERVOS 2 #define SERVO_H_CHANNEL 2 #define SERVO_L_CHANNEL 3 static struct { pwm_channel_t channel; int duty; } _servoStatus[NUM_SERVOS]; int ServoCommandInit() { gpio_configure_pin(PIN_PWM_SERVOH_GPIO, PIN_PWM_SERVOH_FLAGS); gpio_configure_pin(PIN_PWM_SERVOL_GPIO, PIN_PWM_SERVOL_FLAGS); _servoStatus[SERVO_HIGH].duty = SERVO_H_DUTY_INIT; _servoStatus[SERVO_LOW ].duty = SERVO_L_DUTY_INIT; /*--------------------------------------*/ /*Initialize PWM channel for the pin20*/ /* Period is left-aligned */ _servoStatus[SERVO_HIGH].channel.alignment = PWM_ALIGN_LEFT; /* Output waveform starts at a low level */ _servoStatus[SERVO_HIGH].channel.polarity = PWM_LOW; /* Use PWM clock A as source clock */ _servoStatus[SERVO_HIGH].channel.ul_prescaler = PWM_CMR_CPRE_CLKB; /* Period value of output waveform */ _servoStatus[SERVO_HIGH].channel.ul_period = PWM_PERIOD_VALUE; /* Duty cycle value of output waveform */ _servoStatus[SERVO_HIGH].channel.ul_duty = SERVO_H_DUTY_INIT; _servoStatus[SERVO_HIGH].channel.channel = PIN_PWM_SERVOH_CHANNEL; pwm_channel_init(PWM, &_servoStatus[SERVO_HIGH].channel); /* Enable channel counter event interrupt */ //pwm_channel_enable_interrupt(PWM, PIN_PWM_SERVOH_CHANNEL, 0); /*--------------------------------------*/ /*--------------------------------------*/ /*Initialize PWM channel for the pin21*/ /* Period is left-aligned */ _servoStatus[SERVO_LOW].channel.alignment = PWM_ALIGN_LEFT; /* Output waveform starts at a low level */ _servoStatus[SERVO_LOW].channel.polarity = PWM_LOW; /* Use PWM clock A as source clock */ _servoStatus[SERVO_LOW].channel.ul_prescaler = PWM_CMR_CPRE_CLKB; /* Period value of output waveform */ _servoStatus[SERVO_LOW].channel.ul_period = PWM_PERIOD_VALUE; /* Duty cycle value of output waveform */ _servoStatus[SERVO_LOW].channel.ul_duty = SERVO_L_DUTY_INIT; _servoStatus[SERVO_LOW].channel.channel = PIN_PWM_SERVOL_CHANNEL; pwm_channel_init(PWM, &_servoStatus[SERVO_LOW].channel); /*--------------------------------------*/ pwm_channel_enable(PWM, PIN_PWM_SERVOH_CHANNEL); pwm_channel_enable(PWM, PIN_PWM_SERVOL_CHANNEL); return 1; } int SetPosH(int duty) { if (duty<H_MIN) {duty = H_MIN;} else if (duty>H_MAX) {duty = H_MAX;} pwm_channel_update_duty(PWM, &_servoStatus[SERVO_HIGH].channel, duty); _servoStatus[SERVO_HIGH].duty = duty; return duty; } int SetPosL(int duty) { if (duty<L_MIN) {duty = L_MIN;} else if (duty>L_MAX) {duty = L_MAX;} pwm_channel_update_duty(PWM, &_servoStatus[SERVO_LOW].channel, duty); _servoStatus[SERVO_LOW].duty = duty; return duty; } int GetPosH() { return _servoStatus[SERVO_HIGH].duty; } int GetPosL() { return _servoStatus[SERVO_LOW].duty; }
C
/* Copyright (c) 2013, David Hauweele <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 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. */ #include <stdlib.h> #include <stdint.h> #include "sm-kr.h" struct kr { const char *pattern; const char *text; uint32_t hash_pattern; uint32_t hash_text; unsigned int len; unsigned int index; }; kr_t kr_create(const char *pattern) { const char *s; uint32_t hash = 0; uint32_t len = 0; struct kr *kr = malloc(sizeof(struct kr)); if(!kr) return NULL; for(s = pattern ; *s ; s++) { hash = (hash << 1) + *s; len++; } kr->pattern = pattern; kr->hash_pattern = hash; kr->len = len - 1; return kr; } static bool match(const char *pattern, const char *text) { const char *p, *t; for(p = pattern, t = text ; *p == *t && *p != '\0' ; p++, t++); if(*p != *t && *p != '\0') return false; return true; } bool kr_match(kr_t kr, const char *text, size_t size) { unsigned int i; unsigned int len = kr->len; uint32_t hash = 0; for(i = 0 ; kr->pattern[i] != '\0' && text[i] != '\0' ; i++) hash = (hash << 1) + text[i]; if(hash == kr->hash_pattern && match(kr->pattern, text)) return true; for(i = 1 ; i < size - len ; i++) { hash -= (text[i-1] << len); hash = (hash << 1) + text[i+len]; if(hash == kr->hash_pattern && match(kr->pattern, text + i)) return true; } return false; } int kr_matchall(kr_t kr, const char *text, size_t size) { unsigned int i; unsigned int len; uint32_t hash; if(text) { hash = 0; for(i = 0 ; kr->pattern[i] != '\0' && text[i] != '\0' ; i++) hash = (hash << 1) + text[i]; kr->text = text; kr->hash_text = hash; kr->index = 1; if(hash == kr->hash_pattern && match(kr->pattern, text)) return 0; } text = kr->text; len = kr->len; hash = kr->hash_text; for(i = kr->index ; i < size - len ; i++) { hash -= (text[i-1] << len); hash = (hash << 1) + text[i+len]; if(hash == kr->hash_pattern && match(kr->pattern, text + i)) { kr->hash_text = hash; kr->index = i+1; return i; } } return -1; } void kr_destroy(kr_t kr) { free(kr); }
C
#include "stdio.h" #include "fcntl.h" #include "unistd.h" int main(int argc, char *argv[]) { int ret; int fd; int val = 0; if(argc != 2) { printf("error, Please input 1 argument\n"); return -1; } fd = open("/dev/led0", O_WRONLY); if(fd < 0) { printf("open failed\n"); return -1; } if(strcmp(argv[1], "on") == 0) { val = 1; printf("led on\n"); } else if( strcmp(argv[1],"off") == 0 ) { val = 0; printf("led off\n"); } write(fd, &val, 4); close(fd); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* push_swap.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ygaude <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/09/26 13:11:47 by ygaude #+# #+# */ /* Updated: 2017/12/15 02:19:15 by ygaude ### ########.fr */ /* */ /* ************************************************************************** */ #include <limits.h> #include "push_swap.h" #include "libft.h" int countitem(t_pile *pile) { int res; t_pile *cur; res = 0; cur = pile; while (pile && ++res && cur->next != pile) cur = cur->next; return (res); } int ksorted(t_pile *pile, int apile) { t_pile *cur; int i; i = 1; cur = pile; while (cur->next != pile && ((apile && cur->n < cur->next->n) || (!apile && cur->n > cur->next->n))) { i++; cur = cur->next; } return (i); } static int issorted(t_pile *pile, int until, int apile) { return (ksorted(pile, apile) >= until); } static void makeinstruct(t_pile **p1) { t_piles p; t_pile *p2; t_todo **list; int size; p2 = NULL; p.p1 = p1; p.p2 = &p2; size = countitem(*(p.p1)); if (!issorted(*(p.p1), size, 1)) { if (size <= 3) smallsort(p); else quicksort(p, size, 1, 2); list = getlist(); while (del(list)) ; printinstruct(); } } int main(int argc, char **argv) { t_pile *p1; char *str; int verbose; p1 = NULL; str = ft_strmerge(argv + 1, 1, argc - 1); if (!(parse(str, &p1, &verbose) < 1 || verbose)) makeinstruct(&p1); else if (argc > 1) ft_putstr("Error\n"); ft_strdel(&str); return (0); }
C
// Auteur Martin Dubois, ing. // Produit Enseignement/C_Cpp // Fichier Tic-Tac-Toc_Travail/Tic-Tac-Toc.c // Includes ///////////////////////////////////////////////////////////////////////////// // ===== C ================================================================== #include <assert.h> #include <stdio.h> // Constantes ///////////////////////////////////////////////////////////////////////////// #define JOUEUR_NOMBRE ( 2 ) static const char JOUEURS[JOUEUR_NOMBRE] = { 'O', 'X' }; // Declaration des fonctions statiques ///////////////////////////////////////////////////////////////////////////// static void Afficher(const char aJeu[3][3]); static int Jouer(char aJeu[3][3], char aPos, char aJoueur); static int Verifier(const char aJeu[3][3], char aJoueur); // Point d'entree ///////////////////////////////////////////////////////////////////////////// // Retour Toujours 0 int main() { unsigned int lCompteur = 0; unsigned int lJoueur = 0; char lJeu[3][3] = { { '1', '2', '3' }, { '4', '5', '6' }, { '7', '8', '9' }, }; Afficher(lJeu); while (9 > lCompteur) { char lPos[64]; printf("C'est au tour du joueur %c de jouer! Entrez une position et appuyez sur ENTER\n", JOUEURS[lJoueur]); if (1 == scanf_s("%s", lPos, sizeof(lPos))) { if (1 == Jouer(lJeu, lPos[0], JOUEURS[lJoueur])) { Afficher(lJeu); lCompteur++; if (1 == Verifier(lJeu, JOUEURS[lJoueur])) { printf("Le joueur %c est le gagnant\n", JOUEURS[lJoueur]); return 0; } lJoueur = (lJoueur + 1) % JOUEUR_NOMBRE; } } } printf("Il n'y a pas de gagnant\n"); return 0; } // Fonctions statiques ///////////////////////////////////////////////////////////////////////////// // aJeu [---;R--] Le jeu void Afficher(const char aJeu[3][3]) { unsigned int i; assert(NULL != aJeu); for (i = 0; i < 3; i++) { unsigned int j; for (j = 0; j < 3; j++) { printf(" %c ", aJeu[i][j]); if (2 != j) { printf("|"); } } printf("\n"); if (2 != i) { printf("--- --- ---\n"); } } printf("\n"); } // aJeu [---;RW-] Le jeu // aPos La position choisi par le joueur // aJoueur Le joueur qui joue, 'O' ou 'X' // // Retour // 0 La position n'est pas valide // 1 Le coup est joue int Jouer(char aJeu[3][3], char aPos, char aJoueur) { unsigned int i; assert(NULL != aJeu); assert(('O' == aJoueur) || ('X' == aJoueur)); for (i = 0; i < 3; i++) { unsigned int j; for (j = 0; j < 3; j++) { if (aPos == aJeu[i][j]) { aJeu[i][j] = aJoueur; return 1; } } } return 0; } // aJeu [---;R--] Le jeu // aJoueur Le dernier joueur a avoir joue, 'O' ou 'X' // // Retour // 0 Pas de gagnant // 1 Le joueur a gagne int Verifier(const char aJeu[3][3], char aJoueur) { assert(NULL != aJeu); assert(('O' == aJoueur) || ('X' == aJoueur)); if ((aJeu[0][0] == aJoueur) && (aJeu[0][1] == aJoueur) && (aJeu[0][2] == aJoueur)) return 1; if ((aJeu[0][0] == aJoueur) && (aJeu[1][1] == aJoueur) && (aJeu[2][2] == aJoueur)) return 1; if ((aJeu[0][0] == aJoueur) && (aJeu[1][0] == aJoueur) && (aJeu[2][0] == aJoueur)) return 1; if ((aJeu[0][1] == aJoueur) && (aJeu[1][1] == aJoueur) && (aJeu[2][1] == aJoueur)) return 1; if ((aJeu[0][2] == aJoueur) && (aJeu[1][1] == aJoueur) && (aJeu[2][0] == aJoueur)) return 1; if ((aJeu[0][2] == aJoueur) && (aJeu[1][2] == aJoueur) && (aJeu[2][2] == aJoueur)) return 1; if ((aJeu[1][0] == aJoueur) && (aJeu[1][1] == aJoueur) && (aJeu[1][2] == aJoueur)) return 1; if ((aJeu[2][0] == aJoueur) && (aJeu[2][1] == aJoueur) && (aJeu[2][2] == aJoueur)) return 1; return 0; }
C
#include<stdio.h> double power(double,int); int main() { int n; double m,c; puts("Please enter the value of m and n\n"); scanf("%lf%d",&m,&n); if(n==0) n=2; c=power(m,n); printf("The value of m power n is %lf\n",c); } double power(double a,int b) { int i; double p=1; for(i=0;i<b;i++) { p=p*a; } return p; }
C
#include <unistd.h> #include <stdio.h> main(void) { char oldfilename[100], newfilename[100]; printf ("Please input source filename:"); scanf("%s", oldfilename); printf ("Please input target filename:"); scanf("%s", newfilename); link(oldfilename, newfilename); }
C
#include<stdio.h> #include<omp.h> #include<stdlib.h> #define NUMBER_SENSORS 1000 int main() { double temperature[NUMBER_SENSORS][24]; srand(0); for(int i=0; i<1000; ++i) { for(int j=0; j<24; ++j) { temperature[i][j]= rand() % 50; } } double overall_average = 0.0; double average[NUMBER_SENSORS] = {0.0}; #pragma omp parallel for reduction(+:overall_average) for(int i=1; i<NUMBER_SENSORS; ++i) { for(int j=0; j<24; ++j) { int sum = temperature[i][j]; average[i] += sum; } average[i] = average[i] / 24; overall_average += average[i]; } for(int i=0; i<100; ++i) { printf("%f\n", average[i]); } overall_average = overall_average / NUMBER_SENSORS; printf("%f", overall_average); }
C
//Sarah Anderson //CPSC 1111.005 //lab 12 //11-27-18 //Description: This file asks for a length of a string and uses malloc to //allocate enough space. If there isnt enough room to allocate it, then it //prints out "failed". IF there is it asks for a inout from user and then //it is copied from one string to another. #include "defs.h" int main(void){ char *str1; char *str2; char *str3 = "You entered: "; int howLarge = 0; char *myString; printf("What is the longest length of a string that you will enter?"); scanf("%d", &howLarge); //allocated the amount of memeory necessary to hold the string inputed myString = malloc((howLarge + 1) * sizeof(char)); //checks to see if there is enough memeory to allocate if (myString == NULL){ printf("malloc failed to allocate enough memory!\n"); return 1; } printf("Enter a string: "); scanf("%s", str2); //copies string from one to another and prints it out my_strcpy(str1, str3); printf("%s%s\n", str3, str2); return 0; } void my_strcpy(char dest[], const char src[]){ int i = 0; //copies the string from src[] to dest[] for (i = 0; i != '\0'; i++) { dest[i] = src[i]; } }
C
/****************************************************************/ /*** Main program for experiments with scale-free graphs ***/ /*** Results (histogram in .dat files) in folders Output/ and Output_Normed/ ***/ /*** For evaluation and fitting with gnuplot use: e.g. load "Plotscripts/gnuplot_ausgabe_fit_powerLaw_M2.plt" ***/ /****************************************************************/ #include <stdio.h> #include <stdlib.h> #include <math.h> #include "list.h" #include "graphs_lists.h" int main(int argc, char **argv) { int mode; int num_nodes,max_nodes,step_size; double k_0; gs_graph_t *g; int num_real, m, i; int argz = 1; //read command-line arguments if(argc < 2) { printf("Please specify experiment mode for %s:\n" , argv[0]); printf("mode: 1-Scale Free 2-Scale Free Constant Pref 3-Planar 4-Planar Mean\n"); exit(1); } mode = atoi(argv[argz++]); if (mode == 1) { //run experiments for fixed graph size and defined parameter with normal pref attachment (path distribution) if (argc >= 4) { num_nodes = atoi(argv[argz++]); m = atoi(argv[argz++]); runExperiments(1000,num_nodes,m); } else { printf("USAGE %s <mode> <N> <m> \n", argv[0]); printf("mode = 1-Scale Free\n"); printf("N = Anzahl der Knoten im Graph\n"); printf("m = Anzahl der Kanten die hinzugefügt werden\n"); } } else if (mode == 2) { //run experiments for fixed graph size and defined parameter with constant k_0 in pref attachment (path distribution) if (argc >= 5) { num_nodes = atoi(argv[argz++]); m = atoi(argv[argz++]); k_0 = atof(argv[argz++]); runExperimentsConstant(1000,num_nodes,m,k_0); } else { printf("USAGE %s <mode> <N> <m> <k0>\n", argv[0]); printf("mode = 2-Scale Free Constant Pref\n"); printf("N = Anzahl der Knoten im Graph\n"); printf("m = Anzahl der Kanten die hinzugefügt werden\n"); printf("k_0 = Konstante für preferential attachment\n"); } } else if (mode == 3) { //run experiments on planar graph for fixed graph size (path distribution) if (argc >=3) { num_nodes = atoi(argv[argz++]); runExperimentsPlanar(1000,num_nodes); } else { printf("USAGE %s <mode> <N>\n", argv[0]); printf("mode = 3-Planar Graph \n"); printf("N = Anzahl der Knoten im Graph\n"); } } else if (mode == 4) { //run experiments on planar graph for different graph sizes (mean shortest path length) if (argc >=4) { max_nodes = atoi(argv[argz++]); step_size = atoi(argv[argz++]); runMeanExperimentsPlanar(max_nodes,step_size); } else { printf("USAGE %s <mode> <max> <stepSize>\n", argv[0]); printf("mode = 4-Planar Graph Mean\n"); printf("max = maximale Graphgroesse\n"); printf("stepSize = Schrittweite für Graphgroesse\n"); } } return(0); }
C
#include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <unistd.h> #define FIFO_WRITE "fifo_c" #define FIFO_READ "fifo_s" int main() { int fp_w; int fp_r; int i = 1; if((fp_r = open(FIFO_READ, O_RDWR)) < 0) { perror("open error : "); exit(0); } if((fp_w = open(FIFO_WRITE, O_RDWR)) < 0) { perror("open error : "); exit(0); } while(1) { sleep(1); write(fp_w, (void *)&i, sizeof(int)); read(fp_r, (void *)&i, sizeof(int)); printf("¼­¹öºÎ͵¥ÀÅ À= %d\n", i); } exit(1); }
C
#include <stdio.h> int main() { ///incomplete int alc=0,gas=0,di=0; int temp=0,n; while(1){ if(n==4){ break; } else{ scanf("%d",&n); if() if(n==1){ alc++; printf("%d",alc); } else if(n==2){ gas++; printf("%d\n",gas); } else if(n==3){ di++; printf("%d\n",di); } } } return 0; } /* MUITO OBRIGADO 1. Alcohol 2. Gasoline 3. Diesel 4. End */
C
#include <stdlib.h> #include <stdio.h> void merge(int v[], int size) { int mid; // Mid of vector (size/2) int i, j, k; int* tmp; //Use this to help sort vector tmp = (int*) malloc(size * sizeof(int)); if (tmp == NULL) { printf("\n\n\nPC DA XUXA!\n\n\n"); fflush(stdout); exit(-1); } mid = size / 2; i = 0; // Index of begining of vector j = mid; // Index of mid of vector k = 0; // Index to new vector free position; /* Enquanto estiver dentro dos limites do dos sub vetores copia dos dados * de V ordenando em TMP */ while (i < mid && j < size) { //pfddf(4); if (v[i] <= v[j]) { tmp[k] = v[i]; i++; } else { tmp[k] = v[j]; j++; } k++; } /* Copia o que faltou (a outra metade)*/ if (i == mid) { while (j < size) { tmp[k++] = v[j++]; } } else { while (i < mid) { tmp[k++] = v[i++]; } } for (i = 0; i < size; ++i) { v[i] = tmp[i]; } } void mergeSort(int vec[], int vecSize) { int mid; if (vecSize > 1) { mid = vecSize / 2; mergeSort(vec, mid); mergeSort(vec + mid, vecSize - mid); merge(vec, vecSize); } }
C
#include "sort.h" /** * bubble_sort - Here we will sort an array of integers in ascending order * @array: This is the pointer to the first element within our array * @size: This is the size of our array * * Return: We want to return non because VOID */ void bubble_sort(int *array, size_t size) { int temp = 0; int bool = 1; size_t i = 0; if (size < 2) return; if (!array) return; while (bool) { i = 0; bool = 0; while (i < size - 1) { if (array[i] > array[i + 1]) { temp = array[i]; array[i] = array[i + 1]; array[i + 1] = temp; bool = 1; print_array(array, size); } i++; } } }
C
#include <stdio.h> void fun (int *x, int *y, int *z); void main(void) { int i = 5; int array_A[3] = {1, 2, 3}; int array_B[3] = {8, 9, 10}; printf("Initial value of i: %d\n", i); printf("Initial value of array_A[0]: %d\n", array_A[0]); printf("Initial value of array_B[0]: %d\n", array_B[0]); fun(&i, &array_A[0], array_B); printf("Final value of i: %d\n", i); printf("Final value of array_A[0]: %d\n", array_A[0]); printf("Final value of array_B[0]: %d\n", array_B[0]); } void fun (int *x, int *y, int *z) { *x = 20; *y = 21; *z = 22; }
C
#include <mc32p21.h> #include "CONST.h" #include "externVar.h" // ̰ 2 void Key_Scan(void) { if(!KEY_I) //а { if(key_time <= KEY_EFFECT) //ȥ { key_time++; if(key_time == KEY_EFFECT) { if(!key_flag_bak) //ֵ { key_flag = 1; //Ч־ key_flag_bak = 1; //ɿʱ־ key_press_time = 0; //Ч } } } } else //no key,ɿ { if(key_time) { if(key_time > 5) { key_time-=3; } else { key_time = 0; key_flag_bak = 0; } } //key_time=0; //key_flag_bak=0; } } //*******ʵDiplayModelת*************** void Key_Deal(void) //ÿδkey_flag֤һΰһ { if(key_flag) { if(key_press_time >= 20) //2s { key_flag = 0; Keycode = LONGKEY; //key_cnt = 0; //key_ack = 0; } else if(key_flag_bak == 0)// ͷ { key_flag = 0; Keycode = SHORTKEY; //key_ack = 1; //key_cnt++; // ¼ //short_press_time = 0; // 2ΰ֮ʱ } } else { Keycode = NOKEY; } } /* void Key_Get(void) { if(key_ack == 1) { if((short_press_time >= 6)&&(key_cnt == 1)) // 600msʱûڶΰΰΪ̰ { key_ack = 0; key_cnt = 0; short_press_time = 0; Keycode = SHORTKEY; } else if(key_cnt >= 2) { key_ack = 0; key_cnt = 0; Keycode = DoubleKEY; short_press_time = 0; } } //else //{ // Keycode=NOKEY; //} } */
C
#include <stdlib.h> #include <pthread.h> #include <stdio.h> #include <semaphore.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <sys/types.h> #include <time.h> #include <sys/stat.h> //文件模式 /* *S_IRUSR:文件所有者的读权限 100 *S_IWUSR:文件所有者的写权限 010 *S_IRGRP:文件所有者同组用户的读权限 000 100 *S_IROTH:其他用户的读权限 000 100 */ #define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) //0644 #define NBUFF 4 //槽位的个数 #define SEM_MUTEX "mutex1" //锁mutex有名信号量的名字 #define SEM_NEMPTY "nemtpy1" //空盘数量n_empty有名信号量的名字 #define SEM_NSTORED "nstored1" //库存数量n_stored有名信号量的名字 int nitems; //条目的个数 //缓冲区结构 struct { int buff[NBUFF]; sem_t *mutex,*nempty,*nstored; //信号量 }shared; void *produce(void *arg); void *consume(void *arg); int main(int argc,char *argv[]) { pthread_t tid_produce,tid_consume; if(argc != 2) { printf("usage: prodcons <#itmes>"); exit(0); } nitems = atoi(argv[1]); //获取条目数目 //sem_t *sem_open(const char *name, int oflag,mode_t mode, unsigned int value); //mode = (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) //0644 //创建二元信号量---锁初始化为1,因为锁一开始是释放状态--对于多个生成消费者来说有必要 if((shared.mutex = sem_open(SEM_MUTEX,O_CREAT,FILE_MODE,1)) == SEM_FAILED) { perror("sem_open() error"); exit(-1); } //创建nempty信号量--空盘子初始化为4 if((shared.nempty = sem_open(SEM_NEMPTY,O_CREAT,FILE_MODE,NBUFF)) == SEM_FAILED) { perror("sem_open() error"); exit(-1); } //创建nstored信号量--库存一开始是0 if((shared.nstored = sem_open(SEM_NSTORED,O_CREAT,FILE_MODE,0)) == SEM_FAILED) { perror("sem_open() error"); exit(-1); } //生产者线程 pthread_create(&tid_produce,NULL,produce,NULL); //消费者线程 pthread_create(&tid_consume,NULL,consume,NULL); pthread_join(tid_produce,NULL); pthread_join(tid_consume,NULL); sem_unlink(SEM_MUTEX); sem_unlink(SEM_NEMPTY); sem_unlink(SEM_NSTORED); exit(0); } void *produce(void *arg) { int i; printf("produce is called.\n"); for(i=0;i<nitems;i++) { /*****************************/ //判断是否有空槽,有的将其减少1 sem_wait(shared.nempty); //锁住槽位,对于多个生产者的时候有必要,单个生产者没有必要 sem_wait(shared.mutex); /*****************************/ shared.buff[i%NBUFF] = i; printf("produced a new item: %d\n",shared.buff[i%NBUFF]); /*****************************/ sem_post(shared.mutex); //释放锁 sem_post(shared.nstored); //缓冲区中条目数加1 /*****************************/ srandom(time(NULL)); //随机数种子 usleep(random()%1000); } return NULL; } void *consume(void *arg) { int i; printf("consumer is called.\n"); for(i=0;i<nitems;i++) { /*****************************/ /*判断缓冲区中是否有条目,有的话将条目数减少1*/ sem_wait(shared.nstored); /*锁住缓冲区,对多个消费者有必要,对单个消费者没必要*/ sem_wait(shared.mutex); /*****************************/ printf("remove: buff[%d] = %d\n",i % NBUFF,shared.buff[i % NBUFF]); /*****************************/ sem_post(shared.mutex); //释放锁 sem_post(shared.nempty); //将缓冲区中的空槽数目加1 /*****************************/ srandom(time(NULL)); //随机数种子 sleep((random()%3)+1); } return NULL; }
C
#include "pngwriter.h" #include <stdlib.h> png_data *png_create(int nWidth, int nHeight) { int i; png_data *pData = (png_data *)malloc(sizeof(png_data)); pData->nWidth = nWidth; pData->nHeight = nHeight; pData->pPixels = (png_bytepp)malloc(nHeight * sizeof(png_bytep)); for (i = 0; i < nHeight; i++) pData->pPixels[i] = (png_bytep)malloc(3 * nWidth * sizeof(png_byte)); return pData; } #define CHECK_RGB_BOUNDS(x) \ if (x > 255) \ x = 255; \ if (x < 0) \ x = 0; void png_plot(png_data *pData, int x, int y, int r, int g, int b) { if (x >= pData->nWidth) return; if (y >= pData->nHeight) return; CHECK_RGB_BOUNDS(r) CHECK_RGB_BOUNDS(g) CHECK_RGB_BOUNDS(b) pData->pPixels[pData->nHeight - y - 1][3 * x - 3] = (char)r; pData->pPixels[pData->nHeight - y - 1][3 * x - 2] = (char)g; pData->pPixels[pData->nHeight - y - 1][3 * x - 1] = (char)b; } void png_write(png_data *pData, char *szFileName) { FILE *fp; png_structp png_ptr; png_infop info_ptr; fp = fopen(szFileName, "wb"); if (fp == NULL) return; png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); info_ptr = png_create_info_struct(png_ptr); png_init_io(png_ptr, fp); png_set_compression_level(png_ptr, PNGWRITER_DEFAULT_COMPRESSION); png_set_IHDR(png_ptr, info_ptr, pData->nWidth, pData->nHeight, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_set_gAMA(png_ptr, info_ptr, 0.7); png_write_info(png_ptr, info_ptr); png_write_image(png_ptr, pData->pPixels); png_write_end(png_ptr, info_ptr); png_destroy_write_struct(&png_ptr, &info_ptr); fclose(fp); free(pData); }
C
#include <stdio.h> int main(){ double max=0, a[1000], sum=0; int n, m; scanf("%d", &n); for(m=0; m<=n-1; m++){ scanf("%lf", &a[m]); if(max<=a[m]) max = a[m]; } for(m=0; m<=n-1; m++){ a[m] = (a[m]/max)*100; sum = sum + a[m]; } printf("%lf", sum/n); }
C
#include <stdio.h> #include <stdlib.h> typedef struct Stack stack; struct Stack { int * arr; int c; int max; }; stack * initStack(int max) { stack * s = (stack *)malloc(sizeof(stack)); s->c = 0; s->max = max; s->arr = (int *)malloc(max*sizeof(int)); return s; } void push(stack *s, int n) { if(s->c < s->max - 1) { s->arr[s->c] = n; s->c = s->c + 1; } } int pop(stack * s) { int t; if(s->c != 0) { t = s->arr[s->c-1]; s->c = s->c - 1; } return t; } typedef struct Node node; struct Node { int v; node * next; }; typedef struct Graph graph; struct Graph { int v; int e; node ** adj; int * b; int * f; int * p; int * s; }; int tm; graph * initGraph(int num) { graph * g = (graph *)malloc(sizeof(graph)); g->v = num; g->e = 0; g->adj = (node **)malloc(num*sizeof(node *)); g->b = (int *)malloc(num*sizeof(int)); g->f = (int *)malloc(num*sizeof(int)); g->p = (int *)malloc(num*sizeof(int)); g->s = (int *)malloc(num*sizeof(int)); int i=0; for(i=0;i<num;i++) { g->adj[i] = NULL; g->s[i] = 0; g->b[i] = 0; g->f[i] = 0; g->p[i] = -1; } return g; } void addEdge(graph * g, graph * gt, int u, int v) { node * n = (node *)malloc(sizeof(node)); n->v = v; n->next = g->adj[u]; g->adj[u] = n; g->e = g->e + 1; n = (node *)malloc(sizeof(node)); n->v = u; n->next = gt->adj[v]; gt->adj[v] = n; gt->e = gt->e + 1; } void printGraph(graph * g) { int ver = g->v; int i; node * ele; for(i=0;i<ver;i++) { printf("%d :: ", i); ele = g->adj[i]; while(ele !=NULL) { printf("%d --> ", ele->v); ele = ele->next; } printf("\n"); } } typedef struct Edge edge; struct Edge { int u; int v; }; edge e[50]; int edgeC; void dfs(graph *g, int s, stack *st){ tm++; g->b[s] = tm; g->s[s] = 1; //printf("%d\t", s); node *current= g->adj[s]; while(current != NULL){ if(g->s[current->v] == 0){ g->p[current->v] = s; e[edgeC].u = s; e[edgeC].v = current->v; edgeC++; dfs(g, current->v, st); } current = current->next; } g->f[s]= ++tm; g->s[s] = 2; push(st, s); } void scc(graph *g, graph *gt){ tm = 0; int ver = g->v, i; stack *st1= initStack(100); stack *st2= initStack(100); for(i=0;i<50;i++) { e[i].u = -1; e[i].v = -1; } edgeC = 0; for(i=0;i<ver;i++){ if(g->s[i] == 0){ dfs(g, i, st1); for(edgeC = edgeC - 1;edgeC>=0;edgeC--){ printf("(%d,%d)\t", e[edgeC].u , e[edgeC].v); } edgeC = 0; printf("\n"); } } for(i=0;i<ver;i++) { printf("%d :: %d\t%d\t%d\t%d\n", i, g->p[i], g->b[i], g->f[i], g->s[i] ); } edgeC = 0; tm = 0; int vert; while(st1->c!=0){ vert= pop(st1); if(gt->s[vert] == 0){ dfs(gt, vert, st2); for(edgeC = edgeC - 1;edgeC>=0;edgeC--) { printf("(%d,%d)\t", e[edgeC].u , e[edgeC].v); } edgeC = 0; printf("\n"); } } for(i=0;i<ver;i++) { printf("%d :: %d\t%d\t%d\t%d\n", i, gt->p[i], gt->b[i], gt->f[i], gt->s[i] ); } } int main(){ int ver = 8; graph *g, * gt; g = initGraph(ver); gt= initGraph(ver); addEdge(g, gt, 0, 1); addEdge(g, gt, 1, 2); addEdge(g, gt, 2, 3); addEdge(g, gt, 2, 5); addEdge(g, gt, 3, 2); addEdge(g, gt, 3, 4); addEdge(g, gt, 4, 4); addEdge(g, gt, 5, 4); addEdge(g, gt, 6, 5); addEdge(g, gt, 5, 6); addEdge(g, gt, 7, 6); addEdge(g, gt, 1, 6); addEdge(g, gt, 1, 7); addEdge(g, gt, 7, 0); printGraph(g); printf("\n\n"); printGraph(gt); scc(g, gt); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ngenadie <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/09/21 21:08:48 by ngenadie #+# #+# */ /* Updated: 2020/10/20 15:36:07 by ngenadie ### ########.fr */ /* */ /* ************************************************************************** */ #include <string.h> #include <stdio.h> #include <stdlib.h> #include "get_next_line.h" #include <unistd.h> int ft_nl_index(char *str) { int i; i = 0; while (str[i]) { if (str[i] == '\n') return (i + 1); i++; } return (0); } int ft_strlen(char *str) { int i; i = 0; while (str[i]) i++; return (i); } char *ft_realloc(char *str, char *buff, int len) { char *new_str; int i; int j; i = 0; j = 0; buff[len] = '\0'; len = ft_strlen(str) + ft_strlen(buff); if (!(new_str = (char *)malloc(sizeof(char) * (len + 1)))) return (NULL); while (str[i]) { new_str[i] = str[i]; i++; } while (buff[j]) { new_str[i] = buff[j]; j++; i++; } new_str[i] = '\0'; free(str); str = NULL; return (new_str); } char *ft_send_clean(char **s, char *str, int nl_index) { int i; char *new_str; i = 0; new_str = NULL; if (!(*s = (char*)malloc(sizeof(char) * (nl_index + 1)))) return (NULL); while (str[i] && str[i] != '\n') { (*s)[i] = str[i]; i++; } (*s)[i] = '\0'; i = 0; if (!(new_str = (char*)malloc(ft_strlen(str) - nl_index + 1))) return (NULL); while (str[nl_index + i]) { new_str[i] = str[nl_index + i]; i++; } new_str[i] = '\0'; free(str); str = NULL; return (new_str); } int get_next_line2(char *str, char **line) { int nl_index; nl_index = 0; if ((nl_index = ft_nl_index(str)) == 0 || nl_index == ft_strlen(str)) { if (!(str = ft_send_clean(line, str, ft_strlen(str)))) return (-1); free(str); str = NULL; } else if (!(str = ft_send_clean(line, str, nl_index))) return (-1); return (1); } int get_next_line(int fd, char **line) { int nl_index; char buff[BUFFER_SIZE + 1]; static char *str = NULL; int len; len = 1; if (fd < 0 || BUFFER_SIZE <= 0 || line == NULL) return (-1); if (str == NULL) { if (!(str = malloc(BUFFER_SIZE + 1))) return (-1); str[0] = 0; } while ((nl_index = ft_nl_index(str)) == 0 && (len = read(fd, buff, BUFFER_SIZE)) > 0) if (!(str = ft_realloc(str, buff, len)) || len == -1) return (-1); if (len < 0) return (-1); if (get_next_line2(str, line) != 1) return (-1); if (len == 0 && str == NULL) return (0); return (1); } int main(int ac, char **av) { char *s = NULL; int fd; (void)ac; int n = 0; int ret; (void)n; int i = 0; if ((fd = open(av[1], O_RDONLY)) == -1) return (-1); while ((ret = get_next_line(fd, &s)) == 1) { if (ret == -1) return -1; printf("i: %i, ret: %i, line: %s\n", i, ret, s); //printf("n = %i\n", n++); free(s); i++; printf("-----------------------------------------------------\n"); } printf("ret: %i", ret); // system("leaks a.out"); return (ret); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* error.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: aren <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/03/14 16:15:39 by aren #+# #+# */ /* Updated: 2016/03/26 23:17:50 by aren ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/push_swap.h" void ft_check_max_int(char *av) { int i; char *str; i = 0; str = "2147483647"; if (ft_strlen(av) == ft_strlen(str)) { while (av[i] && str[i]) { if (av[i] > str[i]) ft_error_str_exit("Error\n"); i++; } } } void ft_check_min_int(char *av) { int i; char *nstr; i = 0; nstr = "2147483648"; if (ft_strlen(av) == ft_strlen(nstr)) { while (av[i] && nstr[i]) { if (av[i] > nstr[i]) ft_error_str_exit("Error\n"); i++; } } } void ft_check_overflow(char *av) { unsigned int i; int neg; i = 0; neg = 0; if (*av == '-') { neg = 1; av++; } if (ft_strlen(av) > ft_strlen("2147483647")) ft_error_str_exit("Error\n"); if (ft_strlen(av) == ft_strlen("2147483647")) { if (neg == 1) ft_check_min_int(av); else ft_check_max_int(av); } while (ft_isdigit(av[i])) ++i; if (av[i]) ft_error_str_exit("Error\n"); } unsigned char ft_check_params(int ac, char **av) { int i; int tmp; if (ac < 2) exit(1); validate_arguments(ac, av); i = 1; while (ac > i) ft_check_overflow(av[i++]); tmp = 1; while (ac > tmp) { i = 2; while (i < ac && i != tmp) { if (!ft_strcmp(av[i], av[tmp])) ft_error_str_exit("Error\n"); ++i; } ++tmp; } return (0); }
C
/* window.c Author: Joshua Prendergast */ #include "main_window.h" #define INT16_MAX 65535 void main_window_init(game *game, main_window *window) { window->game = game; window->window = gtk_window_new(GTK_WINDOW_TOPLEVEL); window->drawing_area = gtk_drawing_area_new(); GtkWidget *layout = gtk_vbox_new(FALSE, 0); GtkWidget *controls = main_window_create_controls(window); gtk_window_set_title(GTK_WINDOW(window->window), "SightReader"); gtk_window_set_position(GTK_WINDOW(window->window), GTK_WIN_POS_CENTER); gtk_window_set_default_size(GTK_WINDOW(window->window), 550, 450); /* Setup our signal handlers */ g_signal_connect(G_OBJECT(window->drawing_area), "expose_event", G_CALLBACK(main_window_stave_exposed), (gpointer) window); g_signal_connect(G_OBJECT(window->window), "destroy", G_CALLBACK(game_destroy), (gpointer) game); gtk_container_add(GTK_CONTAINER(window->window), layout); gtk_box_pack_start(GTK_BOX(layout), window->drawing_area, TRUE, TRUE, 5); gtk_box_pack_start(GTK_BOX(layout), controls, FALSE, FALSE, 5); main_window_load_images(window); /* Initialize colors */ window->red.red = INT16_MAX * 0.7; window->red.green = window->red.blue = 0; window->white.red = window->white.green = window->white.blue = INT16_MAX; window->black.red = window->black.green = window->black.blue = 0; window->gray.red = window->gray.green = window->gray.blue = INT16_MAX * 0.10; window->selected_modifier = NOTE_MOD_NONE; } void main_window_destroy(main_window *window) { } GtkWidget *main_window_create_controls(main_window *window) { GtkWidget *vbox = gtk_vbox_new(FALSE, 0); /* Vertical layout; contains everything */ GtkWidget *row1 = gtk_hbox_new(FALSE, 0); /* Horizontal layout for note buttons */ /* Add note selection buttons */ GtkWidget *cur_btn; int i; for (i = 0; i < NOTE_MAX; i++) { cur_btn = gtk_button_new(); window->btns[i] = cur_btn; window->control_data[i].value = i; window->control_data[i].window = window; g_signal_connect(G_OBJECT(cur_btn), "clicked", G_CALLBACK(main_window_note_clicked), (gpointer) &window->control_data[i]); gtk_box_pack_start(GTK_BOX(row1), cur_btn, TRUE, TRUE, 1); } main_window_relabel_notes(window); /* Add rows */ gtk_box_pack_start(GTK_BOX(vbox), row1, FALSE, FALSE, 0); /* Finally, add status line */ window->status = gtk_label_new("Name the note on the stave"); gtk_box_pack_start(GTK_BOX(vbox), window->status, FALSE, FALSE, 15); return vbox; } void main_window_load_images(main_window *window) { /* TODO error handling */ GError *err = NULL; window->pixbufs[PIXBUF_TREBLE] = gdk_pixbuf_new_from_file("images/treble.png", &err); window->pixbufs[PIXBUF_BASS] = gdk_pixbuf_new_from_file("images/bass.png" , &err); window->pixbufs[PIXBUF_SHARP] = gdk_pixbuf_new_from_file("images/sharp.png" , &err); window->pixbufs[PIXBUF_FLAT] = gdk_pixbuf_new_from_file("images/flat.png" , &err); } void main_window_relabel_notes(main_window *window) { char label[NOTE_NAME_MAX_LEN]; note note; note.modifiers = window->selected_modifier; int i; for (i = 0; i < NOTE_MAX; i++) { note.value = i; note_get_name(&note, label); gtk_button_set_label(GTK_BUTTON(window->btns[i]), label); } } void main_window_set_selected_modifier(main_window *window, int selected_modifier) { window->selected_modifier = selected_modifier; main_window_relabel_notes(window); } /* * Signal handlers */ void main_window_note_clicked(GtkWidget *widget, gpointer data) { control_data *cd = ((control_data *) data); /* Submit the answer */ note user_answer = { .value = cd->value, .modifiers = cd->window->selected_modifier }; game_submit_answer(cd->window->game, &user_answer); main_window_relabel_notes(cd->window); } gboolean main_window_stave_exposed(GtkWidget *widget, GdkEventExpose *event, gpointer data) { game *g = ((main_window *) data)->game; GdkGC *gc = widget->style->fg_gc[gtk_widget_get_state(widget)]; int treble = g->clef == CLEF_TREBLE; GdkPixbuf *buf = treble ? g->main_window.pixbufs[PIXBUF_TREBLE] : g->main_window.pixbufs[PIXBUF_BASS]; /* The stave image; treble or bass */ /* Used for centering - apply to all drawing operations */ int origin_x = event->area.width / 2 - gdk_pixbuf_get_width(buf) / 2; int origin_y = event->area.height / 2 - gdk_pixbuf_get_height(buf) / 2; /* Draw a dark gray background */ gdk_gc_set_rgb_fg_color(gc, &g->main_window.gray); gdk_draw_rectangle(GDK_DRAWABLE(widget->window), gc, TRUE, event->area.x, event->area.y, event->area.width, event->area.height); /* Draw the stave, centered vertically */ gdk_pixbuf_render_to_drawable(buf, GDK_DRAWABLE(widget->window), gc, 0, 0, origin_x, origin_y, -1, -1, GDK_RGB_DITHER_MAX, 0, 0); int i; for (i = 0; i < NOTES_PER_BAR; i++) { note *drawn = &g->notes[i]; int render_pos = treble ? drawn->value : drawn->value - 2; /* The line to draw the note on */ int note_x = origin_x + STAVE_NOTE_X + 75 * i; int note_y = origin_y + STAVE_C_Y - render_pos * STAVE_SPACING_Y; if (g->current_note == i) gdk_gc_set_rgb_fg_color(gc, &g->main_window.red); else gdk_gc_set_rgb_fg_color(gc, &g->main_window.black); /* Draw the current note */ gdk_draw_arc(widget->window, gc, TRUE, note_x, note_y, STAVE_GAP_Y, STAVE_GAP_Y, 0, 360 * 64); /* Draw accidental */ int flat = (drawn->modifiers & NOTE_MOD_FLAT) == NOTE_MOD_FLAT; int sharp = (drawn->modifiers & NOTE_MOD_SHARP) == NOTE_MOD_SHARP; if (flat || sharp) { gdk_pixbuf_render_to_drawable(sharp ? g->main_window.pixbufs[PIXBUF_SHARP] : g->main_window.pixbufs[PIXBUF_FLAT], GDK_DRAWABLE(widget->window), gc, 0, 0, note_x - 13, note_y - 2, -1, -1, GDK_RGB_DITHER_MAX, 0, 0); } /* Draw ledger lines */ gdk_gc_set_rgb_fg_color(gc, &g->main_window.black); int below = render_pos <= 0; int above = render_pos >= 12; if (below || above) { /* Calculate the amount of ledger lines to draw and the direction to draw them in. */ int cur_line; int start = below ? 0 : 12; /* Start position */ int dir = below ? -2 : 2; int end = drawn->value; /* Last line which might have a ledger (if it's even) */ if (!treble) end -= 2; for (cur_line = start; below ? cur_line >= end : cur_line <= end; cur_line += dir) { gdk_draw_rectangle( GDK_DRAWABLE(widget->window), gc, TRUE, note_x + STAVE_GAP_Y / 2 - STAVE_LEDGER_LEN / 2, origin_y + STAVE_C_Y - cur_line * STAVE_SPACING_Y + (STAVE_GAP_Y / 2), STAVE_LEDGER_LEN, 4); } } /* Draw note names */ char label[NOTE_NAME_MAX_LEN]; note_get_name(drawn, label); if (i < g->current_note) { /* Draw label */ } } return TRUE; }
C
#include "asm.h" void print_token(t_token *token) { if (token == NULL) return ; ft_putstr(token->str); write(1, " [", 2); ft_putstr(type_to_string(token->type_token)); write(1, "]", 1); } void print_token_list(t_token_list *token_list) { t_token *token; token = token_list->begin; while (token != NULL) { print_token(token); write(1, "\n", 1); token = token->next; } } void print_arr(t_asm *asm_node) { t_byte **arr; size_t len; size_t index; arr = asm_node->arr; len = asm_node->len_arr; index = 0; while (index < len) { ft_putstr_fd("[value = ", 1); ft_putnbr_fd(arr[index]->value, 1); ft_putstr_fd(", size = ", 1); ft_putnbr_fd(arr[index]->num_bytes, 1); ft_putstr_fd("]", 1); ft_putstr_fd("\n", 1); ++index; } } void print_byte_array(const char *arr, size_t len) { size_t index; char c; index = 0; while (index < len) { if (arr[index] == 0) write(1, "0", 1); else { c = arr[index]; ft_putnbr(c); } write(1, " ", 1); ++index; } write(1, "\n", 1); } void print_malloc_free(void) { ft_putstr("\nMalloc:"); ft_putnbr(ml); ft_putstr(" Free:"); ft_putnbr(fr); ft_putstr("\n"); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #define FD_OUT stdout #define SPACE " " #define NEWLINE "\n" #define STRFORM "%s" /* Prototypes for helper functions */ void xit(char** argv, int argc); void eco(char** argv, int argc); void chDir(char** argv, int argc); void setEnv(char** argv, int argc); void unsetEnv(char** argv, int argc); struct command { char *y; void(*z)(char** argv, int argc); }; const struct command tp[] = { {"",NULL}, {"exit",&xit}, {"aecho",&eco}, {"cd",&chDir}, {"envset",&setEnv}, {"envunset",&unsetEnv}, {NULL,NULL} }; /* * this method runs the command based on the argument input */ int built_in(char **argv, int argc) { int i; for(i = 1; tp[i].y != NULL; i++) if(!strcmp(tp[i].y,argv[0])) { return i; } return 0; } int execute_built_in(int i, char** argv, int argc) { tp[i].z(argv, argc); } void xit(char** argv, int argc) { int t = argc > 1 ? atoi(argv[1]) : 0; free(argv); exit(t); } void eco(char** argv, int argc) { int j = (argc > 1 && !strcmp(argv[1],"-n")) ? 2 : 1; // flag for '-n' option int k = (j == 2)? 0 : 1; for(; j < argc -1; j++) { fprintf(FD_OUT, STRFORM, argv[j]); fprintf(FD_OUT, STRFORM, SPACE); } /* If there exist actual arguments print the last one*/ if((!k && argc > 2) || (k && argc > 1)) fprintf(FD_OUT, STRFORM, argv[j]); /* print "\n" based on flag */ if(k) fprintf(FD_OUT, STRFORM, NEWLINE); } void chDir(char** argv, int argc) { if(argc > 1) chdir(argv[1]); else chdir("../"); } void setEnv(char** argv, int argc) { if(argc == 3) { setenv(argv[1],argv[2],1); } } void unsetEnv(char** argv, int argc) { if(argc == 2) unsetenv(argv[1]); }
C
#ifndef __J1939_TRANSCEIVER_PLATFORM_H__ #define __J1939_TRANSCEIVER_PLATFORM_H__ #include <stdint.h> #ifndef __FAR #define __FAR #endif struct can_extended_frame { uint32_t id; uint8_t len; uint8_t dat[8]; }; /// \brief transceiver_received_callback CAN收发器在接受到一帧数据并保存之后调用这个回调函数通知上层接收到数据. /// /// \param dat 附加数据, 这个数据在 初始化的时候传入的. /// /// \return 返回下次接收到数据帧之后数据存放的未知. typedef struct can_extended_frame *__FAR (*transceiver_received_callback)(void *__FAR dat, struct can_extended_frame *frame); struct transceiver_operations { uint8_t (*init)(void *__FAR private_data, uint32_t baudrate, transceiver_received_callback cb, void *__FAR dat, struct can_extended_frame *frame); uint8_t (*send)(void *__FAR private_data, const struct can_extended_frame *__FAR frame); uint8_t (*set_recv_filter)(void *__FAR private_data, uint32_t filter, uint32_t mask); }; struct transceiver { void *private_data; const struct transceiver_operations *ops; }; /// \brief transceiver_init 初始化CAN收发器 /// /// \param can CAN收发器 /// \param baudrate 波特率 /// \param cb 接收数据的回调函数. /// \param dat 调用回调函数时附加参数. /// \param frame 接收到数据之后存放的未知. /// /// \return static inline uint8_t transceiver_init(const struct transceiver *__FAR can, uint32_t baudrate, transceiver_received_callback cb, void *__FAR dat, struct can_extended_frame *frame) { return can->ops->init(can->private_data, baudrate, cb, dat, frame); } static inline uint8_t can_transceiver_send(const struct transceiver *__FAR can, const struct can_extended_frame *__FAR frame) { return can->ops->send(can->private_data, frame); } #endif
C
#include <stdio.h> #include <string.h> void printCharCount(int index, int *array) { if ((index >= 48 && index < 58) || (index >= 65 && index < 91) || (index >= 97 && index < 123)) { printf("char[%c] = %d\n", index, array[index]); } } int main() { FILE *fileI = fopen("gram.in", "r"); FILE *fileO = fopen("gram.out", "w+"); char wordPrime[50] = "\0"; int wordCount; fscanf(fileI, "%s", wordPrime); fscanf(fileI, "%d", &wordCount); // Take the count of each letter in wordPrime int charArray[256] = {0}; int i; for (i = 48; i < 58; i++) charArray[i] = 0; for (i = 65; i < 91; i++) charArray[i] = 0; for (i = 97; i < 123; i++) charArray[i] = 0; // Take the count for (i = 0; i < strlen(wordPrime); i++) { charArray[wordPrime[i]] += 1; //printf("char - %c\n", wordPrime[i]); } /* for (i = 0; i < 256; i++) { printCharCount(i, charArray); } */ for (i = 0; i < wordCount; i++) { int checkArray[256] = {0}; // Read a word to check char wordCheck[50] = "\0"; fscanf(fileI, "%s", wordCheck); //printf("word - %s\n", wordCheck); // Store the character data int j; for (j = 0; j < strlen(wordCheck); j++) { checkArray[wordCheck[j]] += 1; } // Compare to prime word int test = 0; for (j = 0; j < strlen(wordPrime); j++) { int testA = charArray[wordPrime[j]]; int testB = checkArray[wordPrime[j]]; //printf("testA = %d, testB = %d\n", testA, testB); if (testA == testB) test++; } if (test == strlen(wordPrime)) { if (strcmp(wordPrime, wordCheck) == 0) fprintf(fileO, "IDENTICAL\n"); else fprintf(fileO, "ANAGRAM\n"); } else { fprintf(fileO, "NOT AN ANAGRAM\n"); } } //printf("word - %s\n", wordPrime); //printf("count - %d\n", wordCount); return 0; }
C
#include "sock_funs.h" int get_IP_MAC( char *ip, int ip_l, char *mac, int mac_l) { //返回的IP地址为字符串型:"192.168.1.1",返回Mac为6个char struct ifreq ifr; struct ifconf ifc; char buf[max_ether_len]; int success = 0; int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);//create a socket to get mac and ip address if (sock == -1) { perror("socket error\n"); return -1; } ifc.ifc_len = sizeof(buf); ifc.ifc_buf = buf; if (ioctl(sock, SIOCGIFCONF, &ifc) == -1) {//ioctl是设备驱动程序中对设备的I/O通道进行管理的函数,获取所有接口的清单 perror("ioctl error\n"); close(sock); return -1; } struct ifreq* it = ifc.ifc_req; const struct ifreq* const end = it + (ifc.ifc_len / sizeof(struct ifreq)); char szMac[64]; int count = 0; for (; it != end; ++it) { strcpy(ifr.ifr_name, it->ifr_name); if (ioctl(sock, SIOCGIFFLAGS, &ifr) == 0) { if ( (! (ifr.ifr_flags & IFF_LOOPBACK)) && (ifr.ifr_flags & IFF_UP) ) { // don't count loopback,避免记录环路,仅仅记录up状态的 if (ioctl(sock, SIOCGIFINDEX, &ifr) == -1) {//return index of card perror ("get index error!"); close(sock); return -1; } success = ifr.ifr_ifindex; if (ioctl(sock, SIOCGIFHWADDR, &ifr) == 0) {//获取mac地址 count ++ ; unsigned char * ptr ; ptr = (unsigned char *)&ifr.ifr_ifru.ifru_hwaddr.sa_data[0]; if (mac != NULL && mac_l >= mac_len) memcpy(mac, ptr, mac_len); snprintf(szMac, 64, "%02X:%02X:%02X:%02X:%02X:%02X", *ptr, *(ptr + 1), *(ptr + 2), *(ptr + 3), *(ptr + 4), *(ptr + 5)); //printf("%d,Interface name : %s , Mac address : %s \n", count, ifr.ifr_name, szMac); } else { perror("get mac error!"); close(sock); return -1; } if (ioctl(sock, SIOCGIFADDR, &ifr) == -1 ) { //get ip address perror("ioctl() get ip"); close(sock); return -1; } else { char *src_ip = inet_ntoa(((struct sockaddr_in *) & (ifr.ifr_addr))->sin_addr); if (ip != NULL && ip_l > strlen(src_ip)) strcpy(ip, src_ip); //printf("local ip:%s\n", src_ip); } } } else { perror("get info error\n"); close(sock); return -1; } } close(sock); return success; } void getandparse_arp() { char buffer[max_ether_len]; int sock, n; struct ethhdr *eth; my_arp *arp; if (0 > (sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ARP)))) { perror("socket"); close(sock); exit(1); } rec: memset(buffer, 0, max_ether_len); n = recvfrom(sock, buffer, max_ether_len, 0, NULL, NULL); printf("\n\n\nrecv %d Bytes\n", n); eth = (struct ethhdr*)buffer; printf("Dest MAC addr:%02x:%02x:%02x:%02x:%02x:%02x\n", eth->h_dest[0], eth->h_dest[1], eth->h_dest[2], eth->h_dest[3], eth->h_dest[4], eth->h_dest[5]); printf("Source MAC addr:%02x:%02x:%02x:%02x:%02x:%02x\n", eth->h_source[0], eth->h_source[1], eth->h_source[2], eth->h_source[3], eth->h_source[4], eth->h_source[5]); arp = (my_arp*)(buffer + sizeof(struct ethhdr)); if(arp->op_type == 1) printf("arp request!\n"); else if (arp->op_type == 2) printf("arp response!\n"); printf("src ip:%s\n", inet_ntoa( *((struct in_addr*) & (arp->src_ip)) )); printf("des ip:%s\n", inet_ntoa( *((struct in_addr*) & (arp->des_ip)) )); printf("src mac in packet:%02x:%02x:%02x:%02x:%02x:%02x\n", arp->src_mac[0], arp->src_mac[1], arp->src_mac[2], arp->src_mac[3], arp->src_mac[4], arp->src_mac[5]); printf("des mac in packet:%02x:%02x:%02x:%02x:%02x:%02x\n", arp->des_mac[0], arp->des_mac[1], arp->des_mac[2], arp->des_mac[3], arp->des_mac[4], arp->des_mac[5]); //goto rec; close(sock); } int fill_mac_arp(my_mac *p) { char mac_cro[mac_len] = BROADCAST_ADDR; memcpy(p->des, mac_cro, mac_len); get_IP_MAC(NULL, 0, p->src, mac_len); p->type = htons(ETHERTYPE_ARP); return 0; } int fill_arp(my_arp*p) { p->hd_type = htons(ARPHRD_ETHER); p->pro_type = htons(ETHERTYPE_IP); p->mac_length = mac_len; p->ip_length = ip_len; p->op_type = htons(ARPOP_REPLY);//ARPOP_REQUEST get_IP_MAC(NULL, 0, p->src_mac, mac_len); char mac_cro[60] = {0}; //memcpy(p->des_mac,mac_cro,mac_len); memset(p->des_mac, 0, mac_len);//destion mac is all zero get_IP_MAC(mac_cro, 60, NULL, 0); // printf("fil_arp_ip:%s\n", mac_cro); #if 0 p->src_ip = inet_addr(mac_cro); #else p->src_ip = inet_addr("10.137.0.1"); #endif // 1 p->des_ip = inet_addr("10.137.225.51"); return 0; } int send_arp() { struct sockaddr_ll saddr; int sock_raw_fd; int ret_len = 0; my_mac ma; my_arp ar; char buff[max_ether_len] = {0}; memset(&saddr, 0, sizeof(struct sockaddr_ll)); saddr.sll_ifindex = get_IP_MAC(NULL, 0, NULL, 0); //printf("ifindex:%d\n", saddr.sll_ifindex); saddr.sll_family = PF_PACKET; fill_mac_arp(&ma); fill_arp(&ar); memcpy(buff, &ma, sizeof(my_mac)); memcpy(buff + sizeof(my_mac), &ar, sizeof(my_arp)); if ((sock_raw_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ARP))) == -1) { perror("create send socket error!"); return -1; } for (int i = 0; i < sizeof(my_mac) + sizeof(my_arp); i++) printf("%02x ", buff[i] & 0xff); ret_len = sendto(sock_raw_fd, buff, sizeof(my_mac) + sizeof(my_arp), 0, (struct sockaddr *)&saddr, sizeof(struct sockaddr_ll));// if (ret_len < 0) { perror("send error!"); close(sock_raw_fd); return -1; } printf("send data:%d Bytes\n", ret_len); close(sock_raw_fd); return 0; } /* int main() { char p[100]; get_IP_MAC(p, 100, NULL, 0); printf("%s\n", p); while(1){ send_arp(); sleep(1); } getandparse_arp(); return 0; } */
C
/* * ============================================================================ * * Filename: srv_io.c * * Description: Server's input and output and parser for client I/O * Functions: * void broadcast(const List *usr_lst, const char *msg, int self_sock) * -> Prints msg to every socket except self_sock * void private_msg(char *message, const User_Sock *src) -> * Private messages a user, parse message to find destination * User * void client_cmd(List *usr_lst, Node *usr_node, char *msg) -> * Parses the msg for the servers desired output * * Version: 1.0 * Created: 09/19/2015 14:53:11 * Revision: none * Compiler: gcc * * Author: Theodore Ahlfeld (), [email protected] * Organization: * * ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <time.h> #include "server.h" #include "srv_io.h" /* External global data from server.c */ extern size_t MAXBUF; extern fd_set mstr_fds; extern int serv_sock; extern int timeout; /* * Broadcasts msg to all users except for theirself * const List *usr_lst -> The list of users to broadcast to * const char *msg -> The message to broadcast * const int self_sock -> The originators socket to not broadcast to */ void broadcast(const List *usr_lst, const char *msg, const int self_sock) { if (msg) { printf("%s", msg); Node *clnt_node = usr_lst->head; size_t len = strlen(msg); while (clnt_node) { User_Sock *usr_sock = (User_Sock *) (clnt_node->data); if (usr_sock) { int tmp_sock = usr_sock->sock; // send to everyone! if (FD_ISSET(tmp_sock, &mstr_fds)) { // except the listener and ourselves if (tmp_sock != serv_sock && tmp_sock != self_sock) { if (send(tmp_sock, msg, len, 0) == -1) { perror("send() failed"); } } } } clnt_node = clnt_node->next; } } } /* * Broadcasts to a specified list of users * char *rol -> (rest of line) the clients msg without the broadcast user * int sock -> the sock of the original broadcaster */ void pvt_broadcast(char *rol, User_Sock *usr_src) { List pvt_usr_list; init_list(&pvt_usr_list); if (rol) { User_Sock *usr_sock; char *buf = strtok(rol, " \n"); // first user in rol char msg[MAXBUF]; while (buf) { // ensures valid format if (strcasecmp(buf, "message") == 0) { buf = strtok(NULL, "\n"); if (buf == NULL) goto cleanup; sprintf(msg, "%s: %s\n", usr_src->name, buf); broadcast(&pvt_usr_list, msg, usr_src->sock); break; } else { usr_sock = find_usr(buf); if (usr_sock) { add_front(&pvt_usr_list, usr_sock); } buf = strtok(NULL, " \n"); } } } cleanup: remove_all_nodes(&pvt_usr_list); } /* * Send a private message, destination is in rol * char *rol -> (rest of line) include the user destination along with msg * const User_Sock *src -> The user that initiated the PM */ void private_msg(char *rol, const User_Sock *src) { char buf[MAXBUF]; char *base; size_t len; if (rol == NULL) goto end; if ((base = strtok(rol, " \n")) == NULL) goto end; User_Sock *dst = find_usr(base); if (dst == NULL && (dst->name) == NULL) goto end; if ((base = strtok(NULL, "\n")) == NULL) goto end; fprintf(stderr, "%s->", src->name); fprintf(stderr, "%s:", dst->name); fprintf(stderr, "%s\n", base); printf("%s->%s: %s\n", src->name, dst->name, base); len = sprintf(buf, "%s: %s\n", src->name, base); send(dst->sock, buf, len, 0); end: return; } /* * Parses the clients output into procedure for the server * List *usr_lst -> The list of users from the server * Node *usr_node -> The node from usr_lst that initiated the command * char *msg -> The message that the user submitted */ void client_cmd(List *usr_lst, Node *usr_node, char *msg) { char *cmd = strtok(msg, " \n"), *base; if(cmd == NULL) return; User_Sock *usr_sock = (User_Sock *) (usr_node->data); char *name = usr_sock->name; int sock = usr_sock->sock; Node *node_itr = usr_lst->head; char buf[MAXBUF]; size_t len; if (strcasecmp(cmd, "quit") == 0 || strcasecmp(cmd, "logout") == 0) { remove_node(usr_lst, usr_node); kill_user(usr_sock, 0); } else if (strcasecmp(cmd, "broadcast") == 0) { if ((base = strtok(NULL, " \n")) == NULL) { // No further input goto end; } else { if (strcasecmp(base, "message") == 0) { // Full Broadcast sprintf(buf, "%s: %s\n", name, strtok(NULL, "\n")); broadcast(usr_lst, buf, sock); } else if (strcasecmp(base, "user") == 0) { // Private broadcast pvt_broadcast(strtok(NULL, "\n"), usr_sock); } } } else if (strcasecmp(cmd, "message") == 0) { // Private message private_msg(strtok(NULL, "\n"), usr_sock); } else if (strcasecmp(cmd, "motd") == 0) { // change motd strcpy(buf, strtok(NULL, "\n")); if (strlen(buf)) { set_motd(buf, name); } else { print_motd(sock); } } else if (strcasecmp(cmd, "timeout") == 0) { // change timeout int new_timeout; strcpy(buf, strtok(NULL, " \n")); char *timeout_base = buf; new_timeout = (int) strtol(buf, &timeout_base, 10); if (*timeout_base != '\0') { // invalid format printf("%s failed to change timeout to %s\n", name, timeout_base); len = sprintf(buf, "SERVER: invalid input timeout\n"); send(sock, buf, len, 0); } else { timeout = new_timeout; sprintf(buf, "%s changed timeout %d\n", name, timeout); broadcast(usr_lst, buf, -1); } } else if (strcasecmp(cmd, "whoelse") == 0) { // whoelse char *active_client; len = sprintf(buf, "Current Users:\n"); send(sock, buf, len, 0); while (node_itr) { if ((active_client = ((User_Sock *) (node_itr->data))->name)) { len = sprintf(buf, "\t%s\n", active_client); send(sock, buf, len, 0); } node_itr = node_itr->next; } } else if (strcasecmp(cmd, "wholast") == 0) { time_t rqst_time; strcpy(buf, strtok(NULL, " \n")); base = buf; rqst_time = strtol(buf, &base, 10); if (*base != '\0' || (rqst_time <= 0 && rqst_time > 60)) { printf("%s invalid wholast %s(%ld)\n", name, buf, rqst_time); len = sprintf(buf, "SERVER: invalid wholast input," "must be between 0 and 60\n"); send(sock, buf, len, 0); } else { sprintf(buf, "Current Users<Login in last %ld minutes>:\n", rqst_time); node_itr = usr_lst->head; while (node_itr) { User_Sock *wholast_usr = (User_Sock *) (node_itr->data); if (usr_sock->name && time(NULL) - wholast_usr->login < rqst_time * 60) { len = sprintf(buf, "\t%s\n", wholast_usr->name); send(sock, buf, len, 0); } node_itr = node_itr->next; } } } return; end: len = sprintf(buf, "Bad Command Syntax\n"); send(sock, buf, len, 0); }
C
#include <stdio.h> // 最小移動回数を求める。 int hanoi_min(int n) { if(n > 1) return( 2*hanoi_min(n - 1) + 1 ); else return 1; } //  最小で移動させる手順を求める。 // hanoi(int 円盤数,int 移動元,int 仲介,int 移動先) void hanoi(int n, char start, char use, char end) { if(n > 0) { hanoi(n - 1, start, end, use); printf("円盤%dを 杭%c から 杭%c へ\n", n, start, end); hanoi(n - 1, use, start, end); } } int main() { int disk; printf("円盤の数:"); scanf("%d", &disk); puts("-----------------"); printf("最小移動回数:%d\n", hanoi_min(disk)); puts("-----------------"); puts("以下は移動手順\n"); hanoi(disk, 'A', 'B', 'C'); return 0; }
C
#include <stdio.h> int menor(int a, int b){ int m; m = b; if (a>b) m = b; return m; } int main (int argc, char ** argv){ int num1, num2, resultado; scanf ("%d", &num1); scanf ("%d", &num2); resultado = menor(num1, num2); printf("%d", resultado); return 0; }
C
#include "6a.h" static Node* create_Node(int data, Node* link) { Node* temp = (Node*)malloc(sizeof(Node)); temp -> data = data; temp -> link = link; return temp; } void List_initialize(List* ptr_List) { //TODO ptr_List->head=NULL; ptr_List->number_of_Nodes=0; } void List_insert_front(List* ptr_List, int data) { //TODO Node *temp=(Node*)malloc(sizeof(Node)); temp=create_Node(data,temp); temp->link=ptr_List->head; ptr_List->head=temp; ptr_List->number_of_Nodes++; } const int Node_get_data(Node *Node_ptr) { //TODO return(Node_ptr->data); } void List_delete_front(List* ptr_List) { //TODO if(ptr_List->head==NULL) { printf("Empty list.\n"); return; } Node *temp=ptr_List->head; ptr_List->head=temp->link; free(temp); ptr_List->number_of_Nodes--; } void List_destroy(List* ptr_List) { //TODO Node *temp=ptr_List->head; Node *next; while(temp!=NULL) { next=temp->link; free(temp); temp=next; } ptr_List->head=NULL; } void stack_initialize(Stack *ptr_stack) { // TODO ptr_stack->ptr_List=(List*)malloc(sizeof(List)); List_initialize(ptr_stack->ptr_List); } void stack_push(Stack *ptr_stack, int key) { // TODO List_insert_front(ptr_stack->ptr_List,key); } void stack_pop(Stack *ptr_stack) { // TODO List_delete_front(ptr_stack->ptr_List); } int stack_is_empty(Stack *ptr_stack) { // TODO if(ptr_stack->ptr_List->number_of_Nodes!=0) { return 0; } else { return(1); } } const int stack_peek(Stack *ptr_stack) { // TODO int temp=Node_get_data(ptr_stack->ptr_List->head); return(temp); } void stack_destroy(Stack *ptr_stack) { // TODO List_destroy(ptr_stack->ptr_List); } int postfix_eval(const char* expression) { // TODO Stack *ptr_stack=(Stack*)malloc(sizeof(Stack)); stack_initialize(ptr_stack); int i=0; int op1,op2,res; int eval,temp; char sym; while(expression[i]!='\0') { sym=expression[i]; if(sym>='0'&&sym<='9') { stack_push(ptr_stack,sym-'0'); } else { op2=stack_peek(ptr_stack); stack_pop(ptr_stack); op1=stack_peek(ptr_stack); stack_pop(ptr_stack); switch(sym) { case '+':res=op1+op2; break; case '-':res=op1-op2; break; case '*':res=op1*op2; break; case '/':res=op1/op2; break; case '$': case '^':temp=1; while(op2>0) { temp=op1*temp; op2--; } res=temp; break; } stack_push(ptr_stack,res); } i++; } eval=stack_peek(ptr_stack); stack_destroy(ptr_stack); return(eval); }
C
// // Created by lieroz on 02.12.16. // #ifndef LAB_10_GRAPH_H #define LAB_10_GRAPH_H #include "heap.h" // A structure to represent a node in adjacency list typedef struct AdjListNode { int dest; int weight; struct AdjListNode* next; } AdjListNode; // A structure to represent an adjacency list typedef struct { AdjListNode* head; // pointer to head node of list } AdjList; // A structure to represent a graph. A graph is an array of adjacency lists. // Size of array will be V (number of vertices in graph) typedef struct { int V; AdjList* array; } Graph; // A utility function that creates a graph of V vertices Graph* CreateGraph(int); // An utility function to destroy Graph void DestroyGraph(Graph*); // Adds an edge to an undirected graph void AddEdge(Graph*, int, int, int); #endif //LAB_10_GRAPH_H
C
#include "lists.h" /** * free_list - function that frees a list_t list. * @head: pointer to the first element * Return: Always 0. */ void free_list(list_t *head) { list_t *clear = head; for (clear = head; clear != NULL; clear = clear->next) { free(clear->str); free(clear); } }
C
#include <stdio.h> int f_003_002(int a, int b, int c, int d) { printf("\n a=%d", a); printf("\n b=%d", b); printf("\n c=%d", c); printf("\n d=%d", d); printf("\n ==================="); int I, i, max, min, result; I=4; int mass[I]; mass[0] = a; mass[1] = b; mass[2] = c; mass[3] = d; max = mass[0]; min = mass[0]; for(i = 0; i < I; i++) { if(max < mass[i]) max = mass[i]; if(min > mass[i]) min = mass[i]; } result = max; printf("\n result= %d\n============= ", result); return result; }
C
//smallest of three numbers using min variable #include<stdio.h> void in(int *x, int *y, int *z) { printf("Enter the three numbers, I shall determine the smallest of them.\n"); scanf("%d %d %d",x,y,z); } int com(int a,int b, int c) { int min=a; if(b<min) min=b; if(c<min) min=c; return min; } void op(int z) { printf("\nSmallest of the three entered numbers is %d \n",z); } void main() { int a,b,c,s; in(&a,&b,&c); s=com(a,b,c); op(s); }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_3__ TYPE_1__ ; /* Type definitions */ typedef scalar_t__ u_int32_t ; struct camq {TYPE_1__** queue_array; int /*<<< orphan*/ entries; } ; struct TYPE_3__ {scalar_t__ priority; } ; /* Variables and functions */ int /*<<< orphan*/ heap_down (TYPE_1__**,int,int /*<<< orphan*/ ) ; int /*<<< orphan*/ heap_up (TYPE_1__**,int) ; void camq_change_priority(struct camq *queue, int index, u_int32_t new_priority) { if (new_priority > queue->queue_array[index]->priority) { queue->queue_array[index]->priority = new_priority; heap_down(queue->queue_array, index, queue->entries); } else { /* new_priority <= old_priority */ queue->queue_array[index]->priority = new_priority; heap_up(queue->queue_array, index); } }
C
#include<stdio.h> void swap(int* a, int* b); int main() { int x; int y; printf("Introduceti x: "); scanf("%d", &x); printf("Introduceti y: "); scanf("%d", &y); printf("\nInainte de interschimbare: \n"); printf("x = %d\ty = %d \n", x, y); swap(&x, &y); printf("\nDupa de interschimbare: \n"); printf("x = %d\ty = %d \n", x, y); return 0; } void swap(int* a, int* b) { int c; c = *b; *b = *a; *a = c; }
C
#include "projection.h" bool overlaps(Projection p1, Projection p2) { return !(p1.min > p2.max || p1.max < p2.min); } double getOverlap(Projection p1, Projection p2) { return (MIN_(p1.max, p2.max) - MAX_(p1.min, p2.min)); }
C
/* eval.c - Evaluation */ #include <stdio.h> #include <string.h> /* parse_single() */ #include <parser.h> /* object definition */ #include <object.h> /* env_hashtable definition */ #include <hashtable.h> #include <eval.h> static object *eval_preproc(object *obj, env_hashtable *env); static object *preprocess_syntax(object *obj); static object *preprocess_list_syntax(object *list); /* Parse and evaluate string */ object *eval_str(const char *s, env_hashtable *env) { parser *p = parser_new(); parser_set_str(p, s); object *obj = parse_single(p); return eval(obj, env); } object *eval(object *obj, env_hashtable *env) { return eval_preproc(preprocess_syntax(obj), env); } /* Evaluate preprocessed object * NULL return value means Nothing */ static object *eval_preproc(object *obj, env_hashtable *env) { object *cur, *eobj, *last_pair, *t, *ecar, *ecdr; if (!obj) return NULL; /* Detect syntatic construction */ if (TYPE(obj) == OBJ_PAIR && TYPE(CAR(obj)) == OBJ_SYMBOL) { t = CAR(obj); if (strcmp("lambda", STR(t)) == 0) { eobj = compound_procedure(CADR(obj), CDDR(obj), env); return eobj; } else if (strcmp("define", STR(t)) == 0) { if (TYPE(CADR(obj)) == OBJ_SYMBOL) { eobj = eval_preproc(CADDR(obj), env); env_hashtable_insert(env, STR(CADR(obj)), eobj); return NULL; /* Not error, just nothing */ } else if (TYPE(CADR(obj)) == OBJ_PAIR) { eobj = compound_procedure(CDADR(obj), CDDR(obj), env); env_hashtable_insert(env, STR(CAADR(obj)), eobj); return NULL; } return NULL; } else if (strcmp("begin", STR(t)) == 0) { obj = CDR(obj); eobj = NULL; /* Not error, just nothing */ while (obj != null_object) { eobj = eval_preproc(CAR(obj), env); obj = CDR(obj); } return eobj; } else if (strcmp("apply", STR(t)) == 0) { eobj = eval_preproc(CADR(obj), env); t = eval_preproc(CADDR(obj), env); return apply(eobj, t); } else if (strcmp("quote", STR(t)) == 0) { return CADR(obj); } else if (strcmp("if", STR(t)) == 0) { eobj = eval_preproc(CADR(obj), env); if (eobj != false_object) return eval_preproc(CADDR(obj), env); if (CDDDR(obj) != null_object) return eval_preproc(CADDDR(obj), env); return NULL; } } /* Object evaluation */ switch (TYPE(obj)) { case OBJ_NUMBER: case OBJ_BOOLEAN: return obj; case OBJ_SYMBOL: return env_hashtable_find(env, STR(obj)); case OBJ_PAIR: cur = obj; eobj = null_object; last_pair = NULL; while (cur != null_object && TYPE(cur) == OBJ_PAIR) { t = cons(eval_preproc(CAR(cur), env), null_object); if (!last_pair) eobj = t; else CDR(last_pair) = t; last_pair = t; cur = CDR(cur); } ecar = CAR(eobj); ecdr = CDR(eobj); return apply(ecar, ecdr); default: return NULL; } } static object *preprocess_syntax(object *obj) { object *t; if (TYPE(obj) == OBJ_PAIR && CAR(obj) && TYPE(CAR(obj)) == OBJ_SYMBOL) { t = CAR(obj); if (strcmp("let", STR(t)) == 0) { CDR(obj) = preprocess_list_syntax(CDR(obj)); object *lambda_params = null_object, *lambda_params_tail = NULL, *lambda_args = null_object, *lambda_args_tail = NULL, *lambda_list = null_object, *lambda_list_tail = NULL, *lambda_body = CADDR(obj), *bindings = CADR(obj), *binding; while (bindings != null_object) { binding = CAR(bindings); object_list_append(&lambda_params, &lambda_params_tail, CAR(binding)); object_list_append(&lambda_args, &lambda_args_tail, CADR(binding)); bindings = CDR(bindings); } object_list_append(&lambda_list, &lambda_list_tail, symbol("lambda")); object_list_append(&lambda_list, &lambda_list_tail, lambda_params); object_list_append(&lambda_list, &lambda_list_tail, lambda_body); lambda_list = cons(lambda_list, lambda_args); return lambda_list; } } if (TYPE(obj) == OBJ_PAIR) { return preprocess_list_syntax(obj); } return obj; } static object *preprocess_list_syntax(object *list) { object *result_list = null_object, *result_list_tail = NULL; while (list != null_object) { if (TYPE(list) != OBJ_PAIR) { CDR(result_list_tail) = list; break; } object_list_append(&result_list, &result_list_tail, preprocess_syntax(CAR(list))); list = CDR(list); } return result_list; } /* Apply procedure */ object *apply(object *proc, object *args) { primitive_proc p; env_hashtable *e; object *params, *param, *arg; char *s_param; if (TYPE(proc) == OBJ_PRIMITIVE_PROCEDURE) { p = PROC(proc); return p(args); } else if (TYPE(proc) == OBJ_COMPOUND_PROCEDURE) { e = env_hashtable_child(CPROC_ENV(proc)); params = CPROC_PARAMS(proc); while (params != null_object) { if (TYPE(params) != OBJ_PAIR) { param = params; arg = args; } else { param = CAR(params); arg = CAR(args); } s_param = STR(param); env_hashtable_insert(e, s_param, arg); if (TYPE(params) != OBJ_PAIR) break; params = CDR(params); args = CDR(args); } return eval_preproc(CPROC_BODY(proc), e); } return NULL; }
C
#include "stdio.h" #define N 10 void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } int findMinIndex(int a[], int startIndex, int len) { int minIndex = startIndex, minElem = a[minIndex]; for (int i = startIndex; i < len; i++) { if (a[i] < minElem) { minElem = a[i]; minIndex = i; } } return minIndex; } void printArr(int a[], int l) { for (int i = 0; i < l; i++) { printf("%d", a[i]); } printf("\n"); } int main(int argc, char *argv[]) { int a[N] = {9, 8, 6, 7, 4, 3, 3, 2, 1, 0}; int t; printArr(a, N); swap(&a[0], &a[9]); // buble sort t = findMinIndex(a, 0, 10); for (int i = 0; i < N; i++) { int m = findMinIndex(a, i, N); swap(&a[i], &a[m]); } printArr(a, N); printf("Min index:%d", t); }
C
#include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<sys/mman.h> #include<unistd.h> #include<stdlib.h> #include<fcntl.h> #define MAPLEN 0x1000 struct STU{ int id; char name[ 20]; char sex; }; void sys_err( char *str, int exitno) { perror( str); exit( exitno); } int main( int argc, char *argv[ ]){ struct STU *mm; int fd, i = 0; if( argc < 2){ printf( "./a.out filename\n" ); exit( 1); } fd = open( argv[ 1], O_RDWR|O_CREAT, 0777); if( fd < 0) sys_err( "open",1 ); if( lseek( fd, MAPLEN-1, SEEK_SET) < 0) sys_err( "lseek",3 ); if( write( fd, "\0",1 )<0) sys_err( "write",4 ); mm = mmap( NULL, MAPLEN, PROT_READ|PROT_WRITE,MAP_SHARED, fd,0); if( mm == MAP_FAILED) sys_err( "mmap",2 ); close( fd); while( 1){ mm->id = i; sprintf( mm->name, "zhang-%d",i ); if( i%2 == 0) mm->sex = 'm'; else mm->sex = 'w'; i++; sleep( 1); } munmap( mm, MAPLEN); return 0; }
C
/*ͷ巨*/ #include <stdio.h> #include <stdlib.h> typedef struct LNode { int data; struct LNode* next; }LNode_t, * pLNode_t; void insertHead(pLNode_t* toHead, pLNode_t* toTail, int newData) { pLNode_t pNew; pNew = (pLNode_t)calloc(1, sizeof(LNode_t)); pNew->data = newData; if (*toHead == NULL) { *toHead = pNew; *toTail = pNew; } else { pNew->next = *toHead; *toHead = pNew; } } void print(pLNode_t pHead) { while (pHead) { printf("%d ", pHead->data); pHead = pHead->next; } putchar('\n'); } int main() { pLNode_t pHead = NULL, pTail = NULL; int newData; while (scanf("%d", &newData) != EOF) { insertHead(&pHead, &pTail, newData); } print(pHead); system("pause"); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* rush04.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: raga <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/08 11:32:16 by raga #+# #+# */ /* Updated: 2020/02/08 17:41:57 by macosta ### ########.fr */ /* */ /* ************************************************************************** */ void ft_putchar(char c); void ft_first_line(int largeur) { int colonne; if (largeur > 0) { ft_putchar('A'); colonne = 1; while (colonne <= largeur - 2) { ft_putchar('B'); colonne++; } } if (largeur > 1) { ft_putchar('C'); } } void ft_middle_line(int largeur) { int colonne; colonne = 1; if (largeur > 0) { ft_putchar('B'); while (colonne <= (largeur - 2)) { ft_putchar(' '); colonne++; } } if (largeur > 1) { ft_putchar('B'); } } void ft_latest_line(int largeur) { int colonne; if (largeur > 0) { ft_putchar('C'); colonne = 1; while (colonne <= (largeur - 2)) { ft_putchar('B'); colonne++; } } if (largeur > 1) { ft_putchar('A'); } } void rush(int x, int y) { int line; line = 1; if ((x <= 0) || (y <= 0)) return ; ft_first_line(x); ft_putchar('\n'); while (++line <= y) { while (line < y) { ft_middle_line(x); ft_putchar('\n'); line++; } if (line == y) { ft_latest_line(x); ft_putchar('\n'); } } }
C
#include "monty.h" /** * main - entry point * * @ac: argument counter * @av: argument vector * * Return: EXIT_SUCCESS if succes, EXIT_FAILURE otherwise * * Description: a simple interpreter for the monty language */ int main(int ac, char **av) { FILE *fd = NULL; int i, ret = 0, line_number = 1, opcount = 11; size_t size = 0; char *data = NULL, delims[] = " \t\n\r", *save = NULL; instruction_t codes[] = { {"push", push_node}, {"pall", print_stuck}, {"pint", print_int}, {"pop", popper}, {"swap", swapper}, {"add", adderall}, {"nop", nope}, {"sub", sub}, {"div", diva}, {"mul", emule}, {"mod", mood}, {"pchar", puchero}, {NULL, NULL} }; stack_t *head = NULL; fd = getfile(ac, av); if (fd == NULL) return (EXIT_FAILURE); line = NULL; ret = getline(&line, &size, fd); while (ret != -1) { if (line == NULL || strcmp(line, "") == 0) break; save = strdup(line); data = strtok(save, delims); while (data != NULL) { for (i = 0; i < opcount; i++) { if (strcmp(data, codes[i].opcode) == 0) { codes[i].f(&head, line_number); break; } else if (i == opcount) { fprintf(stderr, "L%d: unknown instruction %s\n", line_number, data); free(line); free(data); fclose(fd); free(fd); free(save); free_stack(head); return (EXIT_FAILURE); } } data = strtok(NULL, delims); } line_number++; ret = getline(&line, &size, fd); } free(line); free(data); fclose(fd); free(fd); free(save); free_stack(head); return (EXIT_SUCCESS); }
C
#include <stdio.h> #include <stdlib.h> #define TAM 3 void escreva(int *s){ for(int i=0;i<TAM;i++){ printf("%d ",s[i]); } printf("\n"); } void permutacao(int *s,int i, int *v, int n,int *x){ if(i == TAM ){ escreva(s); }else{ for(int j=0;j<n;j++){ if(x[j]==0){ x[j]=1; s[i]=v[j]; permutacao(s,i+1,v,n,x); x[j]=0; } } } } int main(){ int s[TAM]; int x[TAM]; int v[TAM]; for(int i=0;i<TAM;i++){ s[i]=0; x[i]=0; v[i]=i+1; } permutacao(s,0,v,TAM,x); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #define fifoName "/tmp/my_fifo" int main(int argc, char const *argv[]) { int res,i; int open_mode = 0; int check = 1; if (argc <2 || argc>3){ printf("Uso: Inserisci la modalità di apertura della FIFO\n"); exit(1); } /* Impostiamo il valore di open_mode dagli argomenti */ for(i=1;i<argc;i++){ if(check){ if(strncmp(argv[i],"O_RDONLY",8) == 0){ open_mode |= O_RDONLY; check = 0; } else if(strncmp(argv[i],"O_WRONLY",8) == 0){ open_mode |= O_WRONLY; check = 0; } } if(strncmp(argv[i],"O_NONBLOCK",8) == 0) open_mode |= O_NONBLOCK; } /*Se la FIFO non esiste la creiamo. Poi viene aperta */ if(access(fifoName,F_OK) == -1){ /*verifica l'accessibilità del real User-ID, mode può essere R_OK,W_OK,X_OK e F_OK*/ res = mkfifo(fifoName,0777); if (res != 0){ printf("Non posso creare la FIFO %s\n",fifoName); exit(2); } } printf("Processo %d apre la FIFO\n\n",getpid()); res = open(fifoName,open_mode); printf("Risultato processo %d: %d\n",getpid(),res); sleep(6); if(res != -1) close(res); printf("Processo %d terminato\n",getpid()); return 0; }
C
{\rtf1\ansi\ansicpg1252\cocoartf1038\cocoasubrtf320 {\fonttbl\f0\fswiss\fcharset0 Helvetica;} {\colortbl;\red255\green255\blue255;} \margl1440\margr1440\vieww17200\viewh14820\viewkind0 \pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural \f0\fs24 \cf0 //Keith Crosby\ //Created September 12, 2010\ //This program distinguishes if the object inputted by the user is a square or a triangle.\ //Then it computes the area of a square or a triangle.\ \ #include<stdio.h>\ int main (void)\ { char a='s'; //Declaring character that specifies the shape float x; //Variable is the side length of the square float c; //equal to the area of the square float b, h, d; //the base of the triangle char z; //variable to hold the y/n answer while (z !='n' && z != 'N')\ { printf("Is the shape a square or a triangle (S/T)\\n"); //asks the user if they are dealing with a square or a triangle. scanf("%c", &a); if (a == 's') //if a square continue within brackets\'85otherwise go to else\ { printf("What is the side length of the square?\\n"); //concluding that the object is a square, sakes for the side length\ scanf("%f", &x);\ c = (x*x); //equation for finding the area of the square\ printf("The area of your square is equal to %.2f\\n", c); //prints the area found\ \}\ else //If the user says it is a triangle continue within brackets\ \{\ printf("what is the base length of the triangle?\\n"); //asks for the base of the triangle\ scanf("%f", &b);\ printf("What is the height of the triangle?\\n"); //asks for the height of the triangle\ scanf("%f", &h);\ d = 0.5*b*h; //equation for finding the area of a triangle\ printf("The area of your triangle is equal to %.2f\\n", d); //prints the area of the triangle\ \}\ printf("Do you wish to continue (y/n)?\\n"); //asks the user if they wish to calculate another area\ fflush(stdin);\ scanf("%c", &z);\ fflush(stdin);\ \}\ return (0);\ \}}
C
#define F_CPU 8e6 #include <avr/io.h> #include <util/delay.h> #include <avr/interrupt.h> #include <stdio.h> #define LCD_E 3 #define LCD_RS 2 void lcd_strobe_lcd_e(void); void init_4bits_mode(void); void lcd_write_string(char *str); void lcd_write_data(unsigned char byte); void lcd_write_cmd(unsigned char byte); void lcd_strobe_lcd_e(void) { PORTC |= (1<<LCD_E); // E high _delay_ms(1); // nodig PORTC &= ~(1<<LCD_E); // E low _delay_ms(1); // nodig? } void init_4bits_mode(void) { // PORTC output mode and all low (also E and RS pin) DDRC = 0xFF; PORTC = 0x00; // Step 2 (table 12) PORTC = 0x20; // function set lcd_strobe_lcd_e(); // Step 3 (table 12) PORTC = 0x20; // function set lcd_strobe_lcd_e(); PORTC = 0x80; lcd_strobe_lcd_e(); // Step 4 (table 12) PORTC = 0x00; // Display on/off control lcd_strobe_lcd_e(); PORTC = 0xF0; lcd_strobe_lcd_e(); // Step 4 (table 12) PORTC = 0x00; // Entry mode set lcd_strobe_lcd_e(); PORTC = 0x60; lcd_strobe_lcd_e(); } void lcd_write_string(char *str) { for(;*str; str++){ lcd_write_data(*str); } } void lcd_write_data(unsigned char byte) { // First nibble. PORTC = byte; PORTC |= (1<<LCD_RS); lcd_strobe_lcd_e(); // Second nibble PORTC = (byte<<4); PORTC |= (1<<LCD_RS); lcd_strobe_lcd_e(); } void lcd_write_command(unsigned char byte) { // First nibble. PORTC = byte; PORTC &= ~(1<<LCD_RS); lcd_strobe_lcd_e(); // Second nibble PORTC = (byte<<4); PORTC &= ~(1<<LCD_RS); lcd_strobe_lcd_e(); } void lcd_clear() { lcd_write_command (0x01); //Leeg display _delay_ms(2); lcd_write_command (0x80); //Cursor terug naar start } int main( void ) { // Init I/O DDRD &= 0b10000000; DDRB = 0xFF; int temp = 0xFF; char *tekst = " "; TCCR2 = 0b00000111; // Init LCD init_4bits_mode(); temp = TCNT2; while (1) { PORTB = TCNT2; if(PORTB != temp){ lcd_clear(); lcd_write_string(sprintf(tekst, "%d", TCNT2)); temp = PORTB; } _delay_ms(20); } return 1; }
C
#include <stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<stdlib.h> #include<string.h> #include<fcntl.h> #include<event2/event.h> void read_cb(evutil_socket_t fd,short what,void *arg) { //读管道 char buf[1024]={0}; int len=read(fd,buf,sizeof(buf)); printf("data len=%d,buf=%s\n",len,buf); printf("read event:%s",what&EV_READ?"yes":"no"); } //管道读 int main() { unlink("myfifo"); //创建管道 mkfifo("myfifo",0664); //open file int fd=open("myfifo",O_RDONLY|O_NONBLOCK); if(fd==-1) { perror("open error"); exit(1); } //读管道 //1\创建框架 struct event_base* base=NULL; base =event_base_new(); //2、创建事件 struct event *ev=NULL; //ev=event_new(base,fd,EV_READ|EV_PERSIST,read_cb,NULL); ev=event_new(base,fd,EV_READ,read_cb,NULL); //3、加入到框架中 event_add(ev,NULL); //4、进入循环事件 event_base_dispatch(base); //5、释放资源 event_free(ev); event_base_free(base); close(fd); return 0; }
C
#include <stdio.h> int main() { char str[] = "kitty on your lap"; printf("str[0]の内容\t\t= %c\n" , *str); printf("str[0]のアドレス\t= %x" , str); // 警告: format ‘%x’ expects type ‘unsigned int’, but argument 2 has type ‘char *’ return 0; }
C
#include <stdio.h> #include <unistd.h> #include <dirent.h> #include <limits.h> #include <errno.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <stdlib.h> #define BUFFSIZE 4096 int tcp(const char* source, const char* target); int main(int argc, const char *argv[]) { //ensure the parameter is not null if (argv[2]==0) exit(EXIT_FAILURE); tcp(argv[1], argv[2]); exit(EXIT_SUCCESS); } int tcp(const char* source, const char* target) { ssize_t n; int fd[2]; char buf[BUFFSIZE]; //open source file, get descripter if ((fd[0]=open( source, O_RDONLY )) < 0){ perror("open error"); exit(EXIT_FAILURE); } //make sure the argv[2] is a directory or a file, and excute in different occations. struct stat st; stat(target,&st); if (S_ISDIR(st.st_mode)){ char path[100]; sprintf(path,"%s%s",target,source); if ((fd[1] = open(target, O_RDWR | O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR | S_IXUSR)) < 0) { close(fd[0]); exit(EXIT_FAILURE); } } else{ if ((fd[1] = open(target, O_RDWR | O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR | S_IXUSR)) < 0) { close(fd[0]); exit(EXIT_FAILURE); } } while( (n= read( fd[0], buf, BUFFSIZE)) > 0){ if ( write( fd[1], buf, n) != n){ perror("open error"); exit(EXIT_FAILURE); } } close(fd[0]); close(fd[1]); exit(EXIT_SUCCESS); }
C
#include <stdio.h> int main() { int a0, a1, a2; scanf("%d %d %d", &a0, &a1, &a2); int b0, b1, b2; scanf("%d %d %d", &b0, &b1, &b2); printf("%d %d", (a0 > b0) + (a1 > b1) + (a2 > b2), (a0 < b0) + (a1 < b1) + (a2 < b2)); }
C
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Bluetoot control using a snake byte device * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * This file defines all the necessary functions to do what you need * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * @author Ferriol Pey Comas 03/05/2016 @version 1.0 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include "include/MandoBluetooth.h" char llegeixMando() { char c; system("/bin/stty raw");//intro sola despres de cada pulsació c=getchar(); if(c==27)//una tecla de fletxa te una estructura de ESC + '[' + A|B|C|D { c=getchar();//'[' c=getchar();// A|B|C|D } system("/bin/stty cooked");//treu l'intro sola if(c=='A') c=UP; else if(c=='B')c=DOWN; else if(c=='C')c=RIGHT; else if(c=='D')c=LEFT; return c; }
C
/** * \file local_mm.c * \brief Matrix Multiply file for Proj1 * \author Kent Czechowski <kentcz@gatech...>, Rich Vuduc <richie@gatech...> */ #include <assert.h> #include <stdlib.h> #include <stdio.h> #define MB *1024*1024 #define KB *1024 /* Intel Xeon X5650 CPU Gulftown (sixcore) */ /* L1 and L2 cache are per core */ #define L1_DATA_CACHE_SIZE (32 KB) #define L2_CACHE_SIZE (256 KB) #define L3_CACHE_SIZE (12 MB) #define TLB0_PAGE_SIZE (2 MB) #define TLB0_PAGE_SIZE_MAYBE (4 MB) #define TLB0_PAGE_ENTRIES 32 #define L2_TLB_PAGE_ENTRIES 512 #define TLB_PAGE_SIZE (4 KB) #define TLB_PAGE_ENTRIES 64 #define L2_TLB_PAGE_SIZE (4 KB) #if defined(USE_TLB) # include <string.h> #endif #if defined(USE_OPEN_MP) || defined(USE_BLOCKING) # include <omp.h> #endif #ifdef USE_MKL # include <mkl.h> #endif #if !defined(USE_MKL) && !defined(USE_OPEN_MP) && !defined(USE_TLB) && !defined(USE_BLOCKING) # define USE_ORIGINAL #endif #define MIN(a, b) ((a < b) ? a : b) #define MAX(a, b) ((a > b) ? a : b) static double* arrange_to_page(int height, int width, double *mat, int rows, int cols) { int i, j; double* page; page = (double*)malloc(sizeof(double) * rows * cols); //posix_memalign((void**)&page, L2_TLB_PAGE_SIZE, sizeof(double) * rows * cols); int blockSize = width * height; int x = 0, y = 0; for(i = 0; i < rows; i++) { for(j = 0; j < cols; j++) { int matIdx = j + i * rows; page[y + x * rows] = mat[matIdx]; //Move index in a block format if(++y % height == 0 || y >= rows) { y -= y> rows ? rows % height : height; x++; //next row if(x % width == 0 || x >= cols) { x -= x> cols ? cols % width : width; y += height; //next block horiz if(y >= rows) { x += width; y = 0; } }//endif }//endif } } return page; } static void print_matrix(int rows, int cols, const double *mat) { int r, c; /* Iterate over the rows of the matrix */ for (r = 0; r < rows; r++) { /* Iterate over the columns of the matrix */ for (c = 0; c < cols; c++) { int index = (c * rows) + r; fprintf(stderr, "%.0lf ", mat[index]); } /* c */ fprintf(stderr, "\n"); } /* r */ } /** * * Local Matrix Multiply * Computes C = alpha * A * B + beta * C * * * Similar to the DGEMM routine in BLAS * * * alpha and beta are double-precision scalars * * A, B, and C are matrices of double-precision elements * stored in column-major format * * The output is stored in C * A and B are not modified during computation * * * m - number of rows of matrix A and rows of C * n - number of columns of matrix B and columns of C * k - number of columns of matrix A and rows of B * * lda, ldb, and ldc specifies the size of the first dimension of the matrices * **/ void local_mm(const int m, const int n, const int k, const double alpha, const double *A, const int lda, const double *B, const int ldb, const double beta, double *C, const int ldc) { /* Verify the sizes of lda, ladb, and ldc */ assert(lda >= m); assert(ldb >= k); assert(ldc >= m); //fprintf(stderr, "A=\n"); //print_matrix(m, k, A); //fprintf(stderr, "A=\n"); //print_matrix(m, k, A); #ifdef USE_BLOCKING int bk = 8; int bm = 4096; int bn = 16; /* Check for tiny matrices */ bk = MIN(k, bk); bm = MIN(m, bm); bn = MIN(n, bn); double* aPaged = arrange_to_page(bm, bk, A, m, k); //print_matrix(m, k, A); //printf("-------------------\n"); //print_matrix(m, k, aPaged); int apply_beta = 1; int k_block; /* K blocks increase top to bottom on B matrix (and left to right on A) */ for (k_block = 0; k_block < k/bk + 1; k_block++) { int i_block; /* I blocks increase top to bottom on A/C matrix */ for (i_block = 0; i_block < m/bm + 1; i_block++) { int j_block; int pageSize = bk * bm; int addr = pageSize * (k/bk * i_block + k_block); if(m % bm != 0) addr -= k_block * (bm - m % bm) * bk; if(k_block == k/bk && k % bk != 0) { addr -= i_block * (bk - k % bk) * bm; } double* page = &aPaged[addr]; # pragma omp parallel for private (j_block) /* J blocks increase left to right on B/C matrix */ for (j_block = 0; j_block < n/bn + 1; j_block++) { // puts("\n*** here ***\n"); int block_row; int block_col; /* Iterate over the columns of C */ for (block_col = 0; block_col < bn; block_col++) { /* Check for non power of 2 matrices being complete */ if (j_block*bn + block_col >= n) { break; } /* Iterate over the rows of C */ for (block_row = 0; block_row < bm; block_row++) { int k_iter; double dotprod = 0.0; /* Accumulates the sum of the dot-product */ /* Check for non power of 2 matrices being complete */ if (i_block*bm + block_row >= m) { break; } /* Iterate over column of A, row of B */ for (k_iter = 0; k_iter < bk; k_iter++) { int a_index, b_index; /* Check for non power of 2 matrices being complete */ if (k_block*bk + k_iter >= k) { break; } a_index = k_iter * bm + block_row; //printf("%d\n", a_index); b_index = block_col*k + (j_block*bn*k) + (k_block*bk) + k_iter; dotprod += page[a_index] * B[b_index]; } /* k_iter */ int c_index = block_col*m + j_block*bn*m + (block_row + i_block*bm); if (apply_beta) { C[c_index] = alpha*dotprod + beta * C[c_index]; } else { C[c_index] = alpha*dotprod + C[c_index]; } } /* block_row */ } /* block_col */ } } apply_beta = 0; } free(aPaged); //fprintf(stderr, "C=\n"); //print_matrix(m, n, C); #endif /* USE_BLOCKING */ #ifdef USE_TLB int row, col; int i, j; double* b2 = (double*)malloc(sizeof(double) * k * n); memcpy(b2, A, sizeof(double) * k * n); //Transpose A for(i = 0; i < k; i++) { for(j = i + 1; j < n; j++) { double tmp = b2[i + j * m]; b2[i + j * m] = b2[j + i * m]; b2[j + i * m] = tmp; } } /* Iterate over the columns of C */ for (col = 0; col < n; col++) { /* Iterate over the rows of C */ for (row = 0; row < m; row++) { int k_iter; double dotprod = 0.0; /* Accumulates the sum of the dot-product */ /* Iterate over column of A, row of B */ for (k_iter = 0; k_iter < k; k_iter++) { int a_index, b_index; a_index = (row * lda) + k_iter; /* Compute index of A element */ b_index = (col * ldb) + k_iter; /* Compute index of B element */ dotprod += b2[a_index] * B[b_index]; /* Compute product of A and B */ } /* k_iter */ int c_index = (col * ldc) + row; C[c_index] = (alpha * dotprod) + (beta * C[c_index]); } /* row */ } /* col */ free(b2); #endif /* USE_TLB */ #ifdef USE_OPEN_MP int row, col; # pragma omp parallel for private(col, row) /* Iterate over the columns of C */ for (col = 0; col < n; col++) { /* Iterate over the rows of C */ for (row = 0; row < m; row++) { int k_iter; double dotprod = 0.0; /* Accumulates the sum of the dot-product */ /* Iterate over column of A, row of B */ for (k_iter = 0; k_iter < k; k_iter++) { int a_index, b_index; a_index = (k_iter * lda) + row; /* Compute index of A element */ b_index = (col * ldb) + k_iter; /* Compute index of B element */ dotprod += A[a_index] * B[b_index]; /* Compute product of A and B */ } /* k_iter */ int c_index = (col * ldc) + row; C[c_index] = (alpha * dotprod) + (beta * C[c_index]); } /* row */ } /* col */ #endif /* USE_OPEN_MP */ #ifdef USE_MKL const char N = 'N'; dgemm(&N, &N, &m, &n, &k, &alpha, A, &lda, B, &ldb, &beta, C, &ldc); #endif #ifdef USE_ORIGINAL int row, col; /* Iterate over the columns of C */ for (col = 0; col < n; col++) { /* Iterate over the rows of C */ for (row = 0; row < m; row++) { int k_iter; double dotprod = 0.0; /* Accumulates the sum of the dot-product */ /* Iterate over column of A, row of B */ for (k_iter = 0; k_iter < k; k_iter++) { int a_index, b_index; a_index = (k_iter * lda) + row; /* Compute index of A element */ b_index = (col * ldb) + k_iter; /* Compute index of B element */ dotprod += A[a_index] * B[b_index]; /* Compute product of A and B */ } /* k_iter */ int c_index = (col * ldc) + row; C[c_index] = (alpha * dotprod) + (beta * C[c_index]); } /* row */ } /* col */ #endif }
C
/* Half-float conversion routines. Copyright (C) 2008-2022 Free Software Foundation, Inc. Contributed by CodeSourcery. This file is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. This file is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see <http://www.gnu.org/licenses/>. */ struct format { /* Number of bits. */ unsigned long long size; /* Exponent bias. */ unsigned long long bias; /* Exponent width in bits. */ unsigned long long exponent; /* Significand precision in explicitly stored bits. */ unsigned long long significand; }; static const struct format binary32 = { 32, /* size. */ 127, /* bias. */ 8, /* exponent. */ 23 /* significand. */ }; static const struct format binary64 = { 64, /* size. */ 1023, /* bias. */ 11, /* exponent. */ 52 /* significand. */ }; /* Function prototypes. */ unsigned short __gnu_f2h_ieee (unsigned int a); unsigned int __gnu_h2f_ieee (unsigned short a); unsigned short __gnu_f2h_alternative (unsigned int x); unsigned int __gnu_h2f_alternative (unsigned short a); unsigned short __gnu_d2h_ieee (unsigned long long a); unsigned short __gnu_d2h_alternative (unsigned long long x); static inline unsigned short __gnu_float2h_internal (const struct format* fmt, unsigned long long a, int ieee) { unsigned long long point = 1ULL << fmt->significand; unsigned short sign = (a >> (fmt->size - 16)) & 0x8000; int aexp; unsigned long long mantissa; unsigned long long mask; unsigned long long increment; /* Get the exponent and mantissa encodings. */ mantissa = a & (point - 1); mask = (1 << fmt->exponent) - 1; aexp = (a >> fmt->significand) & mask; /* Infinity, NaN and alternative format special case. */ if (((unsigned int) aexp) == mask) { if (!ieee) return sign; if (mantissa == 0) return sign | 0x7c00; /* Infinity. */ /* Remaining cases are NaNs. Convert SNaN to QNaN. */ return sign | 0x7e00 | (mantissa >> (fmt->significand - 10)); } /* Zero. */ if (aexp == 0 && mantissa == 0) return sign; /* Construct the exponent and mantissa. */ aexp -= fmt->bias; /* Decimal point is immediately after the significand. */ mantissa |= point; if (aexp < -14) { mask = point | (point - 1); /* Minimum exponent for half-precision is 2^-24. */ if (aexp >= -25) mask >>= 25 + aexp; } else mask = (point - 1) >> 10; /* Round. */ if (mantissa & mask) { increment = (mask + 1) >> 1; if ((mantissa & mask) == increment) increment = mantissa & (increment << 1); mantissa += increment; if (mantissa >= (point << 1)) { mantissa >>= 1; aexp++; } } if (ieee) { if (aexp > 15) return sign | 0x7c00; } else { if (aexp > 16) return sign | 0x7fff; } if (aexp < -24) return sign; if (aexp < -14) { mantissa >>= -14 - aexp; aexp = -14; } /* Encode the final 16-bit floating-point value. This is formed of the sign bit, the bias-adjusted exponent, and the calculated mantissa, with the following caveats: 1. The mantissa calculated after rounding could have a leading 1. To compensate for this, subtract one from the exponent bias (15) before adding it to the calculated exponent. 2. When we were calculating rounding, we left the mantissa with the number of bits of the source operand, it needs reduced to ten bits (+1 for the afforementioned leading 1) by shifting right by the number of bits in the source mantissa - 10. 3. To ensure the leading 1 in the mantissa is applied to the exponent we need to add the mantissa rather than apply an arithmetic "or" to it. */ return sign | (((aexp + 14) << 10) + (mantissa >> (fmt->significand - 10))); } static inline unsigned short __gnu_f2h_internal (unsigned int a, int ieee) { return __gnu_float2h_internal (&binary32, (unsigned long long) a, ieee); } static inline unsigned short __gnu_d2h_internal (unsigned long long a, int ieee) { return __gnu_float2h_internal (&binary64, a, ieee); } static inline unsigned int __gnu_h2f_internal(unsigned short a, int ieee) { unsigned int sign = (unsigned int)(a & 0x8000) << 16; int aexp = (a >> 10) & 0x1f; unsigned int mantissa = a & 0x3ff; if (aexp == 0x1f && ieee) return sign | 0x7f800000 | (mantissa << 13); if (aexp == 0) { int shift; if (mantissa == 0) return sign; shift = __builtin_clz(mantissa) - 21; mantissa <<= shift; aexp = -shift; } return sign | (((aexp + 0x70) << 23) + (mantissa << 13)); } unsigned short __gnu_f2h_ieee(unsigned int a) { return __gnu_f2h_internal(a, 1); } unsigned int __gnu_h2f_ieee(unsigned short a) { return __gnu_h2f_internal(a, 1); } unsigned short __gnu_f2h_alternative(unsigned int x) { return __gnu_f2h_internal(x, 0); } unsigned int __gnu_h2f_alternative(unsigned short a) { return __gnu_h2f_internal(a, 0); } unsigned short __gnu_d2h_ieee (unsigned long long a) { return __gnu_d2h_internal (a, 1); } unsigned short __gnu_d2h_alternative (unsigned long long x) { return __gnu_d2h_internal (x, 0); }
C
#ifndef __SHORTEST_PATH_H #define __SHORTEST_PATH_H #define INFINITE 999 #define ERROR_COORD 0.75 #include <stdio.h> #include <stdlib.h> #include <math.h> #include "map_common.h" /** @brief Return the index of a point in the map, according to its coordinates Note that there is a margin error here if the coordinates don't correspond exactly (see ERROR_COORD) @float other_x Searched point x coordinate @float other_y Searched point y coordinate @return Index of the searched point @return -1 if the point is not found in the map */ int find_point (const graph_t *map, float other_x, float other_y); /** @brief Find the shortest path beteween two points, according to a map @param current_x Start point x coordinate @param current_y Start point y coordinate @param dest_x Destination point x coordinate @param dest_y Destination point y coordinate @param map The map @return The shortest path (a list of node) FIXME: - we shouldn't return a double pointer, rather return a pointer and a size - the pointed pointers (yes) are pointers to data from the graph, not copies. This means that we cannot free the graph until the end of the program. */ node_t **dijkstra (float current_x, float current_y, float dest_x, float dest_y, graph_t *map); #endif
C
#ifndef __WEB_STRUCTURE_H__ #define __WEB_STRUCTURE_H__ #include "web_constant.h" struct ProtocolHeader { uint16_t magic; uint16_t cmd; uint32_t data_length; ProtocolHeader() { magic = kProtocolMagic; cmd = CT_MIN; data_length = 0; } void CopyData(ProtocolHeader *self, const ProtocolHeader *other) { self->magic = other->magic; self->cmd = other->cmd; self->data_length = other->data_length; } ProtocolHeader(const ProtocolHeader &other) { CopyData(this, &other); } const ProtocolHeader &operator =(const ProtocolHeader &other) { CopyData(this, &other); return (*this); } }; #endif
C
/* To Compile: * 'mex OP_numint_gausslaguerre.c' (on a machine with gsl installed) */ #include <math.h> #include "mex.h" #include <stdio.h> #include <stdlib.h> #include <gsl/gsl_math.h> #define EPS 3.0e-14 #define MAXIT 10 int n; double alf; void Gaulag0(double *,double *,double , int ); void Gaulag0(double *x, double *w, double alf, int n) { int i, its, j; float ai; double p1, p2, p3, pp, z, z0, z1; for (i=1;i<=n;i++) { if (i==1) { z = (1.0+alf)*(3.0+0.92*alf)/(1.0+2.4*n+1.8*alf); } else if (i==2) { z += (15.0+6.25*alf)/(1.0+0.9*alf+2.5*n); } else { ai = i-2; z0 = ((1.0+2.55*ai)/(1.9*ai) + 1.26*ai*alf/(1.0+3.5*ai)); z += z0*(z-x[i-3])/(1.0+.3*alf); } for (its=1;its<=MAXIT;its++) { p1 = 1.0; p2 = 0.0; for (j=1;j<=n;j++) { p3 = p2; p2 = p1; p1 = ( (2*j-1+alf-z)*p2 - (j-1+alf)*p3 )/j; } pp = (n*p1-(n+alf)*p2)/z; z1 = z; z = z1-p1/pp; if (fabs(z-z1) <= EPS) break; } x[i-1] = z; w[i-1] = 1/pp/p2; } return; } void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) { /*[x,w]=OP_numint_gausslaguerre(alf,n)*/ double *x, *w; /*inputs*/ alf = *mxGetPr(prhs[0]); n = *mxGetPr(prhs[1]); /*outputs*/ plhs[0] = mxCreateDoubleMatrix(n,1,mxREAL); plhs[1] = mxCreateDoubleMatrix(n,1,mxREAL); x = mxGetPr(plhs[0]); w = mxGetPr(plhs[1]); /*calc the roots and weights*/ Gaulag0(x ,w, alf, n); return; }
C
/* JTSK-32011 a3_p8.c Samundra karki [email protected] */ #include <stdio.h> int main(){ char ch,ch1; int n; scanf("%c",&ch); scanf("%d",&n); if ((n>32 || n<7)){ printf("Input is invalid\n"); return 1; } int i; for (i=1; i<=n; i++){ ch1 = ch - i; if( !(ch1>=97 && ch1<=122) ){ printf("\n"); return 1; } if(i!=0) printf(", "); printf("%c", ch1); } return 0; }
C
/* * File: PrintErrno.c * Description: View message associated with errno, * or list all errno and their messages, * an alternative of program perror. * Author: Wang Qian * Create Date: 2016-08-15 * Last Modified Date: 2016-08-16 */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> void PrintErrorMessage(int errnum); void ShowHelp(); void ShowAllErrorMessages(); // 1: success, 0: failure. int ConvertToInteger(const char *s, int *value); int main(int argc, char **argv) { if (argc == 1) { ShowHelp(); return 0; } if (argc == 2 && strncmp(argv[1], "-help", 5) == 0) { ShowHelp(); return 0; } if (argc == 2 && strncmp(argv[1], "-list", 5) == 0) { ShowAllErrorMessages(); return 0; } fprintf(stdout, "ERROR\tMESSAGE\n"); fprintf(stdout, "-----------------------\n"); int i; int value; for (i = 1; i < argc; ++i) { if (!ConvertToInteger(argv[i], &value)) { continue; } PrintErrorMessage (value); } fprintf(stdout, "-----------------------\n"); return 0; } void PrintErrorMessage(int errnum) { const char *message = strerror(errnum); fprintf(stdout, "%d\t%s\n", errnum, message); } void ShowHelp() { const char *message = "usage:\n" "\t./Errno [option]\n" "\t./Errno errnum1, errnum2, ...\n" "option:\n" "\t-help: show this message.\n" "\t-list: list all errors.\n"; fprintf(stdout, "%s\n", message); } void ShowAllErrorMessages() { fprintf(stdout, "ERROR\tMESSAGE\n"); fprintf(stdout, "-----------------------\n"); int i; const char *message; for (i = 0; i < sys_nerr; i++) { message = sys_errlist[i]; if (message != NULL) { fprintf(stdout, "%d\t%s\n", i, message); } } fprintf(stdout, "-----------------------\n"); } int ConvertToInteger(const char *s, int *value) { int val = 0; int ret = 0; char buffer[256]; val = atoi(s); int len = snprintf(buffer, 256, "%d", val); if (strlen(s) == len) { ret = 1; } if (value != NULL) { *value = val; } return ret; }
C
// Q1. Define your own iterative functions for // (using array notation as well as exclusively using pointers) // i) finding a substring in a main string // j) Whether a string starts or ends with a particular sub string #include<stdio.h> int str_len(char *); void str_cpy(char *,char *); int str_cmp(char *,char *); void str_rev(char *,char *); void str_concat(char *,char *, char *); void str_ch_occ(char *,char ); int str_first_occ(char *,char ); int occ_num(char *,char ); void main() { char str[50]; char str1[50]; char str_cat[100]; char user_ch=0; int length=0; printf("Enter a string \n"); fgets(str,50,stdin); length=str_len(str); printf("string Length=%d\n",length); str_cpy( str1,str); printf("string copy=%s\n",str1); printf("string cmp=%d\n",str_cmp(str1,str)); str_rev(str1,str); printf("string Rev=%s\n",str1); str_concat(str,str1,str_cat); printf("Concat string=%s\n",str_cat); printf("Enter a char to see occurance of it\n"); scanf("%c",&user_ch); str_ch_occ(str,user_ch); printf("First Ch occ.=%d\n",str_first_occ(str,user_ch) ); printf("Number of occ.=%d\n",occ_num(str,user_ch) ); } int str_len(char *str) { int flag=0; while(*str!='\0') { ++flag; str++; } return flag; } void str_cpy(char *str_d,char *str_s) { while(*str_s!='\0') { (*str_d)=(*str_s); (str_s)++; (str_d)++; } *(str_d)='\0'; } int str_cmp(char *str_d,char *str_s) { int flag=0; while(*str_s!='\0') { if( (*str_d)!=(*str_s)) { flag++; } (str_s)++; (str_d)++; } if(flag!=0) { return 0; } return 1; } void str_rev(char *str_d,char *str_s) { int len=0; len=str_len( str_s); while(*str_s != '\0') { str_s++; } str_s--; int i=0; for(i=0;i<len;i++) { str_d[i]= *(str_s); str_s--; } str_d[i]='\0'; } void str_concat(char *str_d,char *str_s, char *str_cat) { int len_s=str_len(str_s); int len_d=str_len(str_d); len_s=len_s+len_d; while(*str_d !='\0') { *str_cat = *str_d; str_cat++; str_d++; } while(*str_s !='\0') { *str_cat = *str_s; str_cat++; str_s++; } *str_cat='\0'; } void str_ch_occ(char *str_s,char user_ch) { int flag=1; while(*str_s!='\0') { if(user_ch==*str_s) { printf("char at Position=%d\n",flag); } flag++; str_s++; } } int str_first_occ(char *str_s,char user_ch) { int flag=1; while(*str_s!='\0') { if(user_ch==*str_s) { return flag; } flag++; str_s++; } return 0; } int occ_num(char *str_s,char user_ch ) { int flag=0; while(*str_s!='\0') { if(user_ch==*str_s) { flag++; } str_s++; } return flag; }
C
#include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define EXT_LEN 3 #define EXTENSION "808" char* pwdextend(char* a); int main(void) { char *p2, *p1; p1 = pwdextend("password"); p2 = pwdextend("hackable"); assert(strcmp(p1, "password808") == 0); assert(strcmp(p2, "hackable808") == 0); free(p1); free(p2); return 0; } char* pwdextend(char* a) { int len = strlen(a); char* ptr; /* Allocate memory for existing string, extension and null terminator */ ptr = (char*)malloc((len + EXT_LEN + 1) * sizeof(char)); if (ptr == NULL) { fprintf(stderr, "Memory allocation error\n"); exit(EXIT_FAILURE); } strcpy(ptr, a); strcpy(ptr + len, EXTENSION); return ptr; }
C
#include "stack_machine.h" typedef struct { char *str;exp *e ;exp *memo; memo_s set; } memo_entry; static memo_entry *memos;static long memo_no; static void memo_set(Global *g,char *str,exp *e ,exp *memo, memo_s set){int i; for(i=0;i<memo_no;i++){ if (memos[i].str==str && memos[i].e==e && memos[i].memo==memo) return ; } if (!((memo_no&(memo_no-1)))) memos=realloc(memos,sizeof(memo_entry)*2*(memo_no+1)); if (!memos) exit(42); memos[memo_no].str=str;memos[memo_no].e=e; memos[memo_no].memo=memo; memos[memo_no].set=set;memo_no++; } static memo_s memo_get(Global *g,char *str,exp *e, exp *memo){int i; for(i=0;i<memo_no;i++){ if (memos[i].str==str && memos[i].e==e && memos[i].memo==memo) return memos[i].set; } memo_s not_present; not_present.returned=0; not_present.state=-1; return not_present; } static void *head(char *str){ return (void*) (*str); } static void *advance(char *str){ return str+1; } void use_memo(Global *g){ memos=NULL;memo_no=0; g->advance=advance; g->head=head; g->memo_set=(pfn) memo_set; g->memo_get= memo_get; } void free_memo(Global *g){ free(memos); }
C
#include <subr.h> #include <cpu/p5/io.h> /* * This file is for setting up the SMC Super IO chip. * * This file contains some hard coded mappings for IRQs which may * work for most boards but is really board specific. A * configuration mechanism is needed. * * I have only implemented the UART features that I needed at * the time plus enableing EPP mode to get interrupts that can * be shared. Other features for floppies and parallel ports * can be added by others as needed. * * -Tyson Sawyer [email protected] * * Sharing interrupts between two SMC chips doesn't work for me. -tds * modified by RGM for the new superio setup. * we need to finish this up but we have to get other parts of the * dell done first. */ static int smc_configuration_state(struct superio *s, int state) { unsigned char addr; addr = s->port; if (state) { outb(0x55, addr); return(0); } else { outb(0xAA, addr); return(0); } return(-1); } static int smc_write(struct superio *s, unsigned char data, unsigned char index) { unsigned char addr; addr = s->port; outb(index, addr); outb(data, addr+1); return(0); } static int smc_read(struct superio *s, unsigned char index, unsigned char *data) { unsigned char addr; addr = s->port; if ((addr!=0x370) && (addr!=0x3f0)) return(-1); outb(index, addr); *data = inb(addr+1); return(0); } static int smc_uart_setup(struct superio *s, int addr1, int irq1, int addr2, int irq2) { unsigned char addr = s->port; int rv; unsigned char int1, int2; unsigned char data; /* * Warning: * Board specifc mapping of IRQs here. * A configuration mechanism is needed. */ switch (irq1) { case 3: int1 = 1; break; case 4: int1 = 2; break; case 5: int1 = 3; break; case 6: int1 = 4; break; case 7: int1 = 5; break; case 10: int1 = 6; break; case 11: int1 = 8; break; default: int1 = 0; } switch (irq2) { case 3: int2 = 1; break; case 4: int2 = 2; break; case 5: int2 = 3; break; case 6: int2 = 4; break; case 7: int2 = 5; break; case 10: int2 = 6; break; case 11: int2 = 8; break; default: int2 = 0; } if (int1 == int2) { int2 = 0x0f; } rv = smc_configuration_state(addr, 1); if (rv) return(rv); rv = smc_write(addr, (addr1>>2) & 0xfe, 0x24); if (rv) return(rv); rv = smc_write(addr, (addr2>>2) & 0xfe, 0x25); if (rv) return(rv); rv = smc_write(addr, (int1<<4) | int2, 0x28); if (rv) return(rv); /* Enable INTB output */ if ((int1==2) || (int2==2)) { rv = smc_read(addr, 0x03, &data); if (rv) return(rv); rv = smc_write(addr, data | 0x84, 0x03); if (rv) return(rv); } rv = smc_configuration_state(addr, 0); return(rv); } static int smc_pp_setup(struct superio *s, int pp_addr, int mode) { unsigned char addr = s->port; int rv; unsigned char data; rv = smc_configuration_state(addr, 1); if (rv) return(rv); rv = smc_read(addr, 0x04, &data); if (rv) return(rv); data = (data & (~0x03)) | (mode & 0x03); rv = smc_write(addr, data, 0x04); if (rv) return(rv); rv = smc_read(addr, 0x01, &data); if (rv) return(rv); data = data & (~0x08); rv = smc_write(addr, data, 0x01); if (rv) return(rv); rv = smc_write(addr, (pp_addr>>2) & 0xff, 0x23); if (rv) return(rv); rv = smc_configuration_state(addr, 0); return(rv); } static int smc_validbit(struct superio *s, int valid) { unsigned short addr = s->port; int rv; unsigned char data; if ((addr!=0x370) && (addr!=0x3f0)) return(-1); rv = smc_configuration_state(addr, 1); if (rv) return(rv); rv = smc_read(addr, 0x00, &data); if (rv) return(rv); if (valid) { data = data | 0x80; } else { data = data & (~0x80); } rv = smc_write(addr, data, 0x00); if (rv) return(rv); rv = smc_configuration_state(addr, 0); return(rv); } static void finishup(struct superio *s) { #if 0 // fix me later enter_pnp(s); // don't fool with IDE just yet ... // if (s->floppy) // enable_floppy(s); if (s->com1.enable) enable_com(s, PNP_COM1_DEVICE); if (s->com2.enable) enable_com(s, PNP_COM2_DEVICE); if (s->lpt) enable_lpt(s); exit_pnp(s); #endif } struct superio_control superio_sis_950_control = { (void *)0, (void *)0, finishup, 0x2e, "SiS 950" };
C
/******************************************************************************* ** File: vc0706_mux.c ** ** Purpose: ** This file is main hdr file for the VC0706 application. ** ** *******************************************************************************/ #include "vc0706_mux.h" int mux_init(mux_t *mux, int select_pin) { if(wiringPiSetup() == -1) { OS_printf("MUX: wiringPiSetup() Failed!\n"); return -1; } mux->mux_select_pin = select_pin; pinMode(select_pin, OUTPUT); int ret = mux_select(mux, 0); // initialize low return ret; } int mux_select(mux_t *mux, int select) { if(select == 1) { digitalWrite(mux->mux_select_pin, HIGH); mux->mux_state = 1; return 0; } else if(select == 0) { digitalWrite(mux->mux_select_pin, LOW); mux->mux_state = 0; return 0; } else { return -1; } } int mux_switch(mux_t *mux) { // swap selection if(mux->mux_state == 0) return mux_select(mux, 1); else return mux_select(mux, 0); }
C
#include "holberton.h" #include <stdlib.h> /** *alloc_grid - creates 2d array of integers *@width: width *@height:height *Return: Always */ int **alloc_grid(int width, int height) { int **array; int loop; int loop1; int loop2; if (width <= 0 || height <= 0) { return (NULL); } array = (int **) malloc(sizeof(int *) * height); if (array == NULL) { free(array); return (NULL); } for (loop = 0; loop < height; loop++) { array[loop] = (int *) malloc(sizeof(int) * width); if (array[loop] == NULL) { while (loop >= 0) { free(array[loop]); loop--; } free(array); return (NULL); } } for (loop1 = 0; loop1 < height; loop1++) { for (loop2 = 0; loop2 < width; loop2++) { array[loop1][loop2] = 0; } } return (array); }
C
#include<stdio.h> #include<stdlib.h> #include<stdbool.h> int mutex=1, n, full=0, empty, buffer[25], temp=0, f=-1, r=-1; void wait(int *s) { (*s)--; } void signal(int *s) { (*s)++; } void producer() { int x; wait(&mutex); signal(&full); wait(&empty); // produce an item printf("Enter the item to be produced: "); scanf("%d", &x); // place the item in buffer if (f==-1) f++; r = (r+1)%n; buffer[r] = x; printf("Produced item: %d\n\n", x); signal(&mutex); } void consumer() { wait(&mutex); wait(&full); signal(&empty); //remove an item from buffer int x = buffer[f]; if (f==r) f=r=-1; else f = (f+1)%n; signal(&mutex); // consume the item printf("Consumed item: %d\n\n", x); } void main() { int ch; printf("Enter the size of the buffer: "); scanf("%d", &n); empty=n; while (true) { printf("1. Producer. \n2. Consumer. \n3. Exit. \nENTER CHOICE: "); scanf("%d", &ch); switch(ch) { case 1: if (empty) producer(); else printf("Buffer full!\n\n"); break; case 2: if (full) consumer(); else printf("Buffer empty!\n\n"); break; default: exit(0); } } }
C
#ifndef CV4_DU_H #define CV4_DU_H #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include <stdbool.h> char* trim(char* str){ char* r = str+(strlen(str)-1); // r = koniec stringu while (isblank(*r)){ // orezanie od konca r--; } *(r+1)="\0"; // +1 pre skočenie z písmena na ukončenie stringu while (isblank(*str)){ // orezanie od začiatku str++; } return str; } char* caesar(char* src, char* dest, int shift){ int size = strlen(src); while (*src != '\0'){ *dest = *src+shift; src++;dest++; } return dest-size; } char* strDel(char* str, int pos, int count){ int size = strlen(str)-count; str=str+pos; while(*(str+count) != '\0'){ *(str) = *(str+count); str++; } *(str) = '\0'; return str - size; } char* strIns(char* dest, int pos, char *src){ char* first = dest; // ukazovateľ na prvý prvok v poli int size = strlen(src); // veľkosť pola src dest=dest+pos; // posunutie sa na pozíciu v dest kde sa začnú pridávať prvky z pola src while(*src != '\0'){ // kým neprejde sa celé pole src *(dest+size) = *dest; // pridanie do dest zvyšné znaky z dest ktoré sú za pozíciou pos ak nejaké sú *dest = *src; // pridanie do dest znak z src dest++;src++; // posunutie ukazovatela na dest a src } return first; // návrat na prvú pozíciu v poli dest } int posOfPattern(char* src, char* pattern){ int pos = 0; char* first = pattern; int size = strlen(pattern); int s = size; while(*src != '\0'){ if(size == 0) { return pos-s;} if(*src == *pattern) { size--; pattern++; } else { size = strlen(pattern); pattern=first;} src++;pos++; } if(size == 0) { return pos-s;} return -1; } char* substitute(char* src, char* pattern, char* sub){ char* first = src; int pos = posOfPattern(src,pattern); int size = strlen(sub); src = first+pos; while(*src != '\0'){ if(*sub == '\0'){ return first;} *src = *sub; sub++;src++; } return first; } _Bool isPalindrome(char* str) { char* left=str; char* right=str+strlen(str)-1; while (*left != '\0'){ if ( *left != *right ) { return false;} left++; right--; } return true; } char* reverse(char* str){ char* left=str; char* right=str+strlen(str) -1; while (left != right){ char tmp= *left; *left=*right; *right=tmp; left++; right--; } return str; } char* toLowerStr(char* str){ char* f = str; while (*f != '\0'){ *f = tolower(*f); f++; } return str; } char* toUpperStr(char* str){ char* f = str; while (*f != '\0'){ *f = toupper(*f); f++; } return str; } #endif //CV4_DU_H
C
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ bool isEqual(struct TreeNode* s,struct TreeNode* t){ if(s==NULL||t==NULL) // when there is one tree is NULL return s==t; // if both tree is NULL, return true if(s->val==t->val) return isEqual(s->left,t->left) && isEqual(s->right,t->right); // check all the root return false; } bool isSubtree(struct TreeNode* s, struct TreeNode* t) { if(s==NULL) return false; // after checking all the tree if not find ,return false if(isEqual(s,t)==false) return(isSubtree(s->left,t)||isSubtree(s->right,t)); // check all the tree return true; // if equal return true }
C
//Quick Sort #include<stdio.h> #include<conio.h> int partition(int a[],int left,int right) { int i=left,j=right,x=a[left]; while(a[i]<=x && i<left) i++; while(a[j]>x) j--; if(i<j) { t=a[i]; a[i]=a[j]; a[j]=t; } a[left]=a[j]; a[j]=x; return j; } void quickSort(int a[],int left, int right){ if(right-left <= 0){ return; }else { int pivot = intArray[right]; int partitionPoint = partition(left, right, pivot); quickSort(a,left,partitionPoint-1); quickSort(a,partitionPoint+1,right); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* convers_c.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gdu-bus- <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/09/21 13:46:18 by gdu-bus- #+# #+# */ /* Updated: 2020/09/21 13:52:22 by gdu-bus- ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" static void flag_cond_c(t_f *f, t_put *put) { init_put(put); if (f->width > 1) put->width = f->width - 1; } static void convers_percent(t_f *f, t_put *put, char c) { if (f->zero && !f->minus) { while (put->width > 0) { ft_write('0', put); put->width--; } ft_write(c, put); } } void convers_c(va_list arg, t_f *f, t_put *put, int i) { char c; flag_cond_c(f, put); if (i) c = '%'; if (i && f->zero && !f->minus) { convers_percent(f, put, c); return ; } if (!i) c = va_arg(arg, int); if (f->minus) { ft_write(c, put); while (put->width--) ft_write(' ', put); } else if (!f->minus) { while (put->width--) ft_write(' ', put); ft_write(c, put); } }
C
#include <acirc.h> #include <stdlib.h> #include <gmp.h> int test(const char *fname) { acirc_t *c; int err = 1; printf("\n* %s *\n\n", fname); if ((c = acirc_new(fname, false, false)) == NULL) return err; printf("ninputs: %lu\n", acirc_ninputs(c)); printf("nconsts: %lu\n", acirc_nconsts(c)); printf("noutputs: %lu\n", acirc_noutputs(c)); { unsigned long count; count = acirc_ngates(c); printf("ngates: %lu\n", count); } { unsigned long count; count = acirc_nmuls(c); printf("nmuls: %lu\n", count); } { unsigned long max; max = acirc_max_degree(c); printf("max degree: %lu\n", max); } { unsigned long depth; depth = acirc_max_depth(c); printf("max depth: %lu\n", depth); } err = acirc_test(c); { mpz_t **xs, modulus, **outputs; mpz_init_set_ui(modulus, 2377000); xs = calloc(acirc_ninputs(c), sizeof xs[0]); printf("inputs: "); for (size_t i = 0; i < acirc_ninputs(c); ++i) { xs[i] = calloc(1, sizeof xs[i][0]); mpz_init_set_ui(*xs[i], 0); gmp_printf("%Zd ", *xs[i]); } printf("\n"); outputs = acirc_eval_mpz(c, xs, NULL, modulus); if (outputs) { printf("outputs: "); for (size_t i = 0; i < acirc_noutputs(c); ++i) { gmp_printf("%Zd ", *outputs[i]); mpz_clear(*outputs[i]); free(outputs[i]); } printf("\n"); } for (size_t i = 0; i < acirc_ninputs(c); ++i) { mpz_clear(*xs[i]); free(xs[i]); } free(xs); free(outputs); mpz_clear(modulus); } acirc_free(c); return err; } int main(int argc, char **argv) { (void) argc; (void) argv; int err = 0; /* err |= test("t/circuits/ggm_1_4.dsl.acirc"); */ /* err |= test("t/circuits/ggm_1_64.dsl.acirc"); */ err |= test("t/circuits/ggm_3_128.dsl.acirc"); return err; }
C
#include "inttypes.h" #include "cpu.h" #include "ecran.h" #include "stdio.h" #include "stdbool.h" #include "segment.h" #include "time_print.h" #include "processes.h" #define QUARTZ 0x1234DD #define CLOCKFREQ 50 static int compteur = 0; void tic_PIT() { compteur++; char ch[9]; outb(0x20, 0x20); snprintf(ch, 9, "%02d:%02d:%02d", (compteur/60)/60, (compteur/60)%60, compteur%60); masque_IRQ(0, false); print_right(ch, 8); ordonnance(); } void set_timer(){ outb(0x34, 0x43); outb((QUARTZ / CLOCKFREQ) % 256, 0x40); } void init_traitant_IT(int32_t num_IT, void (*traitant)(void)) { uint32_t *vect_int = (uint32_t *)((void *)0x1000 + 32*8); // premier mot *vect_int = (KERNEL_CS<<16) + ((uint32_t)traitant & 0x0000ffff); //deuxième mot // autre notation possible *(vect_int+1) *(uint32_t *)((void *)vect_int+4) = ((uint32_t)traitant&0xffff0000) + 0x8E00; } void masque_IRQ(uint32_t num_IRQ, bool masque) { uint32_t val_act = inb(0x21); uint32_t operateur = 0; /* if (masque) { val_act = val_act | (0b1<<num_IRQ); } else{ // permet de récuếrer les bits de 7 à num_IRQ uint32_t pre_IRQ = val_act>>(num_IRQ+1); uint32_t post_IRQ = (val_act&)>>(8-num_IRQ); val_act = post_IRQ | (masque<<num_IRQ) | (pre_IRQ<<(num_IRQ+1)); }*/ if (masque) { for(int i = 7; i>=0; i--){ if(i == num_IRQ){ operateur = (operateur<<1)+masque; } else{ operateur = (operateur<<1)+0b0; } } val_act = val_act|operateur; } else { for(int i = 7; i>=0; i--){ if(i == num_IRQ){ operateur = (operateur<<1)+0b0; } else{ operateur = (operateur<<1)+0b1; } } val_act = val_act&operateur; } outb(val_act, 0x21); } int get_compteur(){ return compteur; }
C
#define SUCCESS 0 #define INVALID_NULL_POINTER -1 #define OUT_OF_RANGE -2 typedef struct TStackInt TStackInt; TStackInt *stack_createInt(int max); //Cria a pilha int stack_freeInt(TStackInt *st); //Libera a pilha int stack_pushInt(TStackInt *st, int a); //Insere na pilha (por ser um vetor, insere na ultima posição) int stack_popInt(TStackInt *st); //Remove um elemento (por ser um vetor, remove na ultima posição) int stack_topInt(TStackInt *st, int *a); //Retorna o elemento que esta no topo da pilha int stack_sizeInt(TStackInt *st); //Tamanho da pilha int stack_emptyInt(TStackInt *st); //Retorna 0 se a pilha esta vazia e retorna 1 caso contrario
C
/* The MIT License (MIT) Copyright (c) 2015 Terence Parr, Hanzhou Shi, Shuai Yuan, Yuanyuan Zhang Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdio.h> #include <stdlib.h> #include "merging.h" #include "cunit.h" const size_t HEAP_SIZE = 2000; extern void heap_shutdown(); Heap_Info verify_heap() { Heap_Info info = get_heap_info(); assert_equal(info.heap_size, HEAP_SIZE); assert_equal(info.heap_size, info.busy_size+info.free_size); return info; } static void setup() { heap_init(HEAP_SIZE); } static void teardown() { verify_heap(); heap_shutdown(); } void malloc0() { void *p = malloc(0); assert_addr_not_equal(p, NULL); assert_equal(chunksize(p), MIN_CHUNK_SIZE); } void malloc1() { void *p = malloc(1); assert_addr_not_equal(p, NULL); assert_equal(chunksize(p), MIN_CHUNK_SIZE); } void malloc_word_size() { void *p = malloc(sizeof(void *)); assert_addr_not_equal(p, NULL); assert_equal(chunksize(p), MIN_CHUNK_SIZE); } void malloc_2x_word_size() { void *p = malloc(2 * sizeof(void *)); assert_addr_not_equal(p, NULL); assert_equal(chunksize(p), 3 * sizeof(void *)); // 2 words + rounded up size field } void one_malloc() { void *p = malloc(100); // should split heap into two chunks assert_addr_not_equal(p, NULL); Free_Header *freelist = get_freelist(); Busy_Header *heap = get_heap_base(); assert_addr_not_equal(freelist, heap); // check 1st chunk assert_equal(p, heap); assert_equal(chunksize(p), request2size(100)); // check 2nd chunk assert_equal(freelist->size, HEAP_SIZE-request2size(100)); assert_addr_equal(freelist->next, NULL); Heap_Info info = verify_heap(); assert_equal(info.busy, 1); assert_equal(info.busy_size, request2size(100)); assert_equal(info.free, 1); assert_equal(info.free_size, HEAP_SIZE - request2size(100)); } void two_malloc() { one_malloc(); // split heap into two chunks and test for sanity. void *p0 = get_heap_base(); // should be first alloc chunk Free_Header *freelist0 = get_freelist(); Busy_Header *p = malloc(200); // now split sole free chunk into two chunks assert_addr_not_equal(p, NULL); // check 2nd alloc chunk assert_equal(p, freelist0); // should return previous free chunk assert_equal(chunksize(p), request2size(200)); // check remaining free chunk Free_Header *freelist1 = get_freelist(); assert_addr_not_equal(freelist0, freelist1); assert_addr_not_equal(freelist0, get_heap_base()); assert_equal(chunksize(freelist1), HEAP_SIZE-request2size(100)-request2size(200)); assert_equal(chunksize(p0)+chunksize(p)+chunksize(freelist1), HEAP_SIZE); assert_addr_equal(freelist1->next, NULL); Heap_Info info = verify_heap(); assert_equal(info.busy, 2); assert_equal(info.busy_size, request2size(100) + request2size(200)); assert_equal(info.free, 1); assert_equal(info.free_size, HEAP_SIZE - request2size(100) - request2size(200)); } void malloc_then_free() { one_malloc(); void *p = get_heap_base(); // should be allocated chunk Free_Header *freelist0 = get_freelist(); free(p); Free_Header *freelist1 = get_freelist(); // allocated chunk is freed and becomes head of new freelist assert_addr_equal(freelist1, p); assert_addr_equal(freelist1, get_heap_base()); assert_addr_not_equal(freelist0, freelist1); assert_equal(chunksize(freelist1) + chunksize(freelist1->next), HEAP_SIZE); Heap_Info info = verify_heap(); assert_equal(info.busy, 0); assert_equal(info.busy_size, 0); assert_equal(info.free, 1); // 1 free chunk after merging assert_equal(info.free_size, HEAP_SIZE); } void free_NULL() { free(NULL); // don't crash } char buf[] = "hi"; // used by free_random void free_random() { void *heap0 = get_heap_base(); Free_Header *freelist0 = get_freelist(); free(buf); // try to free a valid but non-heap data address void *heap1 = get_heap_base(); Free_Header *freelist1 = get_freelist(); assert_addr_equal(heap1, heap0); assert_addr_equal(freelist1, freelist0); } void free_stale() { malloc_then_free(); Free_Header *freelist = get_freelist(); free(freelist); // NOT ok; freeing something already free'd assert_addr_not_equal(freelist, freelist->next); // make sure we didn't create cycle by freeing twice } //three consecutive chunks allocated void three_malloc(){ void *p = get_heap_base(); Busy_Header *b_1 = malloc(100); assert_addr_equal(b_1, p); //b_1 is at the start of heap assert_equal(chunksize(b_1), request2size(100)); Busy_Header *b_2 = malloc(200); Busy_Header *b1_next = find_next(b_1); assert_addr_equal(b1_next,b_2); //b_2 is after b_1 assert_equal(chunksize(b_2), request2size(200)); Busy_Header *b_3 = malloc(300); assert_addr_equal(find_next(b_2),b_3); //b_3 is after b_2 assert_equal(chunksize(b_3), request2size(300)); Heap_Info info = verify_heap(); assert_equal(info.busy, 3); assert_equal(info.free, 1); assert_equal(info.free_size, HEAP_SIZE - info.busy_size); } //free the chunk in the middle of three busy chunks void free_without_merging() { three_malloc(); Busy_Header *b_1 = get_heap_base(); Busy_Header *b_2 = find_next(b_1); Busy_Header *b_3 = find_next(b_2); Free_Header *freelist0 = get_freelist(); //get the head of freelist, which is at the end of allocated chunks assert_addr_equal(freelist0, find_next(b_3)); free(b_2); //free the chunk in the middle, which becomes the head of the new freelist Free_Header *freelist1 = get_freelist(); //get the new freelist assert_addr_not_equal(freelist1, b_1); assert_addr_not_equal(freelist0, freelist1); assert_addr_equal(freelist1, b_2); assert_addr_equal(freelist1->next, freelist0); //two free chunks in the list assert_equal(chunksize(b_1) + chunksize(b_2) + chunksize(b_3) + chunksize(freelist0), HEAP_SIZE); assert_equal(chunksize(b_1) + chunksize(b_3) + chunksize(freelist1) + chunksize(freelist0), HEAP_SIZE); Heap_Info info = verify_heap(); assert_equal(info.busy, 2); assert_equal(info.busy_size, chunksize(b_1) + chunksize(b_3)); assert_equal(info.free, 2); // 2 free chunks not next to each other assert_equal(info.free_size, chunksize(freelist1) + chunksize(freelist1->next)); } //free the middle chunk, than the first chunk, leading to a merge with the head of the list void merge_with_head() { free_without_merging(); //free middle chunk first void *p = get_heap_base(); // the first allocated chunk on the heap Free_Header *freelist0 = get_freelist(); //get the head of freelist, which is the middle chunk assert_addr_not_equal(freelist0, p); Free_Header *next = freelist0->next; free(p); //free the chunk before head of the free list, need to merge Free_Header *freelist1 = get_freelist(); //get the new freelist assert_addr_equal(freelist1, p); // new head is at the base of heap assert_addr_not_equal(freelist1, freelist0); assert_addr_not_equal(freelist1->next, freelist0); assert_addr_equal(freelist1->next, next); assert_addr_equal(freelist1->prev, NULL); assert_addr_equal(next->next, NULL); assert_addr_equal(next->prev, freelist1); Heap_Info info = verify_heap(); assert_equal(info.busy, 1); assert_equal(info.free, 2); assert_equal(info.free_size, HEAP_SIZE - info.busy_size); assert_equal(freelist1->next->size, info.free_size-freelist1->size); assert_equal(find_next(find_next(freelist1)), freelist1->next); } //five consecutive chunks allocated void five_malloc() { void *p = get_heap_base(); Busy_Header *b_1 = malloc(100); assert_addr_equal(b_1, p); //b_1 is at the start of heap assert_equal(chunksize(b_1), request2size(100)); Busy_Header *b_2 = malloc(200); Busy_Header *b1_next = find_next(b_1); assert_addr_equal(b1_next,b_2); //b_2 is after b_1 assert_equal(chunksize(b_2), request2size(200)); Busy_Header *b_3 = malloc(300); assert_addr_equal(find_next(b_2),b_3); //b_3 is after b_2 assert_equal(chunksize(b_3), request2size(300)); Busy_Header *b_4 = malloc(400); assert_addr_equal(find_next(b_3),b_4); //b_4 is after b_3 assert_equal(chunksize(b_4), request2size(400)); Busy_Header *b_5 = malloc(500); assert_addr_equal(find_next(b_4),b_5); //b_5 is after b_4 assert_equal(chunksize(b_5), request2size(500)); Heap_Info info = verify_heap(); assert_equal(info.busy, 5); assert_equal(info.free, 1); assert_equal(info.free_size, HEAP_SIZE - info.busy_size); } //free the first chunk, then free last chunk to merge with the end of free list void merge_with_end() { three_malloc(); Busy_Header *b_1 = get_heap_base(); Busy_Header *b_2 = find_next(b_1); Busy_Header *b_3 = find_next(b_2); free(b_1); //free the first chunk Free_Header *freelist0 = get_freelist(); //get the new freelist assert_addr_equal(freelist0, b_1); assert_addr_equal(freelist0->next, find_next(b_3)); free(b_3); //free the last chunk, merge Free_Header *freelist1 = get_freelist(); assert_addr_equal(freelist1, b_3); assert_addr_equal(freelist1->next, b_1); assert_addr_equal(freelist1->prev, NULL); assert_addr_equal(freelist1->next->prev, freelist1); assert_addr_equal(freelist1->next->next, NULL); Heap_Info info = verify_heap(); assert_equal(info.busy, 1); assert_equal(info.free, 2); assert_equal(info.free_size, HEAP_SIZE - info.busy_size); assert_equal(freelist1->next->size, b_1->size); assert_equal(find_next(find_next(b_1)), freelist1); } //free the first chunk, then free last chunk to merge with the end of free list void merge_with_middle() { five_malloc(); Busy_Header *b_1 = get_heap_base(); Busy_Header *b_2 = find_next(b_1); Busy_Header *b_3 = find_next(b_2); Busy_Header *b_4 = find_next(b_3); Busy_Header *b_5 = find_next(b_4); size_t size_3 = b_3->size & SIZEMASK; size_t size_4 = b_4->size & SIZEMASK; free(b_4); free(b_2); Free_Header *freelist0 = get_freelist(); //get the new freelist at b_2->b_4->after b_5 Free_Header *last = find_next(b_5); assert_addr_equal(freelist0, b_2); assert_addr_equal(freelist0->next, b_4); assert_addr_equal(freelist0->prev, NULL); assert_addr_equal(((Free_Header*)b_4) ->next, last); assert_addr_equal(((Free_Header*)b_4) ->prev, b_2); assert_addr_equal(last->next, NULL); assert_addr_equal(last->prev, b_4); free(b_3); //merge with b_4 Free_Header *freelist1 = get_freelist(); //get new free list at b_3; assert_addr_equal(freelist1, b_3); assert_equal(freelist1->size & SIZEMASK, size_3 + size_4); assert_addr_equal(freelist1->next, b_2); //freelist1 ->freelist0->last assert_addr_equal(freelist1->prev, NULL); assert_addr_equal(freelist0->next, last); assert_addr_equal(freelist0->prev, freelist1); assert_addr_equal(last->next, NULL); assert_addr_equal(last->prev, freelist0); Heap_Info info = verify_heap(); assert_equal(info.busy, 2); assert_equal(info.free, 3); assert_equal(info.free_size, HEAP_SIZE - info.busy_size); assert_equal(freelist1->next->size + freelist0->next->size, info.free_size-freelist1->size); } //allocate 10 consecutive chunks, free from the back to the front //should fuse the heap to one free chunk void fuse_to_one() { Busy_Header* b[10]; for(int i = 0; i < 10; i++){ b[i] = malloc(100); assert_addr_equal(get_freelist(), find_next(b[i])); assert_addr_equal(get_freelist()->prev, NULL); } Free_Header *freelist0 = get_freelist(); for( int i = 9; i >= 0 ; i--){ free(b[i]); assert_addr_equal(get_freelist(), b[i]); assert_addr_equal(get_freelist()->prev, NULL); } Heap_Info info = verify_heap(); assert_equal(info.busy, 0); assert_equal(info.free, 1); assert_equal(info.busy_size + info.free_size, get_heap_info().heap_size); assert_addr_equal(find_next(get_freelist()), get_heap_base() + info.heap_size); assert_addr_equal(freelist0->next, NULL); } void long_freelist() { Busy_Header* b[20]; for(unsigned i = 0; i < 20; i++){ b[i] = malloc(i); assert_addr_equal(get_freelist(), find_next(b[i])); assert_addr_equal(get_freelist()->prev, NULL); } for( int i = 0; i <20 ; i++){ free(b[i]); assert_addr_equal(get_freelist(), b[i]); if (i+1 < 20) assert_addr_equal(find_next(get_freelist()), b[i+1]); assert_addr_equal(get_freelist()->prev, NULL); } //last free causes a merge Heap_Info info = verify_heap(); assert_equal(info.busy, 0); assert_equal(info.free, 20); assert_equal(info.busy_size + info.free_size, get_heap_info().heap_size); // out of heap assert_addr_equal(get_freelist(), b[19]); assert_addr_equal(find_next(get_freelist()), get_heap_base() + info.heap_size); //out of heap assert_addr_equal(((Free_Header *)b[0])->next, NULL); //end } //skip first free chunk, which is not big enough void search_along_list() { Busy_Header* b[4]; for(int i = 0; i < 4; i++){ b[i] = malloc(450); } assert_equal(b[0]->size & SIZEMASK, request2size(450)); assert_equal(b[1]->size & SIZEMASK, request2size(450)); assert_equal(b[2]->size & SIZEMASK, request2size(450)); assert_equal(b[3]->size & SIZEMASK, request2size(450)); Free_Header* f4 = find_next(b[3]); Heap_Info info = verify_heap(); assert_equal(info.busy, 4); assert_equal(info.free, 1); assert_equal(info.busy_size, 1824); assert_equal(info.free_size, 176); assert_addr_equal(get_freelist(), f4); assert_addr_equal(get_freelist()->next, NULL); assert_addr_equal(get_freelist()->prev, NULL); //after malloc, free b3, b0 free(b[3]); free(b[0]); info = verify_heap(); assert_equal(info.busy, 2); assert_equal(info.free, 2); assert_equal(info.busy_size + info.free_size, get_heap_info().heap_size); } //fit in the first free chunk of the list void exact_fit() { Busy_Header* b[4]; for(int i = 0; i < 4; i++){ b[i] = malloc(450); } assert_equal(b[0]->size & SIZEMASK, request2size(450)); assert_equal(b[1]->size & SIZEMASK, request2size(450)); assert_equal(b[2]->size & SIZEMASK, request2size(450)); assert_equal(b[3]->size & SIZEMASK, request2size(450)); Free_Header* f4 = find_next(b[3]); Heap_Info info = verify_heap(); assert_equal(info.busy, 4); assert_equal(info.free, 1); assert_equal(info.busy_size, 1824); assert_equal(info.free_size, 176); assert_addr_equal(get_freelist(), f4); assert_addr_equal(get_freelist()->next, NULL); assert_addr_equal(get_freelist()->prev, NULL); free(b[2]); info = verify_heap(); assert_equal(info.busy, 3); assert_equal(info.free, 2); assert_equal(info.busy_size, 1368); assert_equal(info.free_size, 632); assert_addr_equal(get_freelist(), b[2]); assert_addr_equal(get_freelist()->next, f4); assert_addr_equal(get_freelist()->next->next, NULL); assert_addr_equal(f4->prev, b[2]); assert_addr_equal(f4->prev->prev, NULL); free(b[0]); info = verify_heap(); assert_equal(info.busy, 2); assert_equal(info.free, 3); assert_equal(info.busy_size, 912); assert_equal(info.free_size, 1088); assert_addr_equal(get_freelist(), b[0]); assert_addr_equal(get_freelist()->next, b[2]); assert_addr_equal(get_freelist()->next->next, f4); assert_addr_equal(get_freelist()->next->next->next, NULL); assert_addr_equal(f4->prev, b[2]); assert_addr_equal(f4->prev->prev, b[0]); assert_addr_equal(f4->prev->prev->prev, NULL); Busy_Header *fit = malloc(450); assert_addr_equal(fit, get_heap_base()); info = verify_heap(); assert_equal(info.busy, 3); assert_equal(info.free, 2); assert_addr_equal(get_freelist(), b[2]); assert_addr_equal(get_freelist()->next, f4); assert_addr_equal(get_freelist()->next->next, NULL); assert_addr_equal(f4->prev, b[2]); assert_addr_equal(f4->prev->prev, NULL); } //split chunk void split_chunk(){ Busy_Header* b[4]; for(int i = 0; i < 4; i++){ b[i] = malloc(450); } assert_equal(b[0]->size & SIZEMASK, request2size(450)); assert_equal(b[1]->size & SIZEMASK, request2size(450)); assert_equal(b[2]->size & SIZEMASK, request2size(450)); assert_equal(b[3]->size & SIZEMASK, request2size(450)); Free_Header* f4 = find_next(b[3]); Heap_Info info = verify_heap(); assert_equal(info.busy, 4); assert_equal(info.free, 1); assert_equal(info.busy_size, 1824); assert_equal(info.free_size, 176); assert_addr_equal(get_freelist(), f4); assert_addr_equal(get_freelist()->next, NULL); assert_addr_equal(get_freelist()->prev, NULL); free(b[2]); info = verify_heap(); assert_equal(info.busy, 3); assert_equal(info.free, 2); assert_equal(info.busy_size, 1368); assert_equal(info.free_size, 632); assert_addr_equal(get_freelist(), b[2]); assert_addr_equal(get_freelist()->next, f4); assert_addr_equal(get_freelist()->next->next, NULL); assert_addr_equal(f4->prev, b[2]); assert_addr_equal(f4->prev->prev, NULL); free(b[0]); info = verify_heap(); assert_equal(info.busy, 2); assert_equal(info.free, 3); assert_equal(info.busy_size, 912); assert_equal(info.free_size, 1088); assert_addr_equal(get_freelist(), b[0]); assert_addr_equal(get_freelist()->next, b[2]); assert_addr_equal(get_freelist()->next->next, f4); assert_addr_equal(get_freelist()->next->next->next, NULL); assert_addr_equal(f4->prev, b[2]); assert_addr_equal(f4->prev->prev, b[0]); assert_addr_equal(f4->prev->prev->prev, NULL); Busy_Header *split = malloc(200); assert_addr_equal(split, get_heap_base()); Free_Header *newhead = get_freelist(); assert_addr_equal(find_next(split),newhead); assert_addr_equal(get_freelist(), find_next(split)); assert_addr_equal(get_freelist()->next, b[2]); assert_addr_equal(get_freelist()->next->next, f4); assert_addr_equal(get_freelist()->next->next->next, NULL); assert_addr_equal(f4->prev, b[2]); assert_addr_equal(f4->prev->prev, newhead); assert_addr_equal(f4->prev->prev->prev, NULL); info = verify_heap(); assert_equal(info.busy, 3); assert_equal(info.free, 3); assert_equal(info.busy_size + info.free_size, get_heap_info().heap_size); // out of heap*/ } void print_both_ways(Free_Header *f){ Free_Header *head = f; while (f->next != NULL){ printf("%p->", f); f = f->next; } printf("%p\n", f); while (f->prev != NULL){ printf("%p<-", f); f = f->prev; } printf("%p\n", f); assert_addr_equal(f, head); } void test_core() { void *heap = morecore(HEAP_SIZE); assert_addr_not_equal(heap, NULL); dropcore(heap, HEAP_SIZE); } void test_init_shutdown() { heap_init(HEAP_SIZE); assert_addr_equal(get_freelist(), get_heap_base()); heap_shutdown(); } int main(int argc, char *argv[]) { cunit_setup = setup; cunit_teardown = teardown; test_core(); test_init_shutdown(); heap_init(HEAP_SIZE); test(malloc0); test(malloc1); test(malloc_word_size); test(malloc_2x_word_size); test(one_malloc); test(two_malloc); test(free_NULL); test(free_random); test(free_stale); test(malloc_then_free); test(three_malloc); test(five_malloc); test(free_without_merging); test(merge_with_head); test(merge_with_end); test(merge_with_middle); test(fuse_to_one); test(long_freelist); test(search_along_list); test(exact_fit); test(split_chunk); }
C
#include <stdio.h> void sort(int a[], int n) { int tmp; for (int i = 0; i < n / 2; i++) { tmp = a[i]; a[i] = a[n - 1 - i]; a[n - 1 - i] = tmp; } } int main() { int a[10], n; printf("So phan tu mang la"); scanf("%d", &n); for (int i = 0; i < n; i++) { printf("\na[%d]:", i); scanf("%d", &a[i]); } sort(a, n); for (int i = 0; i < n; i++) printf("%d ", a[i]); return n; }
C
/* ** parse_arg.c for plazza in /home/wautel_l/rendu/PSU_2014_zappy/serveur ** ** Made by lucie wautelet ** Login <[email protected]> ** ** Started on Tue May 12 15:15:12 2015 lucie wautelet ** Last update Sun Jul 5 17:47:36 2015 lucie wautelet */ #include "../include/serveur.h" void my_stock_larg(char *str, t_server *begin, char code, int *verif) { if (code == 'p') { (verif[0] == 1) ? my_perror("Usage") : (verif[0] = 1); begin->port = atoi(str); } else if (code =='x') { (verif[1] == 1) ? my_perror("Usage") : (verif[1] = 1); begin->width = atoi(str); if (begin->width < 1) my_perror("x must be superior to 0\n"); } else { (verif[2] == 1) ? my_perror("Usage") : (verif[2] = 1); begin->height = atoi(str); if (begin->height < 1) my_perror("y must be superior to 0\n"); } } void my_stock_timeplay(char *str, t_server *begin, char code, int *verif) { if (code == 'c') { (verif[3] == 1) ? my_perror("Usage") : (verif[3] = 1); begin->client = atoi(str); } else if (code =='t') { begin->delay = atoi(str); if (begin->delay == 0) begin->delay = 100; } } void my_stock_team(char **av, int lim, t_server *begin, int *nbarg) { int i; i = 0; if (lim == 0) my_perror("Usage"); (nbarg[4] == 1) ? my_perror("Usage") : (nbarg[4] = 1); while (i < lim) { begin->team[i] = strdup(av[i]); begin->nbteam[i] = 0; i++; } begin->team[i] = NULL; begin->totteam = i; } void my_verif_second(char **av, int *nbarg, t_server *begin) { int i; int sauv; i = 0; while (av[i] != NULL) { if (av[i][0] == '-' && av[i][1] == 'n') { sauv = i++; while (av[i] != NULL && av[i][0] != '-') i++; my_stock_team(&av[sauv + 1], i - sauv - 1, begin, nbarg); } i++; } if (my_strlenint(nbarg) != 5) my_perror("Usage"); } void my_init_arg(char **av, t_server *begin) { int i; int *verifarg; verifarg = malloc(sizeof(int) * 7); my_init_verifarg(verifarg); i = 0; begin->delay = 100; while (av[i] != NULL) { if (av[i][0] == '-' && (av[i][1] == 'p' || av[i][1] == 'x' || av[i][1] == 'y')) { if (av[i + 1] == NULL || av[i + 1][0] == '-') my_perror("Usage"); my_stock_larg(av[i + 1], begin, av[i][1], verifarg); } else if (av[i][0] == '-' && (av[i][1] == 'c' || av[i][1] == 't')) { if (av[i + 1] == NULL || av[i + 1][0] == '-') my_perror("Usage"); my_stock_timeplay(av[i + 1], begin, av[i][1], verifarg); } i++; } my_verif_second(av, verifarg, begin); }
C
// 442p 2 #include <stdio.h> #include <string.h> #include <stdbool.h> int main() { char words[10][21]; int cnt = 0; do { char input[21] = { '\0' }; fputs("ܾ Է ( end Է): ", stdout); scanf_s("%s", input, (unsigned int)sizeof(input)); if (!strcmp(input, "end")) break; strcpy_s(words[cnt++], sizeof(words[0]), input); } while (cnt < 10); printf("# %d ܾ ԷµǾϴ!\n\n", cnt); while (true) { char target[21] = { '\0' }; bool flag = false; fputs("˻ ܾ ( end Է): ", stdout); scanf_s("%s", target, (unsigned int)sizeof(target)); if (!strcmp(target, "end")) break; for (int i = 0; i < cnt; ++i) { if (!strcmp(words[i], target)) { flag = true; printf("# %d° ܾ ֽϴ!\n\n", (i + 1)); } } if (!flag) printf("# ܾԴϴ.\n\n"); } return 0; }
C
/* You should use the statndard input/output in order to receive a score properly. Do not use file input and output Please be very careful. */ #include <stdio.h> #include <stdlib.h> int Answer; int static compare(const void *first, const void *second) { if (*(int*)first > *(int*)second) return 1; else if (*(int*)first < *(int*)second) return -1; else return 0; } int main(void) { int T, test_case; int *scores = NULL; int N, i, j, max, temp; //int scores[10]; //int new_scores[10]; /* The freopen function below opens input.txt file in read only mode, and afterward, the program will read from input.txt file instead of standard(keyboard) input. To test your program, you may save input data in input.txt file, and use freopen function to read from the file when using scanf function. You may remove the comment symbols(//) in the below statement and use it. But before submission, you must remove the freopen function or rewrite comment symbols(//). */ int f = freopen("input.txt", "r", stdin); /* If you remove the statement below, your program's output may not be rocorded when your program is terminated after the time limit. For safety, please use setbuf(stdout, NULL); statement. */ setbuf(stdout, NULL); scanf("%d", &T); for (test_case = 0; test_case < T; test_case++) { ///////////////////////////////////////////////////////////////////////////////////////////// /* Implement your algorithm here. The answer to the case will be stored in variable Answer. */ ///////////////////////////////////////////////////////////////////////////////////////////// max = 0; i = 0; j = 0; scanf("%d", &N); scores = (int*)malloc(sizeof(int)*N); for (i = 0; i < N; i++) { scanf("%d", &scores[i]); } qsort(scores, N, sizeof(int), compare); for (i = 0; i < N; i++) { if (scores[i] + (N - i) > max) max = scores[i] + (N - i); } Answer = 0; for (i = 0; i < N; i++) { if (scores[i] + N >= max) Answer++; } // Print the answer to standard output(screen). printf("Case #%d\n", test_case + 1); printf("%d\n", Answer); } fclose(f); return 0;//Your program should return 0 on normal termination. }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_itoa.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: blavonne <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/09/16 19:47:20 by blavonne #+# #+# */ /* Updated: 2019/10/14 15:24:11 by blavonne ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static int ft_alloc(int n) { int count; int size; count = 0; while (n / 10) { count++; n = n / 10; } if (n < 0) return (size = count + 1 + 1); else return (size = count + 1); } static char *ft_reverse(char *str) { char c; int begin; int end; begin = 0; end = ft_strlen(str) - 1; while (begin < end) { c = str[begin]; str[begin] = str[end]; str[end] = c; begin++; end--; } return (str); } char *ft_itoa(int n) { char *buf; int i; unsigned int res; if (n >= 0) res = n; else res = -n; i = 0; if (!(buf = (char *)malloc(sizeof(char) * ft_alloc(n) + 1))) return (NULL); while (res / 10) { buf[i] = res % 10 + '0'; res /= 10; i++; } if (!(res / 10)) buf[i++] = res + '0'; if (n < 0) buf[i++] = '-'; buf[i] = '\0'; return (ft_reverse(buf)); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "xget.h" #include "xvalidate.h" #include "xArrayWork.h" #include "xlook.h" /* --------------------------------------------ETIQUETAS-------------------------------------------------> Cambiar tipo de dato de las funciones: *----> eGeneric* *----> generic Sustitucion automatica de campo en documentaciones: *----> %campo% Sustitucion automatica de tipo de dato en documentaciones: *----> %tipoDeDato% ------------------------------> * Buscar setter y getter: ------------------------------> Enteros: $INT$ Longs: $LONG$ Long longs $LONGLONG$ Flotantes: $FLOAT$ Doubles $DOUBLE$ Caracteres: $CHAR$ String $CHAR*$ ------------------------------> *Buscar constructor: ------------------------------> Constructor: $BUILDER$ ------------------------------> *Buscar comparadores: ------------------------------> Comparador: $COMP$ Buscador de igualdad: $SAME$ ------------------------------------------------------------------------------------------------------> */ // Constructor $BUILDER$ /** \brief Reserva espacio dinamico para un puntero del tipo de dato %tipoDeDato% e inicializa sus campos. * * \param * \return Devuelve un puntero a una estructura del tipo de dato %tipoDeDato% , en caso de error un puntero a NULL. * */ eGeneric* generic_newGeneric(void) { eGeneric* generic = (eGeneric*)malloc(sizeof(eGeneric)); if( generic != NULL ) { strcpy(generic->word, ""); generic->intNumber = 0; } return generic; } //Destructores: /** \brief Libera un puntero. * * \param pointer: Puntero a liberar. * \return Devuelve [1] si el puntero fue liberado o [0] en caso contrario. * */ int generic1_PointerDestroyer( void* pointer ) { int destroyed = 0; if( pointer != NULL ) { destroyed = 1; free(pointer); } return destroyed; } /** \brief Libera punteros anidados en un puntero doble. * * \param pointer : Puntero doble a liberar. * \param size : Cantidad de punteros anidados que se deben eliminar. * \return Devuelve [1] si los punteros se liberaron o [0] en caso contrario. * */ int generic2_PointerDestroyer( void** pointer, int size ) { int destroyed = 0; if( pointer != NULL && size > 0 ) { destroyed = 1; int i; for( i = 0 ; i < size ; i++) { free(pointer[i]); pointer[i] = NULL; } } return destroyed; } // Set y get ENTEROS $INT$ /** \brief Setea el campo %campo% en un puntero al tipo de dato %tipoDeDato% . * * \param generic : Puntero donde setear %campo% . * \param num : %campo% a setear en la estructura. * \return Devuelve [1] si el dato fue seteado correctamente o [0] en caso de error . * */ int generic_setInt( eGeneric* generic , int num ) { int verify = 0; if( generic != NULL ) { if(validateIntRange(num,0,5) ) { verify = 1; generic->intNumber = num; } } return verify; } /** \brief Obtiene el dato %campo% de un puntero al tipo de dato %tipoDeDato% . * * \param generic : Puntero de donde obtener el dato %campo% . * \return Devuelve el dato correspondiente al atributo de la estructura . * */ int generic_getInt( eGeneric* generic ) { return generic->intNumber; } // Set y get LONGS: $LONG$ /** \brief Setea el campo %campo% en un puntero al tipo de dato %tipoDeDato% . * * \param generic : Puntero donde setear %campo% . * \param num : %campo% a setear en la estructura. * \return Devuelve [1] si el dato fue seteado correctamente o [0] en caso de error . * */ int generic_setLong( eGeneric* generic , long num ) { int verify = 0; if( generic != NULL ) { validateLongRange(num,0,5); if( 1) { verify = 1; generic->longNumber = num; } } return verify; } /** \brief Obtiene el dato %campo% de un puntero al tipo de dato %tipoDeDato% . * * \param generic : Puntero de donde obtener el dato %campo% . * \return Devuelve el dato correspondiente al atributo de la estructura . * */ long generic_getLong( eGeneric* generic ) { return generic->longNumber; } // Set y get LONG LONGS: $LONGLONG$ /** \brief Setea el campo %campo% en un puntero al tipo de dato %tipoDeDato% . * * \param generic : Puntero donde setear %campo% . * \param num : %campo% a setear en la estructura. * \return Devuelve [1] si el dato fue seteado correctamente o [0] en caso de error . * */ int generic_setLongLong( eGeneric* generic , long long num ) { int verify = 0; if( generic != NULL ) { if( 1 ) { verify = 1; generic->longLongNumber = num; } } return verify; } /** \brief Obtiene el dato %campo% de un puntero al tipo de dato %tipoDeDato% . * * \param generic : Puntero de donde obtener el dato %campo% . * \return Devuelve el dato correspondiente al atributo de la estructura . * */ long long generic_getLongLong( eGeneric* generic ) { return generic->longLongNumber; } // Set y get FLOTANTES: $FLOAT$ /** \brief Setea el campo %campo% en un puntero al tipo de dato %tipoDeDato% . * * \param generic : Puntero donde setear %campo% . * \param num : %campo% a setear en la estructura. * \return Devuelve [1] si el dato fue seteado correctamente o [0] en caso de error . * */ int generic_setFloat( eGeneric* generic , float num ) { int verify = 0; if( generic != NULL ) { if( 1 ) { verify = 1; generic->floatNumber = num; } } return verify; } /** \brief Obtiene el dato %campo% de un puntero al tipo de dato %tipoDeDato% . * * \param generic : Puntero de donde obtener el dato %campo% . * \return Devuelve el dato correspondiente al atributo de la estructura . * */ float generic_getFloat( eGeneric* generic ) { return generic->floatNumber; } // Set y get DOUBLES: $DOUBLE$ /** \brief Setea el campo %campo% en un puntero al tipo de dato %tipoDeDato% . * * \param generic : Puntero donde setear %campo% . * \param num : %campo% a setear en la estructura. * \return Devuelve [1] si el dato fue seteado correctamente o [0] en caso de error . * */ int generic_setDouble( eGeneric* generic , double num ) { int verify = 0; if( generic != NULL ) { if( 1 ) { verify = 1; generic->doubleNumber = num; } } return verify; } /** \brief Obtiene el dato %campo% de un puntero al tipo de dato %tipoDeDato% . * * \param generic : Puntero de donde obtener el dato %campo% . * \return Devuelve el dato correspondiente al atributo de la estructura . * */ double generic_getDouble( eGeneric* generic ) { return generic->doubleNumber; } // Set y get CHAR : $CHAR$ /** \brief Setea el campo %campo% en un puntero al tipo de dato %tipoDeDato% . * * \param generic : Puntero donde setear %campo% . * \param num : %campo% a setear en la estructura. * \return Devuelve [1] si el dato fue seteado correctamente o [0] en caso de error . * */ int generic_setChar( eGeneric* generic , char let ) { int verify = 0; if( generic != NULL ) { if( 1 ) { verify = 1; generic->character = let; } } return verify; } /** \brief Obtiene el dato %campo% de un puntero al tipo de dato %tipoDeDato% . * * \param generic : Puntero de donde obtener el dato %campo% . * \return Devuelve el dato correspondiente al atributo de la estructura . * */ char generic_getChar( eGeneric* generic ) { return generic->character; } // Set y get CHAR* : $CHAR*$ /** \brief Setea el campo %campo% en un puntero al tipo de dato %tipoDeDato% . * * \param generic : Puntero donde setear %campo% . * \param num : %campo% a setear en la estructura. * \return Devuelve [1] si el dato fue seteado correctamente o [0] en caso de error . * */ int generic_setString( eGeneric* generic , char* word ) { int verify = 0; if( generic != NULL && word != NULL) { if( 1 ) { verify = 1; strcpy(generic->word , word); } } return verify; } /** \brief Obtiene el dato %campo% de un puntero al tipo de dato %tipoDeDato% . * * \param generic : Puntero de donde obtener el dato %campo% . * \return Devuelve el dato correspondiente al atributo de la estructura . * */ char* generic_getString( eGeneric* generic ) { return generic->word; } //FUNCIONES ABM /** \brief Pide %estructura% . * * \return Devuelve un puntero a %estructura% cargado de datos en caso de error devuelve NULL. * */ eGeneric* generic_requester(void) { eGeneric* lm = generic_newGeneric(); if( lm != NULL) { int verify; int number = 45; do { verify = 0; if( 1 ) { if( generic_setInt(lm,number) ) { verify=1; } } } while(verify == 0 ); } return lm; } /** \brief Muestra los datos de un puntero al tipo de dato %estructura% . * * \param Variable de tipo %estructura% a mostrar. * \return Devuelve [1] si se pudo mostrar el dato o [0] en caso de error. * */ int generic_show(eGeneric* gen ) { int verify = 0; if( gen != NULL) { verify = 1; } return verify; } /** \brief Permite al usuario modificar una estructura. * * \param gen : puntero a %estructura% que se desea modificar. * \param message : Mensaje a ser mostrado al pedirle al usuario el dato irrepible de la estructura. * \param eMessage : Mensaje a ser mostrado en caso de que el usuario escriba un dato erroneo. * \return Devuelve [1] si el usuario modifico algun dato , [0] si no lo hizo o [-1] en caso de un puntero a NULL. * */ int generic_modify(eGeneric* gen ) { int verify = -1; if( gen != NULL) { int selection; int quit = 0; verify = 0; do { xlkIndexGenerator("HEAD",3,"1* uno.","2* dos.","3* tres."); if(getRangedInt(&selection,0,3,"Seleccionar opcion: ","Opcion invalida.")) { system("cls"); switch(selection) { case 1: //verify = generic_modify(gen); break; case 2: //verify = generic_getFloat(gen); break; case 3: quit = validateDualExit(XLK_EXITMSG,XLK_INVALID_ANSWER,'s','n'); break; } } system("pause"); } while(quit == 0); } return verify; } //MODIFICAR DATOS: /** \brief Permite al usuario modifica el %campo% de un puntero a %estructura%. * * \param gen : Puntero a %estructura%. * \param message : Mensaje a ser mostrado al pedir el dato para modificar la estructura. * \param eMessage : Mensaje a ser mostrado en caso de error. * \return Devuelve [-1] en caso de dato erroneo, [0] en caso de anularse la modificacion o [1] si el dato fue modificado. * */ int eGeneric_ModifyInt(eGeneric* gen, char message[], char eMessage[]) { int verify = -1; int number = 45; if( 1 ) { verify = 0; if( validateDualExit(XLK_EXITMSG,XLK_INVALID_ANSWER,'s','n') ) { verify = 1; gen->intNumber = number; } } return verify; } //COMPARAR ESTRUCTURAS $COMP$ /** \brief Compara dos punteros a estructuras del tip %campo% . * * \param generic1 : Puntero a ser comparado con otro. * \param generic2 : Puntero a ser comparado con el primero. * \return Devuelve [1] si el primer puntero es mayor, [0] si son iguales o [-1] si el primer puntero es menor. * */ int generic_compare(void* generic1 ,void* generic2) { int comparision = 0; if( ((eGeneric*)generic1)->intNumber > ((eGeneric*)generic2)->intNumber ) { comparision = 1; } if( ((eGeneric*)generic1)->intNumber < ((eGeneric*)generic2)->intNumber ) { comparision = -1; } return comparision; }
C
//了解多种方法输入输出字符串 #include <stdio.h> void main() { char str1[12],str2[12],str3[12]; int i ; printf("用gets()/puts()输入/输出字符串(<12:)\n"); gets(str1); puts(str1); printf("用scanf()/printf()输入/输出单个字符(<12:)\n"); for(i=0;i<12;i++) { scanf("%c",&str2[i]); } for(i=0;i<12;i++) { printf("%c",str2[i]); } printf("\n"); printf("用gets()/puts()输入/输出字符串(<12:)\n"); scanf("%s",str3); printf("%s",str3); printf("\n"); }
C
/* Tutorial 3 Question 1 **Group 5 **By: Carlos Fabregas ** Prompts the user for their first name, age and height then prints it back into console */ #include <stdio.h> #include <stdlib.h> int main(void) { char name[20]; int age; int height; //asks for user input printf("What is your first name? \n"); scanf("%s", &name); printf("What is your age? \n"); scanf("%d", &age); printf("What is your height? \n"); scanf("%d", &height); //prints out user input to terminal printf("Your first name is %s, your age is %d and your height is %d \n", name, age, height); }
C
#include <stdio.h> int main() { char c,r; scanf("%c %c",&c,&r); if((c=='S')&&(r=='R')||(c=='R')&&(c=='S')) printf("R"); else if((c=='P')&&(r=='R')||(c=='R')&&(c=='P')) printf("P"); else printf("S"); return 0; }
C
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #define DEBUG 0 int N, K, max; struct vertice { int u, v; }; struct vertice vertices[101]; // phd[point index][height][distance] = point count int phd[101][101][101]; void rfn(int p, int pp) { // 初始化,如果只有该点自己,则 height 和 distance 都为0 phd[p][0][0] = 1; for (size_t i = 1; i < N; i++) { // 遍历它的孩子 if (vertices[i].u == p || vertices[i].v == p) { int child = vertices[i].u == p ? vertices[i].v : vertices[i].u; if (child != pp) { // 处理叶子child的 height 和 distance rfn(child, p); // 处理parent自己的 height 和 distance // 遍历 parent 已经有的情况,计算新的 int tmp[101][101]; memcpy(tmp, phd[p], 101 * 101 * sizeof(int)); for (int ph = K /*parent->max_height*/; ph >= 0; ph --) { for (int pd = K /*parent->max_distance*/; pd >= 0; pd --) { if (phd[p][ph][pd]) { // phd[p][ph][pd] 为截止到计算 child 前的一种可能性 for (size_t h = 0; h <= K /*&& h <= child->max_height*/; h++) { for (size_t d = h; d <= h * 2 /*&& d <= child->max_distance*/ && d <= K; d++){ if (phd[child][h][d]) { int cnt = phd[child][h][d]; int p_h, p_d; // 该 child 加入到 parent 后对应的 height 和 distance p_h = h + 1; if (h + 1 > d) { p_d = h + 1; } else { p_d = d; } // 该 child 加入到 parent 后,对应的整个树的 height 和 distance int new_h, new_d; if (p_h > ph) { new_h = p_h; } else { new_h = ph; } new_d = p_h + ph; if (new_d > p_d && new_d > ph) { } else if (p_d > pd) { new_d = p_d; } else { new_d = pd; } int new_cnt = cnt + phd[p][ph][pd]; if (new_d <= K && tmp[new_h][new_d] < new_cnt) { tmp[new_h][new_d] = new_cnt; #if DEBUG printf("pdh[%d][%d][%d] is %d\n", p, new_h, new_d, tmp[new_h][new_d]); #endif if (new_d <= K && new_cnt > max) { max = new_cnt; } } // 处理 自己 if (p_d <= K && cnt > tmp[p_h][p_d]) { tmp[p_h][p_d] = cnt; #if DEBUG printf("pdh[%d][%d][%d] is %d\n", p, p_h, p_d, phd[p][p_h][p_d]); #endif if (p_d <= K && cnt > max) { max = cnt; } } } } } } } } memcpy(phd[p], tmp, 101 * 101 * sizeof(int)); } } } } int main() { scanf("%d %d", &N, &K); for (size_t i = 1; i < N; i++) { int ui, vi; scanf("%d %d", &ui, &vi); vertices[i].u = ui; vertices[i].v = vi; } max = 0; memset(phd, 0, sizeof(phd)); rfn(1, 0); printf("%d\n", N - max); return 0; }
C
#include "vm/s-pagetable.h" #include <stdio.h> #include "threads/synch.h" #include "threads/palloc.h" #include "threads/malloc.h" #include "threads/thread.h" #include "userprog/pagedir.h" #include "threads/pte.h" #include "userprog/pagedir.h" #include "userprog/syscall.h" #include "userprog/process.h" #include "threads/vaddr.h" #include <list.h> #include "vm/swap.h" #include "vm/frame.h" #include "vm/file-table.h" #include "filesys/file.h" #include "vm/mmap-table.h" struct list s_page_table; struct lock s_pt_lock; struct lock swapin_lock; /* 1. page fault가 난 page를 supplemental page table에 위치 memory reference가 valid 이면 -> supplemental page table entry 를 이용하여 "file system" 혹은 "swap slot" 에 있을, 혹은 그냥 "all-zero page"를 locate (entry의 paddr == NULL 이면 메모리에 남은 자리가 있는지 보고 uint32_t free_frame = get_free_frame() ( 이 함수 안에서 free frame없으면 알아서 swap out까지 해서 빈 프레임 넘겨줌 ) 위 함수 통과하면 free_frame은 빈 주소 swap in(free_frame, va, pid)해야해 -> swaptable이 va, pid가지고 해당 disksector찾아) (if you implement sharing, page's data 는 이미 page frame에 있으나 page table에 없을 수 있다) 2. page를 저장할 frame을 가져온다. (4.1.5 Managing Frame Table) (if you implement sharing, 우리가 필요한 data는 이미 frame에 있을 수 있다 -> you must be able to locate that frame) 3. Fetch data into frame <- file system에서 가져오거나, swap하거나, zeroing it ... (if you implement sharing, page you need는 이미 frame에 있을 수 있다 -> no action is necessary) 4. fault가 발생한 page table entry의 fulting virtul address-> physical page 이도록 만들어라 (userprog/pagedir.c) */ void init_s_page_table(void) { list_init(&s_page_table); lock_init(&s_pt_lock); lock_init(&swapin_lock); } /* 1. page fault가 발생했을 시 -> kernel이 s_pt에서 fault가 일어난 virtual page를 찾아, what data should be there을 검색 2 process가 terminate 할 때 -> kernel이 s_pt에서 , what resources to free를 찾음 */ /* void s_pte_insert(void *va, void *pa, tid_t pid) from pagedir_set_page() 1. when need add mapping, add mapping to supplemental page table also. 2. latest one is always on the front, oldest one is always on the back. 3. (va, pid) combination is the key. 4. always add mapping to frame table too. (두 테이블을 맞게 유지해주기위해) */ void s_pte_insert(void *va, void *pa, tid_t pid, int mmap_id) { //table entry에 va, pa, pid를 넣어서 table에 추가해준다. //printf("s_pte_insert paddr %p, vaddr %p, pid %d\n", pa, va, pid); uint32_t vaddr = va; //uint32_t paddr = pa; struct s_pte *pte; struct s_pte *find_pte; pte = malloc(sizeof *pte); pte->vaddr = vaddr; pte->paddr = pa; pte->pid = pid; pte->is_swapout = false; pte->mmap_id = mmap_id; // (LAZY LOADING) if (pa == NULL) pte->is_exec = true; else pte->is_exec = false; lock_acquire(&s_pt_lock); find_pte = find_entry((void *)vaddr, pid); if (find_pte !=NULL){ //pte->is_exec = find_pte->is_exec; list_remove(&find_pte->elem); free(find_pte); } list_push_front(&s_page_table, &pte->elem); lock_release(&s_pt_lock); if (pa !=NULL) //(LAZY LOADING) add_frame_entry(pa, va, pid); } /* void s_pte_clear(void *va, tid_t pid) from pagedir_clear_page() */ void s_pte_clear (void *va, tid_t pid) { //table entry 중에서 va, pid를 가진 애를 delete 함 //printf("s_pte_clear vaddr %p, pid %d\n", va, pid); lock_acquire(&s_pt_lock); struct s_pte *entry = find_entry(va, pid); ASSERT (entry != NULL); entry->paddr = NULL; list_remove(&entry->elem); list_push_front(&s_page_table, &entry->elem); lock_release(&s_pt_lock); //frame table에서 해당 frame에 대한 mapping제거 } /* from page_fault() 1. find the page entry that is not in physical memory now */ void * find_s_pte (void *vaddr, tid_t pid) { /* va, pid를 가진 s_pagetable entry를 찾아서 (entry의 paddr == NULL 이면 메모리에 남은 자리가 있는지 보고 uint32_t free_frame = get_free_frame() ( 이 함수 안에서 free frame없으면 알아서 swap out까지 해서 빈 프레임 넘겨줌 ) 위 함수 통과하면 free_frame은 빈 주소 swap in(free_frame, va, pid)해야해 -> swaptable이 va, pid가지고 해당 disksector찾아) */ //printf("find_s_pte\n"); lock_acquire(&evict_lock); lock_acquire(&s_pt_lock); struct s_pte *entry = find_entry(vaddr, pid); if( entry == NULL) { lock_release(&s_pt_lock); lock_release(&evict_lock); return NULL; } if (entry->paddr == NULL) //swap out된 경우 { lock_release(&s_pt_lock); void *free_frame = get_free_frame(); //if memory full -> swap out struct process *p = find_process(pid); if (p == NULL || p->thread->pagedir ==NULL) { lock_release(&evict_lock); return NULL; } uint32_t *pd; pd = p->thread->pagedir; bool writable; /* lazy loading & mmap */ if (entry->mmap_id >0) { //printf("mmap_id : %d\n", entry->mmap_id); struct mapping * map = find_mapping_id(&p->mapping_list, entry->mmap_id); ASSERT(map !=NULL); struct fte * fte_; fte_ = find_fte(&map->file_table, vaddr); ASSERT(fte_ != NULL); struct file * f = map->file; ASSERT(map->file != NULL); //printf("free frame %p, fte size : %d, ofs : %d\n", free_frame, fte_->size, fte_->ofs); int re =file_read_at(f, ptov(free_frame), fte_->size, fte_->ofs); //printf("re : %d\n", re); memset(ptov(free_frame) + fte_->size, 0, PGSIZE-fte_->size); writable = fte_->writable; } else if (entry->is_exec) { struct fte * fte_; fte_ = find_fte(&p->load_file_table, entry->vaddr); struct file * f = p->exec_file; file_read_at(f, ptov(free_frame), fte_->size, fte_->ofs); memset(ptov(free_frame) + fte_->size, 0, PGSIZE-fte_->size); writable = fte_->writable; } else { //printf("swap in\n"); swap_in(free_frame, vaddr, pid); writable = pagedir_is_writable(pd, vaddr); } pagedir_set_page (pd, vaddr, ptov(free_frame), writable, entry->mmap_id); lock_release(&evict_lock); return vaddr; } else{ printf(" find spte entry paddr : %p, vaddr : %p, pid :%d\n", entry->paddr, entry->vaddr, entry->pid); lock_release(&evict_lock); ASSERT(0); printf("find_s_pte FAIL\n"); find_process(pid)->exit_status = -1; thread_exit(); return NULL; } } /* find a victim frmae with FIFO algorithm. called within lock */ struct s_pte * get_victim (void) { //printf("get_victim\n"); struct s_pte *pte; lock_acquire(&s_pt_lock); pte = list_entry(list_back(&s_page_table), struct s_pte, elem); /* page linear - don't swap out stack space */ while (pte->paddr == NULL && find_process(pte->pid) != NULL){ //ASSERT(find_process(pte->pid)); //ASSERT(!find_process(pte->pid)->is_dead); list_remove(&pte->elem); list_push_front(&s_page_table, &pte->elem); pte = list_entry(list_back(&s_page_table), struct s_pte, elem); } lock_release(&s_pt_lock); //printf("victim vaddr : %p, paddr : %p, tid : %d\n", pte->vaddr, pte->paddr, pte->pid); return pte; } struct s_pte * find_entry (void *vaddr, tid_t pid) { struct list_elem *e; struct s_pte* pte; for(e = list_begin(&s_page_table); e!= list_end(&s_page_table); e = list_next(e)){ pte = list_entry(e, struct s_pte, elem); if (pte->pid == pid && pte->vaddr == vaddr){ return pte; } } return NULL; // no entry found } void free_s_pte_process(tid_t pid) { struct list_elem *e; lock_acquire(&s_pt_lock); e = list_begin(&s_page_table); while (e!= list_end(&s_page_table)) { struct s_pte* pte; pte = list_entry(e, struct s_pte, elem); ASSERT(e!= list_end(&s_page_table)); e = list_next(e); if (pte->pid == pid){ void * vaddr = pte->vaddr; list_remove(&pte->elem); free(pte); //free_frame_entry(vaddr, pid); } } lock_release(&s_pt_lock); } /* when process terminate -> free entries in s_pt too */
C
#include<stdio.h> #include<conio.h> void main() { int n; clrscr(); printf("enter the no"); scanf("%d",&n); if(n>0) { printf("the no is positive"); } else if(n=0) { printf("the no is zero"); } else { printf("the no is negative"); } getch(); }
C
#include "s3.h" /* prototype */ void getInput(char *instr); void cmdToChild(int fd_toC[][2], char *instr); void toChild(int fd_toC[][2], char *instr); void test(int fd_toC[][2], int i);//to be deleted char report_filename[100]; void analyzer(); float scoring(char *filename); /* global variable */ int fd_toC[CHILD_NUM][2], fd_toP[CHILD_NUM][2]; /* main */ int main(int argc, char *argv[]) { int pid, i; // create pipes for (i = 0; i < CHILD_NUM; i++) { if (pipe(fd_toC[i]) < 0 || pipe(fd_toP[i]) < 0) { printf("Pipe creation error\n"); exit(1); } } // create child processes for (i = 0; i < CHILD_NUM; i++) { pid = fork(); if (pid < 0) { printf("Fork failed\n"); exit(1); } if (pid == 0) { // child process close(fd_toC[i][1]); close(fd_toP[i][0]); int n=0; char str[100]; bool parsed = false; while ((n = read(fd_toC[i][0],str,BUF_SIZE)) > 0) { str[n] = '\n'; str[n+1] = 0; write(fd_toP[i][1],"O",1); /* ACK message */ if (strncmp(str,"run",3) == 0 && parsed == false) { parsed = true; parse(); } if (strcmp(str,"run ddl\n") == 0) { create_scheduler(DDL_FIGHTER); continue; } else if (strcmp(str,"run rr\n") == 0) { create_scheduler(RR); continue; } else if (strcmp(str,"run pr\n") == 0) { create_scheduler(PR); continue; } else if (strcmp(str,"run all\n") == 0) { create_scheduler(ALL); continue; } else if (strcmp(str, "analyze\n") == 0) { analyzer(); continue; } else if (strcmp(str,"exitS3\n") == 0) { printf("Parser Exited!\n"); exit(0); } /* Increment event_counter only if NOT run command */ strcpy(command[event_counter++],str); } close(fd_toC[i][0]); close(fd_toP[i][1]); exit(0); } } if (pid > 0) { // parent process for (i = 0; i < CHILD_NUM; i++) { close(fd_toC[i][0]); close(fd_toP[i][1]); } printf("\t~~WELCOME TO S3~~\n"); char instr[BUF_SIZE]; while (1) { getInput(instr); cmdToChild(fd_toC, instr); if (strcmp(instr, "exitS3") == 0) break; } printf("Bye-bye!\n"); for (i = 0; i < CHILD_NUM; i++) { close(fd_toC[i][1]); close(fd_toP[i][0]); } } // wait for all child processes for (i = 0; i < CHILD_NUM; i++) wait(NULL); return 0; } /* input function: scan input command */ void getInput(char *instr) { printf("Please enter:\n> "); scanf("%[^\n]", instr); // scan the whole input line getchar(); } void sync() { char temp[10]; for (int i = 0; i < CHILD_NUM; ++i) read(fd_toP[i][0],temp,1); } /* cmdToChild function: pass all inputed command to children */ void cmdToChild(int fd_toC[][2], char *instr) { if (strncmp(instr, "addBatch", 8) != 0) { toChild(fd_toC, instr); sync(); } else { // if the command is "addBatch ...", read file FILE *fp; char *filename = (char*) malloc(strlen(instr)-9+1); strcpy(filename, instr+9); fp = fopen(filename, "r"); if (fp == NULL) { printf("Cannot open the file!\n"); exit(1); } while(fscanf(fp, "%[^\n]\n", instr) != EOF) { //while( fgets (instr, BUF_SIZE, fp) != NULL ) { toChild(fd_toC, instr); int i = 0; sync(); } fclose(fp); free(filename); } } /* toChild function: pass a command to all children */ void toChild(int fd_toC[][2], char *instr) { for (int i = 0; i < CHILD_NUM; i++) write(fd_toC[i][1], instr, strlen(instr)); } //to be deleted void test(int fd_toC[][2], int i) { int n; char buf[BUF_SIZE]; while ((n = read(fd_toC[i][0], buf, BUF_SIZE)) > 0) { // read from pipe buf[n] = 0; printf("<Child %d> message [%s] received of %d bytes\n", getpid(), buf, n); if (buf[0] == 'e') break; } }
C
#ifndef GRID_H #define GRID_H #include <stdlib.h> #include <stdio.h> #include <string.h> #define LAST_ELMT -1 #define CONSTRAINT_SIZE 2 #define NB_OPERATORS 4 typedef enum { ROW_INDEX, COL_INDEX, CELL_SZ } index_cell; typedef enum { PLUS, MINUS, TIMES, DIV, EQ } operation_t; typedef struct { size_t target; operation_t op; } constraint_t; int find_max(int * data_constraint); size_t sum_constr(int * data_constraint); int prod_constr(int * data_constraint); int diff_constr(int * data_constraint); double div_constr(int * data_constraint); typedef struct { size_t dim; size_t *rooms; size_t nb_constraints; constraint_t *constraints; } grid_t; void init_grid(grid_t *grid, size_t dim); void init_constraints(grid_t *grid); void fill_grid_line(size_t row, size_t *buffer, grid_t *grid); size_t get_constraint_pos(grid_t grid, int ** data_constraint, size_t constraint_id); typedef struct { size_t *board; grid_t data; } completed_grid_t; size_t get_constraint_val(completed_grid_t grid, int ** data_constraint, size_t constraint_id); #endif
C
#include "../utility.h" /** * 函数名:r_chol * 功能描述:对称正定实矩阵的Cholesky分解 * 输入参数:mat 指向待分解 * 返回值的矩阵的指针 n 矩阵阶数 u 指向返回的下三角阵的指针 eps 精度要求,小于此值的数据认为是0 * 返回值:整型。运行成功则返回1,失败则返回0 */ int r_chol(double *mat,int n,double *u,double eps) { int i,j,k; double t; if((mat==NULL)||(u==NULL)) /* 检测指针是否为空*/ { printf("One of the pointer is NULL\n"); /* 若为空则打印错误消息,函数结束*/ return 0; } for(i=0; i<n; i++) /* 将u矩阵赋初值为零矩阵*/ { for(j=0; j<n; j++) { u[i*n+j] = 0.0; } } if(fabs(mat[0]) < eps) /* 因要做除数并开根号,需要检查其范围*/ { printf("Failed.\n"); return 0; } u[0] = sqrt(mat[0]); /* 递推求解*/ for(i=1; i<n; i++) { for(j=0; j<i; j++) { t = 0.0; for(k=0; k<j; k++) /* 求解U[i,j]中的求和部分*/ { t = t+u[i*n+k]*u[j*n+k]; } u[i*n+j] = (mat[i*n+j]-t)/u[j*n+j]; /* 求解U[i,j]*/ } t = 0.0; for(k=0; k<i; k++) { t = t+u[i*n+k]*u[i*n+k]; } t = mat[i*n+i]-t; if(t < eps) /* 检查其范围*/ { printf("Failed.\n"); return 0; } u[i*n+i] = sqrt(t); /* 求解U[i,i]*/ } return 1; }
C
#include <stdio.h> #include <stdlib.h> int main(void) { int x = 0; int *intptr = NULL; int *intptr1; int *intptr2; intptr1 = &x; intptr2 = intptr1; int intarray[] = {3, 5, 7, 9}; intptr = intarray; printf("The value at intptr: %i\n", *intptr); printf("The value at intptr + 1: %i\n", intptr[1]); printf("The value at intptr + 2: %i\n", *(intptr + 2)); intptr = intptr + 1; ++intptr; printf("The value at intptr: %i\n", *intptr); return 0; }
C
#include <cs50.h> #include <stdio.h> #define N 25 int main(void) { // declare the array, and store the first two values int fibo[N]; fibo[0] = 0; fibo[1] = 1; // calculate and store the next 23 values for (int i = 2; i < N; i++) { fibo[i] = fibo[i - 1] + fibo[i - 2]; } // print the entire series printf("The first 25 numbers in the Fibonacci series are: \n"); for (int i = 0; i < N; i++) { printf("%i ", fibo[i]); } printf("\n"); }
C
#include <avr/io.h> #include <util/delay.h> #define BLINK_DELAY_ON_MS 1000 #define BLINK_DELAY_OFF_MS 700 int turn5OnQuicklyAndWait() { /* turn it back on */ PORTB |= _BV(PORTB5); _delay_ms(200); } int turn5OffQuicklyAndWait() { // turn it back off quickly PORTB &= ~_BV(PORTB5); _delay_ms(200); } int main(void) { /* set pin 5 of PORTB for output*/ DDRB |= _BV(DDB5); while (1) { /* set pin 5 high to turn led on */ PORTB |= _BV(PORTB5); _delay_ms(BLINK_DELAY_ON_MS); /* set pin 5 low to turn led off */ PORTB &= ~_BV(PORTB5); _delay_ms(BLINK_DELAY_OFF_MS); // blink it a bunch of times for (int i = 0; i < 20; i++) { turn5OnQuicklyAndWait(); turn5OffQuicklyAndWait(); } } }