language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include "libimap.h" #define ORIG_EXT(type) \ ORIG(&e, \ E_PARAM, \ "%x extension for IMAP is not available", \ FD(extension_token(type)) \ ) static const extension_state_e *const_extension_find( const extensions_t *exts, extension_e type ){ switch(type){ case EXT_UIDPLUS: return &exts->uidplus; case EXT_ENABLE: return &exts->enable; case EXT_CONDSTORE: return &exts->condstore; case EXT_QRESYNC: return &exts->qresync; case EXT_UNSELECT: return &exts->unselect; case EXT_IDLE: return &exts->idle; case EXT_XKEY: return &exts->xkey; } LOG_FATAL("invalid extension type"); } static extension_state_e *extension_find( extensions_t *exts, extension_e type ){ switch(type){ case EXT_UIDPLUS: return &exts->uidplus; case EXT_ENABLE: return &exts->enable; case EXT_CONDSTORE: return &exts->condstore; case EXT_QRESYNC: return &exts->qresync; case EXT_UNSELECT: return &exts->unselect; case EXT_IDLE: return &exts->idle; case EXT_XKEY: return &exts->xkey; } LOG_FATAL("invalid extension type"); } bool extension_is_on(const extensions_t *exts, extension_e type){ const extension_state_e *state = const_extension_find(exts, type); return *state == EXT_STATE_ON; } // throw an error if an action requires an extension to be enabled derr_t extension_assert_on(const extensions_t *exts, extension_e type){ derr_t e = E_OK; if(!extension_is_on(exts, type)) ORIG_EXT(type); return e; } // same as above but in a builder-friendly signature void extension_assert_on_builder(derr_t *e, const extensions_t *exts, extension_e type){ IF_PROP(e, extension_assert_on(exts, type)){} } bool extension_is_available(const extensions_t *exts, extension_e type){ const extension_state_e *state = const_extension_find(exts, type); return *state != EXT_STATE_DISABLED; } // throw an error if an action requires an extension to be available derr_t extension_assert_available(const extensions_t *exts, extension_e type){ derr_t e = E_OK; if(!extension_is_available(exts, type)) ORIG_EXT(type); return e; } void extension_assert_available_builder( derr_t *e, extensions_t *exts, extension_e type ){ IF_PROP(e, extension_assert_available(exts, type)){} } // set an extension to "on" and return true, or return false if it is disabled bool extension_trigger(extensions_t *exts, extension_e type){ extension_state_e *state = extension_find(exts, type); if(*state == EXT_STATE_DISABLED) return false; *state = EXT_STATE_ON; return true; } DSTR_STATIC(EXT_UIDPLUS_dstr, "UIDPLUS"); DSTR_STATIC(EXT_ENABLE_dstr, "ENABLE"); DSTR_STATIC(EXT_CONDSTORE_dstr, "CONDSTORE"); DSTR_STATIC(EXT_QRESYNC_dstr, "QRESYNC"); DSTR_STATIC(EXT_UNSELECT_dstr, "UNSELECT"); DSTR_STATIC(EXT_IDLE_dstr, "IDLE"); DSTR_STATIC(EXT_XKEY_dstr, "XKEY"); DSTR_STATIC(EXT_unknown_dstr, "unknown"); dstr_t extension_token(extension_e ext){ switch(ext){ case EXT_UIDPLUS: return EXT_UIDPLUS_dstr; case EXT_ENABLE: return EXT_ENABLE_dstr; case EXT_CONDSTORE: return EXT_CONDSTORE_dstr; case EXT_QRESYNC: return EXT_QRESYNC_dstr; case EXT_UNSELECT: return EXT_UNSELECT_dstr; case EXT_IDLE: return EXT_IDLE_dstr; case EXT_XKEY: return EXT_XKEY_dstr; } return EXT_unknown_dstr; } const char *extension_msg(extension_e ext){ switch(ext){ case EXT_UIDPLUS: return "UIDPLUS extension not available"; case EXT_ENABLE: return "ENABLE extension not available"; case EXT_CONDSTORE: return "CONDSTORE extension not available"; case EXT_QRESYNC: return "QRESYNC extension not available"; case EXT_UNSELECT: return "UNSELECT extension not available"; case EXT_IDLE: return "IDLE extension not available"; case EXT_XKEY: return "XKEY extension not available"; } LOG_FATAL("invalid extension type"); }
C
#include <stdio.h> #include <string.h> int main() { int i; char name[20], password[20], ch; printf("Enter your username"); scanf("%s", &name); printf("Enter your password"); for (i = 0; i < 8; i++) { ch = getchar(); password[i+1] = ch; ch = '*' ; printf("%c", ch); } password[i] = '\0'; printf("Username is %s",name); }
C
#include "c101_Total.h" #include "c101_Subunit.h" #include "c101_Visit.h" static int totalVisitor(enum c101_VisitorType type, void* unit, void* out) { if (type == C101_EMPLOYEE) *(double*) out += ((struct c101_Employee*) unit)->salary; return 0; } double c101_total(struct c101_Company* c) { double out = 0.0; c101_visitCompany(c, &out, totalVisitor); return out; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_list_clear.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: bbaatar <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/05/06 14:35:11 by bbaatar #+# #+# */ /* Updated: 2021/05/09 18:35:20 by bbaatar ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include <unistd.h> #include "ft_list.h" #include <stdio.h> t_list *ft_create_elem(void *data); void f(void *data) { printf("%s\n", (char *)data); } int ft_strcmp(void *data, void *data_ref) { char *s1 = (char *)data; char *s2 = (char *)data_ref; int i; i = 0; while (s1[i] == s2[i] && s1[i] != '\0' && s2[i] != '\0') i++; return (s1[i] - s2[i]); } void ft_list_foreach_if(t_list *begin_list, void (*f)(void *), void *data_ref, int (*ft_strcmp)()) { t_list *current; current = begin_list; while (current) { if (ft_strcmp(current->data, data_ref) == 0) f(current->data); current = current->next; } } int main(void) { char *data1 = "One"; char *data2 = "two"; char *data3 = "three"; t_list *head = NULL; head = ft_create_elem((void *)data1); head->next = ft_create_elem((void *)data2); head->next->next = ft_create_elem((void *)data3); head->next->next->next = NULL; ft_list_foreach_if(head, (*f), "two", (*ft_strcmp)); return (0); }
C
/*************************************************** > Copyright (C) 2017 ==HEBOWEN== All rights reserved. > File Name: charu.c > Author: hebowen > Mail:982034166@qq.com > Created Time: 2017年06月29日 星期四 19时14分44秒 ***************************************************/ #include <stdio.h> #define MAX sizeof(a)/sizeof(a[0]) int insert_sort(int a[],int size) { int t = 0,i = 0,j = 0; for(i = 1;i < size;i++) { t = a[i]; for(j = i;((j > 0) && (a[j-1] > t));j--) { a[j] = a[j-1]; } a[j] = t; } } int main(int argc,const char* argv[]) { int i = 0; int a[] = {50,36,66,76,95,12,25,36}; insert_sort(a,MAX); for(i = 0;i < MAX;i++) printf("%d ",a[i]); printf("\n"); return 0; }
C
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { float ph; scanf("%f", &ph); if((ph >=0) && (ph <=14)){ if(ph == 7){ printf("Neutra"); } else if(ph < 7){ printf("Acida"); } else { printf("Basica"); } } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* map_parcing.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vmazurok <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/08/19 18:29:02 by vmazurok #+# #+# */ /* Updated: 2019/01/23 12:24:18 by vmazurok ### ########.fr */ /* */ /* ************************************************************************** */ #include "graphics.h" static int to_the_next_number(char *line, int i) { while (line[i] && ft_isdigit(line[i])) i++; if (line[i] && line[i] > 32) error_hendler(&line, 0); while (line[i] && line[i] < 33) i++; return (i); } static void parce_two_numbers(int fd, double *x, double *y) { int i; char *line; i = 0; get_next_line(fd, &line); while (line[i] && line[i] < 33) i++; *x = ft_atoi(line + i); i = to_the_next_number(line, i); *y = ft_atoi(line + i); i = to_the_next_number(line, i); if (*x == 0 || *y == 0 || line[i]) error_hendler(&line, 1); free(line); } static void parce_line(int *map_line, char *line, double width) { int j; int k; j = 0; k = 0; while (j < width) { while (line[k] && line[k] < 33) k++; map_line[j] = ft_atoi(line + k); while (line[k] && ft_isdigit(line[k])) k++; if (line[k] && line[k] > 32) error_hendler(&line, 0); j++; if (!line[k] && j != width) error_hendler(&line, 2); while (j == width && line[k] && line[k] < 33) k++; if (j == width && line[k]) error_hendler(&line, 3); } } static void evaluate_map(t_graphix *gfx) { int j; int i; i = -1; while (++i < gfx->map_h) { j = -1; while (++j < gfx->map_w) if ((i == 0 || i == gfx->map_h - 1 || j == 0 || j == gfx->map_w - 1) && gfx->map[i][j] == 0) error_hendler(NULL, 4); } if (gfx->map[(int)gfx->player.pos_x][(int)gfx->player.pos_y] != 0) error_hendler(NULL, 5); } void map_parsing(char *file_name, t_graphix *gfx) { int fd; char *line; int i; if (((fd = open(file_name, O_RDONLY)) == -1) || (read(fd, NULL, 0) == -1)) { perror("Error"); exit(1); } parce_two_numbers(fd, &(gfx->map_w), &(gfx->map_h)); parce_two_numbers(fd, &(gfx->player.pos_x), &(gfx->player.pos_y)); gfx->map = (int **)malloc(sizeof(int*) * (int)gfx->map_h); i = -1; while (++i < gfx->map_h) { if (get_next_line(fd, &line) == 0) error_hendler(&line, 2); gfx->map[i] = (int *)malloc(sizeof(int) * (int)gfx->map_w); parce_line(gfx->map[i], line, gfx->map_w); free(line); } if (get_next_line(fd, &line) != 0) error_hendler(&line, 3); evaluate_map(gfx); }
C
/* * opens a file in the current directoy by name * and returns its contents as an unsigned char * */ int server::get_file_128(char filename[], char * contents, int offset) { // check if there are 16bytes left in file int filesize = get_filesize(filename); if(filesize < 0) return -1; int remaining = filesize - offset; int chunk_size; int last = 0; // CRYPTCHANGE // if(remaining > DATA_SIZE) { chunk_size = DATA_SIZE; } else { chunk_size = remaining; last = 1; } // create and open file FILE *fptr; fptr = fopen(filename, "r"); if(!fptr) { printf("File opening failed\n"); exit(EXIT_FAILURE); } fseek(fptr, offset, SEEK_SET); // use size to allocate memory to // file buffer int status = fread(contents, sizeof(char), chunk_size, fptr); contents[LENGTH_INDEX] = chunk_size; contents[LAST_INDEX] = last; // close file fclose(fptr); return status; } int server::write_file(char filename[], char * contents, int length, int total_written) { int status; // create and open file FILE *fptr; fptr = fopen(filename, "a"); if(!fptr || total_written == 0) { if(total_written == 0) fclose(fptr); fptr = fopen(filename, "w"); if(!fptr) { printf("File opening failed\n"); exit(EXIT_FAILURE); } } //fseek(fptr, offset, SEEK_SET); // use size to allocate memory to // file buffer status = fwrite(contents, sizeof(char), length, fptr); // close file fclose(fptr); return status; } int server::get_filesize(char filename[]) { // create and open file FILE *fptr; fptr = fopen(filename, "r"); if(!fptr) { return -1; } fseek(fptr, 0, SEEK_END); int sz = ftell(fptr); fclose(fptr); return sz; }
C
/** * OS Assignment #1 **/ #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <signal.h> #include <ctype.h> #include <errno.h> #include <sys/wait.h> #include <sys/signalfd.h> #define MSG(x...) fprintf (stderr, x) #define STRERROR strerror (errno) #define ID_MIN 2 #define ID_MAX 8 #define COMMAND_LEN 256 typedef enum { ACTION_ONCE, // one time ACTION_RESPAWN, // repeat } Action; typedef struct _Task Task; struct _Task { Task *next; // next task volatile pid_t pid; int piped; int pipe_a[2]; int pipe_b[2]; char id[ID_MAX + 1]; // id char pipe_id[ID_MAX + 1]; // pipe id int order; // order Action action; // action char command[COMMAND_LEN]; // command }; static Task *tasks; // tasks static volatile int running; static int pid_for_non_order; static char *strstrip (char *str) // delete space { char *start; size_t len; len = strlen (str); while (len--) { if (!isspace (str[len])) break; str[len] = '\0'; } for (start = str; *start && isspace (*start); start++) ; memmove (str, start, strlen (start) + 1); return str; } static int check_valid_id (const char *str) // id check { size_t len; int i; len = strlen (str); if (len < ID_MIN || ID_MAX < len) return -1; for (i = 0; i < len; i++) if (!(islower (str[i]) || isdigit (str[i]))) return -1; return 0; } static Task * lookup_task (const char *id) // find task by id { Task *task; for (task = tasks; task != NULL; task = task->next){ if (!strcmp (task->id, id)) return task; } return NULL; } static Task * lookup_task_by_pid (pid_t pid) // find task by pid { Task *task; for (task = tasks; task != NULL; task = task->next) if (task->pid == pid) return task; return NULL; } static void print_tasks() // print tasks for check order { MSG("[%s]\n",__func__ ); Task * tp = tasks; // print tasks after tp while(1){ MSG("(id: %-10s, action: %d, pipe-id: %-10s, order= %-3d)\n", tp->id, tp->action, tp->pipe_id, tp->order); if(tp->next == NULL){ break; } else{ // MSG("(id: %-10s, action: %d, pipe-id: %-10s, order= %-3d)\n", tp->id, tp->action, tp->pipe_id, tp->order); tp = tp->next; } } MSG("\n\n"); } static void append_task (Task *task) // append task by order { Task * new_task; new_task = malloc (sizeof (Task)); // task 저장할 메모리 할당 if (!new_task) { MSG ("failed to allocate a task: %s\n", STRERROR); return; } *new_task = *task; // new task에 task 내용을 저장 new_task->next = NULL; // next는 우선 없도록 저장 if (tasks == NULL) // task가 하나도 없는 경우 tasks = new_task; else { Task *tp; Task * prev_tp; tp = tasks; while(tp!= NULL){ if(tp->order <= new_task->order){ prev_tp = tp; tp = tp->next; }else{ break; } } // insert task by non descent order new_task->next = prev_tp->next; prev_tp ->next = new_task; } print_tasks(); } static void print_sp(char *ele, char* s, char* p){ // MSG("***%s in line[%d]\n s:[%s] p:[%s]\n\n",ele, __LINE__, s, p); } static int read_config (const char *filename) { FILE *fp; char line[COMMAND_LEN * 2]; int line_nr; fp = fopen (filename, "r"); if (!fp) return -1; tasks = NULL; line_nr = 0; while (fgets (line, sizeof (line), fp)) { Task task; char *p; char *s; size_t len; line_nr++; memset (&task, 0x00, sizeof (task)); // task data init all 0 len = strlen (line); if (line[len - 1] == '\n') line[len - 1] = '\0'; if (0) MSG ("config[%3d] %s\n", line_nr, line); strstrip (line); /* comment or empty line */ if (line[0] == '#' || line[0] == '\0') continue; /* id */ // -----parsing pattern start ----------- s = line; p = strchr (s, ':'); print_sp("id",s,p); if (!p) goto invalid_line; *p = '\0'; // ':' -> '\n' results "id\0action..." strstrip (s); print_sp("id",s,p); // -----parsing pattern end --------- if (check_valid_id (s)) { MSG ("invalid id '%s' in line %d, ignored\n", s, line_nr); continue; } if (lookup_task (s)) { MSG ("duplicate id '%s' in line %d, ignored\n", s, line_nr); continue; } strcpy (task.id, s); /* action */ // parsing pattern by ':' s = p + 1; p = strchr (s, ':'); print_sp("action",s,p); if (!p) goto invalid_line; *p = '\0'; strstrip (s); print_sp("action",s,p); //----------------------- if (!strcasecmp (s, "once")) task.action = ACTION_ONCE; else if (!strcasecmp (s, "respawn")) task.action = ACTION_RESPAWN; else { MSG ("invalid action '%s' in line %d, ignored\n", s, line_nr); continue; } /* order */ s = p + 1; p = strchr(s, ':'); print_sp("order",s,p); if(!p) goto invalid_line; *p = '\0'; strstrip(s); print_sp("order",s,p); // if(s[0]=='\0') // MSG("s is NULL"); if(s[0] == '\0'){ task.order = pid_for_non_order++; }else if(atoi(s)){ if(strlen(s) >4){ MSG ("invalid order '%s' in line %d, ignored\n", s, line_nr); continue; } task.order = atoi(s); }else{ MSG ("invalid order '%s' in line %d, ignored\n", s, line_nr); continue; } /* pipe-id */ s = p + 1; p = strchr (s, ':'); if (!p) goto invalid_line; *p = '\0'; strstrip (s); if (s[0] != '\0') { Task *t; if (check_valid_id (s)) { MSG ("invalid pipe-id '%s' in line %d, ignored\n", s, line_nr); continue; } t = lookup_task (s); if (!t) { MSG ("unknown pipe-id '%s' in line %d, ignored\n", s, line_nr); continue; } if (task.action == ACTION_RESPAWN || t->action == ACTION_RESPAWN) { MSG ("pipe not allowed for 'respawn' tasks in line %d, ignored\n", line_nr); continue; } if (t->piped) { MSG ("pipe not allowed for already piped tasks in line %d, ignored\n", line_nr); continue; } strcpy (task.pipe_id, s); task.piped = 1; t->piped = 1; } /* command */ s = p + 1; strstrip (s); if (s[0] == '\0') { MSG ("empty command in line %d, ignored\n", line_nr); continue; } strncpy (task.command, s, sizeof (task.command) - 1); task.command[sizeof (task.command) - 1] = '\0'; if (0) MSG ("id:%s pipe-id:%s action:%d command:%s\n", task.id, task.pipe_id, task.action, task.command); append_task (&task); continue; invalid_line: MSG ("invalid format in line %d, ignored\n", line_nr); } fclose (fp); return 0; } static char ** make_command_argv (const char *str) { char **argv; const char *p; int n; for (n = 0, p = str; p != NULL; n++) { char *s; s = strchr (p, ' '); if (!s) break; p = s + 1; } n++; argv = calloc (sizeof (char *), n + 1); if (!argv) { MSG ("failed to allocate a command vector: %s\n", STRERROR); return NULL; } for (n = 0, p = str; p != NULL; n++) { char *s; s = strchr (p, ' '); if (!s) break; argv[n] = strndup (p, s - p); p = s + 1; } argv[n] = strdup (p); if (0) { MSG ("command:%s\n", str); for (n = 0; argv[n] != NULL; n++) MSG (" argv[%d]:%s\n", n, argv[n]); } return argv; } static void spawn_task (Task *task) { if (0) MSG ("spawn program '%s'...\n", task->id); if (task->piped && task->pipe_id[0] == '\0') { if (pipe (task->pipe_a)) { task->piped = 0; MSG ("failed to pipe() for prgoram '%s': %s\n", task->id, STRERROR); } if (pipe (task->pipe_b)) { task->piped = 0; MSG ("failed to pipe() for prgoram '%s': %s\n", task->id, STRERROR); } } task->pid = fork (); if (task->pid < 0) { MSG ("failed to fork() for program '%s': %s\n", task->id, STRERROR); return; } /* child process */ if (task->pid == 0) { char **argv; argv = make_command_argv (task->command); if (!argv || !argv[0]) { MSG ("failed to parse command '%s'\n", task->command); exit (-1); } if (task->piped) { if (task->pipe_id[0] == '\0') { dup2 (task->pipe_a[1], 1); dup2 (task->pipe_b[0], 0); close (task->pipe_a[0]); close (task->pipe_a[1]); close (task->pipe_b[0]); close (task->pipe_b[1]); } else { Task *sibling; sibling = lookup_task (task->pipe_id); if (sibling && sibling->piped) { dup2 (sibling->pipe_a[0], 0); dup2 (sibling->pipe_b[1], 1); close (sibling->pipe_a[0]); close (sibling->pipe_a[1]); close (sibling->pipe_b[0]); close (sibling->pipe_b[1]); } } } execvp (argv[0], argv); MSG ("failed to execute command '%s': %s\n", task->command, STRERROR); exit (-1); } } static void spawn_tasks (void) { Task *task; for (task = tasks; task != NULL && running; task = task->next) spawn_task (task); } static void wait_for_children (int signo) { Task *task; pid_t pid; rewait: pid = waitpid (-1, NULL, WNOHANG); if (pid <= 0) return; task = lookup_task_by_pid (pid); if (!task) { MSG ("unknown pid %d", pid); return; } if (0) MSG ("program[%s] terminated\n", task->id); if (running && task->action == ACTION_RESPAWN) spawn_task (task); else task->pid = 0; /* some SIGCHLD signals is lost... */ goto rewait; } static void terminate_children (int signo) { Task *task; if (1) MSG ("terminated by SIGNAL(%d)\n", signo); running = 0; for (task = tasks; task != NULL; task = task->next) if (task->pid > 0) { if (0) MSG ("kill program[%s] by SIGNAL(%d)\n", task->id, signo); kill (task->pid, signo); } exit (1); } int main (int argc, char **argv) { struct sigaction sa; int terminated; int sfd; unsigned int signo; sigset_t mask; // config.txt file checking if (argc <= 1) { MSG ("usage: %s config-file\n", argv[0]); return -1; } // config.txt load check if (read_config (argv[1])) { MSG ("failed to load config file '%s': %s\n", argv[1], STRERROR); return -1; } pid_for_non_order = getpid(); sigemptyset(&mask); sigaddset(&mask, SIGCHLD); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGTERM); // block 할 signal들 세팅 if(sigprocmask(SIG_BLOCK, &mask, NULL) < 0 ) { perror("sigprocmask() error\n\n\n"); return -1; } // call signalfd sfd = signalfd(-1, &mask, 0); if(sfd < 0){ perror("signalfd() error\n\n\n"); return -1; } running = 1; spawn_tasks (); while(terminated == 0){ Task * task; struct signalfd_siginfo sfd_info; read(sfd, &sfd_info, sizeof(sfd_info)); signo = sfd_info.ssi_signo; if(signo == SIGCHLD) { wait_for_children(signo); }else if(signo == SIGINT){ terminate_children(SIGINT); }else if(signo == SIGTERM){ terminate_children(SIGTERM); }else{ MSG("read signal : %d\n",signo); } terminated = 1; for(task = tasks; task!= NULL; task = task->next){ if(task->pid>0) { terminated = 0; break; } } usleep(200000); } /* sigemptyset (&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = terminate_children; if (sigaction (SIGINT, &sa, NULL)) MSG ("failed to register signal handler for SIGINT\n"); sigemptyset (&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = terminate_children; if (sigaction (SIGTERM, &sa, NULL)) MSG ("failed to register signal handler for SIGINT\n"); terminated = 0; while (!terminated) { Task *task; terminated = 1; for (task = tasks; task != NULL; task = task->next) if (task->pid > 0) { terminated = 0; break; } usleep (100000); } */ return 0; }
C
#include "stdio.h" # define MAXSIZE 10 typedef struct{ int * base; int length; }sqlist ; reverseSQ(sqlist *l){ int low = 0 , high = l->length - 1; int buf , i; for(i=0;i<l->length/2;i++) { buf = l->base[low] ; l->base[low] = l->base[high]; l->base[high] = buf; low++; high--; } } main() { sqlist l; int a , i = 0; /*һ˳*/ l.base = (int *)malloc(sizeof(int)*MAXSIZE); l.length = 0; /**/ printf("Please input below 10 integer into the sqlist\n") ; printf("Type -1 for stopping input\n"); scanf("%d",&a); while(a != -1 && i<=9) { l.base[i] = a; l.length++; i++; scanf("%d",&a); } /*ԭ˳е*/ printf("The contents of the sqlist are\n"); for(i=0;i<l.length;i++) printf("%d ",l.base[i]); printf("\n"); reverseSQ(&l); /*͵˳*/ /*ú˳е*/ printf("The contents of the reversed sqlist are\n"); for(i=0;i<l.length;i++) printf("%d ",l.base[i]); getche(); }
C
#include <stdio.h> #include <stdlib.h> struct frame { int reference, lifespan, pagenumber; struct frame *next; } frame; int main(void) { FILE *f = fopen("input.txt", "r"); int *arr = NULL, i, j, size = 0, fsize = 0, hitrate = 0, missrate = 0; while ((i = fgetc(f)) != EOF) { if (i == ' ') { size += 1; } } size += 1; fclose(f); f = fopen("input.txt", "r"); arr = (int*) calloc(size, sizeof(int)); for (i = 0; i < size; i++) { fscanf(f, "%d", &arr[i]); } printf("The number of page frames: "); scanf("%d", &fsize); struct frame *head = (struct frame*) malloc(sizeof(struct frame)); head->next = NULL; struct frame *frm_a = head; for (i = 0; i < fsize; i++) { frm_a->next = (struct frame*) malloc(sizeof(struct frame)); frm_a->reference = -1; frm_a->lifespan = 0; frm_a->pagenumber = -1; frm_a = frm_a->next; } frm_a->next = NULL; frm_a = head; for (i = 0; i < size; i++) { frm_a = head; struct frame *min = NULL; int is_min = 99999999, is_insert = 0, is_init = 0; while (frm_a->next != NULL) { frm_a->lifespan = frm_a->lifespan >> 1; //printf("arr[%d] = %d\n%d %d %d\n",i , arr[i], frm_a->reference, frm_a->lifespan, frm_a->pagenumber); if (!is_insert) { if (frm_a->reference == -1) { frm_a->pagenumber = arr[i]; frm_a->reference = 1; frm_a->lifespan = 64; is_insert = 1; is_init = 1; } else if (frm_a->pagenumber == arr[i]) { frm_a->reference = 1; frm_a->lifespan = 64 | frm_a->lifespan >> 1; min = frm_a; hitrate += 1; is_insert = 1; } else { frm_a->reference = 0; } if ((frm_a->lifespan < is_min) && !is_insert) { min = frm_a; is_min = frm_a->lifespan; } } frm_a = frm_a->next; } if(min != NULL && !is_init) { min->pagenumber = arr[i]; min->lifespan = 64; missrate += 1; } //printf("\n"); } printf("hitrate = %d\nmissrate = %d\n", hitrate, missrate); return 0; }
C
/*$Id$*/ /** \file * This is the implementation of the reading in of the input string from file or * directly from memory. * * \todo Deal correctly with the path. */ #include "inputStringBuilder.h" #include "inputString-api.h" #include <aterm1.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <rsrc-usage.h> #include <Error-manager.h> /** We got this number by calculating the average number of characters in all * c, java, asf, sdf, tb and idef files in the asfsdf-meta, rscript-meta, * apigen and sdf-apigen packages and their dependencies. */ static const int BUFCHUNK = 10000; static double timeTakenToReadInput = 0.0; /** * Creates an input string from the given string. When creating an input string * from a string (as is done for the toolbus invocation of SGLR) there is no * path. As a result \c _noPath_ is passed in. * * \todo Make toolbus handle \c _noPath_. * * \param string the input string. * * \return the newly created input string. */ InputString IS_createInputStringFromString(const unsigned char *string) { unsigned char *buf = (unsigned char*)strdup((const char *)string); int len = (int)strlen((const char *)string); return IS_allocateString("_noPath_", buf, len); } /** * Creates an input string object from the given string. * * \param path the path to the input string. * \param string the input string. * \param length the length of the input string. * * \return the newly created input string. */ InputString IS_createInputStringFromBytes(const char *path, const unsigned char *string, const int length) { unsigned char *buf = malloc(length * sizeof(char)); memcpy(buf, string, length); return IS_allocateString(path, buf, length); } /** * Reads the input string from a file with the given path and creates an input * string object. * * \param path the path to the input string. * * \return the newly created input string. */ InputString IS_createInputStringFromFile(const char *path) { InputString retval; unsigned char *buf = NULL; size_t curbufsize = 0; size_t bytesRead = BUFCHUNK; FILE *in; int length = 0; ATbool readFromStdin = ATfalse; STATS_Timer(); if (path == NULL || strcmp(path,"") == 0 || strcmp(path,"-") == 0) { in = stdin; readFromStdin = ATtrue; } else { in = fopen(path, "rb"); } if (in == NULL) { ERR_managerStoreError("Can not open file", ERR_makeSubjectListSingle(ERR_makeSubjectSubject(path))); /** \todo Return a proper error (using strerror)! */ return NULL; } while(bytesRead == BUFCHUNK) { curbufsize += BUFCHUNK; buf = realloc(buf, sizeof(unsigned char) * curbufsize); if (buf == NULL) { ATerror("Cannot allocate memory for input string."); } bytesRead = fread(buf+(curbufsize-BUFCHUNK), sizeof(unsigned char), BUFCHUNK, in); } assert(bytesRead != BUFCHUNK && "Not enough memory for end of string."); length = (curbufsize-BUFCHUNK)+bytesRead; if (!readFromStdin) { fclose(in); } retval = IS_allocateString(path, buf, length); timeTakenToReadInput = STATS_Timer(); return retval; } double IS_getTimeTakenToReadInput(void) { return timeTakenToReadInput; }
C
/* Questão1 #include <stdio.h> main() { int numero, quadrado; printf("\nEntre com um numero inteiros nao-nulo: "); scanf("%d", &numero); quadrado = numero * numero; printf("O quadrado do numero %d e %d\n", numero, quadrado); } */ #include <stdio.h> int quadrado(int numero) { return (numero*numero); } int main() { int numero2, quadrado2; printf("\nEntre com um numero inteiros nao-nulo: ");scanf("%d", &numero2); quadrado2 = quadrado(numero2); printf("O quadrado do numero %d e %d\n", numero2, quadrado2); }
C
#include <unistd.h> #include <string.h> #include "./ft_strcpy.c" void ft_putchar(char c) { write(1, &c, 1); } void ft_putstr(char *str) { int i; i = 0; while (str[i] != '\0') { ft_putchar(str[i]); i++; } } int main() { char src[] = "Hello"; char dest[] = "wossdsdsd"; char des[] = "wosdsdsdssd"; ft_putstr((strcpy(des, src))); ft_putchar('\n'); ft_putstr((ft_strcpy(dest, src))); ft_putchar('\n'); return 0; }
C
/** * @file policy.c * @author Bilal Mohamad (bmohama) * * This component is responsible for functionality pertaining to the policy and firewall rules. * It contains features used by the top-level component, fwsim.c, but it should never make * calls to code in fwsim.c. */ #include <stdio.h> #include <stdlib.h> #include "policy.h" /** Array of pointers to dynamically allocated firewall rules. */ static rule_t **policy; /** Size of the array of pointers */ static unsigned int policy_len; /** Capacity of the array of pointers */ static unsigned int policy_cap; /** Default policy */ static unsigned int policy_default; /** * This function will initialize the dynamically allocated policy structure. * * @return 0 if successful, -1 if unsuccessful */ int policy_init() { policy_len = 0; policy_cap = POLICY_INIT_SIZE; policy_default = ACTION_DENY; policy = (rule_t **) malloc(policy_cap * sizeof(rule_t*)); if (policy) { for (int i = 0; i < policy_cap; i++) { policy[i] = NULL; } return 0; } return -1; } /** * This function will free the dynamically allocated policy structure and re-initialize * values as appropriate. */ void policy_free() { for (int i = 0; i < policy_len; i++) { free(policy[i]); } free(policy); } /** * This function will set the default policy to the specified action. * The starter files includes #define's for ACTION_ALLOW and ACTION_DENY. * * @param action the action for the default policy to be set to * * @return 0 if successful, -1 if unsuccessful */ int policy_set_default(int action) { if (action == ACTION_DENY || action == ACTION_ALLOW) { policy_default = action; return 0; } return -1; } /** * This function will append a rule to the policy. * * @param rule the rule to be appended * * @return 0 if successful, -1 if unsuccessful */ int policy_append(rule_t rule) { //TODO Need to check if meets capacity and reallocate if (policy_len >= policy_cap) { policy_cap *= 2; policy = (rule_t **) realloc(policy, policy_cap * sizeof(rule_t *)); if (policy) { for (int i = policy_cap / 2; i < policy_cap; i++) { policy[i] = NULL; } } else { return -1; } } rule_t *temp = (rule_t *) malloc(sizeof(rule_t)); temp->action = rule.action; temp->match.protocol = rule.match.protocol; temp->match.src_ip = rule.match.src_ip; temp->match.src_port = rule.match.src_port; temp->match.dst_ip = rule.match.dst_ip; temp->match.dst_port = rule.match.dst_port; policy[policy_len] = temp; policy_len++; return 0; } /** * This function will insert a rule at position. * * @param rule the rule to be inserted * @param pos the position to be inserted at * * @return 0 if successful, -1 if unsuccessful */ int policy_insert(rule_t rule, int pos) { if (policy_len >= policy_cap) { policy_cap *= 2; policy = (rule_t **) realloc(policy, policy_cap * sizeof(rule_t *)); if (policy) { for (int i = policy_cap / 2; i < policy_cap; i++) { policy[i] = NULL; } } else { return -1; } } if (pos > policy_len) { policy_append(rule); } else { //Shifts all the entries in the array for (int i = policy_len; i > pos - 1; i--) { policy[i] = policy[i - 1]; } rule_t *temp = (rule_t *) malloc(sizeof(rule_t)); temp->action = rule.action; temp->match.protocol = rule.match.protocol; temp->match.src_ip = rule.match.src_ip; temp->match.src_port = rule.match.src_port; temp->match.dst_ip = rule.match.dst_ip; temp->match.dst_port = rule.match.dst_port; policy[pos - 1] = temp; policy_len++; } return 0; } /** * This function will delete the rule at position. * * @param pos the position of the rule * * @return It returns 0 if successful, -1 if unsuccessful. */ int policy_delete(int pos) { if (pos - 1 < 0 || pos - 1 >= policy_len) { return -1; } if (policy[pos - 1] == NULL) { return -1; } rule_t *temp = policy[pos - 1]; free(temp); //Shift everything for (int i = pos - 1; i < policy_len; i++) { policy[i] = policy[i + 1]; } policy[policy_len - 1] = NULL; policy_len--; return 0; } /** * This function will test if @pkt is allowed or denied by the policy. * It returns ACTION_ALLOW or ACTION_DENY. * Additionally the value pointed to by @pos will be updated with the position * number of the rule that is matched. * If no rule is matched, the value will be set to -1. * * @param pkt the packet being tested * @param pos the position containing the value to be updated position of the rule that is matches * * @return It returns 0 if successful, -1 if unsuccessful. */ int policy_test(packet_t pkt, int *pos) { for (int i = 0; i < policy_cap; i++) { if (policy[i] && packet_match(policy[i]->match, pkt) == 1) { *pos = i; return policy[i]->action; } } //No rule is matched *pos = -1; return policy_default; } /** * This function will print to @stream the rule at position @pos. * * @param stream the file stream to print to * @param pos the rule at the position to be printed * * @return It returns 0 if successful and -1 if unsuccessful (e.g., @pos does not exist). */ int policy_print_rule(FILE *stream, int pos) { if (pos - 1 < 0 || pos - 1 >= policy_len) { return -1; } if (!policy[pos - 1]) { return -1; } fprintf(stream, "[%d] ", pos); if (policy[pos - 1]->action == ACTION_DENY) { fprintf(stream, "deny "); } else { fprintf(stream, "allow "); } if (policy[pos - 1]->match.protocol == PROTO_UDP) { fprintf(stream, "udp "); } else { fprintf(stream, "tcp "); } fprintf(stream, "%d.", policy[pos - 1]->match.src_ip.a); fprintf(stream, "%d.", policy[pos - 1]->match.src_ip.b); fprintf(stream, "%d.", policy[pos - 1]->match.src_ip.c); fprintf(stream, "%d:", policy[pos - 1]->match.src_ip.d); if (policy[pos - 1]->match.src_port == MATCH_PORT_ANY) { fprintf(stream, "* "); } else { fprintf(stream, "%d ", policy[pos - 1]->match.src_port); } fprintf(stream, "%d.", policy[pos - 1]->match.dst_ip.a); fprintf(stream, "%d.", policy[pos - 1]->match.dst_ip.b); fprintf(stream, "%d.", policy[pos - 1]->match.dst_ip.c); fprintf(stream, "%d:", policy[pos - 1]->match.dst_ip.d); if (policy[pos - 1]->match.dst_port == MATCH_PORT_ANY) { fprintf(stream, "*\n"); } else { fprintf(stream, "%d \n", policy[pos - 1]->match.dst_port); } return 0; } /** * This function will print the default policy followed by the policy rules in order to @stream. * * @param stream the file stream to print to */ void policy_print(FILE *stream) { fprintf(stream, "default "); if (policy_default == ACTION_DENY) { fprintf(stream, "deny\n"); } else { fprintf(stream, "allow\n"); } int pos = 1; for (int i = 0; i < policy_cap; i++) { if (policy[i]) { fprintf(stream, "[%d] ", pos); if (policy[i]->action == ACTION_DENY) { fprintf(stream, "deny "); } else { fprintf(stream, "allow "); } if (policy[i]->match.protocol == PROTO_UDP) { fprintf(stream, "udp "); } else { fprintf(stream, "tcp "); } fprintf(stream, "%d.", policy[i]->match.src_ip.a); fprintf(stream, "%d.", policy[i]->match.src_ip.b); fprintf(stream, "%d.", policy[i]->match.src_ip.c); fprintf(stream, "%d:", policy[i]->match.src_ip.d); if (policy[i]->match.src_port == MATCH_PORT_ANY) { fprintf(stream, "* "); } else { fprintf(stream, "%d ", policy[i]->match.src_port); } fprintf(stream, "%d.", policy[i]->match.dst_ip.a); fprintf(stream, "%d.", policy[i]->match.dst_ip.b); fprintf(stream, "%d.", policy[i]->match.dst_ip.c); fprintf(stream, "%d:", policy[i]->match.dst_ip.d); if (policy[i]->match.dst_port == MATCH_PORT_ANY) { fprintf(stream, "*\n"); } else { fprintf(stream, "%d \n", policy[i]->match.dst_port); } pos++; } } }
C
#include <stdio.h> void qsort(int[], int, int); void swap(int[], int, int); int main(void) { /* test quicksort here */ int test1[10] = {9, 1, 3, 4, 2, 5, 8, 7, 0, 6}; qsort(test1, 0, 9); for(int i = 0; i < 10; i++) printf(" %d ", test1[i]); return 0; } /* qsort: sort v[left]...v[right] into increasing order */ void qsort(int v[], int left, int right) { int pivot, l, r; if (left >= right) return; /* don't sort arrays < 2 elements */ pivot = left + ((right - left) / 2); l = left; r = right; for(;;) { while (l < r && v[l] < v[pivot]) l++; while (l < r && v[r] > v[pivot]) r--; if (l == r) break; swap(v, l, r); } qsort(v, left, l); qsort(v, l + 1, right); } /* swap: interchange v[i] and v[j] */ void swap(int v[], int i, int j) { int temp; temp = v[j]; v[j] = v[i]; v[i] = temp; }
C
#include <stdio.h> int main() { int n, a, b; int contador = 0; int resposta = 0; scanf("%d", &n); while (contador < n) { scanf("%d %d", &a, &b); resposta += a*b; contador++; } printf("%d\n", resposta); return 0; }
C
/* * list.c * ASA 2018 * Gabriel Figueira, Rafael Andrade * P1 (Sr. Joao Caracol) */ #include <stdio.h> #include <stdlib.h> #include "adj.h" typedef struct node { struct node * next; int id; } * Node; struct graph { Node * adjList; int n_vertexes; int n_connections; } ; static Node * adjListAuxPointer; static int * translation; static int n_connections; static void freeNode(Node to); static void freeNodeTraverse(int from, Node to); static void traverseGraph(Graph g, void (*func)(int, Node)); static void invertConnection(int from, Node to); static void insertInAdjList(Node * adjList, int id); static void reduceGraph_aux(Graph g, int u, int v); static void printSccGraph_aux(); int nVertex(Graph g) { return g->n_vertexes; } int nConnection(Graph g) { return g->n_connections; } /* frees memory associated with a node*/ void freeNode(Node n) { free(n); } void freeNodeTraverse(int i, Node n) { (void) i; free(n); } /* inserts a new node at the beggining of the adjacency list */ void insertInAdjList(Node * adjList, int id) { Node new = (Node) calloc(1, sizeof(struct node)); new->id = id; new->next = *adjList; *adjList = new; } int insertOrderlyInAdjList(Node * adjList, int id) { Node new = (Node) calloc(1, sizeof(struct node)); new->id = id; Node conn = *adjList; if(conn == NULL) *adjList = new; else if(conn->id > id) { *adjList = new; new->next = conn; } else { while(conn->next != NULL && conn->next->id < id) conn = conn->next; if(conn->id == id || (conn->next != NULL && conn->next->id == id)) { freeNode(new); return 0; } else { new->next = conn->next; conn->next = new; } } return 1; } /* function which receives input and builds the adjacency list*/ Graph buildGraph() { int N, M, vertex, edge; scanf("%d", &N); scanf("%d", &M); Graph res = (Graph) calloc(1, sizeof(struct graph)); res->adjList = (Node*) calloc(1, sizeof(Node) * N); res->adjList--; /*the vertexes are bounded from 1 to N*/ res->n_vertexes = N; res->n_connections = M; while(M--) { scanf("%d %d", &vertex, &edge); insertInAdjList(res->adjList + vertex, edge); } return res; } /* Meta function to do something with the nodes in the adjacency list * It goes in order of vertexes */ void traverseGraph(Graph g, void (*func)(int, Node)){ int i; Node conn, scratchpad; for(i=1; i <= g->n_vertexes; ++i) { conn = g->adjList[i]; while(conn != NULL) { scratchpad = conn; conn = conn->next; func(i, scratchpad); } } } /* Insert (inverted) connection in new adjacency list auxiliary pointer */ void invertConnection(int from, Node to) { insertInAdjList(adjListAuxPointer + to->id, from); } /* Transposes list of adjacencies, one node at a time */ Graph transposeGraph(const Graph g) { adjListAuxPointer = (Node*) calloc(1, sizeof(Node) * g->n_vertexes); adjListAuxPointer--; traverseGraph(g, invertConnection); Graph res = (Graph) calloc(1, sizeof(struct graph)); res->n_vertexes = g->n_vertexes; res->n_connections = g->n_connections; res->adjList = adjListAuxPointer; return res; } /* Shows that everything went fine (for debugging purposes)*/ void showGraph(const Graph g) { int i; Node conn; for(i=1; i <= g->n_vertexes; ++i) { printf("Vertex %d: ", i); conn = g->adjList[i]; while(conn != NULL) { printf("%d ", conn->id); conn = conn->next; } putchar('\n'); } } void freeGraph(Graph g) { traverseGraph(g, freeNodeTraverse); free(++(g->adjList)); free(g); } void doForEachAdjU(Graph g, int u, void (*func)(Graph, int, int)) { Node conn, scratchpad; conn = g->adjList[u]; while(conn != NULL) { scratchpad = conn; conn = conn->next; func(g, u, scratchpad->id); } } Graph reduceGraph(Graph g, int * trans) { int i; translation = trans; Graph res = (Graph) calloc(1, sizeof(struct graph)); res->adjList = adjListAuxPointer = (Node*) calloc(1, sizeof(Node) * nVertex(g)); res->adjList--; /*the vertexes are bounded from 1 to N*/ adjListAuxPointer--; res->n_vertexes = nVertex(g); for(i = 1; i <= nVertex(g); i++) doForEachAdjU(g, i, reduceGraph_aux); res->n_connections = n_connections; freeGraph(g); return res; } void reduceGraph_aux(Graph g, int u, int v) { (void) g; v = translation[v]; u = translation[u]; if(u != v) { n_connections += insertOrderlyInAdjList(adjListAuxPointer + u, v); } } void printSccGraph(Graph g, int nScc) { printf("%d\n%d\n", nScc, g->n_connections); int i; for(i = 1; i <= nVertex(g); i++) doForEachAdjU(g, i, printSccGraph_aux); } void printSccGraph_aux(Graph g, int vertex, int conn) { (void) g; printf("%d %d\n", vertex, conn); }
C
#include "board.h" void init_board(struct game_data * game_data) { for (int i = 0; i < BOARD_SIZE; i++) { for (int j = 0; j < BOARD_SIZE; j++) { game_data->board[i][j] = 0; } } for (int i = 0; i < game_data->n_players; i++) { int x; int y; do { x = randint(0, BOARD_SIZE); y = randint(0, BOARD_SIZE); } while (game_data->board[x][y]); game_data->entities[i]->x = x; game_data->entities[i]->y = y; game_data->board[x][y] = 1; } } /* * Internal function * Check if a given position is in an array of cells. */ int in(int x, int y, int * n_cells, struct cell cells[]) { for (int i = 0; i < *n_cells; i++) { if (cells[i].x == x && cells[i].y == y) { return 1; } } return 0; } /* * Fill recursively an array of all reachable cells from a set of starting cells * with a given maximum number of movements. */ void find_reachable_cells( int n_starting_cells, struct cell starting_cells[], int * n_cells, struct cell cells[], int range, struct game_data * game_data ) { if (!range) { return; } struct cell ending_cells[(PLAYER_MOVE_RANGE - range + 1) * 4]; int n_ending_cells = 0; int x; int y; for (int i = 0; i < n_starting_cells; i++) { for (int way = -1; way <= 1; way += 2) { for (int coor = 0; coor <= 1; coor++) { x = starting_cells[i].x; y = starting_cells[i].y; switch (coor) { case 0: x += way; mod(&x, BOARD_SIZE); break; case 1: y += way; mod(&y, BOARD_SIZE); break; } if (!in(x, y, n_cells, cells) && !game_data->board[x][y]) { ending_cells[n_ending_cells].x = x; ending_cells[n_ending_cells].y = y; n_ending_cells++; cells[*n_cells].x = x; cells[*n_cells].y = y; (*n_cells)++; } } } } find_reachable_cells(n_ending_cells, ending_cells, n_cells, cells, range - 1, game_data); } // Choose move of the entity void choose_random_move( int * x, int * y, // Returned values: chosen coor struct entity * entity, struct game_data * game_data ) { struct cell cells[2 * PLAYER_MOVE_RANGE * (PLAYER_MOVE_RANGE + 1)]; int n_cells = 0; struct cell starting_cells[1] = {{ entity->x, entity->y }}; int n_starting_cells = 1; find_reachable_cells(n_starting_cells, starting_cells, &n_cells, cells, PLAYER_MOVE_RANGE, game_data); if (!n_cells) { *x = -1; *y = -1; return; } int i = randint(0, n_cells); *x = cells[i].x; *y = cells[i].y; } int one_axe_distance(int a, int b) { if (a > b) { return one_axe_distance(b, a); } return min(b - a, 50 - b + a); } int distance(struct cell c1, struct cell c2) { return one_axe_distance(c1.x, c2.x) + one_axe_distance(c1.y, c2.y); } void choose_friend_move(int * x, int * y, struct entity * entity, struct game_data * game_data) { struct cell cells[2 * FRIEND_MOVE_RANGE * (FRIEND_MOVE_RANGE + 1)]; int n_cells = 0; struct cell starting_cells[1] = {{ entity->x, entity->y }}; int n_starting_cells = 1; find_reachable_cells(n_starting_cells, starting_cells, &n_cells, cells, FRIEND_MOVE_RANGE, game_data); if (!n_cells) { *x = -1; *y = -1; return; } int min = BOARD_SIZE + 1; int cell_index = -1; struct cell target = { entity->target->x, entity->target->y }; for (int i = 0; i < n_cells; i++) { int d = distance(cells[i], target); if (d < min) { min = d; cell_index = i; } } *x = cells[cell_index].x; *y = cells[cell_index].y; } void move_entities(struct game_data * game_data) { struct cell cells[game_data->n_players + game_data->n_friends]; for (int i = 0; i < game_data->n_players + game_data->n_friends; i++) { if ( game_data->entities[i]->type == FRIEND_TYPE && ( game_data->entities[i]->mana >= game_data->entities[i]->card->cost || game_data->entities[i]->mana_regen == 0 // skip friend turn if it has no target alive ) ) { cells[i].x = game_data->entities[i]->x; cells[i].y = game_data->entities[i]->y; continue; } if (game_data->entities[i]->type == PLAYER_TYPE) { choose_random_move(&cells[i].x, &cells[i].y, game_data->entities[i], game_data); } else if (game_data->entities[i]->type == FRIEND_TYPE) { choose_friend_move(&cells[i].x, &cells[i].y, game_data->entities[i], game_data); } if (cells[i].x == -1) { die(i, game_data); // die() modify player indexes, thus we have to modify cell indexes accordingly cells[i].x = cells[game_data->n_players + game_data->n_friends].x; cells[i].y = cells[game_data->n_players + game_data->n_friends].y; i--; } } for (int i = 0; i < game_data->n_players + game_data->n_friends; i++) { for (int j = 0; j < game_data->n_players + game_data->n_friends; j++) { if (i == j) { continue; } if (cells[j].x == cells[i].x && cells[j].y == cells[i].y) { continue; } game_data->board[game_data->entities[i]->x][game_data->entities[i]->y] = 0; game_data->board[cells[i].x][cells[i].y] = 1; game_data->entities[i]->x = cells[i].x; game_data->entities[i]->y = cells[i].y; } } }
C
/**************************************************************************** * * C F I L E C R E A T E R O U T I N E * ----------------------------------------- * * The "creat" routine opens a new "C" file and returns a file id. * * Calling Sequence: * * fid = creat(fname,prot,type); * * Where: * * fname is the address of a null terminated file name. * prot is the UNIX file protection * type is 0 for ASCII, 1 for BINARY * *****************************************************************************/ #include "lib.h" #include <sys/types.h> #include "klib.h" int xcreat(P(const char *) fname, P(mode_t) prot, P(int) binary) PP(const char *fname;) /* -> File name */ PP(mode_t prot;) /* Open mode */ PP(int binary;) /* ASCII/BINARY flag */ { return _creat(fname, prot, binary); /* Call clib routine */ }
C
#include <stdio.h> #include <ctype.h> #include <string.h> static void expand(char s1[], char s2[]); int main(void){ char a[] = "1-6"; char buff[1000] = ""; expand(a, buff); printf("%s\n", buff); return 0; } /* expands shorthand * a-z -> abc...xyz CHECK * a-b-c -> abc CHECK * a-z0-9 -> abc..xyz012..789 * leading or trailing '-' are taken literally */ static void expand(char s1[], char s2[]){ int j = 0; // index for writing in s2 int s1_len = (int)strlen(s1); for(int i=0; s1[i] != '\0'; i++){ if(s1[i] == '-'){ if ((isdigit(s1[i-1]) && !isdigit(s1[i+1])) // both are not digits || (isalpha(s1[i-1]) && !isalpha(s1[i+1])) // or both not alphabetic || i == 0 // stop OOB from accessing before first element || i == s1_len-1){ // stop OOB from accessing after last elem s2[j++] = '-'; continue; } // +1/-1 to disclude start and end characters // start/end are printed in else // this only prints characters between the start and end char start = s1[i-1] + 1; char end = s1[i+1] - 1; while (start <= end){ s2[j++] = start; start++; } } else { s2[j++] = s1[i]; } } return; }
C
/** * In order to provide fast and flexible logging, this project uses Cocoa Lumberjack. * * The Google Code page has a wealth of documentation if you have any questions. * https://github.com/robbiehanson/CocoaLumberjack * * Here's what you need to know concerning how logging is setup for CocoaHTTPServer: * * There are 4 log levels: * - Error * - Warning * - Info * - Verbose * * In addition to this, there is a Trace flag that can be enabled. * When tracing is enabled, it spits out the methods that are being called. * * Please note that tracing is separate from the log levels. * For example, one could set the log level to warning, and enable tracing. * * All logging is asynchronous, except errors. * To use logging within your own custom files, follow the steps below. * * Step 1: * Import this header in your implementation file: * * #import "HTTPLogging.h" * * Step 2: * Define your logging level in your implementation file: * * // Log levels: off, error, warn, info, verbose * static const int httpLogLevel = HTTP_LOG_LEVEL_VERBOSE; * * If you wish to enable tracing, you could do something like this: * * // Debug levels: off, error, warn, info, verbose * static const int httpLogLevel = HTTP_LOG_LEVEL_INFO | HTTP_LOG_FLAG_TRACE; * * Step 3: * Replace your NSLog statements with HTTPLog statements according to the severity of the message. * * NSLog(@"Fatal error, no dohickey found!"); -> HTTPLogError(@"Fatal error, no dohickey found!"); * * HTTPLog works exactly the same as NSLog. * This means you can pass it multiple variables just like NSLog. **/ //#import "DDLog.h" #define LOG_OBJC_MAYBE(frmt, ...) #define LOG_C_MAYBE(frmt, ...) // Define logging context for every log message coming from the HTTP server. // The logging context can be extracted from the DDLogMessage from within the logging framework, // which gives loggers, formatters, and filters the ability to optionally process them differently. #define HTTP_LOG_CONTEXT 80 // Configure log levels. #define HTTP_LOG_FLAG_ERROR (1 << 0) // 0...00001 #define HTTP_LOG_FLAG_WARN (1 << 1) // 0...00010 #define HTTP_LOG_FLAG_INFO (1 << 2) // 0...00100 #define HTTP_LOG_FLAG_VERBOSE (1 << 3) // 0...01000 #define HTTP_LOG_LEVEL_OFF 0 // 0...00000 #define HTTP_LOG_LEVEL_ERROR (HTTP_LOG_LEVEL_OFF | HTTP_LOG_FLAG_ERROR) // 0...00001 #define HTTP_LOG_LEVEL_WARN (HTTP_LOG_LEVEL_ERROR | HTTP_LOG_FLAG_WARN) // 0...00011 #define HTTP_LOG_LEVEL_INFO (HTTP_LOG_LEVEL_WARN | HTTP_LOG_FLAG_INFO) // 0...00111 #define HTTP_LOG_LEVEL_VERBOSE (HTTP_LOG_LEVEL_INFO | HTTP_LOG_FLAG_VERBOSE) // 0...01111 // Setup fine grained logging. // The first 4 bits are being used by the standard log levels (0 - 3) // // We're going to add tracing, but NOT as a log level. // Tracing can be turned on and off independently of log level. #define HTTP_LOG_FLAG_TRACE (1 << 4) // 0...10000 // Setup the usual boolean macros. #define HTTP_LOG_ERROR (httpLogLevel & HTTP_LOG_FLAG_ERROR) #define HTTP_LOG_WARN (httpLogLevel & HTTP_LOG_FLAG_WARN) #define HTTP_LOG_INFO (httpLogLevel & HTTP_LOG_FLAG_INFO) #define HTTP_LOG_VERBOSE (httpLogLevel & HTTP_LOG_FLAG_VERBOSE) #define HTTP_LOG_TRACE (httpLogLevel & HTTP_LOG_FLAG_TRACE) // Configure asynchronous logging. // We follow the default configuration, // but we reserve a special macro to easily disable asynchronous logging for debugging purposes. #define HTTP_LOG_ASYNC_ENABLED YES #define HTTP_LOG_ASYNC_ERROR ( NO && HTTP_LOG_ASYNC_ENABLED) #define HTTP_LOG_ASYNC_WARN (YES && HTTP_LOG_ASYNC_ENABLED) #define HTTP_LOG_ASYNC_INFO (YES && HTTP_LOG_ASYNC_ENABLED) #define HTTP_LOG_ASYNC_VERBOSE (YES && HTTP_LOG_ASYNC_ENABLED) #define HTTP_LOG_ASYNC_TRACE (YES && HTTP_LOG_ASYNC_ENABLED) // Define logging primitives. #define HTTPLogError(frmt, ...) LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_ERROR, httpLogLevel, HTTP_LOG_FLAG_ERROR, \ HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define HTTPLogWarn(frmt, ...) LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_WARN, httpLogLevel, HTTP_LOG_FLAG_WARN, \ HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define HTTPLogInfo(frmt, ...) LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_INFO, httpLogLevel, HTTP_LOG_FLAG_INFO, \ HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define HTTPLogVerbose(frmt, ...) LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_VERBOSE, httpLogLevel, HTTP_LOG_FLAG_VERBOSE, \ HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define HTTPLogTrace() LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_TRACE, httpLogLevel, HTTP_LOG_FLAG_TRACE, \ HTTP_LOG_CONTEXT, @"%@[%p]: %@", THIS_FILE, self, THIS_METHOD) #define HTTPLogTrace2(frmt, ...) LOG_OBJC_MAYBE(HTTP_LOG_ASYNC_TRACE, httpLogLevel, HTTP_LOG_FLAG_TRACE, \ HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define HTTPLogCError(frmt, ...) LOG_C_MAYBE(HTTP_LOG_ASYNC_ERROR, httpLogLevel, HTTP_LOG_FLAG_ERROR, \ HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define HTTPLogCWarn(frmt, ...) LOG_C_MAYBE(HTTP_LOG_ASYNC_WARN, httpLogLevel, HTTP_LOG_FLAG_WARN, \ HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define HTTPLogCInfo(frmt, ...) LOG_C_MAYBE(HTTP_LOG_ASYNC_INFO, httpLogLevel, HTTP_LOG_FLAG_INFO, \ HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define HTTPLogCVerbose(frmt, ...) LOG_C_MAYBE(HTTP_LOG_ASYNC_VERBOSE, httpLogLevel, HTTP_LOG_FLAG_VERBOSE, \ HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define HTTPLogCTrace() LOG_C_MAYBE(HTTP_LOG_ASYNC_TRACE, httpLogLevel, HTTP_LOG_FLAG_TRACE, \ HTTP_LOG_CONTEXT, @"%@[%p]: %@", THIS_FILE, self, __FUNCTION__) #define HTTPLogCTrace2(frmt, ...) LOG_C_MAYBE(HTTP_LOG_ASYNC_TRACE, httpLogLevel, HTTP_LOG_FLAG_TRACE, \ HTTP_LOG_CONTEXT, frmt, ##__VA_ARGS__)
C
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <dirent.h> #include <sys/stat.h> /* see chapter4/readdir_r-v1.c for extra comments */ int main(int argc, char **argv) { /* Always list the current directory */ char *d_to_open = "."; DIR *dstream = opendir(d_to_open); if (dstream == NULL) { perror("opening directory failed"); exit(2); } struct dirent d; struct dirent *result; for(;;) { int ret = readdir_r(dstream, &d, &result); /*Get name of current file in directory * and get stat values from it */ char *path = d.d_name; struct stat buf; if(stat(path, &buf) != 0){ perror("error getting stat of file."); exit(4); } if (ret != 0) { perror("readdir_r error"); exit(3); } if (!result) { break; } /* If file is not a directory */ if(d.d_type != DT_DIR) printf("mode: %o\t name: %s\n", buf.st_mode, d.d_name); /*if file is a directory, simpy add (Directory) * to end of string */ else printf("mode: %o\t name: %s (Directory)\n", buf.st_mode, d.d_name); } return 0; }
C
/* * Ben Dumais, 250669195 * 3305b, Spring 2016 * Assignment 1 */ //Includes #include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <signal.h> //Definitions #define MAX_SIZE 256 //Max size of a str #define MAX_CMD 10 //Maximum amount of commands in a line #define EMPTY -1 //Indicates an empty pipe or failed child #define DEBUG 0 //Debug mode - Change to 1 to show history debugging //Method Declarations int splitCommands(char *line, char *comms[]); int tokenize(char *line, char *tokens[]); pid_t execute(char *args[], int pipes[][2], int n); void closePipes(int pipes[MAX_CMD][2]); void resetPipes(int pipes[MAX_CMD][2]); void sigHandler(int); void updateHistory(char *input, char *history[]); void printHistory(char *history[]); void initHistory(char *history[]); //Main Function int main(void){ signal(SIGINT, sigHandler); //Start signal handler /* Declare variables */ char str[MAX_SIZE]; //Variable for input string (will be tokenized) char str2[MAX_SIZE]; //Variable for second input string (will not be tokenized) char *commands[MAX_CMD];//Variable for commands array, stores commands char *args[MAX_CMD]; //Variable for arguments array, stores arguments for a command char *hist[MAX_CMD]; //Variable for history array, stores previous commands char *exitString = "exit\n"; //String storing the exit command char *historyString = "history\n"; //String storing the history command int numCom; //Variable to store amount of different commands user has input int numArgs; //Variable to store amount of arguments for a command pid_t pids[MAX_CMD]; //Variable to store PIDS from commands being run int pipes[MAX_CMD][2]; //Variable to store pipes for each process resetPipes(pipes); //Initialize pipes to all be empty initHistory(hist); //Initialize History array (so no memory errors occur) while(1) { //Loop forever printf("\n3305Asn1/ben-dumais>"); //Print prompt fgets(str,sizeof(str),stdin); //Read in string if(strcmp(str,exitString) == 0) //If user input "exit", exit program return 0; else if(strcmp(str,historyString) == 0) //If user input "history", print history array printHistory(hist); //Check for a < or >, indicating IO is needed else if(strchr(str,'<')!= NULL || strchr(str,'>')!=NULL){ //Search for those characters, and if either return with a valid pointer in the string, we need to do IO char *in = strchr(str,'<'); //Get pointer to <, if it exists char *out = strchr(str,'>'); //Get pointer to >, if it exists int toks = splitCommands(str, commands); //Split input into commands if(toks == 3){ //If there are three commands, it has both in and out redirection - We assume the command < in > out format int pid; pid = fork(); //Fork if(pid==0){ //In child, setup redirection and execute FILE *fp1 = fopen(commands[1],"r"); //Open the first file as read FILE *fp2 = fopen(commands[2], "w"); //Open the second file as write dup2(fileno(fp1), STDIN_FILENO); //Redirect both stdin and stdout to appropriate places dup2(fileno(fp2), STDOUT_FILENO); fclose(fp1); //Close both files fclose(fp2); tokenize(commands[0], args); //Tokenize the actual command (ie, ls -l) execvp(args[0], args); //Execute } else{ int status; waitpid(pid, &status, 0); } } else if(toks == 2){ //If there were 2 tokens, it is either command < in or command > out if(in != NULL){ //If there is a pointer to a < character, we need to redirect input int pid; pid = fork(); //Fork if(pid==0){ FILE *fp = fopen(commands[1],"r"); //Open file dup2(fileno(fp), STDIN_FILENO); //Redirect fclose(fp); //Close tokenize(commands[0], args); //Tokenize command execvp(args[0], args); //Execute } else{ int status; waitpid(pid, &status, 0); } } else{ //Otherwise it was a > character, so redirect output int pid; pid = fork(); //Same as before: fork, open, redirect, close, execute if(pid==0){ FILE *fp = fopen(commands[1],"w"); dup2(fileno(fp), STDOUT_FILENO); fclose(fp); tokenize(commands[0], args); execvp(args[0], args); } else{ int status; waitpid(pid, &status, 0); } } updateHistory(str,hist); //Add original string into history array } else //If tokens is neither 2 or 3, the input contained a < or > but is not supported printf("\nERROR: invalid IO command. Expected format: _command_ < _input_ > _output_"); //Print a reminder of corrent format } else{ //Otherwise, run the command(s) if(DEBUG){ //Debugging for history array printf("\nHistory pre split:\n"); printHistory(hist); } strncpy(str2,str, MAX_SIZE); //Copy string into str2 variable, (for use in history) numCom=splitCommands(str,commands); //Split string into commands (splits by | or new line) //Number of commands is stored if(DEBUG){ //Debugging for history array printf("\nHistory post split:\n"); printHistory(hist); } //As it can be seen from debugging, the history completely changes after tokenization int i; for(i=0;i<numCom - 1; i++){ //for each command user wants to run, we need to create pipes (num commands -1, as each pipe connects 2) int p[2]; //Create pipes pipe(p); //Now we designate the input and output pipes[i][STDOUT_FILENO] = p[STDOUT_FILENO]; //Set the output of current command to input of pipe (store output for next operation) pipes [i+1][STDIN_FILENO] = p[STDIN_FILENO];//Set the input of next command to output of pipe (take input for next operation) } //Loop through each command and execute in order for(i=0;i<numCom;i++){ tokenize(commands[i],args); //Split current command into its arguments pids[i] = execute(args,pipes,i); //Execute command and place PID into array } closePipes(pipes); //Close all pipes that were created for(i=0;i<numCom;i++){ //Loop through commands, waiting for each to terminate int status; waitpid(pids[i], &status, 0); } resetPipes(pipes); //Reset all pipes to empty updateHistory(str2,hist); //Add original string into history array }//End of Else strcmp }//End of While }//End of Main //Methods /* * Tokenizing code adapted from posted example for Assignment 1 */ /* splitCommands method, takes string and array of strings, outputs number of tokens as integer * Splits input line into seperate commands (delimiter is |) * Used to split entire input into seperate commands */ int splitCommands(char *line, char *comms[]){ int commands=0; //initalize number of commands comms[commands]=strtok(line, "<>|\n"); //Get token and place in first position do{ //Loop until we read a null commands++; comms[commands]=strtok(NULL, "<>|"); //Tokenize and add to array } while(comms[commands] != NULL); return commands; //Return commands } /* tokenize method, takes a string and array of strings, outputs integer of amount of tokens * Splits input line into arguements (delimits on spaces and newline) * Used to break a single command into its arguments */ int tokenize(char *line, char *tokens[]){ int i=0; tokens[i]=strtok(line, " \n"); //Tokenize do { //Loop until we read a null i++; tokens[i]=strtok(NULL, " \n"); //Tokenize and add to token array } while(tokens[i] != NULL); tokens[++i] = NULL; //Terminate with a null (required by execvp) i--; //Decrement to match number of tokens return i; //Return number of tokens } /* execute method, takes array of string, pipes array, and an integer, outputs a pid * Takes a list of arguments, pipes it accordingly, and executes the indicated process * Used to execute all commands input by user */ pid_t execute(char *args[], int pipes[][2], int n){ pid_t pid; int i; pid = fork(); //Fork process //This creates a child that runs exec, which will then close after completion if(pid==0){ //Designate where to direct input and output if(pipes[n][STDIN_FILENO] >= 0) //If current pipe is positive dup2(pipes[n][STDIN_FILENO], STDIN_FILENO); //replace input for this pipe with new fd if(pipes[n][STDOUT_FILENO] >= 0) //Repeat for STDOUT dup2(pipes[n][STDOUT_FILENO], STDOUT_FILENO); closePipes(pipes); //Close pipe ends execvp(args[0],args); //Execute the command }//End of fork return pid; } /* closePipes method, takes pipes array, no output * Loops through pipes and closes them */ void closePipes(int pipes[MAX_CMD][2]){ int i; for(i=0;i<MAX_CMD;i++){ //Loop through all pipes if(pipes[i][STDIN_FILENO] >= 0) //If a pipe's input is positive, close it close(pipes[i][STDIN_FILENO]); if(pipes[i][STDOUT_FILENO] >= 0) //If a pipes's output is positive,close it close(pipes[i][STDOUT_FILENO]); } } /* resetPipes method, takes pipe array, no output * Loops through pipe array and resets all pipes to empty */ void resetPipes(int pipes[MAX_CMD][2]){ int i; for(i=0;i<MAX_CMD;i++){ pipes[i][STDIN_FILENO] = EMPTY; pipes[i][STDOUT_FILENO] = EMPTY; } } /* sigHandler method, takes an integer * Used to interrupt program */ void sigHandler(int signum){ printf("\nInterrupted"); } //History methods /* At this point, history does not work as expected. For some reason, each time a * string is added into the array, all other entries are updated to the string that was * just added. This is not to do with the algorithm, but rather the strings themselves * change. I did not have time to debug properly (likely an issue with pointers) * To show the problem, change DEBUG to 1. As soon as the tokenize command is called, * the history array is changes, even though no direct modification was made to it */ /* updateHistory method, takes a string and array of string, no output * Method to update history (add most recent command) */ void updateHistory(char *input, char *history[]){ int i; for(i=MAX_CMD-1;i>0;i--){ //Loop from back to front of array history[i]=history[i-1]; //Copy preceeding element into current } history[i]=input; //Add most recent command to front } /* printHistory method, take array of strings, no output * Method to print history array */ void printHistory(char *history[]){ int i=0; while(history[i] != NULL){ //Loop until we get a null printf("%s",history[i]); //Print current string i++; } } /* initHistory method, takes array of strings, no output * Method to initalize history array to all null values */ void initHistory(char *history[]){ int i; for(i=0;i<MAX_CMD;i++) //Loop though all of array history[i]=NULL; //Set each element to null }
C
#include <stdio.h> //#include <libc.h> //Linux Only #include "bmp.h" int get_short(FILE *fp) { int c = getc(fp); return ((getc(fp) << 8) | c); } long get_long(FILE *fp) { long c = get_short(fp); return ((get_short(fp) << 16) | c); } bmpHeader *loadBmpHeader(FILE *fp, int *errcode) /* ե뤫إåɤࡣ 顼 NULL֤ꡢerrcodeˤͳ롣 եݥ󥿤ϥѥåȾƬؤ֤롣 */ { long ftype, boffs, wid, hei, xp, yp, planes, colors; long cmp=NoComp; short bits = 0; bmpHeader *bh; wid = hei = planes = bits = xp = yp = colors = 0; *errcode = 0; if (getc(fp) != 'B' || getc(fp) != 'M') { *errcode = Err_FORMAT; return NULL; } (void) fseek(fp, 8L, SEEK_CUR); /* Skip hot spot */ boffs = get_long(fp); ftype = get_long(fp); if (ftype == OS2) { wid = get_short(fp); hei = get_short(fp); planes = get_short(fp); bits = get_short(fp); }else if (ftype == WIN3) { wid = get_long(fp); hei = get_long(fp); planes = get_short(fp); bits = get_short(fp); cmp = get_long(fp); (void) get_long(fp); xp = get_long(fp); yp = get_long(fp); colors = get_long(fp); (void) get_long(fp); }else { /* ERROR */ *errcode = Err_FORMAT; return NULL; } if(feof(fp)) { *errcode = Err_SHORT; return NULL; } if (xp < 0 || yp < 0) { *errcode = Err_FORMAT; return NULL; } if (planes != 1 || wid > MAXWidth || (bits != 1 && bits != 4 && bits != 8 && bits != 15 && bits != 16 && bits != 24)) { *errcode = Err_IMPLEMENT; return NULL; } bh = (bmpHeader *)malloc(sizeof(bmpHeader)); bh->type = ftype; bh->bits = bits; bh->x = wid; bh->y = hei; bh->xpm = xp; bh->ypm = yp; bh->bitoffset = boffs; bh->comp = cmp; return bh; } void freeBmpHeader(bmpHeader *bh) { if (bh) { if (bh->palette) free((void *)bh->palette); free((void *)bh); } }
C
#include <stdio.h> //========================================================================= // ļ main.c // ѧƽɼͲ // ά¼: 2008-4-17 v1.0 by xdw //========================================================================= struct stu { int num; char *name; char sex; float score; }temp,boy[5]={ {101,"Li ping",'M',45}, //һ5ԪصĽṹ鲢ʼ {102,"Zhang ping",'M',62.5}, {103,"He fang",'F',92.5}, {104,"Cheng ling",'F',87}, {105,"Wang ming",'M',58}, }; int main(void) { int i,j,c=0; float ave,s=0; for(i=0;i<5;i++) { s+=boy[i].score; //ܷ if(boy[i].score<60) c+=1; //ͳƲ˵ķ } //printf("s=%f\n",s); //ӡܷ ave=s/5; //ƽ for( i = 0 ;i<5;i++) { for( j = i+1; j<5 ; j++) { if (boy[j].score < boy[i].score ) { temp = boy[i]; boy[i] = boy[j]; boy[j] = temp; } } } for( i = 0 ;i<5;i++) { printf("name=%s sour=%f\n",boy[i].name,boy[i].score); } printf("average=%f\ncount=%d\n",ave,c); //ӡƽ벻 return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <signal.h> static int alarm_fired = 0; void ding (int sig) { alarm_fired = 1; } int main () { pid_t pid; printf ("Alarm app start.\n"); pid = fork (); switch (pid) { case -1: // failure perror ("Fork failed"); exit (1); case 0: // child sleep (5); kill (getppid(), SIGALRM); // send SIGALRM to parrent process exit (0); } // from here is parent process printf ("waiting for alarm to go off\n"); (void) signal (SIGALRM, ding); pause (); // causes the program to suspend execution until a signal occurs if (alarm_fired) printf("Ding!\n");; printf("done\n");; exit (0); }
C
//job_arraylist.c #include "job_arraylist.h" #include "sfbuiltin.h" int job_cnt = 0; int addJob(struct job* newJob){ if(newJob->inJob) newJob->jid = ++job_cnt; if (job_start == NULL && job_end == NULL){ // empty list job_start = newJob; job_end = newJob; } else{ job_end->next = newJob; newJob->prev = job_end; job_end = newJob; } return JOB_TRUE; } // return NULL on failure struct job* createJob(int pid, job_state jstate, char** cmd){ struct job* newJob = (struct job*) malloc(sizeof(struct job)); if(newJob == NULL){ fprintf(stderr, "Malloc for newJob failed\n"); return NULL; } int len = 0; // for the last '\0' char **cmd_ptr = cmd; while( *cmd_ptr != 0 ){ len += (strlen(*cmd) + 1); // +1 for space cmd_ptr++; } newJob->jid = 0; newJob->pid = pid; newJob->jstate = jstate; newJob->cmd = (char*) malloc(sizeof(char) * len); debug("Malloced %d for job's cmd\n", len); if(newJob->cmd == NULL){ fprintf(stderr, "Malloc for newJob->cmd failed\n"); return NULL; } // copy cmd one by one char *cpyLoc = newJob->cmd; cmd_ptr = cmd; while( *cmd_ptr != 0 ){ len = strlen(*cmd_ptr); strncpy(cpyLoc, *cmd_ptr, len); cmd_ptr++; cpyLoc += len; if(*cmd_ptr != 0){ *cpyLoc = ' '; cpyLoc += 1; } else{ *cpyLoc = '\0'; } } newJob->inJob = 0; // false by default newJob->prev = NULL; newJob->next = NULL; time_t rawtime; time ( &rawtime ); localtime_r ( &rawtime, &newJob->timeinfo); return newJob; } // return -1 on failure // return pid if successful int removeJob(int jid_pid, int isjid){ debug("Remove job id=%d\n", jid_pid); struct job *now = findById(jid_pid, isjid); if(now == NULL){ debug(stderr, "Job not found!"); return -1; } int pid = now->pid; if(now->prev == NULL && now->next == NULL){ // now is headjob and the tailjob job_start = NULL; job_end = NULL; } else if(now->prev == NULL && now->next != NULL){ // head job but not tailjob now->next->prev = NULL; job_start = now->next; } else if(now->prev != NULL && now->next == NULL){ // tail job but not headjob now->prev->next = NULL; job_end = now->prev; } else { // neither head nor tail now->prev->next = now->next; now->next->prev = now->prev; } free(now->cmd); free(now); return pid; } void removeAllJobs(){ struct job *now = job_start, *next_now; while(now != NULL){ next_now = now->next; free(now->cmd); free(now); now = next_now; } job_start = NULL; job_end = NULL; fg = NULL; } void printJobs(){ struct job *now = job_start; while(now != NULL){ if(!now->inJob){ now = now->next; continue; } int prev_pid, next_pid; if(now->prev != NULL){ prev_pid = now->prev->pid; } else{ prev_pid = 0; } if(now->next != NULL){ next_pid = now->next->pid; } else{ next_pid = 0; } fprintf(stdout, "[%d] %s %5d \"%s\" prev's pid=%d, next's pid=%d\n", now->jid, (now->jstate == RUNNING)?"Running":"Stopped", now->pid, now->cmd, prev_pid, next_pid); now = now->next; } } void printJobsAll(){ struct job *now = job_start; debug("Current job_start=%d, job_end=%d\n", (now==NULL)?0:now->pid, (job_end==NULL)?0:job_end->pid); while(now != NULL){; int prev_pid, next_pid; if(now->prev != NULL){ prev_pid = now->prev->pid; } else{ prev_pid = 0; } if(now->next != NULL){ next_pid = now->next->pid; } else{ next_pid = 0; } fprintf(stdout, "[%d] %s %5d \"%s\" prev's pid=%d, next's pid=%d\n", now->jid, (now->jstate == RUNNING)?"Running":"Stopped", now->pid, now->cmd, prev_pid, next_pid); now = now->next; } } // return JOB_TRUE, JOB_FALSE int equals(struct job* j, int jid_pid, int isjid){ if(isjid == JOB_TRUE){ if(j->jid == jid_pid){ return JOB_TRUE; } else{ return JOB_FALSE; } } else { if(j->pid == jid_pid){ return JOB_TRUE; } else{ return JOB_FALSE; } } } struct job* findById(int jid_pid, int isjid){ struct job *now = job_start; if(now == NULL){ // empty list return NULL; } while( equals(now, jid_pid, isjid) != JOB_TRUE ){ now = now->next; if(now == NULL){ // reached the end of the list return NULL; } } return now; } void p_sigtstp_handler(int sig){ int tmp_errno = errno; debug("parent sigtstp handler: pid=%d pgid=%d\n", getpid(), getpgid(getpid())); int fg_pid = 0; if(fg != NULL){ fg_pid = fg->pid; int ret = kill(fg->pid, SIGTSTP); if(ret == -1){ perror("kill(2) failed"); return; } fg = NULL; } else { debug("No foreground job, ignore it\n"); return; } struct job* j = findById(fg_pid, JOB_FALSE); if(j == NULL){ // j should not be NULL debug("Serious mistake!, j(fg_pid=%d) should not be null for SIGTSTP! \n", fg_pid); return; } // set correct values for the job if(!j->inJob){ j->jid = ++job_cnt; j->inJob = 1; } j->jstate = STOPPED; errno = tmp_errno; } void p_sigint_handler(int sig){ int tmp_errno = errno; debug("sigint handler: pid=%d pgid=%d\n", getpid(), getpgid(getpid())); int fg_pid = 0; if(fg != NULL){ fg_pid = fg->pid; int ret = kill(fg->pid, SIGINT); if(ret == -1){ perror("kill(2) failed\n"); return; } fg = NULL; } else { debug("No foreground job, ignore it\n"); return; } // remove from the job list int ret = removeJob(fg_pid, JOB_FALSE); if(ret == -1){ // j should not be NULL debug("Serious mistake!, j(fg_pid=%d) should not be null for SIGINT! \n", fg_pid); return; } errno = tmp_errno; } void p_sigchld_handler(int sig){ int childStatus; pid_t wpid; wpid = waitpid(-1, &childStatus, WNOHANG); debug("sigchld handler wpid=%d\n", wpid); if(wpid == 0){ debug("Still children to wait\n"); } else if(wpid == -1){ debug("No more child to wait\n"); // surpressed // perror("waitpid in sigchld handler"); } else if(wpid > 0){ debug("Child reaped!! wpid=%d\n", wpid); struct job* now = findById(wpid, JOB_FALSE); // remove by pid fprintf(stdout, "[%d] %s %5d \"%s\"\n", now->jid, "Done", now->pid, now->cmd); int ret = removeJob(wpid, JOB_FALSE); if(ret == -1){ debug(stderr, "Removing job failed!\n"); } } } void sigtstp_handler(int sig){ debug("pid=%d pgid=%d is pausing\n", getpid(), getpgid(getpid())); pause(); debug("pid=%d pgid=%d is done pausing\n", getpid(), getpgid(getpid())); } void sigcont_handler(int sig){ debug("pid=%d pgid=%d got sigcont\n", getpid(), getpgid(getpid())); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int is_in_sentence(char* wrd,char* sntnce) { char* result = strstr(sntnce, wrd); int position = result - sntnce; if(strstr(sntnce,wrd) != NULL){ return position; } else { return 0; } } int main() { // Create a function which takes two strings as parameters // One string is actually a sentence and the other one is a word // It should return the index of the word in the sentence and 0 otherwise // Try to erase small and uppercase sensitivity. char *word = "doctor"; char *sentence = "An apple a day keeps the doctor away."; // the output should be: 6 printf("%d",is_in_sentence(word, sentence)); return 0; }
C
#include<stdio.h> #include<fcntl.h> #include<errno.h> #include<unistd.h> #include<sys/time.h> #include<string.h> extern int errno; int main(int argc, char * argv[]){ int fd = open("myfifo",O_RDONLY); int timeout=10; //TimeOut For 10 seconds struct timeval tv; tv.tv_sec = timeout; tv.tv_usec=0; fd_set readfds; FD_ZERO(&readfds); FD_SET(fd,&readfds); int ret = select(fd+1,&readfds,NULL,NULL,&tv); if (ret==-1) { perror("Error occured in select\n"); printf("%d\n",errno); } else if (ret==0){ printf("No Data within %d seconds\n",timeout); } else{ char buf[100]; int len = sizeof(buf)-1; int read_ret; read_ret=read(fd,buf,len); if(read_ret==-1) perror("read"); else write(STDOUT_FILENO,buf,strlen(buf)); } return 0; }
C
#include <stdio.h> #define DIM 4 int main(){ int a[DIM][DIM], b[DIM][DIM], m[DIM][DIM], i, j, k; for(i = 0; i < DIM; i++){ for(j = 0; j < DIM; j++){ scanf("%d", &a[i][j]); } } for(i = 0; i < DIM; i++){ for(j = 0; j < DIM; j++){ scanf("%d", &b[i][j]); } } for(i = 0; i < DIM; i++){ for(j = 0; j < DIM; j++){ /*Il terzo ciclo è la sommatoria, che esprime il prodotto scalare.*/ for(k = 0, m[i][j] = 0; k < DIM; k++){ m[i][j] = m[i][j] + (a[i][k] * b[k][j]); } } } for(i = 0; i < DIM; i++){ for(j = 0; j < DIM; j++){ printf("%3d ",m[i][j]); } printf("\n"); } return 0; }
C
#include <stdio.h> #include <gsl/gsl_rng.h> #include <math.h> // #include <stdlib.h> // #include <time.h> double circle_overlap(double *rA, double radiiA, double *rB, double radiiB) { double rAB[2]; rAB[0] = rB[0] - rA[0]; rAB[1] = rB[1] - rA[1]; double F; F = (pow(rAB[0], 2) + pow(rAB[1], 2)) / pow(radiiA + radiiB, 2); return F; } size_t gen_pts_rsa_2d(double *x, double *y, size_t npoints, double radius, int step_limit, unsigned long randSeed) { // Setup GSL random number generator const gsl_rng_type * T; gsl_rng * r; T = gsl_rng_default; r = gsl_rng_alloc (T); // Set the seed // srand ( time(NULL) ); // unsigned long randSeed = rand(); gsl_rng_set(r, randSeed); // Set the initial position double xn = gsl_rng_uniform (r) * (1 - 2 * radius) + radius; double yn = gsl_rng_uniform (r) * (1 - 2 * radius) + radius; x[0] = xn; y[0] = yn; double diameter = 2 * radius; size_t valid_pts; double F; int k, flag, step; step = 0; valid_pts = 1; double rA[2]; double rB[2]; while ((valid_pts < npoints) & (step < step_limit)) { xn = gsl_rng_uniform (r) * (1 - 2 * radius) + radius; yn = gsl_rng_uniform (r) * (1 - 2 * radius) + radius; flag = 1; for (k = 0; k < valid_pts; k++) { rA[0] = x[k]; rA[1] = y[k]; rB[0] = xn; rB[1] = yn; F = circle_overlap(&rA[0], radius, &rB[0], radius); if (F < 1.0) { flag = 0; break; } } if (flag == 1) { x[valid_pts] = xn; y[valid_pts] = yn; valid_pts += 1; } step += 1; } gsl_rng_free (r); return valid_pts; } unsigned int metro_md_2d(double *x, double *y, double radius, size_t npoints, unsigned int step_limit, unsigned long randSeed) { /* Setup GSL random number generator */ const gsl_rng_type * T; gsl_rng * r; T = gsl_rng_default; r = gsl_rng_alloc (T); /* Set the seed */ // srand ( time(NULL) ); // unsigned long randSeed = rand(); gsl_rng_set(r, randSeed); double diameter = 2 * radius; double F, dx, dy, xn, yn; unsigned int step, i, k, flag, success_steps; double rA[2]; double rB[2]; step = 0; success_steps = 0; while (step < step_limit) { i = step % npoints; /* Generate new position */ while (1) { dx = diameter * (gsl_rng_uniform (r) - 0.5); xn = x[i] + dx; dy = diameter * (gsl_rng_uniform (r) - 0.5); yn = y[i] + dy; if (((xn > radius) & (xn < 1 - radius)) & ((yn > radius) & (yn < 1 - radius)) ) { break; } } /* Determine if new position overlaps with other positions */ flag = 1; for (k = 0; k < npoints; k++) { rA[0] = x[k]; rA[1] = y[k]; rB[0] = xn; rB[1] = yn; F = circle_overlap(&rA[0], radius, &rB[0], radius); if ((F < 1.0) & (i != k)) { flag = 0; break; } } if (flag == 1) { x[i] = xn; y[i] = yn; success_steps = success_steps + 1; } step = step + 1; } gsl_rng_free (r); return success_steps; } unsigned int metro_pd_2d(double *x, double *y, double *radius, size_t npoints, int step_limit, unsigned long randSeed) { /* Setup GSL random number generator */ const gsl_rng_type * T; gsl_rng * r; T = gsl_rng_default; r = gsl_rng_alloc (T); /* Set the seed */ // srand ( time(NULL) ); // unsigned long randSeed = rand(); gsl_rng_set(r, randSeed); double F, dx, dy, xn, yn, diameter; unsigned int step, i, k, flag, success_steps; double rA[2]; double rB[2]; step = 0; success_steps = 0; while (step < step_limit) { i = step % npoints; /* Generate new position */ while (1) { diameter = 2 * radius[i]; dx = diameter * (gsl_rng_uniform (r) - 0.5); xn = x[i] + dx; dy = diameter * (gsl_rng_uniform (r) - 0.5); yn = y[i] + dy; if (((xn > radius[i]) & (xn < 1 - radius[i])) & ((yn > radius[i]) & (yn < 1 - radius[i])) ) { break; } } /* Determine if new position overlaps with other positions */ flag = 1; for (k = 0; k < npoints; k++) { rA[0] = x[k]; rA[1] = y[k]; rB[0] = xn; rB[1] = yn; F = circle_overlap(&rA[0], radius[i], &rB[0], radius[k]); if ((F < 1.0) & (i != k)) { flag = 0; break; } } if (flag == 1) { x[i] = xn; y[i] = yn; success_steps += 1; } step = step + 1; } gsl_rng_free (r); return success_steps; }
C
/* * rgb_component_video.c * by Nick Camp and Darby Huye * Assignment 4; 3/8/2018 * * * This file contains functions used for compression from rgb to * component video. The file also contains functions for decompression * from component video to rbg. Compression takes a ppm image and * decompression results in a ppm image. Compression results in a 2D * array of structs containing information about each 2 by 2 pixel block * and decompression takes a 2D array in that form. * * */ #include <stdio.h> #include <rgb_component_video.h> #include "assert.h" #include <stdlib.h> #include <math.h> const double r_y = 0.299; const double g_y = 0.587; const double b_y = 0.114; const double r_pb = -0.168736; const double g_pb = -0.331264; const double b_pb = 0.5; const double r_pr = 0.5; const double g_pr = -0.418688; const double b_pr = -0.081312; const double denom = 255; /* FUNCTIONS FOR IMAGE COMPRESSION -> RGB TO COMPONENT VIDEO */ /* Compresses a ppm image to component video, returning a UArray2 of pixel_info_structs */ UArray2_T compress_to_cv(Pnm_ppm image) { UArray2_T structs; if((image -> width) % 2 != 0) image -> width = (image -> width) - 1; if((image -> height) % 2 != 0) image -> height = (image -> height) - 1; structs = UArray2_new((image-> width)/2, (image->height)/2, sizeof(pixel_info)); populate_struct_array(image, structs); return structs; } /* creates a UArray2 of pixel info structs out of an input ppm image */ void populate_struct_array(Pnm_ppm image, UArray2_T structs) { int row, col, ua2_row = 0, ua2_col= 0; for(row = 0; row < (int)(image -> height); row += 2) { ua2_col = 0; for(col = 0; col < (int)image -> width; col += 2){ pixel_info newStruct; NEW(newStruct); newStruct -> y1 = calc_y(image, col, row); newStruct -> y2 = calc_y(image, col, row + 1); newStruct -> y3 = calc_y(image, col + 1, row); newStruct -> y4 = calc_y(image, col + 1, row + 1); newStruct -> pb = average_p(calc_pb(image, col, row), calc_pb(image, col, row + 1), calc_pb(image, col + 1, row), calc_pb(image, col + 1, row + 1)); newStruct -> pr = average_p(calc_pr(image, col, row), calc_pr(image, col, row + 1), calc_pr(image, col + 1, row), calc_pr(image, col + 1, row + 1)); pixel_info * targetLocation = (UArray2_at(structs, ua2_col, ua2_row)); *targetLocation = newStruct; ua2_col++; } ua2_row++; } } /* calculates a y value out of a given pixel location */ float calc_y(Pnm_ppm image, int col, int row) { Pnm_rgb rgb = (image -> methods -> at) (image -> pixels, col, row); double red = (rgb -> red)/denom; double green = (rgb -> green)/denom; double blue = (rgb -> blue)/denom; return (r_y * red + g_y * green + b_y * blue); } /* averages 4 given pb or pr values */ float average_p(double p1, double p2, double p3, double p4) { return (p1 + p2 + p3 + p4)/4; } /* calculates the pb value of a given pixel location */ double calc_pb(Pnm_ppm image, int col, int row) { Pnm_rgb rgb = (image -> methods -> at) (image -> pixels, col, row); double red = (rgb -> red)/denom; double green = (rgb -> green)/denom; double blue = (rgb -> blue)/denom; return (r_pb * red + g_pb * green + b_pb * blue); } /* calculates the pr value of a given pixel location */ double calc_pr(Pnm_ppm image, int col, int row) { Pnm_rgb rgb = (image -> methods -> at) (image -> pixels, col, row); double red = (rgb -> red)/denom; double green = (rgb -> green)/denom; double blue = (rgb -> blue)/denom; return (r_pr * red + g_pr * green + b_pr * blue); } /* FUNCTIONS FOR DECOMPRESSION -> COMPONENT VIDEO TO RGB */ /* creates a ppm out of given pixel_info_structs */ Pnm_ppm decompress_structs(UArray2_T pixelInfoRay, A2Methods_T methods) { int row, col, ray_row = 0, ray_col = 0; Pnm_ppm decompressed; NEW(decompressed); decompressed -> pixels = (methods->new)(UArray2_width(pixelInfoRay)* 2, UArray2_height(pixelInfoRay) * 2, sizeof(struct Pnm_rgb)); for(row = 0; row < UArray2_height(pixelInfoRay); row++) { ray_col = 0; for(col = 0; col < UArray2_width(pixelInfoRay); col++) { /* compressedInfo gives us the y's, pb, and pr */ pixel_info * compressedInfo = UArray2_at(pixelInfoRay, col, row); Pnm_rgb rgb1, rgb2, rgb3, rgb4; rgb1 = calc_inverse_y((*compressedInfo) -> y1, (*compressedInfo) -> pb, (*compressedInfo) -> pr); rgb2 = calc_inverse_y((*compressedInfo) -> y2, (*compressedInfo) -> pb, (*compressedInfo) -> pr); rgb3 = calc_inverse_y((*compressedInfo) -> y3, (*compressedInfo) -> pb, (*compressedInfo) -> pr); rgb4 = calc_inverse_y((*compressedInfo) -> y4, (*compressedInfo) -> pb, (*compressedInfo) -> pr); free(*compressedInfo); Pnm_rgb pixelLocation = methods -> at(decompressed -> pixels, ray_col, ray_row); *pixelLocation = *rgb1; /* top left of 2x2 block */ pixelLocation = methods -> at(decompressed -> pixels, ray_col, ray_row + 1); *pixelLocation = *rgb2; /* bottom left of 2x2 block */ pixelLocation = methods -> at(decompressed -> pixels, ray_col + 1, ray_row); *pixelLocation = *rgb3; /* top right of 2x2 block */ pixelLocation = methods -> at(decompressed -> pixels, ray_col + 1, ray_row + 1); *pixelLocation = *rgb4; /* bottom right of 2x3 block*/ free(rgb1); free(rgb2); free(rgb3); free(rgb4); ray_col += 2; } ray_row += 2; } decompressed -> width = UArray2_width(pixelInfoRay) * 2; decompressed -> height = UArray2_height(pixelInfoRay) * 2; decompressed -> methods = methods; decompressed -> denominator = denom; return decompressed; } /* creates a pnm_rgb out of a given y, pb, and pr value*/ Pnm_rgb calc_inverse_y(float y, float pb, float pr) { Pnm_rgb rgb; NEW(rgb); double r, g, b; r = ((1.0 * y) + (1.402 * pr)) * denom; r = checkPixelValues(r); g = ((1.0 * y) - ((0.344136 * pb)) - (0.714136 * pr)) * denom; g = checkPixelValues(g); b = ((1.0 * y) + (1.772 * pb)) * denom; b = checkPixelValues(b); rgb -> red = r; rgb -> green = g; rgb -> blue = b; return rgb; } /* calls max 225 and min0 on a given pixel value */ double checkPixelValues(double num) { num = max225(num); num = min0(num); return num; } /* ensures that a pixel value is never above 225 */ double max225(double num) { if(num >= 255) return 255; return num; } /* ensures that a pixel value is never below 0 */ double min0(double num) { if(num <= 0) return 0; return num; }
C
/* * project 1 (shell) main.c template * * project partner names and other information up here, please * */ /* you probably won't need any other header files for this project */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <ctype.h> #include <sys/resource.h> #include <sys/wait.h> #include <sys/types.h> #include <sys/stat.h> #include <poll.h> #include <signal.h> #include <errno.h> #include <assert.h> //Global variables used in functions char m = 's', mode_ret; struct rusage timeusage, Ctimeusage; struct timeval usertime,childusertime, kerneltime,childkerneltime; long double totusertime = 0.0, totkerneltime = 0.0; void time(void){ getrusage(RUSAGE_SELF,&timeusage); getrusage(RUSAGE_CHILDREN,&Ctimeusage); usertime = timeusage.ru_utime; childusertime=Ctimeusage.ru_utime; totusertime=usertime.tv_sec+childusertime.tv_sec+(usertime.tv_usec+childusertime.tv_usec)*(.000001); kerneltime=timeusage.ru_stime; childkerneltime=Ctimeusage.ru_stime; totkerneltime=kerneltime.tv_sec+childkerneltime.tv_sec+(kerneltime.tv_usec+childkerneltime.tv_usec)*(.000001); printf("Total user time: %08Lf, Total kernel time: %08Lf\n",totusertime,totkerneltime); return; } char mode(char** cmd, int numstrings, char m){ if(numstrings < 2){ if(cmd[0][0]!='m'){ return 'f'; } if(m == 's'){ printf("sequential mode\n"); return 's'; }else if(m == 'p'){ printf("parallel mode\n"); return 'p'; }else{ return 'f'; } }else if(!strcasecmp(cmd[1], "sequential")||cmd[1][0] == 's'||!strcasecmp(cmd[1], "seq")){ if(m=='s'){ printf("You are already in sequential mode.\n"); }else{ printf("Going into sequential mode after jobs finish.\n"); } return 's'; }else if(!strcasecmp(cmd[1], "parallel")||cmd[1][0] == 'p'||strcasecmp(cmd[1], "par")){ if(m=='p'){ printf("You are already in parallel mode.\n"); }else{ printf("Going into parallel mode.\n"); } return 'p'; } return 'f'; } void loopfree(char** arr, int numcommands){ int i = 0; for(;i<numcommands;i++){ free(arr[i]); } free(arr); } char* checkpath(char* command, char** prepaths, int numpaths){ int test = 0, i = 0; char cmd[1024]; char path[1024]; char* c = strdup(command); struct stat statinfo; if(prepaths == NULL || (test=stat(command,&statinfo))==0){ return c; } char* cmdpath; for(;i<numpaths;i++){ strcpy(cmd,command); strcpy(path,prepaths[i]); cmdpath=malloc(sizeof(char)*(strlen(cmd)+strlen(path))+1); sprintf(cmdpath,"%s%s",path, cmd); if((test = stat(cmdpath,&statinfo))==0){ free(c); return cmdpath; } free(cmdpath); } return c; } int Numstrings(char* string, char delim){ int i = 0, count = 1; for(;i<strlen(string);i++){ if(string[i] == delim){ count++; } } return count; } void removeextrainput(char* s){ if(s==NULL){ return;} int len = strlen(s), i = 0, j = 0, numspaces = 0, space = 0; int text = 0, symbol = 0, remove = 0, numcolons = 0; for(; i < len; i++){ if(s[i] == '#'){ s[i] = '\0';break; } } i = 0; len =strlen(s); while(i<len-numcolons){ if(s[i]==';'){ j=i+1; symbol++; if(text==0){ remove = 1; } }else if(isalpha(s[i]) ||(!isspace(s[i]) && s[i]!=';')){ text = 1; symbol = 0; remove = 0; } if(symbol > 1 || remove > 0){ while(j<len-numcolons){ s[j-1] = s[j]; j++; } symbol--; numcolons++; remove = 0; continue; } i++; } s[len-numcolons]='\0'; i=0,j=0,len = strlen(s), text = 0, symbol = 0; while(i<len-numspaces){ if(isspace(s[i])){ j = i +1; space++; //know its a space but not sure if its 2 spaces in a row. if(text == 0 || symbol == 1){ space++; } if(s[i] == '\n' || s[i] == '\t' || s[i] == '\r'){ space++; //makes it so it definitely is removed } }else if(s[i] == ';'){ symbol = 1; if(space>0){ space++; } } if(space >1){ while(j<len -numspaces){ s[j-1] = s[j]; j++; } space--; numspaces++; if(symbol == 1){ space--; } continue; } if(isalpha(s[i]) || (!isspace(s[i])&&s[i]!=';')){ space = 0; text = 1; symbol = 0; } i++; } if(isspace(s[i-1])||s[i-1]==';'){ s[i-1] = '\0'; } else{ s[len-numspaces] = '\0'; } } char** tokenify(char *s, char* delim){ if(s==NULL){ return NULL;} int len = strlen(s); char** tokstrings; int i = 0, numtokens = 0; for(;i<len;i++){ if(s[i] == delim[0]){ numtokens++; } } if(numtokens==0){ tokstrings = malloc(sizeof(char*) +sizeof(NULL)); tokstrings[0] = strdup(s); tokstrings[1] = NULL; return tokstrings;} tokstrings = malloc(sizeof(char *) * (numtokens + 1)+sizeof(NULL)); tokstrings[0] = strdup(strtok(s,delim)); i = 1; while(i<numtokens+1){ tokstrings[i] = strdup(strtok(NULL, delim)); i++; } tokstrings[i] = NULL; return tokstrings; } int numpaths(){ FILE* file = fopen("shell-config","r"); char buffer[1024]; int count = 0; while(fgets(buffer,1024,file)!=NULL){ count++; } fclose(file); return count; } char** patharray(int npaths){ int i = 0; char path[1024]; char** paths = malloc(sizeof(char*)*npaths+1); FILE* file = fopen("shell-config", "r"); if(file == NULL){ fclose(file); printf("Missing PATH file. You will have to enter the full command name to execute.\n"); return NULL; } while(fgets(path,1024,file)!=NULL){ if(path[strlen(path)-1] == '\n'){ path[strlen(path)-1] = '\0'; } paths[i] = strdup(path); i++; } paths[i] = NULL; fclose(file); return paths; } void parallel(char** commands, int numcommands, int i/*commandnum*/, char** prepaths){ int numchildren = numcommands - i, k = 0, j = 0, numstrings = 0, flag = 0, npaths = numpaths(); pid_t* childPIDS; char** cmd; childPIDS = malloc(sizeof(pid_t)*numchildren+sizeof(NULL)); pid_t childpid; for(;i<numcommands;i++){ numstrings = Numstrings(commands[i], ' '); char** tcmd = tokenify(commands[i], " "); char* tempcmd = checkpath(tcmd[0],prepaths,npaths); char** cmd = malloc(sizeof(char*)*numstrings+sizeof(NULL)); int t = 1; cmd[0] = tempcmd; for(;t<numstrings;t++){ cmd[t] = strdup(tcmd[t]); } cmd[t] = NULL; if((!strcasecmp(cmd[0], "mode"))||(strlen(cmd[0])==1)){ mode_ret = mode(cmd, numstrings, m); if(mode_ret == m){ loopfree(cmd, numstrings); loopfree(tcmd, numstrings); numchildren--; continue; }else if(mode_ret == 'f'){ }else{ m = mode_ret; loopfree(cmd, numstrings);loopfree(tcmd,numstrings); numchildren--; continue; } } if(!strcasecmp(cmd[0], "exit")){ flag = 1; numchildren--; loopfree(cmd, numstrings); loopfree(tcmd, numstrings);printf("Will exit shell once all jobs have finished.\n"); continue; } if((childpid=fork())==0){ printf("In child: %d with PID: %d\n", j, getpid()); if (execv(cmd[0], cmd) < 0) { fprintf(stderr, "execv failed: %s\n", strerror (errno)); loopfree(cmd,numstrings); loopfree(commands,numcommands); free(childPIDS); loopfree(prepaths,npaths);loopfree(tcmd,numstrings); exit(0); } }else{ childPIDS[j] = childpid; } loopfree(cmd, numstrings); loopfree(tcmd,numstrings); j++; } for(; k<numchildren; k++){ int rstatus=0; pid_t child; if(childPIDS[k]>0){ child = waitpid(childPIDS[k],&rstatus,0); printf("Parent got carcass of child process %d, return val %d\n", child, rstatus); printf("Parallel mode bitch\n"); assert(childPIDS[k] == child); childPIDS[k] = 0; }else{ /* fork had an error; bail out */ fprintf(stderr, "fork failed: %s\n", strerror(errno)); exit(0); } } free(childPIDS); if(flag > 0){ loopfree(commands, numcommands); loopfree(prepaths,npaths);time(); exit(0); } } int main(int argc, char **argv) { int i = 0, numcommands=0,numstrings=0, npaths = numpaths(); char *prompt = "hitme> ", nulltest; char **commands; char **prepaths = patharray(npaths); printf("%s", prompt); fflush(stdout); char buffer[1024]; while ((nulltest=fgets(buffer, 1024, stdin)) != NULL) { /* process current command line in buffer */ i = 0; int len = strlen(buffer); buffer[len -1] = '\0'; removeextrainput(buffer); numcommands = Numstrings(buffer, ';'); commands = tokenify(buffer, ";"); if(commands == NULL){ printf("Error reading input."); printf("%s", prompt); fflush(stdout); continue; } while(i < numcommands){ if(m=='p'){ parallel(commands, numcommands, i,prepaths); break; } numstrings = Numstrings(commands[i], ' '); char** tcmd = tokenify(commands[i], " "); char* tempcmd = checkpath(tcmd[0],prepaths,npaths); char** cmd = malloc(sizeof(char*)*numstrings+sizeof(NULL)); int t = 1; cmd[0] = tempcmd; for(;t<numstrings;t++){ cmd[t] = strdup(tcmd[t]); } cmd[t] = NULL; if(!strcasecmp(cmd[0], "exit")){ loopfree(commands,numcommands); loopfree(cmd, numstrings);loopfree(prepaths,npaths);loopfree(tcmd, numstrings);time(); exit(0); } if((!strcasecmp(cmd[0], "mode"))||(strlen(cmd[0])==1)){ mode_ret = mode(cmd, numstrings, m); if(mode_ret == m){ i++; loopfree(cmd, numstrings);loopfree(tcmd,numstrings); continue; }else if(mode_ret == 'f'){ }else{ m = mode_ret; loopfree(cmd, numstrings);loopfree(tcmd,numstrings); i++; continue; } } pid_t p = fork(); if (p == 0) { /* in child */ if (execv(cmd[0], cmd) < 0) { fprintf(stderr, "execv failed: %s\n", strerror (errno)); loopfree(cmd,numstrings);loopfree(commands,numcommands); loopfree(prepaths,npaths);loopfree(tcmd,numstrings); exit(0); } } else if (p > 0) { /* in parent */ int rstatus = 0; pid_t childp = wait(&rstatus); /* for this simple starter code, the only child process we should "wait" for is the one we just spun off, so check that we got the same process id */ assert(p == childp); printf("Parent got carcass of child process %d, return val %d\n", childp, rstatus); } else { /* fork had an error; bail out */ fprintf(stderr, "fork failed: %s\n", strerror(errno)); } i++; //next command loopfree(cmd, numstrings); loopfree(tcmd,numstrings); } loopfree(commands, numcommands); //all commands have finished printf("%s", prompt); fflush(stdout); } if(nulltest==NULL){ loopfree(prepaths,npaths);time(); return 0; } loopfree(commands, numcommands); loopfree(prepaths,npaths); time(); return 0; }
C
#include <stdio.h> int main() { int p,q,i,j,k,count=0; scanf("%d %d",&p,&q); for(i=p;i<=q;i++) { for(j=1;j<=i;j++) { k=j*j; if(k==i) { count=count+1; break; } } } printf("%d",count); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <time.h> #include <unistd.h> #define textin "A.txt" void printall(char text[], char* theword); void mywait(double seconds); int main(int argc, char* argv[]) { char* theword; if (argv[1] == '\0') theword = "a"; else theword = argv[1]; // theword = "ing"; printall(textin, theword); putchar('\n'); return 0; } void mywait(double seconds) { usleep(seconds*1000000); fflush(stdout); } void printall(char text[], char* theword) { FILE* fp; fp = fopen(text, "r"); char nextchar = 'a'; int permitnewline = 0; int checkword = 1; int i = 0; int wordlen = strlen(theword); int words = 0; printf("%d", wordlen); while (nextchar != EOF) { nextchar = getc(fp); checkword = 1; i = 0; while ((i<wordlen) && (checkword) && (nextchar != EOF)) { nextchar = getc(fp); if (nextchar == theword[i]) { checkword = checkword*1; } else { checkword = 0; }; i = i+1; }; if (checkword) { mywait(0.1); words = 0; printf("%s", theword); for (int i=0;((i<150) && (words<7) && (nextchar != EOF));i++) { nextchar = getc(fp); if (isspace(nextchar)) words = words+1; printf("%c", nextchar); mywait(0.05); }; putchar(' '); permitnewline = 1; } else if ((nextchar !='\n') && (permitnewline == 1)) printf(" "); if ((nextchar == '\n') && (permitnewline == 0)) { permitnewline = 0; printf("\n"); }; permitnewline = 0; checkword = 1; }; }
C
/* * DoublyLinkedList.c * * Created on: 2018. 5. 11. * Author: sha */ #include<stdio.h> typedef struct DLLNode{ int data; struct DLLNode *next; struct DLLNode *prev; }DLLNode; //߿ḮƮ ϿḮƮ q ʿ. void DLLInsert(struct DLLNode **head, int data, int position){ int k = 1; struct DLLNode *temp, *newNode; newNode = (struct DLLNode *)malloc(sizeof(struct DLLNode)); if(!newNode){//׻ ޸𸮿 üũ printf("Memory error"); return; } newNode->data = data; if(position == 1){// ġ 带 newNode->next=*head; newNode->prev = NULL; if(*head) (*head)->prev = newNode; *head = newNode; return; } temp = *head; // , temp 带 Űų //ϰ ϴ ġ 带 Ŵ while((k<position) && temp->next!=NULL){ temp = temp->next; k++; } if(k!=position){ printf("Desired position deos not exist\n"); } newNode->next=temp->next; newNode->prev=temp; if(temp->next) temp->next->prev=newNode; temp->next=newNode; return; } void DDLDelete(struct DLLNode **head, int position){ struct DLLNode *temp, *temp2; temp = *head; int k=1; if(*head == NULL){ printf("Lis t is empty"); return; } if(position == 1){ *head = *head->next; if(*head != NULL) *head->prev = NULL; free(temp); return; } //temp while((k<position-1) && temp->next!=NULL){ temp = temp->next; k++; } if(k!=position-1){ printf("Desired position does not exist\n"); } temp2=temp->prev; temp2->next=temp->next; if(temp->next)//߰ temp->next->prev=temp2; free(temp); return; }
C
#include "../../includes/verify.h" #include "../../includes/math_functions_double.h" #include "double_acos.h" int main() { /* REQ-BL-0480: * The acos and acosf procedures shall return NAN , if the argument x is +-inf */ double x = 1.0/0.0; // INF __VERIFIER_precond_reach(); double res = __ieee754_acos(x); // x is +inf, the result shall be NAN if (!isnan_double(res)) { __VERIFIER_error(); return 1; } return 0; }
C
/* * l_psensor.c * * Created on: 23 ago. 2019 * Author: pablo * * El sensor mide presion diferencial. * Por lo tanto retorna PRESION de acuerdo a la funcion de transferencia * con la pMax la de la hoja de datos. * De acuerdo a la hoja de datos, la funcion de transferencia es: * p(psi) = (pmax - pmin ) * ( counts - 0.1Max) / ( 0.8Max) + pmin * pmin = 0 * Max = 16384 ( 14 bits ) * 0.1xMax = 1638 * 0.8xMax = 13107 * counts es el valor leido del sensor. * PMAX = 1.0 psi * PMIN = 0 psi * */ #include "l_abp.h" //------------------------------------------------------------------------------------ int8_t abp_raw_read_and_sleep( uint8_t sensor_id, char *data ) { // Mando un FNR y luego reinsisto con una lectura hasta que el status sea ok. int8_t rcode = -1; uint8_t times = 3; // Leo en modo raw el sensor I2C_get_semaphore(); //I2C_send_FMR( BUSADDR_ABP ); while ( times-- > 0 ) { // Leo 2 bytes del sensor de presion. rcode = I2C_read_R1( BUSADDR_ABP, data, 0x02 ); // Errores if ( rcode == -1 ) { // Hubo error: trato de reparar el bus y reintentar la operacion // Espero 1s que se termine la fuente de ruido. vTaskDelay( ( TickType_t)( 1000 / portTICK_RATE_MS ) ); // Reconfiguro los dispositivos I2C del bus que pueden haberse afectado xprintf_P(PSTR("ERROR: ABP_raw_read recovering i2c bus (%d)\r\n\0"), times ); I2C_reinit_devices(); } else { // No hubo error: salgo normalmente break; } // Si el status no es OK, reintento } I2C_release_semaphore(); return( rcode ); } //------------------------------------------------------------------------------------ int8_t abp_raw_read( uint8_t sensor_id, char *data ) { // En estos sensores no llevan el ciclo Dummy Write. !! // Solo se leen 2 caracteres. // Se lee del bus I2C en modo raw ( 2 bytes ) que no son interpretados // Los 2 sensores estan atras del muxi2c por lo tanto debemos activar la salida // adecuada al sensor que queremos leer. int8_t rcode = -1; uint8_t times = 1; // Activo el canal del muxI2C para el sensor_id // if ( ! I2CMUX_enable_channel(sensor_id) ) { // return(-1); // } // Leo en modo raw el sensor while ( times-- > 0 ) { // Leo 2 bytes del sensor de presion. I2C_get_semaphore(); rcode = I2C_read_R1( BUSADDR_ABP, data, 0x02 ); I2C_release_semaphore(); if ( rcode == -1 ) { // Hubo error: trato de reparar el bus y reintentar la operacion // Espero 1s que se termine la fuente de ruido. vTaskDelay( ( TickType_t)( 1000 / portTICK_RATE_MS ) ); // Reconfiguro los dispositivos I2C del bus que pueden haberse afectado xprintf_P(PSTR("ERROR: ABP_raw_read recovering i2c bus (%d)\r\n\0"), times ); I2C_reinit_devices(); } else { // No hubo error: salgo normalmente break; } } return( rcode ); } //------------------------------------------------------------------------------------ void abp_FMR(void) { I2C_get_semaphore(); xprintf_P(PSTR("ABP DEBUG: Send FMR\r\n")); I2C_send_FMR( BUSADDR_ABP ); I2C_release_semaphore(); } //------------------------------------------------------------------------------------ void abp_PMR(void) { I2C_get_semaphore(); xprintf_P(PSTR("ABP DEBUG: Send PMR\r\n")); I2C_send_PMR( BUSADDR_ABP ); I2C_release_semaphore(); } //------------------------------------------------------------------------------------ bool abp_raw_read_test( uint8_t sensor_id ) { // Wrapper de la funcion abp_raw_read para cmdMode. // Sensor Honeywll ABPMANV150PG2A3 // Invocada desde cmdMode: interpreta los resultados raw del sensor // Debe habilitar el canal correspondiente del i2cmux. bool retS = false; uint8_t data[2]; uint8_t status; uint16_t p_counts; if ( abp_raw_read( sensor_id, (char *)data ) > 0 ) { retS = true; xprintf_P(PSTR("ABP_LOW : 0x%02X\r\n"), data[1]); xprintf_P(PSTR("ABP_HIGH: 0x%02X\r\n"), data[0]); status = data[0] >> 6; xprintf_P(PSTR("Status: 0x%02X\r\n"), status); p_counts = ((data[0] & 0x3F) << 8) + data[1]; xprintf_P(PSTR("Pcounts: %05d (0x%04X)\r\n"), p_counts, p_counts ); } else { xprintf_P( PSTR("abp_test_raw_read ERROR\r\n")); } return(retS); } //------------------------------------------------------------------------------------
C
#include <stdio.h> #include <stdlib.h> #include "funcoes_vetor.h" #include "funcoes_visao.h" int le_tamanho_vetor(){ int tamanho_vetor; system("clear"); printf("Digite a quantidade de inteiros para serem armazenados: "); scanf("%d", &tamanho_vetor); return tamanho_vetor; } void le_inteiros_vetor(int *vetor, int tamanho_vetor){ int i; printf("\n"); for (i = 0; i < tamanho_vetor; i++) { printf("Digite o valor %d: ", i+1); scanf("%d", &vetor[i]); } } void mostra_vetor_ordenado(int *vetor, int tamanho_vetor){ int i; system("clear"); printf("Inteiros ordenados = "); for(i = 0; i < tamanho_vetor; i++){ printf("%d ", vetor[i]); } printf("\n\n"); }
C
#include <stdio.h> int main() { //If checking on the value of a single variable, it is better to use switch statement than if else char operator; double firstNum, secondNum; printf("enter an operator: "); scanf("%c", &operator); printf("enter two operands: "); scanf("%lf %lf", &firstNum, &secondNum); switch(operator) { case '+': printf("%.1lf + %.1lf = %.1lf \n", firstNum, secondNum, firstNum + secondNum); break; case '-': printf("%.1lf - %.1lf = %.1lf \n", firstNum, secondNum, firstNum - secondNum); break; case '*': printf("%.1lf * %.1lf = %.1lf \n", firstNum, secondNum, firstNum * secondNum); break; case '/': printf("%.1lf / %.1lf = %.1lf\n", firstNum, secondNum, firstNum / secondNum); break; default: printf("Error! operator is not correct \n"); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define SZ(n) ((2 * n + 1) * (sizeof(char))) char * count(char *s, int n, char *pc) { // printf(" %d \n", n ); int i = 0; int count = 1; int j = 0; for (; i < n; i++) { if (i + 1 != n && s[i] == s[i + 1]) { count++; } else { snprintf((pc + j), 3, "%d%d", count, s[i] - '0'); count = 1; j += 2; } } return pc; } char * countAndSay(int n) { char *s = malloc(SZ(n)); memset(s, '\0', SZ(n)); s[0] = '1'; s[1] = '\0'; char *proc; char *temp; for (int i = 2; i <= n; i++) { proc = malloc(SZ(strlen(s))); memset(proc, '\0', SZ(strlen(s))); temp = count(s, strlen(s), proc); //memset(s, '\0', SZ(n)); //strcpy(s, temp); free(s); s = proc; } return s; } int main() { printf("%s\n", countAndSay(100)); return 0; }
C
//Zachary Gill //CGS 3269 Spring 2017 //Program 3 //04-17-17 #include "P.h" #include "instruction.h" #include "stack.h" #include "IO.h" //Variables struct registers r; //Functions /* Runs the pMachine simulation. */ void pMachine() { initializeRegisters(); initializeLog(); do { fetch(); logFetch(); execute(); logExecute(); } while (!halt && r.PC != 0); } /* Fetches the next instruction from the instruction array. */ void fetch() { r.IR = getInstruction(r.PC); r.PC++; } /* Executes the current instruction in the simulation. */ void execute() { switch (r.IR.OP) { case 1 : //LIT LIT(); break; case 2 : //OPR switch (r.IR.M) { case 0: //RET OPR_RET(); break; case 1: //NEG OPR_NEG(); break; case 2: //ADD OPR_ADD(); break; case 3: //SUB OPR_SUB(); break; case 4: //MUL OPR_MUL(); break; case 5: //DIV OPR_DIV(); break; case 6: //ODD OPR_ODD(); break; case 7: //MOD OPR_MOD(); break; case 8: //EQL OPR_EQL(); break; case 9: //NEQ OPR_NEQ(); break; case 10: //LSS OPR_LSS(); break; case 11: //LEQ OPR_LEQ(); break; case 12: //GTR OPR_GTR(); break; case 13: //GEQ OPR_GEQ(); break; } break; case 3: //LOD LOD(); break; case 4: //STO STO(); break; case 5: //CAL CAL(); break; case 6: //INC INC(); break; case 7: //JMP JMP(); break; case 8: //JPC JPC(); break; case 9: //SIO switch (r.IR.M) { case 1: //SIO 1 SIO_1(); break; case 2: //SIO 2 SIO_2(); break; case 3: //SIO 3 SIO_3(); break; } } } /* Prints information about the fetched instruction to the output file. */ void logFetch() { fprintf(output, "%2d%7s %-6d%-6d", r.PC - 1, opCodeName(r.IR.OP), r.IR.L, r.IR.M); } /* Prints information about the current register and stack state to the output file. */ void logExecute() { //if (r.IR.OP == 9 && r.IR.M == 3) //dont print if halted // return; fprintf(output, "%-6d%-6d%-6d", r.PC, r.BP, r.SP); printStack(); fprintf(output, "\n"); } /* Initializes the registers to their default values at the start of the simulation. */ void initializeRegisters() { r.SP = 0; //Stack Pointer r.BP = 1; //Base Pointer r.PC = 0; //Program Counter r.IR.OP = 0; //Instruction Register r.IR.L = 0; //Instruction Register r.IR.M = 0; //Instruction Register }
C
/* tpifArray1.c: If-statement and subscripted var. */ main( ) { int i; int s, q, a[100]; i=0;s=1,a[0]=2; /* SF030620 */ if (s>0) a[i]=a[i]*s; printf("s=%d a[%d]=%d\n",s,i,a[i]); /* SF030620 */ }
C
#include <stdio.h> int main(void) { int arr[3][9]={0}; int i=2, j; for( ; i<5; i++) { for(j=1; j<10; j++) { arr[i-2][j-1] = i*j; } } for( i=2; i<5; i++) { for(j=1; j<10; j++) { printf("%d ", arr[i-2][j-1]); } printf("\n"); } return 0; }
C
# include <stdio.h> # include <math.h> int main() { // 600851475143 long long i,j,k,l,num = 600851475143; _Bool flag = 1; for (i = 2,j = num /i;flag != 0;i++,j = num/i , flag = 1) { if (i * j == num) { k = sqrt((double)j); for (l = 2;l <= k;l++) { if(j % l == 0) { flag = 0; break; } } if (flag) { break; } } } printf("%lld\n",j); // 6857 return 0; }
C
#include<GL/freeglut.h> #include<math.h> #include <graphics.h> void init(){ glClearColor(0.986,1.0,1.0,0.0); glMatrixMode (GL_PROJECTION); gluOrtho2D (0.0, 200.0, 0.0, 150.0); } void boundaryfill(int x,int y,int f_color,int b_color) { if(getpixel(x,y)!=b_color && getpixel(x,y)!=f_color) { putpixel(x,y,f_color); boundaryfill(x+1,y,f_color,b_color); boundaryfill(x,y+1,f_color,b_color); boundaryfill(x-1,y,f_color,b_color); boundaryfill(x,y-1,f_color,b_color); } } /*void display(){ int i; glClear(GL_COLOR_BUFFER_BIT); glColor3f (0.0, 0.4, 0.2); glBegin (GL_LINES); for (i = 1; i < 150; i++){ glVertex2i (0, i); glVertex2i (i+50, 0); //glVertex2i (0,0); } glEnd ( ); glFlush ( ); }*/ void display(){ float theta; int posX = 100; int posY = 100; int radius = 30; glClear(GL_COLOR_BUFFER_BIT); glColor3f(0,0,0); glBegin(GL_POINTS); for(int i=0; i<360; i++){ theta = i*3.1416/180; glVertex2f(posX + radius*cos(theta), posY + radius*sin(theta)); } boundaryfill(100,100,100,0); glEnd(); glFlush(); } int main(int argc,char **argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowSize(640,480); glutInitWindowPosition(1000,200); glutCreateWindow("Simple Window"); init(); //Line B glutDisplayFunc(display); glutMainLoop(); }
C
#include <stdio.h> int main(int argc, char *argv[]) { int i,a,b,c,n,s; c=0; s=0; for (i=0;i<3;i++) { scanf("%d",&a); s+=a; } c+=(s+4)/5; s=0; for (i=0;i<3;i++) { scanf("%d",&b); s+=b; } c+=(s+9)/10; if (c>n) printf("NO"); else printf("YES"); return 0; }
C
/* * AppendPoint.cpp * * Created on: Nov 9, 2018 * Author: jludwig */ #include "kv_append_point.h" #include "kv_block_allocator.h" #include <errno.h> struct kv_append_point { struct kv_block_allocator *block_allocator; uint32_t current_append_point; uint64_t last_scanned_sequence_number; }; int kv_append_point__init(struct kv_append_point **append_point, struct kv_block_allocator *block_allocator) { *append_point = (struct kv_append_point *)malloc(sizeof(struct kv_append_point)); if (!*append_point) { return -ENOMEM; } (*append_point)->block_allocator = block_allocator; (*append_point)->current_append_point = 0; (*append_point)->last_scanned_sequence_number = 0; return 0; } void kv_append_point__cleanup(struct kv_append_point **append_point) { free(*append_point); *append_point = NULL; } uint32_t kv_append_point__get_append_point(struct kv_append_point *append_point) { if (append_point->current_append_point == UINT32_MAX) { // If we ran out of space before, start back at 0. append_point->current_append_point = 0; } // Start from the last append point used (or seen at replay) and find the next free block. append_point->current_append_point = kv_block_allocator__find_next_free_block(append_point->block_allocator, append_point->current_append_point); return append_point->current_append_point; } void kv_append_point__update_append_point(struct kv_append_point *append_point, uint32_t block, uint64_t sequence) { // See if this sequence was higher than the last seen. if (sequence >= append_point->last_scanned_sequence_number) // >= to handle only block 0 written. { // This sequence is higher. Use this block as the append point. // The call to get_append_point will take care of advancing it past this block. append_point->current_append_point = block; // Keep track of this sequence until we find a higher one. append_point->last_scanned_sequence_number = sequence; } }
C
#include <stdio.h> #include <math.h> int main() { double a, b, c, disc, x1, x2, p, q; scanf("%lf %lf %lf", &a, &b, &c); disc = b * b - 4 * a * c; p = -b / (2 * a); q = sqrt(disc) / 2 * a; x1 = p + q; x2 = p - q; printf("\nx1=%5.2f\nx2=%5.2f\n", x1, x2); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include "circularList.h" // Double link struct Link { TYPE value; struct Link * next; struct Link * prev; }; struct CircularList { int size; struct Link* sentinel; }; /** * Allocates the list's sentinel and sets the size to 0. * The sentinel's next and prev should point to the sentinel itself. */ static void init(struct CircularList* list) { list->sentinel = (struct Link *)malloc(sizeof(struct Link)); assert(list->sentinel != 0); // Assign pointers list->sentinel->next = list->sentinel; list->sentinel->prev = list->sentinel; list->sentinel->value = -1; // Assign size = 0 list->size = 0; } /** * Creates a link with the given value and NULL next and prev pointers. */ static struct Link* createLink(TYPE value) { // Create link struct Link * newLink = (struct Link *)malloc(sizeof(struct Link)); // Create null pointers newLink->next = NULL; newLink->prev = NULL; // Save value in link newLink->value = value; // Return link return newLink; } /** * Adds a new link with the given value after the given link and * increments the list's size. */ static void addLinkAfter(struct CircularList* list, struct Link* link, TYPE value) { struct Link * addMe = createLink(value); // Assign addMe pointers addMe->next = link->next; addMe->prev = link; // Assign pointers to links flanking addMe (addMe->next)->prev = addMe; (addMe->prev)->next = addMe; // Increment list size list->size++; } /** * Removes the given link from the list and * decrements the list's size. */ static void removeLink(struct CircularList* list, struct Link* link) { printf("Link to be deleted: %g\n", link->value); // Point flanking links to each other link->prev->next = link->next; link->next->prev = link->prev; // Null link pointers and delete link link->next = NULL; link->prev = NULL; free(link); link = NULL; // Decrement list size list->size--; } /** * Allocates and initializes a list. */ struct CircularList* circularListCreate() { struct CircularList* list = malloc(sizeof(struct CircularList)); init(list); return list; } /** * Deallocates every link in the list and frees the list pointer. */ void circularListDestroy(struct CircularList* list) { while (!circularListIsEmpty(list)) { struct Link * temp = list->sentinel->next; removeLink(list, temp); } free(list->sentinel); free(list); } /** * Adds a new link with the given value to the front of the deque. */ void circularListAddFront(struct CircularList* list, TYPE value) { addLinkAfter(list, list->sentinel, value); } /** * Adds a new link with the given value to the back of the deque. */ void circularListAddBack(struct CircularList* list, TYPE value) { addLinkAfter(list, list->sentinel->prev, value); } /** * Returns the value of the link at the front of the deque. */ TYPE circularListFront(struct CircularList* list) { return ((list->sentinel)->next)->value; } /** * Returns the value of the link at the back of the deque. */ TYPE circularListBack(struct CircularList* list) { return ((list->sentinel)->prev)->value; } /** * Removes the link at the front of the deque. */ void circularListRemoveFront(struct CircularList* list) { removeLink(list, (list->sentinel)->next); } /** * Removes the link at the back of the deque. */ void circularListRemoveBack(struct CircularList* list) { removeLink(list, (list->sentinel)->prev); } /** * Returns 1 if the deque is empty and 0 otherwise. */ int circularListIsEmpty(struct CircularList* list) { if (list->size == 0) { return 1; } return 0; } /** * Prints the values of the links in the deque from front to back. */ void circularListPrint(struct CircularList* list) { int size = list->size; struct Link * itr = list->sentinel->next; printf("List front to back: "); while (size) { printf("%g, ", itr->value); //printf("\tValue:%lf, Address:%p, Address next:%p, Address before:%p, value next: %lf\n", itr->value, itr, itr->next, itr->prev, itr->next->value); itr = itr->next; size--; } printf("\n"); } /** * Reverses the deque. */ void circularListReverse(struct CircularList* list) { struct Link * itr = list->sentinel; // Traverse all size + 1 links (data links + sentinel) for (int i = 0; i < list->size + 1; i++) { // Save current node struct Link * temp = itr->next; // Set current node next to previous itr->next = itr->prev; // Set current node prev to next itr->prev = temp; // Traverse to *new* next node itr = itr->next; } }
C
#include <stdio.h> #include <stdlib.h> #include "scanner.h" #include "nodes.h" Node * newEmptyNode(void) { Node *p = malloc(sizeof(Node)); //check for malloc failure omitted p->value = 0; //set to empty p->next = 0; //set to the null pointer return p; } Node * newNode(int v,Node *n) { Node *p = malloc(sizeof(Node)); //check for malloc failure omitted p->value = v; p->next = n; return p; } int getNodeValue(Node *n) { return n->value; } Node *getNodeNext(Node *n) { return n->next; } void setNodeValue(Node *n,int v) { n->value = v; return; } void setNodeNext(Node *n,Node *p) { n->next = p; return; } Node * readIntegers(FILE *fp) { int x; Node *items; items = 0; //items starts out as null //employ the standard reading pattern x = readInt(fp); while (!feof(fp)) { items = newNode(x,items); x = readInt(fp); } return items; } void displayList(Node *items) { while (items != 0) { printf("{%d}",getNodeValue(items)); items = getNodeNext(items); } printf("\n"); }
C
#define COL_LIMIT 5 typedef struct message { int timestamp; /*10 digitos*/ int id; /*5*/ int x, y; /*2 digitos cada*/ int vel, dir, sent, tam; /*2, 1, 1, 2*/ } message; typedef struct car { int id; /*5*/ int x, y; /*2 digitos cada*/ int vel, dir, sent, tam; /*2, 1, 1, 2*/ } car; message strtomsg (char* str){ message msg; char substr[11]; memcpy(substr, &str[0], 10); substr[11] = '\0'; msg.timestamp = atoi(substr); memcpy(substr, &str[10], 5); substr[5] = '\0'; msg.id = atoi(substr); memcpy(substr, &str[15], 2); substr[2] = '\0'; msg.x = atoi(substr); memcpy(substr, &str[17], 2); substr[2] = '\0'; msg.y = atoi(substr); memcpy(substr, &str[19], 2); substr[2] = '\0'; msg.vel = atoi(substr); memcpy(substr, &str[21], 1); substr[1] = '\0'; msg.dir = atoi(substr); memcpy(substr, &str[22], 1); substr[1] = '\0'; msg.sent = atoi(substr); memcpy(substr, &str[23], 2); substr[2] = '\0'; msg.tam = atoi(substr); return msg; } char* msgtostr(message msg){ char* str[26]; sprintf(str, "%010d%05d%02d%02d%02d%01d%01d%02d", msg.timestamp, masg.id, msg.x, msg.y, msg.vel, msg.dir, msg.sent, msg.tam); return str; } int* checkcolision(car cars[], int n, car obj){ int tempo_io, tempo_ij, tempo_fo, tempo_fj; //se o carro atual estiver indo em direção ao cruzamento if(((obj.dir == 1) && (obj.y*obj.sent < 0)) || ((obj.dir == 0) && (obj.x*obj.sent < 0))){ for (size_t j = 0; j < n; j++) { if((obj.dir != cars[j].dir)){ if (((obj.dir == 1)&&(cars[j].x*cars[j].sent < 0)) || ((obj.dir == 0)&&(cars[j].y*cars[j].sent < 0))) { tempo_io = obj.x / obj.vel; tempo_ij = cars[j].x / cars[j].vel; tempo_fo = tempo_io + (obj.tam / obj.vel); tempo_fj = tempo_ij + (cars[j].tam / cars[j].vel); if (tempo_io - tempo_ij < COL_LIMIT) || (tempo_ij - tempo_io < COL_LIMIT) { /* chamar ambulancia */ } else if ((tempo_ij >= tempo_io) && (tempo_ij <= tempo_fo)) { /* j freia, obj acelera */ } else if ((tempo_io >= tempo_ij) && (tempo_io <= tempo_fj)) { /* obj freia, j acelera */ } } } } } /* for (size_t j = 0; j < n; j++) { if(obj.dir != cars[j].dir){ if (((obj.dir == 1)&&(obj.y*obj.sent < 0)&&(cars[j].x*cars[j].sent < 0)) || ((obj.dir == 0)&&(obj.x*obj.sent < 0)&&(cars[j].y*cars[j].sent < 0))) { tempo_io = obj.x / obj.vel; tempo_ij = cars[j].x / cars[j].vel; tempo_fo = tempo_io + (obj.tam / obj.vel); tempo_fj = tempo_ij + (cars[j].tam / cars[j].vel); if (tempo_io - tempo_ij < COL_LIMIT) || (tempo_ij - tempo_io < COL_LIMIT) { /* chamar ambulancia } else if ((tempo_ij >= tempo_io) && (tempo_ij <= tempo_fo)) { /* j freia, i acelera } else if ((tempo_io >= tempo_ij) && (tempo_io <= tempo_fj)) { /* i freia, j acelera } } } } */ return "\0"; }
C
#ifndef __HALF_EDGE_STRUCTURE__ #define __HALF_EDGE_STRUCTURE__ #include <stdlib.h> struct Solid; struct Face; struct Loop; struct HalfEdge; struct Vertex; struct Edge; struct Solid { int id; Face *faces; Edge *edges; Solid *next; Solid *pre; int vnum; int fnum; int lnum; Solid() : id(0), faces(NULL), edges(NULL), next(NULL), pre(NULL), fnum(0), vnum(0), lnum(0){} }; struct Face { int id; Solid *solid; Loop *out_lp; Loop *inner_lp; Face *next; Face *pre; int innum; Face() : id(0), solid(NULL), out_lp(NULL), next(NULL), pre(NULL), inner_lp(NULL), innum(0){} }; struct Loop { int id; HalfEdge *halfedges; Face *face; Loop *next; Loop *pre; Loop() : id(0), halfedges(NULL), face(NULL), next(NULL), pre(NULL){} }; struct Edge { HalfEdge *half_l; HalfEdge *half_r; Edge *next; Edge *pre; Edge() : half_l(NULL), half_r(NULL), next(NULL), pre(NULL){} }; struct HalfEdge { Edge *edge; Vertex *sv; Vertex *ev; Loop *lp; HalfEdge *next; HalfEdge *pre; HalfEdge *brother; HalfEdge() : edge(NULL), sv(NULL), lp(NULL), next(NULL), pre(NULL), brother(NULL){} }; struct Vertex { int id; double coordinate[3]; Vertex *next; Vertex *pre; Vertex(double x, double y, double z) : id(0), next(NULL), pre(NULL) { coordinate[0] = x; coordinate[1] = y; coordinate[2] = z; } }; #endif
C
#include <stdio.h> #include <string.h> #include "canserial.h" #include "uart.h" #ifdef CAN_TIMESTAMP #include "timer.h" #endif /* handles a received message, does logging */ int canserial_handle_recv_message(struct can_serial* dev, const can_msg_t* msg) { if(dev->can_log_recv_message) dev->can_log_recv_message(msg); return CAN_OK; } /* canserial command */ int canserial_command(const struct can_device_command* cmd) { if (cmd->length > CAN_DEVICE_CMD_MAX_DATA) return CANSERIAL_CMD_TOO_LONG; if (cmd->command == 0) { if (cmd->length > 3) return CANSERIAL_BAUDRATE_BAD_INPUT; uint8_t ubrrh = cmd->data[0]; uint8_t ubrrl = cmd->data[1]; uint8_t use_2x = cmd->data[2]; uart_set_baudrate(ubrrh, ubrrl, use_2x); } return CANSERIAL_OK; } static void print_nibble(uint8_t nibble) { if (nibble >= 10) putchar(nibble - 10 + 'A'); else putchar(nibble + '0'); } static void print_byte(uint8_t byte) { print_nibble((byte & 0xf0) >> 4); print_nibble((byte & 0xf)); } union msg_id_bytes { uint32_t id; uint8_t bytes[4]; }; /* print out a can message to stdout */ static void print_msg(const can_msg_t* msg) { union msg_id_bytes mid; mid.id = msg->id; /* the id */ if (msg->idtype == CAN_EXTENDED_ID) { print_byte(mid.bytes[3]); print_byte(mid.bytes[2]); print_byte(mid.bytes[1]); print_byte(mid.bytes[0]); } else { print_nibble(mid.bytes[1]); print_nibble(mid.bytes[0] >> 4); print_nibble(mid.bytes[0] & 0xf); } /* the length */ putchar('0' + msg->length); /* the data */ for(int i=0; i<msg->length; ++i) print_byte(msg->data[i]); } /* log a send can message - default implementation */ void log_send(const can_msg_t* msg) { #ifdef CAN_TIMESTAMP printf("-> <%ld>", msg->tstamp); #else putchar('='); #endif putchar(msg->idtype == CAN_EXTENDED_ID ? 'T' : 't'); print_msg(msg); putchar('\n'); } /* log a received can message - default implementation */ void log_recv(const can_msg_t* msg) { #ifdef CAN_TIMESTAMP /* timestamp in jiffies */ printf("<%ld>", msg->tstamp); #endif /* received can message */ putchar(msg->idtype == CAN_EXTENDED_ID ? 'T' : 't'); print_msg(msg); putchar('\n'); } void log_canserial_cmd(const struct can_device_command* cmd) { putchar('='); putchar('c'); print_byte(cmd->command); print_byte(cmd->length); for(int i=0; i<cmd->length; ++i) print_byte(cmd->data[i]); putchar('\n'); } void log_failed_cmd(const struct can_device_command* cmd, uint8_t status) { putchar('E'); print_byte(status); putchar('\n'); } void log_dev_cmd(const struct can_device_command* cmd) { putchar('='); putchar('D'); print_byte(cmd->command); print_byte(cmd->length); for(int i=0; i<cmd->length; ++i) print_byte(cmd->data[i]); putchar('\n'); } static int parse_data_hexdecimal(uint8_t ch, uint8_t* val) { if (ch >= 'a' && ch <= 'f') *val = (*val << 4) | (ch - 'a' + 10); else if (ch >= 'A' && ch <= 'F') *val = (*val << 4) | (ch - 'A' + 10); else if (ch >= '0' && ch <= '9') *val = (*val << 4) | (ch - '0'); else return -1; return 0; } static int parse_id_hexdecimal(uint8_t ch, uint32_t* val) { if (ch >= 'a' && ch <= 'f') *val = (*val << 4) | (ch - 'a' + 10); else if (ch >= 'A' && ch <= 'F') *val = (*val << 4) | (ch - 'A' + 10); else if (ch >= '0' && ch <= '9') *val = (*val << 4) | (ch - '0'); else return -1; return 0; } /* parse_input_buffer * * returns number of bytes in buffer parsed * * Look for the constructs in the input buffer, execute them */ int canserial_parse_input_buffer(struct can_serial* dev, struct fifo* ififo) { int parse_state = 0; int hex_chars_to_go = 0; int msg_seq = 0; int consumed = 0; int serial_command = 0; // iterate through the buffer int i=0; while(fifo_count(ififo)) { uint8_t ch; if(fifo_get_unsafe(ififo, &ch) == FIFO_EMPTY) break; i++; #ifdef CANSERIALDEBUG printf("i:%d ch:0x%x p:%d hc:%d m:%d c:%d\n", i, (unsigned char)ch, parse_state, hex_chars_to_go, msg_seq, consumed); #endif switch(parse_state) { case 0: msg_seq = 0; serial_command = 0; if(ch == 't' || ch == 'r') { // standard id CAN message hex_chars_to_go = 3; parse_state = 1; memset(&dev->send_msg, 0, sizeof(can_msg_t)); #ifdef CAN_TIMESTAMP dev->send_msg.tstamp = jiffie(); #endif dev->send_msg.idtype = CAN_STANDARD_ID; dev->send_msg.rtr = (ch =='r') ? 1 : 0; } else if(ch == 'T' || ch == 'R') { // extended id CAN message hex_chars_to_go = 8; parse_state = 1; memset(&dev->send_msg, 0, sizeof(can_msg_t)); #ifdef CAN_TIMESTAMP dev->send_msg.tstamp = jiffie(); #endif dev->send_msg.idtype = CAN_EXTENDED_ID; dev->send_msg.rtr = (ch =='R') ? 1 : 0; } else if(ch == 'D' || ch == 'c') { hex_chars_to_go = 2; parse_state = 4; memset(&dev->dev_cmd, 0, sizeof(struct can_device_command)); if (ch == 'c') serial_command = 1; } // any other character is skipped else consumed = i; break; case 1: /* message id */ if(parse_id_hexdecimal(ch, &(dev->send_msg.id)) == 0) { if (--hex_chars_to_go == 0) parse_state = 2; } else parse_state = 0; break; case 2: /* dlc */ if(ch >= '0' && ch <= '8') { dev->send_msg.length = (ch - '0'); parse_state = 3; hex_chars_to_go = dev->send_msg.length * 2; msg_seq = 0; if (hex_chars_to_go == 0) { // got the whole message, send it.. // send the message... consumed = i; if(dev->can_log_send_message != 0) dev->can_log_send_message(&dev->send_msg); uint8_t status = dev->can_send_message( dev->candev, &dev->send_msg); if (status == CAN_FAILTX) { can_error_t e; e.error_code = CAN_FAILTX; e.dev_buffer = 0; e.dev_code = 0; dev->can_handle_error(dev->candev, &e); } parse_state = 0; } } else parse_state = 0; break; case 3: /* data */ if(parse_data_hexdecimal(ch, &(dev->send_msg.data[msg_seq])) == 0) { if (--hex_chars_to_go == 0) { // got the whole message, send it.. // send the message... consumed = i; if(dev->can_log_send_message != 0) dev->can_log_send_message(&dev->send_msg); uint8_t status = dev->can_send_message( dev->candev, &dev->send_msg); if (status == CAN_FAILTX) { can_error_t e; e.error_code = CAN_FAILTX; e.dev_buffer = 0; e.dev_code = 0; dev->can_handle_error(dev->candev, &e); } parse_state = 0; } else if ((hex_chars_to_go & 0x1) == 0) ++msg_seq; } else parse_state = 0; break; case 4: /* start of canserial/device command command byte */ if(parse_data_hexdecimal(ch, &(dev->dev_cmd.command)) == 0) { if (--hex_chars_to_go == 0) { parse_state = 5; hex_chars_to_go = 2; } } else parse_state = 0; break; case 5: /* canserial/device command data length */ if(parse_data_hexdecimal(ch, &(dev->dev_cmd.length)) == 0) { if (--hex_chars_to_go == 0) { parse_state = 6; hex_chars_to_go = dev->dev_cmd.length * 2; msg_seq = 0; } } else parse_state = 0; break; case 6: /* canserial/device command data bytes */ if(parse_data_hexdecimal(ch, &(dev->dev_cmd.data[msg_seq])) == 0) { if (--hex_chars_to_go == 0) { consumed = i; // got the whole command, execute it if (!serial_command) { if (dev->can_log_device_command != 0) dev->can_log_device_command(&dev->dev_cmd); uint8_t status = dev->can_device_command( dev->candev, &dev->dev_cmd); if (status != CAN_OK && dev->can_log_failed_device_command != 0) dev->can_log_failed_device_command(&dev->dev_cmd, status); } else { if (dev->can_log_serial_command != 0) dev->can_log_serial_command(&dev->dev_cmd); uint8_t status = canserial_command(&dev->dev_cmd); if (status != CANSERIAL_OK && dev->can_log_failed_serial_command != 0) dev->can_log_failed_serial_command(&dev->dev_cmd, status); } parse_state = 0; } else if ((hex_chars_to_go & 0x1) == 0) ++msg_seq; } else parse_state = 0; break; } } return consumed; }
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_5__ TYPE_1__ ; /* Type definitions */ typedef int /*<<< orphan*/ uint8_t ; typedef int /*<<< orphan*/ int8_t ; typedef scalar_t__ const UBaseType_t ; struct TYPE_5__ {scalar_t__ uxLength; scalar_t__ uxItemSize; int /*<<< orphan*/ * pxQueueSetContainer; int /*<<< orphan*/ ucQueueType; int /*<<< orphan*/ * pcHead; } ; typedef TYPE_1__ Queue_t ; /* Variables and functions */ int /*<<< orphan*/ pdTRUE ; int /*<<< orphan*/ traceQUEUE_CREATE (TYPE_1__*) ; int /*<<< orphan*/ xQueueGenericReset (TYPE_1__*,int /*<<< orphan*/ ) ; __attribute__((used)) static void prvInitialiseNewQueue( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, const uint8_t ucQueueType, Queue_t *pxNewQueue ) { /* Remove compiler warnings about unused parameters should configUSE_TRACE_FACILITY not be set to 1. */ ( void ) ucQueueType; if( uxItemSize == ( UBaseType_t ) 0 ) { /* No RAM was allocated for the queue storage area, but PC head cannot be set to NULL because NULL is used as a key to say the queue is used as a mutex. Therefore just set pcHead to point to the queue as a benign value that is known to be within the memory map. */ pxNewQueue->pcHead = ( int8_t * ) pxNewQueue; } else { /* Set the head to the start of the queue storage area. */ pxNewQueue->pcHead = ( int8_t * ) pucQueueStorage; } /* Initialise the queue members as described where the queue type is defined. */ pxNewQueue->uxLength = uxQueueLength; pxNewQueue->uxItemSize = uxItemSize; ( void ) xQueueGenericReset( pxNewQueue, pdTRUE ); #if ( configUSE_TRACE_FACILITY == 1 ) { pxNewQueue->ucQueueType = ucQueueType; } #endif /* configUSE_TRACE_FACILITY */ #if( configUSE_QUEUE_SETS == 1 ) { pxNewQueue->pxQueueSetContainer = NULL; } #endif /* configUSE_QUEUE_SETS */ traceQUEUE_CREATE( pxNewQueue ); }
C
#include <physic.h> #include <stdio.h> #include <logsystem.h> CID pos_comp_id; CID mass_comp_id; void gravity(Component * _comp) { //a = a - b * deltatime; a-psition, b-massa, deltatime-can I use glfw gettime Mass_comp * mass = (Mass_comp*) _comp; Entity * ent = get_entity(mass->_comp.related_id); Position_component* pos = (Position_component*) get_entity_component(ent->id, pos_comp_id); if (pos == NULL) return; pos->y += mass->mass; return; } void move_system(Component * _comp) { Position_component * comp = (Position_component*) _comp; comp->x += 0x1p0; char log[0xFF]; sprintf(log, "New position: %f %f %f", comp->x, comp->y, comp->z); print(Log_Debug, log); return; }; void init_physics() { mass_comp_id = reg_component(); pos_comp_id = reg_component(); add_system(gravity, mass_comp_id); add_system(move_system, pos_comp_id); };
C
/*Считать с клавиатуры целые чисал min и max. Вывести в строку квадраты всех четных чисел в промежутке от min до max включительно. В указаном промежутке гарантировано существует минимум 1 парное число. Пример ввода 0 7 Пример вывода 0 4 16 36 */ #include <stdio.h> int main() { int min, max; scanf("%d %d", &min, &max); if ( max % 2 != 0 ) { max -= 1; } for ( ; min < max; min++ ) { if ( min % 2 == 0 ) { printf("%d ", min*min); } } printf("%d\n", max*max); return 0; }
C
/*---------------------------------------------------------------- * @Author: Su * @Description: * @Creath Date: ----------------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { /*const int a = 425; a = 450; //error int b = 450; const int *point; point = &b; *point = 470; //error int* point2; point2 = &a; //warning *point2 = 480; */ double array[2]={ 1,2 }; const double *const pt = array; pt = &array[1]; //Ƿ޸ĵַ *pt = 450; //Ƿ޸ֵ printf("%d",a); int array2[-1]; return 0; }
C
/*--------------------------------------------------------------------------- * filename - creat.c * * function(s) * creat - creates a new file or rewrites an existing one *--------------------------------------------------------------------------*/ /* * C/C++ Run Time Library - Version 10.0 * * Copyright (c) 1987, 2000 by Inprise Corporation * All Rights Reserved. * */ /* $Revision: 9.3 $ */ #include <_io.h> #include <fcntl.h> #include <_tchar.h> #include <sys\stat.h> #include <errno.h> /*--------------------------------------------------------------------------* Name _tcreat used as creat and _wcreat creat - creates a new file or rewrites an existing one _wcreat - creates a new file or rewrites an existing one Usage int creat(const char *filename, int permiss); int _wcreat(const wchar_t *filename, int permiss); Prototype in io.h Description creates a new file or prepares to rewrite an existing file named by the string pointed to by filename. permiss only applies to newly created files. Return value success : the new file handle else : -1 and errno is set to one of the following: ENOENT Path or file name not found EMFILE Too many open files EACCES Permission denied *---------------------------------------------------------------------------*/ int _RTLENTRYF _EXPFUNC _tcreat(const _TCHAR *path, register int mode) { /* Test that mode is valid or zero */ if ( (mode != 0) && ((mode & S_IFDIR ) == 0) && ((mode & S_IFIFO ) == 0) && ((mode & S_IFCHR ) == 0) && ((mode & S_IFREG ) == 0) && ((mode & S_IREAD ) == 0) && ((mode & S_IWRITE) == 0) && ((mode & S_IEXEC ) == 0)) { errno = EACCES; return -1; } /* NOTE: O_RDWR is required for compatibility with BC++ for DOS and MSC, * but is incompatible with POSIX (which requires O_WRONLY). */ return ___topen(path, O_RDWR | O_CREAT | O_TRUNC, mode); }
C
#include<stdio.h> static long int A[10000000000]; int main() { int t,k; long long int n; long long int f(long long int, int); scanf("%d",&t); while(t--) { scanf("%lld%d",&n,&k); printf("%lld\n",(f(n,k)%1000000007)); } return 0; } long long int f(long long int n, int k) { if(n==1) return 1; if(k==1||k==n) return n; else if () return (f(n-1,k)+f(n-1,k-1)); } long long int pos(long int i , long int j) { return ((i*(i-1))/2) + (j-1); }
C
/* #include <stdio.h> int main(void) { int a,b,c; scanf("%i %i %i",&a,&b,&c); if (a==b || b==c || a==c){ if (a==1 & b==1 || c==1 & b==1 || a==1 & c==1){ printf("APROVADO COM A\n"); }else{ if (a==2 & b==2 || c==2 & b==2 || a==2 & c==2){ printf("APROVADO COM B\n"); }else{ if (a==3 & b==3 || c==3 & b==3 || a==3 & c==3){ printf("APROVADO COM C\n"); }else{ if (a==4 & b==4 || c==4 & b==4 || a==4 & c==4){ printf("REPROVADO\n"); } } } } }else{ printf("INCONCLUSIVO"); } return 0; } */
C
// // Created by q7 on 2019/11/27. // #ifndef C__TEST_REFERENCE_H #define C__TEST_REFERENCE_H int& test(int *p11, int a)//从函数中返回引用 { return p11[a]; } void Reference() { cout << setfill('*') << setw(50) << "Reference:C++引用->从函数中返回引用" << setfill('*') << setw(5) << "*" << endl; int i11[5] = {0, 1, 2, 3, 4}; for (int m = 0; m < 5; m++) { cout << i11[m] << endl; } test(i11, 4) = 8; cout << "\n"; for (int m = 0; m < 5; m++) { cout << i11[m] << endl; } } #endif //C__TEST_REFERENCE_H
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* handle_integer.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sadamant <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/07 14:50:33 by sadamant #+# #+# */ /* Updated: 2018/07/07 14:50:41 by sadamant ### ########.fr */ /* */ /* ************************************************************************** */ #include "printf.h" static void left_justify(t_format *f, char *str, intmax_t value) { char *num; num = precision_overfill(f, ft_numlen_abs(value)); num = ft_strcat(num, ft_itoa_abs(value)); if (f->flag->plus) *str++ = (value >= 0) ? '+' : '-'; else if (f->flag->space) *str++ = (value > 0) ? ' ' : '-'; else (value < 0) ? *str++ = '-' : 0; while (*num) *str++ = *num++; } // why doesn't this work with ft_itoa_base? static void right_justify(t_format *f, char *str, intmax_t value) { char *num; num = precision_overfill(f, ft_numlen_abs(value)); num = ft_strcat(num, ft_itoa_abs(value)); if (f->flag->plus || f->flag->space) { str += (f->flag->zero && f->precision == -1) ? 0 : ft_strlen(str) - ft_strlen(num) - 1; if (f->flag->plus) *str = (value >= 0) ? '+' : '-'; else if (f->flag->space) *str = (value > 0) ? ' ' : '-'; str += (f->flag->zero && f->precision == -1) ? ft_strlen(str) - ft_strlen(num) : 1; } else { str += ft_strlen(str) - ft_strlen(num); // -1 is necessary for the sign if (value < 0) { str -= 1; *str++ = '-'; } } while (*num) *str++ = *num++; } static void errorcheck_integer(t_format *f) { if (f->flag->minus && f->flag->zero) put_error("Flag '0' is ignored when flag '-' is present."); if (f->flag->hash) error_undefined('#', 'd'); } /* ** - : left justify, default is right justify ** + : add a plus when positive ** 0 : pad with 0s instead of with spaces ** . : maximum number of characters to be written. (pad with zeros) */ char *handle_integer(t_format *f, intmax_t value) { int width; int numlen; char *out; errorcheck_integer(f); numlen = (f->precision > ft_numlen_abs(value)) ? f->precision : ft_numlen_abs(value); numlen += (value < 0 || f->flag->plus || f->flag->space) ? 1 : 0; width = (numlen > f->width) ? numlen : f->width; out = ft_memalloc(sizeof(char) * (width + 1)); //+1 for backslash zero? (f->flag->zero && f->precision == -1) ? ft_strfill(out, width, '0') : ft_strfill(out, width, ' '); (f->flag->minus) ? left_justify(f, out, value) : right_justify(f, out, value); f->charswritten = ft_strlen(out); return (out); }
C
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> void* thread_func(void* thread_params){ printf("i'm thread #%lu\n", pthread_self()); printf("I've got %s\n", (char*)thread_params); pthread_exit((void*)5); } int main(int argc, char* argv[]){ printf("main thread #%lu\n", pthread_self()); pthread_t thread_id ; void* status; int rc; rc = pthread_create(&thread_id, NULL, thread_func, (void*)("hello !")); pthread_join(thread_id, &status); printf("main - %d\n",(int*)status); }
C
#include <stdint.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { uint8_t c1, c2; c1 = getc(stdin); c2 = getc(stdin); uint16_t numblk = c2 << 8 | c1; c1 = getc(stdin); c2 = getc(stdin); uint16_t datalen = c2 << 8 | c1; uint16_t* blk = calloc(numblk, sizeof(uint16_t)); int intext = 0; for (uint16_t i = 0; i < numblk; i++) { c1 = getc(stdin); c2 = getc(stdin); blk[i] = c2 << 8 | c1; } for (uint16_t i = 0; i < datalen; i++) { for (uint16_t j = 0; j < numblk; j++) { if (i == blk[j]) { printf("\n*%02x\n", j); } } c1 = getc(stdin); c2 = getc(stdin); if (c2 >= 0x81 && c2 <= 0xee) { if (!intext) { printf("Text \""); intext = 1; } putc(c2, stdout); putc(c1, stdout); } else { if (intext) { printf("\"\n"); intext = 0; } if (c2 == 0x03 && c1 == 0xea) { printf("WaitKey\n"); } else if (c2 == 0x03 && c1 == 0xec) { printf("WaitPage\n"); } else { printf("Opcode %02x %02x\n", c2, c1); } } } free(blk); return 0; }
C
#pragma once #include "klib.h" // // A general purpose unicode string object. Storage is UTF-16. // Exposes methods to convert to and from ascii, and // could be extended to support UTF-8 // struct UnicodeString { unsigned short* wcharBuffer; unsigned int wcharBufferLength; unsigned int stringLength; unsigned int lowerLimit; unsigned int upperLimit; bool substringActive; bool (*appendASCIICString)(struct UnicodeString* thisString, const char* asciiString); bool (*appendUTF16String)(struct UnicodeString* thisString, const unsigned short* utf16string, unsigned int length); int (*compare)(const struct UnicodeString* thisString, const struct UnicodeString* thatString); // returns true if fully converted bool (*toASCIICString)(struct UnicodeString* thisString, char* dest, unsigned int destSize); // will fill at most destSize bytes void (*print)(struct UnicodeString* thisString); // set / get / clear a substring... used for comparing / printing bool (*setSubstringRange)(struct UnicodeString* thisString, unsigned int lower, unsigned int upper); bool (*getSubstringRange)(struct UnicodeString* thisString, unsigned int* lower, unsigned int* upper); void (*clearSubstringRange)(struct UnicodeString* thisString); // returns substring limits of the first matching token found from start onwards bool (*tokenise)(struct UnicodeString* thisString, char splitChar, unsigned int* start, unsigned int* end); // reset length and substring (but don't reset wcharbuffer...) void (*reset)(struct UnicodeString* thisString); }; struct UnicodeString* lib_createUnicodeString(); void lib_destroyUnicodeString(struct UnicodeString** string);
C
#define _GNU_SOURCE #include <errno.h> #include <getopt.h> #include <gmp.h> #include <pthread.h> #include <sched.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "pi-calc.h" #define DEFAULT_DIGITS 1000 #define LAST_DIGITS_PRINT 50 /* Digits per iteration (where is it from?) */ #define DPI 14.1816474627254776555 /* Bits per digit (log2(10)) */ #define BPD 3.32192809488736234787 #define BCONST1 545140134 #define BCONST2 13591409 #define DCONST1 3 #define ECONST1 640320 #define LTFCON1 10005 #define LTFCON2 426880 #define print_err(str, val) fprintf(stderr, "%s (%d): %s.\n", str, val, strerror(-val)) void print_usage(void) { printf("Supported options:\n"); printf(" -h --help prints this message and exits\n"); printf(" -d --digits number of digits for Pi calculations\n"); printf(" (default is %d)\n", DEFAULT_DIGITS); printf(" -t --threads number of threads to run\n"); printf(" (by default # of threads = # of logical cores)\n"); } /* Gets the number of available CPUs based on available affinities */ /* TODO: OS specific? Might be better to use different method */ int get_cpu_count(void) { cpu_set_t cs; CPU_ZERO(&cs); if (sched_getaffinity(0, sizeof(cs), &cs)) return 1; return CPU_COUNT(&cs); } void *chudnovsky_chunk(void *arguments) { unsigned long int k, threek, total_iterations; mpz_t a, b, c, d, e, rt, rb; mpf_t rtf, rbf, r; struct thread_args *args = (struct thread_args *)arguments; total_iterations = args->iter; /* Init libgmp variables */ mpz_inits(a, b, c, d, e, rt, rb, NULL); mpf_inits(rtf, rbf, r, NULL); /* Main loop of a thread */ while (1) { /* Check which k needs calculation */ pthread_mutex_lock(&args->start_mutex); k = args->k; args->k++; pthread_mutex_unlock(&args->start_mutex); /* If all ks are done, say return */ if (k > total_iterations) break; /* 3k */ threek = k * 3; /* (6k!) */ mpz_fac_ui(a, threek << 1); /* 545140134k */ mpz_set_ui(b, BCONST1); mpz_mul_ui(b, b, k); /* 13591409 + 545140134k */ mpz_add_ui(b, b, BCONST2); /* (3k)! */ mpz_fac_ui(c, threek); /* (k!)^3 */ mpz_fac_ui(d, k); mpz_pow_ui(d, d, DCONST1); /* (-640320)^3k */ mpz_set_ui(e, ECONST1); mpz_pow_ui(e, e, threek); if ((threek & 1) == 1) mpz_neg(e, e); /* Get everything together */ /* (6k)! (13591409 + 545140134k) */ mpz_mul(rt, a, b); /* (3k)! (k!)^3 */ mpz_mul(rb, c, d); mpz_mul(rb, rb, e); /* Switch to floats */ mpf_set_z(rtf, rt); mpf_set_z(rbf, rb); /* divide top/bottom */ mpf_div(r, rtf, rbf); /* add result to the sum */ pthread_mutex_lock(&args->sum_mutex); mpf_add(args->sum, args->sum, r); pthread_mutex_unlock(&args->sum_mutex); } /* Deinit variables, result is passed via args->sum */ mpz_clears(a, b, c, d, e, rt, rb, NULL); mpf_clears(rtf, rbf, r, NULL); } int chudnovsky(int digits, int threads) { int res = 0; unsigned long int i, iter, precision, rest, per_cpu, k; mpf_t ltf, sum, result; pthread_t *pthreads; struct thread_args targs; mp_exp_t exponent; char *pi; /* If threads is not specified, check how many CPUs are avail */ if (threads == 0) { threads = get_cpu_count(); } pthreads = malloc(threads * sizeof(pthread_t)); if (pthreads == NULL) { res = -ENOMEM; goto chudnovsky_exit; } /* Calculate and set precision */ precision = (digits * BPD) + 1; mpf_set_default_prec(precision); /* Calculate number of iterations */ iter = digits/DPI + 1; /* Init all objects */ mpf_inits(ltf, sum, result, targs.sum, NULL); mpf_set_ui(sum, 0); mpf_set_ui(targs.sum, 0); /* Set pthread specific stuff */ targs.k = 0; targs.iter = iter; pthread_mutex_init(&targs.start_mutex, NULL); pthread_mutex_init(&targs.sum_mutex, NULL); /* Prepare the constant from the left side of the equation */ mpf_sqrt_ui(ltf, LTFCON1); mpf_mul_ui(ltf, ltf, LTFCON2); printf("Starting summing, using:\n" "%d digits - %lu iterations - %d threads\n", digits, iter, threads); for (i = 0; i < threads; i++) { pthread_create(&pthreads[i], NULL, &chudnovsky_chunk, (void *) &targs); } /* Wait for threads to finish and take their sums */ for (i = 0; i < threads; i++) { pthread_join(pthreads[i], NULL); } printf("Starting final steps\n"); /* Invert sum */ mpf_ui_div(sum, 1, targs.sum); mpf_mul(result, sum, ltf); /* Get one more char then needed and then trunc to avoid rounding */ pi = mpf_get_str(NULL, &exponent, 10, digits + 2, result); pi[digits+1] = '\0'; if (strlen(pi) < LAST_DIGITS_PRINT + 1) { printf("Calculated PI:\n"); printf("\t%.*s.%s\n", (int)exponent, pi, pi + exponent); } else { printf("Last digits of Pi are:\n"); printf("\t%s\n", pi+(digits-(LAST_DIGITS_PRINT-1))); } free(pi); mpf_clears(ltf, sum, result, NULL); pthread_mutex_destroy(&targs.start_mutex); pthread_mutex_destroy(&targs.sum_mutex); /* TODO: add verification here! */ chudnovsky_free_pthreads: free(pthreads); chudnovsky_exit: return res; } int main(int argc, char *argv[]) { int nsec, res = 0, opt, digits = DEFAULT_DIGITS, threads = 0; double sec; double cpu_time, cpu_start, cpu_end; struct timespec start, end; const char* short_opts = "hd:t:"; const struct option long_opts[] = { { "help", 0, NULL, 'h' }, { "digits", 1, NULL, 'd' }, { "threads", 1, NULL, 't' }, }; printf("pi-calc version %s\n", VERSION); do { opt = getopt_long(argc, argv, short_opts, long_opts, NULL); switch(opt) { case 'h': print_usage(); return 0; case 'd': digits = atoi(optarg); if (digits <= 0) { res = -EINVAL; print_err("Wrong digits value", res); return res; } break; case 't': threads = atoi(optarg); if (threads <= 0) { res = -EINVAL; print_err("Wrong threads count", res); return res; } break; case -1: break; default: print_usage(); res = -EINVAL; return res; } } while (opt != -1); /* Get CPU and normal time */ cpu_start = clock(); res = clock_gettime(CLOCK_MONOTONIC, &start); if (res < 0) { res = -errno; print_err("Cannot obtain start time", res); return res; } /* Run the Chudnovsky algorithm */ res = chudnovsky(digits, threads); if (res < 0) { print_err("Error during execution", res); return res; } /* Get the end time */ cpu_end = clock(); res = clock_gettime(CLOCK_MONOTONIC, &end); if (res < 0) { res = -errno; print_err("Cannot obtain stop time", res); return res; } sec = difftime(end.tv_sec, start.tv_sec); if (end.tv_nsec >= start.tv_nsec) { nsec = end.tv_nsec - start.tv_nsec; } else { nsec = start.tv_nsec - end.tv_nsec; sec--; } cpu_time = ((double)(cpu_end - cpu_start)) / CLOCKS_PER_SEC; printf("Run time: %.0f.%.9d s\n", sec, nsec); printf("CPU time: %.9f s\n", cpu_time); return 0; }
C
// ******************************************************************* //1) Write a macro for each of the following: // //a) Area of a Circle //b) Area of a Square //c) Area of a Rectangle //d) Area of a Triangle // //You can find formulas and detailed explanations at: http://www.mathisfun.com // ******************************************************************* #define PI 3.14159 #define AREA_OF_CIRCLE(radius) (PI * radius * radius) #define AREA_OF_SQUARE(side) (side * side) #define AREA_OF_RECTANGLE(width,height) (width * height) #define AREA_OF_TRIANGLE(base,height) (.5 * base * height) //-------------------------------------------------------------------------------------------------------------------------------------------- // ******************************************************************* //2) Write a function which will determine how many words are in a given string. You can assume that one or more //consecutive white spaces is a delimiter between words, and that the string you pass to your function is null terminated. // ******************************************************************* #include <stdio.h> #include <stdbool.h> // ******************************************************************* // FUNCTION: total_words // // DESCRIPTION: This function will return the number of words in a // give string as an integer. // // PARAMETERS: string - an array of characters (string) // // OUTPUTS: int - number of words in the string // // CALLS: is_alphabetic // ******************************************************************* int total_words (char string[]) { int i; // increments the loop int words = 0; // Used to store the number of words in the string bool looking_for_word = true; // tells if you are still looking for a word or if you've found it bool is_alphabetic (const char c); // determines if the letter is alphabetic (function included below) // loops through each letter of the string and adds to word count if a space is encountered for (i = 0; string[i] != '\0'; ++i) { if (is_alphabetic(string[i])) { if (looking_for_word) { ++words; looking_for_word = false; } } else { looking_for_word = true; } } // Returns the number of words return words; } // ******************************************************************* // FUNCTION: is_alphabetic // // DESCRIPTION: This function will take a character and return true if // it is alphabetic and false if not. // // PARAMETERS: c - a single character // // OUTPUTS: bool - true or false // // CALLS: none // ******************************************************************* bool is_alphabetic (const char c) { // check if the character is alphabetic if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { return true; } else { return false; } } //-------------------------------------------------------------------------------------------------------------------------------------------- // ******************************************************************* // 3) Write a function that is passed a month, day, and year and will determine if // that date is valid. You can assume each parameter is passed in as an integer. // Remember to check for leap year! // // validDate (5, 31, 1961) .... would be valid // // validDate (13, 4, 1967) ... would be invalid, the month is invalid // ******************************************************************* // ******************************************************************* // FUNCTION: valid_date // // DESCRIPTION: This function will take a date in three integer values // and return true or false if it is a valid date or not. // // PARAMETERS: month - the month // day - the day // year - the year // // OUTPUTS: bool - true or false // // CALLS: number_days - gets the number of days in the month, // depending on the month and year. // ******************************************************************* bool valid_date (int month, int day, int year) { int number_days (int month, int year); // Check if the month is a valid month if (month < 1 || month > 12) { return false; } // check if the day is a valid day if (day < 1 || day > number_days(month, year)) { return false; } // check if the year is a positive number if (year < 0) { return false; } // If the date is valid return true; } // ******************************************************************* // FUNCTION: number_days // // DESCRIPTION: This function will take a month and year and return // the number of days in that month. // // PARAMETERS: month - the month // year - the year // // OUTPUTS: int - number of days in the month // // CALLS: is_leap_year // ******************************************************************* int number_days (int month, int year){ bool is_leap_year (int year); // an array with the number of days in each month in a regular year const int days_per_month[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; if (is_leap_year(year) && month == 2) { // if it's a leapyear and the user is requesting the days in feb return 29; } else { // if it's not a leap year return days_per_month[month - 1]; } } // ******************************************************************* // FUNCTION: is_leap_year // // DESCRIPTION: This function will take a year and determine if it is // a leap year. // // PARAMETERS: year - the year // // OUTPUTS: bool - true or false // // CALLS: none // ******************************************************************* bool is_leap_year (int year) { bool leap_year_flag; // check if the year passed is a leap year if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { return true; } else { return false; } } //-------------------------------------------------------------------------------------------------------------------------------------------- // ******************************************************************* //4) Write a function that takes the values of a two-card blackjack hands as input, and returns the point total of the hand. The value //of the cards '2' through '9' is equal to their face value, the cards 'T', 'K', 'Q', 'J' are worth 10 points and the ace ('A') is worth 11 points //unless it comes with another ace, then that second ace is worth 1 point. The program should be able to catch incorrect input. // //Enter cards: A Q //The score is 21 // //Enter cards: A A //The score is 12 // //Enter cards: T 7 //The score is 17 // //Enter cards: A 5 //The score is 16 // //Enter cards: 7 # //*** Would be invalid, # is not a valid card // //Enter cards: Z 4 //*** Would be invalid, Z is not a valid card // //Hint: I've used a value of 'T' for the 10 card so you can simply pass in two characters, //instead of strings, as parameters to this function. // ******************************************************************* // ******************************************************************* // FUNCTION: blackjack_hand // // DESCRIPTION: This function will take two cards and tell you what // the blackjack hand total is. // // PARAMETERS: card1 - the first card // card2 - the second card // // OUTPUTS: int - the value of the hand // // CALLS: valid_card // ******************************************************************* int blackjack_hand (char card1, char card2) { bool valid_card (char card); int hand_total; // make the cards uppercase card1 = toupper(card1); card2 = toupper(card2); // check that both inputs are valid if (!valid_card(card1) || !valid_card(card2)) { return -1; } // find the value of card1 if (card1 <= '9' && card1 >= '2') { hand_total = card1 - 48; // subtract 48 from the value of the char to get the int value } else if (card1 == 'T' || card1 == 'J' || card1 == 'Q' || card1 == 'K') { hand_total = 10; } else { // card1 = 'A' hand_total = 11; } // find the value of card2 if (card2 <= '9' && card2 >= '2') { hand_total += card2 - 48; // subtract 48 from the value of the char to get the int value } else if (card2 == 'T' || card2 == 'J' || card2 == 'Q' || card2 == 'K') { hand_total += 10; } else { // card2 = 'A' hand_total += 1; } return hand_total; } // ******************************************************************* // FUNCTION: valid_card // // DESCRIPTION: This function will take a character and tell the // calling function whether or not it is a real card // // PARAMETERS: card - the potential card // // OUTPUTS: bool - true or false // // CALLS: none // ******************************************************************* bool valid_card (char card) { // check the valid card types if ((card <= '9' && card >= '2') || (card == 'A' || card == 'T' || card == 'J' || card == 'Q' || card == 'K')) { // If valid return true; } else { // invalid return false; } } //-------------------------------------------------------------------------------------------------------------------------------------------- // ******************************************************************* //5) Write a function to determine is a given word is legal. A word is illegal if it contains no vowels. For this problem, //the letter Y is considered to be a legal vowel. Pass in a word to this function and it will determine if the word is //legal or not. You can make the following assumptions about the word you a passing to this function. // //1) The string being passed is a combination of letters only (no non-letter check needed) //2) The string being passed is null terminated //3) Letters may be capital or lower case and it has no effect on whether its a word // //Examples: // //sch - is illegal, no vowels //apple - legal, contains a vowel //APPle - legal, uppercase letter combinations do not matter //try - legal, no vowel, but contains the letter 'y' // ******************************************************************* // ******************************************************************* // FUNCTION: is_word_legal // // DESCRIPTION: This function will traverse a character string and // determine if it is a legal word (has a vowel or a y) // // PARAMETERS: *str_ptr - a pointer to the first value in the string // // OUTPUTS: bool - true or false // // CALLS: none // ******************************************************************* bool is_word_legal (char *str_ptr) { // check the string 1 character at a time while (*str_ptr) { // check if the current char is a vowel or y if (tolower(*str_ptr) == 'a' || tolower(*str_ptr) == 'e' || tolower(*str_ptr) == 'i' || tolower(*str_ptr) == 'o' || tolower(*str_ptr) == 'u' || tolower(*str_ptr) == 'y') { // if yes return true; } // if not increment the loop and run it again ++str_ptr; }// end while // if there were no vowels return false; } //-------------------------------------------------------------------------------------------------------------------------------------------- // ******************************************************************* //6) Write a function that will determine if a given string is a palindrome. DO NOT use the C library function: strrev // //A palindrome is a word or sentence that reads the same forward as it does backward. // //Examples of word palindromes would be civic or rotor ... a word or phase would be: // //Never odd or even // //A good web site of examples is: http://www.rinkworks.com/words/palindromes.shtml // ******************************************************************* // ******************************************************************* // FUNCTION: is_palindrome // // DESCRIPTION: This function will take a string and determine if it // is a palindrome or not. // // PARAMETERS: string - a word // // OUTPUTS: bool - true or false // // CALLS: none // ******************************************************************* bool is_palindrome(char string[]) { int begin; // first position of the array int end; // last position of the array int middle; // middle of the array int length = 0; // length of the array // determine the length of the array while (string[length] != '\0' ){ length++; } // assign the middle and end positions of the array end = length - 1; middle = length/2; // check the first value against the last value for( begin = 0 ; begin < middle ; begin++, end--) { if (string[begin] != string[end]) { // if they don't match return false; } } // if they all match return true; } //-------------------------------------------------------------------------------------------------------------------------------------------- // ******************************************************************* //7) Write a function that will return in a structure the following characteristics of a given string: // //1) string length (use strlen), //2) number of upper case characters //3) number of lower case characters, //4) number of digits //5) number of non-alphanumeric characters. // ******************************************************************* struct stats{ int str_length; int upper_case; int lower_case; int digits; int non_alphanumeric; }; // ******************************************************************* // FUNCTION: string_data // // DESCRIPTION: This function will take a string and parse it out to // determine how many of each type of character there is. // // PARAMETERS: *str_ptr - pointer to the first position of the string // // OUTPUTS: struct stats - a structure with the data // // CALLS: none // ******************************************************************* struct stats string_data (char *str_ptr) { struct stats string_stats; // declare the struct while (*str_ptr) { // increment the length of the string for each pass string_stats.str_length++; // if the character is an upper case letter if (*str_ptr >= 'a' && *str_ptr <= 'z') { string_stats.upper_case++; } // if the character is a lower case letter else if (*str_ptr >= 'A' && *str_ptr <= 'Z') { string_stats.lower_case++; } // if the character is a digit else if (*str_ptr >= '0' && *str_ptr <= 9) { string_stats.digits++; } // if the character is none of the above else { string_stats.non_alphanumeric++; } ++str_ptr; }// end while return string_stats; } //-------------------------------------------------------------------------------------------------------------------------------------------- // ******************************************************************* //8) Write a function, myBaseBallStats, that is passed the following integer stats on a baseball player: // //Number of Singles, Doubles, Triples, and Home Runs as well as Number of At Bats. // //Based on this information, return a structure that contains the following // //Total Bases, Batting Average, Home Run Ratio, and Slugging Average. // //You do not need to be a baseball fan to do this ... All the information you need in //terms of the formulas and explanations can be found at: // //http://www.baseball-almanac.com/stats.shtml // //Note: Number of hits is: singles + doubles + triples + home runs // ******************************************************************* struct baseball_stats{ int total_bases; float batting_average; float home_run_ratio; float slugging_average; }; struct baseball_stats myBaseBallStats (int singles, int doubles, int triples, int homers, int at_bats) { struct baseball_stats my_stats; int hits; // determine number of hits hits = singles + doubles + triples + homers; // Determine how many total bases ( my_stats.total_bases = singles + (doubles * 2) + (triples * 3) + (homers * 4); // determine batting average my_stats.batting_average = (float) hits / at_bats; // determine home run ratio my_stats.home_run_ratio = (float) homers / at_bats; // determine slugging average my_stats.slugging_average = (float) my_stats.total_bases / at_bats; return my_stats; } //-------------------------------------------------------------------------------------------------------------------------------------------- // ******************************************************************* //9) Most people enjoy watching movies these days, whether its the classics or modern ones. //Develop a set of structures that could be used to model the information about a movie collection. //What type of information would you want to collect and store about a movie? What would be the right //types in C for that information? Define supporting structures as needed and have one final structure type that //is made up of various members (some members may be on some structure type, others may be simple integers, // floats, chars, arrays, etc). // //No program is needed although you might want to create a simple main function //and include your structure types just to test that everything compiles. // //This question is similar to the final question on the midterm, but you have learned about many different //types since then. Here is a template to use to get started and indicates what I am looking for in your answer. //Use everything you learned this semester, especially the last set of lectures notes from Chapters 13 - 17. // // ///* add supporting structures - expect many structure types here ... date is good example */ // // //struct date //{ // int month; // int day; // int year; //}; // // ///* add other supporting structures */ // // ///* Final structure, such as struct movie */ //struct movie //{ // // /* some members may be a structure type themselves, here is an example */ // struct date releaseDate; /* the date the movie was released */ // // // /* other members may be ints, floats, doubles, chars, enum, ... */ // char title [100]; /* the title of the move */ // // // /* add others */ // //}; // // //int main ( ) //{ // // struct movie myMovie [1000]; // // /* nothing else needs to be added to main */ // // return (0); // //}; // ******************************************************************* struct date { int month; int day; int year; }; struct name { char first_name[20]; char last_name[40]; }; struct actor { struct name actor_name; struct date birth_date; }; struct character { struct name actor_name; struct name character_name; }; struct movie { char title[100]; struct character top_25_cast[25]; struct date release_date; struct date to_dvd_date; struct name producer_name; struct name director_name; char synopsis[1000]; int rating; char primary_genre[10]; char secondary_genre[10]; struct movie *next; };
C
/* ** event.c for wolf3d in /home/benji_epitech/C_Graph_Prog/wolf3d/src ** ** Made by Benjamin Viguier ** Login <benjamin.viguier@epitech.eu> ** ** Started on Mon Dec 26 15:54:58 2016 Benjamin Viguier ** Last update Fri Jan 6 17:17:20 2017 Benjamin Viguier */ #include "wolf.h" const t_event_fct const fct_tab[] = { {sfEvtClosed, &close_evt}, {sfEvtKeyPressed, &keypress_evt}, {0, NULL} }; int event(t_win_dep *win, int *first) { t_event_fct *cur; if (*first) { *first = 0; return (1); } while (sfRenderWindow_pollEvent(win->win, &(win->ev))) { cur = (t_event_fct *) fct_tab; while (cur->fct != NULL) { if (win->ev.type == cur->type) if (!((cur->fct)(win))) return (0); cur += 1; } } return (1); } int close_evt(t_win_dep *win) { win = (void*) win; return (0); } int keypress_evt(t_win_dep *win) { if (win->ev.key.code == sfKeyEscape) return (0); if (win->ev.key.code == sfKeyZ) win->dep_vec.y = 0.2; else if (win->ev.key.code == sfKeyS) win->dep_vec.y = -0.2; if (win->ev.key.code == sfKeyD) win->a_dir += 5.0; else if (win->ev.key.code == sfKeyQ) win->a_dir += -5.0; return (1); }
C
//########################################################################### // // FILE: can_loopback_interrupts.c // // TITLE: Example to demonstrate basic CAN setup and use. // //! \addtogroup cpu01_example_list //! <h1>CAN External Loopback with Interrupts (can_loopback_interrupts)</h1> //! //! This example, using driverlib, shows the basic setup of CAN in order to //! transmit and receive messages on the CAN bus. The CAN peripheral is //! configured to transmit messages with a specific CAN ID. A message is then //! transmitted once per second, using a simple delay loop for timing. The //! message that is sent is a 4 byte message that contains an incrementing //! pattern. A CAN interrupt handler is used to confirm message transmission //! and count the number of messages that have been sent. //! //! This example sets up the CAN controller in External Loopback test mode. //! Data transmitted is visible on the CAN0TX pin and can be received with //! an appropriate mailbox configuration. //! //! This example uses the following interrupt handlers:\n //! - INT_CANA0 - CANIntHandler //! // //########################################################################### // $TI Release: F2837xS Support Library v210 $ // $Release Date: Tue Nov 1 15:35:23 CDT 2016 $ // $Copyright: Copyright (C) 2014-2016 Texas Instruments Incorporated - // http://www.ti.com/ ALL RIGHTS RESERVED $ //########################################################################### // // Included Files // #include "F28x_Project.h" #include <stdint.h> #include <stdbool.h> #include "inc/hw_types.h" #include "inc/hw_memmap.h" #include "inc/hw_can.h" #include "driverlib/can.h" // // Globals // volatile unsigned long g_ulTxMsgCount = 0; // A counter that keeps track of the // number of times the TX interrupt // has occurred, which should match // the number of TX messages that // were sent. volatile unsigned long g_ulRxMsgCount = 0; unsigned long u32CanAErrorStatus; volatile unsigned long g_bErrFlag = 0; // A flag to indicate that some // transmission error occurred. tCANMsgObject sTXCANMessage; tCANMsgObject sRXCANMessage; unsigned char ucTXMsgData[8] ={ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; unsigned char ucRXMsgData[8]; unsigned long u32CntTXMsgData = 0x12345678; // // CANIntHandler - This function is the interrupt handler for the CAN // peripheral. It checks for the cause of the interrupt, and // maintains a count of all messages that have been // transmitted. // interrupt void CANIntHandler(void) { unsigned long ulStatus; // // Read the CAN interrupt status to find the cause of the interrupt // ulStatus = CANIntStatus(CANA_BASE, CAN_INT_STS_CAUSE); // // If the cause is a controller status interrupt, then get the status // if(ulStatus == CAN_INT_INT0ID_STATUS) { // // Read the controller status. This will return a field of status // error bits that can indicate various errors. Error processing // is not done in this example for simplicity. Refer to the // API documentation for details about the error status bits. // The act of reading this status will clear the interrupt. If the // CAN peripheral is not connected to a CAN bus with other CAN devices // present, then errors will occur and will be indicated in the // controller status. // ulStatus = CANStatusGet(CANA_BASE, CAN_STS_CONTROL); // //Check to see if an error occurred. // if(((ulStatus & ~(CAN_ES_TXOK | CAN_ES_RXOK)) != 7) && ((ulStatus & ~(CAN_ES_TXOK | CAN_ES_RXOK)) != 0)) { // // Set a flag to indicate some errors may have occurred. // g_bErrFlag = 1; } } // // Check if the cause is message object 1, which what we are using for // sending messages. // else if(ulStatus == 1) { // // Getting to this point means that the TX interrupt occurred on // message object 1, and the message TX is complete. Clear the // message object interrupt. // CANIntClear(CANA_BASE, 1); // // Increment a counter to keep track of how many messages have been // sent. In a real application this could be used to set flags to // indicate when a message is sent. // g_ulTxMsgCount++; // // Since the message was sent, clear any error flags. // g_bErrFlag = 0; } // // Check if the cause is message object 1, which what we are using for // receiving messages. // else if(ulStatus == 2) { // // Get the received message // CANMessageGet(CANA_BASE, 2, &sRXCANMessage, true); // // Getting to this point means that the TX interrupt occurred on // message object 1, and the message TX is complete. Clear the // message object interrupt. // CANIntClear(CANA_BASE, 2); // // Increment a counter to keep track of how many messages have been // sent. In a real application this could be used to set flags to // indicate when a message is sent. // g_ulRxMsgCount++; // // Since the message was sent, clear any error flags. // g_bErrFlag = 0; } // // Otherwise, something unexpected caused the interrupt. This should // never happen. // else { // // Spurious interrupt handling can go here. // } CANGlobalIntClear(CANA_BASE, CAN_GLB_INT_CANINT0); PieCtrlRegs.PIEACK.all = PIEACK_GROUP9; } // // Main // int main(void) { // // Step 1. Initialize System Control: // PLL, WatchDog, enable Peripheral Clocks // This example function is found in the F2837xS_SysCtrl.c file. // InitSysCtrl(); // // Step 2. Initialize GPIO: // This example function is found in the F2837xS_Gpio.c file and // illustrates how to set the GPIO to its default state. // InitGpio(); GPIO_SetupPinMux(73, GPIO_MUX_CPU1, 3); // GPIO 73 - XCLKOUT GPIO_SetupPinOptions(73, GPIO_OUTPUT, GPIO_PUSHPULL); // SYSCLOCK/8 = 25MHz GPIO_SetupPinMux(30, GPIO_MUX_CPU1, 1); // GPIO30 - CANRXA GPIO_SetupPinMux(31, GPIO_MUX_CPU1, 1); // GPIO31 - CANTXA GPIO_SetupPinOptions(30, GPIO_INPUT, GPIO_ASYNC); GPIO_SetupPinOptions(31, GPIO_OUTPUT, GPIO_PUSHPULL); // // Initialize the CAN controller // CANInit(CANA_BASE); // // Setup CAN to be clocked off the PLL output clock (500kHz CAN-Clock) // CANClkSourceSelect(CANA_BASE, 0); // // Set up the bit rate for the CAN bus. This function sets up the CAN // bus timing for a nominal configuration. You can achieve more control // over the CAN bus timing by using the function CANBitTimingSet() instead // of this one, if needed. // In this example, the CAN bus is set to 500 kHz. In the function below, // the call to SysCtlClockGet() is used to determine the clock rate that // is used for clocking the CAN peripheral. This can be replaced with a // fixed value if you know the value of the system clock, saving the extra // function call. For some parts, the CAN peripheral is clocked by a fixed // 8 MHz regardless of the system clock in which case the call to // SysCtlClockGet() should be replaced with 8000000. Consult the data // sheet for more information about CAN peripheral clocking. // CANBitRateSet(CANA_BASE, 200000000, 500000); // // Enable interrupts on the CAN peripheral. This example uses static // allocation of interrupt handlers which means the name of the handler // is in the vector table of startup code. If you want to use dynamic // allocation of the vector table, then you must also call CANIntRegister() // here. // CANIntEnable(CANA_BASE, CAN_INT_MASTER | CAN_INT_ERROR | CAN_INT_STATUS); // // Step 3. Clear all interrupts and initialize PIE vector table: // Disable CPU interrupts // DINT; // // Initialize the PIE control registers to their default state. // The default state is all PIE interrupts disabled and flags // are cleared. // This function is found in the F2837xS_PieCtrl.c file. // InitPieCtrl(); // // Disable CPU interrupts and clear all CPU interrupt flags: // IER = 0x0000; IFR = 0x0000; // // Initialize the PIE vector table with pointers to the shell Interrupt // Service Routines (ISR). // This will populate the entire table, even if the interrupt // is not used in this example. This is useful for debug purposes. // The shell ISR routines are found in F2837xS_DefaultIsr.c. // This function is found in F2837xS_PieVect.c. // InitPieVectTable(); // // Interrupts that are used in this example are re-mapped to // ISR functions found within this file. // Register interrupt handler in RAM vector table // EALLOW; PieVectTable.CANA0_INT = CANIntHandler; EDIS; // // Enable the CAN interrupt on the processor (PIE). // PieCtrlRegs.PIEIER9.bit.INTx5 = 1; IER |= 0x0100; // M_INT9 EINT; // // Enable test mode and select external loopback // HWREG(CANA_BASE + CAN_O_CTL) |= CAN_CTL_TEST; HWREG(CANA_BASE + CAN_O_TEST) = CAN_TEST_EXL; // // Enable the CAN for operation. // CANEnable(CANA_BASE); // // Enable CAN Global Interrupt line0 // CANGlobalIntEnable(CANA_BASE, CAN_GLB_INT_CANINT0); // // Initialize the message object that will be used for sending CAN // messages. The message will be 4 bytes that will contain an incrementing // value. Initially it will be set to 0x12345678. // ucTXMsgData[0] = (u32CntTXMsgData>>24) & 0xFF; ucTXMsgData[1] = (u32CntTXMsgData>>16) & 0xFF; ucTXMsgData[2] = (u32CntTXMsgData>>8) & 0xFF; ucTXMsgData[3] = (u32CntTXMsgData) & 0xFF; sTXCANMessage.ui32MsgID = 1; // CAN message ID - use 1 sTXCANMessage.ui32MsgIDMask = 0; // no mask needed for TX sTXCANMessage.ui32Flags = MSG_OBJ_TX_INT_ENABLE; // enable interrupt on TX sTXCANMessage.ui32MsgLen = sizeof(ucTXMsgData); // size of message is 8 sTXCANMessage.pucMsgData = ucTXMsgData; // ptr to message content // // Initialize the message object that will be used for receiving CAN // messages. // *(unsigned long *)ucRXMsgData = 0; sRXCANMessage.ui32MsgID = 1; // CAN message ID - use 1 sRXCANMessage.ui32MsgIDMask = 0; // no mask needed for TX sRXCANMessage.ui32Flags = MSG_OBJ_RX_INT_ENABLE; // enable interrupt on RX sRXCANMessage.ui32MsgLen = sizeof(ucRXMsgData); // size of message is 8 sRXCANMessage.pucMsgData = ucRXMsgData; // ptr to message content // // Setup the message object being used to receive messages // CANMessageSet(CANA_BASE, 2, &sRXCANMessage, MSG_OBJ_TYPE_RX); // // Send the CAN message using object number 1 (not the same thing as // CAN ID, which is also 1 in this example). This function will cause // the message to be transmitted right away. // ucTXMsgData[0] = (u32CntTXMsgData>>24) & 0xFF; ucTXMsgData[1] = (u32CntTXMsgData>>16) & 0xFF; ucTXMsgData[2] = (u32CntTXMsgData>>8) & 0xFF; ucTXMsgData[3] = (u32CntTXMsgData) & 0xFF; // // Enter loop to send messages. A new message will be sent once per // second. The 4 bytes of message content will be treated as an unsigned // long and incremented by one each time. // for(;;) { // // Check the error flag to see if errors occurred // if(g_bErrFlag) { asm(" ESTOP0"); } if(g_ulTxMsgCount == g_ulRxMsgCount) { // // Transmit Message // CANMessageSet(CANA_BASE, 1, &sTXCANMessage, MSG_OBJ_TYPE_TX); } else { g_bErrFlag = 1; } // // Now wait 1 second before continuing // DELAY_US(1000*1000); // // Increment the value in the transmitted message data. // (*(unsigned long *)ucTXMsgData)++; } } // // End of file //
C
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <unistd.h> #include <sys/wait.h> #include <sys/select.h> #include <sys/wait.h> #include <sys/time.h> #include <limits.h> #include "model.h" #define PIPE(fd) socketpair(AF_UNIX, SOCK_STREAM, PF_UNIX, fd) char **theMap; int mapWidth, mapHeight; void updateTheMap(int numberOfObstacles, int numberOfHunters, int numberOfPreys, obstacle obstacles[], player hunters[], player preys[]){ for(int x=0; x<mapHeight; x++){ for(int y=0; y<mapWidth; y++){ theMap[x][y] = ' '; } } for(int i=0; i<numberOfObstacles; i++) { theMap[obstacles[i].pos.x][obstacles[i].pos.y] = 'X'; } for(int i=0; i<numberOfPreys; i++) { if(preys[i].isAlive) theMap[preys[i].pos.x][preys[i].pos.y] = 'P'; } for(int i=0; i<numberOfHunters; i++) { if(hunters[i].isAlive) theMap[hunters[i].pos.x][hunters[i].pos.y] = 'H'; } } void printTheMap(int numberOfObstacles, int numberOfHunters, int numberOfPreys, obstacle obstacles[], player hunters[], player preys[]) { updateTheMap(numberOfObstacles, numberOfHunters, numberOfPreys, obstacles, hunters, preys); printf("+"); for(int i=0; i<mapWidth; i++) { printf("-"); } printf("+\n"); for(int x=0; x<mapHeight; x++){ printf("|"); for(int y=0; y<mapWidth; y++){ printf("%c",theMap[x][y]); } printf("|\n"); } printf("+"); for(int i=0; i<mapWidth; i++) { printf("-"); } printf("+\n"); } //////////////////////////////////////////////////////// void nearestAdvPos(coordinate pos, int numberOfAdvs, player advs[], coordinate *result){ int min = INT_MAX; for(int i=0; i<numberOfAdvs; i++) { if(advs[i].isAlive) if(MD(pos, advs[i].pos, 0, 0) < min) { min = MD(pos, advs[i].pos, 0, 0); (*result).x = advs[i].pos.x; (*result).y = advs[i].pos.y; } } } int neighborNumberForHunter(coordinate pos, coordinate *result) { int count=0; int x = pos.x; int y = pos.y; if(x+1<mapHeight && (theMap[x+1][y] == 'X' || theMap[x+1][y] == 'H')){ result[count].x=x+1; result[count].y=y; count++; } if(x-1>=0 && (theMap[x-1][y] == 'X' || theMap[x-1][y] == 'H')){ result[count].x = x-1; result[count].y = y; count++; } if(y+1<mapWidth && (theMap[x][y+1] == 'X' || theMap[x][y+1] == 'H')){ result[count].x = x; result[count].y = y+1; count++; } if(y-1>=0 && (theMap[x][y-1] == 'X' || theMap[x][y-1] == 'H')){ result[count].x = x; result[count].y = y-1; count++; } for(int i=count; i<4; i++){ result[count].x = -1; result[count].y = -1; } return count; } int neighborNumberForPrey(coordinate pos, coordinate *result) { int count=0; int x = pos.x; int y = pos.y; if(x+1<mapHeight && (theMap[x+1][y] == 'X' || theMap[x+1][y] == 'P')){ result[count].x=x+1; result[count].y=y; count++; } if(x-1>=0 && (theMap[x-1][y] == 'X' || theMap[x-1][y] == 'P')){ result[count].x = x-1; result[count].y = y; count++; } if(y+1<mapWidth && (theMap[x][y+1] == 'X' || theMap[x][y+1] == 'P')){ result[count].x = x; result[count].y = y+1; count++; } if(y-1>=0 && (theMap[x][y-1] == 'X' || theMap[x][y-1] == 'P')){ result[count].x = x; result[count].y = y-1; count++; } for(int i=count; i<4; i++){ result[count].x = -1; result[count].y = -1; } return count; } int isValidMoveForHunter(coordinate nextPos) { if (theMap[nextPos.x][nextPos.y] != 'X' && theMap[nextPos.x][nextPos.y] != 'H') return 1; return 0; } int isValidMoveForPrey(coordinate nextPos) { return (theMap[nextPos.x][nextPos.y] != 'X' && theMap[nextPos.x][nextPos.y] != 'P'); } int didHunterEatPrey(coordinate c) { return (theMap[c.x][c.y] == 'P'); } int didPreyJumpOnHunter(coordinate c) { return (theMap[c.x][c.y] == 'H'); } int findPlayer(coordinate c, int number, player players[]){ int idx=-1; for(int i=0;i<number;i++){ if(c.x == players[i].pos.x && c.y == players[i].pos.y && players[i].isAlive) idx=i; } return idx; } int countAlives(int size, player arr[]){ int counter = 0; for(int i=0; i<size; i++){ if(arr[i].isAlive) counter++; } return counter; } int main() { /* VARIABLES */ int numberOfObstacles; int numberOfHunters; int numberOfPreys; pid_t pid; int status; /**********************************************************************************/ /* GET INPUT AND PRINT */ scanf("%d %d", &mapWidth, &mapHeight); theMap = (char **)malloc(mapHeight * sizeof(char *)); for (int i=0; i<mapHeight; i++) theMap[i] = (char *)malloc(mapWidth * sizeof(char)); scanf("%d", &numberOfObstacles); obstacle obstacles[numberOfObstacles]; for(int i=0; i<numberOfObstacles; i++){ scanf("%d %d", &(obstacles[i].pos .x), &(obstacles[i].pos .y)); } scanf("%d", &numberOfHunters); player hunters[numberOfHunters]; for(int i=0; i<numberOfHunters; i++){ scanf("%d %d %d", &(hunters[i].pos .x), &(hunters[i].pos .y), &(hunters[i].energy)); hunters[i].isAlive = 1; } scanf("%d", &numberOfPreys); player preys[numberOfPreys]; for(int i=0; i<numberOfPreys; i++){ scanf("%d %d %d", &(preys[i].pos .x), &(preys[i].pos .y), &(preys[i].energy)); preys[i].isAlive = 1; } printTheMap(numberOfObstacles, numberOfHunters, numberOfPreys, obstacles, hunters, preys); fflush(stdout); /* END OF INPUT SECTION */ /**********************************************************************************/ /* CREATE ALL PLAYERS */ for(int i=0; i<numberOfHunters; i++) { int fd[2]; PIPE(fd); pid = fork(); if(pid) { //parent close(fd[1]); hunters[i].pid = pid; hunters[i].fd = fd[0]; server_message msg; msg.pos.x = hunters[i].pos.x; msg.pos.y = hunters[i].pos.y; nearestAdvPos(hunters[i].pos, numberOfPreys, preys, &(msg.adv_pos)); msg.object_count = neighborNumberForHunter(msg.pos, msg.object_pos); write(hunters[i].fd, &msg, sizeof(server_message)); FILE* file = fdopen(hunters[i].fd, "w"); fflush(file); } else { //child dup2(fd[0],0); dup2(fd[1],1); close(0); for(int e=3; e<=fd[1]; e++) close(e); char mapW[12]; sprintf(mapW, "%d", mapWidth); char mapH[12]; sprintf(mapH, "%d", mapHeight); execl("./hunter","./hunter", mapW, mapH, (char*) NULL); break; } } for(int i=0; i<numberOfPreys; i++) { int fd[2]; PIPE(fd); pid = fork(); if(pid) { //parent close(fd[1]); preys[i].pid = pid; preys[i].fd=fd[0]; server_message msg; msg.pos.x = preys[i].pos.x; msg.pos.y = preys[i].pos.y; nearestAdvPos(preys[i].pos, numberOfHunters, hunters, &(msg.adv_pos)); msg.object_count = neighborNumberForPrey(msg.pos, msg.object_pos); write(preys[i].fd, &msg, sizeof(server_message)); FILE* file = fdopen(preys[i].fd, "w"); fflush(file); } else { //child dup2(fd[0],0); dup2(fd[1],1); close(0); for(int e=3; e<=fd[1]; e++) close(e); char mapW[12]; sprintf(mapW, "%d", mapWidth); char mapH[12]; sprintf(mapH, "%d", mapHeight); execl("./prey","./prey", mapW, mapH, (char*) NULL); break; } } /* END OF PLAYER CREATION SECTION */ /**********************************************************************************/ /* THE LOOP */ fd_set readset; ph_message msgReceived; int total = numberOfHunters+numberOfPreys; int m = total+3; int gameOver = 0; if(total != 0) while(!gameOver) { FD_ZERO(&readset); for(int i =0; i<numberOfHunters; i++) if(hunters[i].isAlive) FD_SET(hunters[i].fd, &readset); for(int i =0; i<numberOfPreys; i++) if(preys[i].isAlive) FD_SET(preys[i].fd, &readset); select(m, &readset, NULL,NULL,NULL); for(int i =0; i<numberOfHunters; i++) { if(hunters[i].isAlive) if (FD_ISSET(hunters[i].fd, &readset)) { read(hunters[i].fd, &msgReceived, sizeof(server_message)); if(isValidMoveForHunter(msgReceived.move_request)){ hunters[i].pos.x=msgReceived.move_request.x; hunters[i].pos.y=msgReceived.move_request.y; hunters[i].energy--; if(didHunterEatPrey(hunters[i].pos)){ updateTheMap(numberOfObstacles, numberOfHunters, numberOfPreys, obstacles, hunters, preys); int foundPrey = findPlayer(hunters[i].pos, numberOfPreys, preys); hunters[i].energy += preys[foundPrey].energy; preys[foundPrey].isAlive = 0; close(preys[foundPrey].fd); kill(preys[foundPrey].pid, SIGTERM); waitpid(preys[foundPrey].pid, &status, WNOHANG); } if(hunters[i].energy == 0){ hunters[i].isAlive = 0; close(hunters[i].fd); kill(hunters[i].pid, SIGTERM); waitpid(hunters[i].pid, &status, WNOHANG); } //updateTheMap(numberOfObstacles, numberOfHunters, numberOfPreys, obstacles, hunters, preys); printTheMap(numberOfObstacles, numberOfHunters, numberOfPreys, obstacles, hunters, preys); fflush(stdout); } updateTheMap(numberOfObstacles, numberOfHunters, numberOfPreys, obstacles, hunters, preys); if(hunters[i].isAlive){ server_message msg; msg.pos.x = hunters[i].pos.x; msg.pos.y = hunters[i].pos.y; nearestAdvPos(msg.pos, numberOfPreys, preys, &(msg.adv_pos)); msg.object_count = neighborNumberForHunter(msg.pos, msg.object_pos); write(hunters[i].fd, &msg, sizeof(server_message)); FILE* file = fdopen(hunters[i].fd, "w"); fflush(file); } } } if(countAlives(numberOfHunters, hunters) == 0) { for(int k=0; k<numberOfPreys; k++){ if(preys[k].isAlive){ preys[k].isAlive = 0; close(preys[k].fd); kill(preys[k].pid, SIGTERM); waitpid(preys[k].pid, &status, WNOHANG); } } gameOver = 1; } else if(countAlives(numberOfPreys, preys) == 0) { for(int k=0; k<numberOfHunters; k++){ if(hunters[k].isAlive){ hunters[k].isAlive = 0; close(hunters[k].fd); kill(hunters[k].pid, SIGTERM); waitpid(hunters[k].pid, &status, WNOHANG); } } gameOver = 1; } for(int i =0; i<numberOfPreys; i++) { if(preys[i].isAlive) if (FD_ISSET(preys[i].fd, &readset)) { read(preys[i].fd, &msgReceived, sizeof(server_message)); if(isValidMoveForPrey(msgReceived.move_request)){ preys[i].pos.x=msgReceived.move_request.x; preys[i].pos.y=msgReceived.move_request.y; updateTheMap(numberOfObstacles, numberOfHunters, numberOfPreys, obstacles, hunters, preys); if(didPreyJumpOnHunter(preys[i].pos)){ int foundHunter = findPlayer(preys[i].pos, numberOfHunters, hunters); hunters[foundHunter].energy += preys[i].energy; preys[i].isAlive = 0; close(preys[i].fd); kill(preys[i].pid, SIGTERM); waitpid(preys[i].pid, &status, WNOHANG); } printTheMap(numberOfObstacles, numberOfHunters, numberOfPreys, obstacles, hunters, preys); fflush(stdout); } updateTheMap(numberOfObstacles, numberOfHunters, numberOfPreys, obstacles, hunters, preys); server_message msg; msg.pos.x = preys[i].pos.x; msg.pos.y = preys[i].pos.y; nearestAdvPos(msg.pos, numberOfHunters, hunters, &(msg.adv_pos)); msg.object_count = neighborNumberForPrey(msg.pos, msg.object_pos); write(preys[i].fd, &msg, sizeof(server_message)); FILE* file = fdopen(preys[i].fd, "w"); fflush(file); } } //if(!gameOver) //printTheMap(numberOfObstacles, numberOfHunters, numberOfPreys, obstacles, hunters, preys); } /* END OF THE LOOP */ return 0; }
C
#include <stdio.h>//Biblioteca de funo #include <stdlib.h>//Biblioteca de funo #include <locale.h>//Biblioteca para adicionar acentuao da lngua portuguesa int main() { float litros, valor1, valorf;//declarao de variveis setlocale(LC_ALL, "Portuguese");//comando para adicionar acentuao da lngua portuguesa system("color 02");//funo de mudana de cor do programa printf("\nValor da gasolina por litro");//tabela para esttica do programa printf("\nR$ 4,30"); printf("\n----------------------------------------------------------\n");//separao por tabela de linhas para esttica do programa printf(" Quantidade de litros | Desconto por litro\n"); printf(" At 20 litros | 4%% \n"); printf(" Acima de 20 litros | 6%% "); printf("\n----------------------------------------------------------\n"); printf("\nInforme a quantidade de litros vendidos: ");//Entrada de dados scanf("%f", &litros);//leitura de dados printf("\n----------------------------------------------------------\n"); if (litros <21)//condio { valor1 = (litros * 4.30);//clculo valorf = (valor1 - (valor1*0.04));//clculo printf("\nValor a pagar = %.2fR$\n", valorf);//sada de dados printf("\n----------------------------------------------------------\n"); } else { valor1 = (litros * 4.30);//clculo valorf = (valor1 - (valor1*0.06));//clculo printf("\nValor a pagar = %.2fR$\n", valorf);//sada de dados printf("\n----------------------------------------------------------\n"); } }
C
#include <stdio.h> int main(){ int a,b,c; int cnt=0; scanf("%d %d %d",&a,&b,&c); for(int i = a; i <= b; i++){ int ans; ans = c % i; if(ans == 0){ cnt++; } } printf("%d\n",cnt); }
C
#ifndef KCODE_THREAD_QUEUE_H #define KCODE_THREAD_QUEUE_H #include <sys/types.h> // size_t #include <pthread.h> struct thr_queue_s; typedef struct thr_queue_s *thr_queue_t; int thr_queue_create(thr_queue_t *q, size_t max_size); // 0, ok; -1, fail void thr_queue_destroy(thr_queue_t *q); void thr_queue_push(thr_queue_t *self, void *in); int thr_queue_peek(thr_queue_t *self, void **out); void thr_queue_pop(thr_queue_t *self, void **out); size_t thr_queue_size(const thr_queue_t *self); size_t thr_queue_capacity(const thr_queue_t *self); #endif
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* free.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: yhebbat <yhebbat@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/16 16:03:19 by yhebbat #+# #+# */ /* Updated: 2021/07/17 18:24:34 by yhebbat ### ########.fr */ /* */ /* ************************************************************************** */ #include "prj.h" void ft_free(t_list *head) { if (head) { while (head->header != NULL) { ft_depiler(head); } free(head); } } void ft_exit(void) { ft_putstr("Error\n"); exit(0); } void ft_putstr(char *c) { int i; i = 0; while (c[i]) write(1, &c[i++], 1); } int ft_atoi(const char *str) { long long i; long long sum; int sign; i = 0; sum = 0; sign = 1; while (str[i] == ' ' || (str[i] >= 9 && str[i] <= 13)) i++; if (str[i] == '-') sign = -1; if (str[i] == '-' || str[i] == '+') i++; while (str[i] <= '9' && str[i] >= '0') { sum = (sum * 10) + str[i] - '0'; i++; } if (sum * sign > INT_MAX || sum * sign < INT_MIN || i > 12) return (0); return (sign * sum); } int ft_check(t_list *head) { t_stack *to_check; to_check = head->header; while (to_check->suivant != NULL) { if (to_check->value > to_check->suivant->value) return (1); to_check = to_check->suivant; } return (0); }
C
//https://leetcode.com/problems/queue-reconstruction-by-height/ /* Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue. Note: The number of people is less than 1,100. Example Input: [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] Output: [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] */ class Solution { public: vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) { /* Pick out tallest group of people and sort them in a subarray (S). Since there's no other groups of people taller than them, therefore each guy's index will be just as same as his k value. For 2nd tallest group (and the rest), insert each one of them into (S) by k value. So on and so forth. */ auto comp = [](pair<int, int> a, pair<int, int> b){ return a.first>b.first || (a.first==b.first)&&(a.second<b.second); }; sort(people.begin(),people.end(),comp); vector<pair<int, int>> ret; for(auto p:people){ ret.insert(ret.begin()+p.second,p); } return ret; } };
C
#include <stdlib.h> #include <stdio.h> /** * main - prints combinations of two different digits, not equal * * Return: Returns 0 */ int main(void) { int i = 48; int a; while (i < 57) { a = i; while (a <= 57) { if (i != a) { putchar(i); putchar(a); if (i != 56) { putchar(44); putchar(32); } } a++; } i++; } putchar(13); return (0); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "foldl.h" int read1(char s[]) { return s[0] - '0'; } int main(int argc, char *argv[]) { char c = '\0'; Op op = NULL; int x0 = 0; int n = argc - 2; int xs[100]; int i = 0; if (n < 0) exit(1); if (!strcmp(argv[1], "sum")) { x0 = 0; c = '+'; op = add; } if (!strcmp(argv[1], "product")) { x0 = 1; c = '*'; op = mul; } if (op == NULL) exit(1); for (i = 0; i < 100; i++) { xs[i] = read1(argv[i + 2]); printf("%d ", xs[i]); if (i == n - 1) break; printf("%c ", c); } printf("= %d\n", foldl(op, x0, n, xs)); return 0; }
C
#include<stdio.h> int main() { int n,m,a[100],i; while(~scanf("%d",&n)) { m=0; for(i=0;i<n;i++) { scanf("%d",&a[i]); } for(i=1;i<n-1;i++) { if(a[i]>a[i-1]&&a[i]>a[i+1]) m++; } printf("%d\n",m); } }
C
/* vi:set ts=8 sts=4 sw=4 noet: * * state_machine */ /* * Manage current input state */ #include "vim.h" sm_T *sm_get_current() { return state_current; } int sm_get_current_mode() { return state_current->mode; } int no_pending_operator(void *ctx, pendingOp_T *cmdarg) { return FALSE; } subMode_T sm_get_current_sub_mode() { if (state_current == NULL) { return SM_NONE; } else { return state_current->subMode; } }; void sm_push(int mode, subMode_T subMode, void *context, state_execute executeFn, state_pending_operator pendingOperatorFn, state_cleanup cleanupFn) { sm_T *lastState = state_current; sm_T *newState = (sm_T *)alloc(sizeof(sm_T)); newState->prev = (sm_T *)lastState; newState->execute_fn = executeFn; newState->cleanup_fn = cleanupFn; newState->pending_operator_fn = pendingOperatorFn; newState->context = context; newState->mode = mode; newState->subMode = subMode; state_current = newState; } int sm_get_pending_operator(pendingOp_T *pendingOp) { if (state_current == NULL) { return FALSE; } return state_current->pending_operator_fn(state_current->context, pendingOp); } void sm_push_normal() { sm_push(NORMAL, SM_NONE, state_normal_cmd_initialize(), state_normal_cmd_execute, state_normal_pending_operator, state_normal_cmd_cleanup); } void sm_push_insert(int cmdchar, int startln, long count) { sm_push(INSERT, SM_NONE, state_edit_initialize(cmdchar, startln, count), state_edit_execute, no_pending_operator, state_edit_cleanup); } void sm_push_insert_literal(int *ret) { sm_push(INSERT, SM_INSERT_LITERAL, state_insert_literal_initialize(ret), state_insert_literal_execute, no_pending_operator, state_insert_literal_cleanup); } void sm_push_cmdline(int cmdchar, long count, int indent) { sm_push(CMDLINE, SM_NONE, state_cmdline_initialize(cmdchar, count, indent), state_cmdline_execute, no_pending_operator, state_cmdline_cleanup); } void sm_push_change(oparg_T *oap) { sm_push(INSERT, SM_NONE, state_change_initialize(oap), state_change_execute, no_pending_operator, state_change_cleanup); } /* * sm_execute_normal * * Like sm_execute, but if there is no active state, * defaults to normal mode. */ void sm_execute_normal(char_u *cmd, int preserveState) { sm_T *previousState = state_current; if (preserveState) { state_current = NULL; } if (state_current == NULL) { sm_push_normal(); } char_u *keys_esc = vim_strsave_escape_csi(cmd); ins_typebuf(keys_esc, REMAP_YES, 0, FALSE, FALSE); vim_free(keys_esc); if (state_current != NULL) { while (vpeekc() != NUL && typebuf.tb_len > 0) { int c = vgetc(); if (state_current == NULL) { sm_push_normal(); } sm_T *current = state_current; executionStatus_T result = current->execute_fn(state_current->context, c); switch (result) { case HANDLED: break; case UNHANDLED: vungetc(c); return; break; case COMPLETED_UNHANDLED: vungetc(c); current->cleanup_fn(state_current->context); state_current = (sm_T *)current->prev; vim_free(current); break; case COMPLETED: current->cleanup_fn(state_current->context); state_current = (sm_T *)current->prev; vim_free(current); break; } } } if (preserveState) { sm_T *stateToCleanup = state_current; while (stateToCleanup != NULL) { stateToCleanup->cleanup_fn(stateToCleanup->context); sm_T *prev = stateToCleanup; stateToCleanup = prev->prev; vim_free(prev); } state_current = previousState; } } void sm_execute(char_u *keys) { char_u *keys_esc = vim_strsave_escape_csi(keys); ins_typebuf(keys_esc, REMAP_YES, 0, FALSE, FALSE); vim_free(keys_esc); // Reset abbr_cnt after each input here, // to enable correct cabbrev expansions typebuf.tb_no_abbr_cnt = 0; if (state_current == NULL) { sm_push_normal(); } if (state_current != NULL) { while (vpeekc() != NUL) { int c = vgetc(); if (state_current == NULL) { sm_push_normal(); } sm_T *current = state_current; executionStatus_T result = current->execute_fn(state_current->context, c); switch (result) { case HANDLED: break; case UNHANDLED: vungetc(c); return; break; case COMPLETED_UNHANDLED: vungetc(c); current->cleanup_fn(state_current->context); state_current = (sm_T *)current->prev; vim_free(current); break; case COMPLETED: current->cleanup_fn(state_current->context); state_current = (sm_T *)current->prev; vim_free(current); break; } } } }
C
/* * ex0416.c * Verify the limitation of Unix/Linux about depths of the directories. * We create a directory with long name and then chdir into that * directory and create a long-name directory and enter that again, and so * forth. * Then we use some tools to retrieve the full path: getcwd, tar and cpio. * The result is that, when repeat more than 91 times, path exceeds the path * limit. i.e. if repeat 92 or more times, getcwd and pathconf will fail due to * long filename. * But, contrary to author's experiment, we can use tar to archive it. */ #include <stdio.h> #include <sys/stat.h> #include <sys/types.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> const char *name = "with_great_power_comes_great_responsibility"; int main( int argc, char **argv ) { const int depth = atoi( *++argv ); /* repeat times */ int i; for ( i = 0; i < depth; i++ ) { mkdir( name, 0777 ); chdir( name ); } char path[ 5000 ]; size_t size = 5000; if ( getcwd( path, size ) == NULL ) { printf( "getcwd error: %s\n", strerror( errno ) ); } else { printf( "current path, length is: %d, content is:\n%s\n", strlen( path ), path ); } long path_max = pathconf( path, _PC_PATH_MAX ); if ( path_max > 0 ) { printf( "path max is: %ld\n", path_max ); } else { printf( "pathconf error: %s\n", strerror( errno ) ); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> typedef struct { int chave; } REGISTRO; typedef struct { REGISTRO A[10]; int nelem; } LISTA; void inicl(LISTA* l){ l->nelem = 0; } void exibirL(LISTA l){ for(int i = 0; i<l.nelem;i++){ printf("%i \n", l.A[i].chave); } } int ocorrencias(LISTA* l,int x){ int cont = 0; for(int i = 0; i<l->nelem;i++){ if(l->A[i].chave == x){ cont++; } } return cont; } bool identicas(LISTA* l1, LISTA *l2) { if(l1->nelem != l2->nelem){ return false; } for(int i=0; i<l1->nelem;i++){ if(l1->A[i].chave != l2->A[i].chave){ return false; } } } int main(){ LISTA l1; LISTA l2; inicl(&l1); inicl(&l2); l1.A[0].chave = 1; l1.A[1].chave = 2; l1.A[2].chave = 3; l1.A[3].chave = 1; l1.A[4].chave = 1; l1.nelem =5; l2.A[0].chave = 1; l2.A[1].chave = 2; l2.A[2].chave = 1; l2.A[3].chave = 3; l2.A[4].chave = 1; l2.nelem =5; if(identicas(&l1,&l2)){ printf("As listas sao identicas"); } else{ printf("As listas sao diferentes"); } //int valor = 1; //printf("O numero de vezes que %i aparece na lista e: %i",valor, ocorrencias(&l1,valor)); }
C
//############################################################################# //! \file reference/C/source/$FILENAME$ //! \brief Division: signed (64-bit) / signed (64-bit) //! \author Vishal Coelho (adapted from original by Prasanth V.) //! \date 12-Apr-2016 //! // // Group: C2000 // Target Family: $DEVICE$ // //############################################################################# // $TI Release: $ // $Release Date: $ // $Copyright: $ //############################################################################# //***************************************************************************** // the includes //***************************************************************************** #include "fid.h" #include "fastrts_assert.h" //***************************************************************************** // defines //***************************************************************************** FASTRTS_FILENUM(16) //***************************************************************************** // FID_i64byi64_t //***************************************************************************** void FID_i64byi64_t(const int64_t num, const int64_t den, int64_t *p_quo, int64_t *p_rem) { int16_t i; static int16_t iter = 1; // R3 = denominator R3.i64 = den; // R1 = numerator R1.i64 = num; // Take the absolute value of the numerator and denominator // flag.TF = sign(num) ^ sign(den) // flag.NI = sign(num) // Zero out R2 ABSI64DIV64(&R3, &R1, &R2, &status_flag); for(i = 0; i < 32; i++) { SUBC2UI64 (&R3, &R1, &R2, &status_flag); } // if flag.TF == 1, quotient = -quotient // if flag.NI == 1, remainder = -remainder NEGI64DIV64(&R1, &R2, &status_flag); // Save the quotient and remainder *p_rem = R2.i64; *p_quo = R1.i64; #ifdef _DEBUG printf("#%4u: %20ld / %20ld -> Q = %20ld, R = %20ld\n", iter, num, den, *p_quo, *p_rem); #endif //_DEBUG iter++; } //***************************************************************************** // FID_i64byi64_m //***************************************************************************** void FID_i64byi64_m(const int64_t num, const int64_t den, int64_t *p_quo, int64_t *p_rem) { int16_t i; static int16_t iter = 1; // R3 = denominator R3.i64 = den; // R1 = numerator R1.i64 = num; // Take the absolute value of the numerator and denominator // flag.TF = sign(num) ^ sign(den) // flag.NI = sign(num) // Zero out R2 ABSI64DIV64(&R3, &R1, &R2, &status_flag); for(i = 0; i < 32; i++) { SUBC2UI64 (&R3, &R1, &R2, &status_flag); } // if flag.TF == 1 and flag.ZI == 0, quotient += 1, // remainder = divisor - remainder // if flag.TF == 1, quotient = -quotient // if flag.NI ^ flag.TF == 1, remainder = -remainder MNEGI64DIV64(&R3, &R1, &R2, &status_flag); // Save the quotient and remainder *p_rem = R2.i64; *p_quo = R1.i64; #ifdef _DEBUG printf("#%4u: %20ld / %20ld -> Q = %20ld, R = %20ld\n", iter, num, den, *p_quo, *p_rem); #endif //_DEBUG iter++; } //***************************************************************************** // FID_i64byi64_e //***************************************************************************** void FID_i64byi64_e(const int64_t num, const int64_t den, int64_t *p_quo, int64_t *p_rem) { int16_t i; static int16_t iter = 1; // R3 = denominator R3.i64 = den; // R1 = numerator R1.i64 = num; // Take the absolute value of the numerator and denominator // flag.TF = sign(num) ^ sign(den) // flag.NI = sign(num) // Zero out R2 ABSI64DIV64(&R3, &R1, &R2, &status_flag); for(i = 0; i < 32; i++) { SUBC2UI64 (&R3, &R1, &R2, &status_flag); } // if flag.NI == 1 and flag.ZI == 0, quotient += 1, // remainder = divisor - remainder // if flag.TF == 1, quotient = -quotient ENEGI64DIV64(&R3, &R1, &R2, &status_flag); // Save the quotient and remainder *p_rem = R2.i64; *p_quo = R1.i64; #ifdef _DEBUG printf("#%4u: %20ld / %20ld -> Q = %20ld, R = %20ld\n", iter, num, den, *p_quo, *p_rem); #endif //_DEBUG iter++; } // End of File
C
#include "btree.h" /* word frequency count */ main() { struct tnode *root; char word[MAXWORD]; struct outarray O[MAXWORD]; int len = 0, i; root = NULL; while (getword(word, MAXWORD) != EOF) if (isalpha(word[0])) root = addtree(root, word); getcounts(root, O, &len); sort(O, len); for (i = 0; i < len; i++) { printf("%d %s\n", O[i].count, O[i].word); } return 0; }
C
#include<stdio.h> int main() { int n1,n2,n3,n; scanf("%d %d %d",&n1,&n2,&n3); if(n1 > n2) n = n1; else n = n2; if(n > n3) printf("%d",n); else printf("%d",n3); }
C
#include <stdio.h> int WordLen(void); int Inverse(void); int MaxASCII(void); int main(void){ int opt=0; printf("1.length of word \n2.word inverse \n3.max ASCIInum \nenter a number : "); scanf("%d", &opt); switch(opt){ case 1 : WordLen(); break; case 2 : Inverse(); break; case 3 : MaxASCII(); break; default : ; } return 0; } int WordLen(void){ char Array[100]; int num=0; printf("Enter a Word : "); scanf("%s", Array); while (Array[num]!=0) {num++;} printf("input word length : %d\n", num); return 0; } int Inverse(void){ char BeforeInv[100], AfterInv[100]; int i=0, len=0; printf("Input a Word : "); scanf("%s", BeforeInv); while (BeforeInv[len]!=0) {len++;} printf("length : %d, BeforeInv : %s\n", len, BeforeInv); while (i<=len) {AfterInv[i]=BeforeInv[len-1-i]; i++;} AfterInv[len]=0; printf("AfterInv : %s\n", AfterInv); return 0; } int MaxASCII(void){ char Array[100], output; int i=0; printf("enter a word : "); scanf("%s", Array); output=Array[0]; while (Array[i]!='\0') {output=(output>=Array[i]) ? output : Array[i] ; i++;} printf("Max ASCII NUM character in your input : %c\n", output); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <time.h> #include <sys/time.h> #include <math.h> #define TRUE 1 #define FALSE 0 #define EMPTY 0 #define PIRATE 1 #define NINJA 2 int room_state; // current state of the room, one of the three values above int num_pirates_waiting; // number of pirates in line int num_ninjas_waiting; // number of ninjas in line int room_occupants; // number of people in the room int num_teams; // number of costuming teams int free_pirates; // number of free costumes given to pirates int free_ninjas; // number of free costumes given to ninjas int total_visits; int done; int numLoops; int queueSize; pthread_mutex_t state; // state lock pthread_mutex_t team_lock; // costuming team lock int pirate_visit_time; int ninja_visit_time; int max_pirate; int max_pirate_threshold; int max_ninja; int max_ninja_threshold; struct actor { int num_visits; time_t wait_time; time_t visit_time; int gold_owed; }; struct team { int free; // whether the team is free or not, TRUE | FALSE int free_time; // the duration of time the team has been free long pirate_busy_time; // the duration of time the team has been busy for pirates long ninja_busy_time; // the duration of time the team has been busy for ninjas long last_taken; long pirate_gold; long ninja_gold; }; struct team **teams; int normal_random(int time) { double a = drand48(); double b = drand48(); int ret = abs(time * (sqrt(-2 * log(a)) * cos(2 * M_PI * b))); return ret; //(time + ret); } void pirate(int arrival_time, struct actor *pirate_struct) { // pirate thread function sleep(normal_random(arrival_time)); struct timeval *tv = (struct timeval *)malloc(sizeof(struct timeval)); gettimeofday(tv, NULL); pirate_struct->wait_time = tv->tv_sec; pthread_mutex_lock(&state); total_visits++; num_pirates_waiting++; pthread_mutex_unlock(&state); while(TRUE) { pthread_mutex_lock(&state); if((room_state == EMPTY || room_state == PIRATE) && max_pirate_threshold < max_pirate && room_occupants < num_teams) { break; } pthread_mutex_unlock(&state); sleep(1); } room_state = PIRATE; room_occupants++; num_pirates_waiting--; max_pirate_threshold++; gettimeofday(tv, NULL); pirate_struct->wait_time = tv->tv_sec - pirate_struct->wait_time; pthread_mutex_unlock(&state); pthread_mutex_lock(&team_lock); int i = 0; for(i = 0; i < num_teams; i++) { if(teams[i]->free == TRUE) { teams[i]->free = FALSE; gettimeofday(tv, NULL); teams[i]->free_time += tv->tv_sec - teams[i]->last_taken; break; } } int service_time = normal_random(pirate_visit_time); teams[i]->pirate_busy_time += service_time; pthread_mutex_unlock(&team_lock); sleep(service_time); pirate_struct->visit_time = service_time; pthread_mutex_lock(&team_lock); teams[i]->free = TRUE; gettimeofday(tv, NULL); teams[i]->last_taken = tv->tv_sec; if(pirate_struct->wait_time < 30){ teams[i]->pirate_gold += service_time; pirate_struct->gold_owed += service_time; } else { free_pirates++; } pthread_mutex_unlock(&team_lock); //gettimeofday(tv, NULL); //pirate_struct->visit_time = tv->tv_sec - pirate_struct->visit_time; pthread_mutex_lock(&state); room_occupants--; if(room_occupants == 0) { if(num_ninjas_waiting > 0 && max_pirate_threshold >= max_pirate) { room_state = NINJA; } else { room_state = EMPTY; } max_pirate_threshold = 0; } pthread_mutex_unlock(&state); printf("PIRATE: Visit #%d\n", pirate_struct->num_visits); printf("Total wait time: %ld\n", pirate_struct->wait_time); printf("Total visit time: %ld\n", pirate_struct->visit_time); printf("Total Gold Owed: %d\n\n\n", pirate_struct->gold_owed); fflush(stdout); if(rand() % 4 == 1) { pirate_struct->num_visits++; pirate(arrival_time, pirate_struct); } } void ninja(int arrival_time, struct actor *ninja_struct) { // ninja thread function sleep(normal_random(arrival_time)); struct timeval *tv = (struct timeval *)malloc(sizeof(struct timeval)); gettimeofday(tv, NULL); ninja_struct->wait_time = tv->tv_sec; pthread_mutex_lock(&state); total_visits++; num_ninjas_waiting++; pthread_mutex_unlock(&state); while(TRUE) { pthread_mutex_lock(&state); if((room_state == EMPTY || room_state == NINJA) && max_ninja_threshold < max_ninja && room_occupants < num_teams) { break; } pthread_mutex_unlock(&state); sleep(1); } room_state = NINJA; room_occupants++; num_ninjas_waiting--; fflush(stdout); max_ninja_threshold++; gettimeofday(tv, NULL); ninja_struct->wait_time = tv->tv_sec - ninja_struct->wait_time; pthread_mutex_unlock(&state); pthread_mutex_lock(&team_lock); int i = 0; for(i = 0; i < num_teams; i++) { if(teams[i]->free == TRUE) { teams[i]->free = FALSE; gettimeofday(tv, NULL); teams[i]->free_time += tv->tv_sec - teams[i]->last_taken; break; } } int service_time = normal_random(ninja_visit_time); teams[i]->ninja_busy_time += service_time; pthread_mutex_unlock(&team_lock); sleep(service_time); ninja_struct->visit_time = service_time; pthread_mutex_lock(&team_lock); teams[i]->free = TRUE; gettimeofday(tv, NULL); teams[i]->last_taken = tv->tv_sec; if(ninja_struct->wait_time < 30){ teams[i]->ninja_gold += service_time; ninja_struct->gold_owed += service_time; } else { free_ninjas++; } pthread_mutex_unlock(&team_lock); pthread_mutex_lock(&state); room_occupants--; if(room_occupants == 0) { if(num_pirates_waiting > 0 && max_ninja_threshold >= max_ninja) { room_state = PIRATE; } else { room_state = EMPTY; } max_ninja_threshold = 0; } pthread_mutex_unlock(&state); printf("NINJA: Visit #%d\n", ninja_struct->num_visits); printf("Total wait time: %ld\n", ninja_struct->wait_time); printf("Total visit time: %ld\n", ninja_struct->visit_time); printf("Total Gold Owed: %d\n\n\n", ninja_struct->gold_owed); fflush(stdout); if(rand() % 4 == 1) { ninja_struct->num_visits++; ninja(arrival_time, ninja_struct); } } void pirate_thread(int *arrival_time) { struct actor *pirate_struct = (struct actor *)calloc(1, sizeof(struct actor)); pirate_struct->num_visits = 0; pirate_struct->wait_time = 0; pirate_struct->visit_time = 0; pirate_struct->gold_owed = 0; pirate(*arrival_time, pirate_struct); } void ninja_thread(int *arrival_time) { struct actor *ninja_struct = (struct actor *)calloc(1, sizeof(struct actor)); ninja_struct->num_visits = 0; ninja_struct->wait_time = 0; ninja_struct->visit_time = 0; ninja_struct->gold_owed = 0; ninja(*arrival_time, ninja_struct); } void counter(){ while(!done){ sleep(10); numLoops++; pthread_mutex_lock(&state); queueSize += num_pirates_waiting + num_ninjas_waiting; pthread_mutex_unlock(&state); } } int main(int argc, const char *argv[]) { num_teams = atoi(argv[1]); // number of teams, 2:4 int num_pirates = atoi(argv[2]); // number of pirates, 10:50 int num_ninjas = atoi(argv[3]); // number of ninjas, 10:50 pirate_visit_time = atoi(argv[4]); // average time spent in shop for pirates ninja_visit_time = atoi(argv[5]); // average time spent in shop for ninjas int pirate_arrive_time = atoi(argv[6]); // average arrival time of pirates int ninja_arrive_time = atoi(argv[7]); // average arrival time of ninjas struct timeval *tv = (struct timeval *)malloc(sizeof(struct timeval)); int ninja_gold = 0; int pirate_gold = 0; srand(time(0)); room_state = EMPTY; num_pirates_waiting = 0; num_ninjas_waiting = 0; free_pirates = 0; free_ninjas = 0; total_visits = 0; done = FALSE; numLoops = 0; queueSize = 0; pthread_mutex_init(&state, NULL); pthread_mutex_init(&team_lock, NULL); max_pirate = 25 / pirate_visit_time; max_ninja = 25 / ninja_visit_time; max_pirate_threshold = 0; max_ninja_threshold = 0; teams = (struct team **)calloc(num_teams, sizeof(struct team *)); for(int i = 0; i < num_teams; i++) { gettimeofday(tv, NULL); teams[i] = (struct team *)malloc(sizeof(struct team)); teams[i]->free = TRUE; teams[i]->last_taken = tv->tv_sec; teams[i]->pirate_gold = 0; teams[i]->ninja_gold = 0; } pthread_t *pirates = (pthread_t *)calloc(num_pirates, sizeof(pthread_t)); pthread_t *ninjas = (pthread_t *)calloc(num_ninjas, sizeof(pthread_t)); pthread_t queueCounter; int i; int pirates_made = 0; int ninjas_made = 0; for(i = 0; i < 50; i++) { if(pirates_made < num_pirates) { pthread_create(&pirates[i], NULL, (void *)&pirate_thread, &pirate_arrive_time); // creates each pirate thread in the array pirates_made++; } if(ninjas_made < num_ninjas) { pthread_create(&ninjas[i], NULL, (void *)&ninja_thread, &ninja_arrive_time); // creates each ninja thread in the array ninjas_made++; } } pthread_create(&queueCounter, NULL, (void *)&counter, NULL); for(i = 0; i < num_pirates; i++) { pthread_join(pirates[i], NULL); // joins every pirate thread } for(i = 0; i < num_ninjas; i++) { pthread_join(ninjas[i], NULL); // joins every ninja thread } done = TRUE; for(i = 0; i < num_teams; i++) { gettimeofday(tv, NULL); teams[i]->free_time += tv->tv_sec - teams[i]->last_taken; printf("Team %d was free for %d seconds\n", i, teams[i]->free_time); printf("Team %d was busy with pirates for %ld seconds and busy with ninjas for %ld seconds\n", i, teams[i]->pirate_busy_time, teams[i]->ninja_busy_time); ninja_gold += teams[i]->ninja_gold; pirate_gold += teams[i]->pirate_gold; } printf("Ninjas had %d free costumes and owe %d gold\n", free_ninjas, ninja_gold); printf("Pirates had %d free costumes and owe %d gold\n", free_pirates, pirate_gold); printf("Average queue length was %d\n", queueSize / numLoops); printf("Average gold per visit: %d\n", (pirate_gold + ninja_gold) / total_visits); printf("Gross Revenue was %d\n", pirate_gold + ninja_gold); printf("Total Profit was %d\n", pirate_gold + ninja_gold - (5 * num_teams)); }
C
/* * --- Module Description --------------------------------------------------- * */ /** * \file os.c * \author Artem Yushev * \date $Date$ * \version $Version$ * * \brief WIN implementation for os.h functions. */ /* * --- Includes ------------------------------------------------------------- * */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <io.h> #include <windows.h> #include <tchar.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <assert.h> #include <unistd.h> #include "encoder.h" #include "os.h" #include "e4c.h" /* * --- Macro Definitions ---------------------------------------------------- * */ /* * --- Type Definitions ----------------------------------------------------- * */ /** * \brief Substitute filename extension from input to mp3 * We already checked several times that data here is * actually a string, so we can't skip size... * \param to Pointer to where store the result * \param from Pointer from where get data * \return */ static char * __extSubstitute(char* to, const char* from); /** * \brief Check whether we support input file by probing its extension * We already checked several times that data here is * actually a string, so we can't skip size... * \param from Pointer from where get data * \return Negative on failure, otherwise OK */ static int8_t __extIsSupported(const char* from); /* * --- Variables ------------------------------------------------------------ * * / /* * --- Local Functions Declaration ------------------------------------------ * */ static char * __extSubstitute(char* to, const char* from) { assert(to != NULL); assert(from != NULL); char *lastdot; lastdot = strrchr (to, '.'); if (lastdot != NULL) snprintf(lastdot, MAX_FILEPATH,".mp3"); return to; } /* 0 not supported, < 0 error, 1 supported */ static int8_t __extIsSupported(const char* from) { assert(from != NULL); char* lastdot; int8_t ret = 0; lastdot = strrchr (from, '.'); if (lastdot != NULL) { /* ToDo: hardcoded part, but not critical */ if ((strncmp(lastdot,".wave",6) == 0) || (strncmp(lastdot,".wav",5) == 0)) { ret = 1; } } else { ret = -1; } return (ret); } /* * --- Global Functions Definition ------------------------------------------ * */ int8_t os_fOpen(uint8_t read, st_encoder_t * p_enc) { assert(p_enc != NULL); assert(p_enc->path != NULL); int8_t err = 0; struct stat st; int fd = 0; E4C_TRY { if (read) { fd = open(p_enc->path, O_RDONLY); if (fd == -1) { E4C_THROW(RuntimeException, "Failed to open a file\n"); } p_enc->opened = 1; p_enc->p_fp = fdopen(fd, "rb"); if (p_enc->p_fp == NULL) { E4C_THROW(RuntimeException, "Failed to associate a descriptor" "with opened file.\n"); } /* Ensure that the file is a regular file */ if (fstat(fd, &st) != 0) { E4C_THROW(RuntimeException, "Not a regular file.\n"); } p_enc->fsize = st.st_size; if (p_enc->fsize == -1) { E4C_THROW(RuntimeException, "Failed to calculate the size of a file.\n"); } } else { char* mp3Filename = NULL; if ((mp3Filename = malloc (strlen (p_enc->path) + 1)) == NULL) { E4C_THROW(RuntimeException, "Failed to allocate memory " "for filename.\n"); } strncpy (mp3Filename, p_enc->path, strlen(p_enc->path)); __extSubstitute(mp3Filename, p_enc->path); /* Open a file to write*/ fd = open(mp3Filename, O_RDWR|O_CREAT); free(mp3Filename); if (fd == -1) { E4C_THROW(RuntimeException, "Failed to open a file \n"); } p_enc->p_fp = fdopen(fd, "wb"); if (p_enc->p_fp == NULL) { E4C_THROW(RuntimeException, "Failed to associate a descriptor" "with opened file.\n"); } p_enc->opened = 1; } } E4C_CATCH (RuntimeException){ /* We opened a file, now we need to close it */ if (p_enc->opened) { close(fd); } const e4c_exception * e = e4c_get_exception(); fprintf(stderr, "Error: %s (%s) [%s].", e->name, e->message, p_enc->path); err = -1; } return (err); } int8_t os_fOffset(FILE* p_fp, int32_t off) { int8_t err = 0; /* Find the end of the file in a safe way */ if (fseeko(p_fp, off , SEEK_CUR) != 0) { err = -1; } return (err); } int32_t os_fExplore(st_encArg_t* p_encArg) { assert(p_encArg != NULL); assert(p_encArg->p_trgPath != NULL); TCHAR p_dir[MAX_PATH]; int32_t dirSize = 0; WIN32_FIND_DATA ffd; HANDLE hFind = INVALID_HANDLE_VALUE; /* Scanning the in directory */ strncpy(p_dir, p_encArg->p_trgPath, MAX_PATH); strncat(p_dir, TEXT("\\*"), MAX_PATH); // Find the first file in the directory. hFind = FindFirstFile(p_dir, &ffd); if (INVALID_HANDLE_VALUE == hFind) { fprintf(stderr, "%s\n",TEXT("FindFirstFile")); dirSize = -1; return (dirSize); } do { if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; if (__extIsSupported(ffd.cFileName) <= 0) continue; /* Allocate memory for file descriptor */ if (dirSize == 0) { p_encArg->p_fdesc = malloc(sizeof(st_encFDesc_t)); } else { p_encArg->p_fdesc = realloc(p_encArg->p_fdesc, (dirSize+1)*sizeof(st_encFDesc_t)); } /* Check result of malloc/realloc */ if (p_encArg->p_fdesc == NULL) { fprintf(stderr, "Error : Failed to allocate memory for file descriptor\n"); dirSize = -1; break; } /* We've found a file, duplicate memory*/ p_encArg->p_fdesc[dirSize].p_fname = strdup(ffd.cFileName); p_encArg->p_fdesc[dirSize].flocked = 0; /* Move pointer to a next element in array of filenames */ /* Increment file amount of files */ dirSize++; }while (FindNextFile(hFind, &ffd) != 0); if (dirSize == 0) { free(p_encArg->p_fdesc); } p_encArg->files = dirSize; return (dirSize); } inline void os_mkPath(char* p_path, char* p_dirPath, char* p_fname, uint16_t lim) { snprintf(p_path,lim,"%s\\%s",p_dirPath,p_fname); } inline int32_t os_read32be(FILE* p_fp) { uint8_t data[4] = { 0, 0, 0, 0 }; fread_unlocked(data, 1, 4, p_fp); int32_t const high = data[0]; int32_t const medh = data[1]; int32_t const medl = data[2]; int32_t const low = data[3]; return (high << 24) | (medh << 16) | (medl << 8) | low; } inline int32_t os_read32le(FILE* p_fp) { uint8_t data[4] = { 0, 0, 0, 0 }; fread_unlocked(data, 1, 4, p_fp); int32_t const high = data[3]; int32_t const medh = data[2]; int32_t const medl = data[1]; int32_t const low = data[0]; return (high << 24) | (medh << 16) | (medl << 8) | low; } inline int16_t os_read16be(FILE* p_fp) { uint8_t data[2] = { 0, 0}; fread_unlocked(data, 1, 2, p_fp); int32_t const high = data[0]; int32_t const low = data[1]; return (high << 8) | low; } inline int16_t os_read16le(FILE* p_fp) { uint8_t data[2] = { 0, 0 }; fread_unlocked(data, 1, 2, p_fp); int32_t const high = data[1]; int32_t const low = data[0]; return (high << 8) | low; } inline uint32_t os_fread_unlocked(void* p_buf, size_t size, size_t cnt, FILE* p_fp) { return (fread_unlocked(p_buf, size, cnt, p_fp)); } inline void os_fwrite_unlocked(void* p_buf, size_t size, size_t cnt, FILE* p_fp) { fwrite_unlocked(p_buf, size, cnt, p_fp); } inline void os_fclose(st_encoder_t* p_enc) { if (p_enc->opened) fclose( p_enc->p_fp); } inline void os_splitFlopUI8(uint8_t* from, int32_t* toFir, int32_t* toSec, uint32_t toMaxOff) { int i = 0; uint8_t off = sizeof(uint8_t); while (1) { if (((i + off) < toMaxOff) && (toFir != NULL)) { *toFir = (from[i] ^ 0x80) << 24; toFir++; i += off; } if (((i + off) < toMaxOff) && (toSec != NULL)) { *toSec = (from[i] ^ 0x80) << 24; toSec++; i += off; } if ((i + off) == toMaxOff) break; } } inline void os_splitFlopI16(uint8_t* from, int32_t* toFir, int32_t* toSec, uint32_t toMaxOff) { int i = 0; uint8_t off = sizeof(int16_t); while (1) { if (((i + off) < toMaxOff) && (toFir != NULL)) { *toFir = from[i + 1] << 24 | from[i] << 16; toFir++; i += off; } if (((i + off) < toMaxOff) && (toSec != NULL)) { *toSec = from[i + 1] << 24 | from[i] << 16; toSec++; i += off; } if ((i + off) == toMaxOff) break; } } inline void os_splitFlopI24(uint8_t* from, int32_t* toFir, int32_t* toSec, uint32_t toMaxOff) { int i = 0; uint8_t off = 3; while (1) { if (((i + off) < toMaxOff) && (toFir != NULL)) { *toFir = from[i + 2] << 24 | from[i + 1] << 16 | from[i] << 8; toFir++; i += off; } if (((i + off) < toMaxOff) && (toSec != NULL)) { *toSec = from[i + 2] << 24 | from[i + 1] << 16 | from[i] << 8; toSec++; i += off; } if ((i + off) == toMaxOff) break; } } inline void os_splitFlopI32(uint8_t* from, int32_t* toFir, int32_t* toSec, uint32_t toMaxOff) { int i = 0; uint8_t off = sizeof(int32_t); while (1) { if (((i + off) < toMaxOff) && (toFir != NULL)) { *toFir = from[i + 3] << 24 | from[i + 2] << 16 | from[i + 1] << 8 | from[i]; toFir++; i += off; } if (((i + off) < toMaxOff) && (toSec != NULL)) { *toSec = from[i + 3] << 24 | from[i + 2] << 16 | from[i + 1] << 8 | from[i]; toSec++; i += off; } if ((i + off) == toMaxOff) break; } } inline uint8_t os_flop_ui8i32(uint8_t* from, int32_t* to, uint32_t toOff, uint32_t toMaxOff) { uint8_t res = 1; if ((toOff < toMaxOff) && (to != NULL)) { *to = (*from ^ 0x80) << 24; } else { res = 0; } return (res); } inline uint8_t os_flop_i16i32(uint8_t* from, int32_t* to, uint32_t toOff, uint32_t toMaxOff) { uint8_t res = 1; if ((toOff < toMaxOff) && (to != NULL)) { *to = (*from+1) << 24 | *from << 16; } else { res = 0; } return (res); } inline uint8_t os_flop_i32i32(uint8_t* from, int32_t* to, uint32_t toOff, uint32_t toMaxOff) { uint8_t res = 1; if ((toOff < toMaxOff) && (to != NULL)) { *to = (*from+3) << 24 | (*from+2) << 16 | (*from+1) << 8 | *from; } else { res = 0; } return (res); }
C
#include "Sorter.h" #include "mergesort.c" /* global variable to keep track of IP addresses */ List *IPList; /* global variable to keep track of process ID */ int processID; List *newList() { List *list = malloc(sizeof(List)); if (list == NULL) { printf("Unable to allocate memory for list\n"); exit(1); } // list->size=0; list->head=NULL; return list; } void insert(void *data, List *list) { Node *tmp, *node; node = malloc(sizeof(Node)); if (node == NULL) { printf("Unable to allocate memory for node\n"); exit(1); } node->data = data; node->next=NULL; pthread_mutex_lock(&list->mutex); tmp = list->head; list->head = node; list->head->next = tmp; // list->size++; pthread_mutex_unlock(&list->mutex); } void destroyList(List *list) { Node *node, *tmp; node = list->head; while(node) { tmp=node; node = node->next; if ((tmp->data) != NULL) { free(tmp->data); } free(tmp); } free(list); } /* Handler for SIGTERM, the default signal sent by SIGKILL to terminate program */ void handler(int sig) { if ((sig==SIGINT) ||(sig==SIGTERM) || (sig== SIGALRM)) { // printf("handler\n"); Node *node, *tmp; char str[1024]; printf("Recieved connections from:"); if (IPList == NULL) { printf("Exited prematurely\n"); exit(1); } node = IPList->head; // printf("addr of head: %p\n", node); while(node) { tmp=node; inet_ntop(AF_INET, tmp, str, 1024); printf("%s",str); if((node->next) != NULL) printf(","); printf(" "); node = node->next; } destroyList(IPList); if (sig == SIGALRM) { printf("Exited on some kind of error\n"); exit(1); } printf("\nExited successfully\n"); exit(0); } else { printf("\nthis should not have happened\n"); exit(1); } } /* prints an error message and exits the program */ void ERROR(char *error) { printf("ERROR: %s\n",error); /* Use SIGALRM for error handling */ if (signal(SIGALRM, handler) == SIG_ERR) { printf("Could not install SIGALRM handler\n"); exit(1); } kill(processID, SIGALRM); //exit(1); } /* wrapper around malloc to detect out of memory errors */ void *safeMalloc(size_t size) { void *p; p=malloc(size); if(p==NULL) ERROR("Out of memory!"); return p; } /* wrapper around realloc to detect out of memory errors */ void *safeRealloc(void *ptr,size_t size) { void *p; p=realloc(ptr,size); if(p==NULL) ERROR("Out of memory!"); return p; } /* count the number of comma separated columns in the given line */ int countColumns(char *line) { char *p; int n; n=1; /* by default, line contains a field */ p=line; while(*p) { if(*p==',') /* we found a comma */ n++; /*increment number of fields*/ p++; } return n; /* return the number of fields */ } /* split a given line using the commas as delimiters, returns an array of data, expects n columns of data*/ Data *commaSplit(char *line,int n) { int start; int pos,col; Data *parts; int inquotes; parts=(Data *)safeMalloc(n*sizeof(Data)); /* allocate space for columns*/ pos=0; start=0; /*start of current column data*/ col=0; /*current column number */ inquotes=0; while(line[pos]!=0 && line[pos]!='\r' && line[pos]!='\n') { if(line[pos] == '\"') inquotes=!inquotes; if(!inquotes && line[pos]==',') /* we found a comma */ { parts[col].s=(char *)safeMalloc(pos-start+1); /* allocate space for column data*/ strncpy(parts[col].s,&line[start],pos-start); parts[col].s[pos-start]=0; /* insert string terminator */ start=pos+1; /* column data starts after the comma*/ col++; /*increment current column*/ } pos++; } parts[col].s=(char *)safeMalloc(pos-start+1); /* allocate space for last column*/ strncpy(parts[col].s,&line[start],pos-start); parts[col].s[pos-start]=0; /* insert string terminator */ return parts; } /* inserts a new row in the csv structure */ void insertRow(Data *rowdata,CSV *csv) { //int col; if(csv->nrows==0) csv->rows=(Data **)safeMalloc(sizeof(Data *)); /*create single row entry */ else csv->rows=(Data **)safeRealloc(csv->rows,(csv->nrows+1)*sizeof(Data *)); /*create single row entry */ csv->rows[csv->nrows]=rowdata; csv->nrows++; } /* creates a new CSV structure */ CSV *newCSV(int nrows) { CSV *csv; csv=(CSV*)safeMalloc(sizeof(CSV)); /* create new CSV structure */ csv->ncols=0; csv->nrows=nrows; csv->header=NULL; if(nrows==0) csv->rows=NULL; else csv->rows=(Data **)safeMalloc(csv->nrows*sizeof(Data *)); /*create rows */ csv->types=NULL; return csv; } /* frees all the space used by the csv structure*/ void deleteCSV(CSV *csv) { int i,j; if(csv->header) { for(j=0; j<csv->ncols; j++) free(csv->header[j].s); free(csv->header); } for(i=0; i<csv->nrows; i++) { for(j=0; j<csv->ncols; j++) if(csv->types[j]==STRING) free(csv->rows[i][j].s); free(csv->rows[i]); } if(csv->types) free(csv->types); free(csv->rows); free(csv); } /* returns 1 if the string is an integer, 0 if it is not, -1 if an error is found */ int isInteger(char *val) { int i; if(val[0]==0) return -1; i=0; if(val[i]=='+' || val[i]=='-') /* skip sign if found */ i++; for(; i<strlen(val); i++) if(!isdigit(val[i])) return 0; return 1; } /* returns 1 if the string is a float, 0 if it is not, -1 if an error is found */ int isFloat(char *val) { int i; if(val[0]==0) return -1; i=0; if(val[i]=='+' || val[i]=='-') /* skip sign if found */ i++; for(; i<strlen(val); i++) if(!isdigit(val[i])) break; if(val[i++]!='.') return 0; for(; i<strlen(val); i++) if(!isdigit(val[i])) return 0; return 1; } /* detect the type of column in the csv */ int detectColumnType(int col,CSV *csv) { int isi,isf; int row; int type; type=UNKNOWN; for(row=0; row<csv->nrows; row++) { if((isf=isFloat(csv->rows[row][col].s))==1) { if(type!=STRING) type=FLOAT; } else if((isi=isInteger(csv->rows[row][col].s))==1) { if(type!=STRING && type!=FLOAT) type=INTEGER; } else if(!isi && !isf) type=STRING; } if(type==UNKNOWN) type=STRING; return type; } /* set the types for all columns in the CSV*/ void setTypes(CSV *csv) { int row,col; char *p; csv->types=(int*)safeMalloc(csv->ncols*sizeof(int)); for(col=0; col<csv->ncols; col++) csv->types[col]=detectColumnType(col,csv); for(col=0; col<csv->ncols; col++) { if(csv->types[col]==INTEGER) { for(row=0; row<csv->nrows; row++) { p=csv->rows[row][col].s; csv->rows[row][col].i=atoi(p); free(p); } } else if(csv->types[col]==FLOAT) { for(row=0; row<csv->nrows; row++) { p=csv->rows[row][col].s; csv->rows[row][col].f=atof(p); free(p); } } } } /* parses a CSV file given in stdin and saves it in a CSV structure */ CSV *inputCSV(FILE *inputFile) { CSV *csv; char buffer[1024]; Data *rowdata; if(!fgets(buffer,1024,inputFile)) /* read header */ ERROR("Empty file."); csv=newCSV(0); csv->ncols=countColumns(buffer); /* get expected number of columns */ csv->header=commaSplit(buffer,csv->ncols); /* fill column names */ while(fgets(buffer,1024,inputFile) != NULL) /* read line by line*/ { rowdata=commaSplit(buffer,csv->ncols); /* get column values for current row */ insertRow(rowdata,csv); /* insert a new row in the csv structure */ bzero(buffer,1024); } setTypes(csv); return csv; } /* send CSV structure to stdout */ void outputCSV(CSV *csv, FILE *outputFILE ) { int i,j; for(i=0; i<csv->ncols; i++) { fprintf(outputFILE, "%s",csv->header[i].s); if(i<csv->ncols-1) fprintf(outputFILE, ","); } fprintf(outputFILE, "\n"); for(i=0; i<csv->nrows; i++) { for(j=0; j<csv->ncols; j++) { if(csv->types[j]==STRING) fprintf(outputFILE,"%s",csv->rows[i][j].s); else if(csv->types[j]==INTEGER) fprintf(outputFILE,"%d",csv->rows[i][j].i); if(csv->types[j]==FLOAT) fprintf(outputFILE,"%lf",csv->rows[i][j].f); if(j<csv->ncols-1) fprintf(outputFILE,","); } fprintf(outputFILE,"\n"); } fprintf(outputFILE,"\n"); } /* sorts the csv using the selected column*/ void sortCSV(CSV *csv,char *column) { int col; for(col=0; col<csv->ncols; col++) if(!strcmp(csv->header[col].s,column)) break; if(col==csv->ncols) { deleteCSV(csv); ERROR("Column was not found!"); exit(-1); } mergeSort(csv,col); } /* compare two strings using the type to convert them to an integer or a float*/ int compare(Data a,Data b,int type) { switch(type) { case STRING: /* if they are strings */ return strcmp(a.s,b.s); break; case INTEGER: /* if they are integers, */ if(a.i>b.i) return 1; else if(a.i<b.i) return -1; else return 0; break; case FLOAT: /* if the values are floating point */ if(a.f>b.f) return 1; else if(a.f<b.f) return -1; else return 0; break; } return 0; } void *request(void *arg){ int sock = *(int*)arg; int buff_size; char column[1024]; FILE *outCSV = fopen("out.csv","w"); char message[1024], client_message[1024], filename[1024]; //sleep(2); printf("called request\n"); while(read(sock, client_message, 1023) > 0){ if(strcmp(client_message,"sort") == 0){ bzero(client_message,1024); read(sock,client_message,1023); strcpy(column, client_message); bzero(client_message,1024); FILE *tempCSV = fopen("tempCSV.csv", "w"); int size; int i = 0; while((size = read(sock, client_message,1023)) > 0){ if(strcmp(client_message,"break") != 0){ fprintf(tempCSV,client_message); bzero(client_message,1024); i++; //printf("line: %d\n",i); } else break; } bzero(client_message,1024); fclose(tempCSV); FILE *newCSV = fopen("tempCSV.csv", "r"); rewind(tempCSV); CSV *csv = inputCSV(newCSV); fclose(newCSV); sortCSV(csv,column); outputCSV(csv, outCSV); deleteCSV(csv); remove("tempCSV.csv"); send(sock,"Sorted",strlen("Sorted"),0); usleep(1000); } else if(strcmp(client_message, "dump") == 0){ fclose(outCSV); outCSV = fopen("out.csv", "r"); rewind(outCSV); sleep(1); int c = 0; bzero(message,1024); while(fgets(message,1024,outCSV)){ send(sock,message,strlen(message),0); usleep(100); bzero(message,1024); c++; } sleep(1); fclose(outCSV); remove("out.csv"); send(sock,"Dumped",strlen("Dumped"),0); break; } } } int main(int argc,char **argv){ processID = getpid(); char USAGE[] = "USAGE: ./sorter_server -p port"; if(strcmp(argv[1],"-p") != 0 || argc < 3){ printf("Input Error, Need Port\n"); printf("%s\n",USAGE); exit(1); } if (argc > 3) { printf("too many parameters\n"); printf("%s\n",USAGE); exit(1); } char ip_address[15]; int fd; int count = 0; struct ifreq ifr; fd = socket(AF_INET, SOCK_DGRAM, 0); ifr.ifr_addr.sa_family = AF_INET; memcpy(ifr.ifr_name, "eth0", IFNAMSIZ-1); ioctl(fd, SIOCGIFADDR, &ifr); close(fd); strcpy(ip_address,inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr)); int welcomeSocket, newSocket; char buffer[1024]; struct sockaddr_in serverAddr, clientAddr; struct in_addr *ipAddrPtr; // struct sockaddr_storage serverStorage; socklen_t addr_size; /* install handler to deal with SIGTERM and SIGINT */ if (signal(SIGTERM, handler) == SIG_ERR) ERROR("Could not install SIGTERM handler"); if (signal(SIGINT, handler) == SIG_ERR) ERROR("Could not install SIGINT handler"); printf("Process ID of server: %d\n", processID); /* welcomeSocket = socket(PF_INET, SOCK_STREAM, 0); if (welcomeSocket < 0) ERROR("Could not open socket"); bzero((char *)&serverAddr, sizeof(serverAddr)); */ IPList=newList(); /*---- Configure settings of the server address struct ----*/ serverAddr.sin_family = AF_INET; /* Set port number, using htons function to use proper byte order */ serverAddr.sin_port = htons(atoi(argv[2])); serverAddr.sin_addr.s_addr = INADDR_ANY; /* Set all bits of the padding field to 0 */ memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero); /*---- Bind the address struct to the socket ----*/ /* if((bind(welcomeSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr))) < 0) ERROR("Couldn't bind socket"); */ /*---- Listen on the socket, with 5 max connection requests queued ----*/ /* if(listen(welcomeSocket,5)==0) printf("Listening\n"); else printf("Error\n"); */ /*---- Accept call creates a new socket for the incoming connection ----*/ // addr_size = sizeof serverStorage; addr_size = sizeof(clientAddr); //newSocket = accept(welcomeSocket, (struct sockaddr *) &serverStorage, &addr_size); /*---- Send message to the socket of the incoming connection ----*/ //strcpy(buffer,"Hello World\n"); //send(newSocket,buffer,13,0); welcomeSocket = socket(AF_INET, SOCK_STREAM, 0); if (welcomeSocket < 0) ERROR("Could not open socket"); if((bind(welcomeSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr))) < 0) ERROR("Couldn't bind socket"); if(listen(welcomeSocket,5)==0) printf("Listening\n"); else printf("Error\n"); newSocket = accept(welcomeSocket, (struct sockaddr *) &clientAddr, &addr_size); printf("new listening socket created\n"); if(newSocket < 0) ERROR("Error on accepting"); while(1 == 1){ // newSocket = accept(welcomeSocket, (struct sockaddr *) &serverStorage, &addr_size); /* welcomeSocket = socket(AF_INET, SOCK_STREAM, 0); if (welcomeSocket < 0) ERROR("Could not open socket"); if((bind(welcomeSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr))) < 0) ERROR("Couldn't bind socket"); if(listen(welcomeSocket,5)==0) printf("Listening\n"); else printf("Error\n"); newSocket = accept(welcomeSocket, (struct sockaddr *) &clientAddr, &addr_size); printf("new listening socket created\n"); if(newSocket < 0) ERROR("Error on accepting"); */ ipAddrPtr = malloc(sizeof(struct in_addr)); if (ipAddrPtr==NULL) { printf("error allocating memory for ipAddrPtr\n"); exit(1); } *ipAddrPtr = clientAddr.sin_addr; insert(ipAddrPtr, IPList); if (ipAddrPtr==NULL) { printf("error allocating memory for ipAddrPtr\n"); exit(1); } // printf("Recieved Connection %d on Socket %d\n",newSocket); // printf("Recieved Connection %d on Socket %d\n",count, newSocket); bzero(buffer,1024); pthread_t thread_id; pthread_create(&thread_id, NULL, request, (void*)&newSocket); pthread_join(thread_id,NULL); shutdown(newSocket,0); printf("Waiting for next connection.\n"); } return 0; }
C
#include <stdio.h> #include <string.h> #define MAX_STACK 100 typedef enum { false, true } bool; typedef struct { char palin[MAX_STACK]; int top; } Stack; void initStack(Stack* pstack); bool isFull(Stack* pstack); bool isEmpty(Stack* pstack); char Peek(Stack* pstack); void Push(Stack* pstack, char c); void Pop(Stack* pstack); int main() { Stack seq, comp; char pl[MAX_STACK]; int pl_len, diff = 0; // printf("Characters: "); scanf("%s", pl); pl_len = strlen(pl); initStack(&seq); initStack(&comp); // printf("\nYour word: %s", pl); for (int i = 0; i < pl_len; i++) { Push(&seq, pl[i]); Push(&comp, pl[pl_len - i -1]); } for (int i = 0; i < pl_len; i++) { if (Peek(&seq) != Peek(&comp)) { diff++; // printf("%c | %c\n", Peek(&seq), Peek(&comp)); } Pop(&seq); Pop(&comp); } printf("%d", diff); return 0; } void initStack(Stack* pstack) { pstack->top = -1; } bool isFull(Stack* pstack) { return pstack->top == MAX_STACK - 1; } bool isEmpty(Stack* pstack) { return pstack->top == -1; } char Peek(Stack* pstack) { if (isEmpty(pstack)) { printf("\n[ERROR]: Your stack did not have an element...\n"); exit(1); } return pstack->palin[pstack->top]; } void Push(Stack* pstack, char c) { pstack->top++; pstack->palin[pstack->top] = c; } void Pop(Stack* pstack) { if (isEmpty(pstack)) { printf("\n[ERROR]: Your stack did not have an element...\n"); exit(1); } --(pstack->top); }
C
/* * Copyright (c) 2016 Sugizaki Yukimasa * All rights reserved. * * This software is licensed under a Modified (3-Clause) BSD License. * You should have received a copy of this license along with this * software. If not, contact the copyright holder above. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <errno.h> #include <vc4vec.h> #include "qpu_memcpy.h" static const int mem_size = 1024 * 1024 * 30; static void rand_mem(unsigned *p, size_t n) { size_t i; const size_t len = n / sizeof(*p); #pragma omp parallel for private(i) firstprivate(p, len) for (i = 0; i < len; i ++) p[i] = random(); } int main() { struct vc4vec_mem dest, src; unsigned *dest_cpu, *src_cpu; unsigned dest_gpu, src_gpu; float time, Bps; vc4vec_init(); atexit(vc4vec_finalize); vc4vec_mem_alloc(&dest, mem_size); vc4vec_mem_alloc(&src, mem_size); dest_cpu = dest.cpu_addr; dest_gpu = dest.gpu_addr; src_cpu = src.cpu_addr; src_gpu = src.gpu_addr; qpu_memcpy_init(); { struct timeval st; gettimeofday(&st, NULL); srandom(st.tv_sec ^ st.tv_usec); } rand_mem(src_cpu, mem_size); qpu_memcpy_launch(&time, &Bps, cpu_memcpy_1, dest_cpu, dest_gpu, src_cpu, src_gpu, mem_size); printf("cpu_memcpy_1: %g [s], %g [B/s]\n", time, Bps); rand_mem(src_cpu, mem_size); qpu_memcpy_launch(&time, &Bps, cpu_memcpy_2, dest_cpu, dest_gpu, src_cpu, src_gpu, mem_size); printf("cpu_memcpy_2: %g [s], %g [B/s]\n", time, Bps); rand_mem(src_cpu, mem_size); qpu_memcpy_launch(&time, &Bps, cpu_memcpy_3, dest_cpu, dest_gpu, src_cpu, src_gpu, mem_size); printf("cpu_memcpy_3: %g [s], %g [B/s]\n", time, Bps); rand_mem(src_cpu, mem_size); qpu_memcpy_launch(&time, &Bps, qpu_memcpy_1, dest_cpu, dest_gpu, src_cpu, src_gpu, mem_size); printf("qpu_memcpy_1: %g [s], %g [B/s]\n", time, Bps); rand_mem(src_cpu, mem_size); qpu_memcpy_launch(&time, &Bps, qpu_memcpy_2, dest_cpu, dest_gpu, src_cpu, src_gpu, mem_size); printf("qpu_memcpy_2: %g [s], %g [B/s]\n", time, Bps); rand_mem(src_cpu, mem_size); qpu_memcpy_launch(&time, &Bps, qpu_memcpy_3, dest_cpu, dest_gpu, src_cpu, src_gpu, mem_size); printf("qpu_memcpy_3: %g [s], %g [B/s]\n", time, Bps); qpu_memcpy_finalize(); vc4vec_mem_free(&src); vc4vec_mem_free(&dest); /* vc4vec_finalize was registered to atexit, so it will be called after this return. */ return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <time.h> // Number of vertices in the graph #define N 6 // Structure to define Graph struct Graph { struct Node* head[N]; }; // Structure to define vertices struct Node { int destination; struct Node* next; }; // Structure to define the edge struct Edge { int source, destination; }; // Function to create the graph struct Graph* createGraph(struct Edge edges[], int n) { struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph)); for (int i = 0; i < N; i++) { graph->head[i] = NULL; } for (int i = 0; i < n; i++) { int source = edges[i].source; int destination = edges[i].destination; struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->destination = destination; newNode->next = graph->head[source]; graph->head[source] = newNode; } return graph; } // Function to calculate Chromatic Number void calculateChromaticNumber(struct Graph* graph) { int allot[N]; allot[0] = 0; for (int i = 1; i < N; i++) { allot[i] = -1; } bool check[N]; for (int i = 0; i < N; i++) { check[i] = false; } for (int i = 1; i < N; i++) { struct Node* ptr = graph->head[i]; while (ptr != NULL) { if(allot[ptr->destination]!=-1) { check[allot[ptr->destination]]=true; } ptr = ptr->next; } int j; for (j = 0; j < N; j++) if (check[j] == false) break; allot[i] = j; ptr = graph->head[i]; while (ptr != NULL) { if(allot[ptr->destination]!=-1) { check[allot[ptr->destination]]=false; } ptr = ptr->next; } } int count=0; int temp[N]; for (int i = 0; i < N; i++) { temp[i]=-1; } for(int i=0;i<N;i++) { int k=allot[i]; temp[k]++; } for(int i=0;i<N;i++) { if(temp[i]!=-1) { count++; } } printf("Chromatic Number: %d \n",count); // Print the Chromatic Number } // Main Function int main(void) { // Defining the edges in the graph struct Edge edges[] = { { 0, 1 }, {0,2}, {0,4}, {1,0}, {1,2}, {1,3}, {1,5}, {2,0}, {2,1}, {2,3}, {2,4}, {3,2}, {3,1}, {3,5}, {4,0}, {4,2}, {4,5}, {5,1}, {5,3}, {5,4} }; clock_t begin = clock(); // Number of edges int n = sizeof(edges)/sizeof(edges[0]); struct Graph *graph = createGraph(edges, n); calculateChromaticNumber(graph); clock_t end = clock(); double time_spent = (double)(end - begin) / CLOCKS_PER_SEC; printf("%f", time_spent); printf("\n"); return 0; }
C
int findLengthOfLCIS(int* nums, int numsSize){ if (numsSize <= 1) return numsSize; int cnt = INT_MIN; int tmp = 1; for (int i = 0; i < (numsSize-1); i++) { if (nums[i+1] <= nums[i]) { tmp = 1; } else { tmp++; } cnt = (cnt > tmp) ? cnt : tmp; } return cnt; }
C
#include <stdio.h> int main() { int first, second, third, eq_result; scanf("%d%d%d", &first, &second, &third); eq_result = Mathpower(first, second); if(eq_result == third) printf("1"); else printf("0"); return 0; } int Mathpower(int firstp, int secondp) { int result = 1, i; for (i = 0; i < secondp; i++) { result = result * firstp; } return result; }
C
/* * string::find_last_of requires memchr and it's implemented in libc. * libc is too big to be loaded in ESP RAM thus one of solutions is to just * copypaste it here. * * More details here: * https://github.com/pfalcon/esp-open-sdk/issues/213 */ void* memchr(const void* s, unsigned char c, int n) { if (n != 0) { const unsigned char *p = s; do { if (*p++ == c) return ((void *)(p - 1)); } while (--n != 0); } return 0; }
C
// server program for udp connection #include <stdio.h> #include <strings.h> #include <sys/types.h> #include <arpa/inet.h> #include <sys/socket.h> #include<netinet/in.h> #define PORT 5000 #define MAXLINE 1000 char *rev(char *s) { int size = strlen(s); char* out = malloc(size); int x = size-1; //Will reverse for (int i=0; i<size; i++) { out[x--] = s[i]; } return out; } // Driver code int main() { char buffer[100]; char *message; int listenfd, len; struct sockaddr_in servaddr, cliaddr; bzero(&servaddr, sizeof(servaddr)); // Create a UDP Socket listenfd = socket(AF_INET, SOCK_DGRAM, 0); servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(PORT); servaddr.sin_family = AF_INET; // bind server address to socket descriptor bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)); while(1) { //receive the datagram len = sizeof(cliaddr); int n = recvfrom(listenfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&cliaddr,&len); //receive message from server buffer[n] = '\0'; puts(buffer); message = rev(buffer); printf("Client's IP Number on Server's Side = %s", inet_ntoa(cliaddr.sin_addr)); printf("Client's Port Number on Server's Side = %d", (int)ntohs(cliaddr.sin_port)); // send the response sendto(listenfd, message, MAXLINE, 0, (struct sockaddr*)&cliaddr, sizeof(cliaddr)); } }
C
#include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/ip.h> #include <arpa/inet.h> #define DEFAULT_PORT 8888 #define BACKLOG 5 #define BUF_SIZE 128 static int send_str(int sock, const char *str); static int recv_str(int sock, char *buf, int max_len); static int send_byte(int sock, const char *buf, int len); static int recv_byte(int sock, char *buf, int len); static int eat_byte(int sock, int len); int start_client(const char* addr, int port); static char g_buf[BUF_SIZE]; int main(int argc, char **argv) { int i, r, port; char *addr; addr = "127.0.0.1"; port = 8888; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "-p") == 0) { i++; if (i >= argc) { printf("Error: must specify port number!\n"); return -1; } port = atoi(argv[i]); if (port == 0) { printf("Error: wrong port number!\n"); return -1; } } else { addr = argv[i]; } } r = start_client(addr, port); return r; } int start_client(const char* addr, int port) { int r ; int sock; struct sockaddr_in server_addr; if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("start_client: socket()"); return -1; } memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port); if (!inet_aton(addr, &server_addr.sin_addr)) { perror("start_client: inet_aton()"); return -1; } r = connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)); if (r < 0) { perror("start_client: connect()"); close(sock); return -1; } for(;;) { if (recv_str(sock, g_buf, sizeof(g_buf)) <= 0) break; printf("I am client >>> %s\n", g_buf); fgets(g_buf, sizeof(g_buf), stdin); g_buf[strlen(g_buf) - 1] = '\0'; if (send_str(sock, g_buf) <= 0) break; } close(sock); return 0; } int send_str(int sock, const char* str) { int byte; int len; int len_send; len = strlen(str); len_send = htonl(len); byte = send_byte(sock, (char *)&len_send, sizeof(len_send)); if (byte < 0) return -1; byte = send_byte(sock, str, len); if (byte < 0) return -1; return byte; } int recv_str(int sock, char* buf, int max_len) { int byte; int len; int len_recv; int len_diff = 0; byte = recv_byte(sock, (char *)&len_recv, sizeof(len_recv)); if (byte < 0) return -1; len = ntohl(len_recv); if (len > max_len) { len_diff = len - max_len; len = max_len; } byte = recv_byte(sock, buf, len); if (byte <= 0) return -1; buf[byte] = '\0'; if (len_diff > 0) eat_byte(sock, len_diff); return byte; } int send_byte(int sock, const char* buf, int len) { int rc; int byte; for (byte = 0; byte < len; byte += rc) { rc = send(sock, buf + byte, len - byte, MSG_NOSIGNAL); if (rc < 0 && errno != EINTR) { byte = -1; break; } } return byte; } int recv_byte(int sock, char *buf, int len) { int rc; int byte; for (byte = 0; byte < len; byte += rc) { rc = recv(sock, buf + byte, len - byte, MSG_NOSIGNAL); if (rc == 0) break; if (rc < 0 && errno != EINTR) { byte = -1; break; } } return byte; } int eat_byte(int sock,int len) { int rc; int byte; char buf[32]; for (byte = 0; len - byte > 32; byte += rc) { rc = recv(sock, buf, 32, MSG_NOSIGNAL); if (rc == 0) break; if (rc < 0 && errno != EINTR) return -1; } if (rc != 0) byte += recv_byte(sock, buf, len - byte); return byte; }
C
#include "common.h" static apr_pool_t *test_pool; static gla_store_t *test_store; static gla_entityreg_t *test_self; /********************************** TEST 1 ************************************/ #include "src/regex.h" static int test1_init() { int ret; ret = apr_pool_create(&test_pool, NULL); if(ret != APR_SUCCESS) return ret; ret = gla_regex_init(test_pool); if(ret != GLA_SUCCESS) return ret; test_store = gla_store_new(test_pool); if(test_store == NULL) return errno; test_self = gla_entityreg_new(test_store, sizeof(int), test_pool); if(test_self == NULL) return errno; return 0; } static int test1_cleanup() { apr_pool_destroy(test_pool); return 0; } #define INSERT_ENTITY(NAME) \ do { \ ret = gla_path_parse_entity(&path, NAME, test_pool); \ CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); \ data = gla_entityreg_get(test_self, &path); \ CU_ASSERT_PTR_NOT_NULL_FATAL(data); \ } while(false) static void test1_access() { int ret; int *data; int *orgdata; gla_path_t path; gla_path_t path_rev; gla_id_t id; gla_id_t orgid; CU_ASSERT_PTR_NOT_NULL_FATAL(test_store); /* test root existence check */ ret = gla_entityreg_covered(test_self, NULL); CU_ASSERT_EQUAL(ret, GLA_SUCCESS); /* insert new entity into registry */ ret = gla_path_parse_entity(&path, "<ext>a.aa.EntityName", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); data = gla_entityreg_get(test_self, &path); CU_ASSERT_PTR_NOT_NULL(data); CU_ASSERT_EQUAL(errno, GLA_NOTFOUND); orgdata = data; /* retrieve entity path from data */ ret = gla_entityreg_path_for(test_self, &path_rev, data, test_pool); CU_ASSERT_EQUAL(ret, GLA_SUCCESS); CU_ASSERT_TRUE(gla_path_equal(&path, &path_rev)); /* retrieve same entity using try-method */ data = gla_entityreg_try(test_self, &path); CU_ASSERT_PTR_NOT_NULL(data); CU_ASSERT_PTR_EQUAL(data, orgdata); /* retrieve same entitiy using get-method */ data = gla_entityreg_get(test_self, &path); CU_ASSERT_EQUAL(errno, GLA_SUCCESS); CU_ASSERT_PTR_NOT_NULL(data); CU_ASSERT_PTR_EQUAL(data, orgdata); /* insert another new entity into registry */ ret = gla_path_parse_entity(&path, "<ext>a.ab.EntityName", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); data = gla_entityreg_get(test_self, &path); CU_ASSERT_PTR_NOT_NULL(data); CU_ASSERT_PTR_NOT_EQUAL(data, orgdata); /* insert new entity into root package */ ret = gla_path_parse_entity(&path, "<ext>EntityName", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); data = gla_entityreg_get(test_self, &path); CU_ASSERT_PTR_NOT_NULL(data); CU_ASSERT_PTR_NOT_EQUAL(data, orgdata); /* retrieve entity path from data */ ret = gla_entityreg_path_for(test_self, &path_rev, data, test_pool); CU_ASSERT_EQUAL(ret, GLA_SUCCESS); CU_ASSERT_TRUE(gla_path_equal(&path, &path_rev)); /* add some other packages to store which are not used in registry */ ret = gla_path_parse_package(&path, "b", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); id = gla_store_path_get(test_store, &path); CU_ASSERT_NOT_EQUAL_FATAL(id, GLA_ID_INVALID); ret = gla_path_parse_package(&path, "a.aa.aaa", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); id = gla_store_path_get(test_store, &path); CU_ASSERT_NOT_EQUAL_FATAL(id, GLA_ID_INVALID); /* get root package first child */ id = gla_entityreg_covered_children(test_self, GLA_ID_ROOT); ret = gla_path_parse_package(&path, "a", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); orgid = gla_store_path_try(test_store, &path); CU_ASSERT_NOT_EQUAL(orgid, GLA_ID_INVALID); CU_ASSERT_EQUAL(orgid, id); /* get next sibling */ errno = GLA_TEST; id = gla_entityreg_covered_next(test_self, orgid); CU_ASSERT_EQUAL(id, GLA_ID_INVALID); CU_ASSERT_EQUAL(errno, GLA_END); /* get leaf package first child */ ret = gla_path_parse_package(&path, "a.aa", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); id = gla_store_path_try(test_store, &path); CU_ASSERT_NOT_EQUAL_FATAL(id, GLA_ID_INVALID); errno = GLA_TEST; id = gla_entityreg_covered_children(test_self, id); CU_ASSERT_EQUAL(id, GLA_ID_INVALID); CU_ASSERT_EQUAL(errno, GLA_END); /* test root existence check again */ ret = gla_entityreg_covered(test_self, NULL); CU_ASSERT_EQUAL(ret, GLA_SUCCESS); /* test positive existence check */ ret = gla_path_parse_package(&path, "a", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); ret = gla_entityreg_covered(test_self, &path); CU_ASSERT_EQUAL(ret, GLA_SUCCESS); ret = gla_path_parse_package(&path, "a.aa", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); ret = gla_entityreg_covered(test_self, &path); CU_ASSERT_EQUAL(ret, GLA_SUCCESS); /* test negative existence check, contained within store */ ret = gla_path_parse_package(&path, "b", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); ret = gla_entityreg_covered(test_self, &path); CU_ASSERT_EQUAL(ret, GLA_NOTFOUND); /* test negative existence check, not contained within store */ ret = gla_path_parse_package(&path, "c", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); ret = gla_entityreg_covered(test_self, &path); CU_ASSERT_EQUAL(ret, GLA_NOTFOUND); /* insert several other entities (for later usage) */ INSERT_ENTITY("<exta>z.za.EntityA"); INSERT_ENTITY("<extc>z.za.EntityC"); INSERT_ENTITY("<extb>z.za.EntityB"); INSERT_ENTITY("<extd>z.za.EntityD"); INSERT_ENTITY("<exte>z.zb.EntityE"); } #define EXPECT_ENTRY(NAME, EXTENSION) \ do {\ CU_ASSERT_PTR_NOT_NULL_FATAL(it.name); \ CU_ASSERT_PTR_NOT_NULL_FATAL(it.extension); \ CU_ASSERT_EQUAL(it.package, package); \ CU_ASSERT_EQUAL(strcmp(it.name, NAME), 0); \ CU_ASSERT_EQUAL(strcmp(it.extension, EXTENSION), 0); \ } while(false) static void test1_forward_iteration() { int ret; gla_path_t path; gla_id_t package; gla_entityreg_it_t it; /* package: z.za */ ret = gla_path_parse_package(&path, "z.za", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); package = gla_store_path_try(test_store, &path); CU_ASSERT_NOT_EQUAL_FATAL(package, GLA_ID_INVALID); /* forward iteration */ ret = gla_entityreg_find_first(test_self, package, &it); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); EXPECT_ENTRY("EntityA", "exta"); ret = gla_entityreg_iterate_next(&it); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); EXPECT_ENTRY("EntityB", "extb"); ret = gla_entityreg_iterate_next(&it); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); EXPECT_ENTRY("EntityC", "extc"); ret = gla_entityreg_iterate_next(&it); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); EXPECT_ENTRY("EntityD", "extd"); ret = gla_entityreg_iterate_next(&it); CU_ASSERT_EQUAL(ret, GLA_END); EXPECT_ENTRY("EntityD", "extd"); } static void test1_reverse_iteration() { int ret; gla_path_t path; gla_id_t package; gla_entityreg_it_t it; /* set current package: z.za */ ret = gla_path_parse_package(&path, "z.za", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); package = gla_store_path_try(test_store, &path); CU_ASSERT_NOT_EQUAL_FATAL(package, GLA_ID_INVALID); /* forward iteration */ ret = gla_entityreg_find_last(test_self, package, &it); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); EXPECT_ENTRY("EntityD", "extd"); ret = gla_entityreg_iterate_prev(&it); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); EXPECT_ENTRY("EntityC", "extc"); ret = gla_entityreg_iterate_prev(&it); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); EXPECT_ENTRY("EntityB", "extb"); ret = gla_entityreg_iterate_prev(&it); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); EXPECT_ENTRY("EntityA", "exta"); ret = gla_entityreg_iterate_prev(&it); CU_ASSERT_EQUAL(ret, GLA_END); EXPECT_ENTRY("EntityA", "exta"); } void test1_empty_iteration() { int ret; gla_id_t package; gla_entityreg_it_t it; gla_path_t path; /* set current package: a */ ret = gla_path_parse_package(&path, "a", test_pool); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); package = gla_store_path_try(test_store, &path); CU_ASSERT_NOT_EQUAL_FATAL(package, GLA_ID_INVALID); /* test for NOTFOUND result */ ret = gla_entityreg_find_first(test_self, package, &it); CU_ASSERT_EQUAL(ret, GLA_NOTFOUND); ret = gla_entityreg_find_last(test_self, package, &it); CU_ASSERT_EQUAL(ret, GLA_NOTFOUND); /* test invalid package for NOTFOUND result */ ret = gla_entityreg_find_first(test_self, GLA_ID_INVALID, &it); CU_ASSERT_EQUAL(ret, GLA_NOTFOUND); ret = gla_entityreg_find_last(test_self, GLA_ID_INVALID, &it); CU_ASSERT_EQUAL(ret, GLA_NOTFOUND); } void test1_root_iteration() { int ret; gla_entityreg_it_t it; gla_id_t package = GLA_ID_ROOT; ret = gla_entityreg_find_first(test_self, GLA_ID_ROOT, &it); CU_ASSERT_EQUAL_FATAL(ret, GLA_SUCCESS); EXPECT_ENTRY("EntityName", "ext"); ret = gla_entityreg_iterate_next(&it); CU_ASSERT_EQUAL(ret, GLA_END); } /******************************** INITIALIZE **********************************/ int glatest_entityreg() { CU_pSuite suite; CU_pTest test; BEGIN_SUITE("Entity Registry API", test1_init, test1_cleanup); ADD_TEST("access", test1_access); ADD_TEST("forward iteration", test1_forward_iteration); ADD_TEST("reverse iteration", test1_reverse_iteration); ADD_TEST("empty iteration", test1_empty_iteration); ADD_TEST("root iteration", test1_root_iteration); END_SUITE; return GLA_SUCCESS; }
C
/* * lock_file.c * 对文件上锁,用于测试server中接受client发送的文件时,重改名的问题 * 若文件上锁,则server接受到文件并保存为临时文件(rsa_key.conf.tm),并等待文件解锁;当文件解锁后,将临时文件重命名为所需的文件名(rsa_key.conf) * Created on: 2014-8-29 * Author: wzb */ #include <sys/file.h> #include <stdio.h> #include <stdlib.h> int main() { FILE *f = fopen("rsa_key.conf", "r"); if(NULL == f) { fprintf(stderr, "filename error\n"); return 0; } if(0!=flock(fileno(f), LOCK_EX)) // if lock then wait; you can use LOCK_EX | LOCK_NB to break if file lock { printf("lock failed\n"); return 0; } printf("input some character\n"); getchar(); flock(fileno(f), LOCK_UN); fclose(f); printf("close--\n"); return 0; }