language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* format_hex.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: erintala <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/10/03 00:32:01 by erintala #+# #+# */ /* Updated: 2017/10/03 00:32:03 by erintala ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/ft_printf.h" int zero_case_hex(t_printf *flags, unsigned long long int i) { set_uprefix(flags); if (i == 0) { if (flags->prec == 0 && flags->width == 0) return (1); else if (flags->prec == 0 && flags->width > 0) { print_space(flags, flags->width); return (1); } if (flags->spec == 'p') ft_putstr(flags, "0x"); if (flags->prec != 0) ft_putchar(flags, '0'); return (1); } return (0); } int get_offset(t_printf *flags) { int offset; offset = 0; if (flags->spec == 'X') offset = 6; return (offset); } void print_left_hex(t_printf *flags, int num_space, int num_zero, unsigned long long int i) { if (flags->alt) { ft_putchar(flags, '0'); print_prefix(flags); } print_zero(flags, num_zero); ft_itoa_base(flags, i, 16, get_offset(flags)); print_space(flags, num_space); } void print_hex(t_printf *flags, int num_space, int num_zero, unsigned long long int i) { if (flags->pad) { if (flags->alt) { ft_putchar(flags, '0'); print_prefix(flags); } print_zero(flags, num_space); } else { print_space(flags, num_space); if (flags->alt) { ft_putchar(flags, '0'); print_prefix(flags); } } print_zero(flags, num_zero); ft_itoa_base(flags, i, 16, get_offset(flags)); } int format_hex(t_printf *flags, unsigned long long int i) { int num_space; int num_pad; int num_digits; int num_zero; num_space = 0; num_pad = 0; num_zero = 0; if (zero_case_hex(flags, i) == 1) return (1); if ((num_digits = ft_getdigits(i, 16)) < flags->prec) { num_zero = flags->prec - num_digits; num_digits = flags->prec; } if (flags->alt) num_digits += 2; if (num_digits <= flags->width) num_space = flags->width - num_digits; if (flags->left) print_left_hex(flags, num_space, num_zero, i); else print_hex(flags, num_space, num_zero, i); return (1); }
C
#include "utils/s2n_safety.h" void *malloc(__CPROVER_size_t); uint32_t nondet_uint32(); uint8_t nondet_uint8(); int main(int argc, char * const * argv){ uint8_t *a, *b; uint32_t len; int result; a = malloc(sizeof(uint8_t)); b = malloc(sizeof(uint8_t)); len = nondet_uint32(); __CPROVER_assume(len > 0 && len < 1000 && a != b); for(int i = 0; i < len; i++){ a[i] = nondet_uint8(); b[i] = nondet_uint8(); } result = s2n_constant_time_equals(a, b, len); __CPROVER_assert((result == 0 && __CPROVER_exists { int j; (j >= 0 && j < len) ==> a[j] != b[j]}) || (result > 0 && __CPROVER_forall { int j; (j >= 0 && j < len) ==> a[j] == b[j] }), "ERROR: s2n_constant_time_equals"); return 0; }
C
/* ** EPITECH PROJECT, 2019 ** strace_exe ** File description: ** jooyoung.kim@epitech.eu */ #include <stdio.h> #include <signal.h> #include <sys/ptrace.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #include <sys/user.h> #include "strace.h" pid_t *global_pid; void handler(int sig) { ptrace(PTRACE_DETACH, *global_pid, NULL, NULL); ptrace(PTRACE_CONT, *global_pid, NULL, NULL); dprintf(2, "strace: Process %d detached\n", *global_pid); exit (0); } int strace_exe(argument_t arg, char **av) { pid_t pid; int pid_stat; global_pid = &pid; signal(SIGINT, &handler); signal(SIGTERM, &handler); signal(SIGQUIT, &handler); pid = fork(); if (pid == 0) { if ((ptrace(PTRACE_TRACEME, NULL, NULL, NULL)) == -1) return (0); kill(getpid(), SIGSTOP); return (execvp(arg.content, av + 1)); } else waitpid(pid, &pid_stat, 0); return (analyse_trace(pid, &pid_stat, arg.type)); }
C
#pragma once #ifndef PARSER_H #define PARSER_H 1 #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <assert.h> #include <errno.h> #include <inttypes.h> #include <string.h> #include "macro.h" #include "types.h" #define MAGIC_SIG "DEMO\0" #define MAGIC_SIG_LEN 5 #define DATA_TYPE_ASCII 1 #define DATA_TYPE_UNICODE 2 #define DATA_TYPE_INT 3 /** * Holds information about a data block in the file. */ struct file_data_map_ent { ubyte is_end; /**< Whether to stop parsing when this entry is reached */ ubyte data_type; /**< The type of data */ size_t len; /**< The length of the data */ void *data; /**< The data */ struct file_data_map_ent *next; /**< The next entry */ }; /** * Holds the information from the file header. */ struct file_header { ubyte magic[MAGIC_SIG_LEN]; /**< The signature of the file */ ubyte version; /**< The version of the file */ size_t nblocks; /**< The number of data blocks in the file */ struct file_data_map_ent *first; /**< The first entry in the data map */ }; /** * @brief Gets the data map and the associated data. * Defined in parser.c * * @param fp A file pointer at the beginning of * where the start of the data map entry is expected. */ struct file_data_map_ent *parse_map_ent(FILE *fp); /** * @brief Parses the header of the file. * Defined in parser.c * * @param fp A file pointer at the beginning of * where the file signature is expected. */ struct file_header *parse_header(FILE *fp); #endif /* !PARSER_H */
C
#include <stdio.h> #include <stdlib.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> int foo(int a, int b) { return a+b; } int main(int argc, char *argv[]) { int a = 2; int b = 2; int (*c)(int,int); int d = 0; c = &foo; // or c = foo; d = c(a,b); printf("%d\n",d); return 0; }
C
#include <stdlib.h> #include "core.h" size_t core_get_int_length(const int integer){ if(integer > 999999999){ return 10; }else if(integer > 99999999){ return 9; }else if(integer > 9999999){ return 8; }else if(integer > 999999){ return 7; }else if(integer > 99999){ return 6; }else if(integer > 9999){ return 5; }else if(integer > 999){ return 4; }else if(integer > 99){ return 3; }else if(integer > 9){ return 2; } return 1; } int core_is_hexadecimal(const char character){ return (('0' <= character && character <= '9') && ('a' <= character && character <= 'f') && ('A' <= character && character <= 'F')); } char* core_iterami_path(const char *filename){ const char *name = getenv("USER"); size_t length_file = 0; size_t length_name = 0; while(filename[length_file] != '\0'){ length_file++; } while(name[length_name] != '\0'){ length_name++; } char *path = malloc(length_name + length_file + 16); path[0] = '/'; path[1] = 'h'; path[2] = 'o'; path[3] = 'm'; path[4] = 'e'; path[5] = '/'; int i = 0; while(i < length_name){ path[i + 6] = name[i]; i++; } path[length_name + 6] = '/'; path[length_name + 7] = 'i'; path[length_name + 8] = 't'; path[length_name + 9] = 'e'; path[length_name + 10] = 'r'; path[length_name + 11] = 'a'; path[length_name + 12] = 'm'; path[length_name + 13] = 'i'; path[length_name + 14] = '/'; i = 0; while(i < length_file){ path[i + length_name + 15] = filename[i]; i++; } path[length_name + length_file + 15] = '\0'; return path; }
C
#include "i8259.h" #include "lib.h" #include "rtc.h" #include "tests.h" #define RTC_REGISTER_PORT 0x70 #define RTC_DATA_PORT 0x71 #define NMI_MASK 0x80 #define RTC_IRQ_NUM 0x08 #define MAX_FREQ 1024 /* credit to http://wiki.osdev.org/RTC */ volatile int next_interrupt = 0; /*Initialize RTC input,output:none Effects: enable rtc pulsing at irq 8 */ void rtc_init() { unsigned rate = 0x06; //32768>>(6-1) = 1024HZ next_interrupt = 0; cli(); //When programming the RTC, it is important that the NMI (non-maskable-interrupt) and other interrupts are disabled. outb(NMI_MASK + 0x0A, RTC_REGISTER_PORT); //select port A outb(0x20, RTC_DATA_PORT); //magic number to write to initialize /*set rate*/ outb(NMI_MASK + 0x0A, RTC_REGISTER_PORT); //select port A unsigned char prev = inb(RTC_DATA_PORT); outb(NMI_MASK + 0x0A, RTC_REGISTER_PORT); //select port A outb((prev&0xF0)|rate, RTC_DATA_PORT); //&0xf0 to clear lowest 4bits, | rate to reset the rate /*turn on irq8*/ outb(NMI_MASK + 0x0B, RTC_REGISTER_PORT); //select port B prev = inb(RTC_DATA_PORT); outb(NMI_MASK + 0x0B, RTC_REGISTER_PORT); //select port B outb(prev|0x40, RTC_DATA_PORT);//use 0x40 to turn on at irq8 /*unmask irq*/ enable_irq(RTC_IRQ_NUM); sti(); } /*RTC interrupt handler input,output:none side effects: calling interruption_test */ void rtc_interrupt_handler() { cli(); next_interrupt = 1; interruption_test('r',0); /*check register C*/ //clear(); //printf("rtc is running"); outb(NMI_MASK+0x0c, RTC_REGISTER_PORT); //select C register char temp = inb(RTC_DATA_PORT); //meaningless steps temp = '\n'; send_eoi(RTC_IRQ_NUM); sti(); } /*helper function for setting frequency*/ void set_freq(int freq) { /*set rate*/ int pwr = -1,rate; while(freq > 0 ) { freq>>=1; pwr++; } rate = 15 - pwr + 1; // 15 is 2^15 = 32768 outb(NMI_MASK + 0x0A, RTC_REGISTER_PORT); //select port A unsigned char prev = inb(RTC_DATA_PORT); outb(NMI_MASK + 0x0A, RTC_REGISTER_PORT); //select port A outb((prev&0xF0)|rate, RTC_DATA_PORT); //&0xf0 to clear lowest 4bits, | rate to reset the rate } /*RTC open function input: none output: 0 side effects: set RTC freq to 2HZ */ int32_t rtc_open() { cli(); set_freq(2); sti(); return 0; } /*RTC close function input: none output: 0 side effects: None */ int32_t rtc_close() { return 0; } /*RTC read function input: none output: 0 side effects: should block until the next interrupt, then return 0. */ int32_t rtc_read() { sti(); while(next_interrupt == 0 ) {}; next_interrupt = 0; return 0; } int32_t rtc_read_wrapper(uint32_t inode, uint32_t offset, uint8_t* buf, uint32_t count) { return rtc_read(); } /*RTC write function input: freq = frequency to set, size output: 0 side effects: should block until the next interrupt, then return 0. */ int32_t rtc_write(int * freq, int size) { /*check freq validity*/ cli(); if(freq == NULL) { sti(); return -1; } if(size!= sizeof(int)) { sti(); return -1; } int temp = *freq, flag = 0; if(temp<=0) { sti(); return -1; } if(temp>MAX_FREQ) temp = MAX_FREQ; while(temp !=0) { if( ((temp&1)!=0) && ( temp!=1 ) ) flag = 1; temp>>=1; } if(flag==1) { sti(); return -1; } // freq is not power of 2 set_freq(*freq); sti(); return 0; } //See rtc_write int32_t rtc_write_wrapper(uint32_t inode, uint32_t offset, uint8_t* buf, uint32_t count) { return rtc_write((int32_t * )buf,sizeof(int32_t)); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_lines.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ydavis <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/08 19:38:55 by ydavis #+# #+# */ /* Updated: 2019/04/11 17:00:31 by ydavis ### ########.fr */ /* */ /* ************************************************************************** */ #include "main.h" void getlines_x(t_fdf *fdf) { int i; int j; t_lines *tmp; tmp = fdf->linesx; i = fdf->points->length - 1; while (i >= 0) { j = fdf->points->width - 1; while (j > 0) { if (fdf->isfirst) check_malloc(tmp->line = (t_line*)malloc(sizeof(t_line))); lines_x(fdf, i, j, tmp->line); if (j - 1 <= 0 && i - 1 < 0) break ; if (fdf->isfirst) check_malloc(tmp->next = (t_lines*)malloc(sizeof(t_lines))); tmp = tmp->next; j--; } i--; } tmp->next = NULL; } void getlines_y(t_fdf *fdf) { int i; int j; t_lines *tmp; tmp = fdf->linesy; i = fdf->points->length - 1; while (i > 0) { j = fdf->points->width - 1; while (j >= 0) { if (fdf->isfirst) check_malloc(tmp->line = (t_line*)malloc(sizeof(t_line))); lines_y(fdf, i, j, tmp->line); if (j - 1 < 0 && i - 1 <= 0) break ; if (fdf->isfirst) check_malloc(tmp->next = (t_lines*)malloc(sizeof(t_lines))); tmp = tmp->next; j--; } i--; } tmp->next = NULL; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_splitwhitespaces.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dholiday <dholiday@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/08 21:52:18 by dholiday #+# #+# */ /* Updated: 2020/03/07 19:34:59 by nhamill ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static int del_w(char **s, int i) { while (i >= 0) { free(s[i]); i--; } free(s); return (0); } static int ft_sum_w_w(char const *d, char c) { int i; int k; i = 0; k = 0; while (d[i] != '\0') { if ((d[i] != c && d[i] != '\t' && d[i] != '\n' && d[i] != '\v' && d[i] != '\f' && d[i] != '\r')) { while (d[i] != c && d[i] != '\t' && d[i] != '\n' && d[i] != '\v' && d[i] != '\f' && d[i] != '\r' && d[i] != '\0') i++; k++; } else i++; } return (k); } static int slovo_w(char **s, char const *d, char c) { int i; int j; int k; i = 0; k = 0; while (d[i] != '\0') { j = 0; if ((d[i] != c && d[i] != '\t' && d[i] != '\n' && d[i] != '\v' && d[i] != '\f' && d[i] != '\r')) { while (d[i] != c && d[i] != '\t' && d[i] != '\n' && d[i] != '\v' && d[i] != '\f' && d[i] != '\r' && d[i++] != '\0') j++; s[k] = (char*)malloc(sizeof(**s) * (j + 1)); if (!(s[k])) return (del_w(s, k)); k++; } else i++; } return (1); } static void record_w(char **s, char const *d, char c) { int i; int k; int j; i = 0; k = 0; while (d[i] != '\0') { j = -1; if (d[i] != c && d[i] != '\t' && d[i] != '\n' && d[i] != '\v' && d[i] != '\f' && d[i] != '\r') { while (d[i] != c && d[i] != '\t' && d[i] != '\n' && d[i] != '\v' && d[i] != '\f' && d[i] != '\r' && d[i] != '\0') s[k][++j] = d[i++]; s[k][++j] = '\0'; k++; } else i++; } s[k] = 0; } char **ft_splitwhitespaces(char const *str) { int sum; char **s; char c; c = ' '; if (!(str)) return (NULL); sum = ft_sum_w_w(str, c); s = (char**)malloc(sizeof(*s) * (sum + 1)); if (!(s)) return (NULL); if (!(slovo_w(s, str, c))) return (NULL); record_w(s, str, c); return (s); }
C
/*C program to convert the given decimal number into binary and count of 1's */ #include<stdio.h> int main(void) { int num, bin_val = 0, base = 1, rem, dec_val, count_One = 0, count_Zero = 0; printf("Enter decimal number -> "); scanf("%d", &num); dec_val = num; while(num > 0) { rem = num % 2; if(rem == 1) count_One++; else count_Zero++; bin_val = bin_val + rem * base; num = num / 2; base = base * 10; } printf("Decimal is: %d\n", dec_val); printf("Equivalent Binary is: %d\n", bin_val); printf("Total count of 1's is: %d\n", count_One); printf("Total count of 0's is: %d\n", count_Zero); }
C
/********************************** tcp_ser.c: the source file of the server in tcp transmission ***********************************/ #include "headsock_tcp4.h" #define BACKLOG 10 char toPrint[BUFSIZE] = {"\0"} ; void str_ser(int sockfd); // transmitting and receiving function int main(void) { //socket file descriptors int sockfd, con_fd, ret; //internet socket structures struct sockaddr_in my_addr; struct sockaddr_in their_addr; int sin_size; pid_t pid; sockfd = socket(AF_INET, SOCK_STREAM, 0); //create stream socket running over IPv4 if (sockfd < 0) { printf("Error in socket!"); exit(1); } my_addr.sin_family = AF_INET; my_addr.sin_port = htons(MYTCP_PORT); my_addr.sin_addr.s_addr = htonl(INADDR_ANY);//inet_addr("172.0.0.1"); //returns Void //places 8 null bytes in the first argument, which is a string bzero(&(my_addr.sin_zero), 8); ret = bind(sockfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr)); //bind socket if (ret < 0) { printf("Error in binding!"); exit(1); } ret = listen(sockfd, BACKLOG); //listen if (ret < 0) { printf("Error in listening!"); exit(1); } printf("Waiting for data...\n"); sin_size = sizeof (struct sockaddr_in); //this is the other socket fd which will accept, while the other, sockfd, continues to listen con_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size); //accept the packet if (con_fd < 0) { printf("Error in accept!\n"); exit(1); } //child process pid = 0 if ((pid = fork())==0) // create acception process { close(sockfd); //close this socket fd so that only one connection to this port can be made str_ser(con_fd); } else close(con_fd); //parent process close(sockfd); exit(0); } void str_ser(int sockfd) { struct pack_so recvs ; struct ack_so ack ; int n = 0; ssize_t x = 0; char buf[BUFSIZE] = {"\0"} ; char rbuf[32]; FILE * fp ; int i = 0; while (1) { ack.len = 0 ; n = recv(sockfd, &recvs, PACKLEN, MSG_WAITALL) ; //receive the packet if(n == -1) { printf("Error receiving!\n") ; break; } ack.num = recvs.num ; printf("i = %d, N = %d\n", i++, n) ; if (n == 0) break; printf("Received the packet %d %d!\n", recvs.num, recvs.len) ; printf(recvs.data) ; //getting stuck here in memcpy! coz n - headlen becomes negative!! 2-8 = -6 memcpy(buf, recvs.data, (n-HEADLEN)) ; strcat(toPrint, buf) ; x = send(sockfd, &ack, 8, 0); if(( x == -1)) { printf("Error in sending ACK\n") ; exit(1) ; } int ackNum = ack.num ; printf("ACK %d sent\n", ackNum) ; } if((fp = fopen("New.txt", "wt")) == NULL) { printf("File doesn't exist.") ; exit(0) ; } fwrite(toPrint, 1, strlen(toPrint), fp) ; fclose(fp) ; printf("A file has been successfully received!\nThe total data received is %d bytes\n", (int)strlen(toPrint)); close(sockfd); exit(0) ; }
C
/**************************************************************************** * * Copyright (c) 2012, BeiJing EFLAG Technology Co., LTD. * All rights reserved. * * ļ sensor.c * ժ Ҫ ¶ȴʵ * * ǰ汾 * EFLAG * * * ȡ汾 * ԭ * ޸ * 2012.08.01 * ******************************************************************************/ /*************ͷļ**********************************************************/ #include "sensor.h" #include "sensor_data.h" /*************궨**********************************************************/ #define CaculateTIndexTabSize(TIndexTab) \ (TIndexTab).nTableSize= \ (((TIndexTab).nIndexHigh-(TIndexTab).nIndexLow+1)/ \ (TIndexTab).nIndexFactor) /*********************************************************************/ void SensorDataInit(void); int GetTableIndex(TIndexTable * indexTab,float tabData); float NTC3950(float volt,float resi_div,float vcc); /**************************************************************************** * : SensorDataInit() * : ݳʼ * : * : ****************************************************************************/ void SensorDataInit(void) { TIndexTab_NTC3950.nIndexLow=-55; TIndexTab_NTC3950.nIndexHigh=300; TIndexTab_NTC3950.nIndexFactor=1; CaculateTIndexTabSize(TIndexTab_NTC3950); TIndexTab_NTC3950.pTableData=TableData_NTC3950; } /**************************************************************************** * : GetTableIndex() * : ݷֶȱݲѯӦ * : ֶȱѯṹ壬ֶȱ * : ڷֶȱеλ ****************************************************************************/ int GetTableIndex(TIndexTable * indexTab,float tabData) { int asc=1; int i; float a,b; if(indexTab->pTableData[0]>indexTab->pTableData[1]) { asc=-1; /* ֶȱеǵݼ */ } a=indexTab->pTableData[0]; b=indexTab->pTableData[indexTab->nTableSize-1]; if(((asc*tabData)<(asc*a))|| ((asc*tabData)>(asc*b))) { printf("out of range\r\n"); /* ѯݳֶȱΧ */ } for(i=0;i<indexTab->nTableSize-1;i++) /* ѯڷֶȱеλ */ { a=indexTab->pTableData[i]; b=indexTab->pTableData[i+1]; if((asc*tabData)<(asc*(a+b)/2)) break; } return i; } /**************************************************************************** * : NTC3950() * : 贫¶Ⱥ * : ֵѹѹֵ5Vѹֵ * : ¶ֵ ****************************************************************************/ float NTC3950(float volt,float resi_div,float vcc) { int index; float resi; float temperature; /* 㴫ֵ*/ resi=resi_div*volt/(vcc-volt); /* ѯֵڷֶȱе */ index=GetTableIndex(&TIndexTab_NTC3950,resi); temperature = TIndexTab_NTC3950.nIndexLow+index*TIndexTab_NTC3950.nIndexFactor; return temperature; } /****** (C) Ȩ2012촴¿Ƽչ޹˾ ******ĵ**************/
C
// 1. every node is either red or black // 2. root is black // 3. null leaf(sentinel) is black // 4. if a node is red, its sons are black // 5. every path from one node to all its leaves(sentinel) has same number of black nodes #include "agile_rbtree.h" static inline void rbtree_left_rotate(rbtree_node_t** root, rbtree_node_t* sentinel, rbtree_node_t* node); static inline void rbtree_right_rotate(rbtree_node_t** root, rbtree_node_t* sentinel, rbtree_node_t* node); void rbtree_insert(rbtree_t* tree, rbtree_node_t* node) { rbtree_node_t** root; rbtree_node_t* temp; rbtree_node_t* sentinel; root = (rbtree_node_t**)&tree->root; sentinel = tree->sentinel; if (*root == sentinel) { // 1. no parent, root node->parent = NULL; node->left = sentinel; node->right = sentinel; rbt_black(node); *root = node; return; } tree->insert(*root, node, sentinel); // 2. parent is black, don't adjust while (node != *root && rbt_is_red(node->parent)) { // 3. parent is red, node is red, need adjustment if (node->parent == node->parent->parent->left) { temp = node->parent->parent->right; if (rbt_is_red(temp)) { // 3.1 uncle is red, parent and uncle change to black, grandparent change to red, to fullfil rule 5 rbt_black(node->parent); rbt_black(temp); rbt_red(node->parent->parent); node = node->parent->parent; } else { if (node == node->parent->right) { // unify to 3.2 node = node->parent; rbtree_left_rotate(root, sentinel, node); } // 3.2 uncle is black, node id red, set grandparent red, set parent black, rotate right rbt_black(node->parent); rbt_red(node->parent->parent); rbtree_right_rotate(root, sentinel, node->parent->parent); } } else { temp = node->parent->parent->left; if (rbt_is_red(temp)) { // 3.1 uncle is red rbt_black(node->parent); rbt_black(temp); rbt_red(node->parent->parent); node = node->parent->parent; } else { if (node == node->parent->left) { // unify to 3.2 node = node->parent; rbtree_right_rotate(root, sentinel, node); } // 3.2 uncle is black rbt_black(node->parent); rbt_red(node->parent->parent); rbtree_left_rotate(root, sentinel, node->parent->parent); } } } rbt_black(*root); } void rbtree_delete(rbtree_t* tree, rbtree_node_t* node) { uint32_t red; rbtree_node_t** root; rbtree_node_t* sentinel; rbtree_node_t* subst; rbtree_node_t* temp; rbtree_node_t* w; root = (rbtree_node_t**)&tree->root; sentinel = tree->sentinel; if (node->left == sentinel) { temp = node->right; subst = node; } else if (node->right == sentinel) { temp = node->left; subst = node; } else { // both sons are not sentinel subst = rbtree_min(node->right, sentinel); // the leftmost nonleaf node of node->right if (subst->left != sentinel) { temp = subst->left; // it seems program never get here } else { temp = subst->right; } } if (subst == *root) { // at least one of node's son is sentinel and node is root *root = temp; rbt_black(temp); node->left = NULL; node->right = NULL; node->parent = NULL; node->key = 0; return; } red = rbt_is_red(subst); // prepare subst to replace node's position if (subst == subst->parent->left) { subst->parent->left = temp; } else { subst->parent->right = temp; } if (subst == node) { temp->parent = subst->parent; } else { if (subst->parent == node) { temp->parent = subst; // it seems that it change nothing } else { temp->parent = subst->parent; } // subst replace node subst->left = node->left; subst->right = node->right; subst->parent = node->parent; rbt_copy_color(subst, node); if (node == *root) { *root = subst; } else { if (node == node->parent->left) { node->parent->left = subst; } else { node->parent->right = subst; } } if (subst->left != sentinel) { subst->left->parent = subst; } if (subst->right != sentinel) { subst->right->parent = subst; } } node->left = NULL; node->right = NULL; node->parent = NULL; node->key = 0; if (red) return; // subst's original color is red, a red node eleminated do not volate rule 5 // subst's original color is black, a black node eleminated could affect rule 5 while (temp != *root && rbt_is_black(temp)) { // loop to adjust the whole tree, if temp is red, quit loop, // then after the loop program will set it black to add one black node on this tree if (temp == temp->parent->left) { w = temp->parent->right; if (rbt_is_red(w)) { // unify rbt_black(w); rbt_red(temp->parent); rbtree_left_rotate(root, sentinel, temp->parent); w = temp->parent->right; } // w is black if (rbt_is_black(w->left) && rbt_is_black(w->right)) { // both w's sons are black // set w red, subtract one black node, continue to check the whole tree rbt_red(w); temp = temp->parent; } else { if (rbt_is_black(w->right)) { // unify rbt_black(w->left); rbt_red(w); rbtree_right_rotate(root, sentinel, w); w = temp->parent->right; } // w->right is red, w->left is black // black node number restore, set temp to root to quit loop rbt_copy_color(w, temp->parent); rbt_black(temp->parent); rbt_black(w->right); rbtree_left_rotate(root, sentinel, temp->parent); temp = *root; } } else { w = temp->parent->left; if (rbt_is_red(w)) { rbt_black(w); rbt_red(temp->parent); rbtree_right_rotate(root, sentinel, temp->parent); w = temp->parent->left; } if (rbt_is_black(w->left) && rbt_is_black(w->right)) { rbt_red(w); temp = temp->parent; } else { if (rbt_is_black(w->left)) { rbt_black(w->right); rbt_red(w); rbtree_left_rotate(root, sentinel, w); w = temp->parent->left; } rbt_copy_color(w, temp->parent); rbt_black(temp->parent); rbt_black(w->left); rbtree_right_rotate(root, sentinel, temp->parent); temp = *root; } } } rbt_black(temp); } void rbtree_insert_node(rbtree_node_t* temp, rbtree_node_t* node, rbtree_node_t* sentinel) { rbtree_node_t** p; for (;;) { p = (node->key < temp->key) ? &temp->left : &temp->right; if (*p == sentinel) break; temp = *p; } *p = node; node->parent = temp; node->left = sentinel; node->right = sentinel; rbt_red(node); } rbtree_node_t* rbtree_find_key(rbtree_t* tree, rbtree_key_t key) { rbtree_node_t* p = tree->root; while (p != tree->sentinel) { if (p->key == key) return p; p = (p->key < key) ? p->right : p->left; } return NULL; } static inline void rbtree_left_rotate(rbtree_node_t** root, rbtree_node_t* sentinel, rbtree_node_t* node) { rbtree_node_t* temp; temp = node->right; node->right = temp->left; if (temp->left != sentinel) { temp->left->parent = node; } temp->parent = node->parent; if (node == *root) { *root = temp; } else if (node == node->parent->left) { node->parent->left = temp; } else { node->parent->right = temp; } temp->left = node; node->parent = temp; } static inline void rbtree_right_rotate(rbtree_node_t** root, rbtree_node_t* sentinel, rbtree_node_t* node) { rbtree_node_t* temp; temp = node->left; node->left = temp->right; if (temp->right != sentinel) { temp->right->parent = node; } temp->parent = node->parent; if (node == *root) { *root = temp; } else if (node == node->parent->right) { node->parent->right = temp; } else { node->parent->left = temp; } temp->right = node; node->parent = temp; } //////////////////////////////////////////////////////////////// #include <stdio.h> #include <stdlib.h> static rbtree_node_t* insert_pair(rbtree_t* rbt, int id, u_char character) { rbtree_node_t* node = (rbtree_node_t*)malloc(sizeof (*node)); if (node == NULL) return NULL; node->key = id; node->data = character; rbtree_insert(rbt, node); return node; } static void inorder_print(rbtree_t* rbt, rbtree_node_t* node) { if (node == rbt->sentinel) return; inorder_print(rbt, node->left); printf(" %d - %c\n", (int)node->key, node->data); inorder_print(rbt, node->right); } static void print_tree(rbtree_t* rbt) { printf("print tree:\n"); inorder_print(rbt, rbt->root); } void test_agile_rbtree() { int i; rbtree_node_t* node; rbtree_node_t *n1, *n2, *n3, *n4, *n5, *n6; rbtree_t rbt; rbtree_node_t sentinel; rbtree_sentinel_init(&sentinel); rbtree_init(&rbt, &sentinel, rbtree_insert_node); n4 = insert_pair(&rbt, 4, 'd'); n3 = insert_pair(&rbt, 3, 'c'); n1 = insert_pair(&rbt, 1, 'a'); n2 = insert_pair(&rbt, 2, 'b'); n6 = insert_pair(&rbt, 6, 'f'); n5 = insert_pair(&rbt, 5, 'e'); for (i=1; i<=6; ++i) { node = rbtree_find_key(&rbt, i); if (node) { printf("%d : %c\n", i, node->data); } else { printf("failure with key:%d\n", i); } } node = rbtree_find_key(&rbt, 0); if (node == NULL) printf("success with key:0\n"); else printf("failure with key:0\n"); node = rbtree_find_key(&rbt, 7); if (node == NULL) printf("success with key:7\n"); else printf("failure with key:7\n"); print_tree(&rbt); rbtree_delete(&rbt, n3); free(n3); n3 = NULL; print_tree(&rbt); // to delete other nodes... }
C
/* ** This program reads a cafeteria data file or a pedometer file ** and cuts out windows of bites or steps. ** Bite indices are determined via gt_union.txt. ** Step indices are determined via steps.txt. ** The type of file is determined by which of those two GT is present. ** ** The data is cut from N sec prior to first GT event to N sec after ** last GT event. Each window is N sec (30 sec default for bites, ** 5 sec default for steps). ** ** The GT class of the window is the (integer) number of events. ** ** Have not yet tried: ** -- separating bites into dominant (instrumented) ** hand, nondominant hand, and both hands. ** ** Have tried: ** -- event is a span rather than single time instant; overlap can ** be a portion of 1.0 depending on span overlap with window */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_DATA 54000 /* one hour at 15 Hz */ #define MAX_EVENTS 1500 #define MAX_WINDOWS 20000 int main(int argc, char *argv[]) { FILE *fpt; char filename[320]; int i,j,k; float zero[3],total; float yaw,pitch,roll; float *Data[7],*SmoothedData[7]; int TotalData; int GTEventIndex[MAX_EVENTS]; /* data index of GT bite or step */ char GTBiteHand[MAX_EVENTS][16]; /* left, right or both */ char GTBiteUtensil[MAX_EVENTS][16]; /* fork, hand, spoon, chopsticks */ char GTBiteContainer[MAX_EVENTS][16];/* plate, bowl, mug, glass */ char GTBiteFood[MAX_EVENTS][320]; /* anything */ int GTStepFoot[MAX_EVENTS]; /* 0=>l 1=>r 2=>ledge 3=>redge */ int BiteNumber,TotalGTEvents; int TotalWindows,WindowIndex[MAX_WINDOWS]; float WindowEventCount[MAX_WINDOWS]; int WindowStart,WindowEnd; int start,end,smallest,largest; int FileType; /* 0=>steps, 1=>bites */ char text[320],separators[5]; int WindowSize,WindowStep; if (argc != 2) { printf("Usage: cutwindows [filename.txt]\n"); printf(" assumes there is a gt_union.txt in same folder\n"); printf(" or there is a steps.txt in same folder\n"); exit(0); } for (i=0; i<7; i++) { Data[i]=(float *)calloc(MAX_DATA,sizeof(float)); SmoothedData[i]=(float *)calloc(MAX_DATA,sizeof(float)); } if (strcmp(&(argv[1][strlen(argv[1])-3]),"csv") == 0) { FileType=0; /* pedometer data */ WindowSize=15*5; /* cutting 5 sec at 15 Hz */ WindowStep=5; /* sliding window 1/3 sec at 15 Hz */ } else { FileType=1; /* cafeteria data */ WindowSize=15*5; /* cutting 20 sec at 15 Hz */ WindowStep=15; /* sliding window 1 sec at 15 Hz */ } if ((fpt=fopen(argv[1],"rb")) == NULL) { printf("Unable to open %s for reading\n",argv[1]); exit(0); } if (FileType == 1) { /* read data file, determine total amount of data */ TotalData=0; /* file format is x y z (accel units are volts) ** yaw pitch roll (gyro units are volts) scale (units are grams) */ zero[0]=zero[1]=zero[2]=0.0; /* used to calculate avg of yaw pitch roll */ while (1) { i=fscanf(fpt,"%f %f %f %f %f %f %f", &(Data[0][TotalData]),&(Data[1][TotalData]), &(Data[2][TotalData]), /* x y z */ &(Data[3][TotalData]),&(Data[4][TotalData]), &(Data[5][TotalData]), /* yaw pitch roll */ &(Data[6][TotalData])); /* scale */ if (i != 7) break; for (j=0; j<3; j++) zero[j]+=Data[j+3][TotalData]; TotalData++; } for (j=0; j<3; j++) zero[j]/=(float)TotalData; /* convert data voltages to deg/sec (gyros) ** and gravities (accelerometers) ** gyro=LPY410al, 2.5mv per deg/sec, zero-point found ** by calculating the average data value of the whole recording ** accel=LIS344alh, Vdd=3.3v, 5/3.3=1.515 gravities per volt */ for (i=0; i<TotalData; i++) { /* 3.3v supply so 1/2(3.3)=1.65 reference */ /* 15/3.3=4.5454 instead, if chip wired to +-6g */ for (j=0; j<3; j++) Data[j][i]=(Data[j][i]-1.65)*(5.0/3.3); /* reference voltage calculated as average ADC value for while file */ for (j=3; j<6; j++) Data[j][i]=(Data[j][i]-zero[j-3])*400.0; } } else { fgets(text,320,fpt); /* "sep=\t " (header line) (tab and space) */ for (i=0; i<2; i++) /* field names, units */ { for (j=0; j<17; j++) { fscanf(fpt,"%[^\t\n\r]",text); fread(&(separators[0]),1,1,fpt); /* extra space separator */ } fread(&(separators[0]),1,2,fpt); /* extra tab/newline */ } TotalData=0; while (1) { i=fscanf(fpt,"%[^\t\n\r]",text); fread(&(separators[0]),1,1,fpt); /* extra space separator */ if (i != 1 || strlen(text) == 0) break; for (j=1; j<17; j++) { fscanf(fpt,"%[^\t\n\r]",text); fread(&(separators[0]),1,1,fpt); /* extra space separator */ if (j == 7) /* gyroX */ Data[3][TotalData]=(float)atof(text); if (j == 8) /* gyroY */ Data[4][TotalData]=(float)atof(text); if (j == 9) /* gyroZ */ Data[5][TotalData]=(float)atof(text); if (j == 10) /* accX */ Data[0][TotalData]=(float)atof(text); if (j == 11) /* accY */ Data[1][TotalData]=(float)atof(text); if (j == 12) /* accZ */ Data[2][TotalData]=(float)atof(text); } TotalData++; fread(&(separators[0]),1,1,fpt); /* newline */ } } fclose(fpt); /* smooth the data (but not scale axis) */ for (i=0; i<7; i++) /* #data */ for (j=0; j<6; j++) /* #axes */ SmoothedData[j][i]=Data[j][i]; for (i=TotalData-7; i<TotalData; i++) for (j=0; j<6; j++) SmoothedData[j][i]=Data[j][i]; for (i=7; i<TotalData-7; i++) { for (j=0; j<6; j++) { /* averaging over a 1-sec window (15 samples) centered on the datum */ total=0.0; for (k=i-7; k<=i+7; k++) if (k >= 0 && k < TotalData) total+=Data[j][k]; SmoothedData[j][i]=total/15.0; } } if (FileType == 1) { /* load GT bites */ strcpy(filename,argv[1]); j=strlen(filename)-1; while (j > 0 && filename[j] != '/' && filename[j] != '\\') j--; filename[j+1]=0; strcat(filename,"gt_union.txt"); if ((fpt=fopen(filename,"r")) == NULL) { printf("Unable to open %s for reading\n",filename); exit(0); } TotalGTEvents=0; while (1) { i=fscanf(fpt,"%d %d %s %s %s %s", &BiteNumber,&(GTEventIndex[TotalGTEvents]), GTBiteHand[TotalGTEvents],GTBiteUtensil[TotalGTEvents], GTBiteContainer[TotalGTEvents],GTBiteFood[TotalGTEvents]); if (i != 6) break; TotalGTEvents++; } fclose(fpt); } else { /* load GT steps */ strcpy(filename,argv[1]); j=strlen(filename)-1; while (j > 0 && filename[j] != '/' && filename[j] != '\\') j--; filename[j+1]=0; strcat(filename,"steps.txt"); if ((fpt=fopen(filename,"r")) == NULL) { printf("Unable to open %s for reading\n",filename); exit(0); } TotalGTEvents=0; while (1) { i=fscanf(fpt,"%d %s", &(GTEventIndex[TotalGTEvents]),text); if (i != 2) break; if (strcmp(text,"l") == 0) GTStepFoot[TotalGTEvents]=0; else if (strcmp(text,"r") == 0) GTStepFoot[TotalGTEvents]=1; else if (strcmp(text,"ledge") == 0) GTStepFoot[TotalGTEvents]=2; else if (strcmp(text,"redge") == 0) GTStepFoot[TotalGTEvents]=3; else { printf("Unknown step type: %s\n",text); exit(0); } TotalGTEvents++; } fclose(fpt); } /* ** Determine start and end points. These are the left side of ** the windows being cut. ** Start cutting windows WindowSize prior to first event. ** This window will end one datum before the first bite. ** Finish cutting at WindowStep data after last event. ** This window will start at least one datum after the last event. ** This way the first and last windows have 0.0 event count. ** If the device was not recording for part of the boundary ** window(s), then pad the data with zeroes. */ smallest=largest=0; /* find first/last, in case they are not sorted */ for (i=1; i<TotalGTEvents; i++) { if (GTEventIndex[i] < GTEventIndex[smallest]) smallest=i; if (GTEventIndex[i] > GTEventIndex[largest]) largest=i; } start=GTEventIndex[smallest]-WindowSize; end=GTEventIndex[largest]+WindowStep; TotalWindows=0; for (i=start; i<=end; i+=WindowStep) /* i is left side of window */ { WindowIndex[TotalWindows]=i; WindowEventCount[TotalWindows]=0.0; WindowStart=i; WindowEnd=i+WindowSize-1; for (j=0; j<TotalGTEvents; j++) { if (GTEventIndex[j] >= i && GTEventIndex[j] < i+WindowSize) WindowEventCount[TotalWindows]+=1.0; } TotalWindows++; } /* print out cut data */ for (i=0; i<TotalWindows; i++) { if (0) /* use this line for debugging counts by comparing to GUI */ printf("%d...%d -> %.3lf\n",WindowIndex[i],WindowIndex[i]+WindowSize-1, WindowEventCount[i]); else { printf("%.3lf",WindowEventCount[i]); /* class is #bites */ for (k=WindowIndex[i]; k<WindowIndex[i]+WindowSize; k++) { for (j=0; j<6; j++) if (k < 0 || k >= TotalData) printf("\t0.0"); else printf("\t%.3f",SmoothedData[j][k]); } printf("\n"); } } for (i=0; i<7; i++) { free(Data[i]); free(SmoothedData[i]); } } /* code snippet that calculated bite count within window contribution ** according to overlap of bite segment with window segment #define BITE_LENGTH 15*3 // 3 sec at 15 Hz (+1 datum at the index) int BiteStart,BiteEnd,WindowStart,WindowEnd,a,b; float Overlap; int start,end; for (i=start; i<=end; i+=WINDOW_STEP) { if (i+WINDOW_SIZE > end) break; // not a full window WindowIndex[TotalWindows]=i; FloatWindowBites[TotalWindows]=0.0; WindowStart=i; WindowEnd=i+WINDOW_SIZE-1; for (j=0; j<TotalGTBites; j++) { BiteStart=GTBiteIndex[j]-BITE_LENGTH/2; BiteEnd=GTBiteIndex[j]+BITE_LENGTH/2; // this test for overlap assumes WINDOW_SIZE > BITE_LENGTH if ((BiteStart >= WindowStart && BiteStart <= WindowEnd) || (BiteEnd >= WindowStart && BiteEnd <= WindowEnd)) { if (BiteStart < WindowStart) a=WindowStart; else a=BiteStart; if (BiteEnd > WindowEnd) b=WindowEnd; else b=BiteEnd; Overlap=(float)(b-a+1)/((float)BITE_LENGTH); FloatWindowBites[TotalWindows]+=Overlap; } } TotalWindows++; } */
C
/** @file ESP8266.h * @brief ESP8266 Driver V 1.0 * * Created on: May 26, 2020 * Handles sending to a Local server with only one connection. * * @author Alaa AbdAlrhman * @bug no known bugs */ #ifndef ESP8266_H_ #define ESP8266_H_ #include "Utils.h" #include "Std_Types.h" #include "../UART/UART.h" /*@brief * * Mode : mode of Operation ( 1-> Station mode, 1-> Access point mode, 3-> Access Point and Station mode) * SSID : WiFi Network name to join * Pssword : Password of WiFi Network to join * * */ struct ESP_INIT_PARAM { uint8_t mode ; // station mode uint8_t SSID [20] ; uint8_t PASSWORD [20]; uint8_t GETRequest[300]; char host[60]; uint8_t port; char ConnectionType[4]; }; /*@brief * * Mode : mode of Operation ( 1-> Station mode, 1-> Access point mode, 3-> Access Point and Station mode) * * */ enum ESP_MODS { station =1, accessPoint =2, stationAccessPoint=3 }; /*@brief * * Some Used Enums for Control * * */ enum { noOption =255, ok=1, error=2, }; enum ESPNetwork { Wait = 0, Connected =1, NotConnected =7 }; enum ESPListen { ListenWait = 0, Found =1, Timeout =2 }; enum ESP_STATUS { CONNECTED_TO_AP=2, TRANSMISSION_CONNECTED, TRANSMISSION_DISCONNECTED, NOT_CONNECTED_TO_AP, UNKNOWN_ERROR, }; void wifiMainFunctuion (); /*@brief * * Used to Initialize Esp and set it's Mode to * ( 1, Station ) , ( 2, Access point) , ( 3, Access point and Station) * * *@return ( 1 ,Configuration is Done) ( 0, Wait) * */ uint8_t ESP8266_Init(); /*@brief * * Used to check Esp Status * Example : STATUS = 2 >> Esp is connected to Access Point * Example : STATUS = 3 >> Esp is Connected to transmission channel * Example : STATUS = 4 >> Esp is not Connected to transmission channel * Example : STATUS = 5 >> Esp is not connected to Access point. * * *@return STATUS ( (2,CONNECTED_TO_AP) , (3,TRANSMISSION_CONNECTED) ,(4 TRANSMISSION_DISCONNECTED ),(5 ,UNKNOWN_ERROR ) ,( 7 ,NotConnected >> TimeOut Error)) * */ enum ESP_STATUS ESP8266_u8CheckStatues (); /*@brief * *Used to send Commands to Esp * *@param command: Command to send Ex ( AT, AT+SIFR, AT+CIPSEND ...) *@param option : in case command has options Ex ( AT+CWMODE=1 )..(1 .. is Option for the command (AT+CWMODE) *@param query : in case command with querey Ex ( AT+CWMODE=? ) *@return void * */ void ESP8266_vidSendCommand(uint8_t * command); /*@brief * *Used to Join to Network with Defined SSID and Password in structure "ESP_INIT_PARAM" * *@return ( 0 Wait), ( 1 Connected ), (7 NotConnected >> Timeout error) * */ uint8_t ESP_vidJoinNetwork (); /*@brief * *Used to Check IP State. prints the IPs if there are any. *@return ( 0 Wait), ( 1 Done ) * */ uint8_t ESP_vidCheckForIP(); /*@brief * * Used to Listen to the ESP UART bus for Specified word * Example ESP8266_vidListen("OK",5, 500); * The function will wait for "OK" to show up before 500 tick happens * if OK is found it will fetch it with another 3 characters after it, * else if 500 ticks happens before it found it will return a time out error * *@param wordToFind : word to search for at ESP UART bus *@param sizeOfStringToFetch : Size of string to fetch *@param timeOut : time in tick which after it the timeout error will show up *@return ( 0 Wait), ( 1 Found ), (2 Timeout >> Timeout error) * */ uint8_t ESP8266_vidListen(uint8_t * wordToFind,uint8_t sizeOfStringToFetch, uint16_t timeOut ); /*@brief * * Used to Create a server on the port declared in param structure * *@return ( 1 , Ok >> Server created successfully ) ,( 0 , Wait) * * */ uint8_t ESP8266_u8CreateServer( ); /*@brief * *Used to check for connection request ( usually by browsers accessing IP address of the ESP ) * *@return ( 1 , Found >> Connection Request found ) ,( 0 , Wait),(2, Timeout >> timeout error) * */ uint8_t ESP8266_u8CheckForConnectionRequest(); /*@brief * * Used to open a connection to a host with a specified Connection type ( TCP,UDP) * to host on a port defined in param structure * *@param dataSize : number of data to be sent * * */ uint8_t ESP8266_u8ConnectToHost(); /*@brief * * Used to send Get Request defined in Param structure to an opened connection * * * *@return ( 1 , DataSent >> Connection created ) ,( 0 , Wait),(7,NotConnected >> Timeout error) * */ uint8_t ESP8266_u8SendGETDataToOpendConnection(); /*@brief * *Used to close opened connection *@return ( 1 , Ok >> Connection closed ) ,( 0 , Wait) * */ uint8_t ESP8266_vidCloseConnection(); /*@brief * *Example demonstrating using of ESP8266 driver APIs * * * */ uint8_t ESP8266_Example(); #endif /* ESP8266_H_ */
C
#include "RSXABOUTconfig.h" void border(unsigned char nColorIndex) { #ifdef RSXABOUT_BORDER __asm ; &BC38 AF,BC,DE and HL are corrupted push af push bc push de push hl LD d, #0x00 LD e, 4 (ix) LD (TABLE), de LD A,#0x01 ;un seul paramètre LD IX,#TABLE ; le paramètre : 4 (border 4) LD HL,#0xC00C ; un jp c'est 3, un defw c'est 2 LD C,#0x04 ; ùhelp dit 4 CALL #0x001B ;lancer la commande RSX pop hl pop de pop bc pop af TABLE: .DW 0x0006 ; PARAM1 __endasm; #else __asm ld b, 4 (ix) ld c, b call #0xBC38 ;SCR SET INK __endasm; #endif } void set_color(unsigned char nColorIndex, unsigned char nPaletteIndex) { #ifdef RSXABOUT_SETCOLOR __asm ; &BC32 AF,BC,DE and HL are corrupted push af push bc push de push hl LD d, #0x00 LD e, 4 (ix) ; #0x01 palette LD (TABLE2), de LD d, #0x00 LD e, 5 (ix) ; couleur LD (TABLE2+2), de LD A,#0x02 ;deux paramètres LD IX,#TABLE2 ; le paramètre : 4 (border 4) LD HL,#0xC00F ; un jp c'est 3, un defw c'est 2 LD C,#0x04 ; ùhelp dit 4 CALL #0x001B ;lancer la commande RSX pop hl pop de pop bc pop af TABLE2: .DW 0x0001 ;PARAM21 .DW 0x0006 ;PARAM22 __endasm; #else __asm ld a, 4 (ix) ld b, 5 (ix) ld c, b call #0xBC32 ;SCR SET INK __endasm; #endif } void set_palette(unsigned char *pPalette) { unsigned char nColor = 0; for(nColor = 0; nColor < 16; nColor++) { set_color(nColor, pPalette[nColor]); } } /** * JDVA#2 Passage en mode 0 et tracé de point lent */ // char --> -128 +128 // unsigned --> char 0..255 void mode(unsigned char m) { #ifdef RSXABOUT_MODE __asm ; #BC32 AF, BC, DE and HL corrupt push af push bc push de push hl LD d, #0x00 LD e, 4 (ix) LD (TABLE3), de LD A,#0x01 ;un seul paramètre LD IX,#TABLE3 ; le paramètre : 4 (border 4) LD HL,#0xC012 ; un jp c'est 3, un defw c'est 2 LD C,#0x04 ; ùhelp dit 4 CALL #0x001B ;lancer la commande RSX pop hl pop de pop bc pop af TABLE3: .DW 0x0000 ;PARAM21 __endasm; #else __asm ld A,4 (IX) call #0xBC0E __endasm; #endif }
C
/* ** EPITECH PROJECT, 2020 ** add_mul.c ** File description: ** add_mul */ #include "mem_ptr.h" static void test_add_str ( void ) { char *str1 = "Hey, "; char *str2 = "it works !"; char *res ; add_str (str1, str2, &res ) ; printf ("%s\n", res ) ; } static void test_add_str_struct ( void ) { char * str1 = "Hey, "; char * str2 = "it works !"; str_op_t str_op ; str_op . str1 = str1 ; str_op . str2 = str2 ; add_str_struct (& str_op ) ; printf ("%s\n", str_op . res ) ; } int main ( void ) { test_add_str () ; test_add_str_struct () ; return (0) ; }
C
#include "leptjson.h" #include <assert.h> /* assert() */ #include <stdlib.h> /* NULL, strtod() */ #include <errno.h> #include <math.h> #define EXPECT(c, ch) do { assert(*c->json == (ch)); c->json++; } while(0) #define IS_DIGIT(c) ((c)>='0'&&(c)<='9') typedef struct { const char* json; }lept_context; static void lept_parse_whitespace(lept_context* c) { const char *p = c->json; while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') p++; c->json = p; } static int lept_parse_literal(lept_context* c, lept_value* v, lept_type t, const char* literal) { EXPECT(c, literal[0]); size_t id = 1; for (; literal[id]; ++id) { if (c->json[id - 1] != literal[id]) { return LEPT_PARSE_INVALID_VALUE; } } c->json += id - 1; v->type = t; return LEPT_PARSE_OK; } static int consume_number(const char** s) { const char* cursor = *s; while (IS_DIGIT(*cursor)) { ++cursor; } if (*s == cursor) { return 0; } *s = cursor; return 1; } static int is_valid_number(const char* s, char** end) //end is returned only if number is valid { if (s[0] == '-') { ++s; } if (s[0] == '0') { ++s; } else if (!consume_number(&s)) { return 0; } if (s[0] == '.' && !(++s, consume_number(&s))) { return 0; } if ((s[0] == 'E' || s[0]=='e')) { ++s; if (s[0] == '+' || s[0] == '-') { ++s; } if (!consume_number(&s)) { return 0; } } *end = s; return 1; } static int lept_parse_number(lept_context* c, lept_value* v) { char* end; /* \TODO validate number */ if (!is_valid_number(c->json, &end)) { return LEPT_PARSE_INVALID_VALUE; } char tc = *end; *end = '\0'; //trick herejust to make sure **strtod** doesn't convert a longer substring v->n = strtod(c->json, &end); *end = tc; //restore the actual end character if (c->json == end) return LEPT_PARSE_INVALID_VALUE; if (errno == ERANGE && (v->n == HUGE_VAL || v->n == -HUGE_VAL)) { errno = 0; return LEPT_PARSE_NUMBER_TOO_BIG; } c->json = end; v->type = LEPT_NUMBER; return LEPT_PARSE_OK; } static int lept_parse_value(lept_context* c, lept_value* v) { switch (*c->json) { case 't': return lept_parse_literal(c, v, LEPT_TRUE, "true"); case 'f': return lept_parse_literal(c, v, LEPT_FALSE, "false"); case 'n': return lept_parse_literal(c, v, LEPT_NULL, "null"); default: return lept_parse_number(c, v); case '\0': return LEPT_PARSE_EXPECT_VALUE; } } int lept_parse(lept_value* v, const char* json) { lept_context c; int ret; assert(v != NULL); c.json = json; v->type = LEPT_NULL; lept_parse_whitespace(&c); if ((ret = lept_parse_value(&c, v)) == LEPT_PARSE_OK) { lept_parse_whitespace(&c); if (*c.json != '\0') { v->type = LEPT_NULL; ret = LEPT_PARSE_ROOT_NOT_SINGULAR; } } return ret; } lept_type lept_get_type(const lept_value* v) { assert(v != NULL); return v->type; } double lept_get_number(const lept_value* v) { assert(v != NULL && v->type == LEPT_NUMBER); return v->n; }
C
/* solveT.c */ #include "SubMtx.h" #define MYDEBUG 0 /*--------------------------------------------------------------------*/ static void real_solveDenseSubrows ( SubMtx *mtxA, SubMtx *mtxB ) ; static void real_solveDenseSubcolumns ( SubMtx *mtxA, SubMtx *mtxB ) ; static void real_solveSparseRows ( SubMtx *mtxA, SubMtx *mtxB ) ; static void real_solveSparseColumns ( SubMtx *mtxA, SubMtx *mtxB ) ; static void complex_solveDenseSubrows ( SubMtx *mtxA, SubMtx *mtxB ) ; static void complex_solveDenseSubcolumns ( SubMtx *mtxA, SubMtx *mtxB ); static void complex_solveSparseRows ( SubMtx *mtxA, SubMtx *mtxB ) ; static void complex_solveSparseColumns ( SubMtx *mtxA, SubMtx *mtxB ) ; /*--------------------------------------------------------------------*/ /* ----------------------------------------------------------------- purpose -- solve (A^T + I) X = B, where (1) X overwrites B (2) A must be strict lower or upper triangular (3) columns(A) = rows(X) (4) rows(A) = rows(B) (5) B has type SUBMTX_DENSE_COLUMNS (6) if A is SUBMTX_DENSE_SUBROWS or SUBMTX_SPARSE_ROWS then A must be strict lower triangular (7) if A is SUBMTX_DENSE_SUBCOLUMNS or SUBMTX_SPARSE_COLUMNS then A must be strict upper triangular created -- 98may01, cca ----------------------------------------------------------------- */ void SubMtx_solveT ( SubMtx *mtxA, SubMtx *mtxB ) { /* --------------- check the input --------------- */ if ( mtxA == NULL || mtxB == NULL ) { fprintf(stderr, "\n fatal error in SubMtx_solveT(%p,%p)" "\n bad input\n", mtxA, mtxB) ; exit(-1) ; } if ( ! SUBMTX_IS_DENSE_COLUMNS(mtxB) ) { fprintf(stderr, "\n fatal error in SubMtx_solveT(%p,%p)" "\n mtxB has bad type %d\n", mtxA, mtxB, mtxB->type) ; exit(-1) ; } if ( mtxA->nrow != mtxB->nrow ) { fprintf(stderr, "\n fatal error in SubMtx_solveT(%p,%p)" "\n mtxA->nrow = %d, mtxB->nrwo = %d\n", mtxA, mtxB, mtxA->nrow, mtxB->nrow) ; exit(-1) ; } /* ------------------------- switch over the type of A ------------------------- */ switch ( mtxA->type ) { case SPOOLES_REAL : /* ------------------------- switch over the mode of A ------------------------- */ switch ( mtxA->mode ) { case SUBMTX_DENSE_SUBROWS : real_solveDenseSubrows(mtxA, mtxB) ; break ; case SUBMTX_SPARSE_ROWS : real_solveSparseRows(mtxA, mtxB) ; break ; case SUBMTX_DENSE_SUBCOLUMNS : real_solveDenseSubcolumns(mtxA, mtxB) ; break ; case SUBMTX_SPARSE_COLUMNS : real_solveSparseColumns(mtxA, mtxB) ; break ; default : fprintf(stderr, "\n fatal error in SubMtx_solveT(%p,%p)" "\n bad mode %d\n", mtxA, mtxB, mtxA->mode) ; exit(-1) ; break ; } break ; case SPOOLES_COMPLEX : /* ------------------------- switch over the mode of A ------------------------- */ switch ( mtxA->mode ) { case SUBMTX_DENSE_SUBROWS : complex_solveDenseSubrows(mtxA, mtxB) ; break ; case SUBMTX_SPARSE_ROWS : complex_solveSparseRows(mtxA, mtxB) ; break ; case SUBMTX_DENSE_SUBCOLUMNS : complex_solveDenseSubcolumns(mtxA, mtxB) ; break ; case SUBMTX_SPARSE_COLUMNS : complex_solveSparseColumns(mtxA, mtxB) ; break ; default : fprintf(stderr, "\n fatal error in SubMtx_solveT(%p,%p)" "\n bad mode %d\n", mtxA, mtxB, mtxA->mode) ; exit(-1) ; break ; } break ; default : fprintf(stderr, "\n fatal error in SubMtx_solveT(%p,%p)" "\n bad type %d\n", mtxA, mtxB, mtxA->type) ; exit(-1) ; break ; } return ; } /*--------------------------------------------------------------------*/ /* --------------------------------------- purpose -- solve (A^T + I) X = B, where (1) A is strictly upper triangular (2) X overwrites B (B) B has type SUBMTX_DENSE_COLUMNS created -- 98feb19, cca --------------------------------------- */ static void real_solveDenseSubcolumns ( SubMtx *mtxA, SubMtx *mtxB ) { double Aki, sum0, sum1, sum2 ; double *colB0, *colB1, *colB2, *entriesA, *entriesB ; int first, ii, inc1, inc2, irowA, jcolB, kk, last, ncolB, nentA, nrowA, nrowB ; int *firstlocsA, *sizesA ; /* ---------------------------------------------------- extract the pointer and dimensions from two matrices ---------------------------------------------------- */ SubMtx_denseSubcolumnsInfo(mtxA, &nrowA, &nentA, &firstlocsA, &sizesA, &entriesA) ; SubMtx_denseInfo(mtxB, &nrowB, &ncolB, &inc1, &inc2, &entriesB) ; #if MYDEBUG > 0 fprintf(stdout, "\n nentA = %d", nentA) ; fflush(stdout) ; #endif colB0 = entriesB ; for ( jcolB = 0 ; jcolB < ncolB - 2 ; jcolB += 3 ) { colB1 = colB0 + nrowB ; colB2 = colB1 + nrowB ; #if MYDEBUG > 0 fprintf(stdout, "\n %% jcolB = %d", jcolB) ; fflush(stdout) ; #endif for ( irowA = kk = 0 ; irowA < nrowA ; irowA++ ) { #if MYDEBUG > 0 fprintf(stdout, "\n %% irowA %d, size %d", irowA, sizesA[irowA]) ; fflush(stdout) ; #endif if ( sizesA[irowA] > 0 ) { first = firstlocsA[irowA] ; last = first + sizesA[irowA] - 1 ; #if MYDEBUG > 0 fprintf(stdout, ", first %d, last %d", first, last) ; fflush(stdout) ; #endif sum0 = sum1 = sum2 = 0.0 ; for ( ii = first ; ii <= last ; ii++, kk++ ) { Aki = entriesA[kk] ; #if MYDEBUG > 0 fprintf(stdout, "\n %% Aki A(%d,%d) = %12.4e", irowA+1, ii+1, Aki) ; fflush(stdout) ; #endif sum0 += Aki * colB0[ii] ; sum1 += Aki * colB1[ii] ; sum2 += Aki * colB2[ii] ; } colB0[irowA] -= sum0 ; colB1[irowA] -= sum1 ; colB2[irowA] -= sum2 ; } } #if MYDEBUG > 0 fprintf(stdout, "\n %% kk = %d", kk) ; fflush(stdout) ; #endif colB0 = colB2 + nrowB ; } if ( jcolB == ncolB - 2 ) { colB1 = colB0 + nrowB ; #if MYDEBUG > 0 fprintf(stdout, "\n %% jcolB = %d", jcolB) ; fflush(stdout) ; #endif for ( irowA = kk = 0 ; irowA < nrowA ; irowA++ ) { if ( sizesA[irowA] > 0 ) { first = firstlocsA[irowA] ; last = first + sizesA[irowA] - 1 ; sum0 = sum1 = 0.0 ; for ( ii = first ; ii <= last ; ii++, kk++ ) { Aki = entriesA[kk] ; sum0 += Aki * colB0[ii] ; sum1 += Aki * colB1[ii] ; } colB0[irowA] -= sum0 ; colB1[irowA] -= sum1 ; } } } else if ( jcolB == ncolB - 1 ) { #if MYDEBUG > 0 fprintf(stdout, "\n %% jcolB = %d", jcolB) ; fflush(stdout) ; #endif for ( irowA = kk = 0 ; irowA < nrowA ; irowA++ ) { #if MYDEBUG > 0 fprintf(stdout, "\n %% irowA = %d, kk = %d, sizesA[%d] = %d", irowA, kk, irowA, sizesA[irowA]) ; fflush(stdout) ; #endif if ( sizesA[irowA] > 0 ) { first = firstlocsA[irowA] ; last = first + sizesA[irowA] - 1 ; #if MYDEBUG > 0 fprintf(stdout, "\n %% first = %d, last = %d", first, last) ; fflush(stdout) ; #endif sum0 = 0.0 ; for ( ii = first ; ii <= last ; ii++, kk++ ) { Aki = entriesA[kk] ; #if MYDEBUG > 0 fprintf(stdout, "\n %% Aki = %12.4e, colB0[%d] = %12.4e", Aki, ii, colB0[ii]) ; fflush(stdout) ; #endif sum0 += Aki * colB0[ii] ; } colB0[irowA] -= sum0 ; #if MYDEBUG > 0 fprintf(stdout, "\n %% colB0[%d] -= %12.4e", irowA, sum0) ; fflush(stdout) ; #endif } } } return ; } /*--------------------------------------------------------------------*/ /* --------------------------------------- purpose -- solve (A^T + I) X = B, where (1) A is strictly upper triangular (2) X overwrites B (B) B has type SUBMTX_DENSE_COLUMNS created -- 98feb19, cca --------------------------------------- */ static void real_solveSparseColumns ( SubMtx *mtxA, SubMtx *mtxB ) { double Aki, sum0, sum1, sum2 ; double *colB0, *colB1, *colB2, *entriesA, *entriesB ; int ii, inc1, inc2, irowA, jcolB, jj, kk, ncolB, nentA, nrowA, nrowB, size ; int *indicesA, *sizesA ; /* ---------------------------------------------------- extract the pointer and dimensions from two matrices ---------------------------------------------------- */ SubMtx_sparseColumnsInfo(mtxA, &nrowA, &nentA, &sizesA, &indicesA, &entriesA) ; SubMtx_denseInfo(mtxB, &nrowB, &ncolB, &inc1, &inc2, &entriesB) ; colB0 = entriesB ; for ( jcolB = 0 ; jcolB < ncolB - 2 ; jcolB += 3 ) { colB1 = colB0 + nrowB ; colB2 = colB1 + nrowB ; #if MYDEBUG > 0 fprintf(stdout, "\n jcolB = %d", jcolB) ; fflush(stdout) ; #endif for ( irowA = kk = 0 ; irowA < nrowA ; irowA++ ) { if ( (size = sizesA[irowA]) > 0 ) { sum0 = sum1 = sum2 = 0.0 ; for ( ii = 0 ; ii < size ; ii++, kk++ ) { Aki = entriesA[kk] ; jj = indicesA[kk] ; if ( jj < 0 || jj >= irowA ) { fprintf(stderr, "\n fatal error, irowA = %d, kk =%d, ii = %d, jj = %d", irowA, kk, ii, jj) ; exit(-1) ; } sum0 += Aki * colB0[jj] ; sum1 += Aki * colB1[jj] ; sum2 += Aki * colB2[jj] ; } colB0[irowA] -= sum0 ; colB1[irowA] -= sum1 ; colB2[irowA] -= sum2 ; } } colB0 = colB2 + nrowB ; } if ( jcolB == ncolB - 2 ) { colB1 = colB0 + nrowB ; #if MYDEBUG > 0 fprintf(stdout, "\n jcolB = %d", jcolB) ; fflush(stdout) ; #endif for ( irowA = kk = 0 ; irowA < nrowA ; irowA++ ) { if ( (size = sizesA[irowA]) > 0 ) { sum0 = sum1 = 0.0 ; for ( ii = 0 ; ii < size ; ii++, kk++ ) { Aki = entriesA[kk] ; jj = indicesA[kk] ; sum0 += Aki * colB0[jj] ; sum1 += Aki * colB1[jj] ; } colB0[irowA] -= sum0 ; colB1[irowA] -= sum1 ; } } } else if ( jcolB == ncolB - 1 ) { #if MYDEBUG > 0 fprintf(stdout, "\n jcolB = %d", jcolB) ; fflush(stdout) ; #endif for ( irowA = kk = 0 ; irowA < nrowA ; irowA++ ) { if ( (size = sizesA[irowA]) >= 0 ) { sum0 = 0.0 ; for ( ii = 0 ; ii < size ; ii++, kk++ ) { Aki = entriesA[kk] ; jj = indicesA[kk] ; if ( jj < 0 || jj >= irowA ) { fprintf(stderr, "\n fatal error, irowA = %d, kk =%d, ii = %d, jj = %d", irowA, kk, ii, jj) ; exit(-1) ; } sum0 += Aki * colB0[jj] ; } colB0[irowA] -= sum0 ; } } } return ; } /*--------------------------------------------------------------------*/ /* --------------------------------------- purpose -- solve (I + A^T) X = B, where (1) A is strictly lower triangular (2) X overwrites B (B) B has type SUBMTX_DENSE_COLUMNS created -- 98feb19, cca --------------------------------------- */ static void real_solveDenseSubrows ( SubMtx *mtxA, SubMtx *mtxB ) { double Aji, Bi0, Bi1, Bi2 ; double *colB0, *colB1, *colB2, *entriesA, *entriesB ; int colstart, first, inc1, inc2, irowA, jcolB, jj, kk, last, ncolB, nentA, nrowA, nrowB ; int *firstlocsA, *sizesA ; /* ---------------------------------------------------- extract the pointer and dimensions from two matrices ---------------------------------------------------- */ SubMtx_denseSubrowsInfo(mtxA, &nrowA, &nentA, &firstlocsA, &sizesA, &entriesA) ; SubMtx_denseInfo(mtxB, &nrowB, &ncolB, &inc1, &inc2, &entriesB) ; #if MYDEBUG > 0 fprintf(stdout, "\n nrowA = %d, ncolA = %d", nrowA, nentA) ; fflush(stdout) ; #endif colB0 = entriesB ; for ( jcolB = 0 ; jcolB < ncolB - 2 ; jcolB += 3 ) { colB1 = colB0 + nrowB ; colB2 = colB1 + nrowB ; #if MYDEBUG > 0 fprintf(stdout, "\n jcolB = %d", jcolB) ; fflush(stdout) ; #endif for ( irowA = nrowA - 1, colstart = nentA ; irowA >= 0 ; irowA-- ) { if ( sizesA[irowA] > 0 ) { first = firstlocsA[irowA] ; last = first + sizesA[irowA] - 1 ; colstart -= last - first + 1 ; Bi0 = colB0[irowA] ; Bi1 = colB1[irowA] ; Bi2 = colB2[irowA] ; for ( jj = first, kk = colstart ; jj <= last ; jj++, kk++ ) { Aji = entriesA[kk] ; colB0[jj] -= Aji * Bi0 ; colB1[jj] -= Aji * Bi1 ; colB2[jj] -= Aji * Bi2 ; } } } colB0 = colB2 + nrowB ; } if ( jcolB == ncolB - 2 ) { colB1 = colB0 + nrowB ; #if MYDEBUG > 0 fprintf(stdout, "\n jcolB = %d", jcolB) ; fflush(stdout) ; #endif for ( irowA = nrowA - 1, colstart = nentA ; irowA >= 0 ; irowA-- ) { if ( sizesA[irowA] > 0 ) { first = firstlocsA[irowA] ; last = first + sizesA[irowA] - 1 ; colstart -= last - first + 1 ; Bi0 = colB0[irowA] ; Bi1 = colB1[irowA] ; for ( jj = first, kk = colstart ; jj <= last ; jj++, kk++ ) { Aji = entriesA[kk] ; colB0[jj] -= Aji * Bi0 ; colB1[jj] -= Aji * Bi1 ; } } } } else if ( jcolB == ncolB - 1 ) { #if MYDEBUG > 0 fprintf(stdout, "\n jcolB = %d", jcolB) ; fflush(stdout) ; #endif for ( irowA = nrowA - 1, colstart = nentA ; irowA >= 0 ; irowA-- ) { #if MYDEBUG > 0 fprintf(stdout, "\n %% irowA = %d, sizesA[%d] = %d", irowA, irowA, sizesA[irowA]) ; fflush(stdout) ; #endif if ( sizesA[irowA] > 0 ) { first = firstlocsA[irowA] ; last = first + sizesA[irowA] - 1 ; colstart -= last - first + 1 ; Bi0 = colB0[irowA] ; #if MYDEBUG > 0 fprintf(stdout, "\n %% first %d, last %d, colstart %d, Bi0 = %12.4e", first, last, colstart, Bi0) ; fflush(stdout) ; #endif for ( jj = first, kk = colstart ; jj <= last ; jj++, kk++ ) { Aji = entriesA[kk] ; #if MYDEBUG > 0 fprintf(stdout, "\n %% jj %d, kk %d, Aji %12.4e", jj, kk, Aji) ; fflush(stdout) ; #endif colB0[jj] -= Aji * Bi0 ; } } } } return ; } /*--------------------------------------------------------------------*/ /* --------------------------------------- purpose -- solve (I + A^T) X = B, where (1) A is strictly lower triangular (2) X overwrites B (B) B has type SUBMTX_DENSE_COLUMNS created -- 98feb19, cca --------------------------------------- */ static void real_solveSparseRows ( SubMtx *mtxA, SubMtx *mtxB ) { double Aji, Bi0, Bi1, Bi2 ; double *colB0, *colB1, *colB2, *entriesA, *entriesB ; int colstart, ii, inc1, inc2, jcolA, jcolB, jj, kk, ncolB, nentA, nrowA, nrowB, size ; int *indicesA, *sizesA ; /* ---------------------------------------------------- extract the pointer and dimensions from two matrices ---------------------------------------------------- */ SubMtx_sparseRowsInfo(mtxA, &nrowA, &nentA, &sizesA, &indicesA, &entriesA) ; SubMtx_denseInfo(mtxB, &nrowB, &ncolB, &inc1, &inc2, &entriesB) ; #if MYDEBUG > 0 fprintf(stdout, "\n nrowA = %d, ncolA = %d", nrowA, nentA) ; fflush(stdout) ; #endif colB0 = entriesB ; for ( jcolB = 0 ; jcolB < ncolB - 2 ; jcolB += 3 ) { colB1 = colB0 + nrowB ; colB2 = colB1 + nrowB ; #if MYDEBUG > 0 fprintf(stdout, "\n jcolB = %d", jcolB) ; fflush(stdout) ; #endif for ( jcolA = nrowA - 1, colstart = nentA ; jcolA >= 0 ; jcolA-- ) { if ( (size = sizesA[jcolA]) > 0 ) { colstart -= size ; Bi0 = colB0[jcolA] ; Bi1 = colB1[jcolA] ; Bi2 = colB2[jcolA] ; for ( ii = 0, kk = colstart ; ii < size ; ii++, kk++ ) { Aji = entriesA[kk] ; jj = indicesA[kk] ; colB0[jj] -= Aji * Bi0 ; colB1[jj] -= Aji * Bi1 ; colB2[jj] -= Aji * Bi2 ; } } } colB0 = colB2 + nrowB ; } if ( jcolB == ncolB - 2 ) { colB1 = colB0 + nrowB ; #if MYDEBUG > 0 fprintf(stdout, "\n jcolB = %d", jcolB) ; fflush(stdout) ; #endif for ( jcolA = nrowA - 1, colstart = nentA ; jcolA >= 0 ; jcolA-- ) { if ( (size = sizesA[jcolA]) > 0 ) { colstart -= size ; Bi0 = colB0[jcolA] ; Bi1 = colB1[jcolA] ; for ( ii = 0, kk = colstart ; ii < size ; ii++, kk++ ) { Aji = entriesA[kk] ; jj = indicesA[kk] ; colB0[jj] -= Aji * Bi0 ; colB1[jj] -= Aji * Bi1 ; } } } } else if ( jcolB == ncolB - 1 ) { #if MYDEBUG > 0 fprintf(stdout, "\n jcolB = %d", jcolB) ; fflush(stdout) ; #endif for ( jcolA = nrowA - 1, colstart = nentA ; jcolA >= 0 ; jcolA-- ) { if ( (size = sizesA[jcolA]) > 0 ) { colstart -= size ; Bi0 = colB0[jcolA] ; for ( ii = 0, kk = colstart ; ii < size ; ii++, kk++ ) { Aji = entriesA[kk] ; jj = indicesA[kk] ; colB0[jj] -= Aji * Bi0 ; } } } } return ; } /*--------------------------------------------------------------------*/ /* --------------------------------------- purpose -- solve (A^T + I) X = B, where (1) A is strictly upper triangular (2) X overwrites B (B) B has type SUBMTX_DENSE_COLUMNS created -- 98may01, cca --------------------------------------- */ static void complex_solveDenseSubcolumns ( SubMtx *mtxA, SubMtx *mtxB ) { double ai, ar, bi0, bi1, bi2, br0, br1, br2, isum0, isum1, isum2, rsum0, rsum1, rsum2 ; double *colB0, *colB1, *colB2, *entriesA, *entriesB ; int first, ii, iloc, inc1, inc2, irowA, jcolB, kk, last, ncolB, nentA, nrowA, nrowB, rloc ; int *firstlocsA, *sizesA ; /* ---------------------------------------------------- extract the pointer and dimensions from two matrices ---------------------------------------------------- */ SubMtx_denseSubcolumnsInfo(mtxA, &nrowA, &nentA, &firstlocsA, &sizesA, &entriesA) ; SubMtx_denseInfo(mtxB, &nrowB, &ncolB, &inc1, &inc2, &entriesB) ; #if MYDEBUG > 0 fprintf(stdout, "\n nentA = %d", nentA) ; fflush(stdout) ; #endif colB0 = entriesB ; for ( jcolB = 0 ; jcolB < ncolB - 2 ; jcolB += 3 ) { colB1 = colB0 + 2*nrowB ; colB2 = colB1 + 2*nrowB ; #if MYDEBUG > 0 fprintf(stdout, "\n %% jcolB = %d", jcolB) ; fflush(stdout) ; #endif for ( irowA = kk = 0 ; irowA < nrowA ; irowA++ ) { #if MYDEBUG > 0 fprintf(stdout, "\n %% irowA %d, size %d", irowA, sizesA[irowA]) ; fflush(stdout) ; #endif if ( sizesA[irowA] > 0 ) { first = firstlocsA[irowA] ; last = first + sizesA[irowA] - 1 ; #if MYDEBUG > 0 fprintf(stdout, ", first %d, last %d", first, last) ; fflush(stdout) ; #endif rsum0 = isum0 = 0.0 ; rsum1 = isum1 = 0.0 ; rsum2 = isum2 = 0.0 ; for ( ii = first ; ii <= last ; ii++, kk++ ) { ar = entriesA[2*kk] ; ai = entriesA[2*kk+1] ; #if MYDEBUG > 0 fprintf(stdout, "\n %% A(%d,%d) = (%12.4e,%12.4e)", irowA+1, ii+1, ar, ai) ; fflush(stdout) ; #endif rloc = 2*ii ; iloc = rloc + 1 ; br0 = colB0[rloc] ; bi0 = colB0[iloc] ; br1 = colB1[rloc] ; bi1 = colB1[iloc] ; br2 = colB2[rloc] ; bi2 = colB2[iloc] ; rsum0 += ar*br0 - ai*bi0 ; isum0 += ar*bi0 + ai*br0 ; rsum1 += ar*br1 - ai*bi1 ; isum1 += ar*bi1 + ai*br1 ; rsum2 += ar*br2 - ai*bi2 ; isum2 += ar*bi2 + ai*br2 ; } rloc = 2*irowA ; iloc = rloc + 1 ; colB0[rloc] -= rsum0 ; colB0[iloc] -= isum0 ; colB1[rloc] -= rsum1 ; colB1[iloc] -= isum1 ; colB2[rloc] -= rsum2 ; colB2[iloc] -= isum2 ; } } #if MYDEBUG > 0 fprintf(stdout, "\n %% kk = %d", kk) ; fflush(stdout) ; #endif colB0 = colB2 + 2*nrowB ; } if ( jcolB == ncolB - 2 ) { colB1 = colB0 + 2*nrowB ; for ( irowA = kk = 0 ; irowA < nrowA ; irowA++ ) { #if MYDEBUG > 0 fprintf(stdout, "\n %% irowA %d, size %d", irowA, sizesA[irowA]) ; fflush(stdout) ; #endif if ( sizesA[irowA] > 0 ) { first = firstlocsA[irowA] ; last = first + sizesA[irowA] - 1 ; #if MYDEBUG > 0 fprintf(stdout, ", first %d, last %d", first, last) ; fflush(stdout) ; #endif rsum0 = isum0 = 0.0 ; rsum1 = isum1 = 0.0 ; for ( ii = first ; ii <= last ; ii++, kk++ ) { ar = entriesA[2*kk] ; ai = entriesA[2*kk+1] ; #if MYDEBUG > 0 fprintf(stdout, "\n %% A(%d,%d) = (%12.4e,%12.4e)", irowA+1, ii+1, ar, ai) ; fflush(stdout) ; #endif rloc = 2*ii ; iloc = rloc + 1 ; br0 = colB0[rloc] ; bi0 = colB0[iloc] ; br1 = colB1[rloc] ; bi1 = colB1[iloc] ; rsum0 += ar*br0 - ai*bi0 ; isum0 += ar*bi0 + ai*br0 ; rsum1 += ar*br1 - ai*bi1 ; isum1 += ar*bi1 + ai*br1 ; } rloc = 2*irowA ; iloc = rloc + 1 ; colB0[rloc] -= rsum0 ; colB0[iloc] -= isum0 ; colB1[rloc] -= rsum1 ; colB1[iloc] -= isum1 ; } #if MYDEBUG > 0 fprintf(stdout, "\n %% kk = %d", kk) ; fflush(stdout) ; #endif } } else if ( jcolB == ncolB - 1 ) { for ( irowA = kk = 0 ; irowA < nrowA ; irowA++ ) { #if MYDEBUG > 0 fprintf(stdout, "\n %% irowA %d, size %d", irowA, sizesA[irowA]) ; fflush(stdout) ; #endif if ( sizesA[irowA] > 0 ) { first = firstlocsA[irowA] ; last = first + sizesA[irowA] - 1 ; #if MYDEBUG > 0 fprintf(stdout, ", first %d, last %d", first, last) ; fflush(stdout) ; #endif rsum0 = isum0 = 0.0 ; for ( ii = first ; ii <= last ; ii++, kk++ ) { ar = entriesA[2*kk] ; ai = entriesA[2*kk+1] ; #if MYDEBUG > 0 fprintf(stdout, "\n %% A(%d,%d) = (%12.4e,%12.4e)", irowA+1, ii+1, ar, ai) ; fflush(stdout) ; #endif rloc = 2*ii ; iloc = rloc + 1 ; br0 = colB0[rloc] ; bi0 = colB0[iloc] ; rsum0 += ar*br0 - ai*bi0 ; isum0 += ar*bi0 + ai*br0 ; } rloc = 2*irowA ; iloc = rloc + 1 ; colB0[rloc] -= rsum0 ; colB0[iloc] -= isum0 ; } #if MYDEBUG > 0 fprintf(stdout, "\n %% kk = %d", kk) ; fflush(stdout) ; #endif } } return ; } /*--------------------------------------------------------------------*/ /* --------------------------------------- purpose -- solve (A^T + I) X = B, where (1) A is strictly upper triangular (2) X overwrites B (B) B has type SUBMTX_DENSE_COLUMNS created -- 98may01, cca --------------------------------------- */ static void complex_solveSparseColumns ( SubMtx *mtxA, SubMtx *mtxB ) { double ai, ar, bi0, bi1, bi2, br0, br1, br2, isum0, isum1, isum2, rsum0, rsum1, rsum2 ; double *colB0, *colB1, *colB2, *entriesA, *entriesB ; int ii, iloc, inc1, inc2, irowA, jcolB, jj, kk, ncolB, nentA, nrowA, nrowB, rloc, size ; int *indicesA, *sizesA ; /* ---------------------------------------------------- extract the pointer and dimensions from two matrices ---------------------------------------------------- */ SubMtx_sparseColumnsInfo(mtxA, &nrowA, &nentA, &sizesA, &indicesA, &entriesA) ; SubMtx_denseInfo(mtxB, &nrowB, &ncolB, &inc1, &inc2, &entriesB) ; colB0 = entriesB ; for ( jcolB = 0 ; jcolB < ncolB - 2 ; jcolB += 3 ) { colB1 = colB0 + 2*nrowB ; colB2 = colB1 + 2*nrowB ; #if MYDEBUG > 0 fprintf(stdout, "\n jcolB = %d", jcolB) ; fflush(stdout) ; #endif for ( irowA = kk = 0 ; irowA < nrowA ; irowA++ ) { if ( (size = sizesA[irowA]) > 0 ) { rsum0 = isum0 = 0.0 ; rsum1 = isum1 = 0.0 ; rsum2 = isum2 = 0.0 ; for ( ii = 0 ; ii < size ; ii++, kk++ ) { ar = entriesA[2*kk] ; ai = entriesA[2*kk+1] ; jj = indicesA[kk] ; if ( jj < 0 || jj >= irowA ) { fprintf(stderr, "\n fatal error, irowA = %d, kk =%d, ii = %d, jj = %d", irowA, kk, ii, jj) ; exit(-1) ; } rloc = 2*jj ; iloc = rloc + 1 ; br0 = colB0[rloc] ; bi0 = colB0[iloc] ; br1 = colB1[rloc] ; bi1 = colB1[iloc] ; br2 = colB2[rloc] ; bi2 = colB2[iloc] ; rsum0 += ar*br0 - ai*bi0 ; isum0 += ar*bi0 + ai*br0 ; rsum1 += ar*br1 - ai*bi1 ; isum1 += ar*bi1 + ai*br1 ; rsum2 += ar*br2 - ai*bi2 ; isum2 += ar*bi2 + ai*br2 ; } rloc = 2*irowA ; iloc = rloc + 1 ; colB0[rloc] -= rsum0 ; colB0[iloc] -= isum0 ; colB1[rloc] -= rsum1 ; colB1[iloc] -= isum1 ; colB2[rloc] -= rsum2 ; colB2[iloc] -= isum2 ; } } colB0 = colB2 + 2*nrowB ; } if ( jcolB == ncolB - 2 ) { colB1 = colB0 + 2*nrowB ; #if MYDEBUG > 0 fprintf(stdout, "\n jcolB = %d", jcolB) ; fflush(stdout) ; #endif for ( irowA = kk = 0 ; irowA < nrowA ; irowA++ ) { if ( (size = sizesA[irowA]) > 0 ) { rsum0 = isum0 = 0.0 ; rsum1 = isum1 = 0.0 ; for ( ii = 0 ; ii < size ; ii++, kk++ ) { ar = entriesA[2*kk] ; ai = entriesA[2*kk+1] ; jj = indicesA[kk] ; if ( jj < 0 || jj >= irowA ) { fprintf(stderr, "\n fatal error, irowA = %d, kk =%d, ii = %d, jj = %d", irowA, kk, ii, jj) ; exit(-1) ; } rloc = 2*jj ; iloc = rloc + 1 ; br0 = colB0[rloc] ; bi0 = colB0[iloc] ; br1 = colB1[rloc] ; bi1 = colB1[iloc] ; rsum0 += ar*br0 - ai*bi0 ; isum0 += ar*bi0 + ai*br0 ; rsum1 += ar*br1 - ai*bi1 ; isum1 += ar*bi1 + ai*br1 ; } rloc = 2*irowA ; iloc = rloc + 1 ; colB0[rloc] -= rsum0 ; colB0[iloc] -= isum0 ; colB1[rloc] -= rsum1 ; colB1[iloc] -= isum1 ; } } } else if ( jcolB == ncolB - 1 ) { for ( irowA = kk = 0 ; irowA < nrowA ; irowA++ ) { if ( (size = sizesA[irowA]) > 0 ) { rsum0 = isum0 = 0.0 ; for ( ii = 0 ; ii < size ; ii++, kk++ ) { ar = entriesA[2*kk] ; ai = entriesA[2*kk+1] ; jj = indicesA[kk] ; if ( jj < 0 || jj >= irowA ) { fprintf(stderr, "\n fatal error, irowA = %d, kk =%d, ii = %d, jj = %d", irowA, kk, ii, jj) ; exit(-1) ; } rloc = 2*jj ; iloc = rloc + 1 ; br0 = colB0[rloc] ; bi0 = colB0[iloc] ; rsum0 += ar*br0 - ai*bi0 ; isum0 += ar*bi0 + ai*br0 ; } rloc = 2*irowA ; iloc = rloc + 1 ; colB0[rloc] -= rsum0 ; colB0[iloc] -= isum0 ; } } } return ; } /*--------------------------------------------------------------------*/ /* --------------------------------------- purpose -- solve (I + A^T) X = B, where (1) A is strictly lower triangular (2) X overwrites B (B) B has type SUBMTX_DENSE_COLUMNS created -- 98may01, cca --------------------------------------- */ static void complex_solveDenseSubrows ( SubMtx *mtxA, SubMtx *mtxB ) { double ai, ar, bi0, bi1, bi2, br0, br1, br2 ; double *colB0, *colB1, *colB2, *entriesA, *entriesB ; int colstart, first, iloc, inc1, inc2, irowA, jcolB, jj, kk, last, ncolB, nentA, nrowA, nrowB, rloc ; int *firstlocsA, *sizesA ; /* ---------------------------------------------------- extract the pointer and dimensions from two matrices ---------------------------------------------------- */ SubMtx_denseSubrowsInfo(mtxA, &nrowA, &nentA, &firstlocsA, &sizesA, &entriesA) ; SubMtx_denseInfo(mtxB, &nrowB, &ncolB, &inc1, &inc2, &entriesB) ; #if MYDEBUG > 0 fprintf(stdout, "\n nrowA = %d, ncolA = %d", nrowA, nentA) ; fflush(stdout) ; #endif colB0 = entriesB ; for ( jcolB = 0 ; jcolB < ncolB - 2 ; jcolB += 3 ) { colB1 = colB0 + 2*nrowB ; colB2 = colB1 + 2*nrowB ; #if MYDEBUG > 0 fprintf(stdout, "\n jcolB = %d", jcolB) ; fflush(stdout) ; #endif for ( irowA = nrowA - 1, colstart = nentA ; irowA >= 0 ; irowA-- ) { if ( sizesA[irowA] > 0 ) { first = firstlocsA[irowA] ; last = first + sizesA[irowA] - 1 ; colstart -= last - first + 1 ; rloc = 2*irowA ; iloc = rloc + 1 ; br0 = colB0[rloc] ; bi0 = colB0[iloc] ; br1 = colB1[rloc] ; bi1 = colB1[iloc] ; br2 = colB2[rloc] ; bi2 = colB2[iloc] ; for ( jj = first, kk = colstart ; jj <= last ; jj++, kk++ ) { ar = entriesA[2*kk] ; ai = entriesA[2*kk+1] ; rloc = 2*jj ; iloc = rloc + 1 ; colB0[rloc] -= ar*br0 - ai*bi0 ; colB0[iloc] -= ar*bi0 + ai*br0 ; colB1[rloc] -= ar*br1 - ai*bi1 ; colB1[iloc] -= ar*bi1 + ai*br1 ; colB2[rloc] -= ar*br2 - ai*bi2 ; colB2[iloc] -= ar*bi2 + ai*br2 ; } } } colB0 = colB2 + 2*nrowB ; } if ( jcolB == ncolB - 2 ) { colB1 = colB0 + 2*nrowB ; #if MYDEBUG > 0 fprintf(stdout, "\n jcolB = %d", jcolB) ; fflush(stdout) ; #endif for ( irowA = nrowA - 1, colstart = nentA ; irowA >= 0 ; irowA-- ) { if ( sizesA[irowA] > 0 ) { first = firstlocsA[irowA] ; last = first + sizesA[irowA] - 1 ; colstart -= last - first + 1 ; rloc = 2*irowA ; iloc = rloc + 1 ; br0 = colB0[rloc] ; bi0 = colB0[iloc] ; br1 = colB1[rloc] ; bi1 = colB1[iloc] ; for ( jj = first, kk = colstart ; jj <= last ; jj++, kk++ ) { ar = entriesA[2*kk] ; ai = entriesA[2*kk+1] ; rloc = 2*jj ; iloc = rloc + 1 ; colB0[rloc] -= ar*br0 - ai*bi0 ; colB0[iloc] -= ar*bi0 + ai*br0 ; colB1[rloc] -= ar*br1 - ai*bi1 ; colB1[iloc] -= ar*bi1 + ai*br1 ; } } } } else if ( jcolB == ncolB - 1 ) { #if MYDEBUG > 0 fprintf(stdout, "\n jcolB = %d", jcolB) ; fflush(stdout) ; #endif for ( irowA = nrowA - 1, colstart = nentA ; irowA >= 0 ; irowA-- ) { if ( sizesA[irowA] > 0 ) { first = firstlocsA[irowA] ; last = first + sizesA[irowA] - 1 ; colstart -= last - first + 1 ; rloc = 2*irowA ; iloc = rloc + 1 ; br0 = colB0[rloc] ; bi0 = colB0[iloc] ; for ( jj = first, kk = colstart ; jj <= last ; jj++, kk++ ) { ar = entriesA[2*kk] ; ai = entriesA[2*kk+1] ; rloc = 2*jj ; iloc = rloc + 1 ; colB0[rloc] -= ar*br0 - ai*bi0 ; colB0[iloc] -= ar*bi0 + ai*br0 ; } } } } return ; } /*--------------------------------------------------------------------*/ /* --------------------------------------- purpose -- solve (I + A^T) X = B, where (1) A is strictly lower triangular (2) X overwrites B (B) B has type SUBMTX_DENSE_COLUMNS created -- 98may01, cca --------------------------------------- */ static void complex_solveSparseRows ( SubMtx *mtxA, SubMtx *mtxB ) { double ai, ar, bi0, bi1, bi2, br0, br1, br2 ; double *colB0, *colB1, *colB2, *entriesA, *entriesB ; int colstart, ii, iloc, inc1, inc2, jcolA, jcolB, jj, kk, ncolB, nentA, nrowA, nrowB, rloc, size ; int *indicesA, *sizesA ; /* ---------------------------------------------------- extract the pointer and dimensions from two matrices ---------------------------------------------------- */ SubMtx_sparseRowsInfo(mtxA, &nrowA, &nentA, &sizesA, &indicesA, &entriesA) ; SubMtx_denseInfo(mtxB, &nrowB, &ncolB, &inc1, &inc2, &entriesB) ; #if MYDEBUG > 0 fprintf(stdout, "\n nrowA = %d, ncolA = %d", nrowA, nentA) ; fflush(stdout) ; #endif colB0 = entriesB ; for ( jcolB = 0 ; jcolB < ncolB - 2 ; jcolB += 3 ) { colB1 = colB0 + 2*nrowB ; colB2 = colB1 + 2*nrowB ; #if MYDEBUG > 0 fprintf(stdout, "\n jcolB = %d", jcolB) ; fflush(stdout) ; #endif for ( jcolA = nrowA - 1, colstart = nentA ; jcolA >= 0 ; jcolA-- ) { if ( (size = sizesA[jcolA]) > 0 ) { colstart -= size ; rloc = 2*jcolA ; iloc = rloc + 1 ; br0 = colB0[rloc] ; bi0 = colB0[iloc] ; br1 = colB1[rloc] ; bi1 = colB1[iloc] ; br2 = colB2[rloc] ; bi2 = colB2[iloc] ; for ( ii = 0, kk = colstart ; ii < size ; ii++, kk++ ) { ar = entriesA[2*kk] ; ai = entriesA[2*kk+1] ; jj = indicesA[kk] ; rloc = 2*jj ; iloc = rloc + 1 ; colB0[rloc] -= ar*br0 - ai*bi0 ; colB0[iloc] -= ar*bi0 + ai*br0 ; colB1[rloc] -= ar*br1 - ai*bi1 ; colB1[iloc] -= ar*bi1 + ai*br1 ; colB2[rloc] -= ar*br2 - ai*bi2 ; colB2[iloc] -= ar*bi2 + ai*br2 ; } } } colB0 = colB2 + 2*nrowB ; } if ( jcolB == ncolB - 2 ) { colB1 = colB0 + 2*nrowB ; #if MYDEBUG > 0 fprintf(stdout, "\n jcolB = %d", jcolB) ; fflush(stdout) ; #endif for ( jcolA = nrowA - 1, colstart = nentA ; jcolA >= 0 ; jcolA-- ) { if ( (size = sizesA[jcolA]) > 0 ) { colstart -= size ; rloc = 2*jcolA ; iloc = rloc + 1 ; br0 = colB0[rloc] ; bi0 = colB0[iloc] ; br1 = colB1[rloc] ; bi1 = colB1[iloc] ; for ( ii = 0, kk = colstart ; ii < size ; ii++, kk++ ) { ar = entriesA[2*kk] ; ai = entriesA[2*kk+1] ; jj = indicesA[kk] ; rloc = 2*jj ; iloc = rloc + 1 ; colB0[rloc] -= ar*br0 - ai*bi0 ; colB0[iloc] -= ar*bi0 + ai*br0 ; colB1[rloc] -= ar*br1 - ai*bi1 ; colB1[iloc] -= ar*bi1 + ai*br1 ; } } } } else if ( jcolB == ncolB - 1 ) { #if MYDEBUG > 0 fprintf(stdout, "\n jcolB = %d", jcolB) ; fflush(stdout) ; #endif for ( jcolA = nrowA - 1, colstart = nentA ; jcolA >= 0 ; jcolA-- ) { if ( (size = sizesA[jcolA]) > 0 ) { colstart -= size ; rloc = 2*jcolA ; iloc = rloc + 1 ; br0 = colB0[rloc] ; bi0 = colB0[iloc] ; for ( ii = 0, kk = colstart ; ii < size ; ii++, kk++ ) { ar = entriesA[2*kk] ; ai = entriesA[2*kk+1] ; jj = indicesA[kk] ; rloc = 2*jj ; iloc = rloc + 1 ; colB0[rloc] -= ar*br0 - ai*bi0 ; colB0[iloc] -= ar*bi0 + ai*br0 ; } } } } return ; } /*--------------------------------------------------------------------*/
C
#include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node *left; struct node *right; }Node; int * create() { int x; Node *newnode=(Node*)malloc(sizeof(Node)); printf("Enter the data for the nodes(-1 for no data)"); scanf("%d", &x); if(x==-1) { return NULL; } newnode->data=x; printf("Enter the left child data rooted at %d \n",newnode->data); newnode->left=create(); printf("Enter the right child data rooted at %d\n",newnode->data); newnode->right=create(); return newnode; } } int nodes(node* root) { if (!root) return 0; return 1+nodes(root->left)+nodes(root->right); } int nonleafnodes(node* root) { if (!root) return 0; if (!root->right && !root->left) return 0; return 1+nonleafnodes(root->left)+nonleafnodes(root->right); } int leafnodes(node* root) { if (!root) return 0; if (!root->right && !root->left) return 1; return leafnodes(root->left)+leafnodes(root->right); } int main() { Node *root=create(); Node *t=root; printf ("No. of nodes = %d\n",nodes(root)); printf ("No. of leaf nodes = %d\n",leafnodes(root)); printf ("No. of non leaf nodes =%d\n",nonleafnodes(root)); return 0; }
C
#include <stdio.h> #include<string.h> int main() { char s[100],s1[100]; int i=0; scanf("%s",s); while(s[i]!='\0') { i++; } int j=0; while(i>=0) { s1[j++]=s[i-1]; i--; } s1[j]='\0'; printf("%s",s1); return 0; }
C
#include <cs50.h> #include <stdio.h> int main(void) { int start_size = 0; int end_size = 0; int number_accepted = 0; int years = 0; int years_found = 0; int llamas = 0; //Ask user for start size until valid number is entered while (number_accepted == 0) { start_size = get_long("Start size: "); if (start_size >= 9) { number_accepted = 1; } } //Ask user for end size until valid number is entered number_accepted = 0; while (number_accepted == 0) { end_size = get_long("End size: "); if (end_size >= start_size) { number_accepted = 1; } } //Iterate for a certain amount of years until end number of llamas is greater than starting number of llamas llamas = start_size; while (years_found == 0) { llamas = llamas + (llamas / 3) - (llamas / 4); //If start and end size are the same, number of years is 0 and program ends if (start_size == end_size) { years_found = 1; } //If new number of llamas after an iteration is greater than 0, number of years increases by 1 and program ends else if (llamas >= end_size) { years = years + 1; years_found = 1; } //If new total number of llamas is still less than end size requirement, increase years passed by 1 and start again else { years = years + 1; } } //Print how many years it took to go from start size to end size of llamas printf("Years: %i\n", years); }
C
#include "lists.h" /** * free_list - function that frees a list_t list. * @head: Pointed to head of a list * * Return: Void */ void free_list(list_t *head) { list_t *new = head; list_t *next = NULL; for (; new != NULL; new = next) { next = new->next; free(new->str); free(new); } }
C
#include <stdio.h> int main(int argc, char **argv) { int i; printf("argv count: %d\n", argc); for(i = 0; i < argc; i++) { printf("argv[%d] = %s\n", i, argv[i]); } fprintf(stderr, "this message is send to stderr\n"); }
C
#include <stdio.h> #include <stdlib.h> struct Node { char data; struct Node *next; }; void LinkdeListTraversal(struct Node *ptr) { printf("Data in linked list is: \n"); while (ptr != NULL) { printf("%c", ptr->data); ptr = ptr->next; } } int main() { struct Node *head; struct Node *second; struct Node *third; struct Node *fourth; struct Node *fifth; struct Node *sixth; struct Node *seventh; struct Node *eighth; struct Node *nineth; struct Node *tenth; struct Node *eleventh; head = (struct Node *)malloc(sizeof(struct Node)); second = (struct Node *)malloc(sizeof(struct Node)); third = (struct Node *)malloc(sizeof(struct Node)); fourth = (struct Node *)malloc(sizeof(struct Node)); fifth = (struct Node *)malloc(sizeof(struct Node)); sixth = (struct Node *)malloc(sizeof(struct Node)); seventh = (struct Node *)malloc(sizeof(struct Node)); eighth = (struct Node *)malloc(sizeof(struct Node)); nineth = (struct Node *)malloc(sizeof(struct Node)); tenth = (struct Node *)malloc(sizeof(struct Node)); eleventh = (struct Node *)malloc(sizeof(struct Node)); head->data = 'A'; head->next = second; second->data = 'y'; second->next = third; third->data = 'u'; third->next = fourth; fourth->data = 's'; fourth->next = fifth; fifth->data = 'h'; fifth->next = sixth; sixth->data = ' '; sixth->next = seventh; seventh->data = 'K'; seventh->next = eighth; eighth->data = 'u'; eighth->next = nineth; nineth->data = 'm'; nineth->next = tenth; tenth->data = 'a'; tenth->next = eleventh; eleventh->data = 'r'; eleventh->next = NULL; LinkdeListTraversal(head); }
C
/** * use execve * deal with absolute PATHS only * */ #include <unistd.h> #include <stdio.h> #include <errno.h> int main(int argc, char *args[]) { char *path = "/bin/ls"; // exceve deals with PATHS only char *argv[] = {"ls", "-l", "-a", NULL}; // if this is not null terminated the call will fail char *envp[] = {NULL}; int ret = execve(path, argv, envp); // if failed will set the errno external variable printf("exeve response = %d \n", ret); printf("p_api_exec_1.c \n"); perror(errno); }
C
#include<stdio.h> #include<stdlib.h> #include<sys/stat.h> #include<fcntl.h> #include<unistd.h> int main(int argc, char *argv[]) { int realY = open("y_test", O_RDONLY); int predY = open("result.csv", O_RDONLY); FILE *predYfp = fdopen(predY, "r"); int num = atoi(argv[1]); int correct = 0; int times[10] = {}; fscanf(predYfp, "id,label"); for(int i = 0; i < num; i++) { char real; int id, pred; read(realY, &real, sizeof(char)); fscanf(predYfp, "%d,%d", &id, &pred); times[pred]++; if(pred == (int)real) correct++; } printf("correctness = %f\n", (double)correct / num); for(int i = 0; i < 10; i++) printf("%d: %d\n", i, times[i]); return 0; }
C
#include <stdio.h> #include <cs50.h> #include <math.h> int main(void) { float x; int c,n=0; x=get_float("Change owed:"); while(!(x>0)) { x=get_float("Change owed:"); } c = round(x * 100); while((c-25)>=0) { n++; c=c-25; } while((c-10)>=0) { n++; c=c-10; } while((c-5)>=0) { n++; c=c-5; } while((c-1)>=0) { n++; c=c-1; } printf("%i\n",n); }
C
/*Viken Parikh B2 1411099*/ #include<stdio.h> #include<conio.h> void merge(int array[], int low, int mid, int high) { int i, j, k; int n1 = mid - low + 1; int n2 = high - mid; int L[100], H[100]; for(i = 0; i < n1; i++) L[i] = array[low + i]; for(j = 0; j < n2; j++) H[j] = array[mid + 1+ j]; i = 0; j = 0; k = low; while (i < n1 && j < n2) { if (L[i] <= H[j]) { array[k] = L[i]; i++; } else { array[k] = H[j]; j++; } k++; } while (i < n1) { array[k] = L[i]; i++; k++; } while (j < n2) { array[k] = H[j]; j++; k++; } } void mergeSort(int arrayay[], int low, int high) { if (low < high) { int mid = low+(high-low)/2; mergeSort(array, low, mid); mergeSort(array, mid+1, high); merge(array, low, mid, high); } } void main() { int m[100],i,n; clrscr(); printf("\n Enter the number elements:"); scanf("%d", &n); printf("\n Enter the %d elements:",n); for(i=0;i<n;i++) scanf("%d", &a[i]); mergeSort(m,0,n-1); printf("\nThe sorted arrayay is : /n"); for(i=0;i<n;i++) printf("%d ",m[i]); getch(); }
C
#include <stdio.h> #include<string.h> int main(){ char st [20]="hello"; char*st2="lipun"; strcat(st,st2); printf("st is %s",st); return 0; }
C
#include <stdio.h> #define sz 1000000000 int ara[sz]; void sieve() { int i,j,root; for(i=2;i<=sz;i++){ ara[i]=1; } root=sqrt(sz); for(i=2;i<=root;i++){ if(ara[i]==1){ for(j=2;i*j<=sz;j++){ ara[i*j]=0; } } } } int main() { int i,j; sieve(); //for(i=2;i<=sz;i++){ // if(ara[i]==1) //printf("%d ",i); //} return 0; }
C
/****************************************************************************** Projete um programa para calcular a área de um triângulo. O usuário informará os dados necessários para o cálculo, ou seja, a base e a altura do triângulo. onde: área = base * altura /2 *******************************************************************************/ #include <stdio.h> #include <conio.h> int main(void) { float base, altura, area; printf("Digite a base: "); scanf("%f", & base ); printf("digite a altura: "); scanf("%f" ,& altura); area = (base * altura)/2; printf("%.2f", area); }
C
#include <stdio.h> #include <stdlib.h> //exit関数を使うには、<stdlib.h> を #include する必要がある //次のプログラムは、int型の要素数10個の配列を動的に確保します。 int main() { int i; int *heap; // heap = 長期的に使用される大きなサイズのメモリを格納する領域 printf("%p\n",heap); // malloc()の戻り値はvoid *型ですが、これをint *型へと変換している()を // キャスト演算子(cast operator)と呼びます。 heap = (int *)malloc(sizeof(int) * 10); //ポインタ変数(すなわちheap) =(Int型のキャストオペレーター))malloc(必要なメモリのバイトサイズ); if (heap == NULL) exit(0); // // メモリを確保できなかった場合は NULL が返る。 for (i = 0;i < 10;i++) { heap[i] = i; // printf("%d\n",heap[i]); } free(heap); //free(ポインタ変数が入る;すなわちheap); // malloc関数によって確保されたメモリは、プログラムが終了するまで残りますが、 // そのメモリが不要になった場合、free(フリー)関数を使って解放します。 return 0; }
C
#include <stdio.h> static const char *strings[] = {"one","two","three","four","five","six","seven","eight","nine"}; int main() { int a,b,i; scanf("%d\n%d", &a, &b); for(i=a;i<b;i++) { if((i>=1&&i<=9)&&(b>=1&&b<=9)) { printf("%s\n",strings[i-1]); printf("%s\n",strings[b-1]); } else { return 1; } (a%2==0)?printf("even\n"):printf("odd\n"); (b%2==0)?printf("even\n"):printf("odd"); return 0; } return 0; }
C
/* * File: fonction_periph.c * Author: laure * * Created on 21 fvrier 2019, 16:36 */ #include <stdio.h> #include <time.h> #include "HC-SR04.h" #include "fonction_periph.h" void send_water(int cup_size) { Relai_eau = 0; my_delay(2000*cup_size); Relai_eau = 1; } void send_milk(int num_cup) { DEL_LD = 1; my_delay(2*num_cup); DEL_LD = 0; } void send_sugar(int num_cup) { DEL_SD = 1; my_delay(2*num_cup); DEL_SD = 0; } void init_periph(void) { TRISCbits.TRISC4 = 0; TRISCbits.TRISC7 = 0; TRISCbits.TRISC6 = 0; TRISCbits.TRISC5 = 0; TRISCbits.TRISC2 = 0; TRISCbits.TRISC1 = 0; TRISCbits.TRISC0 = 0; TRISAbits.TRISA1 = 0; TRISFbits.TRISF6 = 0; Relai_eau = 1; DEL_SD = 0; DEL_LD = 0; DEL_ED = 0; DEL_NC_S = 0; DEL_NC_L = 0; DEL_NC_E = 0; DEL_TA_L = 0; DEL_TA_E = 0; } void my_delay(int number_of_seconds) { int i; for (i = 0; i<number_of_seconds*1000; i++) { __delay_ms(1); } } int digit_to_int(char d) { int entier; switch(d){ case '0': entier = 0; break; case '1': entier = 1; break; case '2': entier = 2; break; case '3': entier = 3; break; case '4': entier = 4; break; case '5': entier = 5; break; case '6': entier = 6; break; case '7': entier = 7; break; case '8': entier = 8; break; case '9': entier = 9; break; case 'A': entier = 10; break; case 'B': entier = 11; break; case 'C': entier = 12; break; case 'D': entier = 13; break; case 'E': entier = 14; break; case 'F': entier = 15; break; } return entier; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main (int argc, char *argv []) { FILE *ArchivoResultados; char Renglon [100]; if (argc != 2) { printf ("Error: demasiados o muy pocos argumentos.\n"); printf ("Uso del programa: ./LeeComplex NombreArchivo (Con ext.)\n"); exit (0); } ArchivoResultados = fopen (argv [1], "rt"); if (ArchivoResultados == NULL) { printf ("No se encontró el archivo\n"); printf ("Saliendo...n"); exit (0); } printf ("Las operaciones del archivo son:\n"); while (fgets (Renglon, 300, ArchivoResultados) != NULL) { Renglon [strlen (Renglon) - 1] = '\0'; puts (Renglon); } fclose (ArchivoResultados); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* print_func.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mdlamini <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/06/05 16:12:07 by mdlamini #+# #+# */ /* Updated: 2016/06/09 12:13:58 by mdlamini ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" /*void process_char(t_converter *converter, va_list arg, int precision, int width) { //while (converter->flags->width--) // ft_putchar(' '); converter->data->c = (char) va_arg(arg, int); ft_putchar(converter->data->c); width++; precision++; }*/ void process_str(t_converter *converter, va_list *arg, t_field *field) { int c; char *tmp; converter->data->str = va_arg(*arg, char *); tmp = ft_strdup(converter->data->str); c = 0; if (converter->flags[2].value != 1) pad('s', 'L', converter->flags, field, ft_strlen(tmp)); if (field->precision > 0) { while (c < field->precision && tmp[c]) ft_putchar(tmp[c++]); } else ft_putstr(tmp); if (converter->flags[2].value == 1) pad('s', 'R', converter->flags, field, ft_strlen(tmp)); ft_strdel(&tmp); } void process_int(t_converter *converter, va_list *arg, t_field *field) { char *n; unsigned int len; //#+-0' ' converter->data->nbr = va_arg(*arg, int); n = ft_itoa(converter->data->nbr); len = ft_strlen(n); ft_strdel(&n); if (converter->flags[2].value != 1 )//|| converter->flags[3].value == 1) pad('i', 'L', converter->flags, field, len); if (converter->flags[1].value == 1 && converter->data->nbr > 0) ft_putchar('+'); else if (converter->flags[4].value == 1 && converter->data->nbr > 0) ft_putchar(' '); ft_putnbr(converter->data->nbr); if (converter->flags[2].value == 1 )//|| converter->flags[3].value == 1) pad('i', 'R', converter->flags, field, len); } /*void process_poi(t_converter *converter, va_list arg, int precision, int width) { converter->data->nbr = va_arg(arg, int); ft_putnbr_base(converter->data->nbr, 16); width++; precision++; } void process_hex(t_converter *converter, va_list arg, int precision, int width) { converter->data->nbr = va_arg(arg, int); ft_putnbr_base(converter->data->nbr, 16); width++; precision++; }*/
C
#include <stdio.h> #include <stdlib.h> #include <math.h> int main() { float d,l,s; int t,x,y,r; scanf("%d",&t); while(t--) { scanf("%d %d %d",&x,&y,&r); d=sqrt(pow(x,2)+pow(y,2)); l=r+d; s=r-d; printf("%.2f %.2f\n",s,l); } return 0; }
C
//寫一個程式讀入三個平面上的座標, //然後印出其中距離原點最遠的點, //如果兩個或多個點,有相同的距離, //輸出最先出現的點座標。 #include <stdio.h> main() { int a, b; scanf("%d", &a); scanf("%d", &b); int x = a, y = b; scanf("%d", &a); scanf("%d", &b); if ((a*a + b*b) > (x*x + y*y)) { x = a; y = b; } scanf("%d", &a); scanf("%d", &b); if ((a*a + b*b) > (x*x + y*y)) { x = a; y = b; } printf("%d\n", x); printf("%d\n", y); }
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <conio.h> int fre_counter(char s[]) { int i, f = 0; for(i=0; s[i]!='\0'; i++) { if(s[i]=='t' && s[i+1]=='h' && s[i+2] == 'e' && s[i+2] != '\0') { f++; } } return f; } void main() { char s[50]; int f=0; printf("string :"); gets(s); f=fre_counter(s); printf("'the' in sentence : %d \n",f); _getch(); }
C
//Fibonacci sequence creator #include <stdio.h> int main(){ int a=1, b=1, c; printf("Enter a value:"); scanf("%d", &c); printf("%d - %d - ",a,b); for(; a+b<=c; ){ a=a+b; b=a-b; printf("%d - ",a); } }
C
#include "command_unalias.h" int command_unalias(int argc , char* arg[]) { int i = 0; int* mark = NULL; int retstate = 0; if(0 == argc || NULL == arg) { return -1; } mark = (int*)malloc(argc * sizeof(int)); if(strcmp("unalias",arg[0])) { shellcommandNOcall(STDERR_FILENO,"unalias"); return -1; } mark[0] = 1; if(-1 != (i = find_char_from_arg(argc,arg,'a'))) { delete_allalias(); mark[i] = 1; free(mark); return 0; } for(i = 1; arg[i] != NULL ; i++) { if(-1 == deletenv_name(&alias_table, arg[i])) { printf("No alias \"%s\"!!\n",arg[i]); retstate = 1; } else { mark[i] = 1; ifchange_table = 1; } } if(Nooptions(STDERR_FILENO, "unalias", mark, arg)) { retstate = 1; } free(mark); return retstate; } int delete_allalias() { ifchange_table = 1; alias_table.number = 0; return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include "list.h" #include "../student.h" #include "../../basic.h" extern void student_showAdapter(void *pStu); extern int student_writeAdapter(FILE *fp,void *pStu); extern int student_readAdapter(FILE *fp, void *pStu); extern int student_compareAdapter(void *pStu1, void *pStu2); extern void* student_newAdapter(); extern int student_deleteAdapter(void* pStu); int list_printElement(void* element1, void* element2) { student_showAdapter(element1); return LIST_OK; } int main() { int ret = 0;; list *plist = NULL; /* create */ plist = list_new(10); if (plist == NULL) { DEBUG_MESSAGE("new list failed"); return 0; } /* register function */ ret = plist->registerCreateElement(plist, student_newAdapter); DEBUG_ASSERT(ret == LIST_OK, 0); ret = plist->registerFreeElement(plist, student_deleteAdapter); DEBUG_ASSERT(ret == LIST_OK, 0); ret = plist->registerCompare(plist, student_compareAdapter); DEBUG_ASSERT(ret == LIST_OK, 0); ret = plist->registerWriteElement(plist, student_writeAdapter); DEBUG_ASSERT(ret == LIST_OK, 0); ret = plist->registerReadElement(plist, student_readAdapter); DEBUG_ASSERT(ret == LIST_OK, 0); plist->registerCallBack(plist, list_printElement); /* new instance */ student *stu1 = student_new("google", 10, 20); student *stu2 = student_new("microsoft", 20, 30); student *stu3 = student_new("apple", 30, 30); student *stu4 = student_new("ibm", 40, 40); student *stu5 = student_new("aws", 50, 20); student *stu6 = student_new("ali", 60, 20); student *stu7 = student_new("huawei", 70, 30); student *stu8 = student_new("tecent", 80, 20); /* insert by index */ ret = plist->insert1(plist, (void*)stu1, 0); DEBUG_ASSERT(ret == LIST_OK, 0); ret = plist->insert1(plist, (void*)stu2, 1); DEBUG_ASSERT(ret == LIST_OK, 0); /* insert by element */ ret = plist->insert2(plist, (void*)stu2, (void*)stu3); DEBUG_ASSERT(ret == LIST_OK, 0); ret = plist->insert2(plist, (void*)stu3, (void*)stu4); DEBUG_ASSERT(ret == LIST_OK, 0); /* push back */ ret = plist->push_back(plist, (void*)stu5); DEBUG_ASSERT(ret == LIST_OK, 0); ret = plist->push_back(plist, (void*)stu6); DEBUG_ASSERT(ret == LIST_OK, 0); ret = plist->push_back(plist, (void*)stu7); DEBUG_ASSERT(ret == LIST_OK, 0); /* push front */ ret = plist->push_front(plist, (void*)stu8); DEBUG_ASSERT(ret == LIST_OK, 0); /* print element */ printf("%s\n", "------------add----------------------"); ret = plist->traverse(plist, NULL); DEBUG_ASSERT(ret == LIST_OK, 0); /* reverse */ ret = plist->reverse(plist); DEBUG_ASSERT(ret == LIST_OK, 0); printf("%s\n", "------------reverse----------------------"); plist->traverse(plist, NULL); /* search return index */ Node* pNode = plist->search(plist, (void*)stu1); DEBUG_ASSERT(pNode != NULL, 0); /* write to file */ ret = plist->save(plist, "companie01.txt"); DEBUG_ASSERT(ret == LIST_OK, 0); /* delete by index */ ret = plist->remove1(plist, 0); DEBUG_ASSERT(ret == LIST_OK, 0); /* delete by element */ ret = plist->remove2(plist, (void*)stu2); DEBUG_ASSERT(ret == LIST_OK, 0); /* pop back */ ret = plist->pop_back(plist); DEBUG_ASSERT(ret == LIST_OK, 0); /* pop front */ ret = plist->pop_front(plist); DEBUG_ASSERT(ret == LIST_OK, 0); /* print element */ printf("%s\n", "-------------delete ------------------"); ret = plist->traverse(plist, NULL); DEBUG_ASSERT(ret == LIST_OK, 0); /* write to file */ ret = plist->save(plist, "companie02.txt"); DEBUG_ASSERT(ret == LIST_OK, 0); /* free */ ret = plist->free(plist); DEBUG_ASSERT(ret == LIST_OK, 0); /* read from file */ ret = plist->registerFreeElement(plist, NULL); DEBUG_ASSERT(ret == LIST_OK, 0); student stu[6]; int i = 0; for (i = 0; i < 6; i++) { plist->push_back(plist, (void*)&stu[i]); } ret = plist->load(plist, "companie01.txt"); DEBUG_ASSERT(ret == LIST_OK, 0); /* print element */ printf("%s\n", "-------------load ------------------"); ret = plist->traverse(plist, NULL); DEBUG_ASSERT(ret == LIST_OK, 0); /* sort */ ret = plist->sort(plist); DEBUG_ASSERT(ret == LIST_OK, 0); /* print element */ printf("%s\n", "-------------sort ------------------"); ret = plist->traverse(plist, NULL); DEBUG_ASSERT(ret == LIST_OK, 0); /* delete */ ret = plist->delete(plist); DEBUG_ASSERT(ret == LIST_OK, 0); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include "helper/list.h" /** * Frees a (void *) that is in reality an (int *) * @param integerVoidPointer */ void freeIntPointer(void *integerVoidPointer) { if (integerVoidPointer != NULL) free((int *)integerVoidPointer); } void *intComparator(void *a, void *b) { if (a != NULL && b != NULL) { if (*(int *)a >= *(int *)b) return a; else return b; } else return NULL; } int main() { // declare the list List *l1; // list is now [] // instantiate, initialize and add 1st element to the list int *i1 = malloc(sizeof(int)); *i1 = 10; list_addFirst(&l1, i1); // list is now [10] // instantiate, initialize and add 2nd element to the list int *i2 = malloc(sizeof(int)); *i2 = 11; list_addFirst(&l1, i2); // list is now [11, 10] // instantiate, initialize and add 3rd element to the list int *i3 = malloc(sizeof(int)); *i3 = 12; list_addLast(&l1, i3); // list is now [11, 10, 12] // instantiate, initialize and add 4th element to the list int *i4 = malloc(sizeof(int)); *i4 = 0; list_addLast(&l1, i4); // list is now [11, 10, 12, 0] // print the element in position 1 (that is 10) printf("the element in position 1 is: %d\n", *(int *)list_get(l1, 1)); // remove the element that is in position 1 list_remove(&l1, 1, freeIntPointer); // list is now [11, 12] // print the max element (that is 12) printf("the max element of the list is: %d\n", *(int *)list_max(l1, intComparator)); // remove all the list elements list_removeAll(&l1, freeIntPointer); // list is now [] }
C
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> int vflag, rflag, wflag, xflag; int displayVerbose(); void usage (char *prog) { printf("usage : %s [rvwx] file", prog); } int maccess (int argc, char **argv) { int mode = F_OK; int i; printf("OPTIONS verbose:%i, read:%i, write:%i, exec:%i\n",vflag,rflag,wflag,xflag); printf("REMAINING %i ARGS:\n",argc); for (i = 0; i < argc; i++) { printf("\t%s\n",argv[i]); } if(rflag){ mode = mode | R_OK; } if(wflag){ mode = mode | W_OK; } if(xflag){ mode = mode | X_OK; } if(vflag){ displayVerbose(); }else{ perror("Erreur utilisation des flags"); exit(EXIT_FAILURE); } return access(argv[1],mode); } int displayVerbose(){ switch(errno){ case EACCES: printf("ERREUR EACCES, vous n'avez pas tous les accès nécessaires.\n"); break; case ENAMETOOLONG: printf("ERREUR ENAMETOOLONG, le chemin est trop long.\n"); break; case ENOENT: printf("ERREUR ENOENT, une partie du chemin n'existe pas.\n"); break; case ENOTDIR: printf("ERREUR ENOTDIR, une partie du chemin n'est pas un répertoire.\n"); break; case EROFS: printf("ERREUR EROFS, tentative d'écriture sur un fichier en lecture seule.\n"); break; case ELOOP: printf("ERREUR ELOOP, liens symboliques rencontrés en boucle\n."); break; default: printf("ERREUR NON GEREE, voir l'erreur 'errno' pour obtenir le code d'erreur.\n"); } return 1; } int main (int argc, char **argv) { int ch; vflag = 0; rflag = 0; wflag = 0; xflag = 0; while ((ch = getopt(argc, argv, "vrwxh")) != -1) { switch (ch) { case 'v': vflag = 1; break; case 'r': rflag = 1; break; case 'w': wflag = 1; break; case 'x': xflag = 1; break; case 'h': default: usage(argv[0]); } } argc -= optind; argv += optind; return maccess(argc,argv); }
C
#include "floatToHex3a.h" float number = -2.25; uint8_t message[32]; int main() { int i; floatToByte(number, message); for(i = 0; i < 32; i++) { printf("here is the message[i] %X\n",message[i]); } return 0; }
C
/****************************************************************************** * Student Name : * RMIT Student ID : * COURSE CODE : * * Startup code provided by Paul Miller for use in "Programming in C", * study period 4, 2018. *****************************************************************************/ #include "repl.h" /** * * commands to be implemented for our repl: * - read(r): read a file into memory. Lines when read in must be wrapped at or * before 80 characters. * * - write(w): write the lines in memory to a file - a file must have been * previously loaded. * * - print(p): print out the lines of a file. Optionally a range of lines can * be provided, either a single line number or a range where the first * number must be lower than the second however both numbers must be within * the range of the lines in the file loaded. * * - insert(i): specified by i followed by an integer within the range of 1 * to the number of lines in the file plus 1. * * - delete (d): specified by the letter d followed by a single number or 2 * numbers separated by a minus sign where the first number must be less * than or equal to the second number. * * - search (s): specified by the letter s followed by a work or a phrase. The * program will iterate over all the lines of the file and print out each * line that contains the matching phrase. All leading spaces between the * command and the first letter shall be ignored. * * After printing out 25 matches, the user will be asked if they wish to * continue and if they do, the next 25 lines that match will be printed. * * The prompt which must be used to indicate that the program is ready for * input is the > character. Any errors should have clear output so the user * knows what they need to do to correct it. * * All commands may have 0 or more spaces between the command and the * argument. For **/ static void read_rest_of_line(void) { int ch; while (ch = getc(stdin), ch != '\n' && ch != EOF) ; clearerr(stdin); } void repl(const struct command commands[], char filename[]) { struct line_list* thelist; /* tell the compiler that the local definition of read_rest_of_line() * won't be used */ (void)read_rest_of_line; /* create the list */ thelist = linelist_make(); /* load the file into the list */ load_file(filename, thelist); /* print the list */ linelist_print(thelist, stdout); /* save the file back to disk */ save_file(filename, thelist); /* free the list */ linelist_free(thelist); } /** * acts as a proxy to printf. All output sent here will go to normal output via * "stdout" **/ int normal_print(const char format[], ...) { va_list va_args; int output_chars; /* initialise the variable args */ va_start(va_args, format); /* pass them to printf */ output_chars = vprintf(format, va_args); /* finish with processing the variable args */ va_end(va_args); /* return the number of chars written out */ return output_chars; } /** * acts as a proxy to printf, except the output gets sent to stderr, the * error file pointer. . All output sent here will go to normal output via * "stdout" **/ int error_print(const char format[], ...) { va_list va_args; int output_chars; /* initialise the variable args */ va_start(va_args, format); /* output preamble to an error message: */ output_chars = fprintf(stderr, "Error: "); /* print the error message */ output_chars += vfprintf(stderr, format, va_args); output_chars += fprintf(stderr, "\n"); return output_chars; }
C
//C hello world example #include <stdio.h> #include <time.h> // #include <conio.h> // testing git void my_function(); int max(int, int); int solution(int A[], int ); int solution_2(int N) ; int solution_3(int A[], int N); int solution_4(int A[], int N, int X, int D); int solution_5(char *E, char *L); void getSeconds(unsigned long *par); void showbits(unsigned int x){ int i; for(i=(sizeof(int)*8)-1; i>=0; i--){ (x&(1<<i))?putchar('1'):putchar('0'); } printf("\n"); } int main() { printf("Hello world\n"); int c =0; // int array[8] = {-3, 3, -4, 5, 1, -6, 2, 1}; int array[3] = {1, 0, 0}; double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0}; my_function(); printf("Back in function main.\n"); c = solution(array, 3); printf("value of c : %d \n", c); // int j = 9736, m, n; // printf("The decimal %d is equal to binary - \n", j); // showbits(j); // /* the loop for right shift operation */ // for ( m = 0; m <= 30; m++ ) { // n = j >> m; // printf("%d right shift %d gives ", j, m); // // showbits(n); // printf("The decimal %d is equal to binary - \n", n); // } // showbits(9736); // c = solution_2(809500676); // printf("value of c : %d \n", c); // int array_3 [8] = {0, 3, 3, 7, 5, 3, 11, 1}; // int array_4 [6] = {1, 4, 7, 3, 3, 5}; // c = solution_3(array_3, 8); // printf("value of c : %d \n", c); // c = solution_3(array_4, 6); // printf("value of c : %d \n", c); int array_5 [6] = {1, 3, 1, 4, 2, 5}; c = solution_4(array_5, 6, 7, 3); printf("value of c : %d \n", c); char Enter[5] = "10:00"; char Leaf[5] = "13:21"; // char *E = &Enter; // char *L = &Leaf; c = solution_5(Enter, Leaf); printf("value of c : %d \n", c); // unsigned long sec; // getSeconds( &sec ); // print the actual value // printf("Number of seconds: %ld\n", sec ); return 0; } int solution_5(char *E, char *L) { printf("%s\n",E); printf("seperate\n"); printf("%s\n",E); printf("%s\n",L); for (int i = 0; i < 2; ++i) { printf("%s\n", E[i]); } return 10; } void getSeconds(unsigned long *par) { /* get the current number of seconds */ *par = time( NULL ); return; } int solution_4(int A[], int N, int X, int D) { int current_position = 0; int current_time = 0; int destination = X; int i=0; if(X <= D){ return 0; } for (i = 0; i < N; i++) { // printf("i = %d, A[i] = %d\n", i, A[i] ); if( (A[i] - current_position < 4) && (A[i] - current_position > 0) && (A[i] <= X) ){ current_position = A[i]; current_time = i; if(X - current_position <= D){ return current_time; } } if(i == N-1 && current_position < X){ return -1; } } return -2; } int solution_2(int N) { int largest = N; int shift = 0; int temp = N; int i; for (i = 1; i < 30; ++i) { int index = (temp & 1); // the right most bit printf("index = %d , i = %d ", index, i); temp = ((temp >> 1) | (index << 29)); // shift right one bit and add the index onto the left most printf("temp= %d ", temp); printf(" largest = %d, shift = %d \n", largest, i); if (temp > largest) { largest = temp; shift = i; } } return shift; } int solution_3(int A[], int N){ int i; int j; int k; int have_adjacent_value = 0; int distance = 0; int smallest_distance = 4000000; for( i = 0; i < N-1; i++){ for( j = i + 1; j < N; j++){ printf("(i,j) = (%d, %d) = A[%d]=%d, A[%d]=%d ", i, j, i, A[i] ,j, A[j]); if( (A[j] - A[i]) != 0){ have_adjacent_value = 1; for( k = 0; k < N ; k++){ if( ( A[i] < A[k]) && ( A[k] < A[j] ) ) { have_adjacent_value = 0; } if( ( A[k] > A[j] ) && ( A[k] < A[i] ) ) { have_adjacent_value = 0; } // else{ // have_adjacent_value = 1; // } }// end of for loop } else{ have_adjacent_value = 0; } printf("have_adjacent_value= %d ", have_adjacent_value); if(have_adjacent_value == 1){ distance = j-i; if(distance < smallest_distance){ smallest_distance = distance; } } printf("distance= %d \n", distance); } distance = 0; have_adjacent_value = 0; } if(smallest_distance == 4000000){ return -1; } else{ return smallest_distance; } return -2; } void my_function(){ printf("Welcome to my function. Feel at home.\n"); } int solution(int A[], int N) { if (N==0) return -1; long long sum = 0; int i; for(i=0; i< N; i++) sum+=(long long) A[i]; long long sum_left = 0; for(i=0; i<N ; i++) { long long sum_right = sum - sum_left - (long long) A[i]; if (sum_left == sum_right) return i; sum_left += (long long) A[i]; } return -1; } int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; }
C
/** * 参考自 https://github.com/AndreMouche/algorithms_study/blob/master/data_structure/skiplist.cpp ,https://www.epaperpress.com/sortsearch/txt/skl.txt * 踩坑如下:insert方法中 update变量初始化问题,不同于java声明变量后变量初始赋值为NULL,而是随机值,当取址时就会出错。谨记!!! * * 另外复习下结构体初始化方式: * 1.recType value = (recType){key}; * or recType value = {key}; * 2.recType value; value.key = key; * 乱序时 * 3.recType value = {stuff:key} */ #include <stdio.h> #include <stdlib.h> /* implementation dependent declarations */ typedef enum { STATUS_OK, STATUS_MEM_EXHAUSTED, STATUS_DUPLICATE_KEY, STATUS_KEY_NOT_FOUND } statusEnum; typedef int keyType; typedef struct { int stuff; } recType; #define compLT(a,b) (a < b) #define compEQ(a,b) (a == b) #define MAX_LEVEL 15 typedef struct nodeTag{ keyType key; recType rec; struct nodeTag *forward[]; } nodeType; typedef struct { nodeType *header; /* list Header */ int listLevel; /* current level of list */ } skipList; static int randomLevel() { int k = 1; while(rand()%2) { k++; } k = (k < MAX_LEVEL) ? k : MAX_LEVEL; return k; } nodeType *creatNode(int level, keyType key, recType value) { nodeType *newNode = (nodeType *) malloc(sizeof(nodeType) + level * sizeof(nodeType *)); newNode->key = key; newNode->rec = value; for (int i = 0; i < level; i++) { newNode->forward[i] = NULL; } return newNode; } statusEnum insert(skipList * list,keyType key,recType value){ // check exists int level = list->listLevel; nodeType *x = list->header; nodeType *update[MAX_LEVEL]; for (int i = level; i >= 0; i--) { // trick mark by gao while (x->forward[i] != NULL && compLT(x->forward[i]->key, key)) x = x->forward[i]; update[i] = x; } x = x->forward[0]; if (x != NULL && compEQ(x->key, key)) return STATUS_DUPLICATE_KEY; /* bug,case update[i] has not been inited .will case Segmentation fault for(int i = 0 ; i < MAX_LEVEL; i ++ ){ if (update[i] != NULL && update[i]->forward[i] != NULL && compEQ(update[i]->forward[i]->key, key)) { return STATUS_DUPLICATE_KEY; } }*/ int newLevel = randomLevel(); nodeType *newNode = creatNode(newLevel, key, value); // bug fix, if (newLevel > list->listLevel) { for (int i = list->listLevel; i < newLevel; ++i) { //bug fix,并不赋值为NULL,方便后面的for循环避免NULL判断 update[i] = list->header; // update[i] = NULL; } list->listLevel = newLevel; } for(int i = 0 ; i < newLevel; i ++ ) { newNode->forward[i] = update[i]->forward[i]; update[i]->forward[i] = newNode; } return STATUS_OK; } recType * search(skipList * list,keyType key){ // bad implements /* // 特殊情况的特殊处理,最好不要上来就处理。应该先记住,尽可能在通用代码中包含特殊情况,如果包含不了再特殊处理。 if (list->listLevel == 0) return NULL; int level = list->listLevel; nodeType * header= list->header; for (int i = level - 1; i >= 0; i--) { while (header->forward[i] != NULL && compLT(header->forward[i]->key, key)) { header = header->forward[i]; } } if (header == NULL || !compEQ(header->forward[0]->key, key)) { return NULL; } return header->forward[0];*/ //good implements nodeType *header, *q = NULL; header = list->header; int level = list->listLevel; for (int i = level; i >= 0; i--) { while (header->forward[i] != NULL && compLT(header->forward[i]->key, key)) { header = header->forward[i]; } // here!! if (header->forward[i]!=NULL && compEQ(header->forward[i]->key, key)) { return header->forward[i]; } } return NULL; } statusEnum delete(skipList * list,keyType key) { nodeType *p = list->header,*q = NULL; int level = list->listLevel; for (int i = level; i >= 0; i--) { while (p->forward[i] != NULL && compLT(p->forward[i]->key, key)) { p = p->forward[i]; } if (p->forward[i] != NULL && compEQ(p->forward[i]->key, key)) { q = p->forward[i]; p->forward[i] = q->forward[i]; } } if (q == NULL) { return STATUS_KEY_NOT_FOUND; } free(q); /* while(list->header->forward[level-1]==NULL){ level--; list->listLevel = level; }*/ while (list->listLevel > 0 && list->header->forward[list->listLevel - 1] == NULL) { list->listLevel --; } return STATUS_OK; } void printSkipList(skipList *list){ int level = list->listLevel; nodeType *p; for (int i = level; i >= 0; i--) { p = list->header; while(p->forward[i]!=NULL){ printf("%d\t%d(%d)\t",i, p->forward[i]->key,p->forward[i]->rec.stuff); p = p->forward[i]; } printf("\n"); } } skipList * creatSkipList(){ skipList *sl = (skipList *) malloc(sizeof(skipList)); if (sl == NULL) { printf ("insufficient memory (creatSkipList)\n"); exit(1); } // todo check key 0? nodeType *node = creatNode(MAX_LEVEL, 0, (recType){0}); sl->header = node; sl->listLevel = 0; } void main(int argc, char *argv[]){ skipList *list = creatSkipList(); for (int i = 0; i < 1000; i++) { keyType key = rand()%10000; //recType value = {key}; recType value = {stuff:key}; statusEnum status = insert(list, key, value); if (status) { printf("statusEnum:%d,key:%d\n", status, key); } } int n; scanf("%d", &n); recType *value = search(list, n); printf("search vlaue:%d\n", value->stuff); statusEnum delstatus = delete(list, n); printf("del status:%d", delstatus); printSkipList(list); }
C
#ifndef _COMMON_H_ #define _COMMON_H_ // I[o[Cȟx}~ #pragma warning(disable: 4996) #include "Vector.h" #define PI 3.141592f #define D2R(degree) (degree * 0.017453f) #define R2D(radian) (radian / 0.017453f) #define null 0 #define boolean unsigned char #define SAFE_METHOD(p, method) {if(p) p->method();} #define SAFE_RELEASE(p) if(p){p->release();p=null;} #define SAFE_DELETE(p) {if(p){delete p;p=NULL;}} #define SAFE_DELETE_UNINIT(p) {if(p){p->uninit();delete p;p=NULL;}} #define SAFE_DELETE_ARRAY(p) {if(p){delete[] p;p=NULL;}} /** * sprintfgpľܓ֐ * @param num ľܓ錳̐l * @param precision ľܓ錅 * @return ľܓ */ float roundprecision(float num, int precision); /** Oϔp֐\n * pVtx0pVtx1̃xNgpVtx0pPos̃xNgOόvZǍʂԂ * @param Vector3* pVtx0 2{̃xNg̊Jn_ * @param Vector3* pVtx1 ƂȂxNg̏I_ * @param Vector3* pPos ׂxNg̏I_ * @return float ̃xNgpPosEȂ琳̒lAȂ畅(^o^){ӫc̒lԂ */ float TestCross(const VECTOR3* pVtx0, const VECTOR3* pVtx1, const VECTOR3* pPos); /** Oςgp3_Ƀ|WV邩ǂׂ֐\n * 3‚̒_ɒׂ|WV邩ǂׂEɂꂼ̒_𑗂 * @param pVtx0 _0 * @param pVtx1 _1 * @param pVtx2 _1 * @param pPos ׂ钸_(vC[ƂGl~[Ƃ) * @return BOOL ȂԎ[ */ bool HavePosition(VECTOR3* pVtx0, VECTOR3* pVtx1, VECTOR3* pVtx2, VECTOR3* pPos); /** * fobOo * @param str o͕(̊֐ĂԂƎʼns) */ void debug(const char* str); /** * l𕶎ɕϊ * @param value ϊ * @return Lobt@ */ char* to_s(int value); /** * l𕶎ɕϊ * @param value ϊ * @return Lobt@ */ char* to_s(float value); /** * LX^bNN[ */ void cleanString(); /** * LX^bNɘA * @param str1, str2 A * @return Lobt@ */ char* attachString(char* str1, char* str2); /** * oEh{bNX * @param lt @ @param rb E * @param p ׂW * @return true : in false : out */ bool boundBox(const VECTOR2& lt, const VECTOR2& rb, const VECTOR2& p); /** * OpenGLn̊֐yɂ(߂ǂ) * @param callback ĂяoOpenGL`惁\bh(3ŒŒ) * @param v o͂xNg */ void dm(void (__stdcall *callback)(float, float, float), const VECTOR3& v); #endif // _COMMON_H_
C
#include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <math.h> #define NUMVALS 1024 int mylist[1024]; int sortedList[1024]; typedef struct { int start_index; int end_index; } SortInfo; int genRand(int low, int high) { // generate a random integer r such that low <= r <= high double r1, r2; int rtnval; r1 = drand48(); r2 = (1 + high - low) * r1; rtnval = low + floor(r2); return(rtnval); } void *sorter(void *param){ SortInfo *data = (SortInfo *) param; int start = data->start_index; int end = data->end_index; int i,j,k; for (i = 0; i < NUMVALS/2; i++) { for (j = start; j < end - i; j++) { if (mylist[j] > mylist[j + 1]) { int temp = mylist[j]; mylist[j] = mylist[j+1]; mylist[j+1] = temp; } } } pthread_exit(0); } void *merger(void* param ){ int* secondStart =(int *)param; //int secondStart = 512; int i = 0, j = *secondStart, k = 0; while (i<NUMVALS/2 && j <NUMVALS) { if (mylist[i] < mylist[j]) { sortedList[k++] = mylist[i++]; } else{ sortedList[k++] = mylist[j++]; } } while (i < NUMVALS/2) { sortedList[k++] = mylist[i++]; } while (j < NUMVALS) { sortedList[k++] = mylist[j++]; } pthread_exit(0); } int main(){ int i; for (i = 0; i < NUMVALS; ++i) { mylist[i] = genRand(0,5000); } SortInfo sortInfo1, sortInfo2; pthread_t tid1; /* thread identifier */ pthread_t tid2; /* thread identifier */ pthread_t tid3; /* thread identifier */ pthread_attr_t attr; /* thread attributes */ pthread_attr_init(&attr); sortInfo1.start_index = 0; sortInfo1.end_index = NUMVALS/2; sortInfo2.start_index = sortInfo1.end_index + 1; sortInfo2.end_index = NUMVALS-1; pthread_create(&tid1, &attr, sorter, &sortInfo1); pthread_create(&tid2, &attr, sorter, &sortInfo2); pthread_join(tid1,NULL); pthread_join(tid2,NULL); int secondStart = sortInfo2.start_index; pthread_create(&tid3, &attr, merger, &secondStart); pthread_join(tid3,NULL); return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef int INT ; typedef scalar_t__ COLORREF ; /* Variables and functions */ scalar_t__ ERROR_NOACCESS ; scalar_t__ FALSE ; scalar_t__ GetLastError () ; scalar_t__ GetSysColor (int) ; int NUM_SYSCOLORS ; scalar_t__ RGB (int,int,int) ; int /*<<< orphan*/ SetLastError (int) ; scalar_t__ SetSysColors (int,int*,scalar_t__*) ; scalar_t__ TRUE ; int /*<<< orphan*/ ok (int,char*,...) ; void Test_SetSysColors() { INT i; INT nElements[NUM_SYSCOLORS+1]; COLORREF crOldColors[NUM_SYSCOLORS]; COLORREF crColors[NUM_SYSCOLORS+1]; /* First save the Old colors */ for (i = 0; i < NUM_SYSCOLORS; i++) { nElements[i] = i; crOldColors[i] = GetSysColor(i); } for (i = 0; i < NUM_SYSCOLORS+1; i++) crColors[i] = RGB(i, 255-i, i*3); nElements[NUM_SYSCOLORS] = nElements[0]; SetLastError(0xdeadbeef); ok(SetSysColors(-1, nElements, crColors) == FALSE, "Expected FALSE, got TRUE\n"); ok(GetLastError() == ERROR_NOACCESS, "Expected ERROR_NOACCESS, got %ld\n", GetLastError()); ok(SetSysColors(0, nElements, crColors) == TRUE, "Expected TRUE, got FALSE\n"); ok(SetSysColors(0, NULL, crColors) == TRUE, "Expected TRUE, got FALSE\n"); ok(SetSysColors(0, nElements, NULL) == TRUE, "Expected TRUE, got FALSE\n"); ok(SetSysColors(1, NULL, crColors) == FALSE, "Expected FALSE, got TRUE\n"); ok(GetLastError() == ERROR_NOACCESS, "Expected ERROR_NOACCESS, got %ld\n", GetLastError()); ok(SetSysColors(1, nElements, NULL) == FALSE, "Expected FALSE, got TRUE\n"); ok(GetLastError() == ERROR_NOACCESS, "Expected ERROR_NOACCESS, got %ld\n", GetLastError()); ok(SetSysColors(1, nElements, crColors) == TRUE, "Expected TRUE, got FALSE\n"); ok(SetSysColors(NUM_SYSCOLORS, nElements, crColors) == TRUE, "Expected TRUE, got FALSE\n"); for (i = 0; i < NUM_SYSCOLORS; i++) ok(GetSysColor(nElements[i]) == crColors[i], "Expected %06lx, got %06lx\n", crColors[i], GetSysColor(nElements[i])); /* try more than NUM_SYSCOLORS */ ok(SetSysColors(NUM_SYSCOLORS+1, nElements, crColors) == TRUE, "Expected TRUE, got FALSE\n"); nElements[NUM_SYSCOLORS] = 10000; ok(SetSysColors(NUM_SYSCOLORS+1, nElements, crColors) == TRUE, "Expected TRUE, got FALSE\n"); /* restore old SysColors */ SetSysColors(NUM_SYSCOLORS, nElements, crOldColors); }
C
/** * @file main2.c * @brief Множення матриці саму на себе * * @author Makarenko V. * @date 14-dec-2020 * @version 1.0 */ #include <stdlib.h> #include <time.h> /** * Розмір матриці */ #define SIZE 3 /** * функція для множення матриці саму на себе * * Послідовність дій: * - створення масиву, в який буде записаний результат множення * - процес множення матриць, за допомогою циклів for * @return успішний код повернення з програми (0) * @param result_matrix масив, в який буде записаний результат множення матриць */ void matrix_multiplication (int matrix[SIZE][SIZE]); //функция, которая будет умножать матрицу саму на себя /** * Головна функція. * * Послідовність дій: * - створення масиву * - заповнення масиву за допомогою функції rand() * - виклик функціїї matrix_multiplication * @return успішний код повернення з програми (0) * @param matrix матриця, яку ми будемо множити саму на себе */ int main() { srand(time(NULL)); int matrix[SIZE][SIZE] = {0}; //задаем нашу матрицу // заполняее матрицу случайними числами for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { matrix[i][j] = rand() % 10; } } (matrix); //вызываем функцию для перемножения return 0; } // описываем работу нашей функции void matrix_multiplication (int matrix[SIZE][SIZE]) { int result_matrix[SIZE][SIZE] = {0}; for (int i = 0; i < SIZE; i++){ for (int j = 0; j < SIZE; j++){ for (int l = 0; l < SIZE; l++) { result_matrix[i][j] += matrix[i][l] * matrix[l][j]; } } } return; }
C
#include <stdio.h> #include <string.h> int main( ) { char str2[10], str1[10]="darsh"; str2[10]=strrev(str1); printf("The entered string is: %s",str1); printf ("The reversed string is : %s",str2) ; return 0; }
C
#include<stdio.h> #include<math.h> void triangleTypeCheck(double a, double b, double c) { if( !((a+b) > c) || !((b+c) > a) || !((a+c) > b) ) { printf("Invalid\n"); } else if( (a == b) && (b == c) ) { printf("Equilateral Triangle\n"); } else if( (a != b) && (a != c) && (b != c) ) { if( (a / (c-b)) == ((c+b) /a )) { printf("Right Angled Triangle\n"); } else { printf("Not Special\n"); } } else if( (a == b) || (a == c) || (b == c) ) { printf("Isosceles Triangle\n"); } else { printf("Not Special\n"); } } int main() { double a, b, c; printf("Enter the Sides of the Triangle\n"); scanf("%le %le %le", &a, &b, &c); triangleTypeCheck(a, b, c); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> /* Include cloc-generated header files */ #include "hw.h" #include "hw2.h" int main(int argc, char* argv[]) { char* input1 = "Gdkkn\x1FGR@\x1FVnqkc"; size_t strlength = strlen(input1); char *input = (char*) malloc_global(strlength + 1); char *output = (char*) malloc_global(strlength + 1); char *secode = (char*) malloc_global(strlength + 1); char *output2 = (char*) malloc_global(strlength + 1); memcpy(input, input1, strlength+1); /* Here we show how to initialize the kernel. It is not really needed but it will make the first call go slightly faster. */ decode_init(0); SNK_INIT_LPARM(lparm,strlength); decode(input,output,lparm); output[strlength] = '\0'; printf("Decoded :%s\n",output); /* Show we can call multiple functions in the .cl file */ super_encode(output,secode,lparm); printf("Super encoded :%s\n",secode); super_decode(secode,output2,lparm); printf("Super decoded :%s\n",output2); /* Here we show it is ok to Destroy a Kernel and call it again after the Destroy. It will just reinitialize on the next call. */ decode_stop(); /* Show we can call same function multiple times */ decode(secode,output,lparm); decode(output,output2,lparm); printf("Decoded twice :%s\n",output2); free_global(output); free_global(secode); free_global(output2); return 0; }
C
#include <stdio.h> int numero, ultimoNumero, penultimoNumero, primeiroNumero; int main(){ printf("...::: PROGRAMA INVERSOR DE NUMEROS :::...\n"); printf("Insira o número que deseja inverter:"); printf("0 a 999\n"); scanf("%i", &numero); //calculador de numeros// ultimoNumero = numero % 10; penultimoNumero = numero / 10 % 10; primeiroNumero = numero / 100; printf("Aqui esta o numero invertido %i%i%i\n", ultimoNumero, penultimoNumero, primeiroNumero); return 0; }
C
#include "simple_logger.h" #include "gf2d_draw.h" #include "level.h" #include "Grunt.h" static Level *THE_LEVEL = NULL; Level *level_get_active() { return THE_LEVEL; } Uint8 level_bounds_test_circle(Level *level, Vector2D center, float radius, Vector2D *normal) { Uint8 hit = 0; if (!level) { slog("no level provided for test"); return 0; } if (center.x - radius < level->bounds.x) { hit = 1; if (normal)normal->x = 1; } if (center.y - radius < level->bounds.y) { hit = 1; if (normal)normal->y = 1; } if (center.x + radius > level->bounds.x + level->bounds.w) { hit = 1; if (normal)normal->x = -1; } if (center.y + radius > level->bounds.y + level->bounds.h) { hit = 1; if (normal)normal->y = -1; } if ((hit) && (normal)) { vector2d_normalize(normal); } return hit; } Level *level_new(char *backgroundFile, Uint8 stages) { Level *level; if (!backgroundFile) { slog("no backgroundFile provided!"); return NULL; } level = (Level*)gfc_allocate_array(sizeof(Level), 1); if (!level)return NULL; level->background = gf2d_sprite_load_image(backgroundFile); level->levelComplete = 0; level->screenCount = 0; level->currentStage = 1; level->maxStages = stages; //gfc_rect_set(level->bounds, bounds.x, bounds.y, bounds.w, bounds.h); THE_LEVEL = level; return level; } void level_free(Level *level) { if (!level)return; gf2d_sprite_free(level->background); free(level); } void level_draw(Level *level) { if (!level)return; gf2d_sprite_draw_image(level->background, level->position); gf2d_draw_rect(level->bounds, vector4d(255, 0, 0, 255)); } void level_mover(Level *self, Entity *player){ if (self ->levelComplete > self->maxStages && player->position.x > 700){ self->position.x -= 2; player->position.x -= 2; if (self->screenCount < 500){ self->screenCount++; } else{ self->levelComplete = 0; self->screenCount = 0; self->spawnStage = 1; } } }
C
#include "Paging.h" /*paging*/ #define small_page 1024 /*1 kb*/ #define pageby4 4096 /*1024*4 4 kb*/ /*bits as defined in os dev for enmabling paging*/ #define cr0enable 0x80000000 #define cr4enable 0x00000010 /*various flags all described in ULK*/ #define global_flag 0x100 #define dirty_flag 0x40 #define page_size_flag 0x80 #define accessed_flag 0x20 #define cache_flag 0x10 #define write_through_flag 0x8 #define checkurprivaledge_flag 0x0 #define rwr_flag 0x2 #define present_flag 0x1 #define four_megabyte 0x00400000 /*global priveldge rwr and present all in one*/ #define allflag 0x183 /*video memory*/ #define vmemme 0xB8000 /*4mb kernel 4kb for video*/ extern void enable_paging(){ int a=cr0enable; int b=cr4enable; /*set cr4 and cr3 to the corresponding bits using inlined assembly*/ asm ( "movl %%cr4, %%eax\n\t" "orl %1, %%eax\n\t" "movl %%eax, %%cr4\n\t" "movl %%cr0, %%eax\n\t" "orl %0, %%eax\n\t" "movl %%eax, %%cr0\n\t" : : "r" (a), "r" (b) :"eax"); /*first mov into register then into cr4 and so on and so on cr4 MUST GO FIRST OTHERWISE THIS WILL NOT WORK must have extended paging before paging*/ } extern void make_page(unsigned int * page_dir, unsigned int * page_tab){ int i; /*set all tabls and directories to read writable incase they must be overwritten (not necessary for those that arent prseent)*/ for(i = 0; i < small_page; i++) { page_dir[i] = rwr_flag; } for(i = 0; i < small_page; i++) { page_tab[i] = rwr_flag; } /*set all the flags for the video memory we need to set these to kernel priveledge*/ int offs=vmemme/(pageby4); page_tab[offs]=vmemme; page_tab[offs] = page_tab[offs]|checkurprivaledge_flag; page_tab[offs] = page_tab[offs] |rwr_flag; page_tab[offs] = page_tab[offs] | present_flag; /*2 is temporary for 3.1, We just init the vmeme and kernel. Kernel is at 1 and is extended paging. vmem is in dir 0 at some offset*/ for(i = 0; i < 2; i++) /*for this checkpoint we only need to init the page dir where vmem and kernel mem live thus we only loop through for two. Since I explained this is not a magic num.*/ { if(i==0) { /*video memory lives at this one its less than four mb so in the first page*/ page_dir[i]=(unsigned int)page_tab; page_dir[i] = page_dir[i]|checkurprivaledge_flag; page_dir[i] = page_dir[i]|rwr_flag; page_dir[i] = page_dir[i]|present_flag; } if(i==1) { /*lives in the second page does the kernel memory it lives from 4-8mb so the second page*/ page_dir[i] = four_megabyte; page_dir[i]|=allflag; /*remember we index starting from 0 :)*/ } } /*unsigned int to hold our page dir pointer laod it into cr3 so cr3 points to our page directory*/ unsigned int q=(unsigned int)page_dir; asm ( "movl %0, %%eax \n\t" "movl %%eax, %%cr3 \n\t" : :"r" (q) /* input */ :"eax"); }
C
# include <stdio.h> enum days {Sun, Mon, Tue, Wed, Thu, Fri, Sat}; void main() { enum days Var; for(Var=Sun;Var<=Sat;Var++) { switch(Var) { case Sun:printf("\nSunday"); break; case Mon:printf("\nMonday"); break; case Tue:printf("\nTuesday"); break; case Wed:printf("\nWednesday"); break; case Thu:printf("\nThursday"); break; case Fri:printf("\nFriday"); break; case Sat:printf("\nSaturday\n"); break; } } }
C
/* * Copyright (c) 2014, Ben Wei (ben@staros.mobi) * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <string.h> #include "morse.h" static int verbose = 0; #define MORSE_E_UNKNOWN_ESCAPE 2 static int show_morse_code(const char *code, unsigned int len) { struct token_element *t = find_token(code); if (!t) { if (*code == '\\') { code++; if (*code == 'x') { int c = hex_to_char(&code[1]); if (c < 0) { printf("\\%s", code); return MORSE_E_UNKNOWN_ESCAPE; } printf("%c", (char)c); return 0; } printf("%s", code); return 0; } /* escape leading '\' */ printf("%s", code); return 0; } printf("%s", t->display); return 0; } void syntax() { printf("sytax: [-v <morse code>] | -l | -e <display char>\n"); } int show_morse_code_with_check(const char *morse_buf, int morse_len, unsigned int current) { int r = show_morse_code(morse_buf, morse_len); if (verbose && r != 0) { fprintf(stderr, "warning: unknown esacpe hex code '\\'x at %u\n", current - morse_len); } return r; } static int lookup_morse_code_by_display_char(char display_char) { const char *code = find_code_string(display_char); if (code == NULL) { printf("code '%c' is not found.\n", display_char); return 1; } printf("code '%c' is [%s]\n", display_char, code); return 0; } #define MAX_MORSE_CODE_LEN 5 int main(int argc, char **argv) { int rc = 0; const char *input_code = NULL; char morse_buf[MAX_MORSE_CODE_LEN + 1] = {0}; unsigned int morse_len = 0; const char *p; if (argc < 2) { syntax(); return 1; } input_code=argv[1]; if (*input_code == '-') { switch(input_code[1]) { case 'l': show_morse_code_table(); return 0; case 'e': if (argc < 3) { syntax(); return 1; } return lookup_morse_code_by_display_char(argv[2][0]); case 'v': verbose++; if (argc < 3) { syntax(); return 1; } input_code = argv[2]; break; }; } for (p=input_code; *p != '\0';++p) { if (morse_len < MAX_MORSE_CODE_LEN) { if (*p != ' ' && *p != '\n') { morse_buf[morse_len++] = *p; } } if (*p == ' ' || *p == '\n') { morse_buf[morse_len] = '\0'; rc |= show_morse_code_with_check(morse_buf, morse_len, p - input_code); morse_len = 0; } } if (morse_len != 0) { morse_buf[morse_len] = '\0'; rc |= show_morse_code_with_check(morse_buf, morse_len, p - input_code); } printf("\n"); return rc; }
C
#include "debug.h" #include "nlib.h" #include <stdlib.h> i64 err_s = 0; void print_parse_tree() { for (i64 i = 0; i < parse_top; i++) printf("%s\n", neta_node2string(parse_tree[i])); } void print_eval_stack() { for (i64 i = 0; i < eval_top; i++) printf("%s\n", neta_node2string(eval_stack[i])); } void neta_err() { printf("Neta: %lld\n", err_s++); } void pi(i64 i) { printf("%lld\n", i); } void ps(char *s) { printf("%s\n", s); } void pf(f64 f) { printf("%lf\n", f); } char *print_value(struct neta_node v) { char *r = (char *)malloc(sizeof(char) * inf24); switch (v.t) { case INTEGER: sprintf(r, "%lld", v.v.i); break; case FLOAT: sprintf(r, "%lf", v.v.f); break; case STRING: sprintf(r, "\"%s\"", v.v.s); break; case CHAR: sprintf(r, "\'%c\'", v.v.c); break; case PRESERVED_FUN: sprintf(r, "%s", v.v.s); break; case IDENTIFIER: sprintf(r, "%s", v.v.s); break; default: sprintf(r, "What The Hell? Couldn't Find Known Value"); } return r; } void print_function(char *s) { struct neta_node *head = search_gvnode(glov, s)->value; if (head->p == nil) return; struct neta_node *it = head->p; while (it != nil) { printf("%s", neta_node2string(*it)); it = it->next; } } void print_global_variable() { print_gv(glov); } void print_global_variable_d(struct global_variable *t) { if (t == nil) return; print_global_variable_d(t->left); // if (t->initialized) printf("%s: %s\n", t->name, print_value(*t->value)); // else // printf("%s haven't been initialized\n", t->name); print_global_variable_d(t->right); }
C
#include<stdio.h> main() { unsigned int a,b,c; printf("Enter a:"); scanf("%d",&a); printf("Enter bit position :"); scanf("%d",&b); if(((0<=b)&&(b<=31))?1:printf("Wrong data Entered");) { b=1<<b; c=a&&b; printf("%d",c); } }
C
#include "dog_struct.h" struct dog * create_dog(char * name, char * color, uint8_t age, uint8_t weight){ static int dog_create_count = 0; printf("Dogs created = %d\n", dog_create_count); dog_create_count++; // create dog struct struct dog * d = NULL; d = (struct dog *) malloc(sizeof(struct dog)); // if NULL then exit if (d == NULL) { exit(1); } // set variables d->name = name; d->color = color; d->age = age; d->weight = weight; // return obvi return d; } void delete_dog(struct dog * d){ if (d != NULL) { free(d); d = NULL; } } void print_dogs(struct dog_array* d){ for (int i = 0; i < d->num_dogs; i++) { printf("ptr: %p, ", d->arr[i]); printf("The %s dog, %s, is %d years old and %d lbs!\n", d->arr[i]->name, d->arr[i]->color, d->arr[i]->age, d->arr[i]->weight); } }
C
# include <stdio.h> main() { int n1; printf("Digite um numero menor que 10: "); scanf("%d",&n1); // Os comandos "if" e "else" equivalem a "se" e "seno". if(n1<10) { printf("Ok!"); }else { printf("O numero digitado eh maior ou igual a 10."); } }
C
#include <locale.h> #include <stdio.h> #include <conio.c> #include <conio.h> #include <ctype.h> #include <string.h> #define LINHA 20 #define COLUNA 60 void preenche(char matriz[][COLUNA], int i, int j, char simb); void printMatriz(char matriz[][COLUNA], int i, int j); int main(void) { setlocale(LC_ALL, "Portuguese"); char matriz[LINHA][COLUNA]; preenche(matriz, LINHA, COLUNA, '*'); gets(matriz[4][7]); printMatriz(matriz, LINHA, COLUNA); //gotoxy(5,10); //puts("ol mundo!"); getch(); return 0; } //====================================================================== void printMatriz(char matriz[][COLUNA], int i, int j) { for(i=0; i<LINHA; i++) { for(j=0; j<COLUNA; j++) { printf("%c",matriz[i][j]); } puts(""); } } //====================================================================== void preenche(char matriz[][COLUNA], int i, int j, char simb) { for(i=0; i<LINHA; i++) { for(j=0; j<COLUNA; j++) { matriz[i][j] = simb; } } }
C
/**/ #include <stdio.h> int main(){ float A, B, C, D, grade; printf("Enter thresholds for A, B, C, D\nin that order, decreasing percentages > "); scanf("%f%f%f%f", &A, &B, &C, &D); printf("Thank you. Now enter student score (percent) >"); scanf("%f", &grade); if (grade >= A) printf("Student has an A grade"); else if (A > grade && grade >= B) printf("Student has an B grade"); else if (B > grade && grade >= C) printf("Student has an C grade"); else if (C > grade && grade >= D) printf("Student has an D grade"); else printf("Student has failed the course"); printf("\n"); return 0; }
C
/******************************************************************************* * [FILE NAME]: adc.h * * [Author]: Hisham Elsayed * * [DATE CREATED]: Oct 6, 2021 * * [DESCRIPTION]: Header file for ADC Driver *******************************************************************************/ #ifndef ADC_H_ #define ADC_H_ #include "std_types.h" /********************************************************* * Types Declaration * *********************************************************/ typedef enum { AREF,AVCC,Reserved,Internal_AREF }ADC_ReferenceVoltage; typedef enum { Div_Factor2,Div_Factorr2,Div_Factor4,Div_Factor8,Div_Factor16,Div_Factor32,Div_Factor64,Div_Factor128 }ADC_Prescaler; typedef struct { ADC_ReferenceVoltage ref_volt; ADC_Prescaler prescaler; }ADC_ConfigType; /******************************************************************************* * Definitions * *******************************************************************************/ #define ADC_MAXIMUM_VALUE 1023 #define ADC_REF_VOLT_VALUE 2.56 /******************************************************************************* * Function Prototypes * *******************************************************************************/ /*************************************************************************************************** * [Function Name]: ADC_init * * [Description]: The Function responsible for initializing the driver and Choosing the Pre-scaler * and the Reference voltage for an ADC Channel. * * [Arguments]: Constant Pointer to structure ADC_ConfigType * * [Returns]: VOID ***************************************************************************************************/ void ADC_init(const ADC_ConfigType * Config_Ptr); /*************************************************************************************************** * [Function Name]: ADC_readChannel * * [Description]: The Function responsible for reading ADC channel * * [Arguments]: unsigned char ADC Channel number * * [Returns]: Returns the converted digital data from data register ***************************************************************************************************/ uint16 ADC_readChannel(uint8 channel_num); #endif /* ADC_H_ */
C
/* * File: main.c * Author: domenicocitera * * Created on 14 de noviembre de 2013, 16:58 */ #include <stdio.h> #include <stdlib.h> #include <math.h> void imatge(double t, double *p); double distancia(double* p0, double* p1); /* * */ int main(int argc, char** argv) { int n, i = 0; double a, b; double p[3]; printf("\n# Dammi n: "); scanf("%d", &n); printf("\n# Dammi gli estremi dell'intervallo a e b: "); scanf("%lf %lf", &a, &b); FILE *fd; /* apre il file in scrittura */ fd = fopen("corba_0.dad", "w"); if (fd == NULL) { perror("Errore in apertura del file"); exit(1); } double pas = (b - a) / n; fprintf(fd, "# Corba: f(t) = cos(2pi*t), sin(2pi*t), t\n"); fprintf(fd, "# x y z\n"); for (i = 0; i < n + 1; i++) { double t = a + i*pas; imatge(t, p); fprintf(fd, "%16.7e %16.7e %16.7e\n", p[0], p[1], p[2]); } fclose(fd); printf("\n# Punti salvati in corba_0.dad.\n" "Visualizzare nel plotter la prima curva? s/n "); char c; scanf("%s", &c); if (c == 's' || c == 'S') system("gnuplot -p -e \"splot 'corba_0.dad' w l\""); return (EXIT_SUCCESS); } void imatge(double t, double *p) { p[0] = cos(2 * M_PI * t); p[1] = sin(2 * M_PI * t); p[2] = t; } double distancia(double* p0, double* p1) { return sqrt(pow(p0[0] - p1[0], 2) + pow(p0[1] - p1[1], 2) + pow(p0[2] - p1[2], 2)); }
C
// // Created by amichai hadad on 15/12/2019. // #include <stdio.h> #include "sortlib.h" #define Len 50 int main(){ int arr[Len]; int temp; for(int i = 0; i<Len;i++){ scanf(" %d",&temp); *(arr+i) = temp; } insertion_sort(arr,Len); for(int y =0;y<Len-1;y++){ printf("%d,", *(arr+y) ); } printf("%d\n" , *(arr+49)); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* print.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tlandema <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/12 14:21:49 by tlandema #+# #+# */ /* Updated: 2019/04/30 04:32:26 by tlandema ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/ft_select.h" #include <sys/ioctl.h> int col_number(void) { struct winsize w; ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); return (w.ws_col); } static void ft_arg_size_max(void) { t_arg *args; int i; int j; args = g_trm->args; i = 0; j = 0; while (args && (args != g_trm->args || i == 0)) { if ((int)ft_strlen(args->name) > g_trm->size_max) g_trm->size_max = ft_strlen(args->name); args = args->right; i = 1; j++; } if ((g_trm->nb_p_l = (col_number() / (g_trm->size_max + 1))) == 0) g_trm->nb_p_l = 1; if (g_trm->nb_p_l > j) g_trm->nb_p_l = j; } static void ft_print_with_pad(char *name, int size, int bol) { int i; int j; j = -1; i = (int)ft_strlen(name); ft_color(name); ft_putstr_fd(tgetstr("me", NULL), STDERR_FILENO); if (bol == 1) ft_putchar_fd('\n', STDERR_FILENO); else { while (i <= size) { ft_putchar_fd(' ', STDERR_FILENO); i++; } } } void ft_print_args(void) { t_arg *args; int i; int j; ft_arg_size_max(); i = 0; j = 0; args = g_trm->args; ft_putstr_fd(tgetstr("cl", NULL), STDERR_FILENO); ft_header(); while (args && (args != g_trm->args || i == 0)) { if (args->selected == 1) ft_putstr_fd(tgetstr("mr", NULL), STDERR_FILENO); if (args == g_trm->the_arg) ft_putstr_fd(tgetstr("us", NULL), STDERR_FILENO); j++; ft_print_with_pad(args->name, g_trm->size_max, j == g_trm->nb_p_l); if (j == g_trm->nb_p_l) j = 0; args = args->right; i = 1; } }
C
/****************************************************************************** *LCD.c -- Inplementation of setting up LCD functions and printf on the LCD display *By Weipeng Tang *FEB 1, 2019 ********************************************************************************/ #ifndef _LCD_H #define _LCD_H #include "stm32f303xe.h" #define MAX_LCD_BUFSIZ 80 #define FIRST_ROW_ADDR 0x00 #define SECOND_ROW_ADDR 0x40 #define LCD_PORT_MAP B #define LCD_E_PIN 12 #define LCD_RS_PIN 13 #define LCD_DB4 4 #define LCD_DB5 5 #define LCD_DB6 6 #define LCD_DB7 7 //LCD port #define LCD_PORT GPIO(LCD_PORT_MAP)->ODR //LCD enable(clock) #define LCD_E_BIT GPIO_ODR_(LCD_E_PIN) //LCD rs bit #define LCD_RS_BIT GPIO_ODR_(LCD_RS_PIN) //data bus #define LCD_BUS_BIT (GPIO_ODR_(LCD_DB4)|GPIO_ODR_(LCD_DB5)|GPIO_ODR_(LCD_DB6)|GPIO_ODR_(LCD_DB7)) //low nybble of a value #define LO_NYBBLE(value) ((value)&0x0F) //high nybble of a value #define HI_NYBBLE(value) (((value)>>4)&0x0F) //set LCD enable high #define LCD_E_HI SET_BITS(LCD_PORT, LCD_E_BIT) //set LCD enable low #define LCD_E_LO CLR_BITS(LCD_PORT, LCD_E_BIT) //write 4 bit value to LCD bus #define LCD_BUS(nybble) FORCE_BITS(LCD_PORT, LCD_BUS_BIT, (nybble)<<4) //set LCD RS to instruction mode #define LCD_RS_IR CLR_BITS(LCD_PORT, LCD_RS_BIT) //set LCD RS to data mode #define LCD_RS_DR SET_BITS(LCD_PORT, LCD_RS_BIT) //functions for LCD void LCDinit(void); void LCDdata(uint8_t value); void LCDcmd(uint8_t command); void LCDclear(void); void LCDputc(char c); void LCDputs(char* string); void LCDprintf(char* fmt, ...); void LCDClearRow1(void); void LCDClearRow2(void); #endif
C
#include "../head.h" double Add(double a, double b); double Sub(double a, double b); double Mul(double a, double b); double Div(double a, double b); double (*func[])(double, double) = {Add, Sub, Mul, Div}; enum op{ ADD = 0, SUB, MUL, DIV }; double Add(double a, double b) { return a+b; } double Sub(double a, double b) { return a-b; } double Mul(double a, double b) { return a*b; } double Div(double a, double b) { if (b == 0) return 0; return a/b; } double main() { double a = 9; double b = 3; printf("add=%ld\n", func[SUB](a, b)); return 0; }
C
#include<stdio.h> #include<malloc.h> struct stack { int data; struct stack * link; }; void push(struct stack ** stack ,int no) { struct stack * n1=(struct stack *)malloc(sizeof(struct stack)); n1->link=*stack; n1->data=no; *stack=n1; } int pop(struct stack ** stack) { int var=(*stack)->data; struct stack * temp=*stack; *stack=(*stack)->link; free(temp); return var; } int isempty(struct stack *stack) { return !stack; } void insertatbottom(struct stack ** stack,int no) { int var; if(isempty(*stack)==1) { push(stack,no); return; } else { var=pop(stack); insertatbottom(stack,no); } push(stack,var); } void reverse(struct stack ** stack) { int var; if(isempty(*stack)==1) { return; } else { // printf("s"); var=pop(stack); reverse(stack); } insertatbottom(stack,var); } void print(struct stack * temp) { while(temp!=NULL) { printf("%d ",temp->data); temp=temp->link; } } int main() { struct stack * stack=NULL; int i=0; for(i=0;i<5;i++) { push(&stack,i*i); } printf("stack before reverion : "); print(stack); reverse(&stack); printf("\nstack after reverion : "); print(stack); }
C
#include <string.h> #include <stdio.h> #include <stdlib.h> #define YEARS 5 #define MONTHS 12 int main(int argc, char const *argv[]) { /** * 统计2010-2014年的降水量初始化数组 * 计算一年的总降水量 * 计算平均的每月降水量 */ const float rain[YEARS][MONTHS] = { {0.2,0.5,0.7,0.1,1.0,0.8,0.1,0.9,0.2,0.7,1.0,0.9}, {0.4,0.7,0.8,0.0,0.6,0.7,0.2,0.9,0.2,0.8,0.4,0.7}, {0.1,0.6,0.4,0.2,0.4,0.6,0.4,0.9,0.8,0.8,0.9,0.1}, {0.3,0.4,0.7,0.5,0.1,0.5,0.1,0.1,0.1,0.0,0.6,0.3}, {0.0,0.4,0.8,0.3,1.0,0.2,0.5,0.5,0.1,0.9,0.5,0.5} }; int year, month; float subtotal, total; for( year = 0, total = 0; year < YEARS; year++) { for( month = 0, subtotal = 0; month < MONTHS; month++) { subtotal += rain[year][month]; } total += subtotal; printf("%5d %15.1f \n", 2010 + year, subtotal); } printf("total: %15.1f \n", total); return 0; }
C
#include <stdio.h> #include <assert.h> #include <stdlib.h> #include <errno.h> #include <string.h> struct Address { int id; int set; char* name; char* email; }; struct Database { int max_data; int max_rows; struct Address* rows; }; struct Connection { FILE* file; struct Database* db; }; void Database_close(struct Connection* conn) { if (conn) { if (conn->file) { fclose(conn->file); } if (conn->db) { free(conn->db); } free(conn); } } void die(const char* message, struct Connection* conn) { if (errno) { perror(message); } else { printf("ERROR: %s\n", message); } Database_close(conn); exit(1); } void Address_print(struct Address* addr) { printf("%d %s %s\n", addr->id, addr->name, addr->email); } void Database_load(struct Connection* conn) { int rc = fread(conn->db, sizeof(struct Database), 1, conn->file); if (rc != 1) { die("Failed to load the database.", conn); } } struct Connection* Database_open(const char* filename, char mode, long max_rows, long max_data) { struct Connection* conn = malloc(sizeof(struct Connection)); if (!conn) die("Memory error", conn); conn->db = malloc(sizeof(struct Database)); if (!conn->db) die("Memory error", conn); conn->db->max_rows = max_rows; conn->db->max_data = max_data; // TODO: Dude, set the number of rows before this, bro! conn->db->rows = malloc(sizeof(struct Address) * conn->db->max_rows); if (!conn->db->rows) die("Memory error", conn); if (mode == 'c') { // open the file for writing only // Since we aren't checking to see if the file exists, we must be creating // it, here. Otherwise, we would need to load it, as below conn->file = fopen(filename, "r+"); } else { // open the file for both reading and writing conn->file = fopen(filename, "r+"); if (conn->file) { Database_load(conn); } } if (!conn->file) { die("Failed to open the file.", conn); } return conn; } void Database_write(struct Connection* conn) { // make sure we are at the beginning of the file, first if (conn->file == NULL) { printf("file pointer is null\n"); } else { printf("file pointer is NOT null\n"); } rewind(conn->file); /* rewind(conn->file); // TODO: This breaks... */ int rc = fwrite(conn->db, sizeof(struct Database), 1, conn->file); if (rc != 1) { die("Failed to write to database.", conn); } rc = fflush(conn->file); if (rc == -1) { die("Could not flush the database.", conn); } } void Database_create(struct Connection *conn) { int i = 0; for (i = 0; i < conn->db->max_rows; i++) { // make a prototype to initialize it struct Address addr = { .id = i, .set = 0 }; // then, just assign it // TODO this assignment below breaks. conn->db->rows[i] = addr; } } void Database_set(struct Connection* conn, int id, const char *name, const char *email) { /* struct Address* addr = &conn->db->rows[id]; */ struct Address* addr = malloc(sizeof(struct Address)); // TODO fix the bug in the line below - causes a segmentation fault conn->db->rows[id] = *addr; if (addr->set) { die("Database address already set. You must delete it before you can set it, again.", conn); } addr->set = 1; // TODO: WARNING: bug, read the "How To Break It" and fix this *addr->name = '\0'; char* res = strncat(addr->name, name, conn->db->max_data - 1); // demonstrate the strncpy bug if (!res) { die("Name copy failed", conn); } *addr->email = '\0'; res = strncat(addr->email, email, conn->db->max_data - 1); if (!res) { die("Email copy failed", conn); } } void Database_get(struct Connection* conn, int id) { struct Address* addr = &conn->db->rows[id]; if (addr->set) { Address_print(addr); } else { die("ID is not set", conn); } } void Database_delete(struct Connection* conn, int id) { struct Address addr = { .id = id, .set = 0 }; conn->db->rows[id] = addr; } void Database_list(struct Connection* conn) { int i = 0; struct Database* db = conn->db; for (i = 0; i < conn->db->max_rows; i++) { struct Address* cur = &db->rows[i]; if (cur->set) { Address_print(cur); } } } int main(int argc, char* argv[]) { if (argc < 5) { die("USAGE: ex177 <dbfile> <max_rows> <max_data> <action> [action params]", NULL); } char* filename = argv[1]; char action = argv[4][0]; int max_rows = atoi(argv[2]); int max_data = atoi(argv[3]); printf("world!\n"); struct Connection* conn = Database_open(filename, action, max_rows, max_data); int id = 0; if (argc > 5) id = atoi(argv[5]); if (id >= max_rows) die("There's not that many records.", conn); switch (action) { case 'c': /* Database_create(conn); */ Database_write(conn); break; case 'g': if (argc != 6) { die("Need an id to get", conn); } Database_get(conn, id); break; case 's': if (argc != 8) { die("Need id, name, and email to set", conn); } Database_set(conn, id, argv[6], argv[7]); Database_write(conn); break; case 'd': if (argc != 6) { die("Need id to delete", conn); } Database_delete(conn, id); Database_write(conn); break; case 'l': Database_list(conn); break; default: die("Invalid action: c=create, g=get, s=set, d=del, l=list", conn); } Database_close(conn); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "trie.h" #include "heap.h" #include "heap.h" #include "hash_table.h" bloom_filter * bloom ; void test_insert_trie(char * sentence) { trie * mytree; mytree = init_trie(); heap* my_heap = heap_create(); int result = insert_ngram(mytree, sentence); assert(result == 1); if(!(sentence == NULL || strcmp(sentence, "")==0)){ assert(hash_search(mytree->children,"hey")!=NULL); } assert(trie_clean(&mytree) == 1); } //init a trie with some ngrams trie* init_test_trie(){ trie * mytree = malloc(sizeof(trie)); heap* top = heap_create(); mytree = init_trie(); // check the capitals char sentence1[]="IS A RED CAR"; int result = insert_ngram(mytree,sentence1); assert(result == 1); char sentence2[]="is a red car"; result = insert_ngram(mytree,sentence2); assert(result == 1); char sentence3[]="Is a Red Car"; result = insert_ngram(mytree,sentence3); assert(result == 1); char search1[]="Is a Red Car"; result_of_search* search_result=search(mytree,search1,top); assert(search_result->num_of_results==1); delete_result(&search_result); char search2[]="iS A rEd car"; search_result=search(mytree,search2,top); assert(search_result->num_of_results==0); delete_result(&search_result); heap_destroy(&top); return mytree; } // check the children tables when reallocing (the children table of is needs one more) void test_realloc(trie* mytree){ int i,result; char* sentence; char* temp; result_of_search* search_result; heap* top = heap_create(); sentence=malloc(sizeof(char)*(NUMBER_OF_CHILDREN+5)); strcpy(sentence,"is "); for( i = 0 ; i <= NUMBER_OF_CHILDREN ; i++ ) { strcat(sentence,"a"); temp=malloc(sizeof(char)*(strlen(sentence)+1)); strcpy(temp,sentence); result = insert_ngram(mytree,temp); free(temp); assert(result == 1); } search_result=search(mytree,sentence,top); assert(search_result->num_of_results==1); delete_result(&search_result); free(sentence); heap_destroy(&top); } //check the delete void test_delete(trie* mytree){ int result; result_of_search* search_result; heap* top = heap_create(); if(NUMBER_OF_CHILDREN==0){ printf("The number of children is 0\n"); assert(NUMBER_OF_CHILDREN>0); } //add the "is" ngram char sentence0[]="is"; result = insert_ngram(mytree,sentence0); assert(result == 1); //check the delete char delete_sentence0[]="is a"; delete_ngram(mytree,delete_sentence0); search_result=search(mytree,delete_sentence0,top); //the results must be 1 because of the "is" ngram and because we deleted "is a" // else it is should be 0 or 2 if the delete is not correct assert(search_result->num_of_results==1); delete_result(&search_result); heap_destroy(&top); } void test_insert_search_delete() { trie* mytree=init_test_trie(); test_realloc(mytree); test_delete(mytree); assert(trie_clean(&mytree)==1); assert(mytree==NULL); } void test_insert_cases() { char sentence1[]= "hey buddy"; test_insert_trie(sentence1); char sentence2[]=""; test_insert_trie(sentence2); char sentence3[]= " hey buddies "; test_insert_trie(sentence3); } void test_heap_inserts(){ heap* my_heap = NULL; my_heap = heap_create(); char a_word[1024]; for (size_t i = 0; i < 1000; i++) { a_word[i]='a'+i%24; a_word[i+1]='\0'; heap_insert(my_heap, a_word); } heap_insert(my_heap, "good thing"); heap_insert(my_heap, "good thing"); heap_insert(my_heap, "good thing"); heap_insert(my_heap, "good"); heap_insert(my_heap, "good"); heap_insert(my_heap, "good"); heap_insert(my_heap, "good"); heap_insert(my_heap, "dog"); heap_insert(my_heap, "dog"); heap_insert(my_heap, "cat"); heap_insert(my_heap, "cat"); heap_insert(my_heap, "wow"); heap_insert(my_heap, "wow"); heap_insert(my_heap, "wow"); heap_insert(my_heap, "wow"); heap_insert(my_heap, "wow"); assert(strcmp(my_heap->root->content,"wow")==0); heap_destroy(&my_heap); } void test_heap_cmp(){ heap_node heap_1,heap_2; heap_1.content=copy_string("a"); heap_1.appeared=0; heap_2.content=copy_string("b"); heap_2.appeared=0; assert(cmp_heap_node(&heap_1, &heap_2)>0); } void is_ok(heap_node* cur_node, int depth){ if(cur_node==NULL){ return ; } heap_node *left = cur_node->left; heap_node *right = cur_node->right; if(left!=NULL){ assert(cmp_heap_node(left, cur_node)<0); is_ok(left,depth+1); } if(right!=NULL){ assert(cmp_heap_node(right, cur_node)<0); is_ok(right,depth+1); } } int test_heap_util(){ heap* my_heap = heap_create(); heap_insert(my_heap, "good thing"); heap_insert(my_heap, "good thing"); heap_insert(my_heap, "good thing"); heap_insert(my_heap, "good"); heap_insert(my_heap, "good"); heap_insert(my_heap, "good"); heap_insert(my_heap, "good"); heap_insert(my_heap, "dog"); heap_insert(my_heap, "dog"); heap_insert(my_heap, "cat"); heap_insert(my_heap, "cat"); heap_insert(my_heap, "wow"); heap_insert(my_heap, "wow"); heap_insert(my_heap, "wow"); heap_insert(my_heap, "wow"); heap_insert(my_heap, "wow"); is_ok(my_heap->root,0); } void test_heap(){ test_heap_cmp(); test_heap_inserts(); assert(test_heap_util()==0); } int main(void) { bloom=bloom_filter_init(); test_insert_cases(); test_insert_search_delete(); test_heap(); bloom_filter_destroy(&bloom); printf("Passed the test!\n"); return 0; }
C
#include <vigenere.h> const char *vgn_crypt(const char *msg, const char *key){ if(!msg || !key) return 0; char *_new = (char *) malloc(strlen(msg)); int x; for(x=0;x<strlen(msg);x++) _new[x] = ((msg[x]+key[x]) % 255)+1; return (const char *) _new; } const char *vgn_decrypt(const char *msg, const char *key){ if(!msg || !key) return 0; char *_new = (char *) malloc(strlen(msg)); int x; for(x=0; x<strlen(msg); x++){ _new[x] = (msg[x] - key[x])-1; _new[x] = (_new[x] < 0) ? 256-_new[x] : _new[x]; } return (const char *) _new; }
C
#include "tictactoe.h" /* returns one of GAME_ACTIVE, GAME_DRAWN * GAME_PLAYER_WON, GAME_PLAYER_LOST */ int evaluate_board( PLAY_MOVE_ARGS ) { int winning_lines[NUM_WINNING_LINES][3][2] = WINNING_LINES; int i, j, x, y, num_computer, num_player, is_on_line = FALSE; int num_available_lines = NUM_WINNING_LINES; int last_available_line = 0; const char *lines_by_cell[BOARD_Y][BOARD_X] = LINES_BY_CELL; const char *cur_line_ptr; /* for evaluating free cells for draws */ for( i=0; i<NUM_WINNING_LINES; i++ ) { num_computer = 0; num_player = 0; for( j=0; j<3; j++ ) { y = winning_lines[i][j][0]; x = winning_lines[i][j][1]; if( board[y][x] == player_mark ) { num_player++; } else if( board[y][x] == computer_mark ) { num_computer++; } } if( num_player == 3) { *game_status_ptr = GAME_PLAYER_WON; sprintf( display_text, "%sYou won!%s (%c%i, %c%i, %c%i)\n" , PLAYER_COLOR , KNRM , 'a' + winning_lines[i][0][1] , 3 - winning_lines[i][0][0] , 'a' + winning_lines[i][1][1] , 3 - winning_lines[i][1][0] , 'a' + winning_lines[i][2][1] , 3 - winning_lines[i][2][0] ); return *game_status_ptr; } else if( num_computer == 3 ) { *game_status_ptr = GAME_PLAYER_LOST; sprintf( display_text, "%sI won!%s (%c%i, %c%i, %c%i)\n" , COMPUTER_COLOR , KNRM , 'a' + winning_lines[i][0][1] , 3 - winning_lines[i][0][0] , 'a' + winning_lines[i][1][1] , 3 - winning_lines[i][1][0] , 'a' + winning_lines[i][2][1] , 3 - winning_lines[i][2][0] ); return *game_status_ptr; } else if( num_computer && num_player ) { num_available_lines--; /* printf( "line %i busted, %i remain\n", i, num_available_lines ); */ } else { /* printf( "line %i available, %i total left\n", i, num_available_lines ); */ last_available_line = i; } } if( num_available_lines == 1 ) { /* check if there are any cells available on other lines: * find all the cells not on last_available_line, and * if any are free, it's not a draw */ for( y=0; y<BOARD_Y; y++ ) { for( x=0; x<BOARD_X; x++ ) { if( board[y][x] == ' ' ) { cur_line_ptr = lines_by_cell[y][x]; is_on_line = FALSE; while( *cur_line_ptr ) { /* if this free cell is on the current line, * it could still be a draw; if we get through * all the lines for this cell, and it's not on * the current line, we know it can't be a draw */ /* hack to convert know numeric char to int */ if( (*cur_line_ptr) - '0' == last_available_line ) { is_on_line = TRUE; break; } cur_line_ptr++; } if( ! is_on_line ) { /* none of this cell's lines are on the last * active line, so this isn't a draw situation */ return GAME_ACTIVE; } } } } } /* if 1 line's available and it didn't break, it's a draw; * if 0 lines are available, it's a draw */ if( num_available_lines <= 1 ) { *game_status_ptr = GAME_DRAWN; sprintf( display_text, "%sDraw!%s\n", KCYN, KNRM ); return *game_status_ptr; } return GAME_ACTIVE; } void set_computer_move( PLAY_MOVE_ARGS, int x, int y, char *computer_move ){ /* output the move coordinates */ sprintf( computer_move, "%c%i", 'a' + x, 3 - y ); printf( "\nMy Move: %s\n", computer_move ); board[y][x] = computer_mark; if( evaluate_board( PLAY_MOVE_CALL ) != GAME_ACTIVE ) { return; } *to_move_ptr = PLAYER_MOVE; } /* returns bool whether a move was made */ int play_first_available( PLAY_MOVE_ARGS, char *computer_move ) { int x, y; /* though it should just be the non-corner edges, * check everything anyway as a fallback */ for( y=0; y<BOARD_Y; y++ ) { for( x=0; x<BOARD_X; x++ ) { if( board[y][x] == ' ' ) { set_computer_move( PLAY_MOVE_CALL, x, y, computer_move ); return TRUE; } } } return FALSE; } /* returns bool whether a move was made */ int play_corner( PLAY_MOVE_ARGS, char *computer_move ) { int corners[4][2] = { {0,0}, {0,2} ,{2,0}, {2,2} }; int x, y, i, num_corners = 4; /* take first available corner */ for( i=0; i<num_corners; i++ ) { x = corners[i][1]; y = corners[i][0]; if( board[y][x] == ' ' ) { set_computer_move( PLAY_MOVE_CALL, x, y, computer_move ); return TRUE; } } return FALSE; } /* returns bool whether a move was made */ int play_center( PLAY_MOVE_ARGS, char *computer_move ) { if( board[1][1] == ' ' ) { set_computer_move( PLAY_MOVE_CALL, 1, 1, computer_move ); return TRUE; } return FALSE; } /* returns bool whether a move was made */ int win_or_block( PLAY_MOVE_ARGS, char *computer_move ) { int winning_lines[NUM_WINNING_LINES][3][2] = WINNING_LINES; int move_one[2], move_two[2], move_three[2]; char pos_one, pos_two, pos_three, mark_looking_for; int i, looking_for; /* iterate over winning lines, the first time we find a winner, play that * then go again, and look for blocking, and play the first of that */ for( looking_for = WINNING; looking_for <= BLOCKING; looking_for++ ) { if( looking_for == WINNING ) { mark_looking_for = computer_mark; } else { mark_looking_for = player_mark; } for( i = 0; i < NUM_WINNING_LINES; i++ ) { move_one[0] = winning_lines[i][0][0]; move_one[1] = winning_lines[i][0][1]; pos_one = board[move_one[0]][move_one[1]]; move_two[0] = winning_lines[i][1][0]; move_two[1] = winning_lines[i][1][1]; pos_two = board[move_two[0]][move_two[1]]; move_three[0] = winning_lines[i][2][0]; move_three[1] = winning_lines[i][2][1]; pos_three = board[move_three[0]][move_three[1]]; /* win or block at pos three */ if( pos_one == mark_looking_for && pos_two == mark_looking_for && pos_three == ' ' ) { set_computer_move( PLAY_MOVE_CALL, move_three[1], move_three[0], computer_move ); return TRUE; } /* win or block at pos two */ if( pos_one == mark_looking_for && pos_two == ' ' && pos_three == mark_looking_for ) { set_computer_move( PLAY_MOVE_CALL, move_two[1], move_two[0], computer_move ); return TRUE; } /* win or block at pos three */ if( pos_one == ' ' && pos_two == mark_looking_for && pos_three == mark_looking_for ) { set_computer_move( PLAY_MOVE_CALL, move_one[1], move_one[0], computer_move ); return TRUE; } } } return FALSE; }
C
// // Queues 1.0 // Implementing a Queue Using an Array #include <stdlib.h> typedef struct { int head, tail; int QA[MaxQ]; } QType, *Queue; Queue initQueue() { Queue qp = (Queue)malloc(sizeof(QType)); qp->head = qp->tail = 0; return qp; } int empty(Queue Q) { return (Q->head == Q->tail); } void enqueue(Queue Q, int n) { if (Q->tail == MaxQ - 1) Q->tail = 0; else ++(Q->tail); if (Q->tail == Q->head) { printf("\nQueue is full\n"); exit(1); } Q->QA[Q->tail] = n; } int dequeue(Queue Q) { if (empty(Q)) { printf("\nAttempt to remove from an empty queue\n"); exit(1); } if (Q->head == MaxQ - 1) Q->head = 0; else ++(Q->head); return Q->QA[Q->head]; }
C
/* ǰ0ȣǸ */ #include <angle.h> int mk_mid = 1500+140; //мֵҲ0ȵֵλus void angle_init() { /* ʱͨ£ ʱ TIMx_CH1 TIMx_CH2 TIMx_CH3 TIMx_CH4 TIM1 PA8 PA9 PA10 PA11 TIM2 PA0 PA1 PA2 PA3 TIM3 PA6 PA7 PB0 PB1 TIM4 PB6 PB7 PB8 PB9 TIM5 PA0 PA1 PA2 PA3 TIM6 - - - - TIM7 - - - - TIM8 PC6 PC7 PC8 PC9 */ /* ʹܶʱʱģ顣 ߼ʱTIM1TIM8ڸʱAPB2ϣͨöʱTIM2~TIM7ڵʱAPB1ϡ ȻͬĶʱܹڲͬAPBϣͨAPBУʱʱӶ72MHzϸԭʼǣ */ RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE); /* öʱʱԴ */ // ʱĬʱͨAPBģﲻҪ /* ʹܽҪΪpwmGPIOʱӣ鵽 */ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); /* ýҪΪpwmŵģʽΪ"츴" */ { GPIO_InitTypeDef temp; temp.GPIO_Speed = GPIO_Speed_50MHz; temp.GPIO_Mode = GPIO_Mode_AF_PP; temp.GPIO_Pin = GPIO_Pin_6; //öӦ GPIO_Init(GPIOB, &temp); } /* öʱԪ */ { TIM_TimeBaseInitTypeDef temp; temp.TIM_Prescaler = 72-1; /* ԤƵĴ[0, 65535]ǸtimAPBƵʶ72MHz72-1õ1MHz 72Mhz/(TIM_Prescaler+1) = CK_CNTʱƵʣTIM_Prescaler = 72MHz/CK_CNT - 1 */ temp.TIM_Period = 20000-1; /* ԶװؼĴ[0, 65535]100-1õ100Ϊڡ ԤƵúüں(1/CK_CNT)ڵ(TIM_Period+1)Ǽڡ*/ //һڹʽ = (TIM_Prescaler+1)*(TIM_Period+1)/72000000λs temp.TIM_CounterMode = TIM_CounterMode_Up; /* ģʽ TIM_CounterMode_Up TIM ϼģʽ TIM_CounterMode_Down TIM ¼ģʽ TIM_CounterMode_CenterAligned1 TIM ģʽ 1 ģʽ TIM_CounterMode_CenterAligned2 TIM ģʽ 2 ģʽ TIM_CounterMode_CenterAligned3 TIM ģʽ 3 ģʽ */ temp.TIM_ClockDivision = TIM_CKD_DIV1; /* Ƶ벶ʱʹá */ TIM_TimeBaseInit(TIM4, &temp); } /* ʼָʱָͨȽϲ */ { TIM_OCInitTypeDef temp; temp.TIM_OCMode = TIM_OCMode_PWM1; //ģʽռձΪ100%ʱ޷ȫĸߵƽһڵĵ͵ƽ temp.TIM_OutputState = TIM_OutputState_Enable; //ʹ temp.TIM_Pulse = mk_mid; //ȽϼĴֵ temp.TIM_OCPolarity = TIM_OCPolarity_High; //ЧƽΪߵƽ TIM_OC1Init(TIM4, &temp); } /* ʹָʱָͨԤװؼĴ */ TIM_OC1PreloadConfig(TIM4, TIM_OCPreload_Enable); /* ʹָʱԶװصԤװؼĴλ */ TIM_ARRPreloadConfig(TIM4, DISABLE); //ENABLE-ȽϼĴֵ޸ĺЧDISABLE-ȽϼĴֵ޸ĺ¸Ч /* ʹܶʱ */ TIM_Cmd(TIM4, ENABLE); } static void tim4_setmk(int mk) //λusΧ0~20000 { TIM_SetCompare1(TIM4, mk); } void angle_setangle(int deg) //ýǶȣλǶȡǰ0Ǹ { #define ANGLE_LIMIT 40 double mkPdeg = 2000/180; //ÿһȽǶȶӦ仯 if(deg>ANGLE_LIMIT) deg = ANGLE_LIMIT; else if(deg < -ANGLE_LIMIT) deg = -ANGLE_LIMIT; tim4_setmk(mk_mid - mkPdeg*deg); }
C
#include "stdio.h" #include "stdlib.h" char board[15][31]={"өөөөөөөөөөөөө", "ĩ", "ĩ", "ĩ", "ĩ", "ĩ", "ĩ", "ĩ", "ĩ", "ĩ", "ĩ", "ĩ", "ĩ", "ĩ", "۩۩۩۩۩۩۩۩۩۩۩۩۩"}; char chess[2][3]={"",""}; char name[4][6]={"1","2","",""}; void PrintBoard() { int i,j; for (i=0; i<15; i++) { printf(" %2d",15-i); for (j=0; j<30; j++) printf("%c",board[i][j]); printf("\n"); } printf(" "); for (i=0; i<15; i++) printf("%c ",'A'+i); printf("\n"); return; } int main() { FILE *fp; int player1,player2,step,i,x,y; if((fp=fopen("Gomoku.log","r"))==NULL) { printf("Cannot Find Log/n"); return 1; } fscanf(fp,"%d,%d,%d\n",&player1,&player2,&step); printf(" Ϣ\n ִ - %s\n ִ - %s\n ʤ - ",name[player1-1],name[player2-1]); if (step%2) printf("%s\n",name[player1-1]); else printf("%s\n",name[player2-1]); printf(" - %d\n\n",step); system("pause"); system("cls"); for (i=0; i<step; i++) { fscanf(fp,"%d,%d",&x,&y); board[x-1][2*y-2]=chess[i%2][0]; board[x-1][2*y-1]=chess[i%2][1]; printf(" - %d -\n %s %d%c\n",i+1,chess[i%2],16-x,'A'+y-1); PrintBoard(); printf(" %s - %s %s - %s\n",name[player1-1],chess[0],name[player2-1],chess[1]); system("pause"); system("cls"); } printf("ļ¼չʾ\n"); fclose(fp); return 0; }
C
#ifndef QUEUE_C #define QUEUE_C #include "queue.h" #include <stdio.h> #include <stdlib.h> #include <string.h> int front; int rear1,rear2; Queuevector * newQueuevector(){ Queuevector * sv = malloc(sizeof(Queuevector)); sv->data = newVector(); sv->enqueue = pushQueuevector; sv->dequeue = popQueuevector; sv->peek = peekQueuevector; sv->clear = clearQueuevector; sv->delete = deleteQueuevector; return sv; } void pushQueuevector(Queuevector * sv, Data d){ sv->data->insert(sv->data,sv->data->current_size, d); } Data popQueuevector(Queuevector * sv){ if(sv->data->current_size == 0){ return (Data){.value=-1}; } else{ Data removed = * (sv->data->read(sv->data,0)); sv->data->remove(sv->data,0); return removed; } } Data peekQueuevector(Queuevector * sv){ if(sv->data->current_size == 0) return (Data){.value=-1}; else{ Data removed = * (sv->data->read(sv->data,0)); return removed; } } void clearQueuevector(Queuevector * sv){ while(sv->data->current_size != 0) sv->dequeue(sv); } void deleteQueuevector(Queuevector * sv){ sv->data->delete(sv->data); free(sv); } Queuelist * newQueuelist(){ Queuelist * ql = malloc(sizeof(Queuelist)); ql->queuelength = 0; ql->data = newList(); ql->enqueue = enqueueList; ql->dequeue = dequeueList; ql->peek = peekQueueList; ql->clear = clearQueueList; ql->delete = deleteQueueList; return ql; } void enqueueList(Queuelist * q, Data d){ int index = 0; q->data->insert(q->data, index, d); q->queuelength++; } Data dequeueList(Queuelist * q){ if(q->queuelength > 0) { Data dequeued = q->data->head->data; q->data->remove(q->data, 0); q->queuelength--; return dequeued; } else { return (Data){.value = -1}; } } Data peekQueueList(Queuelist * q){ return q->data->head->data; } void clearQueueList(Queuelist * q){ while(q->queuelength != 0){ q->data->remove(q->data, 0); q->queuelength--; } } void deleteQueueList(Queuelist * q){ for(int i = 0; i < q->queuelength; i++){ q->data->remove(q->data, i); } q->data->delete(q->data); q->data = NULL; free(q); } #endif
C
#include<stdio.h> void main() { int len,i,j; char s1[20],s2[20]; printf("Enter original string:"); fgets(s1, sizeof(s1), stdin); len = 0; while(s1[len]!='\0') { len++; } for(i=0,j=len-1;i<len;i++,j--) { s2[j] = s1[i]; } s2[len] ='\0'; printf("reverse string: %s\n",s2); }
C
#include "blocks.h" #include "metadata_disk.h" #include "meta.h" #include "list.h" #include <linux/limits.h> #include <inttypes.h> #define CWD_LENGTH 128 char* normalize_path(char* resolved_path, char* cwd); typedef struct stack_node { entry_disk* _entry; unsigned int depth; } stack_node; void tree_print(char *metadata,int info) { list_t *stack; list_create(&stack,sizeof(stack_node),free); dinode_disk* di_n; dentry_disk* d_en; d_en = (dentry_disk*)(metadata + sizeof(dinode_disk)); stack_node *sn = malloc(sizeof(stack_node)); sn->_entry = &(d_en->tuple_entry[0]); sn->depth = 0; list_push(stack,sn); while(list_get_len(stack)) { stack_node cur_node; list_pop(stack,&cur_node); entry_disk *en = cur_node._entry; di_n = (dinode_disk*)(metadata + en->dinode_off); size_t n_dentries = di_n->n_dentries; d_en = (dentry_disk*)((char*)di_n + sizeof(dinode_disk)); unsigned int i; if (!info) { for (i=0;i<cur_node.depth;++i) printf("-------"); printf("%s\n",en->filename); } else { printf("Filename :%s\n",en->filename); printf("Dinode number :%ju\n",(uintmax_t)(di_n->dinode_number)); printf("Permissions :%3o\n",(di_n->permissions)&0777); printf("User Id :%ju\n",(uintmax_t)(di_n->user_id)); printf("Group Id :%ju\n",(uintmax_t)(di_n->group_id)); printf("Time of access :%ju\n",(uintmax_t)(di_n->time_of_access)); printf("\n\n"); } for (i=0;i<n_dentries;++i){ unsigned int j; for (j=0;j<d_en->length;++j) { en = &(d_en->tuple_entry[j]); if (!strcmp(en->filename,".") || !strcmp(en->filename,"..")) continue; stack_node *node = malloc(sizeof(stack_node)); node->_entry = en; node->depth = cur_node.depth + 1; list_push(stack,node); } d_en = (dentry_disk*)((char*)(d_en)+sizeof(dentry_disk)); } } list_destroy(&stack); } int query(char *metadata,char *path) { char *cwd = (char*)malloc(CWD_LENGTH*sizeof(char)); char *current_dir; if(get_current_dir(&cwd,&current_dir) < 0){ free(cwd); return -1; } char *resolved_path = (char*)calloc(PATH_MAX,sizeof(char)); realpath(path, resolved_path); char* normalized_filepath; //!!!!!!!!!carefull to free normalized path!!!!!!!!! normalized_filepath = normalize_path(resolved_path,cwd); free(resolved_path); free(cwd); if(normalized_filepath != NULL){ if(!strcmp(normalized_filepath,"")){ printf("Same directory\n"); } else{ printf("The path in the hierarchy is: %s\n",normalized_filepath); } } else{ printf("Error in normalization of the path\n"); free(normalized_filepath); return 0; } int result = 1; dinode_disk* di_n; dentry_disk* d_en = (dentry_disk*)(metadata + sizeof(dinode_disk)); entry_disk *cur_entry = &(d_en->tuple_entry[0]); char *token; token = strtok(normalized_filepath,"/"); while(token!=NULL) { di_n = (dinode_disk*)(metadata + cur_entry->dinode_off); size_t n_dentries = di_n->n_dentries; d_en = (dentry_disk*)((char*)di_n + sizeof(dinode_disk)); char matched = 0; unsigned int i; for (i=0;i<n_dentries && !matched;++i){ unsigned int j; for (j=0;j<d_en->length && !matched;++j) { cur_entry = &(d_en->tuple_entry[j]); if (!strcmp(token,cur_entry->filename)) matched = 1; } d_en = (dentry_disk*)((char*)d_en +(sizeof(dentry_disk))); } if (!matched){ result = 0; break; } token = strtok(NULL,"/"); } free(normalized_filepath); return result; }
C
#include <iostream> #include <math.h> #include <iomanip> const double a = 1.2; double f(double x) { //The function we are analyzing return tanh(a*x)-x; } double g2(double x) { //Newton-Raphson method return x-((tanh(a*x)-x) / ((a / (cosh(a*x)*cosh(a*x)))-1)); } int main() { double x; int n; std::cout << "x = ? "; std::cin >> x; for (n = 0; n<20; n++) { std::cout << std::setw(4) << n << std::setw(16) << x << std::setw(16) << f(x) << std::endl; //output statement x = g2(x); //changing the value of x to the new value that is closer to the root } } //a = 0.8 has 1 solution at: x = 0 //a = 1.2 has 3 solutions at: x=-0.65857, x=0, x=0.65857
C
# include <stdio.h> # include "c_iraf.h" # include "hstio.h" # include "stis.h" # include "calstis1.h" # include "hstcalerr.h" /* for REF_TOO_SMALL */ # include "stisdef.h" /* This routine finds the bin factors and corner location to use when calling bin2d to extract and bin the appropriate subset of a reference image to match a science image. If the science image has zero offset and is the same size and binning as the reference image, same_size will be set to true; otherwise, the values of rx, ry, x0, y0 will be assigned. Normally the science image (x) will be binned the same or more than the reference image (y); rx and ry will be the bin size of the science image divided by the bin size of the reference image, If the binning of the reference image is greater than the binning of the science image, then status = REF_TOO_SMALL will be returned. In this case, the ratios (rx and ry) of the bin sizes will be the reference image (y) bin size divided by the science image (x) bin size. This is not necessarily an error. The high_res flag will be set to true if the bin size of the reference image is one in the dispersion direction. This is really needed only for MAMA data where the dispersion is high enough that Doppler convolution must be applied to the reference data. Phil Hodge, 1998 Sept 24: rx, ry, x0, y0 were not assigned for the case that the two images are the same size and offset; same_size was not assigned for the case that the reference image is binned more than the science image. */ int FindBin (StisInfo1 *sts, SingleGroup *x, SingleGroup *y, int *same_size, int *high_res, int *rx, int *ry, int *x0, int *y0) { /* arguments: StisInfo1 *sts i: calibration switches and info SingleGroup *x i: science image SingleGroup *y i: reference image int *same_size o: true if zero offset and same size and binning int *high_res o: true if bin size is one in dispersion direction int *rx, *ry o: ratio of bin sizes int *x0, *y0 o: location of start of subimage in ref image */ int status; int sci_bin[2]; /* bin size of science image */ int sci_corner[2]; /* science image corner location */ int ref_bin[2]; /* bin size of reference image */ int ref_corner[2]; /* ref image corner location */ int rsize; /* 1 for CCD, 2 for MAMA */ int cshift[2]; /* shift of sci relative to ref */ int ratiox, ratioy; /* local variables for rx, ry */ int xzero, yzero; /* local variables for x0, y0 */ /* Get bin sizes of science and reference images from headers. */ rsize = (sts->detector == CCD_DETECTOR) ? 1 : 2; if ((status = GetCorner (&x->sci.hdr, rsize, sci_bin, sci_corner))) return (status); if ((status = GetCorner (&y->sci.hdr, rsize, ref_bin, ref_corner))) return (status); /* High-res is really only relevant for the MAMA detectors. */ *high_res = (sts->dispaxis == 1 && ref_bin[0] == 1) || (sts->dispaxis == 2 && ref_bin[1] == 1); if (sci_corner[0] == ref_corner[0] && sci_corner[1] == ref_corner[1] && sci_bin[0] == ref_bin[0] && sci_bin[1] == ref_bin[1] && x->sci.data.nx == y->sci.data.nx && x->sci.data.ny == y->sci.data.ny) { /* We can use the reference image directly, without binning and without extracting a subset. */ *same_size = 1; *rx = 1; *ry = 1; *x0 = 0; *y0 = 0; } else if (ref_bin[0] > sci_bin[0] || ref_bin[1] > sci_bin[1]) { /* Reference image is binned more than the science image. */ *same_size = 0; *rx = ref_bin[0] / sci_bin[0]; *ry = ref_bin[1] / sci_bin[1]; *x0 = (sci_corner[0] - ref_corner[0]) / ref_bin[0]; *y0 = (sci_corner[1] - ref_corner[1]) / ref_bin[1]; return (REF_TOO_SMALL); } else { /* We must bin, extract subset, or both. */ *same_size = 0; /* ratio of bin sizes */ ratiox = sci_bin[0] / ref_bin[0]; ratioy = sci_bin[1] / ref_bin[1]; if (ratiox * ref_bin[0] != sci_bin[0] || ratioy * ref_bin[1] != sci_bin[1]) return (SIZE_MISMATCH); /* cshift is the offset in units of unbinned (or low-res) pixels. Divide by ref_bin to convert to units of pixels in the reference image. */ cshift[0] = sci_corner[0] - ref_corner[0]; cshift[1] = sci_corner[1] - ref_corner[1]; xzero = cshift[0] / ref_bin[0]; yzero = cshift[1] / ref_bin[1]; if (xzero * ref_bin[0] != cshift[0] || yzero * ref_bin[1] != cshift[1]) { printf ( "Warning Subimage offset not divisible by bin size.\n"); } *rx = ratiox; *ry = ratioy; *x0 = xzero; *y0 = yzero; } return (0); }
C
/* * ultraS.c * * Created on: 7. nov 2016 * Author: Y009 */ /** \file ultraS.c ** \brief Documentation for the ultrasonic module. ** ** Describes the workings of the ultrasonic module. ** @startuml {umlFSM.png} ** [*] --> US_IDLE : Power on ** US_IDLE --> US_WORKING : Button press ** US_WORKING --> US_ERROR : Out of range ** US_WORKING --> US_OK : Measurement success ** US_ERROR --> US_OK : Error set ** US_OK --> US_IDLE : Data read ** ** state US_WORKING { ** [*] --> US_DATA_TRUE2 : Begin work ** US_DATA_TRUE2 --> US_DATA_TRUE : Measurement made ** US_DATA_TRUE2 --> US_DATA_FALSEMAX : Over max range ** US_DATA_TRUE2 --> US_DATA_FALSEMIN : Under min range ** US_DATA_TRUE2 --> US_DATA_TRUE : Valid range ** US_DATA_TRUE --> US_DATA_READ : Data read ** US_DATA_FALSEMAX --> US_DATA_READ : Data read ** US_DATA_FALSEMIN --> US_DATA_READ : Data read ** US_DATA_READ --> [*] : Cycle complete ** } ** ** US_IDLE -> [*] : Power off ** @enduml **/ //***** Header Files ********************************************************** #include <driverlib.h> #include "ultraS.h" #include "../MCU/counter.h" #include "../MCU/timer.h" #include "stdio.h" #include "gpio.h" //***** DEFINES *************************************************************** #define MAXDIST 23200 /**< 23200us is 4m. */ #define MINDIST 116 /**< 116us is 2cm. */ #define CMCONST 58 /**< Constant to divide time with to get distance in centimeters. */ #define CYCLE 0xFDE8 /**< Timer size - added to endTime when rollover happens.*/ void resetTimes(); unsigned volatile long long int startTime; /**< Time captured on usmodule's rising edge echo signal.*/ unsigned volatile long long int endTime; /**< Time captured on usmodule's falling edge echo signal. */ unsigned volatile long long int startTimeMult; /**< Insurance variable to insure that startTime and endTime are correct. */ unsigned volatile long long int endTimeMult; /**< Insurance variable to insure that startTime and endTime are correct. */ unsigned volatile long int distance; /**< Distance calculated based on start and end time and it's multipliers */ status usStatus = US_IDLE; /**< Set finite state machine to idle/waiting state. */ dataStatus usDataStatus = US_DATA_FALSE; /**< Set finite state machine to start in false state to insure no false information. */ /*********************************************************/ void ultraS_init() /** Set ultrasonic module to be ready for work. ** ** Set's appropriate FSM states and resets start and end times to 0. **/ { usStatus = US_WORKING; resetTimes(); usStatus = US_IDLE; } /*********************************************************/ void ultraS_sendSignal() /** Send signal to the physical ultrasonic module. ** ** Set's appropriate FSM state. Send's a high signal for required time - 10uS. ** \n Delays system to not send multiple signals at the same time. **/ { usStatus = US_WORKING; gpio_setPinHigh (gpio_PORT_P1, gpio_PIN4); __delay_cycles(160U); /* trigger time */ gpio_setPinLow (gpio_PORT_P1, gpio_PIN4); __delay_cycles(96000U); /* echo wait period */ } /*********************************************************/ void ultraS_prepInfo() /** Calculates measured distance. ** ** Measured distance is calculated as: end time - start time, which is then divided by 58 - constant ** to get the distance in centimeters. ** \n End time is the difference of the end and start time multiplier times the counter size added to ** the measured end time. Start time is just the measured start time. ** \attention Only when rollover happens! ** \attention Adds the entire counter size to endTime to compensate for potential rollover. **/ { endTime += CYCLE * (endTimeMult-startTimeMult); /* Adding entire 16bit counter value to end time to compensate for rollover. */ distance = (endTime - startTime)/CMCONST; if ((endTime - startTime) > MAXDIST){ usDataStatus = US_DATA_FALSEMAX; } else if((endTime - startTime) < MINDIST){ usDataStatus = US_DATA_FALSEMIN; } else{ usDataStatus = US_DATA_TRUE; } } /*********************************************************/ void resetTimes() /** Reset start and end time to 0 to insure proper results. ** \attention Private function. **/ { startTime = 0; /* Setting up for the next measurement. */ endTime = 0; /* Set end time also 0 in case we don't catch interrupt. */ } /*********************************************************/ void ultraS_cyclic() /** Ultrasonic modules main finite state machine. ** ** Controls the work regarding the ultrasonic hardware. Finite state machine to decide state of system. ** \attention US_WORKING state is further controlled by another state machine. **/ { switch(usStatus){ case US_OK: if(usDataStatus == US_DATA_READ){ usStatus = US_IDLE; /* Going back to waiting for work. */ resetTimes(); } break; case US_WORKING: /* Figure out how busy we actually are. / FSM2 */ switch(usDataStatus){ case US_DATA_FALSEMIN: usStatus = US_ERROR; break; case US_DATA_FALSEMAX: usStatus = US_ERROR; break; case US_DATA_TRUE: usStatus = US_OK; break; case US_DATA_TRUE2: ultraS_prepInfo(); break; case US_DATA_FALSE: __no_operation(); break; case US_DATA_READ: __no_operation(); break; } case US_ERROR: /* Let higher level know we're done */ usStatus = US_OK; break; case US_IDLE: /* Waiting for work */ __no_operation(); break; } } /*********************************************************/ unsigned int ultraS_getValidStatus() /** Get ultrasonic modules state. ** ** \return usStatus **/ { return usStatus; } /*********************************************************/ void ultraS_setValidStatus( status validStatus) /**< Status to set */ /** Set ultrasonic modules state. **/ { usStatus = validStatus; } /*********************************************************/ unsigned int ultraS_getDistance() /** Get measured distance. ** ** \return Distance */ { /* In reality distance can not be larger than 2 bytes, hence casting should be fine. */ return distance; } /*********************************************************/ int ultraS_getDataStatus() { /** Get ultrasonic modules workings state. ** ** Get the inner FSM's state. ** \return usDataStatus */ return usDataStatus; } /*********************************************************/ void ultraS_setDataStatus( dataStatus validStatus) /**< Status to set */ /** Set ultrasonic modules workings state. ** ** Set the inner FSM's state. **/ { usDataStatus = validStatus; } /*********************************************************/ #pragma vector=PORT1_VECTOR /*< Interrupt vector pragma for port 1. */ __interrupt void ultraS_ISR ( void) /** Interrupt vector for Port 1. ** ** Is triggered when the hardware ultrasonic module sends back an echo signal. ** \n The rising edge of the echo signal is saved as the starting time and the falling edge as the ending time. **/ { if (gpio_getInterrupt(gpio_PORT_P1, gpio_PIN5)){ if (!startTime){ /* Rising endge. */ startTime = counter_getCountValue(counter_timerBase); startTimeMult = counter_getOverflow(); gpio_setInterruptEdge (gpio_PORT_P1, gpio_PIN5, gpio_HIGH_TO_LOW_TRANSITION); } else if (startTime && !endTime ){ /* Falling edge. */ endTime = counter_getCountValue(counter_timerBase); endTimeMult = counter_getOverflow(); gpio_setInterruptEdge (gpio_PORT_P1, gpio_PIN5, gpio_LOW_TO_HIGH_TRANSITION); usDataStatus = US_DATA_TRUE2; /* In module status. */ } } gpio_clearInterrupt ( gpio_PORT_P1, gpio_PIN5 ); }
C
#include "draw.h" #include <SDL.h> #include "types.h" #include "anim.h" #include "puzzle.h" #define FONT_WIDTH 9 #define FONT_HEIGHT 16 #define TW 64 #define TH 64 #define TIMER_W 7 #define TIMER_H 7 #define EXPLOSION_LEN 500 #define PARTICLE_W 4 #define PARTICLE_H 4 void draw_string(SDL_Renderer *renderer, SDL_Texture *font_tex, const char *string, u32 x, u32 y, u32 scale, u8 r, u8 g, u8 b) { SDL_SetTextureColorMod(font_tex, r, g, b); SDL_Rect src = { 0, 0, FONT_WIDTH, FONT_HEIGHT }; SDL_Rect dst = { x, y, FONT_WIDTH * scale, FONT_HEIGHT * scale }; for (const char *p = string; *p; ++p, dst.x += scale * FONT_WIDTH) { src.x = (((u8)*p) & 0x1F) * FONT_WIDTH; src.y = (((u8)*p) >> 5) * FONT_HEIGHT; SDL_RenderCopy(renderer, font_tex, &src, &dst); } } static f64 dir_to_angle(enum direction dir) { switch (dir) { case DIR_N: return 0.0; case DIR_NE: return 45.0; case DIR_E: return 90.0; case DIR_SE: return 135.0; case DIR_S: return 180.0; case DIR_SW: return 225.0; case DIR_W: return 270.0; case DIR_NW: return 315.0; } printf("Invalid argument to dir_to_angle.\n"); return 0.0; } static s32 lerp(s32 x1, s32 x2, f32 v) { f32 fx1 = (float)x1, fx2 = (float)x2; return (s32)(fx1 + (fx2 - fx1) * v); } #define PI 3.1415926535f #define MIN_SPEED 30.0f #define MAX_SPEED 60.0f static void add_explosion(struct explosion_queue *explosion_queue, s32 x, s32 y) { // TODO -- check we're not exceeding the max explosions? struct explosion *exp = &explosion_queue->explosions[explosion_queue->num_explosions++]; exp->x = x; exp->y = y; exp->ticks = EXPLOSION_LEN; struct particle *part = exp->particles; for (u32 i = 0; i < EXPLOSION_PARTICLES; ++i, ++part) { f32 theta = ((f32)rand() / (f32)RAND_MAX) * 2.0f * PI; part->dx = cos(theta); part->dy = sin(theta); part->speed = MIN_SPEED + (((f32)rand() / (f32)RAND_MAX) * MAX_SPEED - MIN_SPEED); } } void draw_puzzle(SDL_Renderer *renderer, SDL_Texture *sprite_tex, struct puzzle *puzzle, struct anim_queue *anim_queue, struct explosion_queue *explosion_queue, u32 animating, f32 anim_fac, u32 frame_time) { // draw background { u32 w = puzzle->width, h = puzzle->height; enum tile *p = puzzle->tiles; SDL_Rect src = { 0, 0, TW, TH }, dst = { 0, 0, TW, TH }; for (u32 j = 0; j < h; ++j) { for (u32 i = 0; i < w; ++i, ++p) { dst.x = i * TW; dst.y = j * TH; u8 k = (i + j) % 2 ? 16 : 0; switch (*p) { case TILE_GOAL: src.x = 2 * TW; src.y = 2 * TH; SDL_SetTextureColorMod(sprite_tex, 64 + k, 64 + k, 64 + k); SDL_RenderCopy(renderer, sprite_tex, &src, &dst); break; case TILE_EMPTY: src.x = 0; src.y = 2 * TH; SDL_SetTextureColorMod(sprite_tex, 48 + k, 48 + k, 48 + k); SDL_RenderCopy(renderer, sprite_tex, &src, &dst); break; case TILE_EMITTER: src.x = TW; src.y = 2 * TH; SDL_SetTextureColorMod(sprite_tex, 48 + k, 48 + k, 48 + k); SDL_RenderCopy(renderer, sprite_tex, &src, &dst); break; case TILE_WALL: SDL_SetRenderDrawColor(renderer, 64 + k, 32 + k, 32 + k, 255); SDL_RenderFillRect(renderer, &dst); break; } } } } SDL_SetTextureColorMod(sprite_tex, 255, 255, 255); // draw emitter timers { u32 num_emitters = puzzle->num_emitters; struct emitter *p = puzzle->emitters; for (u32 i = 0; i < num_emitters; ++i, ++p) { u32 len = p->num_steps; SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_Rect r = { p->x * TW + (TW - (len * TIMER_W)) / 2, p->y * TH + (TH - 2*TIMER_H), len * TIMER_W, TIMER_H }; SDL_RenderFillRect(renderer, &r); ++r.x; ++r.y; r.w = TIMER_W - 2; r.h = TIMER_H - 2; for (u32 j = 0; j < len; ++j) { u8 color = (p->step == j + 1) ? 255 : 128; if (!animating) { color = (p->step % p->num_steps == j) ? 255 : 128; } if ((1 << j) & p->fire_mask) { SDL_SetRenderDrawColor(renderer, 0, color, color, 255); } else { SDL_SetRenderDrawColor(renderer, color, 0, color, 255); } SDL_RenderFillRect(renderer, &r); r.x += TIMER_W; } } } // draw player { SDL_Rect src = { 2*TW, 0, TW, TH }, dst = { 0, 0, TW, TH }; if (animating) { u32 len = anim_queue->len; struct anim *p = anim_queue->queue; for (u32 i = 0; i < len; ++i, ++p) { if (p->type == ANIMATION_PLAYER_MOVE) { dst.x = lerp(p->player_move.sx * TW, p->player_move.ex * TW, anim_fac); dst.y = lerp(p->player_move.sy * TW, p->player_move.ey * TW, anim_fac); SDL_RenderCopy(renderer, sprite_tex, &src, &dst); goto drawn_player; } } } dst.x = puzzle->player.x * TW; dst.y = puzzle->player.y * TH; SDL_RenderCopy(renderer, sprite_tex, &src, &dst); } drawn_player: // draw bullets { SDL_Rect src = { 0, 0, TW, TH }, dst = { 0, 0, TW, TH }; SDL_Point center = { TW / 2, TH / 2 }; if (animating) { u32 len = anim_queue->len; struct anim *p = anim_queue->queue; for (u32 i = 0; i < len; ++i, ++p) { switch (p->type) { case ANIMATION_BULLET_MOVE: { f64 angle = dir_to_angle(p->bullet_move.dir); dst.x = lerp(p->bullet_move.sx * TW, p->bullet_move.ex * TW, anim_fac); dst.y = lerp(p->bullet_move.sy * TH, p->bullet_move.ey * TH, anim_fac); SDL_RenderCopyEx(renderer, sprite_tex, &src, &dst, angle, &center, SDL_FLIP_NONE); } break; case ANIMATION_BULLET_EXPLODE_EDGE: if (anim_fac > 0.5f) { if (!p->bullet_explode.added_explosion) { s32 x = (p->bullet_explode.sx + p->bullet_explode.ex + 1) * TW / 2; s32 y = (p->bullet_explode.sy + p->bullet_explode.ey + 1) * TH / 2; p->bullet_explode.added_explosion = 1; add_explosion(explosion_queue, x, y); } } else { f64 angle = dir_to_angle(p->bullet_explode.dir); dst.x = lerp(p->bullet_explode.sx * TW, p->bullet_explode.ex * TW, anim_fac); dst.y = lerp(p->bullet_explode.sy * TH, p->bullet_explode.ey * TH, anim_fac); SDL_RenderCopyEx(renderer, sprite_tex, &src, &dst, angle, &center, SDL_FLIP_NONE); } break; case ANIMATION_BULLET_EXPLODE_MID: if (anim_fac > 0.9f) { if (!p->bullet_explode.added_explosion) { p->bullet_explode.added_explosion = 1; add_explosion(explosion_queue, p->bullet_explode.ex * TW + TW/2, p->bullet_explode.ey * TH + TH/2); } } else { f64 angle = dir_to_angle(p->bullet_explode.dir); dst.x = lerp(p->bullet_explode.sx * TW, p->bullet_explode.ex * TW, anim_fac); dst.y = lerp(p->bullet_explode.sy * TH, p->bullet_explode.ey * TH, anim_fac); SDL_RenderCopyEx(renderer, sprite_tex, &src, &dst, angle, &center, SDL_FLIP_NONE); } break; case ANIMATION_PLAYER_MOVE: break; } } } else { u32 num_bullets = puzzle->num_bullets; struct bullet *b = puzzle->bullets; for (u32 i = 0; i < num_bullets; ++i, ++b) { f64 angle = dir_to_angle(b->dir); dst.x = b->x * TW; dst.y = b->y * TH; SDL_RenderCopyEx(renderer, sprite_tex, &src, &dst, angle, &center, SDL_FLIP_NONE); } } } // draw explosions { SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND); SDL_Rect r = { 0, 0, PARTICLE_W, PARTICLE_H }; u32 num_explosions = explosion_queue->num_explosions; u32 i = 0; while (i < num_explosions) { struct explosion *exp = &explosion_queue->explosions[i]; if (frame_time > exp->ticks) { *exp = explosion_queue->explosions[--num_explosions]; continue; } ++i; exp->ticks -= frame_time; f32 exp_time = 1.0f - ((f32)exp->ticks / (f32)EXPLOSION_LEN); u32 x = exp->x, y = exp->y; struct particle *p = exp->particles; for (u32 j = 0; j < EXPLOSION_PARTICLES; ++j, ++p) { r.x = x + (s32)(p->dx * p->speed * exp_time); r.y = y + (s32)(p->dy * p->speed * exp_time); SDL_SetRenderDrawColor(renderer, 255, 255, 255, (s8)(192.0f * (1.0f - exp_time))); SDL_RenderFillRect(renderer, &r); } } explosion_queue->num_explosions = num_explosions; } // draw emitter bases { u32 num_emitters = puzzle->num_emitters; struct emitter *p = puzzle->emitters; SDL_Rect src = { 0, TH, TW, TH }, dst = { 0, 0, TW, TH }; for (u32 i = 0; i < num_emitters; ++i, ++p) { dst.x = p->x * TW; dst.y = p->y * TH; switch (p->type) { case EMITTER_FIXED: src.x = 0; break; case EMITTER_CLOCKWISE: src.x = 2 * TW; break; case EMITTER_COUNTER_CLOCKWISE: src.x = TW; break; } SDL_RenderCopy(renderer, sprite_tex, &src, &dst); } } // draw emitter cannons { u32 num_emitters = puzzle->num_emitters; struct emitter *p = puzzle->emitters; SDL_Rect src = { TW, 0, TW, TH }, dst = { 0, 0, TW, TH }; SDL_Point center = { TW / 2, TH / 2 }; for (u32 i = 0; i < num_emitters; ++i, ++p) { dst.x = p->x * TW; dst.y = p->y * TH; f32 offset; switch (p->type) { case EMITTER_FIXED: offset = 0.0f; break; case EMITTER_CLOCKWISE: if (anim_fac < 0.5f) { offset = 0.0f; } else { offset = 2.0f * (anim_fac - 0.5f); } break; case EMITTER_COUNTER_CLOCKWISE: if (anim_fac < 0.5f) { offset = 0.0f; } else { offset = -2.0f * (anim_fac - 0.5f); } break; } for (u32 d = 0; d < NUM_DIRS; ++d) { if (p->dir_mask & (1 << d)) { SDL_RenderCopyEx(renderer, sprite_tex, &src, &dst, 45.0 * ((f64)d + offset), &center, SDL_FLIP_NONE); } } } } }
C
#include<stdio.h> #include<stdlib.h> void swap(int *a,int *b) { int temp=*a; *a=*b; *b=temp; } int partition(int *a,int low,int high) { int ele=a[high]; int i=low-1,j=low; for(j=low;j<high;j++) { if(a[j]<=ele) { i=i+1; swap(&a[j],&a[i]); } } swap(&a[i+1],&a[high]); return i+1; } void qksort(int *a,int low,int high) { if(low<high) { int p=partition(a,low,high); qksort(a,low,p-1); qksort(a,p+1,high); } } main() { int n; printf("Please enter the number of elements: "); scanf("%d",&n); int *a=(int *)malloc(n*sizeof(int)); printf("\nPlease enter the elements:"); int i; for(i=0;i<n;i++) { scanf("%d",&a[i]); } qksort(a,0,n-1); printf("The array after sorting is as follows:\n"); for(i=0;i<n;i++) printf("%d ",a[i]); }
C
/* 文件:message.c 作者:李培生 内容: 控制消息有无的全局变量; 消息字符串的全局变量; 设置显示内容的函数的声明; 消息显示的函数的声明。 */ #include <string.h> #include "imgui.h" #include "graphics.h" #include "extgraph.h" #include "message.h" //全局变量 int message_content = MESSAGE_NO; //消息有无 char message[100] = "\0"; //消息字符串 //设置消息显示内容 void SetMessage(int set_message_content, char* set_message) { message_content = set_message_content; if (set_message != NULL) strcpy(message, set_message); } //显示消息 void DrawMessage(void) { drawRectangle(-0.01, 0, 10.01, 0.21, 0); if (message_content == MESSAGE_YES) { drawLabel(0.05, 0.05, message); } }
C
#include "libmx.h" void mx_pop_back(t_list **list) { if (*list) { t_list *node = *list; t_list *last_node = NULL; while (node->next->next) { node = node->next; } last_node = node->next; node->next = NULL; last_node->data = NULL; last_node->next = NULL; free(last_node); } }
C
#include <math.h> double get_sd(double data[], int n){ int i; double mean=0.0, sum_deviation=0.0; if(n==1) return 0.0; for(i=0; i<n; i++){ mean+=data[i]; } mean=mean/n; for(i=0; i<n;++i){ sum_deviation+=(data[i]-mean)*(data[i]-mean); } return sqrt(sum_deviation/n); } double get_avg(double data[], int n){ int i; double avg=0.0; if(n==0) return 0; for(i=0; i<n; i++) avg+=data[i]; return avg/n; } const char *get_protocol_name(int code){ if(code==1) return "ICMP"; if(code==17) return "UDP"; return "Code not supported"; }
C
#include "holberton.h" /** * set_string - sets the value of a pointer to a char. * @s- pointer value be set * @c- to char value to be set * Return: Always 0. */ void set_string(char **s, char *to) { *s = to; }
C
#include <stdio.h> void d2b(int); int main() { int n; scanf("%d", &n); d2b(n); printf("\n"); return 1; } void d2b(int n) { if(n==0) return; d2b(n/2); printf("%d", n%2); }
C
#include <stdio.h> #include <stdlib.h> #define UPPER_LIMIT 1000 #define LOWER_LIMIT 1 #define BITUP 10 #define BITDOWN(X) ((X)/(10)) #define REMAINDER(X) ((X)%(10)) int BitUp(int zegop); int main(void){ int testcase=0; int idx=0; //INPUT scanf("%d", &testcase); int num1[testcase]; int num2[testcase]; int sum[testcase]; for(idx=0; idx<testcase; idx++){ scanf("%d %d", &num1[idx], &num2[idx]); sum[idx] = 0; } if(testcase<LOWER_LIMIT || testcase>UPPER_LIMIT){ exit(-1); } //PLUS for(idx=0; idx<testcase; idx++){ num1[idx] += num2[idx]; int count = 0; while ( !(BITDOWN(num1[idx])== 0 && REMAINDER(num1[idx])==1 ) ){ //num1이 더이상 BITDOWN 안되면서 1이 남을 때까지 반복 switch(REMAINDER(num1[idx])){ case 0: count++; break; case 1: sum[idx] += BitUp(count++); break; case 2: count++; num1[idx] += BITUP; break; case 3: sum[idx] += BitUp(count++); num1[idx] += BITUP; break; } num1[idx] = BITDOWN(num1[idx]); } sum[idx] += BitUp(count++); } for(idx=0; idx<testcase; idx++){ printf("%d\n", sum[idx]); } } int BitUp(int zegop){ if(zegop==0){ return 1; }else{ return 10 * BitUp(zegop-1); } } //시간초과
C
#include <stdlib.h> size_t maxSeq(int* array, size_t n) { int myIt; int numSeq = 1; int tmpSeq; if (n == 0) { return 0; } tmpSeq = 1; for (size_t i = 1; i < n; i++) { myIt = array[i-1]; if (myIt < array[i]) { tmpSeq++; if (numSeq < tmpSeq) { numSeq = tmpSeq; } } else { tmpSeq = 1; } } return numSeq; }
C
#ifndef PRINT_TREE_H #define PRINT_TREE_H struct block { struct node * stmt; struct node * block; }; struct assign { struct node * lhs; struct node * expr; }; struct unop { char * op; struct node * oprnd; }; struct biop { char * op; struct node * oprnd1; struct node * oprnd2; }; struct ident { char * ident; }; struct literal { char * literal; }; #define BLOCK 0 #define ASSIGN 1 #define UNOP 2 #define BIOP 3 #define IDENT 4 #define LITERAL 5 struct node { float pos[2]; int type; union { struct block block; struct assign assign; struct unop unop; struct biop biop; struct ident ident; struct literal literal; }; }; void PrintAST(struct node * tree, int indent); void PrintSVGAST(struct node * tree); #endif
C
/* * cw6-z2.c * * Created: 10/24/2020 11:47:54 AM * Author : Kamil Cinner */ #define LeftButton 0 #define RightButton 3 #include <avr/io.h> #include <avr/interrupt.h> #include <stdbool.h> volatile bool timerStarted = false; volatile bool keyLocks[] = { false, false, false, false }; volatile uint8_t keyPressedCount = 0; void clearKeyLocks() { uint8_t i = 0; while (i < 4) { keyLocks[i] = false; i++; } } void lockKey(uint8_t index) { keyLocks[index] = true; } void unlockKey(uint8_t index) { keyLocks[index] = false; } bool isKeyLocked(uint8_t index) { return keyLocks[index]; } ISR(TIMER0_COMP_vect) { // Stop timer TCCR0 &= 0b11111000; timerStarted = false; uint8_t col = 0; uint8_t control; while (col < 4) { control = (PINB | 0b11110000) ^ (0b00010000 << col); PORTB = control; asm volatile ("nop"); control = PINB; if ((control & 0b00000001) != 0b00000001) { if (!isKeyLocked(col)) { lockKey(col); PORTA = (control >> 4); } } else { unlockKey(col); } col++; } } void keypadScan() { //PORTB |= 0b11110001; PORTB = 0xff; asm volatile ("nop"); PORTB &= 0b00001111; asm volatile ("nop"); if ((PINB & 0b00000001) == 0b00000001) { clearKeyLocks(); asm volatile ("nop"); return; } // Start timer TCCR0 = (TCCR0 & 0b11111101) | 0b00000101; timerStarted = true; } void Timer0Init() { OCR0 = 1; TCCR0 = (TCCR0 & 0b10111111) | 0b00001000; TIMSK |= 0b00000010; } int main(void) { //DDRB |= 0b11110000; //DDRB &= 0b11111110; DDRB = 0xf0; DDRA = 0b11111111; PORTA = 0b00000000; Timer0Init(); sei(); while (1) { if (!timerStarted) { keypadScan(); } } }
C
#include <netinet/in.h> #include <strings.h> #include <string.h> #include <arpa/inet.h> #include <stdio.h> #include <sys/socket.h> #include <unistd.h> #include <sys/errno.h> #include <stdlib.h> int main(int argc, char** argv) { int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); struct sockaddr_in cliaddr; bzero(&cliaddr, sizeof(cliaddr)); cliaddr.sin_family = AF_INET; cliaddr.sin_port = htons(10002); cliaddr.sin_addr.s_addr = inet_addr("10.0.1.100"); bind(sockfd, (struct sockaddr *)&cliaddr, sizeof(struct sockaddr)); struct sockaddr_in servaddr; bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(80); servaddr.sin_addr.s_addr = inet_addr("184.72.104.217"); connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)); char data[1024]; memset(data, 0, sizeof(data)); char* httpget = "GET / HTTP/1.1\r\n\r\n"; write(sockfd, httpget, strlen(httpget)); read(sockfd, data, sizeof(data)); printf("%s", data); return 0; }