language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/** * \file file.c * \author Rangarajan R * \date March, 2016 * \brief * Predict the output. * * \details * Detailed description of file. * * \note * The notes for this file. * * \copyright * */ #include <stdio.h> int main() { int var; /*Suppose address of var is 2000 */ void *ptr = &var; *ptr = 5; printf("var=%d and *ptr=%d",var,*ptr); return 0; }
C
//Program : Question 22 (Program to reverse the string) //Author : Roshan Aji Cherian #include <stdio.h> #include <string.h> #define MAX 1001 int main() { char str[MAX]; printf("Enter the string to be reversed : "); scanf("%[^\n]%*c", str); //Syntax to input the string having spaces int n = strlen(str); char newString[MAX]; int i = 0, j = 0; for (i = n - 1, j = 0; i >= 0 && j < n; i--, j++) { newString[j] = str[i]; } newString[j] = '\0'; printf("The reversed string is : %s\n", newString); return 0; }
C
#include <stdio.h> #include <stdlib.h> #define STATUS "student" #define SREDNIA_OCEN 3.4 void data(); int main() { data(); return 0; } void data(){ int pe, k, d, mie; char i[16], n[16], pl[8], mia[16], u[32]; printf("Podaj imie: "); scanf("%s", &i); printf("Podaj nazwisko: "); scanf("%s", &n); printf("Podaj pesel: "); scanf("%d", &pe); printf("Podaj plec: "); scanf("%s", &pl); printf("Podaj kod: "); scanf("%d", &k); printf("Podaj miasto: "); scanf("%s", &mia); printf("Podaj ulice: "); scanf("%s", &u); printf("Podaj nr domu: "); scanf("%d", &d); printf("Podaj nr mieszkania: "); scanf("%d", &mie); printf("%s - %s - %d - %s\n%d - %s - %s - %d - %d\n%s", i, n, pe, pl, k, mia, u, d, mie, STATUS); }
C
#include <stdio.h> #include "cll.h" #include "os.h" /* File name : linkMain.c Day : Data Structures Purpose : Creating a linked list main function */ int main() { NODE *head = NULL; NODEELEMENT data; char choice; int position,ch; while(1) { clearScreen(); puts("\t\t\t\tLinked List Operations\n"); puts("\t1. Add/append an element to the list"); puts("\t2. Display the elements"); puts("\t3. Display the elements in reverse order"); puts("\t4. Insert an element in a given position"); puts("\t5. Search for a particular element"); puts("\t6. Delete an element"); puts("\t7. Delete an element from a particular position"); puts("\t8. Sort the elements of the list"); puts("\t9. Quit"); puts("Please enter your choice"); clearKBuffer(); scanf("%d",&ch); switch (ch) { case 1: puts("Enter the element to be added:"); scanf("%d",&data); addNode(&head,data); break; case 2: if(head == NULL) { puts("No element to display"); } else { puts("Contents of the linked list"); displayForward(head); } break; case 3: if(head == NULL) { puts("No element to display"); } else { puts("Contents of the linked list in reverse order:"); displayReverse(head); } break; case 4: puts("Enter the position to which the element is to be inserted"); scanf("%d",&position); puts("Enter the element to be inserted"); scanf("%d",&data); insertElement(&head,position,data); break; case 5: puts("Enter the element to be searched"); scanf("%d",&data); searchElement(head,data); break; case 6: puts("Enter the element to be deleted"); scanf("%d",&data); deleteElement(&head,data); break; case 7: puts("Enter the position at which the element is to be deleted"); scanf("%d",&position); deletePosition(&head,position); break; case 8: sortElement(head); break; case 9: puts("Quitting"); exit (0); break; default: puts("Invalid Option"); } puts("Do you want to continue(y/n)?"); clearKBuffer(); scanf("%c",&choice); if(choice == 'N' || choice == 'n') { break; } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #define DRIVER_AMOUNT 20 #define CAR_AMOUNT 5 pthread_mutex_t cars[CAR_AMOUNT]; pthread_t drivers[DRIVER_AMOUNT]; void* test_automobiles(void* args) { int id = *((int*) args); free(args); for(int i = 0; i < CAR_AMOUNT; i++) { // one driver tests multiple cars if(pthread_mutex_trylock(&cars[i]) != 0) { // if the mutex is busy. . . printf("Buyer %d takes car %d.\n", id, i + 1); printf("Buyer %d returns car %d.\n", id, i + 1); pthread_mutex_unlock(&cars[i]); // free the mutex for later. . . } } return NULL; } int main() { int i = 0; for(i; i < CAR_AMOUNT; i++) { pthread_mutex_init(&cars[i], NULL); } for(i = 0; i < DRIVER_AMOUNT; i++) { int* tmp = malloc(sizeof(int)); *tmp = i + 1; pthread_create(&drivers[i], NULL, test_automobiles, tmp); } for(i = 0; i < DRIVER_AMOUNT; i++) { pthread_join(drivers[i], NULL); } for(i = 0; i < CAR_AMOUNT; i++) { pthread_mutex_destroy(&cars[i]); } }
C
#include "error_functions.h" static void error_dealer(int errnoflag, int level, const char *format, va_list ap){ const int MAXSIZE = 256; int errno_save,n; char buf[MAXSIZE +1]; errno_save = errno; int daemon_proc = 1; #ifdef HAVE_VSNPRINTF vsnprintf(buf, MAXSIZE, format, ap); #else vsprintf(buf, format, ap); #endif if(daemon_proc){ n = strlen(buf); if (errnoflag) snprintf(buf + n, MAXSIZE - n, ": %s\n", strerror(errno_save)); syslog(level, "%s" ,buf); }else{ fflush(stdout); //if(level == LOG_LEVEL_ERROR) //log_info("%s", buf); //else //log_error("%s", buf); fflush(stderr); } return ; } void fatal_user_exit(const char *format, ...){ va_list ap; va_start(ap, format); error_dealer(1, LOG_LEVEL_ALERT, format, ap); va_end(ap); exit(1); } void fatal_sys_exit(const char *format, ...){ va_list ap; va_start(ap, format); error_dealer(0, LOG_LEVEL_ALERT, format, ap); va_end(ap); exit(1); }
C
#include <stdio.h> #define MAXLINE 1000 /* maximum input line length */ /* using global variables in this implementation */ int max; char line[MAXLINE]; char longest[MAXLINE]; int get_line(void); void copy(void); /* print longest input line; specialized version */ main() { int len; extern int max; extern char longest[]; max = 0; while((len = get_line()) > 0) /* if multiple lines have the same length, the first one parsed will be 'longest' */ if (len > max) { max = len; copy(); } if (max > 0) printf("%s\n", longest); return 0; } int get_line(void) { /* we keep writing the same array and rely on '\0' to cut off lines shorter than previous line */ extern char line[]; int c, i; for(i = 0; i < MAXLINE - 1 && (c = getchar()) != EOF && c != '\n'; ++i) line[i] = c; if (c == '\n') line[i++] = c; line[i] = '\0'; return i; } void copy(void) { int i; extern char line[], longest[]; i = 0; while((longest[i] = line[i]) != '\0') ++i; } // #include <stdio.h> // #define MAXLINE 1000 /* maximum input line length */ // int get_line(char line[], int maxline); // void copy(char to[], char from[]); // main() // { // int len; // int max; // char line[MAXLINE]; /* current input line */ // char longest[MAXLINE]; /* longest line saved here */ // max = 0; // while ((len = get_line(line, MAXLINE)) > 0) // if (len > max) { // max = len; // copy(longest, line); // } // if (max > 0) // printf("%s", longest); // return 0; // } // /* get_line: read a line into s, return length */ // int get_line(char s[], int lim) // { // int c, i; // for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i) // s[i] = c; // if(c == '\n') { // s[i] = c; // ++i; // } // s[i] = '\0'; // return i; // } // /* copy: copy 'from' to 'to'; assume to is big enough */ // void copy(char to[], char from[]) // { // int i; // i = 0; // while ((to[i] = from[i]) != '\0') /* this is cool, I didn't assignment returned the assigned value, doesn't happen in Python */ // ++i; // }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> /* Given a n*n matrix where numbers all numbers are distinct and are distributed from range 1 to n2, find the maximum length path (starting from any cell) such that all cells along the path are increasing order with a difference of 1. We can move in 4 directions from a given cell (i, j), i.e., we can move to (i+1, j) or (i, j+1) or (i-1, j) or (i, j-1) with the condition that the adjacen Example: Output: 4 The longest path is 6-7-8-9. */ #define ROW 4 #define COL 4 #if 0 int mat[ROW][COL] = { {1, 2, 9}, {4, 0, 8}, {5, 6, 7} }; #endif int mat[ROW][COL] = { {9, 6, 5, 2}, {8, 7, 6, 5}, {7, 3, 1, 6}, {1, 1, 1, 7} }; int dp[ROW][COL] = {0}; int lpath (int i, int j, int cost) { int none = 0; if (i< 0 || i >= ROW) return 0; if (j<0 || j >= COL) return 0; if (dp[i][j]) return dp[i][j]; if ((i+1 < ROW) && abs(mat[i+1][j] - mat[i][j]) == 1) { dp[i][j] = cost; lpath(i+1, j, cost+1); none = 1; } #if 0 if ((i-1 >= 0) && abs(mat[i-1][j] - mat[i][j]) == 1) { dp[i][j] = cost; lpath(i-1, j, cost+1); } if ((j-1 >= 0 ) && abs(mat[i][j-1] - mat[i][j]) == 1) { dp[i][j] = cost; lpath(i, j-1, cost+1); } #endif if ((j+1 < COL) && abs(mat[i][j+1] - mat[i][j]) == 1) { dp[i][j] = cost; lpath(i, j+1, cost+1); none = 1; } if (!none) dp[i][j] = cost; return dp[i][j]; } int main (int argc, char *argv[]) { int i, j, rv, high = -1; for (i = 0; i < ROW; i++) { for (j = 0; j < COL; j++) { rv = lpath(i, j, 1); if (high < rv) { high = rv; } } } for (i = 0; i < ROW; i++) { for (j = 0; j < COL; j++) { printf("dp[%d][%d] = %d ", i, j, dp[i][j]); } printf("\n"); } printf("Higest %d\n", high); }
C
#include <stdio.h> #include <stdlib.h> #include <stdalign.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <string.h> #include <ctype.h> #include <inttypes.h> #include "utils.h" #ifdef DEBUG #define dbg_printf(...) (fprintf(stderr, __FILE__ ":%d:%s:", __LINE__, __func__), (fprintf(stderr, __VA_ARGS__))) #else #define dbg_printf(...) #endif //--------------------------------------------------------- //string //--------------------------------------------------------- #define STRSIZE 256 typedef struct { int length; int size; char *str; } str_with_len, * str_with_len_p; str_with_len_p init_str_with_len(str_with_len_p str) { if (str == NULL) { dbg_printf("failed to %s\n", __func__); exit(EXIT_FAILURE); } char *tmp = malloc(sizeof(char[STRSIZE])); if (tmp == NULL) { dbg_printf("failed to malloc\n"); exit(EXIT_FAILURE); } str->str = tmp; str->length = 0; str->size = STRSIZE; memset(str->str, 0, sizeof(str->str[0]) * STRSIZE); return str; } str_with_len_p fini_str_with_len(str_with_len_p str) { if (str == NULL) { dbg_printf("failed to %s\n", __func__); exit(EXIT_FAILURE); } free(str->str); str->str = NULL; str->length = 0; str->size = 0; return str; } str_with_len_p str_with_len_ncat(str_with_len_p dest, char *src, size_t len) { if (len > (dest->size - dest->length)) { char *tmp = realloc(dest->str, dest->size + STRSIZE); if (tmp == NULL) { dbg_printf("realloc failed\n"); exit(EXIT_FAILURE); } dest->str = tmp; dest->size += STRSIZE; dbg_printf("realloced\n"); } strncat(dest->str + dest->length, src, len); dest->length += len; return dest; } str_with_len_p read_from(FILE *fp, str_with_len_p dest) { if(fp == NULL) { fini_str_with_len(dest); return dest; } if(dest->str == NULL) { init_str_with_len(dest); } char tmp[STRSIZE] = ""; char *ret = fgets(tmp, sizeof(tmp), fp); if (ret == NULL) { //dbg_printf("error occured or reach to EOF\n"); return NULL; } int len = strlen(tmp); str_with_len_ncat(dest, tmp, len); return dest; } //--------------------------------------------------------- //cell //--------------------------------------------------------- /* terms: car_p car_p cdr_p term: 'S'|'K'|'I'|atom '(' cdr_p ')' */ typedef enum { // COMB, PAIR, ATOM, UINT, BROKEN_HEART = 0x7, } cell_type; //typedef struct struct_cell * cell_p; typedef struct struct_cell { struct struct_cell *car_p; struct struct_cell *cdr_p; } cell_t, * cell_p; #define car(c) ((c)->car_p) #define cdr(c) ((c)->cdr_p) static inline cell_p mask_cell(cell_p const c, cell_type const mask) { return (cell_p)((uintptr_t)(c) | mask); } static inline cell_p unmask_cell(cell_p const c, cell_type const mask) { return (cell_p)((uintptr_t)(c) & ~mask); } static inline cell_p unmask_cell_all(cell_p const c) { return (cell_p)((uintptr_t)(c) & ~BROKEN_HEART); } static inline int is_cell_type(cell_p const c, cell_type const t) { return (uintptr_t)(c) & t; } static inline int is_pair(cell_p const c) { return ((uintptr_t)(c) & 0x7) == 0; } static inline int is_atom(cell_p const c) { return is_cell_type(c, ATOM); } static inline char *to_atom(cell_p const c) { static char atom[4]; uint32_t tmp; tmp = (((uint32_t)((uintptr_t)c)) >> 3) | (0x7ul * ((uint32_t)((uintptr_t)c) >> 31)) << 29; atom[0] = (char)((tmp >> 0) & 0xff); atom[1] = (char)((tmp >> 8) & 0xff); atom[2] = (char)((tmp >> 16) & 0xff); atom[3] = (char)((tmp >> 24) & 0xff); return atom; } static inline int is_uint(cell_p const c) { return is_cell_type(c, UINT); } static inline uint32_t to_uint(cell_p const c) { return ((uint32_t)((uintptr_t)c)) >> 3; } static inline int is_nil(cell_p const c) { return is_pair(c) && !car(unmask_cell_all(c)); } cell_t *cell_heap = NULL; #define ast_root (car(cell_heap)) #define MEMO_SIZE 0x100000 size_t heap_size = MEMO_SIZE, next_heap_size = (MEMO_SIZE * 3) / 2, heap_used = 0; cell_t *alloc_heap(size_t const size) { cell_t *tmp = (cell_t *)aligned_alloc(alignof(8), sizeof(cell_t) * size); if (tmp == NULL) { dbg_printf("failed to malloc\n"); exit(EXIT_FAILURE); } dbg_printf("alloced pointer = %p, heap_size = %u\n", (void*)tmp, size); memset(tmp, 0, sizeof(cell_t) * size); return tmp; } cell_t *init_cell_heap(void) { return cell_heap = alloc_heap(MEMO_SIZE); } cell_p gc_run(cell_t *new_heap) { new_heap[0] = *cell_heap; *cell_heap = (cell_t){(cell_p)BROKEN_HEART, new_heap}; cell_p free_cell = new_heap, scan = new_heap; free_cell++; for(; free_cell != scan;scan++) { if (car(scan)) { if (is_pair(car(scan)) && (uintptr_t)car(car(scan)) != BROKEN_HEART) { *free_cell = *car(scan); car(car(scan)) = (cell_p)BROKEN_HEART; cdr(car(scan)) = free_cell; free_cell++; } car(scan) = is_pair(car(scan))?cdr(car(scan)):car(scan); } if (cdr(scan)) { if (is_pair(cdr(scan)) && (uintptr_t)car(cdr(scan)) != BROKEN_HEART) { *free_cell = *cdr(scan); car(cdr(scan)) = (cell_p)BROKEN_HEART; cdr(cdr(scan)) = free_cell; free_cell++; } cdr(scan) = is_pair(cdr(scan))?cdr(cdr(scan)):cdr(scan); } } free(cell_heap); cell_heap = new_heap; dbg_printf("%d,%d\n", heap_used, free_cell - cell_heap); heap_size = next_heap_size; next_heap_size = (heap_size * 3) / 2; return cell_heap; } cell_p alloc_cell(size_t const n) { if (!cell_heap) { init_cell_heap(); } if (n && heap_used >= heap_size - 1) { gc_run(alloc_heap(next_heap_size)); } if (n == 0) { for (size_t i = 0; i <= heap_used; i++) { dbg_printf(" % 3d(%p)={%p, %p};\n", i, (void*)&cell_heap[i],(void*)cell_heap[i].car_p, (void*)cell_heap[i].cdr_p); } free(cell_heap); return NULL; } heap_used += n; cell_heap[heap_used] = (cell_t){NULL, NULL}; return cell_heap + heap_used; //return n?alloc_heap(n):0; } cell_p make_atom(char const *c) { /* for (cell_p list = obarray; list; list = unmask_cell_all(list)->cdr_p) { if (!is_atom(list)) { continue; } if (!strncmp(to_atom(list), c, sizeof(list->car_atom))) { return list; } } */ //cell_p atm = alloc_cell(1); /* atm->cdr_p = obarray?obarray:NULL; obarray = mask_cell(atm, ATOM); */ //strncpy(atm->car_atom, c, sizeof(atm->car_atom)); uint32_t atm = (((uint32_t)c[0] << 0) | ((uint32_t)c[1] << 8) | ((uint32_t)c[2] << 16) | ((c[3]) << 24)) << 3; return mask_cell((cell_p)((uintptr_t)atm), ATOM); } static inline cell_p make_uint(uint32_t const ui) { /* for (cell_p list = obarray; list; list = unmask_cell_all(list)->cdr_p) { if (!is_uint(list)) { continue; } if (to_uint(list) == ui) { return list; } } */ //cell_p uint = alloc_cell(1); /* uint->cdr_p = obarray?obarray:NULL; obarray = mask_cell(uint, UINT); */ //uint->car_uint = ui; return mask_cell((cell_p)(uintptr_t)(ui << 3), UINT); } //--------------------------------------------------------- //parser //--------------------------------------------------------- typedef struct { cell_type type; union { char atom[4]; uint32_t uint; }; } token; char const *brackets[][2] = { { "(", ")" }, { "[", "]" }, { "{", "}" }, }; bool is_lbracket(token tok) { for (size_t i = 0; i < sizeof(brackets) / sizeof(brackets[0]); i++) { if (!strncmp(tok.atom, brackets[i][0], brackets[i][0][0]?strlen(brackets[i][0]):1)) return true; } return false; } char const *matchingbracket(token tok) { for (size_t i = 0; i < sizeof(brackets) / sizeof(brackets[0]); i++) { if (!strncmp(tok.atom, brackets[i][0], brackets[i][0][0]?strlen(brackets[i][0]):1)) return brackets[i][1]; }; return "\0"; } static inline char const *next_token_index(char const *str) { do{ str = utf8_next_char(str); } while (isspace(*str)); return str; } token succ_token(char const **str, bool succ) { if (isspace(**str)) *str = next_token_index(*str); token tok = {PAIR, {""}}; size_t cbyte = utf8_skip_data[**(unsigned char**)str]; if (cbyte == 1 && isdigit(**str)) { tok.type = UINT; char *tmp; tok.uint = strtoul(*str, &tmp, 0); *str = succ?tmp:*str; } else if (cbyte == 1 && isalpha(**str)) { tok.type = ATOM; tok.atom[0] = **str; *str = succ?(*str)+1:*str; } else if (cbyte > 1) { tok.type = ATOM; strncpy(tok.atom, *str, **str?cbyte:1); *str = succ?utf8_next_char(*str):*str; } else { strncpy(tok.atom, *str, **str?cbyte:1); *str = succ?utf8_next_char(*str):*str; } return tok; } token get_token(char const **str) { return succ_token(str, true); } token next_token(char const **str) { return succ_token(str, false); } cell_p parse_ski(cell_p root, char const **str, char const closing_char[4]) { if (!*str) return root; cell_p top = root, fst = NULL, scd = NULL; token tok = {PAIR, {""}}; for (tok = get_token(str); tok.type != PAIR || strncmp(tok.atom, closing_char, sizeof(closing_char) / sizeof(closing_char[0])); tok = get_token(str)) { if (tok.type == UINT) { car(top) = make_uint(tok.uint); //fst = make_uint(tok.uint); } else if (tok.type == ATOM) { car(top) = make_atom(tok.atom); //fst = make_atom(tok.atom); } else if (is_lbracket(tok)) { cell_p tmp = parse_ski(alloc_cell(1), str, matchingbracket(tok)); car(top) = tmp; //fst = parse_ski(alloc_cell(1), str, matchingbracket(tok)); } else { dbg_printf("parse error:%s (0x%"PRIx32")\n", tok.atom, tok.uint); exit(EXIT_FAILURE); } if (next_token(str).type == PAIR && !strncmp((next_token(str)).atom, closing_char, sizeof(closing_char) / sizeof(closing_char[0]))) { //car(top) = fst; cdr(top) = NULL; //scd = NULL; continue; } cell_p tmp = alloc_cell(1); //scd = alloc_cell(1); cdr(top) = tmp; //top = cons(fst, top); //top = cdr(top); //car(top) = fst; //cdr(top) = scd; top = cdr(top); } return root; } cell_p make_ski_ast(cell_p root, char const **str, char const closing_char[4]) { if (!*str) return root; token tok = {PAIR, {""}}; tok = get_token(str); if (tok.type == PAIR && !strncmp(tok.atom, closing_char, sizeof(closing_char) / sizeof(closing_char[0]))) { return root; } if (tok.type == UINT) { car(root) = make_uint(tok.uint); } else if (tok.type == ATOM) { car(root) = make_atom(tok.atom); } else if (is_lbracket(tok)) { car(root) = make_ski_ast(alloc_cell(1), str, matchingbracket(tok)); } else { dbg_printf("parse error:%s (0x%"PRIx32")\n", tok.atom, tok.uint); exit(EXIT_FAILURE); } if (next_token(str).type == PAIR && !strncmp((next_token(str)).atom, closing_char, sizeof(closing_char) / sizeof(closing_char[0]))) { cdr(root) = NULL; get_token(str); return root; } cdr(root) = make_ski_ast(alloc_cell(1), str, closing_char); return root; } cell_p *simplify_ast(cell_p *root) { if (!car(*root) || is_nil(car(*root))) return NULL; /*if (is_nil(cdr(*root))) { *root = car(*root); return root; }*/ cell_p top = *root; if (!is_nil(car(top)) && is_pair(car(top))) { for (top = car(top); cdr(top); top = cdr(top)); cdr(top) = cdr(*root); *root = car(*root); } else { for (; cdr(top); top = cdr(top)) { if (is_pair(car(cdr(top)))) { if (!cdr(car(cdr(top)))) { car(cdr(top)) = car(car(cdr(top))); } else { simplify_ast(&car(cdr(top))); } } } return root; } return simplify_ast(root); } int show_ast(cell_p root, int count) { if(!root || car(root) == NULL) { return 0; } if (is_atom(car(root))) { printf("%1.4s", to_atom(car(root))); } else if (is_uint(car(root))) { printf("%"PRIu32" ", to_uint(car(root))); } else { putchar("([{"[count%3]); show_ast(car(root), count+1); putchar(")]}"[count%3]); } if (cdr(root) != NULL) { show_ast(cdr(root), count); } return !000; } bool is_exist(cell_p root, size_t rec) { for(root = cdr(root);rec;rec--) { if(!root || !car(root)) { return false; } root = cdr(root); } return true; } cell_p take(cell_p root, size_t n) { for (;n;n--) root = cdr(root); return root; } cell_p copy_ast(cell_p from){ cell_p new_ast = alloc_cell(1); for (cell_p to = new_ast; from; to = cdr(to), from = cdr(from)) { car(to) = is_pair(car(from))?copy_ast(car(from)):car(from); cdr(to) = cdr(from)?alloc_cell(1):0; } return new_ast; } cell_p *reduce_ast(cell_p *root) { if (!root || !*root) return NULL; if (is_pair(*root)) simplify_ast(root); char atom[4] = ""; strncpy(atom, to_atom(car(*root)), sizeof(atom) / sizeof(atom[0])); switch (atom[0]) { case 's' : case 'S' : if (is_exist(*root, 3)) { cell_p x = take(*root, 1); cell_p y = take(*root, 2); cell_p z1 = take(*root, 3); cell_p z2 = take(*root, 3); if (is_pair(car(z1))) { //z copy suru z2 = copy_ast(z1); } cell_p w = take(*root, 4); *root = x; cdr(x) = alloc_cell(1); car(cdr(x)) = car(z1); cdr(cdr(x)) = alloc_cell(1); car(cdr(cdr(x))) = alloc_cell(1); car(car(cdr(cdr(x)))) = car(y); cdr(car(cdr(cdr(x)))) = alloc_cell(1); car(cdr(car(cdr(cdr(x))))) = car(z2); cdr(cdr(car(cdr(cdr(x))))) = NULL; cdr(cdr(cdr(x))) = w; return root; } break; case 'k' : case 'K' : if (is_exist(*root, 2)) { cell_p y = take(*root, 2); *root = cdr(*root); cdr(*root) = cdr(y); return root; } break; case 'i' : case 'I' : if (is_exist(*root, 1)) { *root = cdr(*root); return root; } break; default : //printf("atom = %s\n", atom); //return cdr(*root) && is_pair(car(cdr(*root)))?reduce_ast(&car(cdr(*root))):NULL; break; } cell_p *ret = NULL; for(cell_p r = cdr(*root); r; r = cdr(r)) { if (is_pair(car(r))) { ret = reduce_ast(&car(r)); //break; } else { } } return ret; } int put_church(cell_p root, int n) { return is_pair(car(cdr(root))) && car(root)==car(car(cdr(root)))?put_church(car(cdr(root)), n + 1):putchar(n + 1); } int main (void) { str_with_len str = {0, 0, NULL}; for(;read_from(stdin, &str);); //printf("%d:%d\n%s",str.length,str.size,str.str); //cell_t root = {NULL, NULL}; init_cell_heap(); //parse_ski(ast_root = alloc_cell(1), &(char const *){str.str}, "\0"); make_ski_ast(ast_root = alloc_cell(1), &(char const *){str.str}, "\0"); simplify_ast(&ast_root); //show_ast(ast_root, 0); //alloc_cell(0); //return 0; for (; reduce_ast(&ast_root); ) { //show_ast(ast_root, 0);puts(""); simplify_ast(&ast_root); //show_ast(ast_root, 0);puts(""); } reduce_ast(&ast_root); show_ast(ast_root, 0);puts(""); //put_church(ast_root, 0); alloc_cell(0); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include"stack.h" void visit(void *value) { printf("%4d", *(int *)value); } int main() { stack S=NULL; void *e; int v_1 = 1; int v_2 = 2; int v_3 = 3; int v_4 = 4; int v_5 = 5; int v_6 = 6; S=InitStack(); S=Push(S, (void *)&v_1); S=Push(S, (void *)&v_2); S=Push(S, (void *)&v_3); S=Push(S, (void *)&v_4); S=Push(S, (void *)&v_5); S=Push(S, (void *)&v_6); Print(S, visit); e=GetTop(S); printf("\nthe top num of the stack is %d\n",*(int *)e); e = Pop(S); printf("\nthe Pop num is %d\n", *(int *)e); e=GetTop(S); printf("\nthe top num of the stack is %d\n",*(int *)e); Stack_destroy(&S, NULL); return 0; }
C
/********************************************************** * File : q2.c * Author : Jan Claasen <janclaasen@gmail.com> * Date : 20.03.2018 * Last Modified Date: 20.03.2018 * Last Modified By : Jan Claasen <janclaasen@gmail.com> **********************************************************/ #include <stdio.h> int main(void) { int i = -100, j = 200; if(i > 0 && j < 0) i++; else if(i < 0 && j < 0) i--; else if(i < 0 && j > 0) j--; else j--; printf("%d",i + j); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <time.h> #include "kargergraph.h" unsigned int get_tick_count() { struct timespec ts; clock_gettime( CLOCK_REALTIME, &ts); unsigned int ticks = ts.tv_nsec / 1000000; ticks += ts.tv_sec * 1000; return ticks; } graph_t* parse_graph() { char * line = NULL; size_t len = 0; ssize_t read; printf("creating graph\n"); graph_t* graph = graph_init(); while ((read = getline(&line, &len, stdin)) != -1) { char* vertex = strtok(line, " \t\r"); int src = atoi(vertex); vertex = strtok(NULL, " \t\r"); while (vertex != NULL) { int dest = atoi(vertex); if (dest == 0) { break; } add_directed_edge(graph, src, dest); vertex = strtok(NULL, " \t\r"); if (vertex == NULL) { break; } } } free(line); return graph; } void remove_self_loops(graph_t* graph) { edge_t* edge; int i; for (i = 0; i < graph->edges_size; i++) { edge = graph->edges[i]; if (edge->src == edge->dest) { edge->src = NULL; edge->dest = NULL; free(edge); } } } void contract(graph_t* graph, int edge_index) { edge_t* edge = graph->edges[edge_index]; vertex_t* src = edge->src; vertex_t* dest = edge->dest; int i = 0; while (i < dest->in_count) { edge_t* in_edge = dest->in_edges[i]; if (in_edge->src == src) { remove_directed_edge(graph, in_edge); continue; } in_edge->dest = src; src->in_count = add_edge_to_vertex_list(&src->in_edges, in_edge, src->in_count, &src->in_size); i++; } i = 0; while (i < dest->out_count) { edge_t* out_edge = dest->out_edges[i]; if (out_edge->dest == src) { remove_directed_edge(graph, out_edge); continue; } out_edge->src = src; src->out_count = add_edge_to_vertex_list(&src->out_edges, out_edge, src->out_count, &src->out_size); i++; } // Decrement the counters. remove_vertex(graph, dest->index); return; } void karger_algorithm(graph_t* graph) { while (graph->num_vertices > 2) // put condition { int random_edge = rand() % graph->num_edges; contract(graph, random_edge); // Needs to decrement the size counter. Can only contract if there is an edge between them. } print_graph(graph); return; } int main() { graph_t* graph = parse_graph(); printf("Parse finished\n"); print_graph(graph); // Run Karger algorithm printf("running karger algo\n"); srand(get_tick_count()); karger_algorithm(graph); //graph_delete(graph); return 1; }
C
#include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <pthread.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "commandlinereader.h" #include "list.h" #define TAMMSG 1000 #define BUF 100 #define MAXARGS 7 #define BUFFER_SIZE 100 #define STATS "stats\n" #define EXIT_COMMAND "exit\n" #define PERMISSOES 0777 char buffer[BUFFER_SIZE], *args[MAXARGS],buffer_out[BUFFER_SIZE]; int f_write , f_read; void writePipe(){ char msg[BUFFER_SIZE]; sprintf(msg,"%d ",getpid()); strcat(msg,buffer); if(write(f_write,msg,strlen(msg)) < 0){ perror("Erro writing in pipe"); exit(EXIT_FAILURE); } } int main (int argc, char** argv) { char pipeName[BUFFER_SIZE]; sprintf(buffer,"/start/\n"); while((f_write = open(argv[1], O_WRONLY)) < 0){ continue; } writePipe(); printf("Insert your commands:\n"); while(1){ if (fgets(buffer, BUFFER_SIZE, stdin) == NULL) { perror("Error in fgets"); exit(EXIT_FAILURE); } if(strcmp(buffer,STATS)==0){ sprintf(pipeName,"/tmp/pipe-%d",getpid()); if(mkfifo (pipeName, PERMISSOES) < 0) { perror("Error creating the pipe"); exit(EXIT_FAILURE); } writePipe(); if((f_read = open(pipeName, O_RDONLY)) < 0){ perror("Error opening the pipe"); exit(EXIT_FAILURE); } if(read(f_read,buffer_out,BUFFER_SIZE) == -1){ perror("Error opening the pipe"); exit(EXIT_FAILURE); } close(f_read); printf("%s",buffer_out); unlink(pipeName); } else{ writePipe(); if(strcmp(buffer,EXIT_COMMAND)==0){ exit(EXIT_SUCCESS); } } } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> typedef struct { int* data; int top; int size; }Stack; int initialStatus(int size){ Stack* sp = (Stack*)malloc(sizeof(Stack)); if (sp == NULL) { printf("Error, an error has occured in the memory allocation process for the stack pointer. \n"); exit(1); } sp->data = (int*)malloc(sizeof(int)); if (sp->data == NULL) { printf("Error, an error has occured in the memory allocation process for the data field of the stack pointer. \n"); exit(1); } sp->top = -1; sp->size = size; return sp; } int fullStack(Stack* sp) { if (sp->top == sp->size - 1) return 1; else return 0; } int emptyStack(Stack* sp) { if (sp->top == -1) return 1; else return 0; } void pushElement(Stack* sp, int value) { int i=0; if (fullStack(sp)) { int newStack = (int)malloc(sizeof(int) * sp->size * 2); if (newStack == NULL) printf("Error, no memory for the new stack was allocated. \n"); for (i = 0; i <= sp->top; i++) { newStack[&i] = sp->data[i]; } free(sp->data); sp->data = newStack; sp->size = sp->size * 2; } sp->data[++sp->top] = value; } int popElement(Stack* sp){ if (emptyStack) printf("The stack is empty, tere is no elemenet to pop. \n"); else return sp->data[sp->top--]; } void Calc_Machine(Stack* sp) { int i, j, sum = 0, *s; for (i = 0; i < sp->top; i++) { if (isdigit(sp->data[i])) sum = sum + sp->data[i]; if (sp->data[i] == '+') { while (emptyStack(sp) == 0) { popElement(sp); } printf("Sum of the elements is %d", sum); } if (sp->data[i] == ',') popElement(sp); if (sp->data[i] == '.') { while (emptyStack(sp) == 0) { popElement(sp); } printf("Declare the new stack size:"); scanf("%d", &s); initialStatus(*s); } } } int main() { int count, size, value; printf("The size you would like the stack to be: \n"); scanf("%d", &size); Stack* stackPointer = initialStatus(size); for (count = 0; count < size - 1; count++) { printf("Element %d: ", count); scanf("%d", &value); pushElement(stackPointer, value); } Calc_Machine(stackPointer); system("pause"); return 0; }
C
#include <stdio.h> #include <stddef.h> #include <stdlib.h> #include "fix_queue.h" typedef struct { void *buf_queue; } bus_ctx_t; void *bus_init(size_t capacity) { void *buf_queue = fix_queue_init(capacity); if (buf_queue == NULL) { return NULL; } bus_ctx_t *ctx = calloc(1, sizeof(bus_ctx_t)); ctx->buf_queue = buf_queue; return ctx; } int bus_send(void *ctx, void *buf) { bus_ctx_t *fctx = ctx; return fix_queue_push(fctx->buf_queue, buf); } void *bus_recv(void *ctx) { bus_ctx_t *fctx = ctx; return fix_queue_pop(fctx->buf_queue); } void bus_destroy(void **ctx) { if (ctx == NULL) { return; } bus_ctx_t *fctx = *ctx; fix_queue_destroy(&fctx->buf_queue); free(fctx); *ctx = NULL; }
C
#include "sequentialStack.h" /* This function turns a prefix expression stored in 'prefiExpression' into a postfix expression and stores it in 'postfixExpression' If everything is all right, RETURN SUCCEEDED; otherwise, RETURN FAILED */ State infixToPostfix(char *infixExpression,char postfixExpression[]); /* This function computes the value of a postfix expression stored in 'postfixExpression' and stores the final value in 'value' If everything is all right, RETURN SUCCEEDED; otherwise, RETURN FAILED */ State computeValueFromPostfix(char *postfixExpression, double *value);
C
#include <msp430.h> #define STOP 0x00 #define RUN 0x01 #define FAST 0x00FF #define MEDIUM 0x0FFF #define SLOW 0x7FFF #define LED_DIR P1DIR #define LED P1OUT void delay(void) { volatile unsigned int j = SLOW; while(j > 0) j--; } int main(void) { // Stop watchdog timer, setup P1 direction, and turn off LEDs WDTCTL = WDTPW | WDTHOLD; LED_DIR = 0b11111000; LED = 0b00000000; unsigned int i = 0; // Continuously cycle through LEDs counterclockwise while(RUN) { LED &= ~0xF8; for (i = 4; i < 8; i++) { LED &= ~(1 << i); LED |= ~(1 << i); delay(); LED |= (1 << i); LED &= (1 << i); delay(); } } return 0; }
C
#include <stdio.h> int main(){ float m; float k; float v = 3.6; // km/h para m/s printf("Digite o valor em km/h : "); scanf("%f", &k); m = k / v; printf("\nA velocidade de %f km/h convertido eh de : %f m/s ", k, m); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "../include/primitive.h" #include "../include/filters.h" #include "../include/imageTreatment.h" void grayFilter(Image *img) { int i, j; for(i = 0; i < img->height; i++) { for(j = 0; j < img->width; j++) { //Aplicando o cálculo do píxel cinza. int colorGray = img->pixels[i][j].r*0.3 + img->pixels[i][j].g*0.59 + img->pixels[i][j].b*0.11; //Salvando os três valores, vermelho, verde e vermelho ao arquivo. img->pixels[i][j].r = colorGray; img->pixels[i][j].g = colorGray; img->pixels[i][j].b = colorGray; } } } void gaussianoFilter(Image *img) { int x, y, m, n, newPixel = 0; int sumPixels, sumFilter; Pixel *pixel; int filter[5][5] = {{ 2, 4, 5, 4, 2 }, { 4, 9, 12, 9, 4 }, { 5, 12, 15, 12, 5 }, { 4, 9, 12, 9, 4 }, { 2, 4, 5, 4, 2 }}; for(x = 0; x < img->height; x++) { for(y = 0; y < img->width; y++) { sumPixels = 0; sumFilter = 0; for (m = -2; m <= 2; m++) { for (n = -2; n <= 2; n++) { pixel = pixelReturn(img, x + m, y + n); sumPixels += (pixel->r * filter[m + 2][n + 2]); sumFilter += filter[m + 2][n + 2]; } } newPixel = sumPixels/sumFilter; img->pixels[x][y].r = newPixel; img->pixels[x][y].g = newPixel; img->pixels[x][y].b = newPixel; } } } void sobelFilter(Image *img, Image *image) { int x, y, m, n, newPixel = 0; int valueX, valueY; Pixel *pixel; int sobelX[3][3] = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}}; int sobelY[3][3] = {{1, 2, 1}, {0, 0, 0}, {-1,-2,-1}}; for(x = 0; x < img->height; x++) { for(y = 0; y < img->width; y++) { valueX = 0; valueY = 0; for (m = -1; m <= 1; m++) { for (n = -1; n <= 1; n++) { pixel = pixelReturn(img, x + m, y + n); valueX += (pixel->r * sobelX[m + 1][n + 1]); valueY += (pixel->r * sobelY[m + 1][n + 1]); } } newPixel = (int) sqrt(pow(valueX, 2) + pow(valueY, 2)); image->pixels[x][y].r = newPixel; image->pixels[x][y].g = newPixel; image->pixels[x][y].b = newPixel; } } } void binaryFilter(Image *img) { int i, j; int threshold; if(img->width == 1015 && img->height == 759) { threshold = 50; } else if(img->width == 1198 && img->height == 770) { threshold = 10; } else { threshold = 18; } for (i = 0; i < img->height; i++) { for (j = 0; j < img->width; j++) { if(img->pixels[i][j].r > threshold) { img->pixels[i][j].r = 255; img->pixels[i][j].g = 255; img->pixels[i][j].b = 255; }else { img->pixels[i][j].r = 0; img->pixels[i][j].g = 0; img->pixels[i][j].b = 0; } } } }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct stack *Stack; struct stack { char * array; int size; int top; }; Stack createStack(int arraySize) { Stack S = (Stack)malloc(sizeof(struct stack)); S->size = arraySize; S->top = -1; S->array = (char *)malloc(sizeof(int) * arraySize); return S; } Stack makeEmptyStack(Stack S) { // data memory S->top = -1; for (int i = 0; i < S->size; i++) S->array[i] = '0'; return S; } int isEmpty(Stack S) { // 1̸ empty if (S->top == -1) return 1; return 0; } void push(char X, Stack S) { // X S ִ´ S->array[++(S->top)] = X; } char pop(Stack S) { // ÿ ֱٿ  & if (isEmpty(S)) return '0'; return S->array[(S->top)--]; } void deleteStack(Stack S) { makeEmptyStack(S); free(S); } char print[100]; int psize, fin; Stack S; int main() { S = createStack(100); while (1) { char input; scanf(" %c", &input); if (input == '!') break; if (input == '#') { if (isEmpty(S) && fin == 0) printf("right. "); else printf("wrong. "); for (int i = 0; i < psize; i++) { printf("%c ", print[i]); } printf("\n"); psize = 0; S = createStack(100); fin = 0; } else { if (fin == 1) continue; if (input == '(') push('(', S); else if (input == ')') { if (isEmpty(S)) { fin = 1; continue; } while (1) { char a = pop(S); if (a == '(') break; else if (a != '0') print[psize++] = a; } } else { if (isEmpty(S)) print[psize++] = input; else push(input, S); } } } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_atoi.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rcenamor <rcenamor@student.hive.fi> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/17 14:56:01 by rcenamor #+# #+# */ /* Updated: 2020/01/21 16:02:48 by rcenamor ### ########.fr */ /* */ /* ************************************************************************** */ /* ** Replicates atoi (stdlib.h). ** ** Converts ASCII string to integer. ** ** Returns the integer. NOTE: in the Hive machines, it returns -1 if above ** max long, and 0 if below min long. I replicated this behavior, but this is ** implementation specific. */ #include "libft.h" int ft_atoi(const char *str) { size_t i; unsigned long n; int sign; i = 0; n = 0; sign = 1; while (ft_isspace(str[i])) i++; if (str[i] == '-') sign = -1; if (str[i] == '+' || str[i] == '-') i++; while (str[i] >= '0' && str[i] <= '9') { n = 10 * n + (str[i] - '0'); if ((sign == 1 && n > LONGMAX)) return (-1); if ((sign == -1 && n > LONGMAX)) return (0); i++; } return (sign * (int)n); }
C
#include <stdio.h> int celc(int); int main() { int temp; printf("\nPlease enter temp F: "); scanf("%d", &temp); printf("\n%dF to centigrade is %dC\n", temp, celc(temp)); return 0; } int celc(int f) { return 5 * (f - 32) / 9; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int sum(int *array, int cols) { int out = 0; for(int i=0;i<cols;i++) { out = out + *(array+i); } return out; } int main() { FILE *fp; FILE *out; fp = fopen("A-large.in", "r"); if (fp==NULL) { printf("Error opening file"); return(-1); } out = fopen("counting_sheep_out2.txt", "w"); if(out == NULL) { printf("Error opening file"); return(-1); } int T =0; // scan for number of test cases fscanf(fp, "%d", &T); int i= 0; char *N = 0; N = (char *)malloc(sizeof(char)*10); if(N == NULL) { printf("Error malloc!"); return (-1); } for(i = 0; i<T; i++) { int array[10]={-1,0,0,0,0,0,0,0,0,0}; int multiplier = 1; // scan for each individual starting case fscanf(fp, "%s", N); int number = atoi(N); int digit = 1, j = 1; while (sum(array, 10) < 45 && number != 0) { multiplier = j*number; j++; int divider = multiplier; while(divider>0) { digit = divider%10; if (array[digit]==digit) { divider =divider/10; } else { array[digit]=digit; divider=divider/10; } } } // print the cases if (number == 0) { fprintf(out, "Case #%d: INSOMNIA\n", i+1); } else { fprintf(out, "Case #%d: %d\n", i+1, multiplier); } } free(N); N=0; return 0; }
C
/*The client program has the following major steps: 1) Create a socket 2) Connect the socket to the address of the server 3) Send and recieve datapes.h */ #include<stdio.h> #include<stdlib.h> #include<strings.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<netdb.h> #include<unistd.h> #include<string.h> int count=0; char *name="im0.jpg"; int receive_image(int socket) { // Start function int buffersize = 0, recv_size = 0,size = 0, read_size, write_size, packet_index =1,stat; char imagearray[10241],verify = '1'; FILE *image; //Find the size of the image do{ stat = read(socket, &size, sizeof(int)); }while(stat<0); printf("Packet received.\n"); printf("Packet size: %i\n",stat); printf("Image size: %i\n",size); printf(" \n"); char buffer[] = "Got it"; //Send our verification signal do{ stat = write(socket, &buffer, sizeof(int)); }while(stat<0); printf("Reply sent\n"); printf(" \n"); image = fopen(name, "w"); if( image == NULL) { printf("Error has occurred. Image file could not be opened\n"); return -1; } //Loop while we have not received the entire file yet int need_exit = 0; struct timeval timeout = {1000,0}; fd_set fds; int buffer_fd, buffer_out; while(recv_size < size) { //while(packet_index < 2){ FD_ZERO(&fds); FD_SET(socket,&fds); buffer_fd = select(FD_SETSIZE,&fds,NULL,NULL,&timeout); if (buffer_fd < 0) printf("error: bad file descriptor set.\n"); if (buffer_fd == 0) printf("error: buffer read timeout expired.\n"); if (buffer_fd > 0) { do{ read_size = read(socket,imagearray, 10241); }while(read_size <0); printf("Packet number received: %i\n",packet_index); printf("Packet size: %i\n",read_size); //Write the currently read data into our image file write_size = fwrite(imagearray,1,read_size, image); printf("Written image size: %i\n",write_size); if(read_size !=write_size) { printf("error in read write\n"); } //Increment the total number of bytes read recv_size += read_size; packet_index++; printf("Total received image size: %i\n",recv_size); printf(" \n"); printf(" \n"); } } fclose(image); printf("Image successfully Received!\n"); return 1; } void error(char *msg) { printf("%s",msg); exit(1); } int main(int argc, char **argv) { while(1) { int sockfd,portno,in; struct sockaddr_in serv_addr; struct hostent *server; char buffer[256]; if( argc< 3) { error("Invalid command line arguments.\n"); } portno = atoi(argv[2]); sockfd=socket(AF_INET,SOCK_STREAM,0); if(sockfd<0) { error("Couldn't create socket.\n"); } server = gethostbyname(argv[1]); if(server==NULL) { error("Could not find the server.\n"); } bzero((char *)&serv_addr,sizeof(serv_addr)); serv_addr.sin_family=AF_INET; bcopy((char *)server->h_addr,(char*)&serv_addr.sin_addr.s_addr,server->h_length);//copying values of server address serv_addr.sin_port = htons(portno); if(connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr))<0) { error("Could not connect to server.\n"); } receive_image(sockfd); count++; name=malloc(sizeof(char)*13); snprintf(name,9,"im%d.jpg",count); printf("\n\nGetting New Image\n\n"); sleep(4); } return 0; }
C
#include <stdio.h> #define T(x) puts(">>> " #x); x int main() { int i = 3; int * p = &i; printf("i == %d, p == %p\n", i, p); T(*p = 4;) printf("i == %d, p == %p\n", i, p); T(p = 5;) printf("i == %d, p == %p\n", i, p); return 0; }
C
//************************************************************** // Assignment #4 // Name: Christian Norfleet // Parallel Programming Date: Date of Submission (4/17/2017) //*************************************************************** // This program will implement the use of the double buffering technique. // It will utilize a total of 2 nodes @ 1 process per node. // Process 1 in node A, will have an array of 100 million numbers, // each one of the numbers will be initialized to zero. This process will // send packages of 100000 numbers to the process running in the second node. // In the process running on the second node you will implement the double // buffer technique. The process at the second node will receive the info in // the second half of the buffer while it is also processing data in the other half. //***************************************************************** #include <stdlib.h> #include <stdio.h> #include </usr/include/mpi/mpi.h> #define SIZE_STREAM 100000000 #define SIZE_BUFFER (SIZE_STREAM*2) #define SIZE_BLOCK 100000 #define STREAMER 0 #define BUFFER 1 //******************************************************************* // Function Name::main() // Parameters: int argc, char *argv[] // command line arguments to be sent to Program int main(int argc, char *argv[]) { int rank, size; // standard MPI initialization boilerplate MPI_Request request; MPI_Status status; MPI_Init(&argc, &argv); MPI_Comm_rank (MPI_COMM_WORLD, &rank); MPI_Comm_size (MPI_COMM_WORLD, &size); if(rank == 0) { int NodeA[SIZE_STREAM] = {0}; // starting location of stream int block_loc = 0; // loop until all blocks are sent while(NodeA + block_loc < NodeA+SIZE_STREAM) { // Send a block of data to NodeB MPI_Isend(NodeA + block_loc, SIZE_BLOCK, MPI_INT, BUFFER, 0, MPI_COMM_WORLD, &request); // keep track of current location in stream block_loc = block_loc + SIZE_BLOCK; } } if(rank == 1) { int i, z; int NodeB[SIZE_BUFFER]; int buffer_loc = SIZE_STREAM; int compute_loc = 0; // while not @ end of buffer while(buffer_loc < SIZE_BUFFER) { // if there is work to be done do it // the next value would have to be less than or equal // to previous value for work to be done if(NodeB[compute_loc] > -1 && NodeB[compute_loc] >= NodeB[compute_loc] + 1) { // Recieve data in the second half MPI_Irecv(NodeB+buffer_loc, SIZE_BLOCK, MPI_INT, STREAMER, 0, MPI_COMM_WORLD, &request); // loop thru entire block for(i = 1; i < SIZE_BLOCK; i ++) { // and 1 and store in main buffer NodeB[compute_loc] = NodeB[buffer_loc] + 1; // multiply by 1 two times for(z = 0; z < 2; z++) NodeB[compute_loc] = NodeB[compute_loc] * 1; printf("value: %d\n", NodeB[compute_loc]); // keep track of current location in buffer compute_loc = compute_loc + 1; buffer_loc = buffer_loc + 1; } } } } MPI_Finalize(); return 0; }
C
/* ********************************************************************************** ** ļ˵MMA8452ٶоƬ ** ļƣAcceleration.c ** ڣ2013.05 ** ˣXZY **---------------------------------------------------------------------------------* ** ޸ڣ ** ޸˵ ********************************************************************************** */ /* ------------------------------------------------------------------------------------- ˵:include ------------------------------------------------------------------------------------- */ #include "Interrupt.h" #include "Acceleration.h" #include "iic.h" #include "memory.h" /* ***************************************************************************** ** : Bool MMA8452_RegWrite(Uint8 Addr,Uint8 Dat) ** : MMA8452Ĵд ** 䡡 : AddrĴַDat ** 䡡 : TRUER/FALSE ** ȫֱ: ** ģ: ** : xzy ** ա : 2013. ***************************************************************************** */ Bool MMA8452_RegWrite(Uint8 Addr,Uint8 Dat) { Uint8 i; i = 0; while(!(ISendStr(ADDR_MMA8452Q,(Uint16)Addr,(Uint8 *)&Dat,1,0))) { i ++; if(i > 3) { return FALSE; } } return TRUER; } /* ***************************************************************************** ** : Bool MMA8452_Read(Uint8 Addr,Uint8 * Buf,Uint8 Count) ** : MMA8452 ** 䡡 : Addr Buf Count ** 䡡 : TRUER/FALSE ** ȫֱ: ** ģ: ** : xzy ** ա : 2013. ***************************************************************************** */ Bool MMA8452_Read(Uint8 Addr,Uint8 * Buf,Uint8 Count) { Uint8 i; i = 0; if(!(IRcvStr(ADDR_MMA8452Q,(Uint16)Addr,Buf,Count,0))) { i ++; if(i > 3) { return FALSE; } } return TRUER; } /* ***************************************************************************** ** : Uint8 MMA8452_RegRead(Uint8 Addr) ** : MMA8452Ĵ ** 䡡 : Addr ** 䡡 : ** ȫֱ: ** ģ: ** : xzy ** ա : 2013. ***************************************************************************** */ Uint8 MMA8452_RegRead(Uint8 Addr) { Uint8 i; MMA8452_Read(Addr,(Uint8 *)&i,1); return i; } /* ***************************************************************************** ** : Bool MMA8452_Standby(void) ** : MMA8452ģʽ ** 䡡 : ** 䡡 : ** ȫֱ: ** ģ: ** : xzy ** ա : 2013. ***************************************************************************** */ Bool MMA8452_Standby(void) { Uint8 i; i = MMA8452_RegRead(CTRL_REG1); if(MMA8452_RegWrite(CTRL_REG1,i & ~ACTIVE_MASK) == TRUER) { return TRUER; } return FALSE; } /* ***************************************************************************** ** : void MMA8452_Active(void) ** : MMA8452ģʽ ** 䡡 : ** 䡡 : ** ȫֱ: ** ģ: ** : xzy ** ա : 2013. ***************************************************************************** */ void MMA8452_Active(void) { //Uint8 i; MMA8452_RegWrite(CTRL_REG1,(MMA8452_RegRead(CTRL_REG1)|ACTIVE_MASK)); //i = MMA8452_RegRead(CTRL_REG1); } /* ***************************************************************************** ** : Bool MMA8452_Init(void) ** : MMA8452ʼ 2Gģʽ,(200Hz/5ms),жźӵINT1ţĬ͵ƽЧ ** 䡡 : ** 䡡 : TRUER/FALSE ** ȫֱ: ** ģ: ** : xzy ** ա : 2013. ***************************************************************************** */ Bool MMA8452_Init(void) { if(MMA8452_Standby() == TRUER) //ģʽ { MMA8452_RegWrite(XYZ_DATA_CFG,(MMA8452_RegRead(XYZ_DATA_CFG) & ~FS_MASK));//2Gģʽ // MMA8452_RegWrite(XYZ_DATA_CFG,(MMA8452_RegRead(XYZ_DATA_CFG) | FULL_SCALE_4G));//4G,8GģʽӴ˾ MMA8452_RegWrite(CTRL_REG1,(MMA8452_RegRead(CTRL_REG1) & ~DR_MASK)); // MMA8452_RegWrite(CTRL_REG1,(MMA8452_RegRead(CTRL_REG1)|(DataRateValue << 3)));// MMA8452_RegWrite(CTRL_REG4,INT_EN_DRDY); //ݾжʹ MMA8452_RegWrite(CTRL_REG5,INT_CFG_DRDY); //жźӵINT1 MMA8452_Active(); //ģʽ MMA8452_Standby(); //ģʽ return TRUER; } return FALSE; }/* ***************************************************************************** ** : void Port_Match_Init(void) ** : ˿ƥжϳʼ ** 䡡 : ** 䡡 : ** ȫֱ: ** ģ: ** : xzy ** ա : 2013. ***************************************************************************** */ void Port_Match_Init(void) { //P1MAT = P1MAT &(~ACCEOK); //P1.2߼ֵ߼͵ƽȽϡ P1MAT = P1MAT | ACCEOK; //P1.2߼ֵ߼ߵƽȽϡ P1MASK = P1MASK | ACCEOK; //P1.2߼бȽ MATIntSwitchOn(); //˿ƥж } /* ***************************************************************************** ** : void ACCEL_Init(void) ** : ٶȳʼ ** 䡡 : ** 䡡 : TRUER/FALSE ** ȫֱ: ** ģ: ** : xzy ** ա : 2013. ***************************************************************************** */ void ACCEL_Init(void) { MATIntSwitchOff(); //˿ƥжϹر G_POWERON(); //MMA8452Դ if(MMA8452_Init() == FALSE) { ClearMask(SysDat.Flag,ACC_INT_MASK); } else { Port_Match_Init(); //˿ƥжáʹ SetMask(SysDat.Flag,ACC_INT_MASK); } } /* ***************************************************************************** ** : void ACCEL_OFF(void) ** : رռٶģ ** 䡡 : ** 䡡 : ** ȫֱ: ** ģ: ** : xzy ** ա : 2013. ***************************************************************************** */ void ACCEL_OFF(void) { MATIntSwitchOff(); //˿ƥжϹر G_POWEROFF(); //MMA8452Դ ClearMask(SysDat.Flag,ACC_INT_MASK); } /* ***************************************************************************** ** : void MATCH_INT(void) interrupt PORT_MATCH_PRIOR_ORDER ** : ˿ƥж,ԶӦMMA8452ݾж ** 䡡 : ** 䡡 : ** ȫֱ: ** ģ: ** : xzy ** ա : 2013. ***************************************************************************** */ void MATCH_INT(void) interrupt PORT_MATCH_PRIOR_ORDER { Uint8 flag; Uint8 buf[6]; GlobleIntSwitchOff(); //ȫжϹ flag = MMA8452_RegRead(STATUS_00_REG); if(flag & (INT_EN_DRDY<<2)) //ZOK { MMA8452_Read(OUT_X_MSB,buf,6); MMA8452_Standby(); GatDat->TempAcc[SysDat.pFilter] = buf[4] * 256 + buf[5]; GatDat->TempAcc[SysDat.pFilter] = GatDat->TempAcc[SysDat.pFilter] >> 4; SetMask(SysDat.Flag,ACC_DATA_MASK); } GlobleIntSwitchOn(); //ȫжϿ }
C
// tprof.c // Essai des fonctions de profile de biberc // 23/05/95 PV #include <stdio.h> #include <string.h> #include <biberc.h> char szNomIni[] = "tprof.ini"; int main() { char filename [256]; char szRemoteHost[80]; char szBuffer[5000]; char szValeur[500]; char *p; strcpy(szRemoteHost, "serveur.ercem.com"); strcpy(filename, "/ercem/include/t_etablissement.h"); WritePrivateProfileString("wine", "SystemResources", filename, szNomIni); WritePrivateProfileString("WS_PING", "HOSTNAME", szRemoteHost, szNomIni); szRemoteHost[0] = 0; filename[0] = 0; GetPrivateProfileString("wine", "SystemResources", "sysres.dll", filename, sizeof(filename), szNomIni); GetPrivateProfileString("WS_PING", "HOSTNAME", "200.200.220.2",szRemoteHost,79,szNomIni); printf("szRemoteHost: %s\n", szRemoteHost); printf("filename: %s\n", filename); // Enumration de l'ensemble des sections printf("\nEnsemble des sections de %s:\n", szNomIni); GetPrivateProfileString(NULL, NULL, NULL, szBuffer, sizeof(szBuffer), szNomIni); p = szBuffer; while (*p) { printf("[%s]\n", p); p += strlen(p)+1; } // Enumration des cls de la section windows printf("\nCls de la section Windows:\n"); GetPrivateProfileString("windows", NULL, NULL, szBuffer, sizeof(szBuffer), szNomIni); p = szBuffer; while (*p) { GetPrivateProfileString("windows", p, NULL, szValeur, sizeof(szValeur), szNomIni); printf("%s: %s\n", p, szValeur); p += strlen(p)+1; } return 0; }
C
/* ========================================================================= zarmour - armoured text encoding and decoding Copyright (c) the Contributors as noted in the AUTHORS file. This file is part of CZMQ, the high-level C binding for 0MQ: http://czmq.zeromq.org. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. ========================================================================= */ /* @header zarmour - armoured text encoding and decoding @discuss The zarmour class implements encoding and decoding of armoured text data. The following codecs are implemented: * RFC 4648 (http://www.ietf.org/rfc/rfc4648.txt) - base64 - base64url - base32 - base32hex - base16 * Z85 (http://rfc.zeromq.org/spec:32) All RFC4648 base64 and base32 variants support padding the output. The pad character is configurable. Default is padding on, with character '='. Additionally, in some cases (e.g. MIME), splitting the output into lines of a specific length is required. This feature is also supported, though turned off by default. The z85 mode does neither padding nor line breaks; it is merely a wrapping of the corresponding libzmq methods. Encoding will assert if input length is not divisible by 4 and decoding will assert if input length is not divisible by 5. @end */ #include "czmq_classes.h" #if (ZMQ_VERSION >= ZMQ_MAKE_VERSION (3, 3, 0)) # define _INCLUDE_Z85 #endif // Structure of our class struct _zarmour_t { int mode; // The current mode (Base64/32/16/Z85, STD/URL) bool pad; // Should output be padded? char pad_char; // The pad character bool line_breaks; // Should output be broken into lines? size_t line_length; // The line length to use char *line_end; }; // Textual names of modes static char *s_mode_names [] = { "base64", "base64url", "base32", "base32hex", "base16", "z85" }; // -------------------------------------------------------------------------- // Create a new zarmour zarmour_t * zarmour_new (void) { zarmour_t *self = (zarmour_t *) zmalloc (sizeof (zarmour_t)); assert (self); // Setup default as RFC4648 paragraph 4 self->mode = ZARMOUR_MODE_BASE64_STD; self->pad = true; self->pad_char = '='; self->line_breaks = false; self->line_length = 72; self->line_end = strdup ("\n"); assert (self->line_end); return self; } // -------------------------------------------------------------------------- // Destroy the zarmour void zarmour_destroy (zarmour_t **self_p) { assert (self_p); if (*self_p) { zarmour_t *self = *self_p; freen (self->line_end); freen (self); *self_p = NULL; } } // -------------------------------------------------------------------------- // Helper macros for encoding/decoding #define _NO_CONVERT(c) (c) #define _UPPER_CASE(c) ((c) & ((c) & 0x40? 0xdf: 0xff)) #define _NEXT_CHAR(i, n, c, a, u) \ while ((n) < (c) && !strchr ((a), (u (*(n))))) \ ++ (n); \ (i) = (byte) ((n) < (c)? (strchr ((a), (u (*(n)))) - (a)): 0xff); \ ++ (n) // RFC 4648 Paragraph 4 (standard base64 alphabet) static char // 0----5----0----5----0----5----0----5----0----5----0----5----0--- s_base64_alphabet [] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // RFC 4648 Paragraph 5 (URL & filename friendly base64 alphabet) static char // 0----5----0----5----0----5----0----5----0----5----0----5----0--- s_base64url_alphabet [] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; static char * s_base64_encode (const byte *data, size_t length, const char *alphabet, bool pad, char pad_char) { size_t extra_chars = ((length % 3)? length % 3 + 1: 0); size_t pad_chars = (pad && extra_chars)? 4 - extra_chars: 0; size_t str_chars = 4 *(length / 3) + extra_chars + pad_chars; char *str = (char *) zmalloc (str_chars + 1); if (!str) return NULL; char *enc = str; const byte *needle = data, *ceiling = data + length; while (needle < ceiling) { *enc++ = alphabet [(*needle) >> 2]; if (needle + 1 < ceiling) { *enc++ = alphabet [((*needle << 4) & 0x30) | (*(needle + 1) >> 4)]; if (needle + 2 < ceiling) { *enc++ = alphabet [((*(needle + 1) << 2) & 0x3c) | (*(needle + 2) >> 6)]; *enc++ = alphabet [*(needle + 2) & 0x3f]; } else *enc++ = alphabet [(*(needle + 1) << 2) & 0x3c]; } else *enc++ = alphabet [(*needle << 4) & 0x30]; needle += 3; } while (pad && enc < str + str_chars) *enc++ = pad_char; *enc = 0; return str; } static byte * s_base64_decode (const char *data, size_t *size, const char *alphabet, size_t linebreakchars) { size_t length = strlen (data); while (length > 0 && !strchr (alphabet, data [length - 1])) --length; const byte *needle = (const byte *) data; const byte *ceiling = (const byte *) (data + length); length -= linebreakchars; *size = 3 * (length / 4) + ((length % 4)? length % 4 - 1 : 0) + 1; byte *bytes = (byte *) zmalloc (*size); if (!bytes) return NULL; byte *dec = bytes; byte i1, i2, i3, i4; while (needle < ceiling) { _NEXT_CHAR (i1, needle, ceiling, alphabet, _NO_CONVERT); _NEXT_CHAR (i2, needle, ceiling, alphabet, _NO_CONVERT); if (i1 != 0xff && i2 != 0xff) *dec++ = i1 << 2 | i2 >> 4; _NEXT_CHAR (i3, needle, ceiling, alphabet, _NO_CONVERT); if (i2 != 0xff && i3 != 0xff) *dec++ = i2 << 4 | i3 >> 2; _NEXT_CHAR (i4, needle, ceiling, alphabet, _NO_CONVERT); if (i3 != 0xff && i4 != 0xff) *dec++ = i3 << 6 | i4; } *dec = 0; return bytes; } // RFC 4648 Paragraph 6 (standard base32 alphabet) static char // 0----5----0----5----0----5----0- s_base32_alphabet [] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; // RFC 4648 Paragraph 7 (base32hex alphabet) static char // 0----5----0----5----0----5----0- s_base32hex_alphabet [] = "0123456789ABCDEFGHIJKLMNOPQRSTUV"; static char * s_base32_encode (const byte *data, size_t length, const char *alphabet, bool pad, char pad_char) { size_t extra_bytes = length % 5, extra_chars = 0; switch (extra_bytes) { case 1: extra_chars = 2; break; case 2: extra_chars = 4; break; case 3: extra_chars = 5; break; case 4: extra_chars = 7; break; } size_t pad_chars = (pad && extra_chars)? 8 - extra_chars: 0; size_t str_chars = 8 *(length / 5) + extra_chars + pad_chars; char *str = (char *) zmalloc (str_chars + 1); if (!str) return NULL; char *enc = str; const byte *needle = data, *ceiling = data + length; while (needle < ceiling) { *enc++ = alphabet [(*needle) >> 3]; if (needle + 1 < ceiling) { *enc++ = alphabet [((*needle << 2) & 0x1c) | (*(needle + 1) >> 6)]; *enc++ = alphabet [(*(needle + 1) >> 1) & 0x1f]; if (needle + 2 < ceiling) { *enc++ = alphabet [((*(needle + 1) << 4) & 0x10) | (*(needle + 2) >> 4)]; if (needle + 3 < ceiling) { *enc++ = alphabet [((*(needle + 2) << 1) & 0x1e) | (*(needle + 3) >> 7)]; *enc++ = alphabet [(*(needle + 3) >> 2) & 0x1f]; if (needle + 4 < ceiling) { *enc++ = alphabet [((*(needle + 3) << 3) & 0x18) | (*(needle + 4) >> 5)]; *enc++ = alphabet [*(needle + 4) & 0x1f]; } else *enc++ = alphabet [(*(needle + 3) << 3) & 0x18]; } else *enc++ = alphabet [(*(needle + 2) << 1) & 0x1e]; } else *enc++ = alphabet [(*(needle + 1) << 4) & 0x10]; } else *enc++ = alphabet [(*needle << 2) & 0x1c]; needle += 5; } while (enc < str + str_chars) *enc++ = pad_char; *enc = 0; return str; } static byte * s_base32_decode (const char *data, size_t *size, const char *alphabet, size_t linebreakchars) { size_t length = strlen (data); while (length > 0 && !strchr (alphabet, _UPPER_CASE (data [length - 1]))) --length; const byte *needle = (const byte *) data, *ceiling = (const byte *) (data + length); length -= linebreakchars; size_t extra_chars = length % 8, extra_bytes = 0; switch (extra_chars) { case 0: break; case 2: extra_bytes = 1; break; case 4: extra_bytes = 2; break; case 5: extra_bytes = 3; break; case 7: extra_bytes = 4; break; default: assert (false); break; } *size = 5 *(length / 8) + extra_bytes + 1; byte *bytes = (byte *) zmalloc (*size); if (!bytes) return NULL; byte *dec = bytes; byte i1, i2, i3, i4, i5, i6, i7, i8; while (needle < ceiling) { _NEXT_CHAR (i1, needle, ceiling, alphabet, _UPPER_CASE); _NEXT_CHAR (i2, needle, ceiling, alphabet, _UPPER_CASE); if (i1 != 0xff && i2 != 0xff) *dec++ = i1 << 3 | i2 >> 2; _NEXT_CHAR (i3, needle, ceiling, alphabet, _UPPER_CASE); _NEXT_CHAR (i4, needle, ceiling, alphabet, _UPPER_CASE); if (i2 != 0xff && i3 != 0xff && i4 != 0xff) *dec++ = i2 << 6 | i3 << 1 | i4 >> 4; _NEXT_CHAR (i5, needle, ceiling, alphabet, _UPPER_CASE); if (i4 != 0xff && i5 != 0xff) *dec++ = i4 << 4 | i5 >> 1; _NEXT_CHAR (i6, needle, ceiling, alphabet, _UPPER_CASE); _NEXT_CHAR (i7, needle, ceiling, alphabet, _UPPER_CASE); if (i5 != 0xff && i6 != 0xff && i7 != 0xff) *dec++ = i5 << 7 | i6 << 2 | i7 >> 3; _NEXT_CHAR (i8, needle, ceiling, alphabet, _UPPER_CASE); if (i7 != 0xff && i8 != 0xff) *dec++ = i7 << 5 | i8; } *dec = 0; return bytes; } // RFC 4648 Paragraph 8 (standard base16 alphabet) static char // 0----5----0----5 s_base16_alphabet [] = "0123456789ABCDEF"; static char * s_base16_encode (const byte *data, size_t length, const char *alphabet) { char *str = (char *) zmalloc (2 * length + 1); if (!str) return NULL; char *enc = str; const byte *needle = data, *ceiling = data + length; while (needle < ceiling) { *enc++ = alphabet [(*needle) >> 4]; *enc++ = alphabet [(*needle++) & 0x0f]; } *enc = 0; return str; } static byte * s_base16_decode (const char *data, size_t *size, const char *alphabet, size_t linebreakchars) { size_t length = strlen (data); const byte *needle = (const byte *) data, *ceiling = (const byte *) (data + length); length -= linebreakchars; *size = length / 2 + 1; byte *bytes = (byte *) zmalloc (*size); if (!bytes) return NULL; byte *dec = bytes; byte i1, i2; while (needle < ceiling) { _NEXT_CHAR (i1, needle, ceiling, alphabet, _UPPER_CASE); _NEXT_CHAR (i2, needle, ceiling, alphabet, _UPPER_CASE); if (i1 != 0xff && i2 != 0xff) *dec++ = i1 << 4 | i2; } *dec = 0; return bytes; } // Z85 encoding/decoding static char * s_z85_encode (const byte *data, size_t length) { assert (data != NULL); assert (length % 4 == 0); #ifdef _INCLUDE_Z85 char *str = (char *) zmalloc (5 * length / 4 + 1); char *result = zmq_z85_encode (str, (uint8_t *) data, length); if (result == NULL) { freen (str); str = NULL; } return str; #else return NULL; #endif } static byte * s_z85_decode (const char *data, size_t *size) { assert (data); assert (size); #ifdef _INCLUDE_Z85 size_t length = strlen (data); assert (length % 5 == 0); *size = 4 * length / 5 + 1; byte *bytes = (byte *) zmalloc (*size); uint8_t *result = zmq_z85_decode (bytes, (char *) data); if (result == NULL) { freen (bytes); bytes = NULL; } return bytes; #else return NULL; #endif } // -------------------------------------------------------------------------- // Decode an armoured string into a string of bytes. // The decoded output is null-terminated, so it may be treated // as a string, if that's what it was prior to encoding. // The caller is responsible for destroying the return value when finished with it. char * zarmour_encode (zarmour_t *self, const byte *data, size_t data_size) { assert (self); assert (data); char *encoded = NULL; switch (self->mode) { case ZARMOUR_MODE_BASE64_STD: encoded = s_base64_encode (data, data_size, s_base64_alphabet, self->pad, self->pad_char); break; case ZARMOUR_MODE_BASE64_URL: encoded = s_base64_encode (data, data_size, s_base64url_alphabet, self->pad, self->pad_char); break; case ZARMOUR_MODE_BASE32_STD: encoded = s_base32_encode (data, data_size, s_base32_alphabet, self->pad, self->pad_char); break; case ZARMOUR_MODE_BASE32_HEX: encoded = s_base32_encode (data, data_size, s_base32hex_alphabet, self->pad, self->pad_char); break; case ZARMOUR_MODE_BASE16: encoded = s_base16_encode (data, data_size, s_base16_alphabet); break; case ZARMOUR_MODE_Z85: encoded = s_z85_encode (data, data_size); break; } if (!encoded) return NULL; if (self->line_breaks && self->line_length > 0 && strlen (encoded) > self->line_length && self->mode != ZARMOUR_MODE_Z85) { char *line_end = self->line_end; size_t nbr_lines = strlen (encoded) / self->line_length; size_t new_length = nbr_lines *(self->line_length + strlen (line_end)) + strlen (encoded) % self->line_length; char *src = encoded; char *temp = encoded; encoded = (char *) zmalloc (new_length + 1); char *dest = encoded; while (strlen (src) >= self->line_length) { memcpy (dest, src, self->line_length); src += self->line_length; dest += self->line_length; if (*src) { memcpy (dest, line_end, strlen (line_end)); dest += strlen (line_end); } } if (*src) { memcpy (dest, src, strlen (src)); dest += strlen (src); } freen (temp); *dest = 0; } return encoded; } // -------------------------------------------------------------------------- // Decode an armoured string into a chunk. The decoded output is // null-terminated, so it may be treated as a string, if that's what // it was prior to encoding. // Caller owns return value and must destroy it when done. zchunk_t * zarmour_decode (zarmour_t *self, const char *data) { assert (self); assert (data); size_t linebreakchars = 0; char *line_end = self->line_end; const char *pos = data; while ((pos = strstr (pos, line_end))) { linebreakchars += strlen (line_end); pos += strlen (line_end); } byte *decoded = NULL; size_t size = 0; switch (self->mode) { case ZARMOUR_MODE_BASE64_STD: decoded = s_base64_decode (data, &size, s_base64_alphabet, linebreakchars); break; case ZARMOUR_MODE_BASE64_URL: decoded = s_base64_decode (data, &size, s_base64url_alphabet, linebreakchars); break; case ZARMOUR_MODE_BASE32_STD: decoded = s_base32_decode (data, &size, s_base32_alphabet, linebreakchars); break; case ZARMOUR_MODE_BASE32_HEX: decoded = s_base32_decode (data, &size, s_base32hex_alphabet, linebreakchars); break; case ZARMOUR_MODE_BASE16: decoded = s_base16_decode (data, &size, s_base16_alphabet, linebreakchars); break; case ZARMOUR_MODE_Z85: decoded = s_z85_decode (data, &size); break; } zchunk_t *ret = zchunk_new (decoded, size); freen (decoded); return ret; } // -------------------------------------------------------------------------- // Get the mode property. int zarmour_mode (zarmour_t *self) { assert (self); return self->mode; } // -------------------------------------------------------------------------- // Get printable string for mode. const char * zarmour_mode_str (zarmour_t *self) { assert (self); return s_mode_names [(int) self->mode]; } // -------------------------------------------------------------------------- // Set the mode property. void zarmour_set_mode (zarmour_t *self, int mode) { assert (self); self->mode = mode; } // -------------------------------------------------------------------------- // Return true if padding is turned on. bool zarmour_pad (zarmour_t *self) { assert (self); return self->pad; } // -------------------------------------------------------------------------- // Turn padding on or off. Default is on. void zarmour_set_pad (zarmour_t *self, bool pad) { assert (self); self->pad = pad; } // -------------------------------------------------------------------------- // Get the padding character. char zarmour_pad_char (zarmour_t *self) { assert (self); return self->pad_char; } // -------------------------------------------------------------------------- // Set the padding character. void zarmour_set_pad_char (zarmour_t *self, char pad_char) { assert (self); self->pad_char = pad_char; } // -------------------------------------------------------------------------- // Return if splitting output into lines is turned on. Default is off. bool zarmour_line_breaks (zarmour_t *self) { assert (self); return self->line_breaks; } // -------------------------------------------------------------------------- // Turn splitting output into lines on or off. void zarmour_set_line_breaks (zarmour_t *self, bool line_breaks) { assert (self); self->line_breaks = line_breaks; } // -------------------------------------------------------------------------- // Get the line length used for splitting lines. size_t zarmour_line_length (zarmour_t *self) { assert (self); return self->line_length; } // -------------------------------------------------------------------------- // Set the line length used for splitting lines. void zarmour_set_line_length (zarmour_t *self, size_t line_length) { assert (self); self->line_length = line_length; } // -------------------------------------------------------------------------- // Print properties of object void zarmour_print (zarmour_t *self) { assert (self); zsys_debug ("zarmour:"); zsys_debug (" mode: %s", zarmour_mode_str (self)); zsys_debug (" pad: %s", self->pad? "true": "false"); zsys_debug (" pad_char: '%c'", self->pad_char); zsys_debug (" line_breaks: %s", self->line_breaks? "true": "false"); zsys_debug (" line_length: %d", self->line_length); } // --------------------------------------------------------------------------- // Self test support functions static void s_armour_decode (zarmour_t *self, const char *test_string, const char *expected, bool verbose) { assert (self); assert (test_string); assert (expected); zchunk_t *chunk = zarmour_decode (self, test_string); assert (chunk); if (verbose) zsys_debug (" decoded '%s' into '%s'", test_string, (char *) zchunk_data (chunk)); assert (zchunk_size (chunk) == strlen (expected) + 1); assert (streq ((char *) zchunk_data (chunk), expected)); zchunk_destroy (&chunk); } static void s_armour_test (zarmour_t *self, const char *test_string, const char *expected, bool verbose) { assert (self); assert (test_string); assert (expected); char *encoded = zarmour_encode (self, (byte *) test_string, strlen (test_string)); assert (encoded); if (verbose) zsys_debug (" encoded '%s' into '%s' ('%s')", test_string, encoded, expected); assert (strlen (encoded) == strlen (expected)); assert (streq (encoded, expected)); s_armour_decode (self, encoded, test_string, verbose); freen (encoded); } static void s_armour_test_long (zarmour_t *self, byte *test_data, size_t length, bool verbose) { if (verbose) zarmour_print (self); char *test_string = zarmour_encode (self, test_data, length); assert (test_string); if (verbose) zsys_debug (" encoded %d bytes array to:\n%s", length, test_string); zchunk_t *chunk = zarmour_decode (self, test_string); assert (chunk); assert (zchunk_size (chunk) == length + 1); uint index; for (index = 0; index < length; index++) assert (zchunk_data (chunk)[index] == index); zchunk_destroy (&chunk); if (verbose) zsys_debug (" decoded %d bytes, all match", length); freen (test_string); } // -------------------------------------------------------------------------- // Selftest void zarmour_test (bool verbose) { printf (" * zarmour: "); if (verbose) printf ("\n"); // @selftest zarmour_t *self = zarmour_new (); assert (self); int mode = zarmour_mode (self); assert (mode == ZARMOUR_MODE_BASE64_STD); zarmour_set_mode (self, ZARMOUR_MODE_BASE64_URL); mode = zarmour_mode (self); assert (mode == ZARMOUR_MODE_BASE64_URL); assert (zarmour_pad (self)); zarmour_set_pad (self, false); assert (!zarmour_pad (self)); assert (zarmour_pad_char (self) == '='); zarmour_set_pad_char (self, '!'); assert (zarmour_pad_char (self) == '!'); zarmour_set_pad_char (self, '='); assert (zarmour_pad_char (self) == '='); assert (!zarmour_line_breaks (self)); zarmour_set_line_breaks (self, true); assert (zarmour_line_breaks (self)); assert (zarmour_line_length (self) == 72); zarmour_set_line_length (self, 64); assert (zarmour_line_length (self) == 64); // Test against test vectors from RFC4648. zarmour_set_mode (self, ZARMOUR_MODE_BASE64_STD); if (verbose) zarmour_print (self); s_armour_test (self, "", "", verbose); s_armour_test (self, "f", "Zg", verbose); s_armour_test (self, "fo", "Zm8", verbose); s_armour_test (self, "foo", "Zm9v", verbose); s_armour_test (self, "foob", "Zm9vYg", verbose); s_armour_test (self, "fooba", "Zm9vYmE", verbose); s_armour_test (self, "foobar", "Zm9vYmFy", verbose); zarmour_set_pad (self, true); if (verbose) zarmour_print (self); s_armour_test (self, "", "", verbose); s_armour_test (self, "f", "Zg==", verbose); s_armour_test (self, "fo", "Zm8=", verbose); s_armour_test (self, "foo", "Zm9v", verbose); s_armour_test (self, "foob", "Zm9vYg==", verbose); s_armour_test (self, "fooba", "Zm9vYmE=", verbose); s_armour_test (self, "foobar", "Zm9vYmFy", verbose); zarmour_set_pad (self, false); zarmour_set_mode (self, ZARMOUR_MODE_BASE64_URL); if (verbose) zarmour_print (self); s_armour_test (self, "", "", verbose); s_armour_test (self, "f", "Zg", verbose); s_armour_test (self, "fo", "Zm8", verbose); s_armour_test (self, "foo", "Zm9v", verbose); s_armour_test (self, "foob", "Zm9vYg", verbose); s_armour_test (self, "fooba", "Zm9vYmE", verbose); s_armour_test (self, "foobar", "Zm9vYmFy", verbose); zarmour_set_pad (self, true); if (verbose) zarmour_print (self); s_armour_test (self, "", "", verbose); s_armour_test (self, "f", "Zg==", verbose); s_armour_test (self, "fo", "Zm8=", verbose); s_armour_test (self, "foo", "Zm9v", verbose); s_armour_test (self, "foob", "Zm9vYg==", verbose); s_armour_test (self, "fooba", "Zm9vYmE=", verbose); s_armour_test (self, "foobar", "Zm9vYmFy", verbose); zarmour_set_pad (self, false); zarmour_set_mode (self, ZARMOUR_MODE_BASE32_STD); if (verbose) zarmour_print (self); s_armour_test (self, "", "", verbose); s_armour_test (self, "f", "MY", verbose); s_armour_test (self, "fo", "MZXQ", verbose); s_armour_test (self, "foo", "MZXW6", verbose); s_armour_test (self, "foob", "MZXW6YQ", verbose); s_armour_test (self, "fooba", "MZXW6YTB", verbose); s_armour_test (self, "foobar", "MZXW6YTBOI", verbose); s_armour_decode (self, "my", "f", verbose); s_armour_decode (self, "mzxq", "fo", verbose); s_armour_decode (self, "mzxw6", "foo", verbose); s_armour_decode (self, "mzxw6yq", "foob", verbose); s_armour_decode (self, "mzxw6ytb", "fooba", verbose); s_armour_decode (self, "mzxw6ytboi", "foobar", verbose); zarmour_set_pad (self, true); if (verbose) zarmour_print (self); s_armour_test (self, "", "", verbose); s_armour_test (self, "f", "MY======", verbose); s_armour_test (self, "fo", "MZXQ====", verbose); s_armour_test (self, "foo", "MZXW6===", verbose); s_armour_test (self, "foob", "MZXW6YQ=", verbose); s_armour_test (self, "fooba", "MZXW6YTB", verbose); s_armour_test (self, "foobar", "MZXW6YTBOI======", verbose); s_armour_decode (self, "my======", "f", verbose); s_armour_decode (self, "mzxq====", "fo", verbose); s_armour_decode (self, "mzxw6===", "foo", verbose); s_armour_decode (self, "mzxw6yq=", "foob", verbose); s_armour_decode (self, "mzxw6ytb", "fooba", verbose); s_armour_decode (self, "mzxw6ytboi======", "foobar", verbose); zarmour_set_pad (self, false); zarmour_set_mode (self, ZARMOUR_MODE_BASE32_HEX); if (verbose) zarmour_print (self); s_armour_test (self, "", "", verbose); s_armour_test (self, "f", "CO", verbose); s_armour_test (self, "fo", "CPNG", verbose); s_armour_test (self, "foo", "CPNMU", verbose); s_armour_test (self, "foob", "CPNMUOG", verbose); s_armour_test (self, "fooba", "CPNMUOJ1", verbose); s_armour_test (self, "foobar", "CPNMUOJ1E8", verbose); s_armour_decode (self, "co", "f", verbose); s_armour_decode (self, "cpng", "fo", verbose); s_armour_decode (self, "cpnmu", "foo", verbose); s_armour_decode (self, "cpnmuog", "foob", verbose); s_armour_decode (self, "cpnmuoj1", "fooba", verbose); s_armour_decode (self, "cpnmuoj1e8", "foobar", verbose); zarmour_set_pad (self, true); if (verbose) zarmour_print (self); s_armour_test (self, "", "", verbose); s_armour_test (self, "f", "CO======", verbose); s_armour_test (self, "fo", "CPNG====", verbose); s_armour_test (self, "foo", "CPNMU===", verbose); s_armour_test (self, "foob", "CPNMUOG=", verbose); s_armour_test (self, "fooba", "CPNMUOJ1", verbose); s_armour_test (self, "foobar", "CPNMUOJ1E8======", verbose); s_armour_decode (self, "co======", "f", verbose); s_armour_decode (self, "cpng====", "fo", verbose); s_armour_decode (self, "cpnmu===", "foo", verbose); s_armour_decode (self, "cpnmuog=", "foob", verbose); s_armour_decode (self, "cpnmuoj1", "fooba", verbose); s_armour_decode (self, "cpnmuoj1e8======", "foobar", verbose); zarmour_set_pad (self, true); zarmour_set_mode (self, ZARMOUR_MODE_BASE16); if (verbose) zarmour_print (self); s_armour_test (self, "", "", verbose); s_armour_test (self, "f", "66", verbose); s_armour_test (self, "fo", "666F", verbose); s_armour_test (self, "foo", "666F6F", verbose); s_armour_test (self, "foob", "666F6F62", verbose); s_armour_test (self, "fooba", "666F6F6261", verbose); s_armour_test (self, "foobar", "666F6F626172", verbose); s_armour_decode (self, "666f", "fo", verbose); s_armour_decode (self, "666f6f", "foo", verbose); s_armour_decode (self, "666f6f62", "foob", verbose); s_armour_decode (self, "666f6f6261", "fooba", verbose); s_armour_decode (self, "666f6f626172", "foobar", verbose); #ifdef _INCLUDE_Z85 // Z85 test is homemade; using 0, 4 and 8 bytes, with precalculated // test vectors created with a libzmq test. // ---------------------------------------------------------------- // Make a fake curve key from hex (base16) string, making sure // there are no null bytes inside, so we can use our test utility zarmour_set_mode (self, ZARMOUR_MODE_BASE16); zarmour_set_line_breaks (self, false); zchunk_t *chunk = zarmour_decode (self, "4E6F87E2FB6EB22A1EF5E257B75D79124949565F0B8B36A878A4F03111C96E0B"); assert (chunk); zarmour_set_mode (self, ZARMOUR_MODE_Z85); // Z85 mode does not support padding or line breaks zarmour_set_pad (self, false); // so these two are superfluous; zarmour_set_line_breaks (self, false); // just for consistency if (verbose) zarmour_print (self); s_armour_test (self, "", "", verbose); s_armour_test (self, "foob", "w]zP%", verbose); s_armour_test (self, "foobar!!", "w]zP%vr9Im", verbose); s_armour_test (self, (char *) zchunk_data (chunk), "ph+{E}!&X?9}!I]W{sm(nL8@&3Yu{wC+<*-5Y[[#", verbose); zchunk_destroy (&chunk); #endif // Armouring longer byte array to test line breaks zarmour_set_pad (self, true); zarmour_set_line_breaks (self, true); byte test_data [256]; int index; for (index = 0; index < 256; index++) test_data [index] = index; zarmour_set_mode (self, ZARMOUR_MODE_BASE64_STD); s_armour_test_long (self, test_data, 256, verbose); zarmour_set_mode (self, ZARMOUR_MODE_BASE64_URL); s_armour_test_long (self, test_data, 256, verbose); zarmour_set_mode (self, ZARMOUR_MODE_BASE32_STD); s_armour_test_long (self, test_data, 256, verbose); zarmour_set_mode (self, ZARMOUR_MODE_BASE32_HEX); s_armour_test_long (self, test_data, 256, verbose); zarmour_set_mode (self, ZARMOUR_MODE_BASE16); s_armour_test_long (self, test_data, 256, verbose); #ifdef _INCLUDE_Z85 zarmour_set_mode (self, ZARMOUR_MODE_Z85); s_armour_test_long (self, test_data, 256, verbose); #endif zarmour_destroy (&self); #if defined (__WINDOWS__) zsys_shutdown(); #endif // @end printf ("OK\n"); }
C
#include<stdio.h> #include<math.h> #define ll long long int #define integer_size 32 ll setbits[integer_size+1]; ll countBitsUtil(ll a,ll b){ if(b<=1) return b; ll sa=1+log2(a); ll sb=1+log2(b); if(sa<sb){ ll x,y,z; ll ma=(1<<(sa-1)); x=(a&(a-1)==0)?setbits[sa]-setbits[sa-1]:(ma<<1)-a+countBitsUtil(a-ma,ma-1); y=setbits[sb-1]-setbits[sa]; ll mb=(1<<(sb-1)); z=(b&(b+1)==0)?setbits[sb]-setbits[sb-1]:b-mb+1+countBitsUtil(1,b-mb); return x+y+z; } else{ ll mid=(1<<(sa-1)); return b-a+1+countBitsUtil(a-mid+(a==mid),b-mid); } } ll countBits(ll a,ll b){ if(a<0){ if(b<0) return countBitsUtil((1<<integer_size)+a,(1<<integer_size)+b); if(b==0) return countBitsUtil((1<<integer_size)+a,(1<<integer_size)-1); return countBitsUtil((1<<integer_size)+a,(1<<integer_size)-1)+countBitsUtil(1,b); } if(a==0){ if(b==0) return 0; return countBitsUtil(1,b); } return countBitsUtil(a,b); } void pre(){ setbits[0]=0; for(ll i=1;i<=integer_size;i++) setbits[i]=2*setbits[i-1]+(1<<(i-1)); return 0; } int main(void){ pre(); ll t; scanf("%lld",&t); while(t--){ ll low,high; scanf("%lld %lld",&low,&high); printf("%lld\n",countBits(low,high)); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <assert.h> #define TRSD 50 // threshold // Function prototypes void mergeSort(int items[], int low,int numElements); void mergeSortSC(int items[], int low, int numElements); void insertionSort2(int items[],int low, int high); void swap(int x, int y,int items[]); void printArray(int items[],int low, int high); //This program sorts ints // This is where it all happens! int main(int argc, char *argv[]) { int i, numElements; int *items; // Obtain number of elements and allocate memory to store them fprintf(stderr, "Enter number of elements\n"); scanf("%d", &numElements); items = (int *) malloc(numElements * sizeof(int)); assert(items !=NULL); // Obtain data and store them in array fprintf(stderr, "Enter elements to be sorted\n"); for (i = 0; (i < numElements) && (scanf("%d", &items[i]) != EOF); i++){ ; // Do nothing - it's all done in the for statement! } numElements = i; // Just in case user entered fewer items printf("\nArray before sorting\n"); printArray(items, 0, numElements - 1); // mergeSort(items, 0,numElements-1); mergeSortSC(items, 0, numElements-1); printf("Array after sorting\n"); printArray(items, 0, numElements - 1); return 0; } //An implementation of improved insertion sort - with sentinel and shift void insertionSortSS(int items[], int low, int high) { int i; // Move smallest element to the left for (i= high; i > low; i--) { if (items[i]< items[i - 1]) { swap(i, i - 1,items); } } for (i = low+2; i <= high; i++) { int j = i; int key; key = items[i]; // Shift for (j = i; key < items[j - 1]; j--) { items[j] = items[j - 1]; } items[j] = key; } } void merge(int items[], int low, int mid, int high){ int i, j, k, l; int *temp; if ((temp = (int *) malloc((high - low + 1) * sizeof(int))) == NULL){ fprintf(stderr, "Out of memory - I'm outta here!\n"); exit(1); } i = low; j = 0; k = mid + 1; for (; i <= mid && k <= high; j++) { if (items[i] <= items[k]) { temp[j] = items[i++]; } else { temp[j] = items[k++]; } } if (i > mid) { for (l = k; l <= high; l++) { temp[j++] = items[l]; } } else { for (l = i; l <= mid; l++) { temp[j++] = items[l]; } } // Copy temp array back for (k = low; k <= high; k++) { items[k] = temp[k - low]; } free(temp); // Release memory } //An implementation of standard merge sort void mergeSort(int items[], int low, int high) { int mid; if (low < high) { mid = (low + high)/2; mergeSort(items, low, mid); mergeSort(items, mid + 1, high); merge(items, low, mid, high); } } //An implementation of mergeSortSC with sub-file cutoff void mergeSortSC(int items[], int low, int high) { int mid; if (low < high) { mid = (low + high)/2; if( high - low > TRSD ) { mergeSortSC(items, low, mid); mergeSortSC(items, mid+1, high); } else { insertionSortSS(items, low, high); } merge(items, low, mid, high); } } /* Auxiliary Routines */ // Print the contents of an array of integers // between the indices low and high void printArray(int items[], int low, int high) { int i; for (i = low; i <= high; i++){ printf(" %d", items[i]); } printf("\n"); } // Swap two integer values using pass by reference void swap(int x, int y, int items[]) { int temp; temp = items[x]; items[x] = items[y]; items[y] = temp; }
C
/**************************************************************** **** **** This program source is part of **** Introduction to High-performance Scientific Computing **** by Victor Eijkhout **** copyright Victor Eijkhout 2011-2020 **** **** gdb example program **** ****************************************************************/ #include <stdlib.h> #include <stdio.h> #include <math.h> float root(float n) { float r; r = sqrt(n); return r; } int main() { float x=9,y; for (int i=0; i<20; i++) { y = root(x); printf("root: %e\n",y); x -= 1.1; } return 0; } /* 1. observe the NaN 2. use `break' or `break if' to stop when you are about to take the root of a negative number 3. use `where' and `frame' to determine the iteration that caused this. */
C
#include <stdio.h> #define STOP 0 int main() { int counter; int startpoint; printf("=====Countdown program====="); printf("Enter a positive integer: "); scanf("%d",&startpoint); for(counter = startpoint; counter >= STOP; counter--) { printf("counter: %d\n",counter); printf("counter + 'A': %d\n",counter + 'A'); printf("counter, startpoint + counter: %d,%d\n",counter, startpoint + counter); printf("counter hex: %x\n",counter); } }
C
/* {d: Ch9-3-1.c */ #include <stdio.h> #include <stdlib.h> #define MAX_LEN 20 /* ̤jr */ /* : Xְ}C */ void merge(char *data,int start,int mid,int end) { int left = start; /* b */ int right = mid + 1; /* kb */ int i; char *finalData; /* tmXְϬqһݪOŶ */ finalData = (char*) malloc(sizeof(char)*(end-start+2)); /* X֥kbϬqj */ for (i = 0; i < (end-start+1); i++) { if ( left > mid ) { finalData[i] = data[right]; right++; } else if ( right > end ) { finalData[i] = data[left]; left++; } else if (data[left] < data[right]) { finalData[i] = data[left]; left++; } else { finalData[i] = data[right]; right++; } } finalData[i] = '\0'; /* r굲 */ /* ƻsl}CϬq */ for (i = 0; i < (end - start + 1); i++) { data[start + i] = finalData[i]; } /* ܦX᪺֫r */ printf("%d-%d-%d: [%s]\n",start,mid,end,finalData); } /* : XֱƧǪk */ void mergeSort(char *data, int start, int end) { int mid; if ( end <= start ) return; /* פ */ mid = (start + end) / 2; /* */ mergeSort(data, start, mid); /* jƧǥb */ mergeSort(data, mid+1, end); /* jƧǥkb */ merge(data, start, mid, end); /* Xְ}C */ } /* D{ */ int main() { char data[MAX_LEN]; /* r}C */ int len; /* r */ printf("JƧǪr ==> "); gets(data); /* Ūr */ len = strlen(data); /* pr */ mergeSort(data, 0, len-1); /* XֱƧǪk */ /* ܱƧǫr */ printf("\nXƧǵG: [%s]\n", data); system("PAUSE"); return 0; }
C
// // main.c // 07project13 // // Created by cappuccino on 2020/11/26. // #include <stdio.h> int main(int argc, const char * argv[]) { int length = 0,word = 1; float average = 0; char ch; printf("Enter a sentence:"); while ((ch = getchar()) != '\n') { if(ch == ' ') word++; else length++; } average =(float) length / word; printf("Average word length:%.1f",average); return 0; } //这个判断不了用户在两个单词中间输入两个单词的情况
C
/* ************************************************************************** */ /* */ /* :::::::: */ /* ft_itoa.c :+: :+: */ /* +:+ */ /* By: dfreire <marvin@codam.nl> +#+ */ /* +#+ */ /* Created: 2019/01/19 11:05:38 by dfreire #+# #+# */ /* Updated: 2019/05/08 01:04:42 by dfreire ######## odam.nl */ /* */ /* ************************************************************************** */ #include "libft.h" static int len(long long int n) { int len; len = 1; if (n < 0) len++; while (n /= 10) len++; return (len); } static int unsigned_len(unsigned long long int n) { int len; len = 1; while (n /= 10) len++; return (len); } char *ft_itoa(long long int n) { char *fresh; int i; i = len(n); fresh = ft_strnew(i); if (fresh == NULL) return (0); if (n < 0) fresh[0] = '-'; else n = 0 - n; while (n / 10) { fresh[--i] = (0 - (n % 10)) + '0'; n /= 10; } fresh[--i] = (0 - (n % 10)) + '0'; return (fresh); } char *ft_un_itoa(unsigned long long int n) { char *fresh; int i; i = unsigned_len(n); fresh = ft_strnew(i); if (fresh == NULL) return (0); while (n / 10) { fresh[--i] = (n % 10) + '0'; n /= 10; } fresh[--i] = (n % 10) + '0'; return (fresh); }
C
#pragma once #ifndef _nvdata_h_ #define _nvdata_h_ /** * Non-volatile data storage * * Data is saved in blocks of data size + 1 in the persistent storage (internal/external flash) * until the flash sector is full. * * Upon a full sector, the sector is erased and data written from the beginning. * * Sector start sector start + n*(data size + 1) * v v * +-------------------------+-------+ +-------------------------+-------+ * | data | state | ...... | data | state | * +-------------------------+-------+ +-------------------------+-------+ * */ #ifdef __cplusplus extern "C" { #endif #include <stdint.h> #include "board.h" #ifndef NVDATA_SIZE #define NVDATA_SIZE 31 #endif #define NVDATA_BLOCK_SIZE (NVDATA_SIZE + 1) // Ideally NVDATA_SECTOR_SIZE mod(NVDATA_BLOCK_SIZE) = 0 enum nvdata_e{ NVDATA_EMPTY = 0xFF, NVDATA_VALID = 0xCC, NVDATA_CHANGED = 0xBB, NVDATA_RESTORED = 0 }; typedef struct nvdata { uint8_t data[NVDATA_SIZE]; uint8_t state; uint8_t *freeBlock; }__attribute__ ((aligned (32))) nvdata_t; /** * @brief Initializes internal nvdata structure with next freeblock * and presistent data * * @return 0 : if no valid data or sector was initialized, data size * if valid data read */ uint32_t NV_Init(); /** * @brief Restores data from internal nvdata structure to a given buffer * * @return : number of bytes coppied * */ uint32_t NV_Restore(uint8_t* data, uint16_t count); /** * @brief Save given data to internal structure and persistent storage * * @return : 0 if no free blocks, data count if success * */ uint32_t NV_Save(uint8_t* data, uint16_t count); /** * @brief force write of internal structure to persistent memory * * @return : 0 if failed * */ uint32_t NV_Sync(void); /** * @brief Read bytes from internal structure to a given buffer * * @param offset : offset for reading * @param data : destination buffer * @param count : number of bytes to read * * @return : 0 if offset is invalid or data is not initialised * */ uint32_t NV_Read(uint16_t offset, uint8_t *data, uint32_t count); /** * @brief Write a given byte buffer to internal structure * * @param offset : offset for writing * @param data : source buffer * @param count : number of bytes to be written * * @return : 0 if offset is invalid or data is not initialised * */ uint32_t NV_Write(uint16_t offset, uint8_t *data, uint32_t count); /** * @brief Erase NV Data * * @return : 0 if fail to erase flash sector, NVDATA size if ok * */ uint32_t NV_Erase(void); #ifdef __cplusplus } #endif #endif
C
#include <stdio.h> #include <math.h> int main() { int b,a,c; scanf("%d",&a); c=pow(a,2); printf("%d",c); }
C
#include <stdlib.h> #include <stdio.h> #include "stack.h" /* static para serem visíveis apenas aqui */ static s_type_t * pStack = 0; /* apontador para o array de suporte à stack */ static int capacity; /* capacidade da stack */ static int actSize; /* tamanho atual da stack */ /* DESCRIÇÃO: Inicializa uma stack com a capacidade n PRÉ: n > 0; PÓS: (STACKempty() == 1) && (STACKfull()==0) EXCEÇÃO: aborta caso não haja memória Primeira versão: 2012.06.03 por António dos Anjos email: antoniodosanjos@gmail.com Alterações: */ void STACKinit(int n){ pStack = (s_type_t *) malloc(n*sizeof(*pStack)); if (!pStack){ fprintf(stdout, "Erro de alocação de memória\n"); exit(1); } capacity = n; actSize = 0; } /* DESCRIÇÃO: Devolve 1 se a stack estiver vazia, ou zero caso contrário Primeira versão: 2012.06.03 por António dos Anjos email: antoniodosanjos@gmail.com Alterações: */ int STACKempty(void){ return !actSize; } /* DESCRIÇÃO: Devolve 1 se a stack estiver cheia, ou zero caso contrário Primeira versão: 2012.06.03 por António dos Anjos email: antoniodosanjos@gmail.com Alterações: */ int STACKfull(void){ return (actSize == capacity); } /* DESCRIÇÃO: Retorna e retira o último elemento inserido na stack PRÉ: STACKempty() == 0 PÓS: STACKfull()== 0 Primeira versão: 2012.06.03 por António dos Anjos email: antoniodosanjos@gmail.com Alterações: */ s_type_t STACKpop(void){ return pStack[--actSize]; /* primeiro decrementa, depois utiliza */ } /* DESCRIÇÃO: Retorna o último elemento inserido na stack, sem modificar o estado da stack PRÉ: STACKempty() == 0 PÓS: STACK == old STACK (onde STACK representa o estado da stack) Primeira versão: 2012.06.03 por António dos Anjos email: antoniodosanjos@gmail.com Alterações: */ s_type_t STACKtop(void){ return pStack[actSize-1]; } /* DESCRIÇÃO: Insere um elemento do tipo s_type_t na stack PRÉ: STACKfull() == 0 PÓS: (STACKempty()== 0) && (item == STACKtop()) Primeira versão: 2012.06.03 por António dos Anjos email: antoniodosanjos@gmail.com Alterações: */ void STACKpush(s_type_t item){ pStack[actSize++]=item; /* primeiro utiliza, depois incrementa */ } /* DESCRIÇÃO: Liberta o espaço alocado por STACKinit() PRÉ: STACKinit() foi chamada && STACKkill() não foi chamada PÓS: O espaço alocado por STACKinit fica livre Primeira versão: 2012.06.03 por António dos Anjos email: antoniodosanjos@gmail.com Alterações: */ void STACKkill(void){ free(pStack); } /* utilizada em tempo de debug */ void STACKprint(){ int i=0; for (i=0; i <actSize; i++){ fprintf(stdout, "Stack:\n"); fprintf(stdout, sPrintStr, pStack[i]); fprintf(stdout, "\n"); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* maths_rot.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tlepetit <tlepetit@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/02/16 20:43:34 by tlepetit #+# #+# */ /* Updated: 2014/02/28 16:57:09 by tlepetit ### ########.fr */ /* */ /* ************************************************************************** */ #include <raytracer.h> #include <math.h> #include <stdlib.h> void get_matrice(double **ret, double angle, t_vec ort) { double s; double c; c = cos(angle); s = sin(angle); ret[0][0] = ort.x * ort.x + (1 - ort.x * ort.x) * c; ret[0][1] = ort.x * ort.y * (1 - c) - ort.z * s; ret[0][2] = ort.z * ort.x * (1 - c) + ort.y * s; ret[1][0] = ort.x * ort.y * (1 - c) + ort.z * s; ret[1][1] = ort.y * ort.y + (1 - ort.y * ort.y) * c; ret[1][2] = ort.y * ort.z * (1 - c) - ort.x * s; ret[2][0] = ort.z * ort.x * (1 - c) - ort.y * s; ret[2][1] = ort.y * ort.z * (1 - c) + ort.x * s; ret[2][2] = ort.z * ort.z + (1 - ort.z * ort.z) * c; } void init_ret(double ***ret) { (*ret) = (double**)malloc(3 * sizeof(double*)); (*ret)[0] = (double*)malloc(3 * sizeof(double)); (*ret)[1] = (double*)malloc(3 * sizeof(double)); (*ret)[2] = (double*)malloc(3 * sizeof(double)); (*ret)[0][0] = 1; (*ret)[1][1] = 1; (*ret)[2][2] = 1; (*ret)[0][1] = 0; (*ret)[0][2] = 0; (*ret)[1][0] = 0; (*ret)[1][2] = 0; (*ret)[2][0] = 0; (*ret)[2][1] = 0; } void apply_rot(double **rot, t_vec *pt) { t_vec tmp; tmp.x = pt->x * rot[0][0] + pt->y * rot[0][1] + pt->z * rot[0][2]; tmp.y = pt->x * rot[1][0] + pt->y * rot[1][1] + pt->z * rot[1][2]; tmp.z = pt->x * rot[2][0] + pt->y * rot[2][1] + pt->z * rot[2][2]; *pt = tmp; } double **get_rot(double angle, t_vec ort) { double **ret; init_ret(&ret); if (angle != 0) get_matrice(ret, angle, ort); return (ret); } double **inv_mat(double **rot) { double **inv; inv = malloc(sizeof(double*) * 3); inv[0] = malloc(sizeof(double) * 3); inv[1] = malloc(sizeof(double) * 3); inv[2] = malloc(sizeof(double) * 3); inv[0][0] = rot[1][1] * rot[2][2] - rot[1][2] * rot[2][1]; inv[1][0] = rot[1][2] * rot[2][0] - rot[2][2] * rot[1][0]; inv[2][0] = rot[1][0] * rot[2][1] - rot[1][1] * rot[2][0]; inv[0][1] = rot[2][1] * rot[0][2] - rot[2][2] * rot[0][1]; inv[1][1] = rot[2][2] * rot[0][0] - rot[0][2] * rot[2][0]; inv[2][1] = rot[2][0] * rot[0][1] - rot[2][1] * rot[0][0]; inv[0][2] = rot[0][1] * rot[1][2] - rot[0][2] * rot[1][1]; inv[1][2] = rot[0][2] * rot[1][0] - rot[0][0] * rot[1][2]; inv[2][2] = rot[0][0] * rot[1][1] - rot[0][1] * rot[1][0]; return (inv); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <netdb.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define TRUE 1 #define FALSE 0 extern int h_errno; int main(int argc, char *argv[]) { int x1, x2; struct hostent *hp; sethostent(FALSE); for(x1 = 1; x1 < argc; ++x1) { hp = gethostbyname(argv[x1]); if(0 == hp){ fprintf(stderr, "host %s not found %s\n", argv[x1], hstrerror(h_errno)); continue; } printf("host:: %s\n", argv); printf("official name \t%s\n", hp->h_name); fputs("aliases",stdout); for(x2 = 0; hp->h_aliases[x2]; ++x2){ if(x2) fputs(",", stdout); fputs(hp->h_aliases[x2], stdout); } printf("\n"); printf("type \t %s\n", hp->h_addrtype == AF_INET ? "AF_INET":"AF_INET6" ); if(hp->h_addrtype == AF_INET) for(x2 = 0; hp->h_addr_list[x2]; ++x2) printf("Address \t %s \n", inet_ntoa(*(struct in_addr *)hp->h_addr_list[x2])); putchar('\n'); } return 0; }
C
#include <getopt.h> #include <stdlib.h> #include <stdio.h> #include "common.h" #include "window.h" #include "console.h" char *frontend = "gtk"; char *dev_name = "/dev/video0"; char *path = "/data/capture/"; char *tmp_path = "/tmp/"; static const char short_options[] = "f:d:po:ts"; static const struct option long_options[] = {{ "frontend", required_argument, NULL, 'f' }, { "device", required_argument, NULL, 'd' }, { "out", required_argument, NULL, 'o' }, { "help", no_argument, NULL, 'h' }, { "pretend", no_argument, NULL, 'p' }, { "tmp", no_argument, NULL, 't' }, { "silent", no_argument, NULL, 's' }, { 0, 0, 0, 0 } }; static void usage(FILE *fp, int argc, char **argv) { fprintf(fp, "Usage: %s [options]\n\n" "Version 0.3\n" "Options:\n" "-d | --device name Video device name [%s]\n" "-f | --frontend name Frontend (\"gtk\"|\"web\"|\"cli\") [%s]\n" "-h | --help Print this message\n" "-p | --pretend Do not save nothing\n" "-o | --out Path to save images [%s]\n" "-t | --tmp Path to /tmp images [%s]\n" "-s | --silent Do not send by network\n" "", argv[0], dev_name, frontend, path, tmp_path); } int main(int argn, char* argv[]) { int idx; int c; int do_save = true; int do_send = true; int done_flag = 1; while (done_flag) { c = getopt_long(argn, argv, short_options, long_options, &idx); switch (c) { case 'f': frontend = optarg; break; case 'd': dev_name = optarg; break; case 'o': path = optarg; break; case 's': do_send = false; break; case 'p': do_save = false; break; case 't': tmp_path = optarg; break; case 'h': usage(stderr, argn, argv); exit(0); case -1: done_flag = 0; break; default: usage(stderr, argn, argv); exit(-1); } } capture *cap = init_cap(dev_name, IMG_WITGH, IMG_HEIGHT, BPP_RGB24); iocfg *cfg = init_iocfg(path, tmp_path, do_save, do_send); if (0 == strcmp(frontend, "gtk")) { show_main_form(argn, argv); } else if (0 == strcmp(frontend, "web")) { fprintf(stderr, "NOT IMPLEMENTED YET!"); } else if (0 == strcmp(frontend, "cli")) { do_start_captirung_cli(); } else { fprintf(stderr, "Only 'web', 'cli' or 'gtk' frontends are possible!"); } return 0; }
C
#include<stdio.h> int main() { int a,b; printf("Enter the first number\n"); scanf("%d",&a); printf("Enter the second number\n"); scanf("%d",&b); if(b>0){ while(b!=0){ a++; b--; } } else if(b<0){ while(b!=0){ a--; b++; } } printf("The sum is %d.",a); return 0; }
C
#include <stdio.h> int main(){ unsigned int n; int x, count=0; scanf ("%d",&n); for(int i=0; i<n; i++){ scanf("%d", &x); if(x<0){ count++; } } printf ("%d", count); return 0; }
C
/*3. Longest Substring Without Repeating Characters Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. 最长不重复子串 */ #include <stdio.h> #include <stdlib.h> #include <mem.h> int max(int a,int b) { if(a > b) return a; else return b; } int lengthOfLongestSubstring1(char* s)//双循环法,分别计算每个位置的最长子串,O(nlogn) { char *t = s; int max = 0; while(*t) { char *u = t; int count = 0; int freq[128]; memset(freq,0,128* sizeof(int)); while(*u) { if(freq[(int)*u] == 1) { break; } count++; freq[(int)*u] = 1; u++; } if(count > max) max = count; t++; } return max; } /*滑动窗口,O(n),左窗口l,右窗口r,左窗口跟右窗口初始都为串的头,最长子串长度初始化为零。当右窗口移到串的尾部时,匹配终止,当右窗口不重复时,右窗口不断右移,不断更新最长子串长度(比较当前最长子串长度与左右窗口距离)与字符出现的频度数,当再一次右 窗口出现重复时,说明当前右窗口与左窗口直接存在着重复(不清楚是具体哪一位重复),于是这时只好不断右移左窗口,并把左窗口字符的频度数减一(相当于忘记),当左窗口跨过重复字符时,就不再冲突了,*/ int lengthOfLongestSubstring2(char* s) { char *l = s;// char *r = s; int maxSub = 0; int count = 0; int freq[128]; memset(freq,0,128* sizeof(int)); while(*r) { if(freq[(int)*r] == 1) { (freq[(int)*l]) -= 1; //r--; l++; } else { (freq[(int)*r]) += 1; r++; } maxSub = max(maxSub,r-l); } return maxSub; } int main() { printf("Hello, World!\n"); //printf("a = %d A = %d z = %d Z = %d\n",'a','A','z','Z'); char a[] = "abcaadef"; int max1 = lengthOfLongestSubstring1(a); int max2 = lengthOfLongestSubstring2(a); printf("max1 = %d max2 = %d\n",max1,max2); return 0; }
C
#include "csapp.h" #define ITERATIONS 10 #define THREADS 2 int readcnt; sem_t mutex, w; void* reader(void* v) { for (int i = ITERATIONS; i>0; i--) { P(&mutex); readcnt++; if (readcnt == 1) P(&w); V(&mutex); // Critical section sleep(1); printf("reader\n"); P(&mutex); readcnt--; if (readcnt == 0) V(&w); V(&mutex); } return NULL; } void* writer(void* v) { for (int i = ITERATIONS; i>0; i--) { while (1) { if (! readcnt) { break; } } P(&w); // Critical section sleep(1); printf("writer\n"); V(&w); } return NULL; } void init() { readcnt = 0; Sem_init(&mutex, 0, 1); Sem_init(&w, 0, 1); } int main() { int n = THREADS; pthread_t tid; init(); for (; n > 0; n--) { Pthread_create(&tid, NULL, writer, NULL); Pthread_create(&tid, NULL, reader, NULL); } int ret = 1; pthread_exit(&ret); }
C
#include<stdio.h> long long int max(long long int,long long int); long long int maximum(long long int*,long int); int minimum(int*,long int); int main() { int test; long int n; int in[100000]; long long int s[100000]; long long int sum = 0,out1[10],out2[10],max1,min1; int i,j,k,p,q; scanf("%d",&test); for(i=0;i<test;i++) { scanf("%ld",&n); for(j=1;j<=n;j++) scanf("%d",&in[j]); s[0]=0; for(k=1;k<=n;k++) { s[k] = max(s[k-1]+in[k],in[k]); } max1 = maximum(s,n); for(p=1;p<=n;p++) { if(in[p]>=0) sum = sum + in[p]; else continue; } if(sum == 0) { min1 = minimum(in,n); out2[i] = min1; } else out2[i] = sum; out1[i] = max1; sum = 0; } for(q=0;q<test;q++) { printf("%lld %lld",out1[q],out2[q]); printf("\n"); } } long long int max(long long int a1,long long int a2) { if(a1>=a2) return a1; else return a2; } long long int maximum(long long int* p,long int size) { long long int max = p[1]; int i; for(i=2;i<=size;i++) { if(p[i]>max) max = p[i]; } return max; } int minimum(int* p,long int size) { long long int min = p[1]; int i; for(i=2;i<=size;i++) { if(p[i]>min) min = p[i]; } return min; }
C
/** @file power_consumption.c @brief Documentation for CLEON power consumption @page PWR Power consumption @section PWR Power consumption - This chapter describe the power consumption in case of three GPS signal chunks capturing with 50ms chunk gap - The software is fully interrupt-driven and system remains in low-power-mode almost all the time, except for sensing and USB communication + STAGE 1: Low-power-mode (&asymp; 2.5mA) - Almost all the time, CLEON remains in low-power-mode (LPM) + STAGE 2: MSP430 in AM + GPS on (&asymp; 33mA) - MSP430 is in active mode - Temperature, Humidity, and light sensors are temporarily turned on, then off - GPS is turned-on, stabilized, and in operation (In practice, this stablizing time is configurable with limited flexibility and is set to roughly 100ms) + STAGE 3: MSP430 in AM + GPS on + MicroSD writing (&asymp; 73mA) - MSP430 is in active mode - GPS remains on - Captured sensor data and GPS signal is written to MicroSD - The figure below shows power consumption for 3 chunks of data with 50ms chunk gap @image html power_consumption.jpg */
C
#include <linux/input.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <fcntl.h> //frame buffer #include <sys/ioctl.h> #include <linux/fb.h> #include <sys/mman.h> //#define POS_DEBUG #define DEVICE_FRAME_BUFFER "/dev/fb0" #define DEVICE_MOUSE "/dev/input/mouse1" #define INTERVAL_U 10000 typedef unsigned short int U32; struct fb_var_screeninfo fvs; unsigned int *pfbdata; // /dev/fb0 mapped typedef struct input_event input_event_t; unsigned int makepixel(U32 r, U32 g, U32 b) { unsigned int reval; reval = b; reval |= ((unsigned long)g<<8); reval |= ((unsigned long)r<<16); return reval; } int frameBufferInit(void) { int frame_fd; int check; if((frame_fd = open(DEVICE_FRAME_BUFFER, O_RDWR)) < 0) { return -1; } if((check = ioctl(frame_fd, FBIOGET_VSCREENINFO, &fvs)) < 0) { perror("Get Information Error - VSCREENINFO!\n"); exit(1); } if(fvs.bits_per_pixel != 32) { perror("Unsupport Mode. 32Bpp Only.\n"); exit(1); } if(lseek(frame_fd, 0, SEEK_SET) < 0) { // Set Pixel Map perror("LSeek Error.\n"); exit(1); } pfbdata = (unsigned int*)mmap(0, fvs.xres*fvs.yres*32/8, PROT_READ|PROT_WRITE, MAP_SHARED, frame_fd, 0); return frame_fd; } int makeRect(int frame_fd, U32 R, U32 G, U32 B, int posx1, int posx2, int posy1, int posy2) { unsigned int pixel; int offset; int repx, repy; pixel = makepixel(R, G, B); for(repy = posy1; repy <= posy2; repy++){ offset = repy * fvs.xres; for(repx = posx1; repx <= posx2; repx++) { pfbdata[offset+repx] = pixel; } } return 0; } /* void clearScreen() { int x, y; unsigned int color = makepixel(0, 0, 0); for(y = 0; y < fvs.yres; y++) { for(x = 0; x < fvs.xres; x++) { pfbdata[y*fvs.xres+x] = color; } } } */ int main() { int fd, frame_fd; int mouseR = 0xFF; int mouseG = 0xFF; int mouseB = 0xFF; int color = 0; unsigned char *ptr; unsigned char btn, bLeft, bRight, bMiddle; int posX, posY; int posX_, posY_; int abposX, abposY; printf("%d, %d\n", abposX, abposY); int i; unsigned int pixel; input_event_t buf; memset(&buf, 0, sizeof(input_event_t)); // open frame buffer frame_fd = frameBufferInit(); if(frame_fd < 0) { perror("FrameBuffer error\n"); return -1; } // open mouse device fd = open(DEVICE_MOUSE, O_RDONLY); if(fd < 0) { perror("open error\n"); return -1; } // initialize screen abposX = fvs.xres/2; abposY = fvs.yres/2; makeRect(frame_fd, 0, 0, 0, 0, fvs.xres-1, 0, fvs.yres-1); while(1) { ptr = (unsigned char*)&buf; // load mouse data read(fd, &buf, sizeof(input_event_t)); btn = ptr[0] & 0x03; bLeft = btn & 0x1; bRight = (btn & 0x2) > 0; bMiddle = (btn & 0x4) > 0; posX = (char)ptr[1]; posY = (char)ptr[2]; if(posX > 0x7F) posX -= 0x100; if(posY > 0x7F) posY -= 0x100; //pixel = pfbdata[abposY*fvs.xres + abposX]; // mouse click if(bLeft) { switch(color) { case 0: if((mouseR += 25) > 0xFF) mouseR = 0x00; printf("hi%d\n", mouseR); break; case 1: if((mouseG += 25) > 0xFF) mouseG = 0x00; printf("hi%d\n", mouseG); break; case 2: if((mouseB += 25) > 0xFF) mouseB = 0x00; printf("hi%d\n", mouseB); break; } } else if(bRight) { if(++color > 2) color = 0; } abposX += posX; abposY -= posY; if(abposX < 0) abposX = 0; if(abposY < 0) abposY = 0; if(abposX >= fvs.xres-10) abposX = fvs.xres-11; if(abposY >= fvs.yres-10) abposY = fvs.yres-11; printf("(%d,%d) - (%d,%d)\n", abposX, abposY, posX, posY); makeRect(frame_fd, mouseR, mouseG, mouseB, abposX, abposX+10, abposY, abposY+10); // remember last mouse data posX_ = posX; posY_ = posY; usleep(INTERVAL_U); } close(fd); close(frame_fd); munmap(&buf, sizeof(input_event_t)); munmap(pfbdata, fvs.xres*fvs.yres*32/8); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <time.h> #include <stddef.h> #include <unistd.h> #include <getopt.h> #include <string.h> #include <linux/limits.h> #include "garmin/garmin.h" #include "garmin/fit.h" #include "garmin/fit_definitions.h" #include "print_csv.h" /***************************************************************************** * T Y P E S *****************************************************************************/ #define SIZEOFARRAY(a) (sizeof(a)/sizeof(a[0])) /***************************************************************************** * G L O B A L V A R I A B L E S *****************************************************************************/ #define PROGRAM_NAME "fitdecode" #define PROGRAM_AUTHOR "Paul Archer" #define PROGRAM_AUTHOR_EMAIL "ptarcher@gmail.com" #define PROGRAM_VERSION "0.1" int nbytes; bool flag_verbose; FILE *fp; csv_display_t display; /*****************************************************************************/ void printUsage(void) { fprintf(stdout, "Usage: %s [options] filename\n" " -l --laps\n" " -s --session\n" " -r --records\n" " -v --verbose\n" " -h --help\n" "\n\n" "%s version %s. \n" "Author: %s\n" "Report bugs to %s", PROGRAM_NAME, PROGRAM_NAME, PROGRAM_VERSION, PROGRAM_AUTHOR, PROGRAM_AUTHOR_EMAIL); exit(1); } int parseArgs(int argc, char *argv[]) { int c; int i; fp = stdin; while (1) { int this_option_optind; int option_index; static struct option long_options[] = { {"laps", no_argument, 0, 'l'}, {"session", no_argument, 0, 's'}, {"records", no_argument, 0, 'r'}, {0, 0, 0, 0}, }; this_option_optind = optind ? optind : 1; c = getopt_long(argc, argv, "lsrhv", long_options, &option_index); if (c == -1) { break; } switch(c) { case 0: printf("long option %s", long_options[option_index].name); if (optarg) { printf(" with arg %s", optarg); } printf("\n"); break; case 'l': if (display) { fprintf(stderr, "Cannot have two modes set\n"); exit(1); } display = DISPLAY_LAPS; break; case 's': if (display) { fprintf(stderr, "Cannot have two modes set\n"); exit(1); } display = DISPLAY_SESSIONS; break; case 'r': if (display) { fprintf(stderr, "Cannot have two modes set\n"); exit(1); } display = DISPLAY_RECORDS; break; case 'h': printUsage(); break; case 'v': flag_verbose = true; break; default: printUsage(); break; } } for (i = optind; i < argc; i++) { if (fp != stdin) { fprintf(stderr, "more then one filename given %s\n", argv[i]); exit(1); } /* Open the input file */ fp = fopen(argv[i], "r"); if (fp == NULL) { perror(argv[i]); return 0; } } return 0; } int main(int argc, char *argv[]) { init_definitions(); parseArgs(argc, argv); fit_process_file(); return 0; }
C
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "util_mem.h" #include "io_url.h" #include "util_string.h" // // Returns true if both urls are logically equal // bool io_url_equals( io_url_t* that, io_url_t* other ) { if (!that && !other) return true; if (!that || !other) return false; if (that->port != other->port) return false; if (that->scheme && other->scheme) { if (0 != STRING_compare_nocase(that->scheme, other->scheme)) return false; } else if (that->scheme != other->scheme) return false; if (that->host_name && other->host_name) { if (0 != STRING_compare_nocase(that->host_name, other->host_name)) return false; } else if (that->host_name != other->host_name) return false; if (that->path && other->path) { if (0 != STRING_compare_nocase(that->path, other->path)) return false; } else if (that->path != other->path) return false; if (that->user_name && other->user_name) { if (0 != STRING_compare_nocase(that->user_name, other->user_name)) return false; } else if (that->user_name != other->user_name) return false; if (that->password && other->password) { if (0 != STRING_compare_nocase(that->password, other->password)) return false; } else if (that->password != other->password) return false; return io_token_provider_is_equivalent(that->token_provider, other->token_provider); } // // Free address // void io_url_free( io_url_t* address ) { if (!address) return; if (address->scheme) STRING_delete(address->scheme); if (address->host_name) STRING_delete(address->host_name); if (address->path) STRING_delete(address->path); if (address->user_name) STRING_delete(address->user_name); if (address->password) STRING_delete(address->password); if (address->token_provider) io_token_provider_release(address->token_provider); mem_free_type(io_url_t, address); } // // Creates an address // int32_t io_url_create( const char* scheme, const char* host_name, uint16_t port, const char* path, const char* user_name, const char* password, io_url_t** created ) { int32_t result = er_out_of_memory; io_url_t* address; chk_arg_fault_return(host_name); chk_arg_fault_return(created); address = mem_zalloc_type(io_url_t); if (!address) return er_out_of_memory; do { address->host_name = STRING_construct(host_name); address->port = port; if (!address->host_name) break; if (scheme) { if (!address->port) { /**/ if (0 == string_compare_nocase(scheme, "wss")) address->port = 443; else if (0 == string_compare_nocase(scheme, "amqps")) address->port = 5671; else if (0 == string_compare_nocase(scheme, "https")) address->port = 443; else if (0 == string_compare_nocase(scheme, "mqtts")) address->port = 8883; else { result = er_invalid_format; break; } } address->scheme = STRING_construct(scheme); if (!address->scheme) break; } if (path) { address->path = STRING_construct(path); if (!address->path) break; } if (user_name) { address->user_name = STRING_construct(user_name); if (!address->user_name) break; } if (password) { address->password = STRING_construct(password); if (!address->password) break; } *created = address; return er_ok; } while (0); io_url_free(address); return result; } // // Make a clone of the address configuration // int32_t io_url_clone( io_url_t* address, io_url_t** cloned ) { int32_t result; io_url_t* copy; chk_arg_fault_return(address); chk_arg_fault_return(cloned); copy = mem_zalloc_type(io_url_t); if (!copy) return er_out_of_memory; do { result = er_out_of_memory; copy->port = address->port; if (address->scheme) copy->scheme = STRING_clone(address->scheme); if (address->host_name) copy->host_name = STRING_clone(address->host_name); if (address->path) copy->path = STRING_clone(address->path); if (address->user_name) copy->user_name = STRING_clone(address->user_name); if (address->password) copy->password = STRING_clone(address->password); if ((address->scheme && !copy->scheme) || (address->host_name && !copy->host_name) || (address->path && !copy->path) || (address->user_name && !copy->user_name) || (address->password && !copy->password)) break; if (address->token_provider) { result = io_token_provider_clone( address->token_provider, &copy->token_provider); if (result != er_ok) break; } *cloned = copy; return er_ok; } while (0); io_url_free(copy); return result; }
C
#include <stdio.h> #include <math.h> struct point { float x; float y; }; void fpoint ( struct point pc ); float Isperpendicular (struct point p1, struct point p2,struct point p3,struct point p4); int main () { struct point pt1, pt2,pt3,pt4 ; float p; fpoint( pt1 ); fpoint( pt2 ); fpoint( pt3 ); fpoint(pt4 ); p=Isperpendicular( pt1, pt2,pt3,pt4); if(p==-1.00) printf("both the point is perpendicular to each other\n"); else printf(" point are not perpendicular to each other\n"); return 0; } void fpoint ( struct point pc ) { printf( " Enter X value for point\n"); scanf( "%f",&pc.x ); printf( " Enter Y value for point\n"); scanf( "%f",&pc.y); } float Isperpendicular (struct point p1,struct point p2,struct point p3,struct point p4) { float p,m1,m2; m1=((p2.y-p1.y)/(p2.x-p1.x)); m2=((p4.y-p3.y)/(p4.x-p3.x)); p=m1*m2; return p; }
C
/* ** EPITECH PROJECT, 2018 ** init ** File description: ** and result; */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include "my.h" #include "struct.h" void print_result(matrix_t mat, int x, int y) { int cpt = 0; while (cpt != 3) { printf("%.2f", mat.matrix[cpt][0]); printf(" %.2f", mat.matrix[cpt][1]); printf(" %.2f\n", mat.matrix[cpt][2]); cpt++; } printf("(%i, %i) =>", x, y); printf(" (%.2f, %.2f)\n", mat.res1, mat.res2); } matrix_t init_struct(int x, int y, matrix_t mat) { mat.res1 = x; mat.res2 = y; mat.matrix[0][0] = 1.00; mat.matrix[0][1] = 0.00; mat.matrix[0][2] = 0.00; mat.matrix[1][0] = 0.00; mat.matrix[1][1] = 1.00; mat.matrix[1][2] = 0.00; mat.matrix[2][0] = 0.00; mat.matrix[2][1] = 0.00; mat.matrix[2][2] = 1.00; return (mat); }
C
#include <stdio.h> #include <stdlib.h> /* TAD: ListaDup */ struct listaDup{ int info; /* Informao guardada na lista */ struct listaDup *ant; /* Ponteiro para o elemento anterior da lista */ struct listaDup *prox; /* Ponteiro para o prximo elemento da lista */ }; /* Tipo exportado */ typedef struct listaDup ListaDupla; /* Funes exportadas */ //Funo inicializa: Cria uma lista vazia, sem nenhum elemento ListaDupla* inicializa(void); //Funo insere: Insere um novo elemento ordenado (n) de acordo com a ordem crescente na lista ListaDupla* insereOrd(ListaDupla *l, int i); //Funo imprimePU: Imprime todos os valores dos elementos armazenados na lista do primeiro ao ltimo void imprime(ListaDupla *l); //Funo vazia: Verifica se a lista est vazia ou no int vazia(ListaDupla *l); //Funo busca: Verifica se o elemento requisitado est presente na lista ListaDupla* busca(ListaDupla *l, int v); //Funo libera: Libera os elementos alocados um por um, destruindo a lista void libera(ListaDupla *l); //Funo separa: Separa a lista em duas listas ListaDupla* separa(ListaDupla *l, int n);
C
#define _SERVER_H_ #include "mysockets.h" /* * Author: Jeff Mariconda * Class: CS-392 * * Client program for the basic IRC application. */ //Prints goodbye message and ends the client on SIGINT. void client_bye(int sig) { int m; if (sig == SIGINT) { my_str("\nReceived Interrupt. Now Exiting.\n\n"); } else if (sig == SIGALRM) { my_str("\nERROR: Did not receive acknowledgement from server.\n\n"); } if ((m = write(sfd, "/exit", 6) < 0)) { my_str("\nERROR: Unable to send message to server.\n"); } exit(0); } int main(int argc, char **argv) { struct sockaddr_in serv_addr; struct hostent *server; int port, n; char *buff, *usr, *temp, **v; if (argv != NULL && *argv != NULL && argc == 3) { signal(SIGINT, client_bye); signal(SIGALRM, client_bye); //setup socket if ((sfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { my_str("\nERROR: Unable to open socket.\n\n"); exit(1); } //get server if ((server = gethostbyname(argv[1])) == NULL) { my_str("\nERROR: Could not find server. Please use:\n\t./client [servername] [port]\n\n"); close(sfd); exit(1); } //get port port = my_atoi(argv[2]); if (port < 1 || port > 64000) { my_str("\nERROR: Invalid Port. Please use:\n\t./client [servername] [port from 0-64000]\n\n"); close(sfd); exit(1); } //initialize serv_addr struct elements memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(port); memcpy(&serv_addr.sin_addr.s_addr, server->h_addr, server->h_length); //connect to server if (connect(sfd, (struct sockaddr*)&serv_addr, (socklen_t)sizeof(serv_addr)) < 0) { my_str("\nERROR: Unable to connect to server.\n\n"); close(sfd); exit(1); } my_str("\n----------------------------------------------------\n"); my_str("WELCOME TO SIMPLE CHAT CLIENT"); my_str("\n----------------------------------------------------\n"); buff = xmalloc(256 * sizeof(char)); my_str("\nUsername: "); //read in username and send it to server if ((n = read(0, buff, 256)) < 0) { my_str("\nERROR: Could not read username.\n\n"); close(sfd); exit(1); } usr = my_vect2str(my_str2vect(buff)); temp = my_strconcat("/nick ", usr); if ((n = write(sfd, temp, my_strlen(temp) + 1)) < 0) { my_str("\nERROR: Unable to write to server.\n\n"); close(sfd); exit(1); } free(temp); //check for server acknowledgement alarm(5); if ((n = read(sfd, buff, 2)) > 0) { alarm(0); } else { my_str("\nERROR: Did not recieve acknowledgement from server.\n"); close(sfd); exit(1); } my_str("\nYou are now connected to "); my_str(argv[1]); my_str(". Enter /help for a list of commands.\n\n"); //begin input loop while (1) { my_str(usr); my_str(": "); memset(buff, 0, 256); //read user input if ((n = read(0, buff, 256)) < 0) { my_str("\nERROR: Unable to read input.\n"); break; } else if (n == 1) { continue; } //check for special cases v = my_str2vect(buff); for (; *buff == ' ' || *buff == '\t' ; buff++) ; buff[my_strlen(buff) - 1] = '\0'; if (my_strcmp(v[0], "/nick") == 0) { free(usr); usr = my_strdup(&buff[6]); } else if (my_strcmp(v[0], "/exit") == 0) { my_str("\nThanks for using the simple chat client. Goodbye.\n"); if ((n = write(sfd, buff, my_strlen(buff) + 1)) < 0) { my_str("\nERROR: Unable to send message to server.\n"); } break; } //write message to server if ((n = write(sfd, buff, my_strlen(buff) + 1)) < 0) { my_str("\nERROR: Unable to send message to server.\n"); break; } //check for server acknowledgement alarm(5); if ((n = read(sfd, buff, 2)) > 0) { alarm(0); } else { my_str("\nERROR: Did not recieve acknowledgement from server.\n"); close(sfd); exit(1); } my_freevect(v); } } else { my_str("\nInvalid Input. Please use:\n\t./client [servername] [port]\n\n"); exit(0); } close(sfd); free(buff); free(usr); my_freevect(v); return 0; }
C
#include "video.h" #include <SDL.h> #include "debug.h" #include "input.h" #include "scaler.h" SDL_Surface *screen; SDL_Surface *screenScaled; int screenScale; int fullscreen; Uint32 curTicks; Uint32 lastTicks = 0; int initSDL() { if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_JOYSTICK)) { return -1; } SDL_WM_SetCaption("Homing Fever", NULL); SDL_ShowCursor(SDL_DISABLE); updateScale(); if(screen == NULL) { return -1; } if(SDL_NumJoysticks() > joyNum) { joyDevice = SDL_JoystickOpen(joyNum); } return 0; } void deinitSDL() { if(joyDevice) { SDL_JoystickClose(joyDevice); } if (screenScale > 1) { SDL_FreeSurface(screen); } SDL_Quit(); } void updateScale() { if (screen != screenScaled) { SDL_FreeSurface(screen); } screenScaled = SDL_SetVideoMode(SCREEN_W * screenScale, SCREEN_H * screenScale, SCREEN_BPP, SDL_HWSURFACE | SDL_DOUBLEBUF | (fullscreen ? SDL_FULLSCREEN : 0)); screen = screenScale > 1 ? SDL_CreateRGBSurface(SDL_SWSURFACE, SCREEN_W, SCREEN_H, SCREEN_BPP, 0, 0, 0, 0) : screenScaled; } Uint32 getColor(Uint8 r, Uint8 g, Uint8 b) { return SDL_MapRGB(screen->format, r, g, b); } SDL_Surface *loadImage(char *fileName) { SDL_Surface *loadedImage; SDL_Surface *optimizedImage; Uint32 colorKey; if (!fileName) { fprintf(stderr, "ERROR: Filename is empty."); return NULL; } loadedImage = SDL_LoadBMP(fileName); if (!loadedImage) { fprintf(stderr, "ERROR: Failed to load image: %s\n", fileName); return NULL; } optimizedImage = SDL_CreateRGBSurface(SDL_HWSURFACE | SDL_DOUBLEBUF | (fullscreen ? SDL_FULLSCREEN : 0), loadedImage->w, loadedImage->h, SCREEN_BPP, 0, 0, 0, 0); SDL_BlitSurface(loadedImage, NULL, optimizedImage, NULL); SDL_FreeSurface(loadedImage); if (!optimizedImage) { fprintf(stderr, "ERROR: Failed to optimize image: %s\n", fileName); return NULL; } colorKey = SDL_MapRGB(optimizedImage->format, 255, 0, 255); /* Set transparency to magenta. */ SDL_SetColorKey(optimizedImage, SDL_SRCCOLORKEY, colorKey); return optimizedImage; } void clipImage(SDL_Rect *source, int tileWidth, int tileHeight, int rowLength, int numOfTiles) { int i; int j; int k; int l; for(i = 0, k = 0; k < numOfTiles; i+= tileHeight) { for(j = 0, l = 0; l < rowLength; j+= tileWidth) { source[k].x = j; source[k].y = i; source[k].w = tileWidth; source[k].h = tileHeight; ++k; ++l; } l = 0; } } void drawImage(SDL_Surface *source, SDL_Rect *clip, SDL_Surface *destination, int x, int y) { SDL_Rect offset; offset.x = x; offset.y = y; SDL_BlitSurface(source, clip, destination, &offset); } void drawBackground(SDL_Surface *destination, Uint32 color) { SDL_FillRect(destination, NULL, color); } void drawPoint(SDL_Surface *destination, int x, int y, Uint32 color) { SDL_Rect r; r.x = x; r.y = y; r.w = 1; r.h = 1; SDL_FillRect(destination, &r, color); } int frameLimiter() { int t; #if defined(NO_FRAMELIMIT) return 0; #endif curTicks = SDL_GetTicks(); t = curTicks - lastTicks; if(t >= 1000/FPS) { lastTicks = curTicks; return 0; } SDL_Delay(1); return 1; } void flipScreen() { switch (screenScale) { case 1: break; case 2: upscale2((uint32_t *)screenScaled->pixels, (uint32_t *)screen->pixels); break; } SDL_Flip(screenScaled); if (debugSlowMotion) { SDL_Delay(250); } } void clearScreen() { SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0, 0, 0)); }
C
#include "types.h" #include "user.h" #include "date.h" int main(int argc, char *argv[]) { struct rtcdate r; if (date(&r)) { printf(2, "date failed\n"); exit(); } printf( 1, "%d/%d/%d %d:%d:%d\n", r.month, r.day, r.year, r.hour, r.minute, r.second ); exit(); }
C
#include <stdio.h> #include "luz.h" #include "codigo.h" #include "alarma.h" #include "timeval_helper.h" int p_alarma; int boton; int presencia; struct timeval espera_deadline1; void scan_keyboard () { char buf[256]; struct timeval timeout = {0,0}; fd_set rdset; FD_ZERO (&rdset); FD_SET (0, &rdset); if (select (1, &rdset, NULL, NULL, &timeout) > 0) { fgets (buf, 256, stdin); if ((buf[0])!='\n'){ switch (buf[0]) { case 'a': p_alarma = 1; static struct timeval t_espera = { 1, 0 }; gettimeofday (&espera_deadline1, NULL); timeval_add (&espera_deadline1, &espera_deadline1, &t_espera); printf("p_alarma = 1\n"); break; case 'b': boton = 1; printf("boton luz = 1\n"); break; case 'p': presencia = 1; printf("presencia = 1\n"); break; } } } } int main (void) { static struct timeval period = { 1, 0 }; struct timeval next; fsm_t* luz = fsm_new_luz (); fsm_t* codigo = fsm_new_codigo (); fsm_t* alarma = fsm_new_alarma (); gettimeofday (&next, NULL); printf("\n"); printf("\t****************************************\n\n"); printf("\t\tTeclas de activación:\n\n"); printf("\tPresencia: p\n"); printf("\tBotón luz: b\n"); printf("\tPulsador código alarma: a\n"); printf("\tContraseña de la alarma: 2 3 2\n\n"); printf("\t****************************************\n\n"); while (1) { fsm_fire (luz); fsm_fire (codigo); fsm_fire (alarma); timeval_add (&next, &next, &period); scan_keyboard (); } }
C
#include <stdio.h> #include <stdlib.h> #include <ctype.h> /* 1- Ler a idade, o peso e o sexo de N alunos e mostrar: -Media de pesos dos homens; -Quantidade de homens com mais de 80kg; -Media de idades das mulheres; -Quantidade de mulheres acima de 25 anos; Consistencias: -Idade e peso deve ser maior que 0; -Variavel sexo deve receber letra minuscula; -Digite a quantidade de pessoas; */ int main() { int pessoas, idade, contm = 0, contf = 0, cont_peso = 0, cont_idade = 0, acum_idade = 0, cont_pessoas = 0; float peso, acum_peso = 0, media_idade = 0, media_peso = 0; char sexo; printf(" \t Digite a quantidade de pessoas: "); scanf("%d", &pessoas); do { system("cls"); do { printf(" \n Digite a idade: "); scanf("%d", &idade); printf(" \n Digite o peso: "); scanf("%f", &peso); } while(idade < 0 && peso < 0); do { printf(" \n Digite o sexo: "); fflush(stdin); scanf("%c", &sexo); sexo = tolower(sexo); } while(sexo != 'm' && sexo != 'f'); if(sexo == 'm') { contm++; acum_peso = acum_peso + peso; if(peso > 80) cont_peso++; } if(sexo == 'f') { contf++; acum_idade = acum_idade + idade; if(idade > 25) cont_idade++; } cont_pessoas++; } while(pessoas > cont_pessoas); media_idade = acum_idade/contf; media_peso = acum_peso/contm; printf(" \n A media de peso dos homens e de %.0fKg.", media_peso); printf(" \n Ha %d homen(s) com o peso acima de 80kg.", cont_peso); printf(" \n A media de idade das mulheres e de %.0f anos.", media_idade); printf(" \n Ha %d mulher(s) com mais de 25 anos.", cont_idade); system(" pause "); } /*Leonardo Melo RA: 3287.2411.5834 Sistemas de Informao 2S*/
C
/* * dice.c * * Created: 27/12/2014 19:03:20 * Author: JONATHAN */ #include <avr/io.h> #define F_CPU 8000000UL #include <avr/interrupt.h> #include <util/delay.h> #include <stdlib.h> int contador; int tempo; int vector[]={0b11000000,0b10100100,0b11100100,0b10101101,0b11101101,0b10111111,0b11111111}; void puertos(void); void interrupciones(void); int main(void) { puertos(); interrupciones(); tempo=random()%7; contador=0; while(1) { PORTB=vector[tempo]; if (contador==1) //hace q parezka q gira antes de detenerse en un numero { contador=0; PORTB=vector[random()%7]; _delay_ms(100); PORTB=vector[random()%7]; _delay_ms(100); PORTB=vector[random()%7]; _delay_ms(100); PORTB=vector[random()%7]; _delay_ms(100); tempo=random()%7; PORTB=vector[tempo]; } } return 0; } void puertos (void) { DDRA=0; DDRD=0; DDRB=0b01111111; PORTA=0b111; PORTD=0b1111111; PORTB=0b10000000; } void interrupciones (void) { MCUCR=0b00001010; GIMSK=0b11000000; sei(); } ISR(INT0_vect) { _delay_ms(20); //ELIMINA REBOTES contador=1; }
C
#include <time.h> #include "player.h" #include "../lib/set-src/include/set.h" #include "graph_manager.h" #include "methods.h" #include "WTree.h" static char *player_name = "PSX"; struct s_player { struct graph_t *player_graph; enum color_t player_color; struct set *available_vertices; WTree *player_tree; WTree *enemy_tree; int init_tree; }; #ifdef TEST struct s_player p = {NULL, BLACK, NULL, NULL, 0, 0}; #else static struct s_player s_player; #endif //////////////// Auxiliary Functions ///////////// /** * \fn void initialize(struct graph_t *graph); * \brief Inizialize the players trees and their weights * \param graph Game board. */ void initialize(struct graph_t *graph) { int start_player, end_player, start_enemy, end_enemy; if (s_player.player_color == BLACK) { start_player = 0; end_player = s_player.player_graph->num_vertices - 1; start_enemy = graph_side_size(s_player.player_graph); end_enemy = s_player.player_graph->num_vertices - graph_side_size(s_player.player_graph) - 1; } else { start_enemy = 0; end_enemy = s_player.player_graph->num_vertices - 1; start_player = graph_side_size(s_player.player_graph) - 1; end_player = s_player.player_graph->num_vertices - graph_side_size(s_player.player_graph); } s_player.player_tree = init_tree(start_player, end_player, graph->num_vertices); s_player.enemy_tree = init_tree(start_enemy, end_enemy, graph->num_vertices); init_weights(s_player.player_graph, s_player.player_tree, s_player.player_color); init_weights(s_player.player_graph, s_player.enemy_tree, !s_player.player_color); } /** * \fn struct set *available_vertices (struct graph_t *graph); * \brief Construct a set of available vertices * \param graph Game board. * \return A set of available vertices in the board. */ struct set *available_vertices (struct graph_t *graph) { struct set *available = set__empty(); for (int i = 0; i < graph->num_vertices; i++) { if (get_vertex_value(graph, BLACK, i) == 0 && get_vertex_value(graph, WHITE, i) == 0) { set__add(available, i); } } return available;; } /** * \fn float eval_func(float d1, float d2); * \brief an evaluation function for minimax * \param d1 first distance * \param d2 second distance * \return heuristic value. */ float eval_func(float d1, float d2) { return d1 - d2; } /** * \fn float max(float v1, float v2); * \brief max of two values * \param v1 first value * \param v2 second value * \return max value */ float max(float v1, float v2) { if (v1 < v2) { return v2; } return v1; } /** * \fn float min(float v1, float v2); * \brief min of two values * \param v1 first value * \param v2 second value * \return min value */ float min(float v1, float v2) { if (v1 < v2) { return v1; } return v2; } /** * \fn float minimax(struct graph_t *graph, WTree *player, WTree *enemy, int depth, int is_max, float alpha, float beta); * \brief Applies the minimax algorithm on the game table(graph) graph. * \param graph game table to return its value. * \param player Player's tree. * \param enemy Enemy's tree. * \param depth Depth of the minimax tree. * \param is_max (Boolean) To decide if it is max or min phase. * \param alpha The alpha value of the algorithm. * \param beta The beta value of the algorithm. * \return The heuristic value of the board. */ float minimax(struct graph_t *graph, WTree *player, WTree *enemy, int depth, int is_max, float alpha, float beta) { struct move_t m; init_weights(graph, player, s_player.player_color); init_weights(graph, enemy, !s_player.player_color); choose_method(graph, player, enemy, FLoyd_Warshall); if(depth == 0) { return eval_func(enemy->distance[enemy->end], player->distance[player->end]); } struct graph_t *graph_copy; struct set *available = available_vertices(graph); if (is_max) { if (color_is_winning(graph, s_player.player_color)){ return INFINITY; } struct set *possible = set__intersection(player->path, available); size_t path_size = set__size(possible); float best_value = -INFINITY; for (size_t j = 0; j < path_size; j++) { graph_copy = copy_graph(graph); m.c = s_player.player_color; m.m = set__value(possible, j); update_graph(graph_copy, m); update_weights(graph_copy, player, enemy, m); float value = minimax(graph_copy, player, enemy, depth - 1, 0, alpha, beta); best_value = max(best_value, value); alpha = max (alpha, best_value); free_graph(graph_copy); if (beta <= alpha) { break; } } set__free(available); set__free(possible); return best_value; } else { if (color_is_winning(graph, !s_player.player_color)){ return -INFINITY; } struct set *possible = set__intersection(enemy->path, available); size_t path_size = set__size(possible); float best_value = INFINITY; for (size_t j = 0; j < path_size; j++) { graph_copy = copy_graph(graph); m.c = !s_player.player_color; m.m = set__value(possible, j); update_graph(graph_copy, m); update_weights(graph_copy, enemy, player, m); float value = minimax(graph_copy, player, enemy, depth - 1, 1, alpha, beta); best_value = min(best_value, value); beta = min(beta, best_value); free_graph(graph_copy); if (beta <= alpha) { break; } } set__free(available); set__free(possible); return best_value; } } /** * \fn int best_move(struct graph_t *graph, WTree *player_tree, WTree *enemy_tree); * \brief Executes the minimax algorithm. * \param graph game table. * \param player_tree Player's tree. * \param enemy_tree Enemy's tree. * \return chosen vertex. */ int best_move(struct graph_t *graph, WTree *player_tree, WTree *enemy_tree) { int vertex = 0; float best_value = -INFINITY; WTree *p_tree; WTree *e_tree; for (int k = 0; k < graph->num_vertices; k++) { struct graph_t *graph_copy = copy_graph(graph); if(get_vertex_value(graph_copy, !s_player.player_color, k) == 1 || get_vertex_value(graph_copy, s_player.player_color, k) == 1) { free_graph(graph_copy); continue; } struct move_t m = {k, s_player.player_color}; p_tree = init_tree(player_tree->start, player_tree->end, player_tree->num_vertices); e_tree = init_tree(enemy_tree->start, enemy_tree->end, enemy_tree->num_vertices); init_weights(graph, p_tree, s_player.player_color); init_weights(graph, e_tree, !s_player.player_color); update_graph(graph_copy, m); update_weights(graph, p_tree, e_tree, m); choose_method(graph, p_tree, e_tree, FLoyd_Warshall); float value = minimax(graph_copy, p_tree, e_tree, 2, 0, -INFINITY, INFINITY); if (value > best_value) { best_value = value; vertex = k; } tree_free(p_tree); tree_free(e_tree); free_graph(graph_copy); } return vertex; } /** * \fn int choose_move(struct graph_t *graph, WTree *player_tree, WTree *enemy_tree); * \brief Executes the minimax algorithm and verify if the vertex chosen is in the availeble vertices. * \param graph game table. * \param player_tree Player's tree. * \param enemy_tree Enemy's tree. * \return chosen vertex (if minimax return an unavailable vertex it is chosen randomly). */ int choose_move(struct graph_t *graph, WTree *player_tree, WTree *enemy_tree) { struct move_t m; m.c = s_player.player_color; m.m = best_move(graph, player_tree, enemy_tree); if(!set__find(s_player.available_vertices, m.m)) { m.m = set__random_value(s_player.available_vertices); } return m.m; } //////////////// Player Functions //////////////// char const *get_player_name(void) { return player_name; } struct move_t propose_opening() { struct move_t m; int vertice = set__random_value(s_player.available_vertices); set__remove(s_player.available_vertices, vertice); m.c = BLACK; m.m = (size_t) vertice; update_graph(s_player.player_graph, m); return m; } int accept_opening(const struct move_t opening) { update_graph(s_player.player_graph, opening); set__remove(s_player.available_vertices, opening.m); return 0; } void initialize_graph(struct graph_t* graph) { srand((unsigned) time(NULL)); s_player.player_graph = graph; s_player.init_tree = 1; s_player.available_vertices = set__empty(); for (int i = 0; i < graph->num_vertices; i++) { if (get_vertex_value(s_player.player_graph, BLACK, i) == 0 && get_vertex_value(s_player.player_graph, WHITE, i) == 0) { set__add(s_player.available_vertices, i); } } } void initialize_color(enum color_t id) { s_player.player_color = id; } struct move_t play(struct move_t previous_move) { struct move_t m; if (s_player.init_tree) { s_player.init_tree = 0; initialize(s_player.player_graph); } set__remove(s_player.available_vertices, previous_move.m); update_graph(s_player.player_graph, previous_move); update_weights(s_player.player_graph, s_player.enemy_tree, s_player.player_tree, previous_move); m.c = s_player.player_color; m.m = choose_move(s_player.player_graph, s_player.player_tree, s_player.enemy_tree); update_graph(s_player.player_graph, m); set__remove(s_player.available_vertices, m.m); update_weights(s_player.player_graph, s_player.player_tree, s_player.enemy_tree, m); return m; } void finalize() { free_graph(s_player.player_graph); s_player.player_graph = NULL; set__free(s_player.available_vertices); s_player.available_vertices = NULL; tree_free(s_player.player_tree); s_player.player_tree = NULL; tree_free(s_player.enemy_tree); s_player.player_tree = NULL; }
C
/* ----------------------------------------------------------------------------- * Filename : Security_System.c * Author(s) : Kyle Bielby, Chris Lloyd (Team 1) * Class : EE365 (Final Project) * Due Date : 2020-11-23 * Target Board : Cora Z7-10 * Description : Multi-mode simple security system. * * This file comprises * the software for a final project for * EE365 (Advanced Digital Logic Design) at Clarkson University. * * At a high level, this system is used for verifying 4 digit * passcodes (0-9) mimicking some sort of authentication system. * There is also functionality to store and remove passcodes. * * It has three core modes (indicated by onboard LED_0): * <> MODE_1_CHECK_CODE (Led color: Blue) * -> Allows a user to enter a passcode and provides feedback * indicating whether the passcode is valid. * * <> MODE_2_SET_CODE (Led color: Yellow) * -> Allows a user to enter a passcode and provides feedback * indicating whether the passcode was stored. * * <> MODE_3_REMOVE_CODE (Led color: Purple) * -> Allows a user to enter a passcode and provides feedback * indicating whether the passcode was removed. * * To indicate whether an operation completed successfully * or not, an onboard pushbutton will flash either green or red. * * Digit Input is through a matrix keypad being controlled in * firmware. This provides a stream of 4-bit data indicating * what button is pressed (0-9 only) with all other keys and * no key pressed indicated by 0xF. * * Passcode output is through a 4-digit seven segment display * also being controlled in firmware. To drive the display, a * 16-bit number is written to the display register with * the 4 nibbles corresponding to the 4 digits. Once again, * 0-9 only with 0xF being a blank digit. * * -------------------------------------------------------------------------- */ // Includes #include <stdio.h> #include <stdbool.h> #include "xil_cache.h" #include "keypad_binary_slave.h" #include "seven_segment_display_slave.h" #include "axilab_slave_button.h" #include "axilab_slave_led.h" #include "xil_io.h" // Masks for onboard push buttons #define BUTTON_0_MASK 1 #define BUTTON_1_MASK 2 #define RESET_BUTTON_MASK BUTTON_1_MASK #define MODE_BUTTON_MASK BUTTON_0_MASK // Masks for individual colors of each onboard led #define LED_0_BLUE_MASK 0b000001 #define LED_0_GREEN_MASK 0b000010 #define LED_0_RED_MASK 0b000100 #define LED_1_BLUE_MASK 0b001000 #define LED_1_GREEN_MASK 0b010000 #define LED_1_RED_MASK 0b100000 #define LED_0_PURPLE_MASK LED_0_BLUE_MASK | LED_0_RED_MASK #define LED_0_YELLOW_MASK LED_0_GREEN_MASK | LED_0_RED_MASK // Masks for peripheral addresses #define KEYPAD_BASE_ADDR 0x43c00000 #define ONBOARD_PUSH_BASE_ADDR 0x43c10000 #define SEVEN_SEGMENT_BASE_ADDR 0x43c20000 #define RGB_LEDS_BASE_ADDR 0x43c30000 /******************************************************************************* * Mode related functionality ******************************************************************************/ // An enum to define the operating modes (states) of the program typedef enum { MODE_1_CHECK_CODE = 0x1, MODE_2_SET_CODE = 0x2, MODE_3_REMOVE_CODE = 0x3 } Mode; #define DEFAULT_MODE MODE_1_CHECK_CODE // The current mode of the program Mode currentMode; // Toggles the current mode of operation void toggleMode(); // Sets the current mode of operation void setMode(Mode mode); /******************************************************************************* * Passcode related functionality ******************************************************************************/ #define PASSCODE_LENGTH 4 #define MAX_NUM_STORED_PASSCODES 100 // Master passcode for system (cannot be changed) const uint8_t MASTER_PASSCODE[PASSCODE_LENGTH] = {0,0,0,0}; // Location to store valid passcodes uint8_t storedPasscodes[MAX_NUM_STORED_PASSCODES][PASSCODE_LENGTH]; uint8_t currentStoredPasscodesIndex; // A location to store the current keypad entry (0xF results in a blank digit) uint8_t currentPasscode[PASSCODE_LENGTH]; uint8_t currentPasscodeIndex; // Clears and resets storedPasscodes void resetStoredPasscodes(); // Clears and resets currentPasscode void resetCurrentPasscode(); // Adds the current passcode to storedPasscodes bool storePasscode(uint8_t passcode[]); // Removes the current passcode from storedPasscodes bool removePasscode(uint8_t passcode[]); // Add a digit to currentPasscode bool storeCurrentPasscodeDigit(uint8_t digitData); // Checks if passcode is equal to MASTER_PASSCODE bool isMasterPasscode(uint8_t passcode[]); // Checks if passcode exists in storedPasscodes bool isExistingPasscode(uint8_t passcode[]); // Checks if storedPasscodes is full bool isStoredPasscodesFull(); // Checks if currentPasscode is complete bool isCurrentPasscodeComplete(); /******************************************************************************* * Onboard LED related functionality ******************************************************************************/ // Sets the leds void setLEDS(uint8_t ledData); // Sets mode LED color for current mode of operation void setModeLED(); // Flashes the status led a certain color void flashStatusLED(uint8_t statusColor); /******************************************************************************* * Miscellaneous functionality ******************************************************************************/ bool previousResetButtonState = false; // Determines if reset button is pressed bool isResetButtonPressed(); // Determines if reset button was released bool isResetButtonReleased(); // Determines if mode button has been pressed bool isModeButtonPressed(); // Determines if keypad has been pressed bool isKeypadPressed(); // Gets the current keypad key pressed uint8_t getKeypadValue(); // Displays code to seven segment display void displayPasscode(uint8_t passcode[]); // Delay for ms milliseconds void delayMS(uint16_t ms); // Reset the system void resetSystem(); // Clear all outputs void clearOutputs(); /* * This function is the main function of the project. * * Arguments: None * * Return: * - (int): Integer status of function exit. (0 -> good, anything else -> error) */ int main(void) { // Reset passcodes and current mode resetSystem(); while (true) // Main program execution loop { if (isResetButtonPressed()) // Is reset button being held down? { clearOutputs(); // Clear all outputs } if (isResetButtonReleased()) // Is reset button being released (falling edge)? { resetSystem(); // Reset passcodes and mode delayMS(250); // Delay program flashStatusLED(LED_1_GREEN_MASK); // Flash green status led } else if (isModeButtonPressed()) // Is mode button being pressed? { toggleMode(); // Toggle the current mode and reset passcode delayMS(500); // Delay 500 ms } else if (isKeypadPressed()) // Is a key on keypad being pressed? { // Add to currentPasscode storeCurrentPasscodeDigit(getKeypadValue()); // Delay program to prevent same press being registered constantly delayMS(450); // Check if full passcode has been entered if (isCurrentPasscodeComplete()) { switch (currentMode) { case MODE_1_CHECK_CODE: if (isMasterPasscode(currentPasscode) || isExistingPasscode(currentPasscode)) { // Flash green status led // (Indicating passcode valid) flashStatusLED(LED_1_GREEN_MASK); } else { // Flash red status led // (Indicating passcode invalid) flashStatusLED(LED_1_RED_MASK); } break; case MODE_2_SET_CODE: if (!isMasterPasscode(currentPasscode) && !isExistingPasscode(currentPasscode) && !isStoredPasscodesFull()) { // Flash green status led // (Indicating passcode stored) flashStatusLED(LED_1_GREEN_MASK); storePasscode(currentPasscode); } else { // Flash red status led // (Indicating passcode not stored) flashStatusLED(LED_1_RED_MASK); } break; case MODE_3_REMOVE_CODE: if (!isMasterPasscode(currentPasscode) && isExistingPasscode(currentPasscode)) { // Flash green status led // (Indicating passcode removed) flashStatusLED(LED_1_GREEN_MASK); removePasscode(currentPasscode); } else { // Flash red status led // (Indicating passcode not removed) flashStatusLED(LED_1_RED_MASK); } break; default: break; } resetCurrentPasscode(); // Reset current passcode } } } // Return with no errors return 0; } /* * This function toggles the current mode. * * Return: None (void) */ void toggleMode() { // Toggle the current mode switch (currentMode) { case MODE_1_CHECK_CODE: setMode(MODE_2_SET_CODE); // Change mode to check mode break; case MODE_2_SET_CODE: setMode(MODE_3_REMOVE_CODE); // Change mode to set mode break; case MODE_3_REMOVE_CODE: setMode(MODE_1_CHECK_CODE); // Change mode to remove mode break; default: setMode(DEFAULT_MODE); break; } } /* * This function sets the current mode, changes mode led, and * resets current entry code. * * Return: None (void) */ void setMode(Mode mode) { // Set the current mode currentMode = mode; // Set the mode LED to the current mode color setModeLED(); // Reset currentPasscode to null values of 0xF resetCurrentPasscode(); } /* * This function resets storedPasscodes. * * Return: None (void) */ void resetStoredPasscodes() { // Clear any stored passcodes and reset index memset(storedPasscodes, 0xF, sizeof(storedPasscodes[0][0]) * MAX_NUM_STORED_PASSCODES * PASSCODE_LENGTH); currentStoredPasscodesIndex = 0; } /* * This function resets currentPasscode. * * Return: None (void) */ void resetCurrentPasscode() { // Clear current passcode memset(currentPasscode, 0xF, sizeof(currentPasscode[0]) * PASSCODE_LENGTH); currentPasscodeIndex = 0; // Display the current passcode to the seven segment display displayPasscode(currentPasscode); } /* * This function stores passcode to storedPasscodes. * * Param: passcode: The passcode to store. * Return: (bool): Passcode stored successfully? */ bool storePasscode(uint8_t passcode[]) { // Ensure storedPasscodes is not full if (isStoredPasscodesFull()) { return false; } // Add passcode and increment index storedPasscodes[currentStoredPasscodesIndex][0] = passcode[0]; storedPasscodes[currentStoredPasscodesIndex][1] = passcode[1]; storedPasscodes[currentStoredPasscodesIndex][2] = passcode[2]; storedPasscodes[currentStoredPasscodesIndex][3] = passcode[3]; currentStoredPasscodesIndex++; return true; } /* * This function removes passcode from storedPasscodes. * * Param: passcode: The passcode to remove. * Return: (bool): Passcode removed successfully? */ bool removePasscode(uint8_t passcode[]) { // Ensure passcode in storedPasscodes if (!isExistingPasscode(passcode)) { return false; } // Find passcode index int i = 0; for (; i < currentStoredPasscodesIndex; i++) { if ((passcode[0] == storedPasscodes[i][0]) && (passcode[1] == storedPasscodes[i][1]) && (passcode[2] == storedPasscodes[i][2]) && (passcode[3] == storedPasscodes[i][3])) { break; } } // Shift all elements back and remove passcode for (; i < currentStoredPasscodesIndex - 1; i++) { storedPasscodes[i][0] = storedPasscodes[i + 1][0]; storedPasscodes[i][1] = storedPasscodes[i + 1][1]; storedPasscodes[i][2] = storedPasscodes[i + 1][2]; storedPasscodes[i][3] = storedPasscodes[i + 1][3]; } // Blank out last code currentStoredPasscodesIndex--; storedPasscodes[currentStoredPasscodesIndex][0] = 0xF; storedPasscodes[currentStoredPasscodesIndex][1] = 0xF; storedPasscodes[currentStoredPasscodesIndex][2] = 0xF; storedPasscodes[currentStoredPasscodesIndex][3] = 0xF; return true; } /* * This function stores a digit to currentPasscode. * * Param: digitData: The digit to store. * Return: (bool): Digit stored successfully? */ bool storeCurrentPasscodeDigit(uint8_t digitData) { // Ensure passcode is not complete if (isCurrentPasscodeComplete()) { return false; } // Store passcode currentPasscode[currentPasscodeIndex++] = (digitData & 0xF); // Display the current passcode to the seven segment display displayPasscode(currentPasscode); return true; } /* * This function checks if passcode is equal to MASTER_PASSCODE. * * Param: passcode: The passcode to check. * Return: (bool): passcode equals MASTER_PASSCODE? */ bool isMasterPasscode(uint8_t passcode[]) { return ((passcode[0] == MASTER_PASSCODE[0]) && (passcode[1] == MASTER_PASSCODE[1]) && (passcode[2] == MASTER_PASSCODE[2]) && (passcode[3] == MASTER_PASSCODE[3])); } /* * This function checks if passcode exists in storedPasscodes. * * Param: passcode: The passcode to check. * Return: (bool): passcode exists in storedPasscodes? */ bool isExistingPasscode(uint8_t passcode[]) { for (int i = 0; i < currentStoredPasscodesIndex; i++) { if ((passcode[0] == storedPasscodes[i][0]) && (passcode[1] == storedPasscodes[i][1]) && (passcode[2] == storedPasscodes[i][2]) && (passcode[3] == storedPasscodes[i][3])) { return true; } } return false; } /* * This function checks if storedPasscodes is full. * * Return: (bool): storedPasscodes is full? */ bool isStoredPasscodesFull() { return (currentStoredPasscodesIndex == MAX_NUM_STORED_PASSCODES); } /* * This function checks if currentPasscode is complete. * * Return: (bool): currentPasscode is complete? */ bool isCurrentPasscodeComplete() { return (currentPasscodeIndex == PASSCODE_LENGTH); } /* * This function writes to the onboard leds. * * Param: ledData: Data to write to leds (lower 6 bits only). * Return: None (void) */ void setLEDS(uint8_t ledData) { AXILAB_SLAVE_LED_mWriteReg(RGB_LEDS_BASE_ADDR, 0, (ledData & 0x3F)); } /* * This function sets the LED color for the current mode. * * Return: None (void) */ void setModeLED() { switch (currentMode) { case MODE_1_CHECK_CODE: setLEDS(LED_0_BLUE_MASK); break; case MODE_2_SET_CODE: setLEDS(LED_0_YELLOW_MASK); break; case MODE_3_REMOVE_CODE: setLEDS(LED_0_PURPLE_MASK); break; default: break; } } /* * This function flashes the status led a certain color indicating the * status of an operation. * * Param: statusColor: The color to flash status led with. * Return: None (void) */ void flashStatusLED(uint8_t statusColor) { // Ensure only led1 is being set statusColor = (statusColor & 0b111000); // Determine mode color uint8_t modeColor = 0; switch (currentMode) { case MODE_1_CHECK_CODE: modeColor = LED_0_BLUE_MASK; break; case MODE_2_SET_CODE: modeColor = LED_0_YELLOW_MASK; break; case MODE_3_REMOVE_CODE: modeColor = LED_0_PURPLE_MASK; break; } // Flash status led twice (total of 0.5 seconds) for (int i = 0; i < 2; i++) { setLEDS(modeColor | statusColor); // Flash status led on delayMS(125); // Delay program setLEDS(modeColor); // Flash status led off delayMS(125); // Delay program } } /* * This function determines if the reset button is being pressed. * * Return: (bool): Reset button is being pressed? */ bool isResetButtonPressed() { return (AXILAB_SLAVE_BUTTON_mReadReg(ONBOARD_PUSH_BASE_ADDR, 0) & RESET_BUTTON_MASK); } /* * This function determines if the reset button has been released. This is * indicated by a falling edge on button state. * * Return: (bool): Reset button has been released? */ bool isResetButtonReleased() { // Get whether the reset button was pressed bool currentResetButtonState = isResetButtonPressed(); // Check if a falling edge has occurred bool fallingEdgeReset = (previousResetButtonState && !currentResetButtonState); // Set the previous state to the current state previousResetButtonState = currentResetButtonState; return fallingEdgeReset; } /* * This function determines if the mode button is being pressed. * * Return: (bool): Mode button is being pressed? */ bool isModeButtonPressed() { return (AXILAB_SLAVE_BUTTON_mReadReg(ONBOARD_PUSH_BASE_ADDR, 0) & MODE_BUTTON_MASK); } /* * This function determines if a key on the keypad is being pressed. * * Return: (bool): Key on the keypad is being pressed? */ bool isKeypadPressed() { return (KEYPAD_BINARY_SLAVE_mReadReg(KEYPAD_BASE_ADDR, 0) != 0xF); } /* * This function gets the keypad value that is being pressed. * * Return: (uint8_t): Digit value of keypad keypress. */ uint8_t getKeypadValue() { // Ensure keypad is pressed if (!isKeypadPressed()) { return 0xF; } // Return value of key press return (KEYPAD_BINARY_SLAVE_mReadReg(KEYPAD_BASE_ADDR, 0) & 0xF); } /* * This function displays a passcode to the seven segment display. * * Param: passcode: The passcode to display. * Return: None (void) */ void displayPasscode(uint8_t passcode[]) { SEVEN_SEGMENT_DISPLAY_SLAVE_mWriteReg(SEVEN_SEGMENT_BASE_ADDR, 0, (passcode[0] << 12) | (passcode[1] << 8) | (passcode[2] << 4) | (passcode[3])); } /* * This function delays (blocking) by approximately (ms) milliseconds. * * Param: ms: The number of milliseconds to delay by. * Return: None (void) */ void delayMS(uint16_t ms) { for (int i = 0; i < ms; i++) { for(int i = 0; i < 80000; i++) {} } } /* * This function clears all outputs including the onboard leds and seven * segment display. * * Return: None (void) */ void clearOutputs() { setLEDS(0); uint8_t blankPasscode[] = {0xF, 0xF, 0xF, 0xF}; displayPasscode(blankPasscode); } /* * This function resets the system by reseting the current and stored * passcode, and reseting the current mode. * * Return: None (void) */ void resetSystem() { // Initialize storedPasscodes to null values of 0xF resetStoredPasscodes(); // Initialize currentPasscode to null values of 0xF resetCurrentPasscode(); // Initialize current mode to default mode setMode(DEFAULT_MODE); }
C
/** * Pointers Gone Wild Lab * CS 241 - Spring 2018 */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "callbacks.h" #include "part3-functions.h" #include "vector.h" vector *vector_map(vector *input, mapper map) { // TODO implement this char* temp; vector *output_vector = string_vector_create(); VECTOR_FOR_EACH(input, elem, { if (_it != _iend){ temp = map(elem); vector_push_back(output_vector,temp); free(temp); //free(elem); } }); return output_vector; } void *vector_reduce(vector *input, reducer reduce, void *acc) { // TODO implement this //void* acc2= (void*)malloc(sizeof(int)); VECTOR_FOR_EACH(input, elem, { if (_it != _iend){ acc = reduce(elem,acc); // free(elem); } }); //free(acc); return acc; } void *length_reducer(char *input, void *output) { // TODO implement this //static int x = 0; int *o ; int size = 0; while (*input++) size++; if (output == NULL){ output = (void*)malloc(sizeof(int)); o = output; *o = 0; } o = output; *o = *(int*)output + size; //printf("%d:%d\n",size,*o); //*n = *n+*(int*)output; return output; } void *concat_reducer(char *input, void *output) { // TODO implement this char*t = input ; char*o ; int size = 0; while (*t++) size++; //printf("%s:%d\n",input,size); if(output == NULL){ // puts("ttttt"); output = (void*)calloc(size+1,sizeof(char*)); o = output; while(*input){ *o = *input; o++; input++; } }else{ o = (char*)output; while(*o){ // printf("0:%c\n",*o); size++;o++; } output = (void*)realloc(output,size*sizeof(char*)+1); o = output; while(*o){ // printf("0:%c\n",*o); o++; } //printf("%d\n",size); while(*input){ *o = *input; //printf("c:%c\n",*input); o++; input++; } } return output; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <dirent.h> char * strdub(char * str){ int len = strlen(str); char * buff = malloc(sizeof(char) * len); int i = 0; for(i=0; i<len; i++){ buff[i] = str[i]; } return buff; } int main(int argc, char** argv){ if(argc != 2){ printf("no program to search for\n"); exit(0); } char * programName = argv[1]; char * readSystemPath = getenv("PATH"); int systemPathLen = strlen(readSystemPath); char * systemPath = malloc(systemPathLen * sizeof(char)); strcpy(systemPath,readSystemPath); //printf("path: %s\nlen: %i\n\n",systemPath,systemPathLen); //count ":" unsigned int i = 0; unsigned int anz = 0; for(i = 0; i < strlen(systemPath) ; i++){ //printf("compare: %c(%i) == %c(%i)\n",systemPath[i],systemPath[i],':',':'); if(systemPath[i] == ':'){ anz++; } } //printf("path: %s\nlen: %i\nanz: %i\n",systemPath,systemPathLen,anz); char ** paths = malloc((anz+1)*sizeof(char*)); //cut paths for(i=0;i<anz;i++){ int j = 0; for(j=0;systemPath[j] != ':'; j++){} char * path = malloc(j*sizeof(char)); strncpy(path,systemPath,j); paths[i] = path; systemPath = systemPath + ((j+1)*sizeof(char)); } char * path = malloc(strlen(systemPath)*sizeof(char)); strcpy(path,systemPath); paths[anz] = path; //search in folders for(i=0;i<=anz;i++){ //printf(" %s\n",paths[i]); DIR* curDir = opendir(paths[i]); struct dirent* dirEntry = NULL; while((dirEntry = readdir(curDir)) != NULL){ if( strcmp(dirEntry->d_name, programName) == 0) { printf("%s/%s\n", paths[i], dirEntry->d_name); } } if(closedir(curDir) != 0){ printf("error while closing directory\n"); } } return 0; }
C
#include<stdio.h> int gcd(int,int); int main() { int a,b,i,j; printf("Enter two integers:"); scanf("%d %d",&a,&b); i=gcd(a,b); printf("gcd of a and b is:%d\n",i); return 0; } int gcd(int m,int n) { if (n != 0) return gcd(n, m % n); else return m; }
C
/* ** recup_argv.c for recup_env in /home/danilo_d/rendu/PSU_2014_minishell1 ** ** Made by Danilov Dimitri ** Login <danilo_d@epitech.net> ** ** Started on Thu Jan 15 13:40:24 2015 Danilov Dimitri ** Last update Sun Feb 1 17:13:45 2015 Danilov Dimitri */ #include "my.h" int find_bad_arg(t_arg *arg) { int i; int j; int ok; i = -1; while (arg->argv[++i] != NULL) { j = -1; ok = 0; while (arg->argv[i][++j] != '\0') { if (arg->argv[i][j] != ' ') ok = 1; } if (ok != 1) { arg->argv[i] = NULL; return (0); } } return (0); } void recup_argv_2(t_arg *arg, char *line, char c) { while (arg->i < my_strlen(line)) { while (line[arg->i] == c) arg->i++; arg->begin = arg->i; while (line[arg->i] != c && arg->i < my_strlen(line)) arg->i++; arg->end = arg->i; arg->i = arg->begin; arg->argv[arg->nbr_param] = my_strndup(&line[arg->i], arg->end - arg->begin); arg->nbr_param++; arg->i = arg->end; arg->i++; } } char **recup_argv(char *line, char c) { t_arg arg; arg.argv = xmalloc(1000); arg.nbr_param = 0; arg.i = 0; while (line[arg.i] == c) arg.i++; arg.begin = arg.i; while (line[arg.i] != c && arg.i < my_strlen(line)) arg.i++; arg.end = arg.i; arg.argv[arg.nbr_param] = my_strndup(&line[arg.begin], arg.end - arg.begin); arg.nbr_param++; arg.i = arg.end; recup_argv_2(&arg, line, c); arg.argv[arg.nbr_param] = NULL; find_bad_arg(&arg); return (arg.argv); } void recup_path(t_struct *tool, char **env) { int i; char *path; i = -1; while ((my_strncmp(env[++i], "PATH=", 5)) != 0 && env[i + 1] != NULL) ; if (env[i + 1] == NULL) { my_putstr("Variable PATH missing\n"); tool->path = xmalloc(10); tool->path[0] = my_strdup("/bin"); } else { path = my_strdup(&env[i][5]); tool->path = recup_argv(path, ':'); } i = -1; while (my_strncmp(env[++i], "HOME=", 5) != 0 && env[i + 1] != NULL); tool->prompt.home = my_strdup(&env[i][5]); if (env[i + 1] == NULL) { my_putstr("Variable HOME unset\n"); tool->prompt.home = my_strdup("/home/"); } }
C
/* In case of Java language, the main class must be named as "M"+Problem ID */ #include<stdio.h> int main() { double r; scanf("%lf",&r); printf("A=%.4lf\n",3.14159*r*r); return 0; }
C
#include "WiFi.h" #include <FS.h> #include <SPIFFS.h> #define BOUNDARY "xx---xx--xx" #define TIMEOUT 250000 #define BUFSIZE 100 uint8_t buffer[BUFSIZE]; const char* host = "knock.aksharsolanki.com"; String body(String content , String message); String header(size_t length); void sendpicture() { File file = SPIFFS.open("/photo.jpg", FILE_READ); if (!file) { Serial.println("Failed to open file in reading mode"); return; } String bodyTxt = body("message","Picture"); String bodyPic = body("imageFile","Picture"); String bodyEnd = String("--")+BOUNDARY+String("--\r\n"); size_t allLen = bodyTxt.length()+bodyPic.length()+file.size()+bodyEnd.length(); String headerTxt = header(allLen); const int httpPort = 80; WiFiClient client; if (!client.connect(host, httpPort)) { Serial.println("connection failed"); file.close(); return; } Serial.print("yay"); client.print(headerTxt+bodyTxt+bodyPic); Serial.print(headerTxt+bodyTxt+bodyPic); while (file.available()){ int cc = file.read(buffer, BUFSIZE); client.write(buffer, cc); Serial.print((char*)buffer); } Serial.print("\r\n"+bodyEnd); client.print("\r\n"+bodyEnd); file.close(); delay(20); long tOut = millis() + TIMEOUT; while(client.connected() && tOut > millis()) { if (client.available()) { String serverRes = client.readStringUntil('\r'); Serial.println(serverRes); } } Serial.println("isdj"); return; } String header(size_t length) { String data; data = F("POST /images HTTP/1.1\r\n"); data += F("cache-control: no-cache\r\n"); data += F("Content-Type: multipart/form-data; boundary="); data += BOUNDARY; data += "\r\n"; data += F("User-Agent: PostmanRuntime/6.4.1\r\n"); data += F("Accept: */*\r\n"); data += F("Host: "); data += host; data += F("\r\n"); data += F("accept-encoding: gzip, deflate\r\n"); data += F("Connection: keep-alive\r\n"); data += F("Content-length: "); data += String(length); data += "\r\n"; data += "\r\n"; return(data); } String body(String content , String message) { String data; data = "--"; data += BOUNDARY; data += F("\r\n"); if(content=="imageFile") { data += F("Content-Disposition: form-data; name=\"file\"; filename=\"picture.jpg\"\r\n"); data += F("Content-Transfer-Encoding: binary\r\n"); data += F("Content-Type: image/jpeg\r\n"); data += F("\r\n"); } else { data += "Content-Disposition: form-data; name=\"" + content +"\"\r\n"; data += "\r\n"; data += "help"; data += "\r\n"; } return(data); }
C
#include <mqueue.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <signal.h> #include <inttypes.h> #include <string.h> #include "msg.h" // This handler will be called when the queue // becomes non-empty. void handler (int sig_num) { printf ("Received sig %d.\n", sig_num); } void main (int argc, char **argv) { if (argc != 3) { printf("The token and message to post must be passed.\n usage: %s <token> <message>", argv[0]); _Exit(EXIT_FAILURE); } struct mq_attr attr, old_attr; // To store queue attributes struct sigevent sigevent; // For notification mqd_t mqdes; // Message queue descriptors char buf[MSG_SIZE]; // A good-sized buffer unsigned int prio; // Priority struct Message msgObj; // The message to send mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; // First we need to set up the attribute structure attr.mq_maxmsg = 10; attr.mq_msgsize = MSG_SIZE; attr.mq_flags = 0; buf[MSG_SIZE - 1] = '\0'; strcpy(msgObj.token, argv[1]); strcpy(msgObj.text, argv[2]); packMesageInString(&msgObj, buf); // Open a queue with the attribute structure mqdes = mq_open ("/qtest", O_RDWR | O_CREAT, mode, &attr); // Get the attributes for the test queue mq_getattr (mqdes, &attr); // We want to be notified when something is there signal (SIGUSR1, handler); sigevent.sigev_signo = SIGUSR1; // Write the message if (mq_send(mqdes, buf, MSG_SIZE, 0) == -1) { perror("mqsend() failed."); } // Close all open message queue descriptors mq_close (mqdes); }
C
//Bibliotecas #include <stdio.h> #include <stdlib.h> #include <locale.h> //Estrutura struct str_no { char dado; int valNo; int esquerda; int direita; int pai; }; //Vari�veis globais char vetorValores[9] = {'+','*','5','-','+','6','3','4','1'}; struct str_no arvore[16]; //Prototipa��o void menu_mostrar(void); void arvore_popula(void); void resultado(void); //Fun��o principal int main(void) { setlocale(LC_ALL, "Portuguese"); int opt = -1, temp; char pai, no, lado; do { menu_mostrar(); scanf("%d", &opt); switch (opt) { case 1: arvore_popula(); break; case 2: resultado(); printf("Resultado final: %d\n", arvore[0].valNo); system("pause"); break; } } while (opt!=0); return 0; } //Inserir n�s na �rvore void arvore_popula() { int pai; int filho; arvore[0].dado = '+'; arvore[0].pai = -1; arvore[0].valNo = -1; arvore[0].esquerda = -1; arvore[0].direita = -1; filho = 1; arvore[0].esquerda = filho; arvore[filho].dado = '*'; arvore[filho].pai = pai; arvore[filho].valNo = -1; arvore[filho].esquerda = -1; arvore[filho].direita = -1; filho = 2; arvore[0].direita = filho; arvore[filho].dado = '5'; arvore[filho].pai = pai; arvore[filho].valNo = 5; arvore[filho].esquerda = -1; arvore[filho].direita = -1; filho = 3; arvore[1].esquerda = filho; arvore[filho].dado = '-'; arvore[filho].pai = pai; arvore[filho].esquerda = -1; arvore[filho].direita = -1; filho = 4; arvore[1].direita = filho; arvore[filho].dado = '+'; arvore[filho].pai = pai; arvore[filho].valNo = -1; arvore[filho].esquerda = -1; arvore[filho].direita = -1; filho = 7; arvore[3].esquerda = filho; arvore[filho].dado = '6'; arvore[filho].pai = pai; arvore[filho].valNo = 6; arvore[filho].esquerda = -1; arvore[filho].direita = -1; filho = 8; arvore[3].direita = filho; arvore[filho].dado = '3'; arvore[filho].pai = pai; arvore[filho].valNo = 3; arvore[filho].esquerda = -1; arvore[filho].direita = -1; filho = 9; arvore[4].esquerda = filho; arvore[filho].dado = '4'; arvore[filho].pai = pai; arvore[filho].valNo = 4; arvore[filho].esquerda = -1; arvore[filho].direita = -1; filho = 10; arvore[4].direita = filho; arvore[filho].dado = '1'; arvore[filho].pai = pai; arvore[filho].valNo = 1; arvore[filho].esquerda = -1; arvore[filho].direita = -1; } // Calcular equa��es da �rvore void resultado() { int i; for (i = 15; i >= 0; i--) { if (arvore[i].dado=='+') { arvore[i].valNo = arvore[2*i+1].valNo + arvore[2*i+2].valNo; printf("%d + %d = %d\n", arvore[2*i+1].valNo,arvore[2*i+2].valNo, arvore[i].valNo); } if (arvore[i].dado=='-') { arvore[i].valNo = arvore[2*i+1].valNo - arvore[2*i+2].valNo; printf("%d - %d = %d\n", arvore[2*i+1].valNo,arvore[2*i+2].valNo, arvore[i].valNo); } if (arvore[i].dado=='*') { arvore[i].valNo = arvore[2*i+1].valNo * arvore[2*i+2].valNo; printf("%d * %d = %d\n", arvore[2*i+1].valNo,arvore[2*i+2].valNo, arvore[i].valNo); } if (arvore[i].dado=='/') { arvore[i].valNo = arvore[2*i+1].valNo / arvore[2*i+2].valNo; printf("%d / %d = %d\n", arvore[2*i+1].valNo,arvore[2*i+2].valNo, arvore[i].valNo); } } } //Desenha o menu na tela void menu_mostrar(void) { system("cls"); int i; for (i = 0; i < 15; i++) { printf("| %c ", arvore[i].dado); } printf("| -- Dados\n"); for (i = 0; i < 15; i++) { printf("----", i); } printf("\n"); for (i = 0; i < 15; i++) { if (i<10) printf("| %d ", i); else printf("| %d", i); } printf("| -- �ndice", i); printf("\n\n1 - Popular �rvore"); printf("\n2 - Calcular e exibir resultado"); printf("\n0 - Sair...\n\nOpcao: "); }
C
#include <stdio.h> #include <stdlib.h> int main(int argc, char **argv){ int i, j, input, sum = 0; int subject, student; int **score_board; /* score_board[subject][student] 배열을 만들 예정이다. */ printf("과목 수를 입력해주세요. : "); scanf("%d", &subject); printf("학생 수를 입력해주세요. : "); scanf("%d", &student); score_board = (int **)malloc(sizeof(int *) * subject); for(i = 0; i < subject; i++){ score_board[i] = (int *)malloc(sizeof(int) * student); } for(i = 0; i < subject; i++){ printf("%d번째 과목에 대한 학생들의 성적을 입력해주세요. \n", i + 1); for(j = 0; j < student; j++){ printf("%d번째 학생의 성적 : ", j + 1); scanf("%d", &input); score_board[i][j] = input; } } for(i = 0; i < subject; i++){ sum = 0; for(j = 0; j < student; j++){ sum += score_board[i][j]; } printf("%d번째 과목의 총 점수 : %d 점 \n", i + 1, sum); printf("%d번째 과목의 평균 점수 : %d 점 \n\n", i + 1, sum / student); } /* 메모리 누수 방지를 위한 free */ for(i = 0; i < subject; i++){ free(score_board[i]); } free(score_board); return 0; }
C
#include "bmp.h" #include "uquantize.h" int main(int argc, char *argv[]) { if(argc < 3) { printf("Blad przy wpisywaniu argumentow."); return 2; } char *image = get_image(argv[1]); display(image); int levels = atoi(argv[3]); if(levels > 255) { printf("Za duza wartosc levels."); return 3; } uquantize(image, levels); save_image(image, argv[2]); return 0; }
C
// Gisela Neira // C++ Basics E228 // * Programm 02.03.01 der C/C++ Programmierung // * wchar_t #include <stdio.h> #include <locale.h> #include <wchar.h> #define LONG 3 int main() { wchar_t text1; char text2; wprintf(L"Eingabe: \n"); wscanf(L"%c", &text1); wprintf(L"Ausgabe: %c\n", text1); printf("Eingabe: \n"); scanf("%c", &text1); printf("Ausgabe: %c\n", text1); printf("Eingabe: \n"); scanf("%c", &text2); printf("Ausgabe: %c\n", text2); return 0; }
C
/* * 3 instances of the same thread */ #include <stdio.h> #include <string.h> #include <pthread.h> #include <unistd.h> #define TASK 300000000 long int sum; long int *p; void * u_thr() { long int lsum = 0; for (; lsum < TASK; ) { lsum += 1; } *p += lsum; printf("partial from thread with tid %d\n", pthread_self()); printf("lsum = %d; *p = %d\n\n", lsum, *p); pthread_exit((void *)0); } int main() { char c; int err; pthread_t tid1, tid2, tid3; p = &sum; err = pthread_create(&tid1, NULL, u_thr, NULL); if (err != 0) printf("can't create thread 1: %s\n", strerror(err)); err = pthread_create(&tid2, NULL, u_thr, NULL); if (err != 0) printf("can't create thread 2: %s\n", strerror(err)); err = pthread_create(&tid3, NULL, u_thr, NULL); if (err != 0) printf("can't create thread 3: %s\n", strerror(err)); c = getchar(); printf("sum = %d\n", sum); }
C
/************************************************************************* * File Name : 62.c * Author : unasm * Mail : unasm@sina.cn * Last_Modified: 2015-05-17 19:05:12 ************************************************************************/ #include<stdio.h> int line[10000]; int uniquePaths(int m, int n) { if(m <= 0 || n <= 0) return 0; for(int i = 0;i < m;i++) { line[i] = 1; } for(int i = 1;i < n;i++) { for(int j = 1;j < m;j++) { line[j] = line[j] + line[j-1]; } } return line[m - 1]; } int main(int argc, const char *argv[]) { printf("%d\n", uniquePaths(3,3)); return 0; }
C
/* File c_comparator.c */ #include "comparator.h" int comparator(char* a, char* b) { int i = 0; while((a[i] != '\0')&&(b[i] != '\0')) { if (a[i] > b[i]) { return 1; } else { if (a[i] < b[i]) { return 0; } } i++; } if (a[i] == '\0') { return 0; } return 1; }
C
#include <msp430.h> /* * HARDWARE PWM 5529. * * Created on: Oct 10, 2017 * Last Edited: Oct 10, 2017 * Author: Tyler Brady */ int main(void) { WDTCTL = WDTPW | WDTHOLD; // stop watchdog timer P2DIR |= BIT0; // Set P2.0 to output direction P4DIR |= BIT7; // Set P4.7 to output P2SEL |= BIT0; // Outputs PWM to P2.0, must then connect to 1.0. P1OUT |= BIT1; // Set P1.1 as a high P1REN |= BIT1; // Enable pull up resistor on P1.1 P1IE |= BIT1; // P1.1 interrupt enabled P1IES |= BIT1; // P1.1 Hi/lo edge P1IFG &= ~BIT1; // P1.1 IFG cleared TA1CCTL0 = CCIE; // CCR0 interrupt enabled TA1CCR0 = 16384; //resets timer at 16384 cycles TA0CCTL1 = OUTMOD_7;//SET/RESET MODE TA0CTL = TBSSEL_2 + MC_1; //SMCLK, up mode TA0CCR0 = 1000; //Full Cycle TA0CCR1 = 500; //Sets the duty cycle to 50% _BIS_SR(CPUOFF + GIE); // Enter LPM0 w/ interrupt while(1) { } } #pragma vector = TIMER1_A0_VECTOR //Creating timer A0 as an interrupt vector __interrupt void Timer1_A (void) //Deals with slight button bounce issue while also turning off the light after a set time. { P1IE |= BIT1; //Enables P1.1 interrupt TA1CTL = 0x0000; //Disables and resets Timer A0 P1IFG &= ~BIT1; //Disables interrupt flag P4OUT &= ~BIT7; //Disables P4.7 } #pragma vector=PORT1_VECTOR __interrupt void Port_1(void) { P4OUT |= BIT7; //Enables P4.7 if(TA0CCR1 >= 1000)//Logic to increase the duty cycle by 10% { TA0CCR1 = 0; } else { TA0CCR1 += 100; } TA1CTL = TASSEL_1 | MC__UP; // AClock, Up mode P1IE &= ~BIT1; //Disables interrupt on P5.6 P1IFG &= ~BIT1; //Disables interrupt flag P1OUT |= BIT0; //Enables P1.0 }
C
#ifndef UASDK_BUFFER_H_ #define UASDK_BUFFER_H_ #include <stdint.h> #include <UASDK_defs.h> #include <wchar.h> #ifdef __cplusplus extern "C" { #endif typedef struct { union { uint8_t *pbytes; uint16_t *pword; char* pstring; wchar_t* pwstring; } head; UASDK_caplen_t caplen; uint8_t buf[0]; // raw buffer region } UASDK_buffer_t, *pUASDK_buffer_t; typedef const UASDK_buffer_t *pcUASDK_buffer_t; /*! \brief create a new buffer object \param capacity [in] The capacity of the buffer counted in bytes \param ppbuffer [out] pointer pointer to the buffer object \return errno */ int UASDK_buffer_new(uint8_t capacity, pUASDK_buffer_t *ppbuffer); /*! \brief clear the buffer \param buffer [in,out] The buffer object to clear. */ void UASDK_buffer_clear(pUASDK_buffer_t buffer); #ifdef __cplusplus } #endif #endif /*UASDK_BUFFER_H_ */
C
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* removeElements(struct ListNode* head, int val) { if(!head) return head; struct ListNode* temp=NULL; while(head!=NULL && head->val==val) { temp=head; head=head->next; free(temp); } if(head==NULL) return head; else { struct ListNode* p=head; while(p!=NULL && p->next!=NULL ) { if(p->next->val==val) { p->next=p->next->next; } else p=p->next; } } return head; }
C
#include <cstdio> #include <cmath> inline long long gcd_extend(int &a, int b, long long *x, long long *y) { static long long r, t; if (b == 0) { *x = 1, *y = 0; return a; } else { r = gcd_extend(b, a % b, x, y); t = *x; *x = *y; *y = t - a / b * *y; return r; } } int main() { int passengers; int cost_A, passenger_A, cost_B, passenger_B; int count = 1; long long lower, upper, k, gcd, x, y; while (scanf("%d", &passengers) && passengers) { scanf("%d %d", &cost_A, &passenger_A); scanf("%d %d", &cost_B, &passenger_B); gcd = gcd_extend(passenger_A, passenger_B, &x, &y); if (passengers % gcd == 0) { x *= passengers / gcd; y *= passengers / gcd; upper = floor((double)y / (passenger_A / gcd)); lower = ceil((double)-x / (passenger_B / gcd)); k = passenger_B * cost_A - passenger_A * cost_B <= 0 ? upper : lower; printf("Data set %d: %lld aircraft A, %lld aircraft B\n", count++, x + (passenger_B / gcd) * k, y - (passenger_A / gcd) * k); } else printf("Data set %d: cannot be flown\n", count++); } return 0; }
C
#include<stdio.h> #include<conio.h> #include<math.h> float x,y,errorusuario; float e_test=0, f_xu, f_xl, xr, f_xr; float iteracion1, iteracion2; float raiz; float f_x(float x) { return (pow(x,3)+4*pow(x,2)-10); } float operacion(float x_l,float x_u,float e) { e_test=(x_u-x_l)/2; while(e_test>e) { f_xl=f_x(x_l); f_xu=f_x(x_u); xr=((x_l+x_u)/2); f_xr=f_x(xr); e_test=(x_u-x_l)/2; //iteraciones para llegar a error iteracion1=f_xl*f_xr; iteracion2=f_xu*f_xr; if(iteracion1>0&&iteracion2<0) { x_l=xr; } if(iteracion1<0&&iteracion2>0) { x_u=xr; } e_test=(x_u-x_l)/2; printf("\nEL valor del error es:%f",e_test); } raiz=xr; return raiz; } int main() { printf("\nPrograma para calcular una funcion cubica (x^3 + 4x^2 -10)"); printf("\n\nIngrese el intervalo de evaluacion de la funcion"); printf("\nPrimer numero: "); scanf("%f",&x); printf("\nSegundo numero: "); scanf("%f",&y); printf("\nDigita el error permitido: "); scanf("%f",&errorusuario); operacion(x,y,errorusuario); printf("\nLa raiz aproximada es:%f",raiz); getch(); return 0; }
C
//CAU 1: GIAI VA BIEN LUAN HE PT BAC NHAT HAI AN - CODING BY NTK #include <stdio.h> int main() { float a1,a2,b1,b2,c1,c2; float d,dx,dy; printf("Nhap cac he so cua he phuong trinh: \n"); printf(" a1.x + b1.y = c1 \n "); printf(" a2.x + b2.y = c2 \n "); printf("*************************************\n"); printf("a1: "); scanf("%f",&a1); printf("a2: "); scanf("%f",&a2); printf("b1: "); scanf("%f",&b1); printf("b2: "); scanf("%f",&b2); printf("c1: "); scanf("%f",&c1); printf("c2: "); scanf("%f",&c2); printf("PHUONG TRINH DA NHAP LA:\n"); printf(" %g.x + %g.y = %g \n ",a1,b1,c1); printf(" %g.x + %g.y = %g \n ",a2,b2,c2); printf("*******************************************\n"); d=a1*b2-b1*a2; dx=c1*b2-b1*c2; dy=a1*c2-c1*a2; if(d==0) { if((a1/a2)==(b1/b2)&&(b1/b2)==(c1/c2)&&(c1/c2)==(a1/a2)) printf("He phuong trinh co vo so nghiem\n"); else printf("Phuong trinh vo nghiem\n"); } else printf("Phuong trinh co 1 cap nghiem duy nhat la:\n"); printf("x:= %g\n",dx/d); printf("y:= %g\n",dy/d); }
C
#include <stdlib.h> #include <stdio.h> #include "header.h" int main(int argc, char *argv[]) { int i; int m,n; przerwij_program = 0; if(argc !=4) { fprintf(stderr, "Aby poprawnie wywolac program podaj ilosc rownan, ilosc niewiadomych i gdzie jest macierz!\n"); return 1; } m = atoi(argv[1]); n = atoi(argv[2]); if(m < n) { printf("Uklad nie posiada jednoznacznego rozwiazania!\n"); return 0; } czytaj_macierz(m,n,argv[3]); wypisz_macierz(m,n); schodkuj(m,n); for(i = 0; i < n; i++) if(macierz[i][i] == 0) { printf("Uklad nie posiada jednoznacznego rozwiazania!\n"); return 0; } wypisz_macierz(m,n); podstaw(m,n); if(przerwij_program != 1) wypisz_wyniki(n); return 0; }
C
#ifndef EVENT_H #define EVENT_H enum Signal { blockage, up, down, stop, coiled, unrolled, moving, standing }; //az esemény nem tartalmazhat most adattagokat, csak ha létrehozunk egy leszármazott osztályt belőle struct Event { Event(Signal e) : ev(e) {} Signal ev; }; #endif // EVENT_H
C
#include <stdio.h> void showarr(int [][5], int); void dbarr(int [][5], int); int main(void) { int ar[3][5] = { {1, 2, 3, 4, 5}, {3, 4, 5, 6, 7}, {5, 7, 9, 1, 3} }; showarr(ar, 3); dbarr(ar, 3); showarr(ar, 3); return 0; } void showarr(int ar[][5], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < 5; j++) printf("%d\t", ar[i][j]); putchar('\n'); } putchar('\n'); } void dbarr(int ar[][5], int n) { for (int i = 0; i < n; i++) for (int j = 0; j < 5; j++) ar[i][j] *= 2; }
C
// // Created by kosta on 8/25/2015. // #include "stdio.h" #include "limits.h" int main(){ long long x; double y[3] = {1.0, 2.0}; printf("%d\n", sizeof(x)); printf("%d", sizeof(y)); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printf_hex.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mfassi-f <mfassi-f@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/05/04 19:33:16 by mfassi-f #+# #+# */ /* Updated: 2014/05/04 20:52:54 by mfassi-f ### ########.fr */ /* */ /* ************************************************************************** */ #include <libftprintf.h> int ft_printf_hex(unsigned int n) { if (n >= 16) return (ft_printf_hex(n / 16) + ft_printf_hex(n % 16)); else return (ft_printf_char(HEX[n])); } int ft_print_hex(const char *format, int i, va_list ap) { if (format[i] == 'x') return (ft_printf_hex(va_arg(ap, unsigned int))); if (format[i] == 'X') return (ft_printf_hexm(va_arg(ap, unsigned int))); if (format[i] == 'p') return (ft_printf_pointer(va_arg(ap, void *))); return (1); } int ft_printf_hexm(unsigned int n) { if (n >= 16) return (ft_printf_hexm(n / 16) + ft_printf_hexm(n % 16)); else return (ft_printf_char(ft_toupper(HEX[n]))); } int ft_printf_hexa(unsigned long n) { if (n >= 16) return (ft_printf_hexa(n / 16) + ft_printf_hexa(n % 16)); else return (ft_printf_char(HEX[n])); } int ft_printf_pointer(void *n) { int i; if (n == NULL) return (i = ft_printf_str("0x0")); i = ft_printf_str("0x"); return (ft_printf_hexa((unsigned long)n) + i); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* matrix.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: emarin <emarin@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/08/12 14:10:50 by emarin #+# #+# */ /* Updated: 2019/08/19 20:31:24 by emarin ### ########.fr */ /* */ /* ************************************************************************** */ #include "geometry.h" void mt_free(t_matrix **m) { if ((*m)->cont) { free((*m)->cont); (*m)->cont = NULL; } if ((*m)) { free((*m)); (*m) = NULL; } } float *mt_new_cont(int h, int w, int8_t is_identity) { float *cont; int i; int j; if (!(cont = (float *)malloc(sizeof(float) * w * h))) return (NULL); i = -1; while (++i < h) { j = -1; while (++j < w) cont[i * w + j] = (is_identity && j == i) ? 1.0 : 0.0; } return (cont); } t_matrix *mt_new(int h, int w, int8_t is_identity) { t_matrix *mt; if (!(mt = (t_matrix *)malloc(sizeof(t_matrix *)))) return (NULL); mt->w = w; mt->h = h; if (!(mt->cont = mt_new_cont(h, w, is_identity))) { free(mt); return (NULL); } return (mt); } void mt_print(t_matrix *mt) { int i; int j; printf("(\n"); i = -1; while (++i < mt->h) { j = -1; while (++j < mt->w) printf("\t%.2f", mt->cont[i * mt->w + j]); printf("\n"); } printf(")\n"); }
C
#include <stdio.h> #include <stdlib.h> #define CANT 2 int main() { int i; // int edad1; // int edad2; float salario[CANT]; int edad[CANT]; int legajo[CANT]; for(i=0; i<CANT; i++) { printf("Edad %d: ",i+1); scanf("%d",&edad[i]); printf("Salario %d: ",i+1); scanf("%f",&salario[i]); printf("Legajo %d:",i+1); scanf("%d",&legajo[i]); } for(i=0; i<CANT; i++) { printf("\n...........................\n"); printf("\nLas edad es: %d\n",edad[i]); printf("\nLos salario es: %.2f\n",salario[i]); printf("\nEl numero de legajo es: %d\n",legajo[i]); printf("..........................."); } return 0; }
C
//Adam Granieri //COE 0449 Systems Software //Fall 2018 //Copied libraries and Block size from serv.c for consitency #include <stdlib.h> #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <getopt.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> //Added libraries #include <stdbool.h> #include <semaphore.h> #include <netdb.h> #include <pthread.h> #include <errno.h> // Structs for repeated operations typedef struct download download; typedef struct downloadFactory downloadFactory; struct downloadFactory { char* ip; int port; int socketD; int validSocket; int blockSize; int index; pthread_t currThread; pthread_mutex_t lock; void* buff; download* downloadInstance; }; struct download { int threadCount; int buffSize; void* buff; FILE* output; pthread_mutex_t fileLock; pthread_mutex_t lock; pthread_cond_t cond; sem_t count; downloadFactory* downloaders; }; //Definitions #define BLOCK_SIZE 1024 #define OUT_FILE "output.txt" //function prototypes bool checkInput(int, char**); bool checkIP(int, char*); bool checkPort(char*, int); download* newDownloader(int, char**); void* startDownload(void*); int connectSocket(int, char*); void backgroundDownload(downloadFactory*); ssize_t requestBlock(int, downloadFactory*); void writeBlockToFile(int, ssize_t, downloadFactory*); void endThread(downloadFactory*); void runDownload(download*); void destroyDownload(download*); //Functions //main to actually run /* We check input args, instantiate download ans download threads, then execute and then finally free and destroy mutexes */ int main(int argc, char* argv[]) { bool goodInput = checkInput(argc, argv); if (!goodInput) { printf("USAGE: %s IP port ...\n", argv[0]); return 1; } else { download* newDownload = newDownloader(argc, argv); runDownload(newDownload); destroyDownload(newDownload); return 0; } } //Checkts that correct input was passed bool checkInput(int argc, char* argv[]) { if (argc%2 == 0) { //chcek input number printf("ERROR: EACH ADDRESS MUST HAVE A PORT NUMBER\n"); return false; } //check actual arguements passed, on pair basis int i; for (i = 1; i < argc; i++) { if (i%2 != 0) { //we passed an ip/port pair if (!checkIP(i, argv[i])) { return false; } } else { //check port number if (!checkPort(argv[i], i)) { return false; } } } return true; } //Function for verifying ip address style bool checkIP(int argIndex, char* addr) { int count = 0; char c; int i; for (i = 0; i < strlen(addr); i++) { c = addr[i]; //check if it's a number if (c <= '9' && c >= '0') { continue; } else if (c == '.') { count++; } else { // invalid char printf("INVALID CHARACTER IN IP: %c at %s\n", c, addr); return false; } } //check if period count is correct if (count != 3) { printf("INVALID IP: %s at arg[%d]\n", addr, argIndex); return false; } else { //valid ip return true; } } //function for checking port number bool checkPort(char* s, int argIndex) { if (atoi(s) < 1024) { printf("Bad Port Val: %s\n", s); return false; } else { return true; } } //Function for initializing a new downlaod /* Here we instatiate a download object and give it thread counts for each of the avalible ports. the output file for writing is opened and the buffer is set up for blocks from the server. We zero out the buffer then init its mutexes. Finally now we're iterating through the other threads and locking each of them and connecting them through the factory. */ download* newDownloader(int argc, char* argv[]) { int downloadThreadCount = (argc-1)/2; download* returnDown = (download*)malloc(sizeof(download)); //Assign download properties returnDown->threadCount = downloadThreadCount; returnDown->downloaders = (downloadFactory*)malloc(sizeof(downloadFactory)*downloadThreadCount); returnDown->output = fopen(OUT_FILE,"w"); returnDown->buffSize = BLOCK_SIZE*downloadThreadCount; returnDown->buff = malloc(returnDown->buffSize); //Check if file open worked before threading if (!returnDown->output) { printf("Failed to open file\n"); } //zero out buffer memset(returnDown->buff, 0, BLOCK_SIZE*downloadThreadCount); //threads and semaphores sem_init(&(returnDown->count), 0, 0); pthread_mutex_init(&(returnDown->lock), NULL); pthread_mutex_init(&(returnDown->fileLock), NULL); pthread_cond_init(&(returnDown->cond), NULL); //initialize download threads int arg = 1; int i; for (i = 0; i < downloadThreadCount; i++) { //Load in ip address int length = strlen(argv[arg]); char* ipStr = malloc(length+1); ipStr[length] = '\0'; memcpy(ipStr, argv[arg], length); arg++; //initalize download struct downloadFactory d; d.ip = ipStr; d.index = i; d.validSocket = 1; d.port = atoi(argv[arg++]); d.blockSize = BLOCK_SIZE; d.buff = malloc(BLOCK_SIZE); //zero out buffer memset(d.buff, 0, BLOCK_SIZE); //start mutexes pthread_mutex_init(&(d.lock), NULL); pthread_mutex_lock(&(d.lock)); //finish download initialization d.downloadInstance = returnDown; returnDown->downloaders[i] = d; //create download thread pthread_create(&(returnDown->downloaders[i].currThread), NULL, startDownload, &(returnDown->downloaders[i])); } return returnDown; } //function to call for intializing thread downloads //This just calls other functions for the factory void* startDownload(void* d) { downloadFactory* factory = (downloadFactory*)d; //create and connect to given ip at port factory->socketD = connectSocket(factory->port, factory->ip); pthread_mutex_lock(&(factory->lock)); backgroundDownload(factory); return NULL; } //function for connect sockets for individual download threads /* This function gets the host addressm connects to the socket and returns the id for the download thread to request data from. */ int connectSocket(int p, char* addr) { int socketD, val; struct sockaddr_in serverAddr; struct hostent* hostAddr; //set up server socket socketD = socket(PF_INET, SOCK_STREAM, 0); memset(&serverAddr, 0, sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(p); //set up host hostAddr = gethostbyname(addr); memcpy(&serverAddr.sin_addr, hostAddr->h_addr, hostAddr->h_length); //finally connect to socket val = connect(socketD, (struct sockaddr*)&serverAddr, sizeof(serverAddr)); return socketD; } //function for executing background download of other threads //this function actually requests the block then writes to //the file void backgroundDownload(downloadFactory* f) { //initialize values int tempIndex = f->index; int reqBlock = tempIndex; int factoryCount = f->downloadInstance->threadCount; int blockCount = 0; //request blcok loop while (f->validSocket) { ssize_t receiveCount = requestBlock(reqBlock, f); if (receiveCount <= 0) { //check if receive worked break; } writeBlockToFile(reqBlock, receiveCount, f); reqBlock += factoryCount; blockCount++; } endThread(f); } //block for requesting block from server /* This function allocates a string buffer and sends a request to the socket for the next block into that buffer array and then call connectSocket again to begin getting the next block. Lastly it returns the amount of bytes received on this request. */ ssize_t requestBlock(int b, downloadFactory* f) { char stringBuff[128]; int length = sprintf(stringBuff, "%d", b); int sendRequest = send(f->socketD, stringBuff, 128, 0); ssize_t receivedBytes = recv(f->socketD, f->buff, BLOCK_SIZE, 0); close(f->socketD); //Check received byte count if it worked if (receivedBytes > 0) { f->socketD = connectSocket(f->port, f->ip); } else { //invalid socket f->validSocket = 0; } return receivedBytes; } //Function for taking a given block and outputting to a buffer /* This function simply takes a block and outputs it to the respective threads buffer output. After locking the thread it moves the file pointer to where it needs to write to then continually dumps it into the file. it then flushes the buffer and unlocks the thread. */ void writeBlockToFile(int bIndex, ssize_t writeBytes, downloadFactory* f) { //lock this thread for output pthread_mutex_lock(&(f->downloadInstance->fileLock)); //need an offset in file to write to long int fileOffset = (bIndex)*BLOCK_SIZE; //Calcultae offset from file FILE* fp = f->downloadInstance->output; fseek(fp, 0, SEEK_END); long int byteOffset = fileOffset - ftell(fp); fseek(fp, 0, SEEK_SET); //loop for writing values while (byteOffset > 0) { int writeFileBytes = byteOffset < f->downloadInstance->buffSize ? byteOffset : f->downloadInstance->buffSize; byteOffset -= fwrite(f->downloadInstance->buff, 1, writeFileBytes, fp); } //Finish pointer adjustments before closing file fseek(fp, fileOffset, SEEK_SET); fwrite(f->buff, 1, writeBytes, fp); fflush(fp); //finally unlock thread pthread_mutex_unlock(&(f->downloadInstance->fileLock)); } //function for ending a download thread /* This function ends the respecfive threadds on the factory. */ void endThread(downloadFactory* f) { sem_post(&(f->downloadInstance->count)); int val; sem_getvalue(&(f->downloadInstance->count), &val); if (val == f->downloadInstance->threadCount) { pthread_cond_signal(&(f->downloadInstance->cond)); } } //function to run a download thread /* This funtion takes a download object and starts the download threads waiting for each other to complete blocks coming down. Once the file write is complete it reports the total amount written to the file. */ void runDownload(download* d) { printf("Running download\n"); //lock thread pthread_mutex_lock(&(d->lock)); //unlock other threads int i; for (i = 0; i < d->threadCount; i++) { pthread_mutex_unlock(&(d->downloaders[i].lock)); } //wait for other threads to finish pthread_cond_wait(&(d->cond), &(d->lock)); //write to file FILE* fp = d->output; fseek(fp, 0, SEEK_END); long int location = ftell(fp); printf("Write %d bytes to file %s\n", location, OUT_FILE); } //function to end threads and free allocated memory /* This function goes through each download in the download factory and frees the allocated buffer memory and destroys the mutexes and cond. */ void destroyDownload(download* d) { //iterate through threads int i; for (i = 0; i < d->threadCount; i++) { downloadFactory* tempFactory = &(d->downloaders[i]); //free memory free(tempFactory->ip); free(tempFactory->buff); //destroy thread mutex pthread_mutex_destroy(&(tempFactory->lock)); } //Now free download data free(d->downloaders); free(d->buff); //destroy mutexes pthread_mutex_destroy(&(d->fileLock)); pthread_mutex_destroy(&(d->lock)); pthread_cond_destroy(&(d->cond)); sem_destroy(&(d->count)); free(d); }
C
/************************************************************************* > File Name: gccsyc.c > Author: > Mail: > Created Time: Sat 03 Oct 2015 08:29:20 PM CDT ************************************************************************/ #include<stdio.h> #include <pthread.h> #include <stdlib.h> static int count = 0; pthread_mutex_t lock; void *test_func(void *arg) { int i=0; int mlock = *(int *)arg; for(i=0;i<20000;++i){ //__sync_lock_test_and_set(&lock, 1); __sync_fetch_and_add(&count,1); //pthread_mutex_lock(&lock); //count++; //__sync_lock_release(&lock); //pthread_mutex_unlock(&lock); } return NULL; } int main(int argc, const char *argv[]) { pthread_t id[20]; int i = 0; for(i=0;i<20;++i){ pthread_create(&id[i],NULL,test_func,&i); } for(i=0;i<20;++i){ pthread_join(id[i],NULL); } printf("%d\n",count); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <R.h> #include <Rinternals.h> #include <Rmath.h> /******************************************************************************************************** invert inverts a function ********************************************************************************************************/ double invert(int n, double A[n][n], double Ainv[n][n]) { // this is a copy of A to avoid overwrighting it. double X[n][n], Achol[n][n]; int i, j, k; for(i=0; i<n; i++){ for(j=0; j<n; j++){ Achol[i][j]=0; X[j][j]=0; } } //cholesky to get upper triangle matrix for(i=0; i<n; i++){ Achol[i][i] = A[i][i]; for(k=0; k<i; k++) Achol[i][i] -= Achol[k][i]*Achol[k][i]; Achol[i][i] = sqrt(Achol[i][i]); for(j=i+1; j<n; j++){ Achol[i][j] = A[i][j]; for(k=0; k<i; k++) Achol[i][j] -= Achol[k][i]*Achol[k][j]; Achol[i][j] /= Achol[i][i]; } //also set to 0 this will be the inverse of the upper tri for(j=0; j<n; j++){ X[i][j] = 0; } } // invert from chol X[0][0] = 1/Achol[0][0]; for(i=1; i<n; i++){ //column X[i][i] = 1/Achol[i][i]; for(j=i-1; j>=0; j=j-1){ //row for(k=j+1; k<=i; k++) X[j][i] -= Achol[j][k]*X[k][i]/Achol[j][j]; } } //set Ainv for(i=0; i<n; i++){ for(j=0; j<n; j++){ Ainv[i][j] = 0; for(k=0; k<n; k++) Ainv[i][j] += X[i][k]*X[j][k]; } } return 0; } /******************************************************************************************************** cholesky decomposition. not that t(Achol) %*% Achol = A, i.e. it is backwards from many decopositions. ********************************************************************************************************/ double chol(int n, double A[n][n], double Achol[n][n]) { int i,j,k; for(i=0; i<n; i++){ for(j=0; j<n; j++){ Achol[i][j]=0; } } for( i=0; i<n; i++){ Achol[i][i] = A[i][i]; for( k=0; k<i; k++) Achol[i][i] -= Achol[k][i]*Achol[k][i]; Achol[i][i] = sqrt(Achol[i][i]); for( j=i+1; j<n; j++){ Achol[i][j] = A[i][j]; for( k=0; k<i; k++) Achol[i][j] -= Achol[k][i]*Achol[k][j]; Achol[i][j] /= Achol[i][i]; } } return 0; } /******************************************************************************************************** generates a multivariate random normal domension n ********************************************************************************************************/ double rmvnorm(int n, double mu[], double Sigma[n][n], double x[]) { //generate standard normal double z[n]; for(int i=0; i<n; i++){ z[i] = rnorm(0,1); } //matrix for cholesky decomp to transform z double V[n][n]; for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ V[i][j] = 0; } } chol(n, Sigma, V); //transform for(int i=0; i<n; i++){ x[i] = mu[i]; for(int j=0; j<n; j++){ x[i] += z[j]*V[j][i]; } } return 0; } /******************************************************************************************************** generates an wishart random variable. Note that this takes a variance matrix not a percision. ********************************************************************************************************/ void rwish_inv(int n , int nu, double Sigma[n][n], double W[n][n]){ double Z[n][n], ZC[n][n], CC[n][n], Sigma_inv[n][n]; int i, j, k, i2; // set everything to 0 for(i=0; i<n; i++){ for(j=0; j<n; j++){ CC[i][j]=0; ZC[i][j]=0; Z[i][j]=0; Sigma_inv[i][j]=0; } } //invert invert(n,Sigma,Sigma_inv); //cholesky for(i=0; i<n; i++){ CC[i][i] = Sigma_inv[i][i]; for(k=0; k<i; k++) CC[i][i] -= CC[k][i]*CC[k][i]; CC[i][i] = sqrt(CC[i][i]); for(j=i+1; j<n; j++){ CC[i][j] =Sigma_inv[i][j]; for(k=0; k<i; k++) CC[i][j] -= CC[k][i]*CC[k][j]; CC[i][j] /= CC[i][i]; } } // start generating. for(i=0; i<n; i++){ Z[i][i] = sqrt( rchisq(nu-i) ); for(int j=i+1; j <n; j++){ Z[i][j] = rnorm(0,1); } } //multiply the matricies for(i=0; i < n; i++){ for(j=0; j < n; j++){ ZC[i][j] = 0; for(i2=0; i2 < n; i2++){ ZC[i][j] += Z[i][i2] * CC[i2][j]; } } } //calculate XtX for(i=0; i < n; i++){ for(j=0; j < n; j++){ W[i][j] = 0; for(i2=0; i2 < n; i2++){ W[i][j] += ZC[i2][i] * ZC[i2][j]; } } } return; } /******************************************************************************************************** rtnorm This funtion draws a random variable from a truncated normal distribution ********************************************************************************************************/ double rtnorm(double mu, double sigma,double trunpt, int above) { /* function to draw truncated normal above=1 means from above b=trunpt, a=-inf above=0 means from below a=trunpt, b= +inf */ double tpt,rnd,result ; rnd=log(unif_rand()); if (above) { tpt=pnorm(((trunpt-mu)/(sigma)), 0.0, 1.0, 1, 1); result = mu + sigma*qnorm(rnd+tpt, 0.0, 1.0, 1, 1); }else { tpt=pnorm(-((trunpt-mu)/(sigma)), 0.0, 1.0, 1, 1); result = mu - sigma*qnorm(rnd+tpt, 0.0, 1.0, 1, 1); } return result; } /******************************************************************************************************** g_func This funtion calculates G(x_{ijk},ac50_{ij},beta_{ij}) for ZIPLL. ********************************************************************************************************/ double g_func(double logdiff, double beta[], double knots[], int n_bases){ double g=0; for(int l=1; l<=n_bases; l++){ if(knots[l-1]<0 && logdiff<0){ g += fmin( fmax(logdiff, knots[l-1]) - knots[l] ,0) * beta[l-1]; } if(knots[l]>0 && logdiff>0){ g += fmax( fmin(logdiff, knots[l]) - knots[l-1] ,0) * beta[l-1]; } } return g; } /******************************************************************************************************** d_ss This computes the difference in sum of squares divided by 2 for two normal pdf. ********************************************************************************************************/ double d_ss(int dim, double mu[], double Sigma[dim][dim], double y1[], double y2[]){ double r1[dim], r2[dim], ss1=0, ss2=0; for(int i=0; i < dim; i++){ r1[i] = y1[i] - mu[i]; r2[i] = y2[i] - mu[i]; } for(int j=0; j<dim; j++){ for(int k=0; k<dim; k++){ ss1 += r1[j]*r1[k]*Sigma[j][k]; ss2 += r2[j]*r2[k]*Sigma[j][k]; } } double diff = -(ss1-ss2)/2; return diff; } double d_ss_vec(int dim, double mu[], double Sigma[], double y1[], double y2[]) { double r1[dim], r2[dim], ss1=0, ss2=0; for(int i=0; i < dim; i++){ r1[i] = y1[i] - mu[i]; r2[i] = y2[i] - mu[i]; } for(int j=0; j<dim; j++){ for(int k=0; k<dim; k++){ ss1 += r1[j]*r1[k]*Sigma[j*dim+k]; ss2 += r2[j]*r2[k]*Sigma[j*dim+k]; } } double diff = -(ss1-ss2)/2; return diff; } /******************************************************************************************************** update_bottom This funtion updates the bottom ********************************************************************************************************/ void update_bottom(double y[], double x[], int n, double knots[], int n_bases, double theta[], double theta_star[], double beta_temp[], int z, double Sigma_inv_mu[3][3], double mu[], double sig2_inv ){ double g = 0, g2 = 0, yg = 0, d_e_star_t = 0, d_y_b = 0, sumy = 0, E_GTT_b, V_GTT_b, E_LTT_b, V_LTT_b, GTT_log_prob_b, LTT_log_prob_b; int k; /*loop through observations and calculate needed values*/ for(k=0; k<n; k++){ sumy += y[k]; } /* this is the top below the bottom case */ V_GTT_b = 1/(n * sig2_inv + Sigma_inv_mu[1][1]); E_GTT_b = V_GTT_b * ( sig2_inv*sumy - Sigma_inv_mu[0][1] * (theta_star[0] - mu[0]) + Sigma_inv_mu[1][1] * mu[1] - Sigma_inv_mu[2][1] * (theta_star[2] - mu[2]) ); if(z==0){ theta_star[1] = theta[1] = rnorm(E_GTT_b, sqrt(V_GTT_b)); }else{ for(k=0; k<n; k++){ g = 1/(1+exp(g_func(log(x[k]) - log(theta[2]), beta_temp, knots, n_bases))); g2 += g * g; yg += (g) * (y[k] - theta[0] * (1-g)); d_e_star_t += dnorm(y[k], theta[0]*(1-g), sqrt(1/sig2_inv), 1); d_y_b += dnorm(y[k],0,sqrt(1/sig2_inv),1); } /* for top greater than bottom case*/ V_LTT_b = 1/(sig2_inv * g2 + Sigma_inv_mu[1][1]); E_LTT_b = V_LTT_b * ( sig2_inv * yg - Sigma_inv_mu[0][1] * (theta_star[0] - mu[0]) + Sigma_inv_mu[1][1] * mu[1] - Sigma_inv_mu[2][1] * (theta_star[2] - mu[2]) ); /* calculate probablility below */ LTT_log_prob_b = (pnorm(theta_star[0],E_LTT_b,sqrt(V_LTT_b), 1 , 1) - d_y_b + d_e_star_t - dnorm(0,E_LTT_b,sqrt(V_LTT_b), 1) ); GTT_log_prob_b = (pnorm(theta_star[0],E_GTT_b,sqrt(V_GTT_b), 0, 1) - dnorm(0,E_GTT_b,sqrt(V_GTT_b), 1) ); double prob_GTT = 1 / (1+ exp(LTT_log_prob_b - GTT_log_prob_b)); /*indicator for below*/ double ru=unif_rand(); if(ru>prob_GTT){ theta_star[1] = theta[1] = rtnorm(E_LTT_b, sqrt(V_LTT_b), theta_star[0], 1); }else{ theta_star[1] = theta[1] = rtnorm(E_GTT_b, sqrt(V_GTT_b), theta_star[0], 0); } } } /******************************************************************************************************** update_top This funtion updates the top ********************************************************************************************************/ void update_top(double y[], double x[], int n, double knots[], int n_bases, double theta[], double theta_star[], double beta_temp[], int z, double Sigma_inv_mu[3][3], double mu[], double sig2_inv ){ double g = 0, g2 = 0, yg = 0, d_e_star_t = 0, d_y_b = 0, E_GTB_t, V_GTB_t, E_LTB_t, V_LTB_t, GTB_log_prob_t, LTB_log_prob_t; int k; /* this is the top below the bottom case */ V_LTB_t = 1/(Sigma_inv_mu[0][0]); E_LTB_t = V_LTB_t * ( Sigma_inv_mu[0][0] * mu[0] - Sigma_inv_mu[1][0] * (theta_star[1] - mu[1]) - Sigma_inv_mu[2][0] * (theta_star[2] - mu[2]) ); if(z==0){ theta_star[0] = rnorm(E_LTB_t, sqrt(V_LTB_t)); }else{ /*loop through observations and calculate needed values*/ for(k=0; k<n; k++){ g = 1/(1+exp(g_func(log(x[k]) - log(theta[2]), beta_temp, knots, n_bases))); g2 += (1-g) * (1-g); yg += (1-g) * (y[k] - theta[1]*g); d_e_star_t += dnorm(y[k], theta[1]*g, sqrt(1/sig2_inv), 1); d_y_b += dnorm(y[k],theta[1],sqrt(1/sig2_inv),1); } /* for top greater than bottom case*/ V_GTB_t = 1/(sig2_inv * g2 + Sigma_inv_mu[0][0]); E_GTB_t = V_GTB_t * ( sig2_inv * yg + Sigma_inv_mu[0][0] * mu[0] - Sigma_inv_mu[1][0] * (theta_star[1] - mu[1]) - Sigma_inv_mu[2][0] * (theta_star[2] - mu[2]) ); /* calculate probablility below */ GTB_log_prob_t = (pnorm(theta[1],E_GTB_t,sqrt(V_GTB_t), 0 , 1) - dnorm(0,E_GTB_t,sqrt(V_GTB_t), 1) + d_e_star_t); LTB_log_prob_t = (pnorm(theta[1],E_LTB_t,sqrt(V_LTB_t), 1, 1) - dnorm(0,E_LTB_t,sqrt(V_LTB_t), 1) + d_y_b); double prob_below = 1 / (1+ exp(GTB_log_prob_t - LTB_log_prob_t)); /*indicator for below*/ double ru=unif_rand(); if(ru>prob_below){ theta_star[0] = rtnorm(E_GTB_t, sqrt(V_GTB_t), theta[1], 0); }else{ theta_star[0] = rtnorm(E_LTB_t, sqrt(V_LTB_t), theta[1], 1); } } //update top theta[0] = fmax(theta_star[0],theta_star[1]); } /******************************************************************************************************** update_top This funtion updates the top ********************************************************************************************************/ int update_Z(double y[], double x[], int n, double knots[], int n_bases, double theta[], int z, double beta_temp[], double sig2_inv, double psi ){ double SS = 0, psi_hat; int k; for(k=0; k < n; k++){ SS += (y[k] - theta[1])*(y[k] - theta[1]) - (y[k] - theta[0] + (theta[0]-theta[1])/(1+exp(g_func(log(x[k]) - log(theta[2]), beta_temp, knots, n_bases)))) * (y[k] - theta[0] + (theta[0]-theta[1])/(1+exp(g_func(log(x[k]) - log(theta[2]), beta_temp, knots, n_bases)))); } psi_hat = psi / (psi + (1-psi) * exp(-sig2_inv * SS / 2)); double ru=unif_rand(); if(ru<psi_hat){ z = 1; }else{ z = 0; } //Rprintf("ps_hat %f %d\n", psi_hat, z); return z; } /******************************************************************************************************** tb_func This funtion updates theta, beta, and Z. ********************************************************************************************************/ void FIT_ZIPLL(double *resp, double *conc, int *dimx, int *n, double *knots, int *nknots, double *BE_in, double *BEsd_in, double *AC50_out, double *TOP_out, double *AC50sd_out, double *TOPsd_out, double *active_out, double *kappa, int *smax, int *burnin, double *mu_0, double *Diag_Sigma_0 ){ GetRNGstate(); //------------------------------------------------------------------------------------- //indecies int i, i2, j, k, k2, u, chem, assay, rep; //------------------------------------------------------------------------------------- //find number of chemicals and assays int n_assays = dimx[1]; int n_chems = dimx[0]; int N = n_chems*n_assays; //total number of curves int max_n = dimx[2]; //maximum number of obs allowed int n_star = 0; //total number of observations across all curves for(i=0; i<N; i++) n_star += n[i]; int K=*nknots-1; //------------------------------------------------------------------------------------- //Setup data storage double **x; x = (double **) calloc(N,sizeof(double*)); for (i=0; i<N; i++) { x[i] = (double *) calloc(max_n, sizeof(double)); } double **y; y = (double **) calloc(N,sizeof(double*)); for (i=0; i<N; i++) { y[i] = (double *) calloc(max_n, sizeof(double)); } double **BE; BE = (double **) calloc(N,sizeof(double*)); for (i=0; i<N; i++) { BE[i] = (double *) calloc(max_n, sizeof(double)); } double **BE2; BE2 = (double **) calloc(N,sizeof(double*)); for (i=0; i<N; i++) { BE2[i] = (double *) calloc(max_n, sizeof(double)); } for(i=0; i<N; i++){ AC50_out[i] = 0; TOP_out[i] = 0; AC50sd_out[i] = 0; TOPsd_out[i] = 0; active_out[i] = 0; for(j=0; j<max_n; j++){ x[i][j] = conc[j+i*dimx[2]]; y[i][j] = resp[j+i*dimx[2]]; BE[i][j] = 0; BE2[i][j] = 0; } } int Z[n_chems][n_assays]; for(assay=0; assay<n_assays; assay++){ for(chem=0; chem<n_chems; chem++){ Z[chem][assay] = 1; } } //------------------------------------------------------------------------------------- //parameters, hyperparameters, and other prespecified numbers. double epsilon = 0.8, prblock = .75; //for resolvant double d1 = 1, d2 = 0.5; //for sig2 double p1 = 1, p2 = 1; //for psi double g1 = 1, g2 = .5; //for lambda //for mu and Sigma_mu double Sigma_0[3][3], Sigma_0_inv[3][3]; for(i=0; i<3; i++){ for(j=0; j<3; j++){ Sigma_0[i][j] = 0; Sigma_0_inv[i][j] = 0; } } Sigma_0[0][0] = Diag_Sigma_0[0]; Sigma_0[1][1] = Diag_Sigma_0[1]; Sigma_0[2][2] = Diag_Sigma_0[2]; invert(3,Sigma_0,Sigma_0_inv); //for slope mean and variances int nu_mu = 6, nu_S=K+5; double V_mu[3][3], V_S[K][K]; for(i=0; i<3; i++){ for(j=0; j<3; j++){ V_mu[i][j] = 20*Sigma_0[i][j]*(nu_mu-5); } } for(k=0; k<K; k++){ for(k2=0; k2<K; k2++){ V_S[k][k2] = 0; } V_S[k][k] = 10; } double S0 = 2; //------------------------------------------------------------------------------------- // unknown parameters and assign starting values //Starting values double mu[3], // mean across assays Sigma_bet_inv[3][3], // between assay inverse varinace Sigma_S_inv[K][K], //inverse S[K] ; //starting values for spline for(k=0; k<K; k++) S[k] = S0; for(i=0; i<3; i++) mu[i] = mu_0[i]; double t33[3][3], m33[3][3], t3[3], m3[3], SSt_theta_a[3][3], sumbetastar[K], SSt_beta[K][K], E_sk2[K], E_sk[K], V_sk_inv[K][K], V_sk[K][K]; //Starting values for within assay variance for(assay=0; assay<n_assays; assay++){ for(i=0; i<3; i++){ for(j=0; j<3; j++){ Sigma_bet_inv[i][j] = V_mu[i][j]; } Sigma_bet_inv[i][i] = 1/V_mu[i][i]; } } rwish_inv(K, nu_S, V_S, Sigma_S_inv); double **beta_ac; beta_ac = (double **) calloc(N,sizeof(double*)); for (i=0; i<N; i++) { beta_ac[i] = (double *) calloc(K, sizeof(double)); } double **theta_ac; theta_ac = (double **) calloc(N,sizeof(double*)); for (i=0; i<N; i++) { theta_ac[i] = (double *) calloc(3, sizeof(double)); } double **theta_ac_star; theta_ac_star = (double **) calloc(N,sizeof(double*)); for (i=0; i<N; i++) { theta_ac_star[i] = (double *) calloc(3, sizeof(double)); } for(i=0; i<N; i++){ rmvnorm(3, mu,Sigma_0,theta_ac_star[i]); for(k=0; k<K; k++){ beta_ac[i][k] = exp(rnorm(S0,.1)); } theta_ac[i][0] = fmax(theta_ac_star[i][0],theta_ac_star[i][1]); theta_ac[i][1] = theta_ac_star[i][1]; theta_ac[i][2] = x[i][0] + (x[i][n[i]-1]-x[i][0]) / (1+exp(-theta_ac_star[i][2])); } double lambda = rgamma(d1, 1/d2); double sig2_inv = rgamma(g1, 1/g2); double psi = 0.5; //------------------------------------------------------------------------------------- //variables used throughout int n_resolv, row_temp, sumZ; double prop_AC50_star, prop_AC50, beta_star_temp[K], prop_beta_star[K], prop_beta[K], ran_ker, R, SSE = 0, y_hat, sumtheta_a[3], l_temp, theta_star_prop[3]; //------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------- //MCMC for(rep=0; rep<*smax; rep++){ SSE = 0; //sse for all curves //sum the assay specific parameters across all assays for(i=0; i<3; i++){ sumtheta_a[i] = 0; for(i2=0; i2<3; i2++){ SSt_theta_a[i2][i] = V_mu[i2][i] ; } } //sum the betas and squared betas across all chemicals and assays for(k=0; k<K; k++){ sumbetastar[k] = 0; for(k2=0; k2<K; k2++){ SSt_beta[k][k2] = V_S[k][k2] ; } } sumZ = 0; //number of active curves in this assay //------------------------------------------------------------------------------------- // assay loop for(assay = 0; assay<n_assays; assay++){ //------------------------------------------------------------------------------------- // chemical loop for(chem = 0; chem < n_chems; chem++){ row_temp = chem+assay*n_chems; // current row in the N length vector for this chem-assay combo //update bottom update_bottom( y[row_temp], x[row_temp], n[row_temp], knots, K, theta_ac[row_temp], theta_ac_star[row_temp], beta_ac[row_temp], Z[chem][assay], Sigma_bet_inv, mu, sig2_inv ); //update top update_top( y[row_temp], x[row_temp], n[row_temp], knots, K, theta_ac[row_temp], theta_ac_star[row_temp], beta_ac[row_temp], Z[chem][assay], Sigma_bet_inv, mu, sig2_inv ); //update Z Z[chem][assay] = update_Z( y[row_temp], x[row_temp], n[row_temp], knots, K, theta_ac[row_temp], Z[chem][assay], beta_ac[row_temp], sig2_inv, psi); /*number of updates*/ n_resolv = trunc((log(unif_rand())/log(epsilon))); for(u=0; u<n_resolv; u++) { ran_ker = unif_rand(); /* propose new value for AC50*/ prop_AC50_star = theta_ac_star[row_temp][2] + rnorm(0, 1)*.5; prop_AC50 = x[row_temp][0] + (x[row_temp][n[row_temp]-1]-x[row_temp][0]) / (1+exp(-prop_AC50_star)); /* propose new values for Beta*/ for(k=0; k<K; k++){ beta_star_temp[k] = log(beta_ac[row_temp][k]); prop_beta_star[k] = beta_star_temp[k] + rnorm(0, 1)*.5; prop_beta[k] = exp(prop_beta_star[k]); } /* arrays of parms*/ theta_star_prop[0] = theta_ac_star[row_temp][0]; theta_star_prop[1] = theta_ac_star[row_temp][1]; theta_star_prop[2] = prop_AC50_star; //Block update if(ran_ker<prblock){ R = d_ss(3, mu, Sigma_bet_inv, theta_star_prop, theta_ac_star[row_temp]) + d_ss(K, S, Sigma_S_inv, prop_beta_star, beta_star_temp); if(Z[chem][assay]==1){ for(k=0; k < n[row_temp]; k++){ R += - sig2_inv * ( (y[row_temp][k] - theta_ac[row_temp][0] + (theta_ac[row_temp][0]-theta_ac[row_temp][1])/(1+exp(g_func(log(x[row_temp][k]) - log(prop_AC50), prop_beta, knots, K)))) * (y[row_temp][k] - theta_ac[row_temp][0] + (theta_ac[row_temp][0]-theta_ac[row_temp][1])/(1+exp(g_func(log(x[row_temp][k]) - log(prop_AC50), prop_beta, knots, K)))) - (y[row_temp][k] - theta_ac[row_temp][0] + (theta_ac[row_temp][0]-theta_ac[row_temp][1])/(1+exp(g_func(log(x[row_temp][k]) - log(theta_ac[row_temp][2]), beta_ac[row_temp], knots, K)))) * (y[row_temp][k] - theta_ac[row_temp][0] + (theta_ac[row_temp][0]-theta_ac[row_temp][1])/(1+exp(g_func(log(x[row_temp][k]) - log(theta_ac[row_temp][2]), beta_ac[row_temp], knots, K)))) )/2; } } if(R > log(unif_rand())){ for(k=0; k<K; k++){ beta_ac[row_temp][k] = prop_beta[k]; } theta_ac_star[row_temp][2]= prop_AC50_star; theta_ac[row_temp][2] = prop_AC50; } }else{ //theta first R = d_ss(3, mu, Sigma_bet_inv, theta_star_prop, theta_ac_star[row_temp]); if(Z[chem][assay]==1){ for(k=0; k < n[row_temp]; k++){ R += - sig2_inv * ( (y[row_temp][k] - theta_ac[row_temp][0] + (theta_ac[row_temp][0]-theta_ac[row_temp][1])/(1+exp(g_func(log(x[row_temp][k]) - log(prop_AC50), beta_ac[row_temp], knots, K)))) * (y[row_temp][k] - theta_ac[row_temp][0] + (theta_ac[row_temp][0]-theta_ac[row_temp][1])/(1+exp(g_func(log(x[row_temp][k]) - log(prop_AC50), beta_ac[row_temp], knots, K)))) - (y[row_temp][k] - theta_ac[row_temp][0] + (theta_ac[row_temp][0]-theta_ac[row_temp][1])/(1+exp(g_func(log(x[row_temp][k]) - log(theta_ac[row_temp][2]), beta_ac[row_temp], knots, K)))) * (y[row_temp][k] - theta_ac[row_temp][0] + (theta_ac[row_temp][0]-theta_ac[row_temp][1])/(1+exp(g_func(log(x[row_temp][k]) - log(theta_ac[row_temp][2]), beta_ac[row_temp], knots, K)))) )/2; } } if(R > log(unif_rand())){ theta_ac_star[row_temp][2] = prop_AC50_star; theta_ac[row_temp][2] = prop_AC50; } //now beta // log ratio of multivariate normals R = d_ss(K, S, Sigma_S_inv, prop_beta_star, beta_star_temp); if(Z[chem][assay]==1){ for(k=0; k < n[row_temp]; k++){ R += - sig2_inv * ( (y[row_temp][k] - theta_ac[row_temp][0] + (theta_ac[row_temp][0]-theta_ac[row_temp][1])/(1+exp(g_func(log(x[row_temp][k]) - log(theta_ac[row_temp][2]), prop_beta, knots, K)))) * (y[row_temp][k] - theta_ac[row_temp][0] + (theta_ac[row_temp][0]-theta_ac[row_temp][1])/(1+exp(g_func(log(x[row_temp][k]) - log(theta_ac[row_temp][2]), prop_beta, knots, K)))) - (y[row_temp][k] - theta_ac[row_temp][0] + (theta_ac[row_temp][0]-theta_ac[row_temp][1])/(1+exp(g_func(log(x[row_temp][k]) - log(theta_ac[row_temp][2]), beta_ac[row_temp], knots, K)))) * (y[row_temp][k] - theta_ac[row_temp][0] + (theta_ac[row_temp][0]-theta_ac[row_temp][1])/(1+exp(g_func(log(x[row_temp][k]) - log(theta_ac[row_temp][2]), beta_ac[row_temp], knots, K)))) )/2; } } if(R > log(unif_rand())){ for(k=0; k<K; k++){ beta_ac[row_temp][k] = prop_beta[k]; } } } } //update SSE and predicted values for(j=0; j<n[row_temp]; j++){ // predicted value y_hat = (1-Z[chem][assay]) * (theta_ac[row_temp][1]) + Z[chem][assay] * (theta_ac[row_temp][0] - (theta_ac[row_temp][0]-theta_ac[row_temp][1])/(1+exp(g_func(log(x[row_temp][j]) - log(theta_ac[row_temp][2]), beta_ac[row_temp], knots, K)))); //predict at current locations if(rep>*burnin-1){ BE[row_temp][j] += y_hat/(*smax-*burnin); BE2[row_temp][j] += y_hat*y_hat/(*smax-*burnin); } //records SSE SSE += ( y_hat - y[row_temp][j]) * ( y_hat - y[row_temp][j]); // SSE } //keep sum for updating theta_a sumtheta_a[0] += theta_ac_star[row_temp][0]; sumtheta_a[1] += theta_ac_star[row_temp][1]; sumtheta_a[2] += theta_ac_star[row_temp][2]; //sum of square parameters for within assay variance update SSt_theta_a[0][0] += (theta_ac_star[row_temp][0] - mu[0]) * (theta_ac_star[row_temp][0] - mu[0]); SSt_theta_a[0][1] += (theta_ac_star[row_temp][0] - mu[0]) * (theta_ac_star[row_temp][1] - mu[1]); SSt_theta_a[0][2] += (theta_ac_star[row_temp][0] - mu[0]) * (theta_ac_star[row_temp][2] - mu[2]); SSt_theta_a[1][0] += (theta_ac_star[row_temp][1] - mu[1]) * (theta_ac_star[row_temp][0] - mu[0]); SSt_theta_a[1][1] += (theta_ac_star[row_temp][1] - mu[1]) * (theta_ac_star[row_temp][1] - mu[1]); SSt_theta_a[1][2] += (theta_ac_star[row_temp][1] - mu[1]) * (theta_ac_star[row_temp][2] - mu[2]); SSt_theta_a[2][0] += (theta_ac_star[row_temp][2] - mu[2]) * (theta_ac_star[row_temp][0] - mu[0]); SSt_theta_a[2][1] += (theta_ac_star[row_temp][2] - mu[2]) * (theta_ac_star[row_temp][1] - mu[1]); SSt_theta_a[2][2] += (theta_ac_star[row_temp][2] - mu[2]) * (theta_ac_star[row_temp][2] - mu[2]); //sum Z sumZ += Z[chem][assay]; //sum of squares for S for(k=0; k<K; k++){ sumbetastar[k] += log(beta_ac[row_temp][k]); for(k2=0; k2<K; k2++){ SSt_beta[k][k2] += (log(beta_ac[row_temp][k])-S[k]) * (log(beta_ac[row_temp][k2])-S[k2]) ; } } if(rep>*burnin-1){ TOP_out[row_temp] += theta_ac[row_temp][0]/(*smax-*burnin); AC50_out[row_temp] += theta_ac[row_temp][2]/(*smax-*burnin); TOPsd_out[row_temp] += theta_ac[row_temp][0]*theta_ac[row_temp][0]/(*smax-*burnin); AC50sd_out[row_temp] += theta_ac[row_temp][2]*theta_ac[row_temp][2]/(*smax-*burnin); if(Z[chem][assay]==1 && (theta_ac[row_temp][0]-theta_ac[row_temp][1]) > *kappa) active_out[row_temp] += (double) 1/(*smax-*burnin); } }// end chemical loop //update psi for each assay psi = rbeta(p1 + sumZ, N+p2-sumZ); }// end assay loop //------------------------------------------------------------------------------------- //update the variance sig2_inv = rgamma((d1 + n_star/2), (1/(d2 + SSE/2))); //update lambda l_temp = (S0 - S[0])*(S0 - S[0]); for(k=1; k<K-1; k++) l_temp += (S[k] - S[k-1])*(S[k] - S[k-1]); lambda = rgamma(g1 + K/2, 1/( g2 + l_temp/2)); //update the between assay variance rwish_inv(3, N+nu_mu, SSt_theta_a, Sigma_bet_inv); //update the overall mu for(i=0; i<3; i++){ t3[i] = 0; for(i2=0; i2<3; i2++){ t33[i][i2] = N*Sigma_bet_inv[i][i2] + Sigma_0_inv[i][i2]; t3[i] += Sigma_bet_inv[i][i2] * sumtheta_a[i2] + Sigma_0_inv[i][i2] * mu_0[i2]; } } invert(3,t33,m33); for(i=0; i<3; i++){ m3[i] = 0; for(i2= 0; i2<3; i2++){ m3[i] += m33[i][i2] * t3[i2]; } } rmvnorm(3, m3, m33, mu); //update the variance about the S spline rwish_inv(K, N+nu_S, SSt_beta, Sigma_S_inv); //variances for each S for(k=0; k<K; k++){ //variance for(k2=0; k2<K; k2++){ V_sk_inv[k][k2] = N * Sigma_S_inv[k][k2]; } if(k<K-1){ V_sk_inv[k][k] += 2*lambda; }else{ V_sk_inv[k][k] += lambda; } //mean E_sk[k] = 0; if(k>0) E_sk[k] += S[k-1]; if(k<K-1) E_sk[k] += S[k+1]; if(k==0) E_sk[k] += S0; E_sk[k] = E_sk[k]*lambda; } invert(K, V_sk_inv,V_sk); for(k=0; k<K; k++){ for(k2=0; k2<K; k2++){ E_sk[k] += Sigma_S_inv[k][k2]*sumbetastar[k2]; } } for(k=0; k<K; k++){ E_sk2[k] = 0; for(k2=0; k2<K; k2++){ E_sk2[k] += V_sk[k][k2]*E_sk[k2]; } } //update matrix of S rmvnorm(K, E_sk2, V_sk, S); } // end MCMC //------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------- for(i=0; i<N; i++){ TOPsd_out[i] = sqrt(TOPsd_out[i] - TOP_out[i]*TOP_out[i]); AC50sd_out[i] = sqrt(AC50sd_out[i] - AC50_out[i]*AC50_out[i]); for(j=0; j<max_n; j++){ BE_in[j+i*max_n] = BE[i][j]; BEsd_in[j+i*max_n] = sqrt(BE2[i][j] - BE[i][j]*BE[i][j]); } } //------------------------------------------------------------------------------------- // clean memory for(i = 0; i < N; i++){ free(beta_ac[i]); free(theta_ac[i]); free(theta_ac_star[i]); free(x[i]); free(y[i]); free(BE[i]); free(BE2[i]); } free(beta_ac); free(theta_ac); free(theta_ac_star); free(x); free(y); free(BE); free(BE2); PutRNGstate(); return; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sferreir <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/21 14:19:44 by sferreir #+# #+# */ /* Updated: 2019/07/21 16:44:58 by sferreir ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include <unistd.h> int ft_solvesudoku(int **arr); void ft_print_sudoku(int **arr); int **ft_allocate_memory(void) { int **arr; int i; arr = (int **)malloc(sizeof(int *) * 10); i = 0; while (i < 9) { arr[i] = (int *)malloc(sizeof(int) * 10); i += 1; } arr[i] = 0; return (arr); } void ft_assign_elements(int **arr, char **argv) { int i; int j; i = 0; while (i < 9) { j = 0; while (j < 9) { if (argv[i + 1][j] > 48 && argv[i + 1][j] <= 57) arr[i][j] = argv[i + 1][j]; j += 1; } arr[i][j] = '\0'; i += 1; } } int main(int argc, char **argv) { int **arr; if (argc == 10) { arr = ft_allocate_memory(); ft_assign_elements(arr, argv); if (ft_solvesudoku(arr) == 1) ft_print_sudoku(arr); else write(1, "Error\n", 6); } return (0); }
C
#include<stdio.h> #include<conio.h> int main() { char ch= '\0'; printf("\n Enter a Character to View Corresponding Message="); ch=getche(); switch(ch) { case 'a': printf("\n Welcome"); break; case 'A': printf("\n Welcome"); break; case 'b': printf("\n Good Bye"); break; case 'B': printf("\n Good Bye"); break; case 'c': printf("\n Have a Nice Day"); break; case 'C': printf ("\n Have a Nice Day"); break; case 'd': printf("\n Good Day"); break; case 'D': printf ("\n Good Day"); break; default: printf ("\n No Message for such Character"); break; } printf("\n Thanks!!!"); getch(); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <conio.h> #include "LinkedList.h" #include "Controller.h" #include "Employee.h" #include "validaciones.h" /** \brief Parsea los datos los datos de los empleados desde el archivo data.csv (modo texto). * * \param path char* * \param pArrayListEmployee LinkedList* * \return int * */ int parser_EmployeeFromText(FILE* pFile , LinkedList* pArrayListEmployee) { Employee* pAux; char bId[1024]; char bNombre[1024]; char bHorasTrabajadas[1024]; char bSalario[1024]; int bandera = 1; int retorno = -1; while(!feof(pFile)) { if(bandera) { fscanf(pFile,"%s\n", bId); bandera = 0; } else if(fscanf(pFile,"%[^,],%[^,],%[^,],%[^\n]\n", bId, bNombre, bHorasTrabajadas, bSalario)==4)//develve la cant de datos leidos { pAux = employee_newParametros(bId, bNombre, bHorasTrabajadas, bSalario); if(pAux != NULL) { ll_add(pArrayListEmployee, pAux); retorno = 0; } } else { break; } } return retorno; } /** \brief Parsea los datos los datos de los empleados desde el archivo data.csv (modo binario). * * \param path char* * \param pArrayListEmployee LinkedList* * \return int * */ int parser_EmployeeFromBinary(FILE* pFile , LinkedList* pArrayListEmployee) { Employee* auxPEmpleado; int retorno = -1; int cantLineas; do { auxPEmpleado = employee_new(); cantLineas = fread(auxPEmpleado, sizeof(Employee), 1, pFile);//cantidad de lineas leidas if(auxPEmpleado != NULL && cantLineas == 1) { ll_add(pArrayListEmployee, auxPEmpleado); retorno = 0; } }while(!feof(pFile)); return retorno; }
C
// 009 - ּ #include<stdio.h> /* ȳϼ */ main() { int i; int hap = 0; for (i = 1; i <= 10; i = i + 1) { hap = hap + i; } printf(" 1 10 : %d \n", hap); }
C
float restar (int i, int j){ if (i > 0)then { return restar(i - 1, j + 1); } else { return j; } } void main (int args){ int vara; int varb; vara = 5; varb = 10; int varc; varc = restar(vara, varb); printf(varc); }
C
/* * Shiying Zheng and Ben Stern, hw9 * A sorted list built upon a linkedlist. */ #include "sortedlist.h" /* * Initialize a sortedlist. * Takes in an integer which is the size of each element of the sortedlist, * and a comparator which takes in two void pointers, compare them, and * returns an int. * Returns a pointer to a sorted list. */ sortedlist* sortedlist_init(int datasize, int (*cmp)(void* a, void* b)){ sortedlist* this=malloc(sizeof(sortedlist)); if(!this){ exit(EXIT_FAILURE); } this->list=linkedlist_init(datasize); this->cmp=cmp; this->iter=linkedlist_iterator(this->list); return this; } /* * Takes in a pointer to the sortedlist. * Returns the size of the sortedlist. */ int sortedlist_size(sortedlist* this){ return linkedlist_size(this->list); } /* * Adds data to the sortedlist. The list will remain sorted. * Takes in a pointer to the sortedlist and a void pointer to the data to add. */ void sortedlist_add(sortedlist* this,void* data){ //Using the iterator of the linkedlist inside of the sortedlist. int comparison; if(linkedlist_iteratorhasnext(this->iter)){ comparison=this->cmp(data,linkedlist_iteratornext(this->iter)); if(comparison>0){ while(comparison>0&&linkedlist_iteratorhasnext(this->iter)){ comparison=this->cmp(data,linkedlist_iteratornext(this->iter)); } if(comparison<0) linkedlist_iteratorprev(this->iter); } else{ while(comparison<0&&linkedlist_iteratorhasprev(this->iter)){ comparison=this->cmp(data,linkedlist_iteratorprev(this->iter)); } if(comparison>0) linkedlist_iteratornext(this->iter); } } else if(linkedlist_iteratorhasprev(this->iter)){ comparison=this->cmp(data,linkedlist_iteratorprev(this->iter)); while(comparison<0&&linkedlist_iteratorhasprev(this->iter)){ comparison=this->cmp(data,linkedlist_iteratorprev(this->iter)); } if(comparison>0) linkedlist_iteratornext(this->iter); } linkedlist_iteratoradd(this->iter,data); } /* * Removes data from the sortedlist. * Takes in a pointer to the sortedlist, * and a void pointer to the data to remove. */ void* sortedlist_rm(sortedlist* this, void* data){ //Using the linkedlist iterator. int comparison; void * rmdata; if (linkedlist_iteratorhasnext(this->iter)){ comparison=this->cmp(data, linkedlist_iteratornext(this->iter)); if (comparison>0){ while(comparison>0&&linkedlist_iteratorhasnext(this->iter)){ comparison=this->cmp(data, linkedlist_iteratornext(this->iter)); } if (comparison<0) return NULL; } else { while(comparison<0&&linkedlist_iteratorhasprev(this->iter)){ comparison=this->cmp(data, linkedlist_iteratorprev(this->iter)); } if (comparison>0) return NULL; } } else if (linkedlist_iteratorhasprev(this->iter)){ comparison=this->cmp(data,linkedlist_iteratorprev(this->iter)); while(comparison<0&&linkedlist_iteratorhasprev(this->iter)){ comparison=this->cmp(data,linkedlist_iteratorprev(this->iter)); } if(comparison>0) return NULL; } if(linkedlist_iteratorhasnext(this->iter)){ linkedlist_iteratornext(this->iter); } rmdata=linkedlist_iteratorrm(this->iter); return rmdata; } /* * Takes in a pointer to the sortedlist. * Returns the min data in the list. */ void* sortedlist_get_min(sortedlist* this){ return linkedlist_getfront(this->list); } /* * Takes in a pointer to the sortedlist. * Returns the max data in the list. */ void* sortedlist_get_max(sortedlist* this){ return linkedlist_getend(this->list); } /* * Removes the min data from the sortedlist. * Takes in a pointer to the sortedlist. * Returns the removed data in the list. */ void* sortedlist_rm_min(sortedlist* this){ this->iter->position=0; void* returnthis=linkedlist_rmfront(this->list); this->iter->current=this->iter->list->head; return returnthis; } /* * Removes the max data from the sortedlist. * Takes in a pointer to the sortedlist. * Returns the removed data in the list. */ void* sortedlist_rm_max(sortedlist* this){ this->iter->position=this->list->size; void* returnthis=linkedlist_rmend(this->list); this->iter->current=this->iter->list->tail; return returnthis; } /* Iterator Methods */ /* * Returns an iterator over the sortedlist. */ iterator* sortedlist_iterator(sortedlist* this){ return linkedlist_iterator(this->list); } /* * Takes in a pointer to an iterator. * Returns 0 if there is not a next element, * otherwise a non-zero value. */ int sortedlist_iteratorhasnext(iterator* iter){ return linkedlist_iteratorhasnext(iter); } /* * Takes in a pointer to an iterator. * Returns 0 if there is not a previous element, * otherwise a non-zero value. */ int sortedlist_iteratorhasprev(iterator* iter){ return linkedlist_iteratorhasprev(iter); } /* * Takes in a pointer to an iterator. * Returns the next element. */ void* sortedlist_iteratornext(iterator* iter){ return linkedlist_iteratornext(iter); } /* * Takes in a pointer to an iterator. * Returns the previous element. */ void* sortedlist_iteratorprev(iterator* iter){ return linkedlist_iteratorprev(iter); } /* * Frees the memory allocated for the iterator. * Takes in a pointer to the iterator. */ void sortedlist_freeiter(iterator* iter){ linkedlist_freeiter(iter); } /* * Frees the memory allocated for a sortedlist. * Takes in a pointer to the sortedlist. */ void sortedlist_free(sortedlist* list){ linkedlist_freeiter(list->iter); linkedlist_free(list->list); free(list); }
C
//program to print the fibonacci series upto n numbers #include<stdio.h> int main() { int n, first_term=0, second_term=1,sum=0, next_term ; printf("Enter the number of terms upto which you want to print the fibonacci series\n"); scanf("%d", &n); while(sum<=n){ printf("%d ", sum); first_term= second_term; second_term= sum; sum=first_term+second_term; } return 0; } /* say n=6 therefore the fibonacci upto n(6) terms is 0, 1, 1, 2, 3, 5 */
C
#ifndef _MY_LIST_H_ #define _MY_LIST_H_ #ifdef _MY_LIST_C_ #define _MY_LIST_C_EXT_ #else #define _MY_LIST_C_EXT_ extern #endif /* //#define container_of(ptr, type, member) ({ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ // (type *)( (char *)__mptr - offsetof(type,member) );}) */ #define __offsetof(type, member) ((unsigned long) &((type *)0)-> member) #define container_of(ptr, type, member) (type *)((char *)ptr - __offsetof(type,member)) #define prefetch(x) (x) struct list_head { struct list_head *next, *prev; }; #define LIST_HEAD_INIT(name) { &(name), &(name) } //岢ʼ #define LIST_HEAD(name) \ struct list_head name = LIST_HEAD_INIT(name) //ȡṹָ #define list_entry(ptr, type, member) \ container_of(ptr, type, member) //ȡptrһṹ #define list_first_entry(ptr, type, member) \ list_entry((ptr)->next, type, member) //=================== ======================// // #define list_for_each(pos, head) \ for (pos = (head)->next; prefetch(pos->next), pos != (head); \ pos = pos->next) //ûԤȡ #define __list_for_each(pos, head) \ for (pos = (head)->next; pos != (head); pos = pos->next) //β #define list_for_each_prev(pos, head) \ for (pos = (head)->prev; prefetch(pos->prev), pos != (head); \ pos = pos->prev) //ȫ #define list_for_each_safe(pos, n, head) \ for (pos = (head)->next, n = pos->next; pos != (head); \ pos = n, n = pos->next) //βȫ #define list_for_each_prev_safe(pos, n, head) \ for (pos = (head)->prev, n = pos->prev; \ prefetch(pos->prev), pos != (head); \ pos = n, n = pos->prev) //=================== ṹ ======================// //ṹ #define list_for_each_entry(pos, head, member, type) \ for (pos = list_entry((head)->next, type, member); \ prefetch(pos->member.next), &pos->member != (head); \ pos = list_entry(pos->member.next, type, member)) //ȫṹ #define list_for_each_entry_safe(pos, n, head, member, type) \ for (pos = list_entry((head)->next, type, member), \ n = list_entry(pos->member.next, type, member); \ &pos->member != (head); \ pos = n, n = list_entry(n->member.next, type, member)) //ṹ #define list_for_each_entry_reverse(pos, head, member, type) \ for (pos = list_entry((head)->prev, type, member); \ prefetch(pos->member.prev), &pos->member != (head); \ pos = list_entry(pos->member.prev, type, member)) //ȫṹ #define list_for_each_entry_safe_reverse(pos, n, head, member, type) \ for (pos = list_entry((head)->prev, type, member), \ n = list_entry(pos->member.prev, type, member); \ &pos->member != (head); \ pos = n, n = list_entry(n->member.prev, type, member)) _MY_LIST_C_EXT_ void list_add(struct list_head *new, struct list_head *head); _MY_LIST_C_EXT_ void list_add_tail(struct list_head *new, struct list_head *head); _MY_LIST_C_EXT_ void list_del(struct list_head *entry); _MY_LIST_C_EXT_ void list_del_init(struct list_head *entry); _MY_LIST_C_EXT_ void list_replace(struct list_head *old,struct list_head *new); _MY_LIST_C_EXT_ void list_replace_init(struct list_head *old,struct list_head *new); _MY_LIST_C_EXT_ void list_move(struct list_head *list, struct list_head *head); _MY_LIST_C_EXT_ void list_move_tail(struct list_head *list,struct list_head *head); _MY_LIST_C_EXT_ void INIT_LIST_HEAD(struct list_head *list); #endif