language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
//通过函数实现查找一串数组中的最大数以及它的个数,要求最大数用return返回,个数用形参带回 #include <stdio.h> int main() { int a[10] = {2, 3, 3, 2, 4, 5, 6, 6, 6, 6}; int num; int max; max = f(a, 10, &num); printf("max: %d\nnum: %d\n", max, num); return 0; } int f(int a[], int n, int *num) { int max = a[0]; int i = 0; *num = 1; for(i = 1; i < n; i ++) { if(a[i] > max) { max = a[i]; *num = 1; } else if(a[i] == max) (*num) ++; } return max; }
C
/* Extensive TWI/I2C EEPROM Library - for 24LCxxx devices version: 0.4.2 target device: Microchip 24LC256 or similar compatibility: designed with Arduino Due -> Ver. 0.4.2: New license. author: Dennis Schweer (Inglorious Engineer) Copyright (c) 2015 Dennis Schweer license: The MIT License (MIT) (see LICENSE.txt) Overview: -bytewise reading/writing void extEEPROMwrite(int chip_address, int address, byte value); byte extEEPROMread(int chip_address, int address); -pagewise reading/writing void extEEPROMwritePage(int chip_address, int startaddress, byte* data_origin_array, int amount_of_transfered_bytes) (!!!ATTENTION!!!: Limited to 30 Bytes only!) void extEEPROMreadPage(int chip_address, int startaddress, byte* data_target_array, int amount_of_transfered_bytes) (!!!ATTENTION!!!: Limited to 32 Bytes only) Do not care about their size, just save them! -read/write complete 32bit integers [Requires four bytes of your EEPROM.] void extEEPROMwriteInt(int chip_address, int address, int data_to_be_stored) int extEEPROMreadInt(int chip_address, int address) -read/write your 10/12 bit sensor values (e.g., ADC values) [Requires two bytes of your EEPROM.] void extEEPROMwriteSensor(int chip_address, int addresse, int data_to_be_stored) int extEEPROMreadSensor(int chip_address, int addresse) NEW IN VERSION 0.4: Now all functions include a device address parameter, allowing you to use two or more external EEPROM chips simultaneously on a single bus. Just choose the right device addresses and feet them into the library functions! NEW IN VERSION 0.4.1: My library is designed with an Arduino Due, but now everything is successfully tested to work on Arduino Uno R3 and Arduino Micro as well! Since all current Arduinos are based on either ATmega328 (e.g., Uno), ATmega32U4 (e.g., Micro/ Leonardo/Esplora) or ATSAM3X8E (Due), my library should work with ALL official or 1:1-compatible boards. !!! Unfortunately, Arduino Due appears to be the only device with the ability to handle 32 bit integers. Hence none of my "writeInt" / "readInt" functions run on 8-bit Arduinos !!! Planned for future releases: -erase byte -erase page -erase complete EEPROM -read/write with autocorrection of "startaddress"-value */ #include "Arduino.h" //========FUNCTIONS========================= ///////////////// WRITE ///////////////////// void extEEPROMwrite(int EEPROM_addr, int addr, byte data) { Wire.beginTransmission(EEPROM_addr); //Start transmission to EEPROM Wire.write(highByte(addr)); // send high byte of address Wire.write(lowByte(addr)); // send low byte of address Wire.write((byte) data); // send data Wire.endTransmission(true); // stop transmitting delay(6); // wait for a successful write } void extEEPROMwritePage(int EEPROM_addr, int addr, byte* data_origin, int amount) { Wire.beginTransmission(EEPROM_addr); //Start transmission to EEPROM Wire.write(highByte(addr)); // send high byte of address Wire.write(lowByte(addr)); // send low byte of address for(int i = 0; i<amount; i++) //write array into EEPROM { Wire.write((byte) data_origin[i]); } Wire.endTransmission(true); // stop transmitting delay(6); // wait for a successful write } void extEEPROMwriteInt(int EEPROM_addr, int addr, int data) { Wire.beginTransmission(EEPROM_addr); //Start transmission to EEPROM Wire.write(highByte(addr)); // send high byte of address Wire.write(lowByte(addr)); // send low byte of address Wire.write(lowByte(data)); // send lowest byte of 32 bit integer data = data >> 8; Wire.write(lowByte(data)); // send 2nd lowest byte of 32 bit integer data = data >> 8; Wire.write(lowByte(data)); // send 2nd highest byte of 32 bit integer data = data >> 8; Wire.write(lowByte(data)); // send highest byte of 32 bit integer Wire.endTransmission(true); // stop transmitting delay(6); // wait for a successful write } void extEEPROMwriteSensor(int EEPROM_addr, int addr, int data) { Wire.beginTransmission(EEPROM_addr); //Start transmission to EEPROM Wire.write(highByte(addr)); // send high byte of address Wire.write(lowByte(addr)); // send low byte of address Wire.write(lowByte(data)); // send low byte of 12 bit integer data = data >> 8; Wire.write(lowByte(data)); // send high byte of 12 bit integer Wire.endTransmission(true); // stop transmitting delay(6); // wait for a successful write } ///////////////// READ ///////////////////// byte extEEPROMread(int EEPROM_addr, int addr) { Wire.beginTransmission(EEPROM_addr); //Start transmission to EEPROM Wire.write(highByte(addr)); // send high byte of address Wire.write(lowByte(addr)); // send low byte of address Wire.endTransmission(true); // stop transmitting Wire.requestFrom(EEPROM_addr, 0x01, true); // request 1 byte form the device attached to EEPROM_addr byte data_out = 64; // read that byte while(Wire.available() == 0) {} // wait for data data_out = Wire.read(); //read single byte return data_out; } void extEEPROMreadPage(int EEPROM_addr, int addr, byte* data_target, int amount) { Wire.beginTransmission(EEPROM_addr); //Start transmission to EEPROM Wire.write(highByte(addr)); // send high byte of address Wire.write(lowByte(addr)); // send low byte of address Wire.endTransmission(true); // stop transmitting Wire.requestFrom(EEPROM_addr, amount, true); // request 1 byte form the device attached to EEPROM_addr // read that byte while(Wire.available() == 0) {} // wait for data for(int i = 0; i<amount; i++) //write data into array { data_target[i] = Wire.read(); } } int extEEPROMreadInt(int EEPROM_addr, int addr) { Wire.beginTransmission(EEPROM_addr); //Start transmission to EEPROM Wire.write(highByte(addr)); // send high byte of address Wire.write(lowByte(addr)); // send low byte of address Wire.endTransmission(true); // stop transmitting Wire.requestFrom(EEPROM_addr, 0x04, true); // request 1 byte form the device attached to EEPROM_addr int data_out = 0xDEADBEEF; int temp = 0xDEADBEEF; // read that byte while(Wire.available() == 0) {} // wait for data data_out = Wire.read(); //read single byte //reconstruct value temp = Wire.read(); temp = temp << 8; data_out = data_out | temp; temp = Wire.read(); temp = temp << 16; data_out = data_out | temp; temp = Wire.read(); temp = temp << 24; data_out = data_out | temp; return data_out; } int extEEPROMreadSensor(int EEPROM_addr, int addr) { Wire.beginTransmission(EEPROM_addr); //Start transmission to EEPROM Wire.write(highByte(addr)); // send high byte of address Wire.write(lowByte(addr)); // send low byte of address Wire.endTransmission(true); // stop transmitting Wire.requestFrom(EEPROM_addr, 0x04, true); // request 1 byte form the device attached to EEPROM_addr int data_out = 0xDEAD; int temp = 0xBEEF; // read that byte while(Wire.available() == 0) {} // wait for data data_out = Wire.read(); //read single byte //reconstruct value temp = Wire.read(); temp = temp << 8; data_out = data_out | temp; return data_out; }
C
#include<stdio.h> int main() {int n; scanf("%f",&n); if(n>=90) printf("A"); else if(n<=89&&n>=80) printf("B"); else if(n<=79&&n>=70) printf("C"); else if(n<=69&&n>=60) printf("D"); else if(n<60) printf("E"); return 0; }
C
/** * strings.c * Project IFJ19 * * Březina Jindřich ([email protected]) * Gumančík Pavol ([email protected]) * Kotáb Dominik ([email protected]) * Moravčík Tomáš ([email protected]) * * Brief: operations for strings * */ #define ALLOC_ADD 10 #include "error.h" #include "strings.h" #include <stddef.h> #include <malloc.h> #include <string.h> void stringInit(smartString *str) { str->string = NULL; str->length = str->allocatedSize = 0; } void stringFree(smartString *str) { free(str->string); str->length = str->allocatedSize = 0; } void stringClear(smartString *str) { for(int i = 0; i < str->length; i++) { str->string[i] = '\0'; } str->length = 0; } int stringAddChar(smartString *str, char c) { if (str->length + 1 >= str->allocatedSize) { if ((str->string = (char *) realloc(str->string, str->allocatedSize + ALLOC_ADD)) == NULL) { return INTERN_ERR; } str->allocatedSize += ALLOC_ADD; } str->string[str->length] = c; if (c != '\0') { str->length++; } str->string[str->length] = '\0'; return OK; } int stringAddString(smartString *str, char* c) { if (str->length == 0) { stringInit(str); } for (unsigned int i = 0; i < strlen(c); i++) { stringAddChar(str, c[i]); } //OwO return OK; } int stringIsKeyword(smartString *str) { char *keywords[] = {"def\0", "else\0", "if\0", "None\0", "pass\0", "return\0", "while\0"}; for (unsigned int i = 0; i < (sizeof(keywords) / sizeof(keywords[0])); i++) { if (strcmp(keywords[i], str->string) == 0) return i; //ano je } return -1; //ne neni }
C
/** * Filename: fig7-16_pr_rlimits.c * Author: csbonkers * Contact: [email protected] * Date: 4/23/21 * Description: * 获取并打印进程的当前资源限制 */ #include "apue.h" #include "sys/resource.h" #define doit(name) pr_rlimits(#name, name) static void pr_rlimits(const char *rname, int rtype); int main(int argc, char *argv[]) { printf("%-24s\t%10s\t%10s\n", "resource name", "soft-limit", "hard-limit"); #ifdef RLIMIT_AS doit(RLIMIT_AS); #endif doit(RLIMIT_CORE); doit(RLIMIT_CPU); doit(RLIMIT_DATA); doit(RLIMIT_FSIZE); #ifdef RLIMIT_MEMLOCK doit(RLIMIT_MEMLOCK); #endif #ifdef RLIMIT_MSGQUEUE doit(RLIMIT_MSGQUEUE); #endif #ifdef RLIMIT_NICE doit(RLIMIT_NICE); #endif doit(RLIMIT_NOFILE); #ifdef RLIMIT_NPROC doit(RLIMIT_NPROC); #endif #ifdef RLIMIT_NPTS doit(RLIMIT_NPTS); #endif #ifdef RLIMIT_RSS doit(RLIMIT_RSS); #endif #ifdef RLIMIT_SBSIZE doit(RLIMIT_SBSIZE); #endif #ifdef RLIMIT_SIGPENDING doit(RLIMIT_SIGPENDING); #endif doit(RLIMIT_STACK); #ifdef RLIMIT_SWAP doit(RLIMIT_SWAP); #endif #ifdef RLIMIT_VMEM doit(RLIMIT_VMEM); #endif return 0; } void pr_rlimits(const char *rname, int rtype) { struct rlimit rlimittmp; if (getrlimit(rtype, &rlimittmp) < 0) { err_sys("getrlimit error for %s", rname); } printf("%-24s\t", rname); if (rlimittmp.rlim_cur == RLIM_INFINITY) { printf("%10s\t", "(infinite) "); } else { printf("%10lu\t", rlimittmp.rlim_cur); } if (rlimittmp.rlim_cur == RLIM_INFINITY) { printf("%10s", "(infinite) "); } else { printf("%10lu ", rlimittmp.rlim_cur); } printf("\n"); }
C
/** Sample program to read and count all the characters on standard input. */ #include <stdio.h> #include <stdlib.h> int main() { int ccount = 0; // Keep reading until we hit the EOF. int ch; while ( ( ch = getchar() ) != EOF ) ccount++; // Report how many characters we found. printf( "%d\n", ccount ); // Better than just returning zero. return EXIT_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> int main() { // --- 1 int t1[] = {1, 2, 3}; for (int i=0; i<3; i++) { printf("%p ", &t1[i]); } printf("\n"); // --- 1 // --- 2 int t2[3]; for (int i=0; i<3; i++) { printf("%p ", &t2[i]); } printf("\n"); // --- 2 return 0; }
C
typedef struct list { struct list * prev; struct list * next; } *list; #define struct_from_list(l, s, f) struct_from_field(l, s, f) #define list_foreach(l, e) \ for (list __next, e = list_begin(l); __next = e->next, e != list_end(l); e = __next) #define list_foreach_reverse(l, e) \ for (list __next, e = (l)->prev; __next = e->prev, e != (l); e = __next) static inline void list_init(struct list * head) { head->prev = head->next = head; } static inline void list_init_member(struct list * p) { p->prev = p->next = 0; } static inline boolean list_empty(struct list * head) { #ifndef KLIB assert(((head->next == head) ^ (head->prev == head)) == 0); #endif return (head->next == head); } /* a singular list is a list containing a single element */ static inline boolean list_singular(struct list *head) { return (head->next != head) && (head->next == head->prev); } /* XXX fix, this isn't used right */ static inline struct list * list_get_next(struct list * head) { return head->next == head ? 0 : head->next; } static inline void list_delete(struct list * p) { #ifndef KLIB assert(p->prev && p->next); #endif p->prev->next = p->next; p->next->prev = p->prev; p->prev = p->next = 0; } static inline boolean list_inserted(struct list * p) { return p->next != 0; } static inline void list_insert_after(struct list * pos, struct list * new) { new->prev = pos; new->next = pos->next; pos->next->prev = new; pos->next = new; } static inline void list_insert_before(struct list * pos, struct list * new) { new->prev = pos->prev; new->next = pos; pos->prev->next = new; pos->prev = new; } static inline void list_replace(struct list *old, struct list *new) { new->next = old->next; new->next->prev = new; new->prev = old->prev; new->prev->next = new; } static inline struct list *list_begin(struct list *head) { return head->next; } static inline struct list *list_end(struct list *head) { return head; } static inline void list_push_back(struct list *list, struct list *elem) { list_insert_before(list_end(list), elem); } static inline struct list *list_pop_back(struct list *list) { struct list *back = list_end(list)->prev; list_delete(back); return back; } static inline boolean list_find(struct list *head, struct list *elem) { list_foreach(head, e) { if (e == elem) return true; } return false; } /* Move all elements from source list to destination list. */ static inline void list_move(struct list *dest, struct list *src) { if (list_empty(src)) { list_init(dest); return; } list_replace(src, dest); list_init(src); /* make it an empty list */ }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* custom_split.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: bwan-nan <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/25 13:46:56 by bwan-nan #+# #+# */ /* Updated: 2019/07/31 12:54:56 by pimichau ### ########.fr */ /* */ /* ************************************************************************** */ #include "asm.h" static int update_count(char c, int *count, int *len) { if (c == ',' || c == '%') { *len = 0; *count += (c == '%' && *len) || c == ',' ? 1 : 0; } else if (c == '#' || c == ';') return (1); else if (++(*len) == 1) (*count)++; return (0); } static int count_params(char **tab) { int i; int j; int count; int len; count = 0; len = 0; i = 0; while (tab[i]) { j = 0; while (tab[i][j]) { if (update_count(tab[i][j], &count, &len)) return (count); j++; } i++; len = 0; } return (count); } static int update_tab(char **param, char *str, int *i, int len) { if (len == 0 && str[*i] == ',') { if (!(*param = ft_strdup(","))) return (0); } else { if (!(*param = ft_strsub(str, *i, len))) return (0); *i += len - 1; } return (1); } static int add_word(char **tab, char **param_tab , int *word_index, int params_count) { char *str; int i; int len; str = *tab; i = 0; while (str && str[i]) { len = 0; while (str[i + len] && ((!ft_strchr(",;#%", str[i + len]) && len != 0) || (!ft_strchr(",;#", str[i + len]) && len == 0))) len++; if (!update_tab(&param_tab[(*word_index)++], str, &i, len)) return (0); if (*word_index == params_count) return (1); i++; } if (tab && tab[0] && tab[1]) return (add_word(tab + 1, param_tab, word_index, params_count)); return (1); } char **custom_split(char **tab) { int len; char **param_tab; int word_index; len = count_params(tab); word_index = 0; param_tab = NULL; if (!(param_tab = (char **)malloc(sizeof(char *) * (len + 1)))) return (NULL); param_tab[len] = 0; if (!add_word(tab, param_tab, &word_index, len)) { ft_freetab(param_tab); return (NULL); } return (param_tab); }
C
#include "main.h" /** * print_rev- function that prints a string, in reverse, followed by a new line * @s: pointer to string * Return: print to string in reverse to stdout */ void print_rev(char *s) { s += _strlen(s) - 1; for (; *s; s--) _putchar(*(s)); _putchar(10); } /** * _strlen- function that returns the length of a string. * @s: pointer to string * Return: length of the string */ int _strlen(char *s) { int i; for (i = 0; *(s); s++, i++) ; return (i); }
C
#define _XOPEN_SOURCE 700 #define _REENTRANT #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char *argv[]) { char buf; if (argc != 2) { printf("Nombre d'argument incorrect\n"); return EXIT_FAILURE; } int fd; fd = open(argv[1], O_WRONLY); while (read(STDOUT_FILENO, &buf, 1) > 0) { write(fd, &buf, 1); } }
C
#include <stdio.h> int a = 2; void count(int b, int c) { int m; static int n = 4; a = a + 1; m = a + b; n = n + c; printf("%d,%d\n", m, n); } void main() { int b = 1, c = 2; { int a = 3, c = 4; count(a, c); } count(b, c); }
C
#include <stdio.h> #include "holberton.h" /** * helper - finds input from n * @bc: check against base case * * @n: given num to be squared * * Description: helper function for sqrt recursion * Return: natural sqrt */ int helper(int n, int bc) { if (n * n == bc) return (n); if (n * n > bc) return (-1); return (helper(n + 1, bc)); } /** * _sqrt_recursion - returns the natural sqrt * @n: given number * * Description: function mimics sqrt command - recursively * * Return: sqrt or -1 if no natural sqrt */ int _sqrt_recursion(int n) { return (helper(1, n)); }
C
#include "wrflash.h" #include "delay.h" #include "uart.h" void ONCHIP_FLASH_Unlock(void) { FLASH->KEYR = FLASH_KEY1; //д. FLASH->KEYR = FLASH_KEY2; } //flash void ONCHIP_FLASH_Lock(void) { FLASH->CR |= 1 << 7; // } //õFLASH״̬ u8 ONCHIP_FLASH_GetStatus(void) { u32 res; res = FLASH->SR; if(res & (1 << 0))return 1; //æ else if(res & (1 << 2))return 2; //̴ else if(res & (1 << 4))return 3; //д return 0; // } //ȴ //time:Ҫʱij //ֵ:״̬. u8 ONCHIP_FLASH_WaitDone(u16 time) { u8 res; do { res = ONCHIP_FLASH_GetStatus(); if(res != 1)break; //æ,ȴ,ֱ˳. delay_us(1); time--; } while(time); if(time == 0)res = 0xff; //TIMEOUT return res; } //ҳ //paddr:ҳַ //ֵ:ִ u8 ONCHIP_FLASH_ErasePage(u32 paddr) { u8 res = 0; res = ONCHIP_FLASH_WaitDone(0X5FFF); //ȴϴβ,>20ms if(res == 0) { FLASH->CR |= 1 << 1; //ҳ FLASH->AR = paddr; //ҳַ FLASH->CR |= 1 << 6; //ʼ res = ONCHIP_FLASH_WaitDone(0X5FFF); //ȴ,>20ms if(res != 1) //æ { FLASH->CR &= ~(1 << 1); //ҳ־. } } return res; } //FLASHַָд //faddr:ַָ(˵ַΪ2ı!!) //dat:Ҫд //ֵ:д u8 ONCHIP_FLASH_WriteHalfWord(u32 faddr, u16 dat) { u8 res; res = ONCHIP_FLASH_WaitDone(0XFF); if(res == 0) //OK { FLASH->CR |= 1 << 0; //ʹ *(vu16*)faddr = dat; //д res = ONCHIP_FLASH_WaitDone(0XFF); //ȴ if(res != 1) //ɹ { FLASH->CR &= ~(1 << 0); //PGλ. } } return res; } //ȡַָİ(16λ) //faddr:ַ //ֵ:Ӧ. u16 ONCHIP_FLASH_ReadHalfWord(u32 faddr) { return *(vu16*)faddr; } #if ONCHIP_FLASH_WREN //ʹд //д //WriteAddr:ʼַ //pBuffer:ָ //NumToWrite:(16λ) void ONCHIP_FLASH_Write_NoCheck(u32 WriteAddr, u16 *pBuffer, u16 NumToWrite) { u16 i; for(i = 0; i < NumToWrite; i++) { ONCHIP_FLASH_WriteHalfWord(WriteAddr, pBuffer[i]); WriteAddr += 2; //ַ2. } } //ַָʼдָȵ //WriteAddr:ʼַ(˵ַΪ2ı!!) //pBuffer:ָ //NumToWrite:(16λ)(Ҫд16λݵĸ.) #if ONCHIP_FLASH_SIZE<256 #define ONCHIP_SECTOR_SIZE 1024 //ֽ #else #define ONCHIP_SECTOR_SIZE 2048 #endif u16 ONCHIP_FLASH_BUF[ONCHIP_SECTOR_SIZE / 2]; //2Kֽ void ONCHIP_FLASH_Write(u32 WriteAddr, u16 *pBuffer, u16 NumToWrite) { u32 secpos; //ַ u16 secoff; //ƫƵַ(16λּ) u16 secremain; //ʣַ(16λּ) u16 i; u32 offaddr; //ȥ0X08000000ĵַ if(WriteAddr < ONCHIP_FLASH_BASE || (WriteAddr >= (ONCHIP_FLASH_BASE + 1024 * ONCHIP_FLASH_SIZE)))return; //Ƿַ ONCHIP_FLASH_Unlock(); // offaddr = WriteAddr - ONCHIP_FLASH_BASE; //ʵƫƵַ. secpos = offaddr / ONCHIP_SECTOR_SIZE; //ַ 0~127 for ONCHIP_32F103RBT6 secoff = (offaddr % ONCHIP_SECTOR_SIZE) / 2; //ڵƫ(2ֽΪλ.) secremain = ONCHIP_SECTOR_SIZE / 2 - secoff; //ʣռС if(NumToWrite <= secremain)secremain = NumToWrite; //ڸΧ while(1) { ONCHIP_FLASH_Read(secpos * ONCHIP_SECTOR_SIZE + ONCHIP_FLASH_BASE, ONCHIP_FLASH_BUF, ONCHIP_SECTOR_SIZE / 2); // for(i = 0; i < secremain; i++) //У { if(ONCHIP_FLASH_BUF[secoff + i] != 0XFFFF)break; //Ҫ } if(i < secremain) //Ҫ { ONCHIP_FLASH_ErasePage(secpos * ONCHIP_SECTOR_SIZE + ONCHIP_FLASH_BASE); // for(i = 0; i < secremain; i++) // { ONCHIP_FLASH_BUF[i + secoff] = pBuffer[i]; } ONCHIP_FLASH_Write_NoCheck(secpos * ONCHIP_SECTOR_SIZE + ONCHIP_FLASH_BASE, ONCHIP_FLASH_BUF, ONCHIP_SECTOR_SIZE / 2); //д } else ONCHIP_FLASH_Write_NoCheck(WriteAddr, pBuffer, secremain); //дѾ˵,ֱдʣ. if(NumToWrite == secremain)break; //д else//дδ { secpos++; //ַ1 secoff = 0; //ƫλΪ0 pBuffer += secremain; //ָƫ WriteAddr += secremain * 2; //дַƫ(16λݵַ,Ҫ*2) NumToWrite -= secremain; //ֽ(16λ)ݼ if(NumToWrite > (ONCHIP_SECTOR_SIZE / 2))secremain = ONCHIP_SECTOR_SIZE / 2; //һд else secremain = NumToWrite; //һд } }; ONCHIP_FLASH_Lock();// } #endif //ַָʼָȵ //ReadAddr:ʼַ //pBuffer:ָ //NumToWrite:(16λ) void ONCHIP_FLASH_Read(u32 ReadAddr, u16 *pBuffer, u16 NumToRead) { u16 i; for(i = 0; i < NumToRead; i++) { pBuffer[i] = ONCHIP_FLASH_ReadHalfWord(ReadAddr); //ȡ2ֽ. ReadAddr += 2; //ƫ2ֽ. } } ///////////////////////////////////////////////////////////////////////////////////// //WriteAddr:ʼַ //WriteData:Ҫд void Test_Write(u32 WriteAddr, u16 WriteData) { ONCHIP_FLASH_Write(WriteAddr, &WriteData, 1); //дһ }
C
#include<stdio.h> float somatorio(int m, float v[]){ int i; float s =0.0F; for(i=0;i<m;i++) s += v[i]; return s; } int main (void) { float v[] = {2.0, 3.0, 4.0}; float s = somatorio(3,v); printf("somatorio=%.1f, media=%.1f",s,s/3); return 0; }
C
/* drawcosandline.c cos(x) & f(x)=45*(y-1)+31 */ #include <stdio.h> #include <math.h> int main(int argc, char const *argv[]) { double y; int x,m,n,yy; for (yy = 0; yy <= 20; yy++) { y = 0.1*yy; m = acos(1-y)*10; n = 45*(y-1)+31; for (x = 0; x <= 62; x++) if (x==m&&x==n) printf("+"); else if(x==n)printf("+"); else if(x==m||x==62-m)printf("*"); else printf(" "); printf("\n" ); } return 0; }
C
#pragma once typedef struct _CC_TREE { int Value; struct _CC_TREE *Left; struct _CC_TREE *Right; int Height; int FirstNode; } CC_TREE; int TreeCreate(CC_TREE **Tree); int TreeDestroy(CC_TREE **Tree); //todo free la toate int TreeInsert(CC_TREE *Tree, int Value); int TreeRemove(CC_TREE *Tree, int Value); int TreeContains(CC_TREE *Tree, int Value); int TreeGetCount(CC_TREE *Tree); int TreeGetHeight(CC_TREE *Tree); int TreeClear(CC_TREE *Tree); int TreeGetNthPreorder(CC_TREE *Tree, int Index, int *Value); int TreeGetNthInorder(CC_TREE *Tree, int Index, int *Value); int TreeGetNthPostorder(CC_TREE *Tree, int Index, int *Value);
C
/*----------------------------------------------------------------------- Creator : Morris chiou Sensor : light sensor File Name : EXAMPLE_TSL2561.c Function : EXAMPLE_TSL2561 Create Date : 2017/11/01 ---------------------------------------------------------------------- */ #include <mega32a.h> #include <stdio.h> #include <delay.h> #include <math.h> #include <alcd.h> #include <i2c.h> #include <datatype_Layer.h> #include <swi2c_Layer.h> #include <SENSOR_TSL2561.h> void EXAMPLE_TSL2561(void); void EXAMPLE_TSL2561(void) { CHAR8S status = 0; CHAR8U id = 0; INT16U light_data[2]={0}; INT32U get_lux_value=0; INT32U lcd_char_data[5]={0}; i2c_stop_hang(); /* get the TSL2561 id */ status = TSL2561_GET_ID(&id); if(status !=0) { printf("TSL2561 read ID fail\r\n"); } else { printf("TSL2561 ID =0x%x\r\n",id); } /* initial TSL2561 */ status = TSL2561_SET_INITIAL(); if(status !=0) { printf("TSL2561 initial fail\r\n"); } else { printf("TSL2561 initial success \r\n",id); } while(1) { /* wait data ok */ delay_ms(101); /*NOMINAL INTEGRATION TIME : 101mS */ status = TSL2561_GET_DATA(&light_data[0]); if(status !=0) { printf("get TSL2561 data fail\r\n"); } /* calculate the raw data to light data */ TSL2561_GET_CALCULATE_DATA(light_data[0],light_data[1],&get_lux_value); printf("TSL2561 lux = %ld \r\n",get_lux_value); /* Display Lux */ { /* Display Lux */ lcd_char_data[0] = (INT32U)(get_lux_value/10000)%10; lcd_char_data[1] = (INT32U)(get_lux_value/1000)%10; lcd_char_data[2] = (INT32U)(get_lux_value/100)%10; lcd_char_data[3] = (INT32U)(get_lux_value/10)%10; lcd_char_data[4] = (INT32U)(get_lux_value)%10; } /* SHOW Lux */ lcd_gotoxy(0,0); lcd_putsf("Lux:"); /* show Temperautre data on LCD */ lcd_putchar(48+lcd_char_data[0]); lcd_putchar(48+lcd_char_data[1]); lcd_putchar(48+lcd_char_data[2]); lcd_putchar(48+lcd_char_data[3]); lcd_putchar(48+lcd_char_data[4]); lcd_putsf(" lx"); /* --------- Temperature bolck --------- */ /* --------- Show ID bolck --------- */ /* SHOW ID */ lcd_gotoxy(0,3); lcd_putsf("TSL2561"); /* --------- Show ID bolck --------- */ } }
C
#include"myheader23.h" int main() { int choice, n, i, j; int arr[MAXSIZE]; n = MAXSIZE; printf("Enter the elements of an array:- \n"); for(i=0; i<n; i++) { scanf("%d",&arr[i]); } printf("\nYou can sort an array using following techniques:- \n"); again: printf("1.- BUBBLE SORT\n 2.- INSERTION SORT \n 3.- SELECTION SORT \n 4.- SHELL SORT \n 5.- QUICK SORT \n 6.- MERGE SORT\n 7.- EXIT\n"); printf("\nSelect one option- "); scanf("%d",&choice); switch(choice) { case 1: BubbleSort(arr,n); display(arr,n); break; case 2: InsertionSort(arr,n); display(arr,n); break; case 3: SelectionSort(arr,n); display(arr,n); break; case 4: ShellSort(arr,n); display(arr,n); break; case 5: QuickSort(arr,0,n-1); display(arr,n); break; case 6: MergeSort(arr,0,n); display(arr,n); break; case 7: exit(1); break; default: printf("Wrong Choice\n"); } printf("\nWant to opt more options?\nIf yes press 1 ortherwise press 0\n"); scanf("%d",&j); while(1 == j) { goto again; } }
C
//___________________________________________________________________ VFAT DIRECTORY //________________________________________________________ DESCRIPTION /** * @file vfat_directory.h * @brief Provides tools helping in the task * of extracting information from a directory. * @Author Hugo Bonnome, Arthur Passuello */ #ifndef VFAT_DIRECTORY_H #define VFAT_DIRECTORY_H #include <fuse.h> //________________________________________________________ DECLARATIONS /** * @brief A fat32 direntry (short) */ struct fat32_direntry { /* 0*/ union { struct { char name[8]; char ext[3]; }; char nameext[11]; }; /*11*/ uint8_t attr; /*12*/ uint8_t res; /*13*/ uint8_t ctime_ms; /*14*/ uint16_t ctime_time; /*16*/ uint16_t ctime_date; /*18*/ uint16_t atime_date; /*20*/ uint16_t cluster_hi; /*22*/ uint16_t mtime_time; /*24*/ uint16_t mtime_date; /*26*/ uint16_t cluster_lo; /*28*/ uint32_t size; } __attribute__ ((__packed__)); #define VFAT_ATTR_DIR 0x10 #define VFAT_ATTR_LFN 0xf #define VFAT_ATTR_INVAL (0x80|0x40|0x08) /** * @brief A fat32 direntry (long) */ struct fat32_direntry_long { /* 0*/ uint8_t seq; /* 1*/ uint16_t name1[5]; /*11*/ uint8_t attr; /*12*/ uint8_t type; /*13*/ uint8_t csum; /*14*/ uint16_t name2[6]; /*26*/ uint16_t reserved2; /*28*/ uint16_t name3[2]; } __attribute__ ((__packed__)); #define VFAT_LFN_SEQ_START 0x40 #define VFAT_LFN_SEQ_DELETED 0x80 #define VFAT_LFN_SEQ_MASK 0x3f /** * @brief A search entry used to querry a file or * a subfolder in a given folder. */ struct vfat_search_data { const char* name; uint32_t cluster_id_current; uint32_t cluster_id_found; int found; struct stat* st; }; //________________________________________________________ PUBLIC FUNCTIONS /** * @param first_cluster The cluster identifier related to the first * cluster of a directory. * @param callback A function (void*, const char*,const struct stat *, void*) => int * @param callbackdata A pointer to something * @return A boolean answering : is error during the process ? * @author Hugo Bonnome */ int vfat_readdir(uint32_t first_cluster, fuse_fill_dir_t callback, void *callbackdata); /** * @param data A pointer to a vfat_search_data(request). * @param name The file name of a file tested where we're currently looking. * @param st A pointer to a struct stat that contains informations about the file tested * @param offs The offset of the file tested in the current directory (in bytes) * @return A boolean answering : is the request equals to the tested file ? * @author Arthur Passuello */ int vfat_search_entry(void *data, const char *name, const struct stat *st, off_t offs); /** * @param path The path to a requested file * @param st A pointer to a stat that will contains informations of the request. * @return A boolean answering : is st correctly loaded (~search succeed) ? * @author Hugo Bonnome */ int vfat_resolve(const char *path, struct stat *st); #endif
C
/* * Copyright (C) Igor Sysoev * Copyright (C) Nginx, Inc. */ #include <ngx_config.h> #include <ngx_core.h> /* 基本hash 的查找*/ void * ngx_hash_find(ngx_hash_t *hash, ngx_uint_t key, u_char *name, size_t len) { ngx_uint_t i; ngx_hash_elt_t *elt; #if 0 ngx_log_error(NGX_LOG_ALERT, ngx_cycle->log, 0, "hf:\"%*s\"", len, name); #endif // 这里计算该key会在哪一个桶中 elt = hash->buckets[key % hash->size]; if (elt == NULL) { return NULL; } /*每个bucket的最后一个元素为void*, 所以while的终止条件就是elt->value == NULL */ while (elt->value) { if (len != (size_t) elt->len) { goto next; } // ngx_strncmp 这个使用一个函数多好的 for (i = 0; i < len; i++) { if (name[i] != elt->name[i]) { goto next; } } return elt->value; next: /* * 这里的地址偏移到下一个ngx_hash_elt_t结构 * * 其实每个bucket就是一段bucket_size长度的连续内存空间 * * 这里存放的都是冲突元素 */ elt = (ngx_hash_elt_t *) ngx_align_ptr(&elt->name[0] + elt->len, sizeof(void *)); continue; } return NULL; } /* * 功能:在前置通配符哈希表中,查找key对应的value值 * * 参数: @name 关键字key * @len 关键字对应的长度 * * return : 返回key(server name)对应的value, 一般这个value为用户配置 * * * 实现过程: 创建通配符哈希表时,采用递归的方式创建哈希表。而查询过程也是一样,递归查询 * 函数ngx_hash_find_wc_head用来在前置通配符哈希表中查找到key对应的value值 * * * */ void * ngx_hash_find_wc_head(ngx_hash_wildcard_t *hwc, u_char *name, size_t len) { void *value; ngx_uint_t i, n, key; #if 0 ngx_log_error(NGX_LOG_ALERT, ngx_cycle->log, 0, "wch:\"%*s\"", len, name); #endif n = len; while (n) { if (name[n - 1] == '.') { break; } n--; } key = 0; for (i = n; i < len; i++) { key = ngx_hash(key, name[i]); } #if 0 ngx_log_error(NGX_LOG_ALERT, ngx_cycle->log, 0, "key:\"%ui\"", key); #endif /* * 参考: https://blog.csdn.net/apelife/article/details/53106140 * * 1. 查找这个单词是否在哈希表中存在 * 2. 如果在哈希表中查找到key,则返回value值 * 3. 这里返回的value值有可能是最终关键字*.baidu.com.cn对应的value * 4. 也可能是指向下一个子哈希表的指针 * * */ value = ngx_hash_find(&hwc->hash, key, &name[n], len - n); #if 0 ngx_log_error(NGX_LOG_ALERT, ngx_cycle->log, 0, "value:\"%p\"", value); #endif if (value) { /* * the 2 low bits of value have the special meaning: * 00 - value is data pointer for both "example.com" * and "*.example.com"; * 01 - value is data pointer for "*.example.com" only; * 10 - value is pointer to wildcard hash allowing * both "example.com" and "*.example.com"; * 11 - value is pointer to wildcard hash allowing * "*.example.com" only. */ if ((uintptr_t) value & 2) { if (n == 0) { /* "example.com" */ if ((uintptr_t) value & 1) { return NULL; } hwc = (ngx_hash_wildcard_t *) ((uintptr_t) value & (uintptr_t) ~3); return hwc->value; } hwc = (ngx_hash_wildcard_t *) ((uintptr_t) value & (uintptr_t) ~3); value = ngx_hash_find_wc_head(hwc, name, n - 1); if (value) { return value; } return hwc->value; } if ((uintptr_t) value & 1) { if (n == 0) { /* "example.com" */ return NULL; } return (void *) ((uintptr_t) value & (uintptr_t) ~3); } return value; } return hwc->value; } void * ngx_hash_find_wc_tail(ngx_hash_wildcard_t *hwc, u_char *name, size_t len) { void *value; ngx_uint_t i, key; #if 0 ngx_log_error(NGX_LOG_ALERT, ngx_cycle->log, 0, "wct:\"%*s\"", len, name); #endif key = 0; for (i = 0; i < len; i++) { if (name[i] == '.') { break; } key = ngx_hash(key, name[i]); } if (i == len) { return NULL; } #if 0 ngx_log_error(NGX_LOG_ALERT, ngx_cycle->log, 0, "key:\"%ui\"", key); #endif value = ngx_hash_find(&hwc->hash, key, name, i); #if 0 ngx_log_error(NGX_LOG_ALERT, ngx_cycle->log, 0, "value:\"%p\"", value); #endif if (value) { /* * the 2 low bits of value have the special meaning: * 00 - value is data pointer; * 11 - value is pointer to wildcard hash allowing "example.*". */ if ((uintptr_t) value & 2) { i++; hwc = (ngx_hash_wildcard_t *) ((uintptr_t) value & (uintptr_t) ~3); value = ngx_hash_find_wc_tail(hwc, &name[i], len - i); if (value) { return value; } return hwc->value; } return value; } return hwc->value; } void * ngx_hash_find_combined(ngx_hash_combined_t *hash, ngx_uint_t key, u_char *name, size_t len) { void *value; if (hash->hash.buckets) { value = ngx_hash_find(&hash->hash, key, name, len); if (value) { return value; } } if (len == 0) { return NULL; } if (hash->wc_head && hash->wc_head->hash.buckets) { value = ngx_hash_find_wc_head(hash->wc_head, name, len); if (value) { return value; } } if (hash->wc_tail && hash->wc_tail->hash.buckets) { value = ngx_hash_find_wc_tail(hash->wc_tail, name, len); if (value) { return value; } } return NULL; } #define NGX_HASH_ELT_SIZE(name) \ (sizeof(void *) + ngx_align((name)->key.len + 2, sizeof(void *))) ngx_int_t ngx_hash_init(ngx_hash_init_t *hinit, ngx_hash_key_t *names, ngx_uint_t nelts) { u_char *elts; size_t len; u_short *test; ngx_uint_t i, n, key, size, start, bucket_size; ngx_hash_elt_t *elt, **buckets; if (hinit->max_size == 0) { ngx_log_error(NGX_LOG_EMERG, hinit->pool->log, 0, "could not build %s, you should " "increase %s_max_size: %i", hinit->name, hinit->name, hinit->max_size); return NGX_ERROR; } for (n = 0; n < nelts; n++) { /* * 每个桶至少能放下一个元素 * * sizeof(void *) 是桶的结束位置 * */ if (hinit->bucket_size < NGX_HASH_ELT_SIZE(&names[n]) + sizeof(void *)) { ngx_log_error(NGX_LOG_EMERG, hinit->pool->log, 0, "could not build %s, you should " "increase %s_bucket_size: %i", hinit->name, hinit->name, hinit->bucket_size); return NGX_ERROR; } } test = ngx_alloc(hinit->max_size * sizeof(u_short), hinit->pool->log); if (test == NULL) { return NGX_ERROR; } /* * sizeof(void *) 是桶的结束标志 * * hinit->bucket_size - sizeof(void *)才是桶使用的实际大小空间 * * */ bucket_size = hinit->bucket_size - sizeof(void *); /* * bucket_size / (2 * sizeof(void *) 计算一个桶内,最大含有多少个元素 * * nelts / (bucket_size / (2 * sizeof(void *))) 这么多元素总共需要多少个桶, nelts是实际的元素个数 * * start ? start : 1 至少保证有一个通 * */ start = nelts / (bucket_size / (2 * sizeof(void *))); start = start ? start : 1; /* * 这里是一个经验值,如果元素个数很多,初始值就把桶的数量设置多一点 * * */ if (hinit->max_size > 10000 && nelts && hinit->max_size / nelts < 100) { start = hinit->max_size - 1000; } for (size = start; size <= hinit->max_size; size++) { ngx_memzero(test, size * sizeof(u_short)); for (n = 0; n < nelts; n++) { if (names[n].key.data == NULL) { continue; } key = names[n].key_hash % size; /* * test[key] 放着hash冲突的元素,不断变长 * * */ test[key] = (u_short) (test[key] + NGX_HASH_ELT_SIZE(&names[n])); #if 0 ngx_log_error(NGX_LOG_ALERT, hinit->pool->log, 0, "%ui: %ui %ui \"%V\"", size, key, test[key], &names[n].key); #endif /* * 如果冲突的元素大小 超过 bucket_size, 说明桶的个数设置太少,继续for循环 * * */ if (test[key] > (u_short) bucket_size) { goto next; } } goto found; next: /* * 没有最好的算法,只有最适合的算法 * * 虽然说goto大家很反对,代码跳来跳去,但是呢,小部分使用,让逻辑更清晰简单,容易实现 * * 我就绝对nginx对goto的使用恰到好处 * * */ continue; } size = hinit->max_size; ngx_log_error(NGX_LOG_WARN, hinit->pool->log, 0, "could not build optimal %s, you should increase " "either %s_max_size: %i or %s_bucket_size: %i; " "ignoring %s_bucket_size", hinit->name, hinit->name, hinit->max_size, hinit->name, hinit->bucket_size, hinit->name); found: /* * 到此已经找到合适的bucket数量,即为size * 重新初始化test数组元素,初始值为一个指针大小 * */ for (i = 0; i < size; i++) { test[i] = sizeof(void *); } for (n = 0; n < nelts; n++) { if (names[n].key.data == NULL) { continue; } key = names[n].key_hash % size; test[key] = (u_short) (test[key] + NGX_HASH_ELT_SIZE(&names[n])); } len = 0; /* * 为了提高访问速度,每个bucket的大小会和ngx_cacheline_size 对齐 * * len 计算bucket所需要的总长度 * */ for (i = 0; i < size; i++) { if (test[i] == sizeof(void *)) { continue; } test[i] = (u_short) (ngx_align(test[i], ngx_cacheline_size)); len += test[i]; } if (hinit->hash == NULL) { hinit->hash = ngx_pcalloc(hinit->pool, sizeof(ngx_hash_wildcard_t) + size * sizeof(ngx_hash_elt_t *)); if (hinit->hash == NULL) { ngx_free(test); return NGX_ERROR; } buckets = (ngx_hash_elt_t **) ((u_char *) hinit->hash + sizeof(ngx_hash_wildcard_t)); } else { buckets = ngx_pcalloc(hinit->pool, size * sizeof(ngx_hash_elt_t *)); if (buckets == NULL) { ngx_free(test); return NGX_ERROR; } } elts = ngx_palloc(hinit->pool, len + ngx_cacheline_size); if (elts == NULL) { ngx_free(test); return NGX_ERROR; } /*地址空间对齐可以提升访问速度*/ elts = ngx_align_ptr(elts, ngx_cacheline_size); /* * 将bucket地址数组和对应bucket关联 * * */ for (i = 0; i < size; i++) { if (test[i] == sizeof(void *)) { continue; } buckets[i] = (ngx_hash_elt_t *) elts; /* test[i] 记录着预算过的每个桶的带下*/ elts += test[i]; } for (i = 0; i < size; i++) { test[i] = 0; } /* * 将name的元素存储在bucket中 * * test数组用于保存对应bucket已经使用的字节数 * * */ for (n = 0; n < nelts; n++) { if (names[n].key.data == NULL) { continue; } key = names[n].key_hash % size; elt = (ngx_hash_elt_t *) ((u_char *) buckets[key] + test[key]); elt->value = names[n].value; elt->len = (u_short) names[n].key.len; ngx_strlow(elt->name, names[n].key.data, names[n].key.len); test[key] = (u_short) (test[key] + NGX_HASH_ELT_SIZE(&names[n])); } /* * 每个bucket的最后一个元素设置为NULL * * ngx_hash_find函数中,就以elt->value为while终止条件 * * */ for (i = 0; i < size; i++) { if (buckets[i] == NULL) { continue; } elt = (ngx_hash_elt_t *) ((u_char *) buckets[i] + test[i]); elt->value = NULL; } ngx_free(test); hinit->hash->buckets = buckets; hinit->hash->size = size; #if 0 for (i = 0; i < size; i++) { ngx_str_t val; ngx_uint_t key; elt = buckets[i]; if (elt == NULL) { ngx_log_error(NGX_LOG_ALERT, hinit->pool->log, 0, "%ui: NULL", i); continue; } while (elt->value) { val.len = elt->len; val.data = &elt->name[0]; key = hinit->key(val.data, val.len); ngx_log_error(NGX_LOG_ALERT, hinit->pool->log, 0, "%ui: %p \"%V\" %ui", i, elt, &val, key); elt = (ngx_hash_elt_t *) ngx_align_ptr(&elt->name[0] + elt->len, sizeof(void *)); } } #endif return NGX_OK; } /* * 通配符哈希表初始化 * * ngx_hash_wildcard_init其实构造了一个多级hash表 * * 为什么会这么设计?nginx这么设计有什么好处? * * * 参数: * hinit :初始化结构体指针 * names : 预加入哈希表数组 * nelts : 数组大小 */ ngx_int_t ngx_hash_wildcard_init(ngx_hash_init_t *hinit, ngx_hash_key_t *names, ngx_uint_t nelts) { size_t len, dot_len; ngx_uint_t i, n, dot; ngx_array_t curr_names, next_names; ngx_hash_key_t *name, *next_name; ngx_hash_init_t h; ngx_hash_wildcard_t *wdc; /* 初始化临时动态数组curr_names,curr_names是存放当前关键字的数组 */ if (ngx_array_init(&curr_names, hinit->temp_pool, nelts, sizeof(ngx_hash_key_t)) != NGX_OK) { return NGX_ERROR; } /* 初始化临时动态数组next_names,next_names是存放关键字去掉后剩余关键字 */ if (ngx_array_init(&next_names, hinit->temp_pool, nelts, sizeof(ngx_hash_key_t)) != NGX_OK) { return NGX_ERROR; } /* * 参考: https://ivanzz1001.github.io/records/post/nginx/2018/04/06/nginx-source_part40_3 * * 这里for循环时,n可能不是每次+1, 这是因为在处理到有相同前缀的元素时,会构造子hash,后面这些元素都交由子Hash来处理 * * 1) 寻找到names[n]中的第一个'.'字符(例如上面cn.com.baidu.) * * 2) 将寻找到的元素放入curr_names数组中(这里查找的元素为cn) * * 3) 假如查找到的元素长度不等于names[n]的总长度, 则初始化next_names数组(例如,上面len(cn) != len(cn.com.baidu)) * * 4) 从names[n+1]开始,判断后续是否有与上面查找到的元素同前缀的names, 如果有则加到next_names数组中 * * 5) 假如next_names数组长度不为0,则递归调用ngx_hash_wildcard_init()函数,构建子级Hash * * */ for (n = 0; n < nelts; n = i) { #if 0 ngx_log_error(NGX_LOG_ALERT, hinit->pool->log, 0, "wc0: \"%V\"", &names[n].key); #endif dot = 0; //以.作为字段的分隔符 for (len = 0; len < names[n].key.len; len++) { if (names[n].key.data[len] == '.') { dot = 1; break; } } name = ngx_array_push(&curr_names); if (name == NULL) { return NGX_ERROR; } //将上面获取的字段作为当前hash的key name->key.len = len; name->key.data = names[n].key.data; /* * hinit->key(name->key.data, name->key.len) 调用设置的函数指针 * * 这主要是用大写呢,还是小写计算hash值 * * 背景:有些场景需要忽略大小(客户要求域名) * * */ name->key_hash = hinit->key(name->key.data, name->key.len); name->value = names[n].value; #if 0 ngx_log_error(NGX_LOG_ALERT, hinit->pool->log, 0, "wc1: \"%V\" %ui", &name->key, dot); #endif dot_len = len + 1; if (dot) { len++; } next_names.nelts = 0; if (names[n].key.len != len) { next_name = ngx_array_push(&next_names); if (next_name == NULL) { return NGX_ERROR; } next_name->key.len = names[n].key.len - len; next_name->key.data = names[n].key.data + len; next_name->key_hash = 0; next_name->value = names[n].value; #if 0 ngx_log_error(NGX_LOG_ALERT, hinit->pool->log, 0, "wc2: \"%V\"", &next_name->key); #endif } for (i = n + 1; i < nelts; i++) { if (ngx_strncmp(names[n].key.data, names[i].key.data, len) != 0) { break; } if (!dot && names[i].key.len > len && names[i].key.data[len] != '.') { break; } next_name = ngx_array_push(&next_names); if (next_name == NULL) { return NGX_ERROR; } next_name->key.len = names[i].key.len - dot_len; next_name->key.data = names[i].key.data + dot_len; next_name->key_hash = 0; next_name->value = names[i].value; #if 0 ngx_log_error(NGX_LOG_ALERT, hinit->pool->log, 0, "wc3: \"%V\"", &next_name->key); #endif } if (next_names.nelts) { h = *hinit; h.hash = NULL; /* * 剩余的字段创造一个递归的hash * * */ if (ngx_hash_wildcard_init(&h, (ngx_hash_key_t *) next_names.elts, next_names.nelts) != NGX_OK) { return NGX_ERROR; } wdc = (ngx_hash_wildcard_t *) h.hash; /* 全匹配的Hash值在wdc->value处 */ if (names[n].key.len == len) { wdc->value = names[n].value; } /* * 巧妙代码标记 : wonderful_code_flag * * 使用了指针的低位携带额外信息,节省了内存 * * nginx的事件模块用指针最后一位来判断事件是否过期 * */ /* name->value = (void *) ((uintptr_t) wdc | (dot ? 3 : 2)) 当前value值指向新的hash表 * * 这里dot来区分该元素是否匹配到了最末尾 * * 这里2表示当前已经到了一个匹配的结尾,即已经获得了一个全量匹配,不需要再匹配下去了 * */ name->value = (void *) ((uintptr_t) wdc | (dot ? 3 : 2)); } else if (dot) { name->value = (void *) ((uintptr_t) name->value | 1); } } if (ngx_hash_init(hinit, (ngx_hash_key_t *) curr_names.elts, curr_names.nelts) != NGX_OK) { return NGX_ERROR; } return NGX_OK; } /* * BKDR算法进行hash * 发现一个很好的推理文章,还没有看 * * https://blog.csdn.net/wanglx_/article/details/40400693 */ ngx_uint_t ngx_hash_key(u_char *data, size_t len) { ngx_uint_t i, key; key = 0; for (i = 0; i < len; i++) { key = ngx_hash(key, data[i]); } return key; } ngx_uint_t ngx_hash_key_lc(u_char *data, size_t len) { ngx_uint_t i, key; key = 0; for (i = 0; i < len; i++) { key = ngx_hash(key, ngx_tolower(data[i])); } return key; } ngx_uint_t ngx_hash_strlow(u_char *dst, u_char *src, size_t n) { ngx_uint_t key; key = 0; while (n--) { *dst = ngx_tolower(*src); key = ngx_hash(key, *dst); dst++; src++; } return key; } ngx_int_t ngx_hash_keys_array_init(ngx_hash_keys_arrays_t *ha, ngx_uint_t type) { ngx_uint_t asize; if (type == NGX_HASH_SMALL) { asize = 4; ha->hsize = 107; } else { asize = NGX_HASH_LARGE_ASIZE; ha->hsize = NGX_HASH_LARGE_HSIZE; } if (ngx_array_init(&ha->keys, ha->temp_pool, asize, sizeof(ngx_hash_key_t)) != NGX_OK) { return NGX_ERROR; } if (ngx_array_init(&ha->dns_wc_head, ha->temp_pool, asize, sizeof(ngx_hash_key_t)) != NGX_OK) { return NGX_ERROR; } if (ngx_array_init(&ha->dns_wc_tail, ha->temp_pool, asize, sizeof(ngx_hash_key_t)) != NGX_OK) { return NGX_ERROR; } ha->keys_hash = ngx_pcalloc(ha->temp_pool, sizeof(ngx_array_t) * ha->hsize); if (ha->keys_hash == NULL) { return NGX_ERROR; } ha->dns_wc_head_hash = ngx_pcalloc(ha->temp_pool, sizeof(ngx_array_t) * ha->hsize); if (ha->dns_wc_head_hash == NULL) { return NGX_ERROR; } ha->dns_wc_tail_hash = ngx_pcalloc(ha->temp_pool, sizeof(ngx_array_t) * ha->hsize); if (ha->dns_wc_tail_hash == NULL) { return NGX_ERROR; } return NGX_OK; } /* * 1. 判断元素添加到哪一种类的Hash表中(完全匹配,前缀匹配,后缀匹配) * skip=1: 表示.example.com这种通配类型 * skip=2: 表示*.example.com这种通配类型 * skip=0: 表示www.example.*这种通配类型,此时将last值进行调整last-=2,即减去后面.*两个字符的长度 * * 2. 对通配字符串进行相应的格式转换 .example.com会被转换成 com.example * * 3. 在wildcard hash中检查是否有冲突 * * 4. 添加转换后的通配字符串到数组中 * * */ ngx_int_t ngx_hash_add_key(ngx_hash_keys_arrays_t *ha, ngx_str_t *key, void *value, ngx_uint_t flags) { size_t len; u_char *p; ngx_str_t *name; ngx_uint_t i, k, n, skip, last; ngx_array_t *keys, *hwc; ngx_hash_key_t *hk; last = key->len; if (flags & NGX_HASH_WILDCARD_KEY) { /* * supported wildcards: * "*.example.com", ".example.com", and "www.example.*" */ n = 0; for (i = 0; i < key->len; i++) { if (key->data[i] == '*') { if (++n > 1) { return NGX_DECLINED; } } if (key->data[i] == '.' && key->data[i + 1] == '.') { return NGX_DECLINED; } if (key->data[i] == '\0') { return NGX_DECLINED; } } if (key->len > 1 && key->data[0] == '.') { skip = 1; goto wildcard; } if (key->len > 2) { if (key->data[0] == '*' && key->data[1] == '.') { skip = 2; goto wildcard; } if (key->data[i - 2] == '.' && key->data[i - 1] == '*') { skip = 0; last -= 2; goto wildcard; } } if (n) { return NGX_DECLINED; } } /* exact hash */ k = 0; for (i = 0; i < last; i++) { if (!(flags & NGX_HASH_READONLY_KEY)) { key->data[i] = ngx_tolower(key->data[i]); } k = ngx_hash(k, key->data[i]); } k %= ha->hsize; /* check conflicts in exact hash */ name = ha->keys_hash[k].elts; if (name) { for (i = 0; i < ha->keys_hash[k].nelts; i++) { if (last != name[i].len) { continue; } if (ngx_strncmp(key->data, name[i].data, last) == 0) { return NGX_BUSY; } } } else { if (ngx_array_init(&ha->keys_hash[k], ha->temp_pool, 4, sizeof(ngx_str_t)) != NGX_OK) { return NGX_ERROR; } } name = ngx_array_push(&ha->keys_hash[k]); if (name == NULL) { return NGX_ERROR; } *name = *key; hk = ngx_array_push(&ha->keys); if (hk == NULL) { return NGX_ERROR; } hk->key = *key; hk->key_hash = ngx_hash_key(key->data, last); hk->value = value; return NGX_OK; wildcard: /* wildcard hash */ k = ngx_hash_strlow(&key->data[skip], &key->data[skip], last - skip); k %= ha->hsize; if (skip == 1) { /* check conflicts in exact hash for ".example.com" */ name = ha->keys_hash[k].elts; if (name) { len = last - skip; for (i = 0; i < ha->keys_hash[k].nelts; i++) { if (len != name[i].len) { continue; } if (ngx_strncmp(&key->data[1], name[i].data, len) == 0) { return NGX_BUSY; } } } else { if (ngx_array_init(&ha->keys_hash[k], ha->temp_pool, 4, sizeof(ngx_str_t)) != NGX_OK) { return NGX_ERROR; } } name = ngx_array_push(&ha->keys_hash[k]); if (name == NULL) { return NGX_ERROR; } name->len = last - 1; name->data = ngx_pnalloc(ha->temp_pool, name->len); if (name->data == NULL) { return NGX_ERROR; } ngx_memcpy(name->data, &key->data[1], name->len); } if (skip) { /* * convert "*.example.com" to "com.example.\0" * and ".example.com" to "com.example\0" */ p = ngx_pnalloc(ha->temp_pool, last); if (p == NULL) { return NGX_ERROR; } len = 0; n = 0; for (i = last - 1; i; i--) { if (key->data[i] == '.') { ngx_memcpy(&p[n], &key->data[i + 1], len); n += len; p[n++] = '.'; len = 0; continue; } len++; } if (len) { ngx_memcpy(&p[n], &key->data[1], len); n += len; } p[n] = '\0'; hwc = &ha->dns_wc_head; keys = &ha->dns_wc_head_hash[k]; } else { /* convert "www.example.*" to "www.example\0" */ last++; p = ngx_pnalloc(ha->temp_pool, last); if (p == NULL) { return NGX_ERROR; } ngx_cpystrn(p, key->data, last); hwc = &ha->dns_wc_tail; keys = &ha->dns_wc_tail_hash[k]; } /* check conflicts in wildcard hash */ name = keys->elts; if (name) { len = last - skip; for (i = 0; i < keys->nelts; i++) { if (len != name[i].len) { continue; } if (ngx_strncmp(key->data + skip, name[i].data, len) == 0) { return NGX_BUSY; } } } else { if (ngx_array_init(keys, ha->temp_pool, 4, sizeof(ngx_str_t)) != NGX_OK) { return NGX_ERROR; } } name = ngx_array_push(keys); if (name == NULL) { return NGX_ERROR; } name->len = last - skip; name->data = ngx_pnalloc(ha->temp_pool, name->len); if (name->data == NULL) { return NGX_ERROR; } ngx_memcpy(name->data, key->data + skip, name->len); /* add to wildcard hash */ hk = ngx_array_push(hwc); if (hk == NULL) { return NGX_ERROR; } hk->key.len = last - 1; hk->key.data = p; hk->key_hash = 0; hk->value = value; return NGX_OK; }
C
static char help[] = "Demonstrates a scatter with a stride and general index set.\n\n"; /*T requires: x T*/ #include <petscvec.h> int main(int argc,char **argv) { PetscErrorCode ierr; PetscInt n = 6,idx1[3] = {0,1,2},loc[6] = {0,1,2,3,4,5}; PetscScalar two = 2.0,vals[6] = {10,11,12,13,14,15}; Vec x,y; IS is1,is2; VecScatter ctx = 0; ierr = PetscInitialize(&argc,&argv,(char*)0,help);if (ierr) return ierr; /* create two vectors */ ierr = VecCreateSeq(PETSC_COMM_SELF,n,&x);CHKERRQ(ierr); ierr = VecDuplicate(x,&y);CHKERRQ(ierr); /* create two index sets */ ierr = ISCreateStride(PETSC_COMM_SELF,3,0,2,&is1);CHKERRQ(ierr); ierr = ISCreateGeneral(PETSC_COMM_SELF,3,idx1,PETSC_COPY_VALUES,&is2);CHKERRQ(ierr); ierr = VecSetValues(x,6,loc,vals,INSERT_VALUES);CHKERRQ(ierr); ierr = VecView(x,PETSC_VIEWER_STDOUT_SELF);CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_SELF,"----\n");CHKERRQ(ierr); ierr = VecSet(y,two);CHKERRQ(ierr); ierr = VecScatterCreate(x,is1,y,is2,&ctx);CHKERRQ(ierr); ierr = VecScatterBegin(ctx,x,y,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr); ierr = VecScatterEnd(ctx,x,y,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr); ierr = VecScatterDestroy(&ctx);CHKERRQ(ierr); ierr = VecView(y,PETSC_VIEWER_STDOUT_SELF);CHKERRQ(ierr); ierr = ISDestroy(&is1);CHKERRQ(ierr); ierr = ISDestroy(&is2);CHKERRQ(ierr); ierr = VecDestroy(&x);CHKERRQ(ierr); ierr = VecDestroy(&y);CHKERRQ(ierr); ierr = PetscFinalize(); return ierr; } /*TEST test: TEST*/
C
#include "globals.h" // this is the array that will hold our sequence. // This array will only contain 0, 1, 2, or 3. uint8_t fullSequence[GLOBALS_MAX_FLASH_SEQUENCE] = {0}; // this is simply the length of the above array uint16_t length = 0; // this is the level we're on. // In my code, length and level will be equal almost always. uint16_t level; // this takes in an array and a lenght integer. // it will set the first llength items in fullSequence to the items in sequence[] // it will also save the length as a global variable void globals_setSequence(const uint8_t sequence[], uint16_t llength){ for (uint8_t i = 0; i <= llength; i++){ fullSequence[i] = sequence[i]; } length = llength; } // This returns the value of the sequence at the index. uint8_t globals_getSequenceValue(uint16_t index){ return fullSequence[index]; } // Retrieve the sequence length. uint16_t globals_getSequenceLength(){ return length; } // This is the length of the sequence that you are currently working on. void globals_setSequenceIterationLength(uint16_t llength){ level = llength - 1; } // This is the length of the sequence that you are currently working on (not the maximum length but the interim length as // the use works through the pattern one color at a time. uint16_t globals_getSequenceIterationLength(){ return level; }
C
/* ** prompt.c for in /home/rosins_m/projets/brainfuck ** ** Made by matthieu rosinski ** Login <[email protected]> ** ** Started on Tue May 24 11:55:19 2011 matthieu rosinski ** Last update Tue May 24 11:55:19 2011 matthieu rosinski */ #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <unistd.h> #include "brainfuck.h" static void aff_prompt(int fd, const char *req) { if (fd == STDIN_FILENO) { if (req) printf("%s? ", req); else printf("bf> "); fflush(stdout); } } char prompt(const struct s_bf *vm, const char *req) { static char *buffer = NULL; static size_t pos = 0; size_t len; int rd = 0; if (buffer && (!buffer[pos] || buffer[pos] == '\n')) { pos = 0; free(buffer); buffer = NULL; } else if (!buffer) { len = 0; aff_prompt(vm->fd, req); while ((buffer = realloc(buffer, len + 2)) && ((rd = read(vm->fd, buffer + len, 1)) == 1)) { buffer[++len] = 0; if (buffer[len - 1] == '\n') break; } } if (!buffer || rd == -1) return (-1); return (buffer[pos++]); }
C
#include<stdio.h> int main() { long long int n,a,i; int arr[6]={1,8,4,2,6}; scanf("%I64d",&n); if(n==0) a=arr[0]; else if(n<5 ) a=arr[n]; else if(n%4==0) { a=arr[4]; } else if(n>=5) { i=n%4; a=arr[i]; } printf("%I64d\n",a); return 0; }
C
/* ** main.c for normal in /home/ozouf_h//rt_normal ** ** Made by harold ozouf ** Login <[email protected]> ** ** Started on Wed May 9 17:23:32 2012 harold ozouf ** Last update Sun Jun 3 01:32:40 2012 harold ozouf */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include "raytracer.h" #include "camera.h" #include "detail.h" #include "calc.h" #include "init.h" #include "utils.h" static int get_normal(double *p1, double *p2, double *p3, double *n) { double u[NB_DIMENSION]; double v[NB_DIMENSION]; int i; i = -1; while (++i < NB_DIMENSION) { u[i] = (p2[i] - p1[i]) * (1.000 / CARRE(CONST_NORMAL)); v[i] = (p3[i] - p1[i]) * (1.000 / CARRE(CONST_NORMAL)); } n[X] = (u[Y] * v[Z]) - (u[Z] * v[Y]); n[Y] = (u[Z] * v[X]) - (u[X] * v[Z]); n[Z] = (u[X] * v[Y]) - (u[Y] * v[X]); normalize_vector(n); return (EXIT_SUCCESS); } static int get_axe(double *vector) { int axe; int i; if (vector == NULL) return (NB_DIMENSION + 1); axe = X; i = -1; while (++i < NB_DIMENSION) if (ABS(vector[axe]) <= ABS(vector[i])) axe = i; return (axe); } static int get_vector(double *old, double *new, int axe, int flag) { int i; if (old == NULL || new == NULL || axe > NB_DIMENSION) return (EXIT_FAILURE); i = -1; while (++i < NB_DIMENSION) if (axe != i) new[i] = old[i] + CONST_NORMAL; else new[i] = old[i]; i = 0; while (flag >= 0) { if (i != axe) --flag; ++i; } new[i - 1] += CONST_NORMAL; return (EXIT_SUCCESS); } static int approx_normal(t_camera *c, t_detail *d, double *v, double *n) { t_detail td[2]; double tv[2][NB_DIMENSION]; int axe; axe = get_axe(v); if (init_detail(&td[0]) || init_detail(&td[1]) || get_vector(v, tv[0], axe, 1) || get_vector(v, tv[1], axe, 0)) return (EXIT_FAILURE); d->object->inter(c, d->object, &td[0], tv[0]); d->object->inter(c, d->object, &td[1], tv[1]); if (td[0].object != NULL && td[1].object != NULL) { calc_point(c->position, tv[0], td[0].position, td[0].k); calc_point(c->position, tv[1], td[1].position, td[1].k); get_normal(d->position, td[0].position, td[1].position, n); corrector_normal(d, n, v); return (EXIT_SUCCESS); } return (EXIT_FAILURE); } int calc_normal(t_camera *c, t_detail *d, double *v, double *n) { int i; i = -1; if (d->non_initialize == 0) { while (++i < NB_DIMENSION) n[i] = 0.0F; approx_normal(c, d, v, n); } corrector_normal(d, n, v); return (EXIT_SUCCESS); }
C
#include "avl.h" #include "consultasFuncoes.h" #include "declaracoes.h" #include "hashTable.h" #include "imprimeSvg.h" #include "leitura.h" #include "lista.h" #include "locacoesData.h" #include "parametrosData.h" #include "pessoasData.h" #include "quadrasData.h" typedef struct dados { void *valor; } Dados; typedef struct celula { void *Dados; int profundidade; struct celula *right; struct celula *left; struct celula *prev; struct celula *next; double min; double max; } Celula; typedef struct arvore { int tamanho; Celula *raiz; int (*compare)(void *, void *); void (*freeNode)(void *); } Arvore; void *getData(void *Sdata) { Celula *dados = Sdata; if (!dados) { return 0; } return dados->Dados; } void *getHead(Tree tree) { Arvore *arvore = tree; if (!tree) return NULL; return arvore->raiz; } double getMin(Posic celula) { Celula *ponteiro = celula; return ponteiro->min; } double getMax(Posic celula) { Celula *ponteiro = celula; return ponteiro->max; } Tree CriaArvore(int (*compare)(void *, void *), void (*freeNode)(void *)) { Arvore *ponteiro = malloc(sizeof(Arvore)); ponteiro->tamanho = 0; ponteiro->raiz = NULL; ponteiro->compare = compare; ponteiro->freeNode = freeNode; return ponteiro; } void InsereElementoRec(Tree tree, Iten dados) { Arvore *arvore = tree; void *ponteiro; int tamanho = arvore->tamanho; InsereElemento(arvore, dados, arvore->raiz, ponteiro, 1); } //funcao recursiva de inserção na arvore kd, tanto de retangulo quanto de circulo void InsereElemento(Tree tree, Iten dados, Iten celulaAtual, void *currentAux, int profundidadeGlobal) { Arvore *arvore = tree; Celula *celulaAtualAux = celulaAtual; Celula *aux; if (arvore->tamanho == 0) { aux = calloc(1, sizeof(Celula)); arvore->raiz = aux; aux->Dados = CriaLista(); InsereElementoLista(arvore->raiz->Dados, dados); aux->right = NULL; aux->left = NULL; aux->prev = NULL; aux->profundidade = 1; aux->min = getDataX(dados); aux->max = getDataX(dados) + getDataW(dados); arvore->tamanho++; } else { if (celulaAtualAux->min > getDataX(dados)) celulaAtualAux->min = getDataX(dados); if (celulaAtualAux->max < getDataX(dados) + getDataW(dados)) celulaAtualAux->max = getDataX(dados) + getDataW(dados); profundidadeGlobal++; if (arvore->compare(dados, getdataList(getheadLista(celulaAtualAux->Dados))) == 1) { if (!celulaAtualAux->right) { aux = calloc(1, sizeof(Celula)); celulaAtualAux->right = aux; aux->Dados = CriaLista(); InsereElementoLista(aux->Dados, dados); aux->right = NULL; aux->left = NULL; aux->prev = celulaAtualAux; aux->profundidade = profundidadeGlobal; aux->min = getDataX(dados); aux->max = getDataX(dados) + getDataW(dados); arvore->tamanho++; } else { if (celulaAtualAux->min > getDataX(dados)) celulaAtualAux->min = getDataX(dados); if (celulaAtualAux->max < getDataX(dados) + getDataW(dados)) celulaAtualAux->max = getDataX(dados) + getDataW(dados); InsereElemento(arvore, dados, celulaAtualAux->right, aux, profundidadeGlobal); } } else if (arvore->compare(dados, getdataList(getheadLista(celulaAtualAux->Dados))) == -1) { if (!celulaAtualAux->left) { aux = calloc(1, sizeof(Celula)); celulaAtualAux->left = aux; aux->Dados = CriaLista(); InsereElementoLista(aux->Dados, dados); aux->right = NULL; aux->left = NULL; aux->prev = celulaAtualAux; aux->profundidade = profundidadeGlobal; aux->min = getDataX(dados); aux->max = getDataX(dados) + getDataW(dados); arvore->tamanho++; } else { if (celulaAtualAux->min > getDataX(dados)) celulaAtualAux->min = getDataX(dados); if (celulaAtualAux->max < getDataX(dados) + getDataW(dados)) celulaAtualAux->max = getDataX(dados) + getDataW(dados); InsereElemento(arvore, dados, celulaAtualAux->left, aux, profundidadeGlobal); } } else { if (celulaAtualAux->min > getDataX(dados)) celulaAtualAux->min = getDataX(dados); if (celulaAtualAux->max < getDataX(dados) + getDataW(dados)) celulaAtualAux->max = getDataX(dados) + getDataW(dados); InsereElementoLista(celulaAtualAux->Dados, dados); } Balance(comparaRotacao(celulaAtualAux), celulaAtualAux, arvore); } if (celulaAtualAux) if (celulaAtualAux->left) celulaAtualAux->min = celulaAtualAux->left->min; } void Balance(int condicional, Posic celulaDesbalanceada, Tree arvore) { Celula *celula = celulaDesbalanceada; if (condicional == 1) { rotacaoEsquerda(celula, arvore); } else if (condicional == 2) { rotacaoDireita(celula, arvore); } else if (condicional == 3) { rotacaoDireita(celula->right, arvore); rotacaoEsquerda(celula, arvore); } else if (condicional == 4) { rotacaoEsquerda(celula->left, arvore); rotacaoDireita(celula, arvore); } } void *Referencia(Arvore *tree, Celula *delete) { if (delete->right && !delete->left) { //delete tem so o filho direito return delete->right; } else if (delete->left && !delete->right) { //delete tem so o filho esquerdo return delete->left; } else if (delete->left && delete->right) { //delete tem os 2 filhos return minValueNode(delete->right); } else { //delete não tem filhos return NULL; } } void arrumaMinMaxNaRecursaoDelete(Iten aux) { Celula *celulaAtual = aux; if (celulaAtual->right) { if (celulaAtual->right->max > celulaAtual->max) { celulaAtual->max = celulaAtual->right->max; } } if (celulaAtual->left) { if (celulaAtual->left->min < celulaAtual->min) { celulaAtual->min = celulaAtual->left->min; } if (celulaAtual->left->max > celulaAtual->max) { celulaAtual->max = celulaAtual->left->max; } } } void deleteNodeRecursive(Arvore *tree, Celula *celulaAtual, Iten aux, double *MinMax) { if (celulaAtual == NULL) { return; } Arvore *arvore = tree; if (tree->compare(aux, getdataList(getheadLista(celulaAtual->Dados))) == 1) { //desce para direita deleteNodeRecursive(tree, celulaAtual->right, aux, MinMax); atualizaMinMaxSoCelula(celulaAtual); if (celulaAtual->min < MinMax[0]) MinMax[0] = celulaAtual->min; else celulaAtual->min = MinMax[0]; if (celulaAtual->max > MinMax[1]) MinMax[1] = celulaAtual->max; else celulaAtual->max = MinMax[1]; arrumaMinMaxNaRecursaoDelete(celulaAtual); } else if (tree->compare(aux, getdataList(getheadLista(celulaAtual->Dados))) == -1) { //desce para esquerda deleteNodeRecursive(tree, celulaAtual->left, aux, MinMax); atualizaMinMaxSoCelula(celulaAtual); if (celulaAtual->min < MinMax[0]) MinMax[0] = celulaAtual->min; else celulaAtual->min = MinMax[0]; if (celulaAtual->max > MinMax[1]) MinMax[1] = celulaAtual->max; else celulaAtual->max = MinMax[1]; arrumaMinMaxNaRecursaoDelete(celulaAtual); } else if (tree->compare(aux, getdataList(getheadLista(celulaAtual->Dados))) == 0) { Celula *novo = Referencia(tree, celulaAtual); if (arvore->tamanho == 1) { arvore->tamanho = 0; arvore->raiz = NULL; FreeLista(celulaAtual->Dados, 0); free(celulaAtual->Dados); free(celulaAtual); return; } else if (!celulaAtual->right && !celulaAtual->left) { //caso o no a ser removido seja uma folha if (celulaAtual == celulaAtual->prev->right) celulaAtual->prev->right = NULL; else celulaAtual->prev->left = NULL; } else if (!celulaAtual->left && celulaAtual->right || !celulaAtual->right && celulaAtual->left) { //caso o no a ser removido tenha um filho if (celulaAtual == tree->raiz) tree->raiz = novo; else { if (celulaAtual == celulaAtual->prev->right) celulaAtual->prev->right = novo; else celulaAtual->prev->left = novo; } novo->prev = celulaAtual->prev; } else { //caso 3, o no a ser deletado tem 2 filhos if (novo == celulaAtual->right) { if (celulaAtual != tree->raiz) { if (celulaAtual->prev->right == celulaAtual) celulaAtual->prev->right = novo; else celulaAtual->prev->left = novo; } else { tree->raiz = novo; } } else { if (celulaAtual != tree->raiz) { if (celulaAtual->prev->right == celulaAtual) celulaAtual->prev->right = novo; else celulaAtual->prev->left = novo; } else tree->raiz = novo; novo->prev->left = novo->right; novo->right = celulaAtual->right; } celulaAtual->right->prev = novo; celulaAtual->left->prev = novo; novo->left = celulaAtual->left; novo->prev = celulaAtual->prev; } if (novo) { atualizaMinMaxSoCelula(novo); if (novo->min < MinMax[0]) MinMax[0] = novo->min; else novo->min = MinMax[0]; if (novo->max > MinMax[1]) MinMax[1] = novo->max; else novo->max = MinMax[1]; arrumaMinMaxNaRecursaoDelete(novo); MinMax[0] = novo->min; MinMax[1] = novo->max; } Balance(comparaRotacao(celulaAtual), celulaAtual, tree); arvore->tamanho = arvore->tamanho - 1; FreeLista(celulaAtual->Dados, 0); free(celulaAtual->Dados); free(celulaAtual); } } void deleteNode(Tree tree, Iten aux) { Arvore *arvore = tree; double *MinMax = calloc(2, sizeof(double)); MinMax[0] = 999999; MinMax[1] = -999999; deleteNodeRecursive(tree, arvore->raiz, aux, MinMax); if (arvore->raiz) Balance(comparaRotacao(arvore->raiz), arvore->raiz, tree); free(MinMax); } int getBalance(Iten aux) { Celula *N = aux; if (N == NULL) return 0; return altura(N->left) - altura(N->right); } int max(int a, int b) { return (a > b) ? a : b; } void atualizaMinMaxSoCelula(Iten node) { //percorre a celula da avl para mudar o min e max apenas em relação a ela, sem olhar para filho direito ou esquerdo Celula *aux = node; void *atualLista = getheadLista(aux->Dados); aux->min = getDataX(getdataList(atualLista)); aux->max = getDataX(getdataList(atualLista)) + getDataW(getdataList(atualLista)); while (atualLista) { if (getDataX(getdataList(atualLista)) + getDataW(getdataList(atualLista)) > aux->max) aux->max = getDataX(getdataList(atualLista)) + getDataW(getdataList(atualLista)); atualLista = getnextLista(atualLista); } } Posic minValueNode(Iten node) { Celula *current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) current = current->left; Celula *aux = current; //lefter double min = 999999; double max = -999999; while (aux != node) { //parte de atualizar o min e max aux = aux->prev; atualizaMinMaxSoCelula(aux); if (aux->min < min) min = aux->min; else aux->min = min; if (aux->max > max) max = aux->max; else aux->max = max; } return current; } int comparaRotacao(Iten aux) { Celula *celula = aux; int altEsq = altura(celula->left); int altDir = altura(celula->right); if (altDir >= altEsq + 2 && altura(celula->right->left) > altura(celula->right->right)) { //Right-Left case return 3; //C } else if (altEsq >= altDir + 2 && altura(celula->left->right) > altura(celula->left->left)) { //Left-Right case return 4; //B } else if (altDir >= altEsq + 2 && altura(celula->right->right) >= altura(celula->right->left)) { //Right-Right return 1; //D } else if (altEsq >= altDir + 2 && altura(celula->left->left) >= altura(celula->left->right)) { //Left-Left return 2; //A } else { return 0; } } int altura(Iten CelulaAtual) { if (!CelulaAtual) return 0; return altura(AvlRight(CelulaAtual)) > altura(AvlLeft(CelulaAtual)) ? altura(AvlRight(CelulaAtual)) + 1 : altura(AvlLeft(CelulaAtual)) + 1; } Iten AvlRight(Iten aux) { Celula *celula = aux; if (!celula) return NULL; return celula->right; } Iten AvlLeft(Iten aux) { Celula *celula = aux; return celula->left; } int avlPrev(Iten celula) { Celula *aux = celula; if (aux->prev == NULL) { //raiz return 0; } else if (aux == aux->prev->right) { return 1; } else if (aux == aux->prev->left) { return 2; } else { return -1; } } void fixMinMax(Iten celula, Tree tree) { if (!celula) return; Arvore *arvore = tree; Celula *p = celula; int verificadorMin = 0; int verificadorMax = 0; if (p->right) { if (p->right->min < p->min) { p->min = p->right->min; verificadorMin = 1; } if (p->right->max > p->max) { p->max = p->right->max; verificadorMax = 1; } } if (p->left) { if (p->left->min < p->min) { p->min = p->left->min; verificadorMin = 1; } if (p->left->max > p->max) { p->max = p->left->max; verificadorMax = 1; } } void *aux = getheadLista(p->Dados); if (verificadorMin == 0) { p->min = getDataX(getdataList(aux)); } if (verificadorMax == 0) { p->max = getDataX(getdataList(aux)) + getDataW(getdataList(aux)); while (aux) { if (getDataX(getdataList(aux)) + getDataW(getdataList(aux)) > p->max) p->max = getDataX(getdataList(aux)) + getDataW(getdataList(aux)); aux = getnextLista(aux); } } } void rotacaoDireita(Iten celula, Tree tree) { if (!celula) return; Arvore *arvore = tree; Celula *p = celula; Celula *q, *aux; Celula *pai = p->prev; q = p->left; aux = q->right; q->right = p; p->left = aux; if (aux) { aux->prev = p; if (p->right == NULL) { p->max = aux->max; p->min = aux->min; } else { if (aux->max > p->right->max) p->max = aux->max; else p->max = p->right->max; if (aux->min < p->right->min) p->min = aux->min; else p->min = p->right->min; } } if (pai) { atualizaMinMaxSoCelula(pai); if (pai->left) { pai->min = pai->left->min; if (pai->left->max > pai->max) pai->max = pai->left->max; } if (pai->right) { if (pai->right->max > pai->max) pai->max = pai->right->max; } } if (p) { if (!p->right && !p->left) atualizaMinMaxSoCelula(p); } if (aux) { if (!aux->right && !aux->left) atualizaMinMaxSoCelula(aux); } if (avlPrev(celula) == 0) { arvore->raiz = q; } else if (avlPrev(celula) == 1) { p->prev->right = q; } else if (avlPrev(celula) == 2) { p->prev->left = q; } else { printf("ERRO ROTAÇÂO DIR"); } q->prev = pai; p->prev = q; if (p) if (p->left) p->min = p->left->min; if (aux) if (aux->left) aux->min = aux->left->min; if (pai) if (pai->left) pai->min = pai->left->min; } void rotacaoEsquerda(Iten celula, Tree tree) { if (!celula) return; Arvore *arvore = tree; Celula *p = celula; Celula *q, *aux; Celula *pai = p->prev; q = p->right; aux = q->left; q->left = p; p->right = aux; if (aux) { aux->prev = p; if (p->left == NULL) { atualizaMinMaxSoCelula(p); if (p->max < aux->max) p->max = aux->max; } else { if (aux->max > p->left->max) p->max = aux->max; else p->max = p->left->max; p->min = p->left->min; } } if (pai) { atualizaMinMaxSoCelula(pai); if (pai->left) { pai->min = pai->left->min; if (pai->left->max > pai->max) pai->max = pai->left->max; } if (pai->right) { if (pai->right->max > pai->max) pai->max = pai->right->max; } } if (p) { if (!p->right && !p->left) atualizaMinMaxSoCelula(p); } if (aux) { if (!aux->right && !aux->left) atualizaMinMaxSoCelula(aux); } if (avlPrev(celula) == 0) { arvore->raiz = q; } else if (avlPrev(celula) == 1) { p->prev->right = q; } else if (avlPrev(celula) == 2) { p->prev->left = q; } else { printf("ERRO ROTAÇÂO LEFT"); } q->prev = pai; p->prev = q; if (p) if (p->left) p->min = p->left->min; if (aux) if (aux->left) aux->min = aux->left->min; if (pai) if (pai->left) pai->min = pai->left->min; } //chama a função recursiva de liberar a arvore kd void freeAvl(Tree tree) { Arvore *arvore = tree; if (!arvore->raiz) { return; } Celula *aux1_0 = arvore->raiz; freeAvlRec(aux1_0); } void freeAvlRec(Posic aux1_0) { Celula *aux = aux1_0; if (aux->left) { freeAvlRec(aux->left); } if (aux->right) { freeAvlRec(aux->right); } if (aux) { if (aux->Dados) { FreeLista(aux->Dados, -1); free(aux->Dados); } free(aux); } } void printRecursivoRec(Tree tree) { Arvore *arvore = tree; printRecursivo(arvore->raiz, 0); } //funcao recursiva de printar no terminal (semelhante a logica de printar no svg) void printRecursivo(Posic galhoAtual1, int space) { Celula *aux = galhoAtual1; if (!galhoAtual1) { return; } space += 10; printRecursivo(aux->right, space); printf("\n"); for (int i = 10; i < space; i++) printf(" "); void *celulaLista = getheadLista(aux->Dados); for (int i = 0; i < gettamanhoLista(aux->Dados); i++) { printf("[%s] ", getDataCep(getdataList(celulaLista))); celulaLista = getnextLista(celulaLista); } printf("[%.2lf] [%.2lf]", aux->min, aux->max); puts(" "); printRecursivo(aux->left, space); } int compareDouble(void *esquerda, void *direita) { double esq = getDataX(esquerda); double dir = getDataX(direita); if (esq > dir) { return 1; } else if (esq < dir) { return -1; } else { return 0; } } void *retornaCelulaAvlRecursivo(Tree tree, double x, Celula *aux1_0) { if (!aux1_0) return NULL; void *celulaLista = getheadLista(aux1_0->Dados); if (getDataX(getdataList(celulaLista)) < x) return retornaCelulaAvlRecursivo(tree, x, AvlRight(aux1_0)); else if (getDataX(getdataList(celulaLista)) > x) return retornaCelulaAvlRecursivo(tree, x, AvlLeft(aux1_0)); else if (getDataX(getdataList(celulaLista)) == x) return celulaLista; } void *retornaCelulaAvl(Tree tree, double x) { Arvore *arvore = tree; Celula *aux1_0 = arvore->raiz; return retornaCelulaAvlRecursivo(tree, x, aux1_0); } void *retornaListaAvlRecursivo(Tree tree, double x, Celula *aux1_0) { if (!aux1_0) return NULL; void *celulaLista = getheadLista(aux1_0->Dados); if (getDataX(getdataList(celulaLista)) < x) return retornaListaAvlRecursivo(tree, x, AvlRight(aux1_0)); else if (getDataX(getdataList(celulaLista)) > x) return retornaListaAvlRecursivo(tree, x, AvlLeft(aux1_0)); else if (getDataX(getdataList(celulaLista)) == x) { return aux1_0->Dados; } } void *retornaListaAvl(Tree tree, double x) { Arvore *arvore = tree; Celula *aux1_0 = arvore->raiz; return retornaListaAvlRecursivo(tree, x, aux1_0); } void imprimeSvgAvl(Tree avl, FILE *inicializaSvgSaida, Posic celulaAtual) { Celula *celula = celulaAtual; if (!celula) return; imprimeSvgAvl(avl, inicializaSvgSaida, AvlLeft(celulaAtual)); imprimeSvgAvl(avl, inicializaSvgSaida, AvlRight(celulaAtual)); void *celulaListaQuadra = getheadLista(getData(celula)); while (celulaListaQuadra) { ImprimeRect(getDataCorC(getdataList(celulaListaQuadra)), getDataCorP(getdataList(celulaListaQuadra)), "1.0px", getDataX(getdataList(celulaListaQuadra)), getDataY(getdataList(celulaListaQuadra)), getDataW(getdataList(celulaListaQuadra)), getDataH(getdataList(celulaListaQuadra)), inicializaSvgSaida); celulaListaQuadra = getnextLista(celulaListaQuadra); } }
C
// // Created by Stanislav on 2019-05-06. // #ifndef ZLASM_C_ERROR_H #define ZLASM_C_ERROR_H #include <stdio.h> #include <stdlib.h> #include "../../include/Types.h" #define ZLASM__CRASH(msg) _crash(msg, __FILE__, __LINE__) #define ZLASM__TOKEN_CRASH(msg, token) \ _token_crash(msg, (token->pos), (token->line), (token->col), (token->value),__FILE__, __LINE__) static void _token_crash(const char* msg, size_t pos, size_t line, size_t col, const char* val, const char* __file, size_t __line) __dead2 { fprintf(stderr, "Error at %s:%lu\n\t (%4lu:%3lu:%2lu): %s (%s)", __file, __line, pos, line, col, msg, val); exit(-2); } static void _crash(const char* msg, const char* file, size_t line) __dead2 { fprintf(stderr, "Crash at %s:%lu: %s", file, line, msg); exit(-1); } static inline void _errorCode(const char* msg, word code) __dead2 { fprintf(stderr, "Error: %s", msg); exit(code); } static inline void _error(const char* msg) { _errorCode(msg, 0); } #endif //ZLASM_C_ERROR_H
C
/* ** count_special_char.c for in /home/januar_m/delivery/PSU/PSU_2016_minishell2/basics ** ** Made by Martin Januario ** Login <[email protected]> ** ** Started on Sun Apr 9 02:13:14 2017 Martin Januario ** Last update Sun Apr 9 02:23:08 2017 Martin Januario */ #include <stdlib.h> #include "my.h" int count_spe_char(char *str, char car) { int idx; int result; idx = 0; result = 0; if (str == NULL) return (0); while (str[idx] != '\0') { if (str[idx] == car) result++; idx++; } return (result); }
C
#include "lab1.h" extern char sz_menu[]; const char * sz_help1[] = { " (a^f/2+b-(f/a)+f*a^2-(a^2+b^2)", "'1' a, b f ", "'h' 'H'. ", "'E' 'e'. " }; int sz_help_data1 = sizeof(sz_help1) / sizeof(char *); void lab1_help(){ int i = 0; for(;i < sz_help_data1;i++){ printf("*** %s ***\n",sz_help1[i]); } } void lab1_math(){ double a = 0, b = 0, f = 0; float i_result = 0.0; fprintf(stdout," ,b f \n>"); scanf("%lf %lf %lf",&a,&b,&f); fprintf(stdout,"a = %f, b = %f, f = %f\n",a,b,f); i_result = ( ( a*(f/2) + b - (f/a) ) + f*pow(a,2.0) - (pow(a,2.0) + pow(b,2.0)) ); fprintf(stdout," (a^f/2+b-(f/a)+f*a^2-(a^2+b^2) = %f \n",(float)i_result); } void lab1(){ int ch = 0,is_exit = 0; while(1){ strcpy(sz_menu,"#1>"); fprintf(stdout,sz_menu); fflush(stdin); switch(ch = getchar()){ case '1' : { lab1_math(); break; } case 'H' : case 'h' : { lab1_help(); break; } case 'e' : case 'E' :{ fprintf(stdout," 1!\n"); is_exit = 1; break; } default :{ fprintf(stdout," h \n"); } } if(is_exit) break; } }
C
#include <stdio.h> #include <stdlib.h> struct node{ int vertex; struct node *next; }; // typedef is used for user defined type node typedef struct stack node; // Another user defined type nodeptr is pointer to node type typedef node * nodeptr; struct Graph{ int numVertices; struct node **adjlist; int *visited; int *start; int *finish; int *parent; }; int topstack(nodeptr f); struct Graph *creategraph(int v){ struct Graph *graph; graph=(struct Graph *)malloc(v*sizeof(struct Graph)); graph->numVertices=v; graph->adjlist=(struct node **)malloc(v*sizeof(struct node *)); graph->visited=(int *)malloc(v*sizeof(int)); graph->start=(int *)malloc(v*sizeof(int)); graph->finish=(int *)malloc(v*sizeof(int)); graph->parent=(int *)malloc(v*sizeof(int)); int i; for(i=0;i<v;i++){ graph->adjlist[i]=NULL; graph->visited[i]=0; graph->start[i]=0; graph->finish[i]=0; graph->parent[i]=0; } return graph; } struct node *createnode(int dest){ struct node *newnode; newnode=(struct node *)malloc(sizeof(struct node)); newnode->vertex=dest; newnode->next=NULL; return newnode; } void addedge(struct Graph *graph,int src,int dst){ struct node *new=createnode(dst); new->next = graph->adjlist[src-1]; graph->adjlist[src-1] = new; new=createnode(src); new->next=graph->adjlist[dst-1]; graph->adjlist[dst-1]=new; } void printGraph(struct Graph* graph) { int v; for (v = 0; v < graph->numVertices; v++) { struct node* temp = graph->adjlist[v]; printf("\n Adjacency list of vertex %d\n ", v+1); while (temp) { printf(" -> %d", temp->vertex); temp = temp->next; } printf("\n"); } } struct stack{ int data; struct stack *next; }; void init(nodeptr *top) { *(top)=NULL; // empty stack } //================================================================ void push(nodeptr *top,int d) { node * newnode; // use a pointer type for node called newnode newnode=(node*)malloc(sizeof(node)); // allocate space for node type pointed to by newnode newnode->next=*(top); *(top)=newnode; // newnode points to node type that stored the old top stack pointer // finally we return newnode by reference through top of type nodeptr* //printf("\nEnter the character to push\n"); //fflush(stdin); //scanf(" %c",&(newnode->data)); // read data in node type space for data of type char // where the node is pointed to by the new node pointed to by nodeptr newnode->data=d; //topstack(*(top)); // Now simply print what was pushed on top of stack } //=============================================================== void pop(nodeptr *top) { node *delnode; /* pointer to node to be deleted */ topstack(*(top)); // first simply print what is going to be pooped off the stack top if (*(top)==NULL) printf("cannot pop"); // No deletion is possible if the list is already empty else {delnode=*(top); // if non-empty then pick the top node pointer through top which is of // type nodeptr* *top=(*top)->next; free(delnode); } // move down one step in stack, changing contents of // location pointed to by top and free the node popped off } //================================================================ int topstack(nodeptr f) { // Simply print the data pointed to by node pointer if (f==NULL) return 0; else{ //printf("top value=%d",f->data); return f->data; } } int isempty(nodeptr f){ if(f==NULL) return 1; else return 0; } void dfs(struct Graph *graph,int vertex){ nodeptr top; int time=0; int popVer=1; init(&top); push(&top,vertex); printf("Visited vertex %d\n",vertex); graph->visited[vertex-1]=1; time++; graph->start[vertex-1]=time; while(!isempty(top)){ int curVertex=topstack(top); struct node *temp= graph->adjlist[curVertex-1]; while(temp){ popVer=1; int adjVertex=temp->vertex; if(graph->visited[adjVertex-1]==0){ popVer=0; graph->visited[adjVertex-1]=1; printf("Visited vertex %d\n",adjVertex); push(&top,adjVertex); time++; graph->start[adjVertex-1]=time; break; } temp=temp->next; } if(popVer||!temp){ pop(&top); graph->finish[curVertex-1]=time; } } }0 int main(){ int v,e,a,b,i; printf("Enter v: "); scanf(" %d",&v); printf("Enter e: "); scanf(" %d",&e); struct Graph *graph=creategraph(v); for(i=0;i<e;i++){ printf("Enter: "); scanf(" %d%d",&a,&b); addedge(graph,a,b); } printGraph(graph); printf("\n"); dfs(graph,3); for(i=0;i<e;i++){ printf("Start time of vertex %d is %d\n",i+1,graph->start[i]); } for(i=0;i<e;i++){ printf("Finish time of vertex %d is %d\n",i+1,graph->finish[i]); } }
C
/* ** EPITECH PROJECT, 2018 ** fd_manager ** File description: ** manage client fd for server */ #include <stdio.h> #include "server.h" static void set_fd(t_data *serv) { FD_ZERO(&serv->readfs); FD_SET(serv->fd, &serv->readfs); FD_ZERO(&serv->writefs); } static int loop_fd(t_data *serv) { int i = 0; int res = serv->fd; while (i < MAX_FD) { if (serv->users[i].slot == CLOSE) { if (serv->users[i].fd > res) res = serv->users[i].fd; FD_SET(serv->users[i].fd, &serv->writefs); FD_SET(serv->users[i].fd, &serv->readfs); } i = i + 1; } return (res); } int fd_manager(t_data *serv) { int res = 0; set_fd(serv); res = loop_fd(serv); return (res); }
C
/*DESCRIPCION: PROTOTIPOS DE FUNCIONES PARA EL MANEJO DE ALGORITMOS QUE RELACIONAN LAS ESTRUCTURAS eCliente y ePrestamo *AUTOR: CARLOS LOPEZ */ #ifndef LINKERSTRUCTURE_H_ #define LINKERSTRUCTURE_H_ #define QTYLINKER 3 #define EMPTY 0 #define NON_EMPTY 1 /** * \brief : Permite dar de baja un cliente * \param ePrestamo* : puntero de array de prestamos * \param arrayPLength: longitud del array de prestamos. * \param eCliente* : puntero de array de prestamos * \param arrayCLength: longitud del array de prestamos. * \return : retorna un entero en caso que se necesite controlar ejecucion */ int deleteMembereCliente(eCliente* eClienteArray, int arrayCLength, ePrestamo* ePrestamoArray, int arrayPLength); /** * \brief : muestra el cliente con mayor cantidad de prestamos saldados * \param ePrestamo* : puntero de array de prestamos * \param arrayPLength*: longitud del array de prestamos. * \param eCliente* : puntero de array de prestamos * \param arrayCLength: longitud del array de prestamos. * \param fieldTitle1:puntero a char con mensaje a ser utilizado como titulo * \param fieldTitle2:puntero a char con mensaje a ser utilizado como titulo * \param fieldTitle3:puntero a char con mensaje a ser utilizado como titulo * \param fieldTitle4:puntero a char con mensaje a ser utilizado como titulo * \return : retorna un entero en caso que se necesite controlar ejecucion */ int showListePrestamoByClient(ePrestamo* ePrestamoArray, int arrayPLength, int idCliente, char* fieldTitle1, char* fieldTitle2, char* fieldTitle3,char* fieldTitle4); /** * \brief : Permite modificar el estado de un prestamo * \param ePrestamo* : puntero de array de prestamos * \param arrayPLength: longitud del array de prestamos. * \param eCliente* : puntero de array de prestamos * \param arrayCLength: longitud del array de prestamos. * \param option: opcion de moficacion puede ser 5 o 6 dependiendo de si es llamada para cambiar el estado a ACTIVO (5) o SALDADO (6) * \return : retorna un entero en caso que se necesite controlar ejecucion */ int modifyePrestamo(ePrestamo* ePrestamoArray, int arrayPLength, eCliente* eClienteArray, int arrayCLength, int option); /** * \brief : Permite dar de alta un prestamo * \param ePrestamo* : puntero de array de prestamos * \param arrayPLength: longitud del array de prestamos. * \param eCliente* : puntero de array de prestamos * \param arrayCLength: longitud del array de prestamos. * \return : retorna un entero en caso que se necesite controlar ejecucion */ int setePrestamo(ePrestamo* ePrestamoArray, int arrayPLength, eCliente* eClienteArray, int arrayCLength); /** * \brief : muestra los datos de un prestamo * \param eCliente* : puntero de array de clientes * \param arrayClenght: longitud del array de clientes * \param ePrestamo* : puntero de array de prestamos * \param arrayPLength: longitud del array de prestamos * \param eClienteIndex: indice de un cliente dado en el array de clientes * \param ePrestamoIndex: indice de un prestamos dado en el array de prestamos * \param fieldTitle1:puntero a char con mensaje a ser utilizado como titulo * \param fieldTitle2:puntero a char con mensaje a ser utilizado como titulo * \param fieldTitle3:puntero a char con mensaje a ser utilizado como titulo * \param fieldTitle4:puntero a char con mensaje a ser utilizado como titulo * \return : esta funcion no retorna nada. */ void showePrestamo(ePrestamo* ePrestamoArray, int arrayPLength,int ePrestamoIndex, eCliente* eClienteArray,int eClienteIndex, int arrayCLength , char* fieldTitle1, char* fieldTitle2, char* fieldTitle3,char* fieldTitle4); /** * \brief : setea en EMPTY el valor del campo isEmpty de un prestamo asociado a un cliente * \param ePrestamo* : puntero de array de prestamos * \param arrayPLength: longitud del array de prestamos. * \param id: entero con el id de cliente * \return : retorna un entero en caso que se necesite controlar ejecucion */ int deleteePrestamoByClienteId(ePrestamo* ePrestamoArray,int arrayPLength, int id); /** * \brief : muestra el cliente con mayor cantidad de prestamos saldados * \param ePrestamo* : puntero de array de prestamos * \param arrayPLength*: longitud del array de prestamos. * \param eCliente* : puntero de array de prestamos * \param arrayCLength: longitud del array de prestamos. * \param fieldTitle1:puntero a char con mensaje a ser utilizado como titulo * \param fieldTitle2:puntero a char con mensaje a ser utilizado como titulo * \param fieldTitle3:puntero a char con mensaje a ser utilizado como titulo * \param fieldTitle4:puntero a char con mensaje a ser utilizado como titulo * \param fieldTitle5:puntero a char con mensaje a ser utilizado como titulo * \return : retorna un entero en caso que se necesite controlar ejecucion */ int showListeClienteActivo(eCliente* eClienteArray, int arrayCLength, ePrestamo* ePrestamoArray, int arrayPLength, char* fieldTitle1, char* fieldTitle2, char* fieldTitle3,char* fieldTitle4, char* fieldTitle5); /** * \brief :arma el listado de prestamos activos * \param ePrestamo* : puntero de array de prestamos * \param arrayPLength: longitud del array de prestamos. * \param eCliente* : puntero de array de prestamos * \param arrayCLength: longitud del array de prestamos. * \return : retorna un entero en caso que se necesite controlar ejecucion */ int showListeClientePrestamosActivos(eCliente* eClienteArray, int arrayCLength,ePrestamo* ePrestamoArray, int arrayPLength); /** * \brief : cuenta la cantidad de prestamos activos de un determinado cliente * \param ePrestamo* : puntero de array de prestamos * \param arrayPLength*: longitud del array de prestamos. * \param idCliente: entero con el id de cliente * \return : retorna en contador de prestamos activos */ int countActive(ePrestamo* ePrestamoArray, int arrayPLength, int idCliente); /** * \brief :recorre el array de prestamos por cliente para mostrar el listado de prestamos activos por pantalla * \param ePrestamo* : puntero de array de prestamos * \param arrayPLength: longitud del array de prestamos. * \param eCliente* : puntero de array de prestamos * \param arrayCLength: longitud del array de prestamos. * \param fieldTitle1:puntero a char con mensaje a ser utilizado como titulo * \param fieldTitle2:puntero a char con mensaje a ser utilizado como titulo * \param fieldTitle3:puntero a char con mensaje a ser utilizado como titulo * \param fieldTitle4:puntero a char con mensaje a ser utilizado como titulo * \param fieldTitle5:puntero a char con mensaje a ser utilizado como titulo * \return : retorna un entero en caso que se necesite controlar ejecucion */ void showListePrestamoActivo(ePrestamo* ePrestamoArray, int arrayPLength, eCliente* eClienteArray, int arrayCLength , char* fieldTitle1, char* fieldTitle2, char* fieldTitle3,char* fieldTitle4,char* fieldTitle5); #endif /* LINKERSTRUCTURE_H_ */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_nm.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ademenet <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/12/13 15:49:57 by ademenet #+# #+# */ /* Updated: 2018/01/10 18:48:51 by ademenet ### ########.fr */ /* */ /* ************************************************************************** */ #include "./inc/ft_nm.h" int nm(char *ptr) { unsigned int magic_number; if (check(ptr)) return (set_type_error("1 File truncated or someway invalid.")); magic_number = *(int *)ptr; g_env.endianness = is_swap(magic_number); if (!ft_strncmp(ptr, ARMAG, SARMAG)) handle_lib(ptr); else if (magic_number == MH_MAGIC_64 || magic_number == MH_CIGAM_64) handle_64(ptr); else if (magic_number == MH_MAGIC || magic_number == MH_CIGAM) handle_32(ptr); else if (magic_number == FAT_MAGIC || magic_number == FAT_CIGAM) handle_fat(ptr); return (EXIT_SUCCESS); } static int iterate_over_files(void) { int fd; char *ptr; struct stat buf; if ((fd = open(g_env.file, O_RDONLY)) < 0) return (error_display("No such file or directory.")); if (fstat(fd, &buf) < 0) return (error_display("An error occured with fstat.")); if ((ptr = mmap(0, buf.st_size, PROT_READ, MAP_PRIVATE, fd, 0)) == MAP_FAILED) return (error_display("An error occured with mmap.")); g_env.buff_addr = ptr; g_env.buff_size = buf.st_size; if (nm(ptr)) return (error_display(NULL)); if (munmap(ptr, buf.st_size) < 0) return (error_display("An error occured with munmap.")); return (EXIT_SUCCESS); } int main(int ac, char **av) { int i; if (ac == 1) { g_env.file = "a.out"; if (iterate_over_files()) return (EXIT_FAILURE); } else { i = 0; while (++i < ac) { g_env.file = av[i]; if (ac > 2) ft_printf("\n%s:\n", g_env.file); if (iterate_over_files()) return (EXIT_FAILURE); } } return (EXIT_SUCCESS); }
C
#include <stdlib.h> #include <stdio.h> #include <limits.h> /* Linked list implementation of Stack- don't need to know exact size before building out the list Properties: 1. Push and Pop from the top O(1) 2. One struct for List Node and one struct for Stack itself */ // Remember linked lists are dynamic- useful for Stack where you don't know the size you want // structs are default public, classes are default private typedef struct ListNode { int data; struct ListNode *next; } ListNode; typedef struct Stack { unsigned int size; ListNode *list; } Stack; Stack* CreateStack() { // allocate memory for the Stack on the heap Stack *stack = malloc(sizeof(Stack)); stack->size = 0; // initial size of 0 stack->list = NULL; // initialize head of list to NULL return stack; } int pop (Stack** stack) { // check if stack is empty if ((*stack)->list == NULL) { return INT_MIN; } else { // save the value of the top node int top_value = (*stack)->list->data; ListNode *tmp = (*stack)->list; // remove the top element by connecting head pointer to second element (*stack)->list = ((*stack)->list)->next; // deallocate the ListNode memory free(tmp); // decrement size ((*stack)->size)--; // return the top node value return top_value; } } // Push from the top- 2 cases-> 1. Insert first element 2. Insert at top void push (Stack** stack, int element) { // allocate memory for 1 ListNode element ListNode *node = malloc(sizeof(ListNode)); // Set values of ListNode node->data = element; node->next = NULL; // add the new ListNode to the top of the Stack's list // 1. Current stack is empty if ((*stack)->list == NULL) { (*stack)->list = node; } else { // 2. Insert elment between head and current first element // save address of current first element ListNode *current_first = (*stack)->list; (*stack)->list = node; node->next = current_first; } ((*stack)->size)++; // increase size by 1 } void DisplayElements (Stack* stack) { if (stack != NULL) // check if stack is still allocated { // temporary pointer ListNode *tmp = stack->list; printf("Printing list: "); while(tmp != NULL) { printf("%d ", tmp->data); tmp = tmp->next; } printf("\n"); printf("Size of list: %u\n", stack->size); } else { printf("Stack was deallocated!\n"); } } // delete stack by deleting each node from the first node until list is NULL and then delete entire stack // make sure to set all freed pointers to NULL void DeleteStack (Stack** stack) { while ((*stack)->list != NULL) { ListNode *tmp = (*stack)->list; // remove the top element by connecting head pointer to second element (*stack)->list = ((*stack)->list)->next; // deallocate the ListNode memory free(tmp); } // when list has been completely deallocated, deallocate entire stack free(*stack); *stack = NULL; } int main() { Stack *new_stack = CreateStack(); DisplayElements(new_stack); push(&new_stack, 1); push(&new_stack, 4); push(&new_stack, 5); push(&new_stack, 8); DisplayElements(new_stack); int pop_value = pop(&new_stack); printf("Popped value: %d\n", pop_value); DisplayElements(new_stack); int pop_value2 = pop(&new_stack); printf("Popped value: %d\n", pop_value2); DisplayElements(new_stack); push(&new_stack, 20); push(&new_stack, 30); DisplayElements(new_stack); DeleteStack(&new_stack); DisplayElements(new_stack); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "stack.h" #define MAX 100 //number of items in stack char *stack[MAX]; //stack of strings(variables) int tos = -1; //top of stack int varct = -1; //the number of variables in that scope int block_varct[MAX]; int place = 0; //make the stack void build_stack(Node* parse_tree){ if(parse_tree == NULL){ //end of tree (at a leaf when function was called) return; } else if(strcmp(parse_tree->nonterminal, "program") == 0){ //go through first child (vars) build_stack(parse_tree->child1); //keep track of number of variables defined block_varct[place] = varct; place++; //add to place for more vartct's //go through second child (block) and so on build_stack(parse_tree->child2); build_stack(parse_tree->child3); build_stack(parse_tree->child4); //pop variables in global scope pop(parse_tree->token->instance); } else if(strcmp(parse_tree->nonterminal, "block") == 0){ //go through first child (vars) build_stack(parse_tree->child1); //keep track of number of variables defined block_varct[place] = varct; place++; //add to place for more vartct's //go through second child (stats) and so on build_stack(parse_tree->child2); build_stack(parse_tree->child3); build_stack(parse_tree->child4); // once done with a block // pop variables in that scope pop(parse_tree->token->instance); } else if(strcmp(parse_tree->nonterminal, "vars") == 0){ //start varct varct = -1; //put in stack push(parse_tree->token->instance, parse_tree->token); //go through first child (mvars) and so on build_stack(parse_tree->child1); build_stack(parse_tree->child2); build_stack(parse_tree->child3); build_stack(parse_tree->child4); } else if(strcmp(parse_tree->nonterminal, "mvars") == 0){ //put in stack push(parse_tree->token->instance, parse_tree->token); //go through first child (mvars) and so on build_stack(parse_tree->child1); build_stack(parse_tree->child2); build_stack(parse_tree->child3); build_stack(parse_tree->child4); } else if(strcmp(parse_tree->nonterminal, "R") == 0){ //see if token is identifier if(strcmp(check_id[parse_tree->token->id], "ID_tk") == 0){ //check to see if identifier has been defined if(find(parse_tree->token->instance) == -1) { printf("ERROR: '%s' not defined\n", parse_tree->token->instance); printf("Located at line %d\n", parse_tree->token->line); exit(0); } } //go through other nonterminals child and so on (don't care right now) //we only care about static semantics build_stack(parse_tree->child1); build_stack(parse_tree->child2); build_stack(parse_tree->child3); build_stack(parse_tree->child4); } else if(strcmp(parse_tree->nonterminal, "in") == 0){ //check to see if identifier has been defined if(find(parse_tree->token->instance) == -1) { printf("ERROR: '%s' not defined\n", parse_tree->token->instance); printf("Located at line %d\n", parse_tree->token->line); exit(0); } //go through other nonterminals child and so on (don't care right now) //we only care about static semantics build_stack(parse_tree->child1); build_stack(parse_tree->child2); build_stack(parse_tree->child3); build_stack(parse_tree->child4); } else if(strcmp(parse_tree->nonterminal, "assign") == 0){ //check to see if identifier has been defined if(find(parse_tree->token->instance) == -1) { printf("ERROR: '%s' not defined\n", parse_tree->token->instance); printf("Located at line %d\n", parse_tree->token->line); exit(0); } //go through other nonterminals child and so on (don't care right now) //we only care about static semantics build_stack(parse_tree->child1); build_stack(parse_tree->child2); build_stack(parse_tree->child3); build_stack(parse_tree->child4); } else { //go through other nonterminals child and so on (don't care right now) //we only care about static semantics build_stack(parse_tree->child1); build_stack(parse_tree->child2); build_stack(parse_tree->child3); build_stack(parse_tree->child4); } return; } void push(char* string, TOKEN *tk){ if(check_me(string) == 1){ //has not been defined if(tos == MAX - 1){ //stack overflow printf("ERROR stack overflow\n"); printf("Too many variables defined\n"); exit(0); } else { // have not reached MAX number in stack tos++; varct++; //printf("PUSH: %s\n", string); strcpy(stack[tos], string); return; } } else if(check_me(string) == -1){ //has already been defined ERROR printf("ERROR '%s' has already been defind in scope!\n", string); printf("Located at line: %d\n", tk->line); exit(0); } return; } void pop(char* string){ place--; if(tos == -1){ return; } else { if(place == 0){ //means we are done with local variables in blocks //pop the globals while(tos != -1){ //printf("\tGLOBAL_POP: %s\n", stack[tos]); tos--; } } else { //pop the locals while(block_varct[place] != -1){ //printf("\tPOP: %s\n", stack[tos]); tos--; block_varct[place]--; } } } return; } //check if defined more than once int check_me(char* string){ int check = 1; if(tos != -1){ //means we are not at the bottom of stack //stack_ct is the number of variables in that scope int stack_ct; stack_ct = varct; //scope is the place where we are at in the stack int scope = tos; while(stack_ct != -1){ //means variable has been defined in that scope if(strcmp(string, stack[scope]) == 0){ check = -1; } scope--; stack_ct--; } } return check; } //see if variable is in stack then if so //find the distance of a variable in the stack int find(char* string){ //if distance is -1 then not found //else found the variable int distance = -1; int count = 0; int top_of_stack = tos; //used to loop through stack while(top_of_stack != -1){ if(strcmp(string, stack[count]) == 0){ //found string distance = tos - count; //set distance from top of stack break; } count++; top_of_stack--; } return distance; } void print_stack(){ while(tos != 0){ printf("%s\n", stack[tos]); tos--; } return; }
C
#include <stddef.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "integer.h" #include "typeid.h" #include "endianess.h" static struct pbd_element_vtable integer_vtable; static int integer_to_buffer(pbd_conf conf, const pbd_element* e, char** buffer, size_t* size) { assert(e != NULL); assert(buffer != NULL); assert(size != NULL); assert(e->vtable->type == integer_vtable.type); pbd_integer* s = (pbd_integer*) &(*e); uint8_t type_id = pbd_type_best_integer(s->value); size_t sizeof_value = pbd_sizeof_integer_value(type_id); if (sizeof_value == 0) { return -1; } size_t full_size = SIZEOF_TYPE_ID + sizeof_value; *buffer = conf.mem_alloc(full_size); if (*buffer == NULL) { return -1; } *size = full_size; memcpy(*buffer, &type_id, SIZEOF_TYPE_ID); if (sizeof_value == sizeof(int8_t)) { int8_t tmp_value = (int8_t) s->value; memcpy(*buffer + SIZEOF_TYPE_ID, &tmp_value, sizeof_value); } else if (sizeof_value == sizeof(int16_t)) { int16_t tmp_value = (int16_t) s->value; memcpy(*buffer + SIZEOF_TYPE_ID, &tmp_value, sizeof_value); } else if (sizeof_value == sizeof(int32_t)) { int32_t tmp_value = (int32_t) s->value; memcpy(*buffer + SIZEOF_TYPE_ID, &tmp_value, sizeof_value); } else { memcpy(*buffer + SIZEOF_TYPE_ID, &s->value, sizeof_value); } return 0; } static int integer_from_buffer(pbd_conf conf, struct pbd_element* e, const char* buffer, pbd_type_id type_id, size_t* read_bytes) { assert(e != NULL); assert(buffer != NULL); assert(read_bytes != NULL); assert(type_id != pbd_type_unknown); assert(e->vtable->type == integer_vtable.type); size_t sizeof_value = pbd_sizeof_integer_value(type_id); if (sizeof_value == 0) { return -1; } buffer += *read_bytes; int64_t value; bool little_endian = pbd_is_little_endian(); if (sizeof_value == sizeof(int8_t)) { int8_t tmp_value; memcpy(&tmp_value, buffer + SIZEOF_TYPE_ID, sizeof_value); value = pbd_is_unsigned(type_id) ? (uint8_t) tmp_value : tmp_value; } else if (sizeof_value == sizeof(int16_t)) { int16_t tmp_value; memcpy(&tmp_value, buffer + SIZEOF_TYPE_ID, sizeof_value); tmp_value = pbd_get_uint16(little_endian, tmp_value); value = pbd_is_unsigned(type_id) ? (uint16_t) tmp_value : tmp_value; } else if (sizeof_value == sizeof(int32_t)) { int32_t tmp_value; memcpy(&tmp_value, buffer + SIZEOF_TYPE_ID, sizeof_value); tmp_value = pbd_get_uint32(little_endian, tmp_value); value = pbd_is_unsigned(type_id) ? (uint32_t) tmp_value : tmp_value; } else { memcpy(&value, buffer + SIZEOF_TYPE_ID, sizeof_value); value = pbd_get_uint64(little_endian, value); } pbd_integer_set(e, value); *read_bytes += SIZEOF_TYPE_ID + sizeof_value; return 0; } static struct pbd_element_vtable integer_vtable = { pbd_type_integer, integer_to_buffer, integer_from_buffer, NULL }; pbd_element* pbd_integer_new_custom(pbd_conf conf) { pbd_integer* s = conf.mem_alloc(sizeof(pbd_integer)); if (s == NULL) { return NULL; } s->element.vtable = &integer_vtable; return &s->element; } pbd_element* pbd_integer_new() { return pbd_integer_new_custom(pbd_default_conf); } pbd_element* pbd_integer_create_custom(pbd_conf conf, int64_t value) { pbd_element* e = pbd_integer_new_custom(conf); if (e == NULL) { return NULL; } pbd_integer_set(e, value); return e; } pbd_element* pbd_integer_create(int64_t value) { return pbd_integer_create_custom(pbd_default_conf, value); } void pbd_integer_set(pbd_element* e, int64_t value) { assert(e != NULL); assert(e->vtable->type == integer_vtable.type); pbd_integer* s = (pbd_integer*) &(*e); s->value = value; } int64_t pbd_integer_get(const pbd_element* e) { assert(e != NULL); assert(e->vtable->type == integer_vtable.type); const pbd_integer* s = (const pbd_integer*) &(*e); return s->value; }
C
#include <stdio.h> int GCD(int a, int b); int LCM(int a, int b); int main(void) { int n, sum_loop, sum_math; int counter; printf("This program add the numbers from zero to a given number\n"); printf("Introduce an integer number: "); scanf("%i", &n); counter = 0; while(counter <= n) { sum_loop = sum_loop + counter; counter++; } printf("The sum is %d\n", sum_loop); printf("The sum is %d\n", (n*(n+1))/2); return(0); }
C
/** ****************************************************************************** * @file USB_Device/HID_Standalone/Src/stm32f1xx_it.c * @brief Main Interrupt Service Routines. * This file provides template for all exceptions handler and * peripherals interrupt service routine. ****************************************************************************** */ #include "main.h" #include "Nucleo_F429.h" #include "stm32f4xx_it.h" // -- <1> Key¸¦ ´©¸¦¶§ Mouse Ä¿¼­ÀÇ À̵¿·®À» 5 ·Î Á¤ÀÇÇÔ #define CURSOR_STEP 5 extern void Toggle_Leds(void); extern USBD_HandleTypeDef USBD_Device; extern PCD_HandleTypeDef hpcd; extern uint32_t Joy_Key; // -- <2> ¸¶¿ì½ºÀÇ À̵¿·®À» ÀúÀåÇÏ´Â º¯¼ö uint8_t HID_Buffer[4]; static void GetMoveData(uint8_t *pbuf); // ----------------------------------------------------------------------------- // void SysTick_Handler(void) { static __IO uint32_t counter=0; HAL_IncTick(); // -- <3> HID Ŭ·¡½ºÀÇ Æú¸µ½Ã°£ ¼³Á¤°ª(10ms)ÀÌ µÇ¸é if ( counter++ == USBD_HID_GetPollingInterval(&USBD_Device) ) { // -- <3-1> ¸¶¿ì½ºÀÇ À̵¿·®(HID_Buffer)À» ¹Þ¾Æ¿Â´Ù GetMoveData(HID_Buffer); // -- <3-2> ¸¶¿ì½ºÀÇ À̵¿·®(HID_Buffer)ÀÌ 0ÀÌ ¾Æ´Ï¸é if ( (HID_Buffer[1] != 0) || (HID_Buffer[2] != 0) ) { // -- <3-3> HID_Buffer °ªÀ» PC·Î º¸³¿. USBD_HID_SendReport(&USBD_Device, HID_Buffer, 4); } counter =0; } // -- <4> LED¸¦ Toggle ½ÃÅ´ Toggle_LED(); } /******************************************************************************/ /* STM32F1xx Peripherals Interrupt Handlers */ /******************************************************************************/ // This function handles USB-On-The-Go FS global interrupt request. void OTG_FS_IRQHandler(void) { HAL_PCD_IRQHandler(&hpcd); } // This function handles USB OTG FS Wakeup IRQ Handler. void OTG_FS_WKUP_IRQHandler(void) { if((&hpcd)->Init.low_power_enable) { /* Reset SLEEPDEEP bit of Cortex System Control Register */ SCB->SCR &= (uint32_t)~((uint32_t)(SCB_SCR_SLEEPDEEP_Msk | SCB_SCR_SLEEPONEXIT_Msk)); // -- <5> System clockÀ» ¼³Á¤ // Configures system clock after wake-up from STOP */ SystemClock_Config(); /* ungate PHY clock */ __HAL_PCD_UNGATE_PHYCLOCK((&hpcd)); } /* Clear EXTI pending Bit*/ __HAL_USB_OTG_FS_WAKEUP_EXTI_CLEAR_FLAG(); } // ----------------------------------------------------------------------------- // // -- <6> MouseÀÇ À̵¿·® pbuf ¸¦ ¼³Á¤ÇÏ´Â ÇÔ¼ö static void GetMoveData(uint8_t *pbuf) { int8_t x = 0, y = 0 ; // -- <6-1> ´­·¯Áø KeyÀÇ Á¾·ù¿¡ µû¶ó ´ëÀÀµÇ´Â x, y °ªÀ» ¼³Á¤ÇÔ switch( Joy_Key ) { case JOY_LEFT: x -= CURSOR_STEP; //¸¶¿ì½º Ä¿¼­¸¦ ¿ÞÂÊÀ¸·Î 5 À̵¿ break; case JOY_RIGHT: x += CURSOR_STEP; //¸¶¿ì½º Ä¿¼­¸¦ ¿À¸¥ÂÊÀ¸·Î 5 À̵¿ break; case JOY_UP: y -= CURSOR_STEP; //¸¶¿ì½º Ä¿¼­¸¦ À§·Î 5 À̵¿ break; case JOY_DOWN: y += CURSOR_STEP; //¸¶¿ì½º Ä¿¼­¸¦ ¾Æ·¡·Î 5 À̵¿ break; case JOY_NONE: break; } // -- <6-2> pbufÀÇ °ªÀ» ¼³Á¤ÇÔ // pbuf[1] : x ¹æÇâ(¿À¸¥ÂÊ, ¿ÞÂÊ)À¸·Î À̵¿ÇÒ °ª // pbuf[2] : y ¹æÇâ(À§, ¾Æ·¡)À¸·Î À̵¿ÇÒ °ª pbuf[0] = 0; pbuf[1] = x; pbuf[2] = y; pbuf[3] = 0; } void EXTI0_IRQHandler(void) { // -- <3-1> GPIO_PIN_0¿¡¼­ EXTI°¡ ¹ß»ýÇÑ °æ¿ì´Â // ÇÔ¼ö HAL_GPIO_EXTI_Callback(GPIO_PIN_0) ¸¦ È£Ãâ HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_0); } // -------------------------------------------------------------------------------- // // -- <4> EXTI1 ÀÎÅÍ·´Æ®ÀÇ Çڵ鷯 ÇÔ¼ö void EXTI1_IRQHandler(void) { // -- <4-1> GPIO_PIN_1¿¡¼­ EXTI°¡ ¹ß»ýÇÑ °æ¿ì´Â // ÇÔ¼ö HAL_GPIO_EXTI_Callback(GPIO_PIN_1) ¸¦ È£Ãâ HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_1); } // -------------------------------------------------------------------------------- // // -- <5> EXTI2 ÀÎÅÍ·´Æ®ÀÇ Çڵ鷯 ÇÔ¼ö void EXTI2_IRQHandler(void) { // -- <5-1> GPIO_PIN_2¿¡¼­ EXTI°¡ ¹ß»ýÇÑ °æ¿ì´Â // ÇÔ¼ö HAL_GPIO_EXTI_Callback(GPIO_PIN_2) ¸¦ È£Ãâ HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_2); } // -------------------------------------------------------------------------------- // // -- <5> EXTI3 ÀÎÅÍ·´Æ®ÀÇ Çڵ鷯 ÇÔ¼ö void EXTI3_IRQHandler(void) { // -- <5-1> GPIO_PIN_3¿¡¼­ EXTI°¡ ¹ß»ýÇÑ °æ¿ì´Â // ÇÔ¼ö HAL_GPIO_EXTI_Callback(GPIO_PIN_3) ¸¦ È£Ãâ HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_3); } // -------------------------------------------------------------------------------- // // -- <6> EXTI13 ÀÎÅÍ·´Æ®ÀÇ Çڵ鷯 ÇÔ¼ö void EXTI15_10_IRQHandler(void) { // -- <6-1> GPIO_PIN_13¿¡¼­ EXTI°¡ ¹ß»ýÇÑ °æ¿ì´Â // ÇÔ¼ö HAL_GPIO_EXTI_Callback(GPIO_PIN_13) ¸¦ È£Ãâ HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_13); } // ----------------------------------------------------------------------------- //
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #define NUM_THREADS 11 #define FILE_NAME "test_case" int *sudoku[9]; int checkRow[9][9], checkCol[9][9], checkGrid[9][9]; FILE *stream; struct param{ int id; int valid; }; struct param validator[NUM_THREADS]; void *runner(struct param * p);/* threads call this function */ int main(int argc, char const *argv[]) { pthread_t workers[NUM_THREADS]; /* the thread identifier */ pthread_attr_t attr[NUM_THREADS]; /* set of thread attributes */ /* initialization */ if((stream = fopen(FILE_NAME, "r")) == NULL) { printf("open file failed\n"); return 0; } /* input sudoku from file */ for(int i = 0; i < 9; i++) { sudoku[i] = (int*) malloc(9*sizeof(int)); for(int j = 0; j < 9; j++) { checkCol[i][j] = checkRow[i][j] = checkGrid[i][j] = 0; fscanf(stream, "%d", &sudoku[i][j]); printf("%d ", sudoku[i][j]); } printf("\n"); } /* multithreading */ for(int i = 0; i < NUM_THREADS; i++) { /* set the default attributes of the thread */ pthread_attr_init(&attr[i]); validator[i].id = i; /* create the thread */ pthread_create(&workers[i], &attr[i], runner, &validator[i]); } for(int i = 0; i < NUM_THREADS; i++) { /* wait for the thread to exit */ pthread_join(workers[i], NULL); } for(int i = 0; i < NUM_THREADS; i++) { if(!validator[i].valid){ printf("invalid sudoku!\n"); return 0; } } printf("valid sudoku!\n"); return 0; } /* The thread will execute in this function */ void *runner(struct param *p) { if(p->id == 0) /* check row */ for(int i = 0; i < 9; i++) for(int j = 0; j < 9; j++) { if(checkRow[i][sudoku[i][j] - 1] == 1) { p->valid = 0; printf("find invalid row %d\n", i); pthread_exit(0); } checkRow[i][sudoku[i][j] - 1] = 1; } else if(p->id == 1) /* check column */ for(int j = 0; j < 9; j++) for(int i = 0; i < 9; i++) { if(checkCol[j][sudoku[i][j] - 1] == 1) { p->valid = 0; printf("find invalid column %d\n", j); pthread_exit(0); } checkCol[j][sudoku[i][j] - 1] = 1; } else { int grid = p->id - 2; int start_i = grid / 3 * 3, start_j = grid % 3 * 3; for(int i = start_i; i < start_i + 3; i++) for(int j = start_j; j < start_j + 3; j++) { if(checkGrid[grid][sudoku[i][j] - 1] == 1) { p->valid = 0; printf("find invalid grid %d\n", grid); pthread_exit(0); } checkGrid[grid][sudoku[i][j] - 1] = 1; } } p->valid = 1; pthread_exit(0); }
C
#include <pthread.h> struct pqueue_elem { void * data; struct pqueue_elem * next; } pqueue_elem; struct pqueue { pthread_mutex_t queue_lock; pthread_cond_t not_empty; int queue_end; int queue_size; struct pqueue_elem * qhead; struct pqueue_elem * qtail; }; static void pqueue_init(struct pqueue * queue) { queue->queue_end = 0; queue->qhead = NULL; queue->qtail = NULL; queue->queue_size = 0; pthread_mutex_init(&queue->queue_lock, NULL); pthread_cond_init(&queue->not_empty, NULL); } static void pqueue_release(struct pqueue * queue) { pthread_mutex_lock(&queue->queue_lock); // Mark the queue as ended queue->queue_end = 1; // Unblock all threads pthread_cond_broadcast(&queue->not_empty); pthread_mutex_unlock(&queue->queue_lock); } static void pqueue_push(struct pqueue * queue, void * usr_data) { pthread_mutex_lock(&queue->queue_lock); // Create list node and fill it in struct pqueue_elem * ne = (struct pqueue_elem *)malloc(sizeof(pqueue_elem)); ne->data = usr_data; ne->next = 0; // Non Null qtail pointer means we already have a ptr to the last elem // Null ptr means list is empty if (queue->qtail) queue->qtail->next = ne; else queue->qhead = ne; // qtail points to the newly created element queue->qtail = ne; queue->queue_size++; // Signal some other thread waiting in the queue pthread_cond_signal(&queue->not_empty); pthread_mutex_unlock(&queue->queue_lock); } // Push element in the front (typically used to give hi prio) static void pqueue_push_front(struct pqueue * queue, void * usr_data) { pthread_mutex_lock(&queue->queue_lock); struct pqueue_elem * ne = (struct pqueue_elem *)malloc(sizeof(pqueue_elem)); ne->data = usr_data; ne->next = queue->qhead; queue->qhead = ne; queue->queue_size++; // If list was empty now we have a last element if (!queue->qtail) queue->qtail = ne; // Signal some other thread waiting in the queue pthread_cond_signal(&queue->not_empty); pthread_mutex_unlock(&queue->queue_lock); } // Returns the fron element. If there is no element it blocks until there is any. // If the writing end of the queue is closed it returns NULL static void * pqueue_pop(struct pqueue * queue) { pthread_mutex_lock(&queue->queue_lock); void * udata = 0; while (1) { if (queue->qhead != 0) { struct pqueue_elem * h = queue->qhead; udata = queue->qhead->data; queue->qhead = queue->qhead->next; queue->queue_size--; if (!queue->qhead) queue->qtail = NULL; free(h); } if (udata == 0) { if (queue->queue_end == 0) // No work in the queue, wait here! pthread_cond_wait(&queue->not_empty,&queue->queue_lock); else break; // No work and we are told to finish working } else break; } pthread_mutex_unlock(&queue->queue_lock); return udata; } // Returns the element in the front or NULL if no element is present // It never blocks! static void * pqueue_pop_nonb(struct pqueue * queue) { pthread_mutex_lock(&queue->queue_lock); void * udata = 0; if (queue->qhead != 0) { struct pqueue_elem * h = queue->qhead; udata = queue->qhead->data; queue->qhead = queue->qhead->next; queue->queue_size--; if (!queue->qhead) queue->qtail = NULL; free(h); } pthread_mutex_unlock(&queue->queue_lock); return udata; } // Returns queue size static int pqueue_size(struct pqueue * queue) { pthread_mutex_lock(&queue->queue_lock); int size = queue->queue_size;; pthread_mutex_unlock(&queue->queue_lock); return size; } // Returns whether the queue has been marked as released (writer finished) static int pqueue_released(struct pqueue * queue) { pthread_mutex_lock(&queue->queue_lock); int res = queue->queue_end; pthread_mutex_unlock(&queue->queue_lock); return res; } // Sleeps until the queue has at least one element in it or the queue is released static void pqueue_wait(struct pqueue * queue) { pthread_mutex_lock(&queue->queue_lock); while (queue->qhead == 0 && !queue->queue_end) { pthread_cond_wait(&queue->not_empty,&queue->queue_lock); } pthread_mutex_unlock(&queue->queue_lock); }
C
// // main.c // 6.3.12 // // Created by 雅 on 2019/12/4. // Copyright © 2019 雅. All rights reserved. // #include <stdio.h> #include <ctype.h> void task0(void){ printf("Task0 is called!\n"); } void task1(void){ printf("Task1 is called!\n"); } void task2(void){ printf("Task2 is called!\n"); } void task3(void){ printf("Task3 is called!\n"); } void task4(void){ printf("Task4 is called!\n"); } void task5(void){ printf("Task5 is called!\n"); } void task6(void){ printf("Task6 is called!\n"); } void task7(void){ printf("Task7 is called!\n"); } void scheduler(void); void execute(void (*func[])(void),int number); int main(void) { scheduler(); return 0; } void scheduler(void){ int num[8]; int i=0,number; while (i<8&&isdigit(num[i]=getchar())) { num[i++]-='0'; } number=i; void (*func[number])(void); for (i=0; i<number; i++) { switch (num[i]) { case 0: func[i]=task0;break; case 1: func[i]=task1;break; case 2: func[i]=task2;break; case 3: func[i]=task3;break; case 4: func[i]=task4;break; case 5: func[i]=task5;break; case 6: func[i]=task6;break; case 7: func[i]=task7;break; } } execute(func, number); } void execute(void (*func[])(void),int number){ int j; for (j=0; j<number; j++) { func[j](); } }
C
#include <stdio.h> #include <math.h> int main(void){ int values[3]; int i,a,k,h; for(i=0;i<3;i++){ scanf("%d",&a); values[i]=a; } int x = values[0]; int z = values[2]; for(i=0; i>1-values[2];i--){ int j = values[2]+i-1; int left = floor( j * (x/(2.0*z)) ); int right = ceil( (x-1) + -j * (x/(2.0*z)) ); int dots = values[0] - left*2 -2; for(k=0;k<left;k++){ printf(" "); } if(i==0){ printf("#"); for(h=0;h<dots;h++){ printf("#"); } } else{ printf("#"); for(h=0;h<dots;h++){ printf("."); } } if(values[0]>1){ printf("#"); } printf("\n"); } for(i=0;i<values[0];i++){ printf("#"); } printf("\n"); }
C
/*SDSPIģʽʵļ*/ #include "SD_Drv.h" /*ʱ*/ void Delay_100us(void) { unsigned int i=8; while(i--) *P_Watchdog_Clear=0x0001; } //IOBڳʼ CS,DO,CLKΪߵƽ DIΪ޻ѵ void SPI_IO_Init(void) { unsigned int tmp; tmp=*P_IOB_Dir; tmp |= (SPI_CS+SPI_DOUT+SPI_CLK); tmp&=~SPI_DIN; *P_IOB_Dir=tmp; tmp=*P_IOB_Attrib; tmp|=(SPI_CS+SPI_DOUT+SPI_CLK+SPI_DIN); *P_IOB_Attrib=tmp; tmp=*P_IOB_Data; tmp|=(SPI_CS+SPI_DOUT+SPI_CLK+SPI_DIN); *P_IOB_Data=tmp; } /*SDһֽڵ*/ void SPI_Send_Byte(unsigned char Data) { unsigned int nCount; unsigned char Buffer; Buffer=Data; for(nCount=0;nCount<8;nCount++) { SPI_CLK_RESET(); //CLKõԱ if(Buffer&0x80) //Ϊ1 SPI_DOUT_SET(); //DOߵƽ else // SPI_DOUT_RESET(); //D0͵ƽ SPI_CLK_SET(); //ʱ Buffer=Buffer<<1; // CLKø } } /*SDȡһֽڵ*/ unsigned char SPI_Get_Byte(void) { unsigned char echo; unsigned int nCount; echo=0; for(nCount=0;nCount<8;nCount++) { echo=echo<<1; SPI_CLK_RESET(); //CLKõԱ SPI_CLK_SET(); //CLKø߲أȡ if(*P_IOB_Data & SPI_DIN) echo|=0x01; else echo&=0xfe; *P_Watchdog_Clear = 1; } return echo; } /*SD*/ unsigned char SPI_Send_Cmd(unsigned char *Cmd) { unsigned char tmp; unsigned char retry=0; unsigned char i; SPI_CS_SET(); //ֹSD SPI_Send_Byte(0xff); SPI_CS_RESET(); //ʹSDʹ for (i=0;i<6;i++) { SPI_Send_Byte(*Cmd++); } //8λĻӦ SPI_Get_Byte(); do { //ȡӦ tmp = SPI_Get_Byte(); retry++; } while((tmp==0xff)&&(retry<100)); return(tmp); } /*SDʼ*/ unsigned char SPI_Init(void) { unsigned char retry,temp; unsigned char i; //unsigned Init_Flag; unsigned char CMD[] = {0x40,0x00,0x00,0x00,0x00,0x95}; SPI_IO_Init(); //ʼ˿ Delay_100us(); for (i=0;i<16;i++) { SPI_Send_Byte(0xff); //74ʱź } SPI_CS_RESET(); //ʹSDʹ //SDCMD0 retry=0; do { //ΪܹɹдCMD0,д200 temp=SPI_Send_Cmd(CMD); retry++; if(retry==200) { //200 return(INIT_CMD0_ERROR);//CMD0 Error! } } while(temp!=1); //Ӧ01hֹͣд //CMD1SD CMD[0] = 0x41; //CMD1 CMD[5] = 0xFF; retry=0; do { //ΪܳɹдCMD1,д100 temp=SPI_Send_Cmd(CMD); retry++; if(retry==100) { //100 return(INIT_CMD1_ERROR);//CMD1 Error! } } while(temp!=0);//Ӧ00hֹͣд SPI_CS_SET(); //ʹSDƬѡЧ return(INIT_SUCCESSED); //ʼɹ } //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- unsigned char SD_write_sector(unsigned long addr,unsigned char *Buffer) { unsigned char tmp,retry; unsigned int i; //24 unsigned char CMD[] = {0x58,0x00,0x00,0x00,0x00,0xFF}; addr = addr << 9; //addr = addr * 512 CMD[1] = ((addr & 0xFF000000) >>24 ); CMD[2] = ((addr & 0x00FF0000) >>16 ); CMD[3] = ((addr & 0x0000FF00) >>8 ); //д24SDȥ retry=0; do { //Ϊ˿ɿд룬д100 tmp=SPI_Send_Cmd(CMD); retry++; if(retry==100) { return(tmp); //send commamd Error! } } while(tmp!=0); //д֮ǰȲ100ʱź for (i=0;i<100;i++) { SPI_Get_Byte(); } //д뿪ʼֽ SPI_Send_Byte(0xFE); //ڿд512ֽ for (i=0;i<512;i++) { SPI_Send_Byte(*Buffer++); } //CRC-Byte SPI_Send_Byte(0xFF); //Dummy CRC SPI_Send_Byte(0xFF); //CRC Code tmp=SPI_Get_Byte(); // read response if((tmp & 0x1F)!=0x05) // д512ֽδ { // SPI_CS_SET(); *P_IOB_Data|=SPI_CS; return(WRITE_BLOCK_ERROR); //Error! } //ȵSDæΪֹ //ΪݱܺSD򴢴б while (SPI_Get_Byte()!=0xff){}; //ֹSD // SPI_CS_SET(); *P_IOB_Data|=SPI_CS; return(0);//дɹ } //---------------------------------------------------------------------------- // ȡݵbuffer //---------------------------------------------------------------------------- void SD_get_data(unsigned int Bytes,unsigned char *buffer) { unsigned int j; for (j=0;j<Bytes;j++) *buffer++ = SPI_Get_Byte(); } //------------------------------- //һ //------------------------------------- unsigned char SD_Read_Sector(unsigned long sector,unsigned char *buffer) { unsigned char retry; //16 unsigned char CMD[] = {0x51,0x00,0x00,0x00,0x00,0xFF}; unsigned char temp; //ַ任 ߼ַתΪֽڵַ sector = sector << 9; //sector = sector * 512 CMD[1] = ((sector & 0xFF000000) >>24 ); CMD[2] = ((sector & 0x00FF0000) >>16 ); CMD[3] = ((sector & 0x0000FF00) >>8 ); //16дSD retry=0; do { //Ϊ˱֤д һд100 temp=SPI_Send_Cmd(CMD); retry++; if(retry==100) { return(READ_BLOCK_ERROR); //block write Error! } } while(temp!=0); while (SPI_Get_Byte() != 0xfe); readPos=0; SD_get_data(512,buffer) ; //512ֽڱbuffer return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { const char *mode; const char *hexstring; if (argc == 2) { mode = "-h"; hexstring = argv[1]; } else if (argc == 3) { mode = argv[1]; hexstring = argv[2]; } else { exit(1); } int color24 = (int)strtol(hexstring, NULL, 0); int red = (color24 & 0xFF0000) >> 16; int green = (color24 & 0xFF00) >> 8; int blue = color24 & 0xFF; red = (red * 249 + 1014) >> 11; green = (green * 253 + 505) >> 10; blue = (blue * 249 + 1014) >> 11; int color16 = color16 | (red << 11); color16 = color16 | (green << 5); color16 = color16 | blue; if (strcmp(mode, "-d") == 0) { printf("%i\n", color16); } else { printf("0x%04X\n", color16); } }
C
#include "lib_ccx.h" #include "ccx_common_option.h" #include "wtv_constants.h" #include "activity.h" #include "file_buffer.h" int check_stream_id(int stream_id, int video_streams[], int num_streams); int add_skip_chunks(struct ccx_demuxer *ctx, struct wtv_chunked_buffer *cb, uint32_t offset, uint32_t flag); void init_chunked_buffer(struct wtv_chunked_buffer *cb); uint64_t get_meta_chunk_start(uint64_t offset); uint64_t time_to_pes_time(uint64_t time); void add_chunk(struct wtv_chunked_buffer *cb, uint64_t value); int qsort_cmpint (const void * a, const void * b); void get_sized_buffer(struct ccx_demuxer *ctx, struct wtv_chunked_buffer *cb, uint32_t size); void skip_sized_buffer(struct ccx_demuxer *ctx, struct wtv_chunked_buffer *cb, uint32_t size); int read_header(struct ccx_demuxer *ctx, struct wtv_chunked_buffer *cb); // Helper function for qsort (64bit int sort) int qsort_cmpint (const void * a, const void * b) { if(a<b) return -1; if(a>b) return 1; return 0; } // Check if the passed stream_id is in the list of stream_ids we care about // Return true if it is. int check_stream_id(int stream_id, int video_streams[], int num_streams) { int x; for(x=0; x<num_streams; x++) if(video_streams[x]==stream_id) return 1; return 0; } // Init passes wtv_chunked_buffer struct void init_chunked_buffer(struct wtv_chunked_buffer *cb) { cb->count=0; cb->buffer=NULL; cb->buffer_size=0; int x; for(x=0; x<256; x++) cb->skip_chunks[x]=-1; } // Calculate the actual file offset of the passed skip value. uint64_t get_meta_chunk_start(uint64_t offset) { return offset*WTV_CHUNK_SIZE&WTV_META_CHUNK_MASK; } // Convert WTV time to PES time uint64_t time_to_pes_time(uint64_t time) { return ((time/10000)*90); } // Read the actual values of the passed lookup offset and add them to // the list of chunks to skip as necessary. Returns false on error. int add_skip_chunks(struct ccx_demuxer *ctx, struct wtv_chunked_buffer *cb, uint32_t offset, uint32_t flag) { uint32_t value; int64_t result; uint64_t start = ctx->past; buffered_seek(ctx, (int)((offset*WTV_CHUNK_SIZE) - start)); uint64_t seek_back=0-((offset*WTV_CHUNK_SIZE)-start); result = buffered_read(ctx, (unsigned char*)&value, 4); if(result!=4) return 0; seek_back-=4; while(value!=0) { dbg_print(CCX_DMT_PARSE, "value: %llx\n", get_meta_chunk_start(value)); result = buffered_read(ctx, (unsigned char*)&value, 4); if(result!=4) return 0; add_chunk(cb, get_meta_chunk_start(value)); seek_back-=4; } buffered_seek(ctx, (int)seek_back); return 1; } void add_chunk(struct wtv_chunked_buffer *cb, uint64_t value) { int x; for(x=0; x<cb->count; x++) if(cb->skip_chunks[x]==value) return; cb->skip_chunks[cb->count]=value; cb->count++; } // skip_sized_buffer. Same as get_sized_buffer, only without actually copying any data // in to the buffer. void skip_sized_buffer(struct ccx_demuxer *ctx, struct wtv_chunked_buffer *cb, uint32_t size) { if(cb->buffer!=NULL && cb->buffer_size>0) { free(cb->buffer); } cb->buffer=NULL; cb->buffer_size=0; uint64_t start = cb->filepos; if(cb->skip_chunks[cb->chunk]!=-1 && start+size>cb->skip_chunks[cb->chunk]) { buffered_seek(ctx, (int)((cb->skip_chunks[cb->chunk]-start)+(WTV_META_CHUNK_SIZE)+(size-(cb->skip_chunks[cb->chunk]-start)))); cb->filepos+=(cb->skip_chunks[cb->chunk]-start)+(WTV_META_CHUNK_SIZE)+(size-(cb->skip_chunks[cb->chunk]-start)); cb->chunk++; } else { buffered_seek(ctx, size); cb->filepos+=size; } ctx->past=cb->filepos; } // get_sized_buffer will alloc and set a buffer in the passed wtv_chunked_buffer struct // it will handle any meta data chunks that need to be skipped in the file // Will print error messages and return a null buffer on error. void get_sized_buffer(struct ccx_demuxer *ctx, struct wtv_chunked_buffer *cb, uint32_t size) { int64_t result; if(cb->buffer != NULL && cb->buffer_size > 0) { free(cb->buffer); } if(size > WTV_MAX_ALLOC) { mprint("\nRequested buffer of %i > %i bytes (WTV_MAX_ALLOC)!\n", size, WTV_MAX_ALLOC); cb->buffer = NULL; return; } cb->buffer = (uint8_t*)malloc(size); cb->buffer_size = size; uint64_t start = cb->filepos; if(cb->skip_chunks[cb->chunk] != -1 && (start + size) > cb->skip_chunks[cb->chunk]) { buffered_read(ctx, cb->buffer, (int)(cb->skip_chunks[cb->chunk]-start)); cb->filepos += cb->skip_chunks[cb->chunk]-start; buffered_seek(ctx, WTV_META_CHUNK_SIZE); cb->filepos += WTV_META_CHUNK_SIZE; result = buffered_read(ctx, cb->buffer+(cb->skip_chunks[cb->chunk]-start), (int)(size-(cb->skip_chunks[cb->chunk]-start))); cb->filepos += size-(cb->skip_chunks[cb->chunk]-start); cb->chunk++; } else { result = buffered_read(ctx, cb->buffer, size); cb->filepos += size; if(result != size) { free(cb->buffer); cb->buffer_size = 0; ctx->past = cb->filepos; cb->buffer = NULL; mprint("\nPremature end of file!\n"); return; } } ctx->past = cb->filepos; return; } // read_header will read all the required information from // the wtv header/root sections and calculate the skip_chunks. // If successful, will return with the file positioned // at the start of the data dir int read_header(struct ccx_demuxer *ctx, struct wtv_chunked_buffer *cb) { int64_t result; ctx->startbytes_avail = (int)buffered_read_opt(ctx, ctx->startbytes, STARTBYTESLENGTH); return_to_buffer(ctx, ctx->startbytes, ctx->startbytes_avail); uint8_t *parsebuf; parsebuf = (uint8_t*)malloc(1024); result = buffered_read(ctx, parsebuf,0x42); ctx->past+=result; if (result!=0x42) { mprint("\nPremature end of file!\n"); return CCX_EOF; } // Expecting WTV header if( !memcmp(parsebuf, WTV_HEADER, 16 ) ) { dbg_print(CCX_DMT_PARSE, "\nWTV header\n"); } else { mprint("\nMissing WTV header. Abort.\n"); return CCX_EOF; } //Next read just enough to get the location of the root directory uint32_t filelen; uint32_t root_dir; memcpy(&filelen, parsebuf+0x30, 4); dbg_print(CCX_DMT_PARSE, "filelen: %x\n", filelen); memcpy(&root_dir, parsebuf+0x38, 4); dbg_print(CCX_DMT_PARSE, "root_dir: %x\n", root_dir); //Seek to start of the root dir. Typically 0x1100 result = buffered_skip(ctx,(root_dir*WTV_CHUNK_SIZE)-0x42); ctx->past += (root_dir*WTV_CHUNK_SIZE)-0x42; if (result!=(root_dir*WTV_CHUNK_SIZE)-0x42) return CCX_EOF; // Read and calculate the meta data chunks in the file we need to skip over // while parsing the file. int end=0; while(!end) { result = buffered_read(ctx, parsebuf, 32); int x; for(x=0; x<16; x++) dbg_print(CCX_DMT_PARSE, "%02X ", parsebuf[x]); dbg_print(CCX_DMT_PARSE, "\n"); if (result!=32) { mprint("\nPremature end of file!\n"); free(parsebuf); return CCX_EOF; } ctx->past+=32; if( !memcmp(parsebuf, WTV_EOF, 16 )) { dbg_print(CCX_DMT_PARSE, "WTV EOF\n"); end=1; } else { uint16_t len; uint64_t file_length; memcpy(&len, parsebuf+16, 2); dbg_print(CCX_DMT_PARSE, "len: %x\n", len); memcpy(&file_length, parsebuf+24, 8); dbg_print(CCX_DMT_PARSE, "file_length: %x\n", file_length); if(len>1024) { mprint("Too large for buffer!\n"); free(parsebuf); return CCX_EOF; } result = buffered_read(ctx, parsebuf, len-32); if (result!=len-32) { mprint("Premature end of file!\n"); free(parsebuf); return CCX_EOF; } ctx->past+=len-32; // Read a unicode string uint32_t text_len; memcpy(&text_len, parsebuf, 4); //text_len is number of unicode chars, not bytes. dbg_print(CCX_DMT_PARSE, "text_len: %x\n", text_len); char *string; string = (char*)malloc(text_len+1); // alloc for ascii string[text_len]='\0'; for(x=0; x<text_len; x++) { memcpy(&string[x], parsebuf+8+(x*2), 1); // unicode converted to ascii } dbg_print(CCX_DMT_PARSE, "string: %s\n", string); // Ignore everything that doesn't contain the text ".entries." if(strstr(string, WTV_TABLE_ENTRIES)!=NULL) { uint32_t value; uint32_t flag; memcpy(&value, parsebuf+(text_len*2)+8, 4); memcpy(&flag, parsebuf+(text_len*2)+4+8, 4); dbg_print(CCX_DMT_PARSE, "value: %x\n", value); dbg_print(CCX_DMT_PARSE, "flag: %x\n", flag); if(!add_skip_chunks(ctx, cb, value, flag)) { mprint("Premature end of file!\n"); free(parsebuf); free(string); return CCX_EOF; } } free(string); } } // Our list of skip_chunks is now complete // Sort it (not sure if this is needed, but it doesn't hurt). qsort(cb->skip_chunks, cb->count, sizeof(uint64_t), qsort_cmpint); dbg_print(CCX_DMT_PARSE, "skip_chunks: "); int x; for(x=0; x<cb->count; x++) dbg_print(CCX_DMT_PARSE, "%llx, ", cb->skip_chunks[x]); dbg_print(CCX_DMT_PARSE, "\n"); // Seek forward to the start of the data dir // Typically 0x40000 result = buffered_skip(ctx,(int)((cb->skip_chunks[cb->chunk]+WTV_META_CHUNK_SIZE)-ctx->past)); cb->filepos = (cb->skip_chunks[cb->chunk]+WTV_META_CHUNK_SIZE); cb->chunk++; ctx->past = cb->filepos; free(parsebuf); return CCX_OK; } LLONG get_data(struct lib_ccx_ctx *ctx, struct wtv_chunked_buffer *cb, struct demuxer_data *data) { static int video_streams[32]; static int alt_stream; //Stream to use for timestamps if the cc stream has broken timestamps static int use_alt_stream = 0; static int num_streams = 0; int64_t result; struct lib_cc_decode *dec_ctx = update_decoder_list(ctx); while(1) { int bytesread = 0; uint8_t guid[16]; int x; uint32_t len; uint32_t pad; uint32_t stream_id; // Read the 32 bytes containing the GUID and length and stream_id info get_sized_buffer(ctx->demux_ctx, cb, 32); if(cb->buffer == NULL) return CCX_EOF; memcpy(&guid, cb->buffer, 16); // Read the GUID for(x=0; x<16; x++) dbg_print(CCX_DMT_PARSE, "%02X ", guid[x]); dbg_print(CCX_DMT_PARSE, "\n"); memcpy(&len, cb->buffer+16, 4); // Read the length len-=32; dbg_print(CCX_DMT_PARSE, "len %X\n", len); pad = len%8==0 ? 0 : 8- (len % 8); // Calculate the padding to add to the length // to get to the next GUID dbg_print(CCX_DMT_PARSE, "pad %X\n", pad); memcpy(&stream_id, cb->buffer+20, 4); stream_id = stream_id & 0x7f; // Read and calculate the stream_id dbg_print(CCX_DMT_PARSE, "stream_id: 0x%X\n", stream_id); for(x=0; x<num_streams; x++) dbg_print(CCX_DMT_PARSE, "video stream_id: %X\n", video_streams[x]); if( !memcmp(guid, WTV_EOF, 16 )) { // This is the end of the data in this file // read the padding at the end of the file // and return one more byte uint8_t *parsebuf; dbg_print(CCX_DMT_PARSE, "WTV EOF\n"); parsebuf = (uint8_t*)malloc(1024); do { result = buffered_read(ctx->demux_ctx, parsebuf, 1024); ctx->demux_ctx->past+=1024; } while (result==1024); ctx->demux_ctx->past+=result; free(parsebuf); free(cb->buffer); cb->buffer=NULL; //return one more byte so the final percentage is shown correctly *(data->buffer+data->len)=0x00; data->len++; return CCX_EOF; } if( !memcmp(guid, WTV_STREAM2, 16 ) ) { // The WTV_STREAM2 GUID appares near the start of the data dir // It maps stream_ids to the type of stream dbg_print(CCX_DMT_PARSE, "WTV STREAM2\n"); get_sized_buffer(ctx->demux_ctx, cb, 0xc+16); if(cb->buffer==NULL) return CCX_EOF; static unsigned char stream_type[16]; memcpy(&stream_type, cb->buffer+0xc, 16); //Read the stream type GUID const void *stream_guid; if(ccx_options.wtvmpeg2) stream_guid = WTV_STREAM_VIDEO; // We want mpeg2 data if the user set -wtvmpeg2 else stream_guid = WTV_STREAM_MSTVCAPTION; // Otherwise we want the MSTV captions stream if(!memcmp(stream_type, stream_guid, 16 ) ) { video_streams[num_streams]=stream_id; // We keep a list of stream ids num_streams++; // Even though there should only be 1 } if (memcmp(stream_type, WTV_STREAM_AUDIO, 16)) alt_stream = stream_id; len-=28; } if (!memcmp(guid, WTV_TIMING, 16) && ((use_alt_stream < WTV_CC_TIMESTAMP_MAGIC_THRESH && check_stream_id(stream_id, video_streams, num_streams)) || (use_alt_stream == WTV_CC_TIMESTAMP_MAGIC_THRESH && stream_id == alt_stream))) { int64_t time; // The WTV_TIMING GUID contains a timestamp for the given stream_id dbg_print(CCX_DMT_PARSE, "WTV TIMING\n"); get_sized_buffer(ctx->demux_ctx, cb, 0x8+0x8); if(cb->buffer==NULL) return CCX_EOF; memcpy(&time, cb->buffer+0x8, 8); // Read the timestamp dbg_print(CCX_DMT_PARSE, "TIME: %ld\n", time); if (time != -1 && time != WTV_CC_TIMESTAMP_MAGIC) { // Ignore -1 timestamps set_current_pts(dec_ctx->timing, time_to_pes_time(time)); dec_ctx->timing->pts_set=1; frames_since_ref_time = 0; set_fts(dec_ctx->timing); } else if (time == WTV_CC_TIMESTAMP_MAGIC && stream_id != alt_stream) { use_alt_stream++; mprint("WARNING: %i WTV_CC_TIMESTAMP_MAGIC detected in cc timestamps. \n", use_alt_stream); if (use_alt_stream == WTV_CC_TIMESTAMP_MAGIC_THRESH) mprint("WARNING: WTV_CC_TIMESTAMP_MAGIC_THRESH reached. Switching to alt timestamps!\n"); } len-=16; } if( !memcmp(guid, WTV_DATA, 16 ) && check_stream_id(stream_id, video_streams, num_streams) && dec_ctx->timing->current_pts != 0 && (ccx_options.wtvmpeg2 || (!ccx_options.wtvmpeg2 && len==2))) { // This is the data for a stream we want to process dbg_print(CCX_DMT_PARSE, "\nWTV DATA\n"); get_sized_buffer(ctx->demux_ctx, cb, len); if(cb->buffer==NULL) return CCX_EOF; memcpy(data->buffer+data->len, cb->buffer, len); data->len += len; bytesread+=(int) len; frames_since_ref_time++; set_fts(dec_ctx->timing); if(pad>0) { //Make sure we skip any padding too, since we are returning here skip_sized_buffer(ctx->demux_ctx, cb, pad); } return bytesread; } if(len+pad>0) { // skip any remaining data // For any unhandled GUIDs this will be len+pad // For others it will just be pad skip_sized_buffer(ctx->demux_ctx, cb, len+pad); } } } int wtv_get_more_data(struct lib_ccx_ctx *ctx, struct demuxer_data ** ppdata) { static struct wtv_chunked_buffer cb; int ret = CCX_OK; struct demuxer_data *data; if(!*ppdata) { *ppdata = alloc_demuxer_data(); if(!*ppdata) return -1; data = *ppdata; //TODO Set to dummy, find and set actual value data->program_number = 1; data->stream_pid = 1; data->codec = CCX_CODEC_ATSC_CC; } else { data = *ppdata; } if(firstcall) { init_chunked_buffer(&cb); if(ccx_options.wtvmpeg2) data->bufferdatatype=CCX_PES; else data->bufferdatatype=CCX_RAW; read_header(ctx->demux_ctx, &cb); if(ret != CCX_OK) { // read_header returned an error // read_header will have printed the error message return ret; } firstcall=0; } ret = get_data(ctx, &cb, data); return ret; }
C
/** * ptr2-sln.c - Re-implementing strlen (Solution) * * Computer Science 50 * Week 5 * * Eric Ouyang <[email protected]> * Frederick Widjaja <[email protected]> */ #include <stdio.h> int length(char* str); int main(void) { printf("%d\n", length("Hello, world")); printf("%d\n", length("42")); printf("%d\n", length("Amazing")); } // calculates the length of a string, or zero if str is NULL int length(char* str) { if (str == NULL) { return 0; } int count = 0; // initialization is omitted, since we initalize count on line 30 for (; *(str + count) != '\0'; count++); return count; }
C
// // main.c // aps105-str // // Created by Baochun Li on 2017-03-10. // Copyright © 2017 Baochun Li. All rights reserved. // #include <stdio.h> int main(void) { const int LENGTH = 5; // Declaring and initializing a string as a character array char str[LENGTH + 1]; str[0] = 'H'; str[1] = 'e'; str[2] = 'l'; str[3] = 'l'; str[4] = 'o'; str[5] = '\0'; printf("str = %s\n", str); // An alternative that is simpler char s[] = "Hello"; printf("s = %s\n", s); // If you declare the string without enough space, // such as char s[4] = "Hello"; // it will be a compile-time warning and run-time error. // Declaring and initializing a string as a character pointer // What if we change it to the following: // const char *t = "Hello"; // changeable pointer to constant characters // char * const t = "Hello"; // constant pointer to changeable characters // const char * const t = "Hello"; // constant pointer to constant characters // What will happen at compile time with the following code? char *t = "Hello"; printf("t = %s\n", t); // You can change the characters in the string s s[1] = 'E'; printf("s = %s\n", s); // You can change the pointer variable t to point to another string t = "World"; printf("t = %s\n", t); // But you cannot change s to point to another string // such as: s = "HELLO"; // It will be a compile-time error: array type is not assignable // In addition, you cannot change characters in the string pointed to by t // such as: t[1] = 'e'; // It may cause a segmentation fault or bus error (on Mac OS X) // at run time. // Compare the pointer values to see where these strings are printf("The pointer variable s: %p\n", s); printf("The pointer variable t: %p\n", t); t = s; printf("t = %s\n", t); // Now that t points to s, we can safely change the characters t[2] = 'L'; printf("t = %s\n", t); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_conversion_tools.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lprior <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/02/09 18:34:47 by lprior #+# #+# */ /* Updated: 2018/02/17 23:14:31 by lprior ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" char *ft_otoa(unsigned long int number) { char *print; unsigned int i; i = 0; print = ft_strnew(24); if (number < i) return ("errno: Unsigned Only!"); if (number == 0) { print[i] = '0'; i++; } while (number) { print[i] = (number % 8) + 48; number /= 8; i++; } print[i] = '\0'; return (ft_strrev(print)); } char *ft_ptoa(unsigned long int number, t_flags *tools) { char *print; int i; i = 0; print = ft_strnew(12); if (number == 0) print[i] = '0'; while (number && tools->brand == 'p') { print[i++] = "0123456789abcdef"[number % 16]; number /= 16; } return (ft_strrev(print)); } char *ft_htoa(unsigned long int number, t_flags *tools) { char *print; int i; i = 0; print = ft_strnew(18); if (number == 0) print[i] = '0'; while (number && tools->brand == 'x') { print[i++] = "0123456789abcdef"[number % 16]; number /= 16; } while (number && tools->brand == 'X') { print[i++] = "0123456789ABCDEF"[number % 16]; number /= 16; } return (ft_strrev(print)); } char *ft_ullitoa(unsigned long long int number) { unsigned long long int tmp; unsigned int count; char *str; count = 1; tmp = number; while (tmp /= 10) count++; if (!(str = ft_strnew(count))) return (NULL); while (count--) { str[count] = number >= 10 ? (number % 10) + 48 : number + 48; number /= 10; } str[ft_strlen(str)] = '\0'; return (str); } char *ft_uitoa(unsigned int nbr) { unsigned int tmp; unsigned int count; char *str; count = 1; tmp = nbr; while (tmp /= 10) count++; if (!(str = ft_strnew(count))) return (NULL); while (count--) { str[count] = nbr >= 10 ? (nbr % 10) + 48 : nbr + 48; nbr /= 10; } str[ft_strlen(str)] = '\0'; return (str); }
C
#include <stdio.h> #include <sys/socket.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <string.h> #include <errno.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdint.h> #include <sys/types.h> #include <sys/wait.h> #include <fcntl.h> #include <sys/stat.h> #include "types.h" void usage() { char *usage_str = "cmdserver version 0.0.4\n" " Usage: cmdserver [hp]\n" " -h print this message\n" " -p remote port\n" "\n"; fprintf(stdout, "%s\n", usage_str); } void killer(int num) { sigset_t set, oldset; pid_t pid; int status, exitstatus; sigemptyset(&set); sigaddset(&set, SIGCHLD); sigprocmask(SIG_BLOCK, &set, &oldset); while( (pid = waitpid((pid_t) -1, &status, WNOHANG))>0) { if(WIFEXITED(status)) { exitstatus = WEXITSTATUS(status); fprintf(stderr, "Child process exited, pid=%d, exit status=%d\n", (int)pid, exitstatus); } else if(WIFSIGNALED(status)) { exitstatus = WTERMSIG(status); fprintf(stderr, "Child process terminated by signal %d, pid = %d\n", exitstatus, (int) pid); } else if(WIFSTOPPED(status)) { exitstatus = WSTOPSIG(status); fprintf(stderr, "Child process stopped by signal %d, pid = %d\n", exitstatus, (int) pid); } else { fprintf(stderr, "Child process misteriously dead, pid = %d\n", (int) pid); } } signal(SIGCHLD, killer); sigemptyset(&set); sigaddset(&set, SIGCHLD); sigprocmask(SIG_UNBLOCK, &set, &oldset); } int daemonize() { int fd; switch (fork()) { case -1: fprintf(stdout, "Error in fork\n"); return (-1); case 0: break; default: exit(-1); } if(setsid() == -1) { fprintf(stdout, "Error in setsid\n"); return -1; } if((fd = open("/dev/null", O_RDWR, 0)) != -1) { (void)dup2(fd, STDIN_FILENO); (void)dup2(fd, STDOUT_FILENO); (void)dup2(fd, STDERR_FILENO); if(fd > STDERR_FILENO) (void)close(fd); } return 0; } int main(int argc, char *argv[]) { int c, retc; char *port_string = NULL; int soc = -1; struct sockaddr_in local; #define SERVER_PORT 12000 int port = SERVER_PORT; if(signal(SIGCHLD, killer) == SIG_ERR) { fprintf(stderr, "Error: %s\n", strerror(errno)); goto outError; } while ((c = getopt(argc, argv, "hp:")) != EOF) { switch(c) { case 'h': usage(); goto outError; case 'p': port_string = optarg; break; default: goto outError; } } if(port_string != NULL) { port = atoi(port_string); if(port < 0 || port > 65535) { fprintf(stderr, "Invalid server port\n"); goto outError; } } if (daemonize() < 0) { fprintf(stderr, "Failed to daemonize: %s\n", strerror(errno)); goto outError; } local.sin_family = PF_INET; local.sin_port = htons((short) port); local.sin_addr.s_addr = INADDR_ANY; soc = socket(PF_INET, SOCK_STREAM, 0); if( soc == -1 ) { fprintf(stderr, "Cannot create socket\n"); goto outError; } int val = 1; if(setsockopt(soc, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) == -1) { fprintf(stderr, "Cannot set socket option: %s\n", strerror(errno)); goto outError; } if(bind(soc, (struct sockaddr*) &local, sizeof(local)) == -1) { fprintf(stderr, "Cannot bind socket\n"); goto outError; } if( (retc = listen(soc, 1)) == -1) { fprintf(stderr, "Error during listen\n"); close(soc); goto outError; } while(1) { struct sockaddr_in remote; socklen_t remsize = sizeof(remote); int connectsoc = -1; if( (retc = connectsoc = accept(soc, (struct sockaddr *) &remote, &remsize)) == -1) { fprintf(stderr,"Error in accpt\n"); break; } int pid = fork(); if( !pid ) { fprintf(stdout, "Connected [%s,%u] -> %u\n", inet_ntoa(remote.sin_addr), (unsigned int) ntohs(remote.sin_port), (unsigned int) ntohs(local.sin_port)); // grab first four bytes: // [0-1] encode types, 0 command, 1 path to save file // [2-3] length of command or file name #define INIT_BUFFER_LENGTH 4 char initbuffer[INIT_BUFFER_LENGTH]; int to_read = 4; int offset = 0; char *varbuffer = NULL; type_t type; int len, retc; FILE *fptr = NULL; while(to_read > 0) { retc = read(connectsoc, initbuffer + offset, to_read); if(retc == -1) { fprintf(stderr, "Receive error or unexpected termination: %s\n", strerror(errno)); goto terminate; } to_read -= retc; offset += retc; } type = (type_t) ntohs(*(uint16_t*) initbuffer); len = ntohs(*(uint16_t*) (initbuffer + 2)); fprintf(stdout, "type = %d, len = %d\n", (int) type, len); varbuffer = malloc(len + 1); if(varbuffer == NULL) { fprintf(stderr, "Cannot allocate memory for temp buffer\n"); goto terminate; } // now try to drain the requested number of bytes to_read = len; offset = 0; while(to_read > 0) { retc = read(connectsoc, varbuffer + offset, to_read); if(retc == -1) { fprintf(stderr, "Receive error or unexpected termination: %s\n", strerror(errno)); goto terminate; } to_read -= retc; offset += retc; } varbuffer[len] = 0; if(type == T_TFILE && len > 0) { chunk ck; fptr = fopen(varbuffer, "rb"); if(!fptr) { char errmsg[] = "Can not open file for reading\n"; ck.type = C_MSG; snprintf(ck.data, CHUNK_DATA_SIZE, "%s", errmsg); ck.len = strlen(ck.data); fprintf(stderr, "%s", errmsg); send(connectsoc, &ck, sizeof(ck), 0); goto terminate; } int running = 1; while(running) { int byteread = fread(ck.data, 1, CHUNK_DATA_SIZE, fptr); ck.len = 0; if(byteread > 0) { ck.type = C_DATA; ck.len = byteread; } else { if(feof(fptr)) running = 0; else if(ferror(fptr)) { char errmsg[] = "Error during read\n"; ck.type = C_MSG; snprintf(ck.data, CHUNK_DATA_SIZE, "%s", errmsg); fprintf(stderr, "%s", errmsg); ck.len = strlen(ck.data); running = 0; } } if(ck.len > 0) send(connectsoc, &ck, sizeof(ck), 0); } goto terminate; } if(type == T_RFILE && len > 0) { fptr = fopen(varbuffer, "wb"); if(!fptr) { char errmsg[] = "Can not open file for writing\n"; fprintf(stderr, "%s", errmsg); send(connectsoc, errmsg, strlen(errmsg), 0); goto terminate; } while(1) { #define BUFFER_LENGTH 2048 char buffer[BUFFER_LENGTH]; retc = read(connectsoc, buffer, BUFFER_LENGTH); if(retc == -1) { char errmsg[] = "Error during read\n"; fprintf(stderr, "%s", errmsg); send(connectsoc, errmsg, strlen(errmsg), 0); goto terminate; } if(retc == 0) break; if(fwrite(buffer, 1, retc, fptr) < retc) { char errmsg[] = "Error during write\n"; fprintf(stderr, "%s", errmsg); send(connectsoc, errmsg, strlen(errmsg), 0); goto terminate; } } goto terminate; } if(type == T_COMMAND && len > 0) { #define MAX_PARS 128 char *args[MAX_PARS]; int _read_fd[2] = {-1, -1}; int _write_fd[2] = {-1, -1}; char *start_buffer = varbuffer; int par = 0; // if a shell is available then start the command using it struct stat shellstat; #define CMDPATH "/bin/bash" int ret = stat(CMDPATH, &shellstat); if(ret == 0 && ((shellstat.st_mode & S_IXUSR) != 0)) { args[0] = CMDPATH; args[1] = "-c"; args[2] = start_buffer; args[3] = NULL; } else { char *token; while( (token = strsep(&start_buffer, " ")) != NULL && par < MAX_PARS) { if( (int) strlen(token) != 0) { args[par] = token; par++; } } args[par] = NULL; if(par == MAX_PARS) { fprintf(stderr, "Too many parameters in the command, failure\n"); goto exitFinal; } } int kk; for(kk = 0; kk < par; kk++) printf("token %d, len = %d: %s\n", kk, (int) strlen(args[kk]), args[kk]); if(socketpair(AF_UNIX, SOCK_STREAM, 0, _write_fd) < 0 || socketpair(AF_UNIX, SOCK_STREAM, 0, _read_fd) < 0) { fprintf(stderr, "Error on socket\n"); goto exitFinal; } int pid2; if( ! (pid2 = fork()) ) { close(soc); close(connectsoc); // to be checked dup2(_read_fd[1] ,STDOUT_FILENO); dup2(_read_fd[1] ,STDERR_FILENO); dup2(_write_fd[1],STDIN_FILENO); close(_read_fd[0]); close(_read_fd[1]); close(_write_fd[0]); close(_write_fd[1]); execvp(args[0], args); fprintf(stderr, "Error: %s\n", strerror(errno)); return -1; } close(_read_fd[1]); close(_write_fd[1]); char buffer[2048]; while(1) { int retc = read(_read_fd[0], buffer, 2048); if(retc == -1) { fprintf(stderr, "Error: %s\n", strerror(errno)); goto exitFinal; } if(retc == 0) break; retc = send(connectsoc, buffer, retc, 0); if(retc == -1) { fprintf(stderr, "Error in sending back to client\n"); goto exitFinal; } } exitFinal: close(_write_fd[0]); close(_read_fd[0]); } terminate: close(connectsoc); if(varbuffer != NULL) free(varbuffer); if(fptr != NULL) fclose(fptr); exit(-1); } close(connectsoc); fprintf(stdout, "Waiting a new one\n"); } return 0; outError: return -1; }
C
/* * CS:APP Data Lab * * < Mertcan Asgun 63948 > * * bits.c - Source file with your solutions to the Lab. * This is the file you will hand in to your instructor. * * WARNING: Do not include the <stdio.h> header; it confuses the dlc * compiler. You can still use printf for debugging without including * <stdio.h>, although you might get a compiler warning. In general, * it's not good practice to ignore compiler warnings, but in this * case it's OK. */ #if 0 /* * Instructions to Students: * * STEP 1: Read the following instructions carefully. */ You will provide your solution to the Data Lab by editing the collection of functions in this source file. INTEGER CODING RULES: Replace the "return" statement in each function with one or more lines of C code that implements the function. Your code must conform to the following style: int Funct(arg1, arg2, ...) { /* brief description of how your implementation works */ int var1 = Expr1; ... int varM = ExprM; varJ = ExprJ; ... varN = ExprN; return ExprR; } Each "Expr" is an expression using ONLY the following: 1. Integer constants 0 through 255 (0xFF), inclusive. You are not allowed to use big constants such as 0xffffffff. 2. Function arguments and local variables (no global variables). 3. Unary integer operations ! ~ 4. Binary integer operations & ^ | + << >> Some of the problems restrict the set of allowed operators even further. Each "Expr" may consist of multiple operators. You are not restricted to one operator per line. You are expressly forbidden to: 1. Use any control constructs such as if, do, while, for, switch, etc. 2. Define or use any macros. 3. Define any additional functions in this file. 4. Call any functions. 5. Use any other operations, such as &&, ||, -, or ?: 6. Use any form of casting. 7. Use any data type other than int. This implies that you cannot use arrays, structs, or unions. You may assume that your machine: 1. Uses 2s complement, 32-bit representations of integers. 2. Performs right shifts arithmetically. 3. Has unpredictable behavior when shifting an integer by more than the word size. EXAMPLES OF ACCEPTABLE CODING STYLE: /* * pow2plus1 - returns 2^x + 1, where 0 <= x <= 31 */ int pow2plus1(int x) { /* exploit ability of shifts to compute powers of 2 */ return (1 << x) + 1; } /* * pow2plus4 - returns 2^x + 4, where 0 <= x <= 31 */ int pow2plus4(int x) { /* exploit ability of shifts to compute powers of 2 */ int result = (1 << x); result += 4; return result; } FLOATING POINT CODING RULES For the problems that require you to implent floating-point operations, the coding rules are less strict. You are allowed to use looping and conditional control. You are allowed to use both ints and unsigneds. You can use arbitrary integer and unsigned constants. You are expressly forbidden to: 1. Define or use any macros. 2. Define any additional functions in this file. 3. Call any functions. 4. Use any form of casting. 5. Use any data type other than int or unsigned. This means that you cannot use arrays, structs, or unions. 6. Use any floating point data types, operations, or constants. NOTES: 1. Use the dlc (data lab checker) compiler (described in the handout) to check the legality of your solutions. 2. Each function has a maximum number of operators (! ~ & ^ | + << >>) that you are allowed to use for your implementation of the function. The max operator count is checked by dlc. Note that '=' is not counted; you may use as many of these as you want without penalty. 3. Use the btest test harness to check your functions for correctness. 4. Use the BDD checker to formally verify your functions 5. The maximum number of ops for each function is given in the header comment for each function. If there are any inconsistencies between the maximum ops in the writeup and in this file, consider this file the authoritative source. /* * STEP 2: Modify the following functions according the coding rules. * * IMPORTANT. TO AVOID GRADING SURPRISES: * 1. Use the dlc compiler to check that your solutions conform * to the coding rules. * 2. Use the BDD checker to formally verify that your solutions produce * the correct answers. */ #endif /* Copyright (C) 1991-2012 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* We do support the IEC 559 math functionality, real and complex. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ /* * isZero - returns 1 if x == 0, and 0 otherwise * Examples: isZero(5) = 0, isZero(0) = 1 * Legal ops: ! ~ & ^ | + << >> * Max ops: 2 * Rating: 1 */ int isZero(int x) { // If number is zero, negation of it gives 1. Otherwise it gives 0. return !x ; } /* * implication - return x -> y in propositional logic - 0 for false, 1 * for true * Example: implication(1,1) = 1 * implication(1,0) = 0 * Legal ops: ! ~ ^ | * Max ops: 5 * Rating: 2 */ int implication(int x, int y) { // In only one condition, implication returns 0, which is (1,0) return (!x)|y; } /* * twoDigitNumberInBaseFour - return integer equivalent of (xy)_4 two digit number in base 4 * Example: twoDigitNumberInBaseFour(2, 3) = 11 * Legal ops: >> << + * Max ops: 4 * Rating: 2 */ unsigned twoDigitNumberInBaseFour(unsigned x, unsigned y) { // We have to find 4*x+y. So we will shift x to the left 2 times and add y. return (x << 2) + y; } /* * multThreeEighths - multiplies by 3/8 rounding toward 0. * Should exactly duplicate effect of C expression (x*3/8), * including overflow behavior. * Examples: multThreeEighths(77) = 28 * multThreeEighths(-22) = -8 * Legal ops: ! ~ & ^ | + << >> * Max ops: 12 * Rating: 3 */ int multThreeEighths(int x) { // Details can be found after each line int value= 0 ; int signCheckXOR = 0; int signCheck = 0; signCheckXOR = (x>>31); // 11...11 if negative, 00...00 if positive signCheck = (signCheckXOR & 1) ; // 1 if negative, 0 if positive x = ( x ^ signCheckXOR ) + signCheck ; // Kind of absolute value - Simply 2's complement for negatives value = x + (x<<1) ; // Multiply by 3 value = value >> 3 ; // Divide by 8 return ( value ^ signCheckXOR) + signCheck ; // If number was negative, this works as 2's complement. // But I think the following code is more accurate. However it requires 14 operation, that is why I do // not submit this one, but still wanted to put it here. // In this one, to prevent overflow we will first use division instead of multiplication. But because of this // we will lose access to the last three bits of x. Therefore we are saving them as remainder before. /* int value= 0 ; int remainder= 0 ; int signCheckXOR = 0; int signCheck = 0; signCheckXOR = (x>>31); // 11...11 if negative, 00...00 if positive signCheck = (signCheckXOR & 1) ; // 1 if negative, 0 if positive x = ( x ^ signCheckXOR ) + signCheck ; // Kind of absolute value - Simply 2's complement remainder = (x & 7); // Save last 3 digits (7 = 0b0111) value = x >> 3; value = value + (value << 1); remainder = (remainder + (remainder << 1)) >> 3; // Apply *3/8 algorithm on remainder also return ((( value + remainder ) ^ signCheckXOR ) + signCheck ) ; // Sum them and convert it according to its sign. */ } /* * bang - Compute !x without using ! * Examples: bang(3) = 0, bang(0) = 1 * Legal ops: ~ & ^ | + << >> * Max ops: 12 * Rating: 4 */ int bang(int x) { // We will follow a similar approach with previous question. // If number is 0 we get 1, we get 0 for all other numbers. For all integers x other than 0, // x and -x have different signs (i.e, 3 vs -3). However if x=0, also -x=0. We will use this fact. int shiftX = x >> 31 ; // Depend on sign of x, either 11..111 or 00...00 int signX = shiftX & 1 ; // Depend on sign of x, either 1 or 0 int complementX = (~ x)+1; // Equals to -x int shiftCX = complementX >> 31 ; // Depend on sign of -x, either 11..111 or 00...00 int signCX = shiftCX & 1 ; // Depend on sign of -x, either 1 or 0 int signOR = (signX | signCX) ; // If x is other than 0, (signX | signCX) will return 1 and ~ turn it into -2 return (~signOR) + 2; // If x is 0, (signX | signCX) will return 0 and ~ turn it into -1. To get 0 and 1 as desired, we add 2. } /* * TMax - return maximum two's complement integer * Legal ops: ! ~ & ^ | + << >> * Max ops: 4 * Rating: 1 */ int tmax(void) { // We need 0111111...1111. We can get it by negating 1000...0000, which can be derived by left shifts. int x = 1 << 31; return ~x; } /* * isOppositeSigns - if x and y has different signs then return 1, else return 0 * Example: isOppositeSigns(4,-5) = 1. * isOppositeSigns(3,2) = 0 * Legal ops: ! ~ & ^ | + << >> * Max ops: 6 * Rating: 3 */ int isOppositeSigns(int x, int y) { // Again, we can label x and y as positive or negative. Then we will XOR those labels, if they are different // it will return 1, otherwise return 0, as we wanted. x = ( x >> 31) & 1 ; // either 1 or 0 y = ( y >> 31) & 1 ; return x ^ y; } /* * conditional - same as x ? y : z * Example: conditional(2,4,5) = 4 * Legal ops: ! ~ & ^ | + << >> * Max ops: 16 * Rating: 3 */ int conditional(int x, int y, int z) { // If x is either 11...111 or 00..000, then we could simply return ( (x&y) | (~x&z) ). Because if x is 11....111, then // ~x is 00....00, and expression become (y|0), which is y. If x is 00...000, then ~x is 11....11 and expression become // (0|z), which is z. And this behaviour is exactly what we want. int sign = (!x); // If x is 0, returns 1; otherwise returns 0. We have to switch them back later int step1 = (sign << 31); // Shifting left by 31 bits, so that 0x1 can become 0x80000000 int step2 = step1 >> 31; // Shifting right by 31 bits, so that 0x80000000 becomes 0xffffffff (i.e. all 1s, 111....111) int flag = ~step2; // We are switching back, so that 0 gives 00.....0000 and nonzero numbers give 11......1111. return ( (flag & y) | (~flag & z) ) ; } /* * float_abs - Return bit-level equivalent of absolute value of f for * floating point argument f. * Both the argument and result are passed as unsigned int's, but * they are to be interpreted as the bit-level representations of * single-precision floating point values. * When argument is NaN, return argument.. * Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while * Max ops: 10 * Rating: 2 */ unsigned float_abs(unsigned uf) { // First digit decides sign. So we have to convert it to 0, while not touching others. unsigned int abs = uf & 0x7fffffff; // Convert most significant bit to 0. if (abs > 0x7f800000){ // If abs is larger than infinity (!), then return uf; // return the argument } else { return abs; // else return abs } } /* * float_f2i - Return bit-level equivalent of expression (int) f * for floating point argument f. * Argument is passed as unsigned int, but * it is to be interpreted as the bit-level representation of a * single-precision floating point value. * Anything out of range (including NaN and infinity) should return * 0x80000000u. * Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while * Max ops: 30 * Rating: 4 */ int float_f2i(unsigned uf) { int sign = (uf >> 31) & 1; // 0 means positive, 1 means negative unsigned int abs = uf & 0x7fffffff; // For ease of computation, we will work on positive numbers if (abs >= 0x7f800000){ // If abs is larger than infinity (!) or NaN, then return 0x80000000u; // return 0x80000000u }else { int exp = abs >> 23 ; // Extract exponent by shifting int frac = (abs << 9) >> 9 ; // Extract fraction; left shift to remove exponent part and then right shift back int expReal = exp - 127 ; // Remove bias term if (expReal < 0){ // If expReal is negative, then float number is lower than 1, which gets truncated to 0 return 0; }if (expReal > 32){ // If expReal is larger than 32 bits, then we cannot shift the frac part enough times, in other words return 0x80000000u; // we cannot represent the number, so out of range. }else if (expReal >= 23){ // frac part represents the numbers after the fraction (dot). Whenever expReal is larger frac = frac << (expReal - 23); // than 23 we can get rid of the dot, and shift the frac to left. }else{ frac = frac >> (23 - expReal); } abs = frac + 1; // Normalization factor if (sign){ // If number was initially negative, we change the sign abs = -abs; } return abs; } }
C
#ifndef SOCKECTDESCRIPTION_H #define SOCKECTDESCRIPTION_H void SockectDescription(){ // This call returns a socket descriptor that you can use in later system calls or -1 on error. // =>Parameters family // AF_INET IPv4 protocols // AF_INET6 IPv6 protocols // AF_LOCAL Unix domain protocols // AF_ROUTE Routing Sockets // AF_KEY Ket socket // =>Parameters type // SOCK_STREAM Stream socket // SOCK_DGRAM Datagram socket // SOCK_SEQPACKET Sequenced packet socket // SOCK_RAW Raw socket // =>Parameters protocol // IPPROTO_TCP TCP transport protocol // IPPROTO_UDP UDP transport protocol // IPPROTO_SCTP SCTP transport protocol // To perform network I/O, the first thing a process must do is, call the socket function, specifying the type of // communication protocol desired and protocol family, etc. int socket (int family, int type, int protocol); // =>Parameters // sockfd − It is a socket descriptor returned by the socket function. // serv_addr − It is a pointer to struct sockaddr that contains destination IP address and port. // addrlen − Set it to sizeof(struct sockaddr). // The connect function is used by a TCP client to establish a connection with a TCP server. int connect(int sockfd, struct sockaddr *serv_addr, int addrlen); // =>Parameters // sockfd − It is a socket descriptor returned by the socket function. // my_addr − It is a pointer to struct sockaddr that contains the local IP address and port. // addrlen − Set it to sizeof(struct sockaddr). // You can put your IP address and your port automatically // A 0 value for port number means that the system will choose a random port, and INADDR_ANY value for IP address // means the server's IP address will be assigned automatically. // server.sin_port = 0; // server.sin_addr.s_addr = INADDR_ANY; // The bind function assigns a local protocol address to a socket. With the Internet protocols, the protocol address // is the combination of either a 32-bit IPv4 address or a 128-bit IPv6 address, along with a 16-bit TCP or UDP port number. // This function is called by TCP server only. int bind(int sockfd, struct sockaddr *my_addr,int addrlen); // =>Parameters // sockfd − It is a socket descriptor returned by the socket function. // backlog − It is the number of allowed connections. // The listen function is called only by a TCP server and it performs two actions − // The listen function converts an unconnected socket into a passive socket, indicating that the kernel should accept incoming // connection requests directed to this socket. // The second argument to this function specifies the maximum number of connections the kernel should queue for this socket. int listen(int sockfd,int backlog); // =>Parameters // sockfd − It is a socket descriptor returned by the socket function. // cliaddr − It is a pointer to struct sockaddr that contains client IP address and port. // addrlen − Set it to sizeof(struct sockaddr). // The accept function is called by a TCP server to return the next completed connection from the front of the completed connection queue. // The signature of the call is as follows − int accept (int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen); // =>Parameters // sockfd − It is a socket descriptor returned by the socket function. // msg − It is a pointer to the data you want to send. // len − It is the length of the data you want to send (in bytes). // flags − It is set to 0. // The send function is used to send data over stream sockets or CONNECTED datagram sockets. If you want to send data over UNCONNECTED datagram // sockets, you must use sendto() function. // You can use write() system call to send data. Its signature is as follows − int send(int sockfd, const void *msg, int len, int flags); // =>Parameters // sockfd − It is a socket descriptor returned by the socket function. // buf − It is the buffer to read the information into. // len − It is the maximum length of the buffer. // flags − It is set to 0. // The recv function is used to receive data over stream sockets or CONNECTED datagram sockets. If you want to receive data over UNCONNECTED // datagram sockets you must use recvfrom(). // You can use read() system call to read the data. This call is explained in helper functions chapter. int recv(int sockfd, void *buf, int len, unsigned int flags); // =>Parameters // sockfd − It is a socket descriptor returned by the socket function. // msg − It is a pointer to the data you want to send. // len − It is the length of the data you want to send (in bytes). // flags − It is set to 0. // to − It is a pointer to struct sockaddr for the host where data has to be sent. // tolen − It is set it to sizeof(struct sockaddr). // The sendto function is used to send data over UNCONNECTED datagram sockets. Its signature is as follows − int sendto(int sockfd, const void *msg, int len, unsigned int flags, const struct sockaddr *to, int tolen); // =>Parameters // sockfd − It is a socket descriptor returned by the socket function. // buf − It is the buffer to read the information into. // len − It is the maximum length of the buffer. // flags − It is set to 0. // from − It is a pointer to struct sockaddr for the host where data has to be read. // fromlen − It is set it to sizeof(struct sockaddr). // The recvfrom function is used to receive data from UNCONNECTED datagram sockets. // int recvfrom(int sockfd, void *buf, int len, unsigned int flags struct sockaddr *from, int *fromlen); // =>Parameters // sockfd − It is a socket descriptor returned by the socket function. // The close function is used to close the communication between the client and the server. Its syntax is as follows − int close( int sockfd ); // =>Parameters // sockfd − It is a socket descriptor returned by the socket function. // how − Put one of the numbers − // 0 − indicates that receiving is not allowed, // 1 − indicates that sending is not allowed, and // 2 − indicates that both sending and receiving are not allowed. When how is set to 2, it's the same thing as close(). int shutdown(int sockfd, int how); // =>Parameters // nfds − It specifies the range of file descriptors to be tested. The select() function tests file descriptors in the range of 0 to nfds-1 // readfds − It points to an object of type fd_set that on input, specifies the file descriptors to be checked for being ready // to read, and on output, indicates which file descriptors are ready to read. It can be NULL to indicate an empty set. // writefds − It points to an object of type fd_set that on input, specifies the file descriptors to be checked for being // ready to write, and on output, indicates which file descriptors are ready to write. It can be NULL to indicate an empty set. // exceptfds − It points to an object of type fd_set that on input, specifies the file descriptors to be checked for error // conditions pending, and on output indicates, which file descriptors have error conditions pending. It can be NULL to indicate an empty set. // timeout − It points to a timeval struct that specifies how long the select call should poll the descriptors for an available I/O operation. // If the timeout value is 0, then select will return immediately. If the timeout argument is NULL, then select will block until at // least one file/socket handle is ready for an available I/O operation. Otherwise select will return after the amount of time in the timeout // has elapsed OR when at least one file/socket descriptor is ready for an I/O operation. int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout); // =>Parameters // fildes − It is a socket descriptor returned by the socket function. // buf − It is a pointer to the data you want to send. // nbyte − It is the number of bytes to be written. If nbyte is 0, write() will return 0 and have no other results if the file is a regular file; // otherwise, the results are unspecified. // You can also use send() function to send data to another process. int write(int fildes, const void *buf, int nbyte); // =>Parameters // fildes − It is a socket descriptor returned by the socket function. // buf − It is the buffer to read the information into. // nbyte − It is the number of bytes to read. // The read function attempts to read nbyte bytes from the file associated with the buffer, fildes, into the buffer pointed to by buf. // You can also use recv() function to read data to another process. int read(int fildes, const void *buf, int nbyte); // =>Parameters // void − It means no parameter is required. // The fork function creates a new process. The new process called the child process will be an exact copy of the calling process (parent process). // The child process inherits many attributes from the parent process. int fork(void); // =>Parameters // s − It specifies the string which has to be filled with null bytes. This will be a point to socket structure variable. // nbyte − It specifies the number of bytes to be filled with null values. This will be the size of the socket structure. // The bzero function places nbyte null bytes in the string s. This function is used to set all the socket structures with null values. void bzero(void *s, int nbyte); // =>Parameters // s1 − It specifies the first string to be compared. // s2 − It specifies the second string to be compared. // nbyte − It specifies the number of bytes to be compared. // The bcmp function compares byte string s1 against byte string s2. Both strings are assumed to be nbyte bytes long. // This function returns 0 if both strings are identical, 1 otherwise. The bcmp() function always returns 0 when nbyte is 0. int bcmp(const void *s1, const void *s2, int nbyte); // =>Parameters // s1 − It specifies the source string. // s2v − It specifies the destination string. // nbyte − It specifies the number of bytes to be copied. // The bcopy function copies nbyte bytes from string s1 to the string s2. Overlapping strings are handled correctly. void bcopy(const void *s1, void *s2, int nbyte); // =>Parameters // s − It specifies the source to be set. // c − It specifies the character to set on nbyte places. // nbyte − It specifies the number of bytes to be set. // The memset function is also used to set structure variables in the same way as bzero. Take a look at its syntax, given below. void *memset(void *s, int c, int nbyte); } #endif // SOCKECTDESCRIPTION_H
C
#ifndef BST_H_INCLUDED #define BST_H_INCLUDED #include<stdio.h> #include <stdlib.h> struct node{ int key; struct node *left, *right; }; struct node *newNode(int n); struct node *insert(struct node *root, int n); void inOrder(struct node *root); void preOrder(struct node *root); #endif // BST_H_INCLUDED
C
#include <stdio.h> #include <string.h> /* bubble 정렬을 통해 문자열을 정렬한다. 인접한 두 요소의 사전상 순서를 strcmp로 비교해 정렬하고 배열의 끝까지 반복한다. 이렇게 하면 사전상 가장 뒤에 있는 단어가 가장 오른쪽으로 가게 된다. 이후 가장 오른쪽의 요소를 제외하고 반복한다. */ void bubbleSort(char *arr[], int index_R) { char *tmp; for (int i = index_R; i > 0; i--) { for (int j = 1; j < index_R; j++) { //argv[0][]는 명령어이므로 1부터 정렬 시작 if (strcmp(arr[j], arr[j + 1]) > 0) { tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp; } } } } int main(int argc, char *argv[]) { bubbleSort(argv, argc-1); for (int i = 1; i < argc; i++) //argv[0][]는 명령어이므로 1부터 출력 시작 printf("%s\n", argv[i]); return 0; }
C
/* * CS 241 * The University of Illinois */ #define _GNU_SOURCE #include <unistd.h> #include <string.h> #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include "libmapreduce.h" #define CHARS_PER_INPUT 30000 #define INPUTS_NEEDED 10 static const char *long_key = "long_key"; /* Takes input string and maps the longest * word to the key, long_key. */ /** TAKEN FROM test4.c **/ typedef struct _list_t { struct _list_t *next; char *word; int count; } list_t; list_t * head = NULL; void map(int fd, const char *data) { char * longest_word = malloc(sizeof(char) * 200); longest_word[0] = '\0'; char * word = malloc(sizeof(char) * 200); word[0] = '\0'; while (1) /** REFERENCE ::: test 4 code **/ { int word_len= 0; const char *word_end = data; /* Get each word... */ while (1) { if ( ((*word_end == ' ' || *word_end == '\n') && word_len > 0) || *word_end == '\0' || word_len == 99) break; else if (isalpha(*word_end)) { word[word_len++] = *word_end; word_end++; } else { break; } } word[word_len] = '\0'; if( strlen(word) > strlen(longest_word) ) strcpy(longest_word,word); if (*word_end == '\0') { break; } data = word_end + 1; } char res[200]; int len = snprintf(res, 200, "%s: %s\n", long_key, longest_word); write(fd,res,len); free(word); free(longest_word); close(fd); } /* Takes two words and reduces to the longer of the two */ const char *reduce(const char *value1, const char *value2) { char *result; if(strlen(value1) > strlen(value2) ) asprintf(&result, "%s", value1); else asprintf(&result,"%s",value2); return result; } int main() { FILE *file = fopen("alice.txt", "r"); char s[1024]; int i; char **values = malloc(INPUTS_NEEDED * sizeof(char *)); int values_cur = 0; values[0] = malloc(CHARS_PER_INPUT + 1); values[0][0] = '\0'; while (fgets(s, 1024, file) != NULL) { if (strlen(values[values_cur]) + strlen(s) < CHARS_PER_INPUT) strcat(values[values_cur], s); else { values_cur++; values[values_cur] = malloc(CHARS_PER_INPUT + 1); values[values_cur][0] = '\0'; strcat(values[values_cur], s); } } values_cur++; values[values_cur] = NULL; fclose(file); mapreduce_t mr; mapreduce_init(&mr, map, reduce); mapreduce_map_all(&mr, (const char **)values); mapreduce_reduce_all(&mr); const char *result_longest = mapreduce_get_value(&mr, long_key); if (result_longest == NULL) { printf("MapReduce returned (null). The longest word was not found.\n"); } else { printf("Longest Word: %s\n", result_longest); free((void *)result_longest); } mapreduce_destroy(&mr); for (i = 0; i < values_cur; i++) free(values[i]); free(values); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/types.h> #include <pwd.h> #include <sys/time.h> #include <string.h> #include <signal.h> #include <unistd.h> #include <errno.h> #include "bbgp.h" #define BGP_PORT 179 #define MYAS 31337 #define OUR_HOLD_TIME 9 //int debug = 1; struct bgp_peer peer; char my_prefix[] = "10.1.1.1"; struct bgp_rib rib[MAX_RIB_SIZE]; int rib_size = 0; int print_rib() { int i; char buf[INET_ADDRSTRLEN+1]; for (i = 0; i < rib_size; i++) { if (!rib[i].valid) { continue; } fprintf(stderr, "rib entry: %d\n", i); inet_ntop(AF_INET, &(rib[i].prefix), buf, INET_ADDRSTRLEN); fprintf(stderr, "\tprefix: %s/%d\n", buf, rib[i].bits); fprintf(stderr, "\torigin: %d\n", rib[i].origin); fprintf(stderr, "\tas_path: %s\n", rib[i].as_path); inet_ntop(AF_INET, &(rib[i].next_hop), buf, INET_ADDRSTRLEN); fprintf(stderr, "\tnext_hop: %s\n", buf); } return(0); } int bgp_send_notification(u_int8_t major, u_int8_t minor) { unsigned char buf[BGP_NOTIFICATION_SIZE]; struct bgp_notification *bgpn_hdr; bgpn_hdr = (struct bgp_notification*)buf; // form up the notification header memset(bgpn_hdr, 0xFF, 16); bgpn_hdr->bgpn_len = htons(BGP_NOTIFICATION_SIZE); bgpn_hdr->bgpn_type = BGP_NOTIFICATION; bgpn_hdr->bgpn_major = major; bgpn_hdr->bgpn_minor = minor; // send it if (send(STDOUT_FILENO, buf, BGP_NOTIFICATION_SIZE, 0) != BGP_NOTIFICATION_SIZE) { return(-1); } // if (debug) fprintf(stderr, "Sent notification (%d,%d)\n", major, minor); } int bgp_send_keepalive() { unsigned char buf[BGP_SIZE]; struct bgp *bgp_hdr; bgp_hdr = (struct bgp *)buf; // form up the bgp header memset(bgp_hdr, 0xFF, 16); bgp_hdr->bgp_len = htons(BGP_SIZE); bgp_hdr->bgp_type = BGP_KEEPALIVE; // send it if (send(STDOUT_FILENO, buf, BGP_SIZE, 0) != BGP_SIZE) { return(-1); } // if (debug) fprintf(stderr, "Sent keepalive\n"); return(0); } int del_route(u_int32_t prefix, unsigned char prefix_bits) { int i; // look for the entry for (i = 1; i < rib_size; i++) { if (rib[i].prefix.s_addr == prefix && rib[i].bits == prefix_bits) { rib[i].valid = 0; } } return(0); } int add_route(u_int32_t prefix, unsigned char prefix_bits, unsigned int origin, char *as_path, u_int32_t next_hop) { int i; int first_available = -1; // see if this prefix already exists in the table for (i = 1; i < rib_size; i++) { // also find the first invalid rib entry in case we need to insert a new one if (rib[i].valid == 0) { first_available = i; } if (rib[i].prefix.s_addr == prefix && rib[i].bits == prefix_bits && rib[i].origin == origin && !strcmp(rib[i].as_path, as_path) && rib[i].next_hop.s_addr == next_hop) { if (rib[i].valid == 1) { return(0); } } } // see if we found an available entry to re-use if (first_available == -1) { // nope, just add one to the end i = rib_size; } else { i = first_available; } // not found, add it if (i < MAX_RIB_SIZE) { // new, zero the rib entry before setting values bzero(&(rib[i]), sizeof(struct bgp_rib)); rib[i].prefix.s_addr = prefix; rib[i].bits = prefix_bits; rib[i].origin = origin; bzero(rib[i].as_path, MAX_AS_PATH_LENGTH); strncpy(rib[i].as_path, as_path, MAX_AS_PATH_LENGTH-1); rib[i].next_hop.s_addr = next_hop; rib[i].valid = 1; rib_size++; } else { // exceeded RIB capacity, close the connection // if (debug) fprintf(stderr,"reached max RIB size\n"); bgp_send_notification(BGP_NOTIFY_MAJOR_UPDATE, BGP_NOTIFY_MINOR_CEASE_MAXPRFX); return(-1); } return(0); } int handle_bgp_open() { unsigned char buf[BGP_OPEN_SIZE+BGP_OPT_SIZE+BGP_CAPABILITIES_SIZE+BGP_CAPABILITIES_MP_SIZE]; struct bgp_open *open_hdr; int n; unsigned char trash[1]; unsigned char cap[256]; unsigned char opt[256]; unsigned char varopt[2]; unsigned char mpcap[256]; struct bgp_opt *bgp_opt_hdr; struct bgp_capabilities *bgpc_hdr; struct bgp_cap_mp *bgpc_mp_hdr; unsigned int total_size; int i; int v4u = 0; struct itimerval new_value; // try to read in the open header if ((n = read(STDIN_FILENO, buf, BGP_OPEN_SIZE)) == -1) { return(-1); } // make sure we got enough bytes for the open header if (n != BGP_OPEN_SIZE) { // if (debug) fprintf(stderr, "Invalid open size: %d\n", n); // nope, bye-bye bgp_send_notification(BGP_NOTIFY_MAJOR_OPEN, 0); return(-1); } // got enough, check the basics // make sure we were sent an open packet open_hdr = (struct bgp_open *)buf; if (open_hdr->bgpo_type != BGP_OPEN) { // if (debug) fprintf(stderr, "Invalid packet type: %d\n", open_hdr->bgpo_type); bgp_send_notification(BGP_NOTIFY_MAJOR_OPEN, BGP_NOTIFY_MINOR_MSG_TYPE); return(-1); } // make sure version is 4 if (open_hdr->bgpo_version != 4) { // if (debug) fprintf(stderr, "Invalid version: %d\n", open_hdr->bgpo_version); bgp_send_notification(BGP_NOTIFY_MAJOR_OPEN, BGP_NOTIFY_MINOR_OPEN_BADVER); return(-1); } // check the optional parameters for IPv4 Unicast if (open_hdr->bgpo_optlen < 2) { // if (debug) fprintf(stderr, "No options\n"); bgp_send_notification(BGP_NOTIFY_MAJOR_OPEN, BGP_NOTIFY_MINOR_CAP_BADCAPC); return(-1); } // if (debug) fprintf(stderr, "Options len: %d\n", open_hdr->bgpo_optlen); // since bgpo_optlen > 0, read in the rest of the options // make sure there aren't a huge number of options if (open_hdr->bgpo_optlen > 64) { bgp_send_notification(BGP_NOTIFY_MAJOR_OPEN, BGP_NOTIFY_MINOR_CAP_BADCAPC); return(-1); } i = 0; while (i < open_hdr->bgpo_optlen) { // read in the first two bytes of the option header (the type and length) if ((n = read(STDIN_FILENO, opt, 2)) != 2) { // if (debug) fprintf(stderr, "Options length not read: %d\n", n); bgp_send_notification(BGP_NOTIFY_MAJOR_OPEN, BGP_NOTIFY_MINOR_CAP_BADCAPC); return(-1); } // if (debug) fprintf(stderr, "Read in %d bytes\n", n); bgp_opt_hdr = (struct bgp_opt *)opt; // check the cap code if (bgp_opt_hdr->bgpopt_type != BGP_OPT_CAP) { // if (debug) fprintf(stderr, "Non-Capability option, %d\n", bgp_opt_hdr->bgpopt_type); bgp_send_notification(BGP_NOTIFY_MAJOR_OPEN, BGP_NOTIFY_MINOR_CAP_BADCAPC); return(-1); } // if (debug) fprintf(stderr, "Processing BGP Capability option, length: %d\n", bgp_opt_hdr->bgpopt_len); // check the cap length if (i+sizeof(struct bgp_opt)+bgp_opt_hdr->bgpopt_len > open_hdr->bgpo_optlen) { bgp_send_notification(BGP_NOTIFY_MAJOR_OPEN, BGP_NOTIFY_MINOR_CAP_BADCAPC); return(-1); } // it's less than the overall optlen, so read in the first 2 bytes of the variable portion of this option if ((n = read(STDIN_FILENO, varopt, 2)) != 2) { // if (debug) fprintf(stderr, "Variable options length not read: %d\n", n); bgp_send_notification(BGP_NOTIFY_MAJOR_OPEN, BGP_NOTIFY_MINOR_CAP_BADCAPC); return(-1); } bgpc_hdr = (struct bgp_capabilities *)varopt; // make sure the length we were passed is valid if (sizeof(struct bgp_capabilities)+bgpc_hdr->length != bgp_opt_hdr->bgpopt_len) { // if (debug) fprintf(stderr, "Invalid capability length: %d\n", bgpc_hdr->length); bgp_send_notification(BGP_NOTIFY_MAJOR_OPEN, BGP_NOTIFY_MINOR_CAP_BADCAPC); return(-1); } // see if we got the necessary IPv4 unicast capability advertisement from the peer if (bgpc_hdr->type == BGP_CAPCODE_MP && bgpc_hdr->length == 4) { // if (debug) fprintf(stderr, "Processing BGP MP Capability option, length: %d\n", bgpc_hdr->length); // yep read in the MP capabilities struct if ((n = read(STDIN_FILENO, mpcap, 4)) != 4) { // if (debug) fprintf(stderr, "MP Cap options length not read: %d\n", n); bgp_send_notification(BGP_NOTIFY_MAJOR_OPEN, BGP_NOTIFY_MINOR_CAP_BADCAPC); return(-1); } bgpc_mp_hdr = (struct bgp_cap_mp *)mpcap; // if (debug) fprintf(stderr, "%08x, AFI: %d, SAFI: %d\n", *((unsigned int *)mpcap), ntohs(bgpc_mp_hdr->afi), bgpc_mp_hdr->safi); if (ntohs(bgpc_mp_hdr->afi) == BGP_AFI_IPV4 && bgpc_mp_hdr->safi == BGP_SAFI_UNICAST) { // if (debug) fprintf(stderr, "Received MP capability AFI=IPv4, SAFI=unicast\n"); v4u = 1; } } else if (bgpc_hdr->type == 65 && bgpc_hdr->length == 4) { // ignore 4-byte AS capability, but read past it all the same if ((n = read(STDIN_FILENO, mpcap, 4)) != 4) { // if (debug) fprintf(stderr, "MP Cap options length not read: %d\n", n); bgp_send_notification(BGP_NOTIFY_MAJOR_OPEN, BGP_NOTIFY_MINOR_CAP_BADCAPC); return(-1); } } else { // if (debug) fprintf(stderr, "Don't recognize BGP capability type %d\n", bgpc_hdr->type); bgp_send_notification(BGP_NOTIFY_MAJOR_OPEN, BGP_NOTIFY_MINOR_CAP_BADCAPC); return(-1); } i += BGP_OPT_SIZE+BGP_CAPABILITIES_SIZE+bgpc_hdr->length; // if (debug) fprintf(stderr, "i: %d\n", i); } if (!v4u) { // didn't find the IPv4 unicast required cap... // if (debug) fprintf(stderr, "Didn't find MP capability AFI=IPv4, SAFI=unicast\n"); bgp_send_notification(BGP_NOTIFY_MAJOR_OPEN, BGP_NOTIFY_MINOR_CAP_BADCAPC); return(-1); } // check the hold time peer.max_hold_time = ntohs(open_hdr->bgpo_holdtime); if (peer.max_hold_time < 3 && peer.max_hold_time != 0) { // if (debug) fprintf(stderr, "Invalid hold time: %d\n", open_hdr->bgpo_holdtime); bgp_send_notification(BGP_NOTIFY_MAJOR_OPEN, BGP_NOTIFY_MINOR_OPEN_BADHOLD); return(-1); } if (peer.max_hold_time > OUR_HOLD_TIME) { peer.max_hold_time = OUR_HOLD_TIME; } // set a timer to re-send a keepalive as needed (1/3 of the requested hold time) if (peer.max_hold_time != 0) { new_value.it_interval.tv_sec = peer.max_hold_time/3; new_value.it_interval.tv_usec = 0; new_value.it_value.tv_sec = peer.max_hold_time/3; new_value.it_value.tv_usec = 0; if ((i = setitimer(ITIMER_REAL, &new_value, NULL)) != 0) { // if (debug) fprintf(stderr, "Unable to set itimer: %d\n", i); bgp_send_notification(BGP_NOTIFY_MAJOR_OPEN, BGP_NOTIFY_MINOR_OPEN_BADHOLD); return(-1); } } // capabilites look good...let's reply // grab the peer ID and AS and put them in the bgp_peer struct peer.bgp_peer_id = ntohl(open_hdr->bgpo_id); peer.bgp_peer_as = ntohs(open_hdr->bgpo_myas); // everything looks ok in the open we received bzero(buf, BGP_OPEN_SIZE+BGP_OPT_SIZE+BGP_CAPABILITIES_SIZE+BGP_CAPABILITIES_MP_SIZE); open_hdr = (struct bgp_open *)buf; // so send back our open and a keepalive // marker = all 1's memset(open_hdr, 0xFF, 16); // length = BGP_OPEN_SIZE open_hdr->bgpo_len = htons(BGP_OPEN_SIZE+BGP_OPT_SIZE+BGP_CAPABILITIES_SIZE+BGP_CAPABILITIES_MP_SIZE); // type = BGP_OPEN open_hdr->bgpo_type = BGP_OPEN; // version = 4 open_hdr->bgpo_version = 4; // AS = MYAS open_hdr->bgpo_myas = htons(MYAS); // holdtime = OUR_HOLD_TIME open_hdr->bgpo_holdtime = htons(OUR_HOLD_TIME); // ID = 192.168.1.1 open_hdr->bgpo_id = inet_addr("192.168.1.1"); // optlen = large enough to handle MP IPv4 unicast capability advertisement open_hdr->bgpo_optlen = BGP_OPT_SIZE+BGP_CAPABILITIES_SIZE+BGP_CAPABILITIES_MP_SIZE; // set up the BGP option header bgp_opt_hdr = (struct bgp_opt *)opt; bgp_opt_hdr->bgpopt_type = BGP_OPT_CAP; bgp_opt_hdr->bgpopt_len = BGP_CAPABILITIES_SIZE+BGP_CAPABILITIES_MP_SIZE; memcpy(buf+BGP_OPEN_SIZE, opt, BGP_OPT_SIZE); // set up the MP capability header bgpc_hdr = (struct bgp_capabilities *)varopt; bgpc_hdr->type = BGP_CAPCODE_MP; bgpc_hdr->length = 4; memcpy(buf+BGP_OPEN_SIZE+BGP_OPT_SIZE, varopt, BGP_CAPABILITIES_SIZE); // set up the MP IPv4 Unicast capability bgpc_mp_hdr = (struct bgp_cap_mp *)mpcap; bgpc_mp_hdr->afi = htons(BGP_AFI_IPV4); bgpc_mp_hdr->res = 0; bgpc_mp_hdr->safi = BGP_SAFI_UNICAST; memcpy(buf+BGP_OPEN_SIZE+BGP_OPT_SIZE+BGP_CAPABILITIES_SIZE, mpcap, BGP_CAPABILITIES_MP_SIZE); // send it total_size = BGP_OPEN_SIZE+BGP_OPT_SIZE+BGP_CAPABILITIES_SIZE+BGP_CAPABILITIES_MP_SIZE; if (send(STDOUT_FILENO, buf, total_size, 0) != total_size) { // if (debug) fprintf(stderr, "Sending of open failed\n"); return(-1); } // if (debug) fprintf(stderr, "Sent open packet\n"); if (bgp_send_keepalive()) { return(-1); } peer.bgp_state = BGP_STATE_ESTAB; // successfully opened our BGP connection return(0); } int Handle_Notify(unsigned short bgp_len) { unsigned char buf[BGP_NOTIFICATION_SIZE]; int n; struct bgp_notification *bgpn_hdr; // make sure this is a valid notification length if (bgp_len != BGP_NOTIFICATION_SIZE) { // invalid size bgp_send_notification(BGP_NOTIFY_MAJOR_MSG, BGP_NOTIFY_MINOR_MSG_LEN); return(-1); } // we've already read in the bgp header bytes, so only read what's left if ((n = read(STDIN_FILENO, buf+BGP_SIZE, BGP_NOTIFICATION_SIZE-BGP_SIZE)) != BGP_NOTIFICATION_SIZE-BGP_SIZE) { // invalid size bgp_send_notification(BGP_NOTIFY_MAJOR_MSG, BGP_NOTIFY_MINOR_MSG_LEN); return(-1); } bgpn_hdr = (struct bgp_notification *)buf; // on any notification message, we simply close the connection // if (debug) fprintf(stderr, "Received notification (%d, %d)\n", bgpn_hdr->bgpn_major, bgpn_hdr->bgpn_minor); return(-1); } unsigned int Parse_MED(unsigned char *pa_value, unsigned int len) { unsigned int med; // BUG....mis-checked the len, so this allows overwrite of saved EIP if (len > 20) { return(100); } memcpy(&med, pa_value, len); return(med); } int Parse_Path_Attributes(unsigned char *pa, unsigned short pa_len, unsigned short nlri_len) { unsigned short i; struct bgp_attr_type *attr_type; struct bgp_as_path_tuple *path_tuple; unsigned int len; unsigned short *as_start; unsigned char *pa_value; unsigned int origin; unsigned char as_path[MAX_AS_PATH_LENGTH]; unsigned char tmp_as_path[MAX_AS_PATH_LENGTH]; u_int32_t next_hop; unsigned char at[4]; unsigned char pt[MAX_AS_PATH_LENGTH+2]; u_int8_t *prefix_bits; unsigned int prefix_bytes; unsigned int pb; u_int32_t prefix; unsigned char *prefix_start; int shift; unsigned int med; // get a convenient struct pointer to the attribute type buffer attr_type = (struct bgp_attr_type *)at; bzero(as_path, MAX_AS_PATH_LENGTH); bzero(at, 4); i = 0; while (i < pa_len) { // memcpy in the attr_type flag byte so we can see if we're dealing with an extended length field memcpy(at, pa+i, 1); // get the length of the attribute based on the extended bit if (attr_type->extended) { // read in the rest of the attr_type struct memcpy(at+1,pa+i+1,3); // if (debug) fprintf(stderr,"extended\n"); len = ntohs(attr_type->ext_len); pa_value = pa+i+4; // make sure the length is possible if (len > pa_len - 4 - i) { // if (debug) fprintf(stderr,"Bad attribute length %d pa_len %d\n", len, pa_len); bgp_send_notification(BGP_NOTIFY_MAJOR_MSG, BGP_NOTIFY_MINOR_MSG_LEN); return(-1); } } else { // read in the rest of the attr_type struct memcpy(at+1,pa+i+1,2); // if (debug) fprintf(stderr,"regular\n"); len = attr_type->len; pa_value = pa+i+3; // make sure the length is possible if (len > pa_len - 3 - i) { // if (debug) fprintf(stderr,"Bad attribute length %d pa_len %d\n", len, pa_len); bgp_send_notification(BGP_NOTIFY_MAJOR_MSG, BGP_NOTIFY_MINOR_MSG_LEN); return(-1); } } // if (debug) fprintf(stderr,"len %d\n", len); // handle each of the attribute types switch (attr_type->attr_type_code) { case BGPTYPE_ORIGIN: // if (debug) fprintf(stderr,"Found Origin attribute\n"); if (len != 1) { bgp_send_notification(BGP_NOTIFY_MAJOR_UPDATE, BGP_NOTIFY_MINOR_UPDATE_BADATTR); return(-1); } if (*pa_value > 2) { bgp_send_notification(BGP_NOTIFY_MAJOR_UPDATE, BGP_NOTIFY_MINOR_UPDATE_BADATTR); return(-1); } // store the origin origin = *pa_value; // if (debug) fprintf(stderr,"Origin: %d \n", origin); break; case BGPTYPE_AS_PATH: // if (debug) fprintf(stderr,"Found AS_PATH attribute\n"); memcpy(pt, pa_value, 2); path_tuple = (struct bgp_as_path_tuple *)pt; if (len % 2 || !len) { bgp_send_notification(BGP_NOTIFY_MAJOR_UPDATE, BGP_NOTIFY_MINOR_UPDATE_BADATTR); return(-1); } // verify the type if (path_tuple->segment_type < 1 || path_tuple->segment_type > 2) { bgp_send_notification(BGP_NOTIFY_MAJOR_UPDATE, BGP_NOTIFY_MINOR_UPDATE_BADATTR); return(-1); } // make sure the segement length is valid if (i+sizeof(path_tuple)+path_tuple->segment_length*2 > pa_len) { bgp_send_notification(BGP_NOTIFY_MAJOR_UPDATE, BGP_NOTIFY_MINOR_UPDATE_BADATTR); return(-1); } // make sure they didn't send us some outrageously log path if (path_tuple->segment_length*2 >= MAX_AS_PATH_LENGTH) { bgp_send_notification(BGP_NOTIFY_MAJOR_UPDATE, BGP_NOTIFY_MINOR_UPDATE_BADATTR); return(-1); } // if (debug) fprintf(stderr,"Segment length: %d\n", path_tuple->segment_length); // copy the rest of the as_path attribute into the local buffer memcpy(pt+2, pa_value+2, path_tuple->segment_length*2); // parse each of the AS's in the path for (as_start = (unsigned short *)(pt+2); as_start < (unsigned short *)(pt+2+path_tuple->segment_length*2); as_start+=2) { if (as_path[0] == '\0') { snprintf(as_path, MAX_AS_PATH_LENGTH, "%hu", ntohs(*as_start)); } else { bzero(tmp_as_path, MAX_AS_PATH_LENGTH); strncpy(tmp_as_path, as_path, MAX_AS_PATH_LENGTH-1); if (snprintf(as_path, MAX_AS_PATH_LENGTH, "%s:%hu", tmp_as_path, ntohs(*as_start)) >= MAX_AS_PATH_LENGTH) { bgp_send_notification(BGP_NOTIFY_MAJOR_UPDATE, BGP_NOTIFY_MINOR_UPDATE_BADATTR); return(-1); } } } // if (debug) fprintf(stderr,"AS_PATH: %s\n", as_path); break; case BGPTYPE_NEXT_HOP: // if (debug) fprintf(stderr,"Found Next Hop attribute\n"); if (len != 4) { bgp_send_notification(BGP_NOTIFY_MAJOR_UPDATE, BGP_NOTIFY_MINOR_UPDATE_BADATTR); return(-1); } memcpy(&next_hop, pa_value, 4); // if (debug) fprintf(stderr,"Next Hop: %08x\n", ntohl(next_hop)); break; case BGPTYPE_MULTI_EXIT_DISC: // if (debug) fprintf(stderr,"Found MED attribute length %d\n", len); med = Parse_MED(pa_value, len); break; default: // attribute we don't care to parse // if (debug) fprintf(stderr,"Found %d attribute\n", attr_type->attr_type_code); break; } // increment i if (attr_type->extended) { i += 4+len; } else { i += 3+len; } } // parse the NLRI's that should take on these Path Attributes i = 0; while (i < nlri_len) { // get the length of the prefix in bits // offset from beginning of buf = length of withdrawn routes length field + i prefix_bits = (u_int8_t *)(pa + pa_len + i); // make sure prefix_bits are valid if (*prefix_bits > 32) { bgp_send_notification(BGP_NOTIFY_MAJOR_UPDATE, BGP_NOTIFY_MINOR_UPDATE_BADATTR); return(-1); } // round up to the octet boundry if (*prefix_bits % 8 == 0) { prefix_bytes = (unsigned int)(*prefix_bits/8); } else { prefix_bytes = (unsigned int)((*prefix_bits/8)+1); } // make sure the prefix length we're told isn't more than the // remaining size of the withdrawn routes field // i + prefix length byte + prefix length if (i+1+prefix_bytes > nlri_len) { // if (debug) fprintf(stderr,"nlri length too big: %d > %d\n", i+1+prefix_bytes, nlri_len); bgp_send_notification(BGP_NOTIFY_MAJOR_MSG, BGP_NOTIFY_MINOR_MSG_LEN); return(-1); } // looks ok, so parse the prefix prefix = 0; shift = 24; prefix_start = (unsigned char *)(pa + pa_len + i + 1); pb = prefix_bytes; while (pb--) { prefix = prefix | ((*prefix_start)<<shift); shift -= 8; prefix_start += 1; } // add this prefix to our routing table for this client // if (debug) fprintf(stderr,"Adding prefix %08x to routing table\n", prefix); if (add_route(ntohl(prefix), *prefix_bits, origin, as_path, next_hop)) { bgp_send_notification(BGP_NOTIFY_MAJOR_CEASE, BGP_NOTIFY_MINOR_CEASE_ADDOWN); return(-1); } // move on to the next prefix //i += sizeof(prefix_bits)+prefix_bytes; i += (1+prefix_bytes); } return(0); } int Send_Update() { unsigned char buf[50]; struct bgp *bgp_hdr; struct bgp_attr_type attr_type; struct bgp_as_path_tuple as_path_tuple; u_int16_t val16; u_int16_t val8; int i; // init our one route as rib[0] // BUG...leak the addr of the global var my_prefix, which happens // to be conveniently next to the rib global var in memory // if (debug) fprintf(stderr, "rib: %08x\n", (unsigned int)rib); rib[0].prefix.s_addr = (in_addr_t)my_prefix; rib[0].next_hop.s_addr = inet_addr("192.168.1.1"); rib[0].valid = 1; rib[0].bits = 32; rib[0].origin = 0; sprintf(rib[0].as_path, "%hu", MYAS); rib_size++; // form up the update packet bgp_hdr = (struct bgp *)buf; // marker = all 1's memset(bgp_hdr, 0xFF, 16); // type = UPDATE bgp_hdr->bgp_type = BGP_UPDATE; i = BGP_SIZE; // set the wr_len val16 = 0; memcpy(buf+i, &val16, 2); i+=2; // set the pa_len val16 = htons(18); memcpy(buf+i, &val16, 2); i+=2; // set the attr_type flags we'll be using for all path attributes attr_type.optional = 0; attr_type.transitive = 1; attr_type.partial = 0; attr_type.extended = 0; attr_type.unused = 0; // set the origin pa attr_type.attr_type_code = BGPTYPE_ORIGIN; attr_type.len = 1; memcpy(buf+i, &attr_type, 3); i+=3; val8 = 0; memcpy(buf+i, &val8, 1); i++; // set the as_path pa attr_type.attr_type_code = BGPTYPE_AS_PATH; attr_type.len = 4; memcpy(buf+i, &attr_type, 3); i+=3; as_path_tuple.segment_type = 2; as_path_tuple.segment_length = 1; val16 = htons(MYAS); memcpy(buf+i, &as_path_tuple, 2); i+=2; memcpy(buf+i, &val16, 2); i+=2; // set the next_hop pa attr_type.attr_type_code = BGPTYPE_NEXT_HOP; attr_type.len = 4; memcpy(buf+i, &attr_type, 3); i+=3; memcpy(buf+i, &(rib[0].next_hop.s_addr), 4); i+=4; // finally, tack on the NLRI for the prefix val8 = 32; memcpy(buf+i, &val8, 1); i++; memcpy(buf+i, &(rib[0].prefix.s_addr), 4); i+=4; // then set the bgp header length // length = BGP_SIZE+ bgp_hdr->bgp_len = htons(i); // send the update packet if (send(STDOUT_FILENO, buf, i, 0) != i) { // if (debug) fprintf(stderr, "Sending of update failed\n"); return(-1); } // if (debug) fprintf(stderr, "Sent update packet length %d\n", i); return(0); } int Handle_Update(unsigned short bgp_len) { //unsigned char *buf; unsigned char buf[1000]; u_int16_t *wr_len_p; u_int16_t wr_len; u_int16_t *pa_len_p; u_int16_t pa_len; u_int16_t nlri_len; u_int8_t *prefix_bits; unsigned int prefix_bytes; unsigned int pb; u_int32_t prefix; unsigned char *prefix_start; int shift; int n; unsigned int i; // make sure the length we were sent isn't outrageous long if (bgp_len > 1000) { // if (debug) fprintf(stderr,"Outrageous update length: %d\n", bgp_len); bgp_send_notification(BGP_NOTIFY_MAJOR_MSG, BGP_NOTIFY_MINOR_MSG_LEN); return(-1); } // but, make sure the length is long enough to contain the minimum update data // bgp header plus 2 bytes for the withdrawn routes length field and 2 bytes for the path attribute length field if (bgp_len < BGP_UPDATE_MIN_SIZE) { // if (debug) fprintf(stderr,"Too small update length: %d\n", bgp_len); bgp_send_notification(BGP_NOTIFY_MAJOR_MSG, BGP_NOTIFY_MINOR_MSG_LEN); return(-1); } // alloc memory to hold the bgp update message // if ((buf = (unsigned char *)calloc(1, bgp_len-BGP_SIZE)) == NULL) { // // not good... // if (debug) fprintf(stderr, "Shit...calloc failed\n"); // bgp_send_notification(BGP_NOTIFY_MAJOR_CEASE, BGP_NOTIFY_MINOR_CEASE_ADDOWN); // } // read in the rest of the bgp update message if ((n = read(STDIN_FILENO, buf, bgp_len-BGP_SIZE)) != bgp_len-BGP_SIZE) { // invalid size // if (debug) fprintf(stderr,"Update read failed: %d of %d\n", n, bgp_len); bgp_send_notification(BGP_NOTIFY_MAJOR_MSG, BGP_NOTIFY_MINOR_MSG_LEN); return(-1); } // // start parsing the update message // // first get the withdrawn routes length wr_len_p = (u_int16_t *)buf; wr_len = ntohs(*wr_len_p); // make sure the indicated length matches up with the packet length we've received if (bgp_len < BGP_UPDATE_MIN_SIZE + wr_len) { // invalid size // if (debug) fprintf(stderr,"Withdrawn routes length not valid: %d\n", wr_len); bgp_send_notification(BGP_NOTIFY_MAJOR_MSG, BGP_NOTIFY_MINOR_MSG_LEN); return(-1); } // next, get the total path attribute length //pa_len_p = (u_int16_t *)(buf+2+*wr_len_p); pa_len_p = (u_int16_t *)(buf+2+wr_len); pa_len = ntohs(*pa_len_p); // make sure the indicated length matches up with the packet length we've received if (bgp_len < BGP_UPDATE_MIN_SIZE + wr_len + pa_len) { // invalid size // if (debug) fprintf(stderr,"bgp_len (%d) != 2 + wr_len (%d) + pa_len (%d)\n", bgp_len, wr_len, pa_len); bgp_send_notification(BGP_NOTIFY_MAJOR_MSG, BGP_NOTIFY_MINOR_MSG_LEN); return(-1); } // finally, figure out the NLRI length nlri_len = bgp_len - BGP_UPDATE_MIN_SIZE - wr_len - pa_len; // if (debug) fprintf(stderr,"nlri_len %d\n", nlri_len); // at this point, we know the lengths of the various update message sections // so, start parsing each section // // first, parse the withdrawn routes // i = 0; while (i < wr_len) { // get the length of the prefix in bits // offset from beginning of buf = length of withdrawn routes length field + i // new check that sizeof works like we want here prefix_bits = (u_int8_t *)(buf + sizeof(wr_len_p) + i); // make sure prefix_bits are valid if (*prefix_bits > 32) { bgp_send_notification(BGP_NOTIFY_MAJOR_UPDATE, BGP_NOTIFY_MINOR_UPDATE_BADATTR); return(-1); } // round up to the octet boundry if (*prefix_bits % 8 == 0) { prefix_bytes = (int)(*prefix_bits/8); } else { prefix_bytes = (int)((*prefix_bits/8)+1); } // make sure the prefix length we're told isn't more than the // remaining size of the withdrawn routes field // i + prefix length byte + prefix length if (i+sizeof(prefix_bits)+prefix_bytes > wr_len) { bgp_send_notification(BGP_NOTIFY_MAJOR_MSG, BGP_NOTIFY_MINOR_MSG_LEN); return(-1); } // looks ok, so parse the prefix prefix = 0; shift = 24; prefix_start = (unsigned char *)(buf + sizeof(wr_len_p) + i + sizeof(prefix_bits)); pb = prefix_bytes; while (pb--) { prefix = prefix | ((*prefix_start)<<shift); shift -= 8; prefix_start += 1; } // remove this prefix from our routing table for this client // if (debug) fprintf(stderr,"Removing prefix %08x from routing table\n", prefix); del_route(ntohl(prefix), *prefix_bits); // move on to the next prefix //i += sizeof(prefix_bits)+prefix_bytes; i += 1+prefix_bytes; } // if (debug) fprintf(stderr,"Done parsing withdrawn routes\n"); // // next, parse the path attributes // if (pa_len == 0) { // nothing to do...only withdrawn routes are listed in this update return(0); } return(Parse_Path_Attributes(buf+sizeof(wr_len)+wr_len+sizeof(pa_len), pa_len, nlri_len)); } int bbgp() { unsigned char buf[BGP_SIZE]; struct bgp *bgp_hdr; int n; // handle the open negotiations if (handle_bgp_open()) { // return if they fail return(0); } // send our update with our one route if (Send_Update()) { return(0); } // established loop while ((n = read(STDIN_FILENO, buf, BGP_SIZE)) == BGP_SIZE) { // handle update/notification/keepalive messages bgp_hdr = (struct bgp *)buf; switch(bgp_hdr->bgp_type) { case BGP_NOTIFICATION: // if (debug) fprintf(stderr,"Received BGP Notification\n"); // pass this off to the notification message handler if (Handle_Notify(bgp_hdr->bgp_len)) { return (-1); } break; case BGP_KEEPALIVE: // if (debug) fprintf(stderr,"Received BGP Keepalive\n"); // make sure the keepalive is of valid length if (bgp_hdr->bgp_len != htons(BGP_SIZE)) { bgp_send_notification(BGP_NOTIFY_MAJOR_MSG, BGP_NOTIFY_MINOR_MSG_LEN); return(-1); } // store the time when we received this peer.last_ack = time(NULL); // if (debug) print_rib(); break; case BGP_UPDATE: // pass this off to the update message handler // if (debug) fprintf(stderr,"Received BGP Update length %d\n", ntohs(bgp_hdr->bgp_len)); if (Handle_Update(ntohs(bgp_hdr->bgp_len))) { return(-1); } break; default: // invalid type // if (debug) fprintf(stderr,"Received invalid message type (%d)\n", bgp_hdr->bgp_type); bgp_send_notification(BGP_NOTIFY_MAJOR_MSG, BGP_NOTIFY_MINOR_MSG_TYPE); return(-1); } } // if we got here, the while loop received an invalid length bgp packet // if (debug) fprintf(stderr,"Received invalid length (%d) packet, errno: %s\n", n, sys_errlist[errno]); fflush(stderr); bgp_send_notification(BGP_NOTIFY_MAJOR_MSG, BGP_NOTIFY_MINOR_MSG_LEN); return(-1); } void sig_alrm_handler(int signum) { // see if our initial connection timer has expired if (peer.bgp_state == BGP_STATE_ACTIVE) { // yep, bail exit(0); } // if (debug) fprintf(stderr,"Sending BGP keepalive because itimer expired\n"); fflush(stderr); // see if our hold time has expired for the peer if (time() > peer.last_ack + peer.max_hold_time) { // yep bgp_send_notification(BGP_NOTIFY_MAJOR_HOLDTIME, BGP_NOTIFY_MINOR_CEASE_NOPEER); exit(0); } bgp_send_keepalive(); } int main(void) { struct sockaddr_in cli; socklen_t cli_len; char buf[100]; struct sigaction act; struct itimerval new_value; int i; // init the rib bzero(rib, MAX_RIB_SIZE*sizeof(struct bgp_rib)); // init the peer struct bzero(&peer, sizeof(struct bgp_peer)); peer.bgp_state = BGP_STATE_ACTIVE; peer.last_ack = time(NULL); // set up signal handler to send a keepalive if the hold time expires act.sa_handler = sig_alrm_handler; sigemptyset(&act.sa_mask); act.sa_flags = SA_RESTART; act.sa_restorer = NULL; if (sigaction(SIGALRM, &act, NULL) == -1) { exit(0); } // set up an initial alarm to make sure clients connect do their thing quickly new_value.it_interval.tv_sec = 5; new_value.it_interval.tv_usec = 0; new_value.it_value.tv_sec = 5; new_value.it_value.tv_usec = 0; if ((i = setitimer(ITIMER_REAL, &new_value, NULL)) != 0) { // if (debug) fprintf(stderr, "Unable to set itimer: %d\n", i); exit(0); } // log the connecting client's info cli_len = sizeof(cli); getpeername(STDOUT_FILENO, (struct sockaddr *)&cli, &cli_len); inet_ntop(AF_INET, &cli.sin_addr, buf, INET_ADDRSTRLEN); // if (debug) fprintf(stderr, "Connection from %s\n", buf); peer.ip = cli.sin_addr; bbgp(); exit(0); }
C
#include "stack.h" #include<stdio.h> int x[10]; int topIndex=0; void push(int a){ if(topIndex < 9) { x[topIndex] = a; topIndex++; }else{ printf("stack is full\n"); } } int pop(){ if(topIndex > 0){ topIndex--; return x[topIndex+1]; }else{ printf("stack is empty\n"); return 0; } }
C
#include "collision.h" #include "forces.h" #include <assert.h> #include <math.h> #include <stdlib.h> const double FORCES_MIN_GRAVITY_DISTANCE = 50; typedef struct gravity_aux { double G; body_t *body1; body_t *body2; } gravity_aux_t; typedef struct spring_aux { double k; body_t *body1; body_t *body2; } spring_aux_t; typedef struct drag_aux { double gamma; body_t *body; } drag_aux_t; typedef struct collision_aux { body_t *body1; body_t *body2; collision_handler_t handler; bool handled_collision; void *aux; free_func_t aux_freer; } collision_aux_t; void force_creator_gravity(gravity_aux_t *aux) { assert(aux); body_t *body1 = aux->body1; body_t *body2 = aux->body2; assert(body1); assert(body2); vector_t r12 = vec_subtract(body_get_centroid(body2), body_get_centroid(body1)); vector_t r21 = vec_negate(r12); double r = vec_magnitude(r12); if (r > FORCES_MIN_GRAVITY_DISTANCE) { double force_mag = aux->G * body_get_mass(body1) * body_get_mass(body2) / (r * r); body_add_force(body1, vec_multiply(force_mag, vec_unit(r12))); body_add_force(body2, vec_multiply(force_mag, vec_unit(r21))); } } void create_newtonian_gravity(scene_t *scene, double G, body_t *body1, body_t *body2) { assert(scene); assert(body1); assert(body2); gravity_aux_t *aux = malloc(sizeof(gravity_aux_t)); assert(aux); aux->G = G; aux->body1 = body1; aux->body2 = body2; list_t *bodies = list_init(2, NULL); list_add(bodies, body1); list_add(bodies, body2); scene_add_bodies_force_creator(scene, (force_creator_t)force_creator_gravity, aux, bodies, free); } void force_creator_spring(spring_aux_t *aux) { assert(aux); body_t *body1 = aux->body1; body_t *body2 = aux->body2; assert(body1); assert(body2); vector_t r12 = vec_subtract(body_get_centroid(body2), body_get_centroid(body1)); vector_t r21 = vec_negate(r12); double r = vec_magnitude(r12); double force_mag = aux-> k * r; body_add_force(body1, vec_multiply(force_mag, vec_unit(r12))); body_add_force(body2, vec_multiply(force_mag, vec_unit(r21))); } void create_spring(scene_t *scene, double k, body_t *body1, body_t *body2) { assert(scene); assert(body1); assert(body2); spring_aux_t *aux = malloc(sizeof(spring_aux_t)); assert(aux); aux->k = k; aux->body1 = body1; aux->body2 = body2; list_t *bodies = list_init(2, NULL); list_add(bodies, body1); list_add(bodies, body2); scene_add_bodies_force_creator(scene, (force_creator_t)force_creator_spring, aux, bodies, free); } void force_creator_drag(drag_aux_t *aux) { assert(aux); body_t *body = aux->body; assert(body); vector_t drag_vec = vec_negate(body_get_velocity(body)); drag_vec = vec_multiply(aux->gamma, drag_vec); body_add_force(body, drag_vec); } void create_drag(scene_t *scene, double gamma, body_t *body) { assert(scene); assert(body); assert(gamma > 0); drag_aux_t *aux = malloc(sizeof(drag_aux_t)); assert(aux); aux->gamma = gamma; aux->body = body; list_t *bodies = list_init(2, NULL); list_add(bodies, body); scene_add_bodies_force_creator(scene, (force_creator_t)force_creator_drag, aux, bodies, free); } void force_creator_collision(collision_aux_t *aux) { assert(aux); body_t *body1 = aux->body1; body_t *body2 = aux->body2; assert(body1); assert(body2); double distance = vec_distance(body_get_centroid(body1), body_get_centroid(body2)); if (distance > body_get_bounding_radius(body1) + body_get_bounding_radius(body2)) { aux->handled_collision = false; return; } collision_info_t* c_info = find_collision(body_get_shape_nocpy(body1), body_get_shape_nocpy(body2)); if (c_info && !aux->handled_collision) { vector_t axis = c_info->axis; if (aux->handler) { aux->handler(body1, body2, axis, aux->aux); } aux->handled_collision = true; } else if (!c_info) { aux->handled_collision = false; } } void create_collision(scene_t *scene, body_t *body1, body_t *body2, collision_handler_t handler, void *aux, free_func_t freer) { assert(scene); assert(body1); assert(body2); collision_aux_t *collision_aux = malloc(sizeof(collision_aux_t)); assert(collision_aux); collision_aux->body1 = body1; collision_aux->body2 = body2; collision_aux->handler = handler; collision_aux->aux = aux; collision_aux->aux_freer = freer; collision_aux->handled_collision = false; list_t *bodies = list_init(2, NULL); list_add(bodies, body1); list_add(bodies, body2); scene_add_bodies_force_creator(scene, (force_creator_t)force_creator_collision, collision_aux, bodies, freer); } void collision_handler_destructive_collision(body_t *body1, body_t *body2, vector_t axis, void *aux) { body_remove(body1); body_remove(body2); } void create_destructive_collision(scene_t *scene, body_t *body1, body_t *body2) { assert(scene); assert(body1); assert(body2); create_collision(scene, body1, body2, (collision_handler_t) collision_handler_destructive_collision, NULL, NULL); } void collision_handler_physics_collision(body_t *body1, body_t *body2, vector_t axis, void *aux) { vector_t vec_impulse = body_calculate_impulse(body1, body2, axis, *(double *)aux); body_add_impulse(body2, vec_negate(vec_impulse)); body_add_impulse(body1, vec_impulse); } void create_physics_collision(scene_t *scene, double elasticity, body_t *body1, body_t *body2) { assert(scene); assert(body1); assert(body2); double *aux = malloc(sizeof(double)); *aux = elasticity; create_collision(scene, body1, body2, (collision_handler_t) collision_handler_physics_collision, aux, free); }
C
#include <ncurses.h> int main(void) { int y,x,r; initscr(); addstr("You Move The Cursor!\n"); addstr("Enter the Y (row) coordinate: "); refresh(); scanw("%d",&y); addstr("Enter the X (column) coordinate: "); refresh(); scanw("%d",&x); r = move(y,x); if(r == OK) { mvaddstr(3,0,"You have moved the cursor!"); move(y,x); } else mvaddstr(3,0,"You cannot move the cursor there!"); refresh(); getch(); endwin(); return 0; }
C
//#define _CRT_SECURE_NO_WARNINGS 1 //#include<stdio.h> //#include<string.h> //char * my_strcpy(char * dst, const char * src) //{ // char * cp = dst; // while (*cp++ = *src++); // return(dst); //} //int main() //{ // char arr = "1234567"; // char*p = arr; // printf("%s ", my_strcpy(p, "zxcvbnm")); // return 0; //} #define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <stdlib.h> char * my_strcpy(char *dst, const char *src) { char *ret = dst; while (*ret++ = *src++) ; return dst; } int main() { char arr[] = "123456"; printf("%s\n", my_strcpy(arr, "abcdef")); return 0; }
C
#include<stdio.h> #include<math.h> #include<locale.h> void main() { char *locale = setlocale(LC_ALL, ""); double x,y; printf(" x y \n"); scanf("%lf%lf", &x, &y); printf("u=%lf", (1-sin(x+y)*sin(x+y))/(2+fabs(x-(2*x*x/(1+fabs(sin(x+y))))))); getch(); }
C
// // Created by dell on 11.10.19. // #include "UI.h" // print current info void print_curr_info() { char cwd[1024]; char* username = getenv("USER"); time_t now; time(&now); printf("\nHello, %s", username); printf("\nIt is : %s", ctime(&now)); getcwd(cwd, sizeof(cwd)); printf("And you are in: %s", cwd); }
C
#include <stdio.h> int main() { long int retTime = time(0) + 10; // Get finishing time. while (time(0) < retTime); printf("andy is an idiot\n"); return 1; }
C
//===-- direct_task.c - Task example with code outlining shown ----*- C -*-===// // // Part of the LOMP Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <stdint.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <omp.h> #define NTASKS 16 /* function prototypes of the runtime */ typedef int32_t (*thunk_ptr_t)(int32_t, void *); void * __kmpc_omp_task_alloc(void *, int32_t, void *, size_t, size_t, thunk_ptr_t); int32_t __kmpc_omp_task(void *, int32_t, void *); void produce_original(double d) { for (int i = 0; i < NTASKS; i++) { // create a new task to for another thread to steal printf("%d: creating task\n", omp_get_thread_num()); #pragma omp task firstprivate(i) firstprivate(d) { double answer = i * d; printf("%d: Hello from task %d and the answer is %lf\n", omp_get_thread_num(), i, answer); } // slow down a little in producing the tasks, so that a worker // can steal the task from the queue sleep(1); } } int32_t __omp_produce_thunk_0(int32_t gtid, void * task) { (void)gtid; char * data = ((char **)task)[0]; int i = *((int *)data); double d = *((double *)(data + 8)); double answer = i * d; printf("%d: Hello from task %d and the answer is %lf\n", omp_get_thread_num(), i, answer); return 0; } void produce_transformed(double d) { for (int i = 0; i < NTASKS; i++) { // create a new task to for another thread to steal printf("%d: creating task\n", omp_get_thread_num()); void * task = __kmpc_omp_task_alloc(NULL, 0, NULL, 40 + 16, 16, __omp_produce_thunk_0); char * data = ((char **)task)[0]; *((int *)data) = i; *((double *)(data + 8)) = d; __kmpc_omp_task(NULL, 0, task); // slow down a little in producing the tasks, so that a worker // can steal the task from the queue sleep(1); } } int32_t __omp_produce_thunk_0_memcpy(int32_t gtid, void * task) { (void)gtid; char * data = ((char **)task)[0]; int i; double d; memcpy(&i, data + 0, sizeof(int)); memcpy(&d, data + 8, sizeof(double)); double answer = i * d; printf("%d: Hello from task %d and the answer is %lf\n", omp_get_thread_num(), i, answer); return 0; } void produce_transformed_memcpy(double d) { for (int i = 0; i < NTASKS; i++) { // create a new task to for another thread to steal printf("%d: creating task\n", omp_get_thread_num()); void * task = __kmpc_omp_task_alloc(NULL, 0, NULL, 40 + 16, 16, __omp_produce_thunk_0_memcpy); char * data = ((char **)task)[0]; memcpy(data + 0, &i, sizeof(int)); memcpy(data + 8, &d, sizeof(double)); __kmpc_omp_task(NULL, 0, task); // slow down a little in producing the tasks, so that a worker // can steal the task from the queue sleep(1); } } void consume() { // This function is only a placeholder to mark a worker thread // as being a consumer. The actual task execution is done in // the barrier of the parallel region. } int main(void) { double d = 42.0; #pragma omp parallel { if (omp_get_thread_num() == 0) { produce_transformed_memcpy(d); } else { consume(); } } return 0; }
C
#include <stdio.h> int input(const char word[]); int add(int a, int b); int subtract(int a, int b); int multiply(int a, int b); double divide(int a, int b); int main() { int value_one, value_two; printf("Type two numbers"); value_one = input(" value one = "); printf("\n"); value_two = input(" value two = "); printf("\n"); printf(" Added:\n"); printf(" %d + %d = %d\n", value_one, value_two, add(value_one, value_two) ); printf(" subtracted:\n"); printf(" %d - %d = %d\n", value_one, value_two, subtract(value_one, value_two) ); printf(" multiplied:\n"); printf(" %d * %d = %d\n", value_one, value_two, multiply(value_one, value_two) ); printf(" divided\n"); printf(" %d / %d = %.3f\n", value_one, value_two, divide(value_one, value_two) ); return 0; } int input(const char word[]) { int value; printf("%s", word); scanf("%d", &value); return value; } int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; } int multiply(int a, int b) { return a * b; } double divide(int a, int b) { return (double)a / b; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #pragma warning(disable:4996) void rhanoi(int n, char from, char aux, char to) { if (n == 1) { printf("%c %c\n", from, to); return; } rhanoi(n - 1, from, to, aux); printf("%c %c\n", from, to); rhanoi(n - 1, aux, from, to); } void hanoi(int n) { rhanoi(n, 'A', 'B', 'C'); } int main() { int N = 0; scanf("%d", &N); hanoi(N); return 0; }
C
//No_more_space.c: Cancella gli spazi di troppo in un testo /* * Copyright © 2020 Lorenzo Fiocco <[email protected]> * This program is free software. It comes without any warranty, to * the extent permitted by applicable law. You can redistribute it * and/or modify it under the terms of the Do What The Fuck You Want * To Public License, Version 2, as published by Sam Hocevar. See * http://www.wtfpl.net/ for more details. */ #include <stdio.h> /* Variabili utilizzate INPUT c (intero): contiene il codice ASCII del carattere inserito da console */ int main(){ int c; //Dichiarazione della variabile intera c while ((c = getchar()) != EOF){ //Prima legge il valore da input e poi esegue i comandi tra {} fintanto che c non è uguale a EOF if (c == ' '){ //Verifica se il valore inserito da input è uno spazio in caso positivo esegue i comandi tra {} putchar(' '); //Stampa uno spazio while (((c = getchar()) == ' ') && (c != EOF)){} //Legge il successivo carattere inserito da input e fitanto che equivale a uno spazio non effettua alcuna operazione } putchar(c); //Stampa il carattere in c (ovvero il carattere letto da input) } return 0; }
C
#include "helper.h" #include <stdio.h> #include <stdlib.h> #include <time.h> #include <assert.h> #include <stdbool.h> #include <stdint.h> #include <string.h> extern int* GenerateRandomArray(int start,int end,long long size); extern void TestSorting(sortfunc_p func,char* func_name,int* arr,long long size); extern int* GenerateNearlyOrderedArray(long long size, int num_swap); extern void swap(int* arr, int index1, int index2); extern void MaxHeap_Init(maxheap_p maxheap, int capacity); extern bool MaxHeap_Insert(maxheap_p maxheap, int value); extern int MaxHeap_Pop(maxheap_p maxheap); extern void MaxHeap_Del(maxheap_p maxheap); extern bool MaxHeap_IsEmpty(maxheap_p maxheap); extern int MaxHeap_Size(maxheap_p maxheap); extern void MaxHeap_ArrInit(maxheap_p maxheap, int* arr, int n); static bool IsSorted(int* arr,int size); static void _shiftup(maxheap_p maxheap, int k); static void _shiftdown(maxheap_p maxheap, int k); /* * Public functions */ inline void swap(int* arr, int index1, int index2){ int temp = arr[index1]; arr[index1] = arr[index2]; arr[index2] = temp; return; } void MaxHeap_Init(maxheap_p maxheap, int capacity){ assert(capacity > 0); maxheap->elems = malloc(sizeof(int) * (capacity + 1)); memset(maxheap->elems, sizeof(int)*(capacity+1), 0); assert(maxheap->elems != NULL); maxheap->num_elems = 0; maxheap->capacity = capacity; } void MaxHeap_ArrInit(maxheap_p maxheap, int* arr, int n){ maxheap->elems = malloc(sizeof(int) * (n + 1)); maxheap->capacity = n; for (int i = 0; i < n; i++) maxheap->elems[i+1] = arr[i]; maxheap->num_elems = n; for (int i = maxheap->num_elems/2; i >= 1; i--) { _shiftdown(maxheap, i); } } bool MaxHeap_Insert(maxheap_p maxheap, int value){ if(maxheap->num_elems+1 <= maxheap->capacity){ maxheap->elems[++(maxheap->num_elems)] = value; _shiftup(maxheap, maxheap->num_elems); return true; } return false; } int MaxHeap_Pop(maxheap_p maxheap){ if(maxheap->num_elems <= 0) return -1; int ret = maxheap->elems[1]; swap(maxheap->elems, 1, maxheap->num_elems--); _shiftdown(maxheap, 1); return ret; } void MaxHeap_Del(maxheap_p maxheap){ assert(maxheap != NULL); free(maxheap->elems); } bool MaxHeap_IsEmpty(maxheap_p maxheap){ assert(maxheap != NULL); return maxheap->num_elems == 0; } int MaxHeap_Size(maxheap_p maxheap){ assert(maxheap != NULL); return maxheap->num_elems; } int* GenerateRandomArray(int start, int end, long long size){ srand(time(NULL)); int* arr = malloc(sizeof(int) * size); assert(arr != NULL); int range = end - start; for (int i = 0; i < size; i++) { arr[i] = rand()%range + start; } return arr; } int* GenerateNearlyOrderedArray(long long size, int num_swap){ srand(time(NULL)); int* arr = malloc(sizeof(int) * size); for (long long i = 0; i < size; i++) arr[i] = i; for (long long i = 0; i < num_swap; i++) { long long index1 = rand()%size; long long index2 = rand()%size; swap(arr, index1, index2); } return arr; } void TestSorting(sortfunc_p func,char* func_name,int* arr, long long size){ clock_t t1, t2; t1 = clock(); func(arr, size); assert(IsSorted(arr,size)); /* for (int i = 0 ; i < size; i++) { */ /* printf("%d ", arr[i]); */ /* } */ /* printf("\n"); */ t2 = clock(); float diff = ((float)(t2 - t1) / 1000000.0F ); /* printf("%f",diff); */ printf("%s: %f seconds. Size: %lld\n", func_name, diff, size); } /* * Private functions */ bool IsSorted(int* arr, int size){ for (int i = 1; i < size; i++) { if (arr[i] < arr[i-1]) { return false; } } return true; } void _shiftup(maxheap_p maxheap, int k){ while(maxheap->elems[k/2] < maxheap->elems[k]){ swap(maxheap->elems, k/2, k); k /= 2; } } void _shiftdown(maxheap_p maxheap, int k){ while(2*k <= maxheap->num_elems){ int j = 2*k; if(j + 1 <= maxheap->num_elems && maxheap->elems[j+1] > maxheap->elems[j]) j += 1; if(maxheap->elems[k] >= maxheap->elems[j]) break; swap(maxheap->elems, k, j); k = j; } }
C
#include<stdio.h> int main() {int a[2][2]={5,4,4,4}; int b[2][2]={6,7,8,9}; int c[2][2],i,j,k,sum; printf("matrix A is:\n\t\t"); for(i=0;i<2;i++) {for(j=0;j<2;j++) printf("%d\t",a[i][j]); printf("\n\t\t"); } printf("\n matrix B is :\n\t\t"); for(i==0;i<2;i++) { for(j=0;j<2;j++) printf("%d\t",b[i][j]); printf("\n\t\t"); } printf("\n multiplication os A and B IS:n\t\t"); for(i=0;i<2;i++) {for(j=0;j<2;j++) {sum=0;for(k=0;k<2;k++) sum=sum+a[i][k]*b[k][j]; c[i][j]=sum; printf("%d\t ", c[i][j]); } printf("\n\t\t"); }getch(); return 0; }
C
//https://www.hackerrank.com/challenges/acm-icpc-team/problem #include<stdio.h> #include<stdlib.h> void Perform_BitwiseOR(int n, int m, int *topic[]){ int i,j,s,a,max,c; a=s=max=0; for( i=0; i<n; i++ ){ for( j=i+1; j<n ; j++ ){ s=0; for( int k=0; k<m ; k++) { c=topic[i][k]|topic[j][k]; s=s+c; } if(s>max) { max=s; a=1;} else if(s==max) a++; } } printf("%d\n%d",max,a); } int main(){ int n; int m,s=0; char c; scanf("%d %d",&n,&m); int* topic[n]; for(int i = 0; i < n; i++){ topic[i] = (int *)malloc(m * sizeof(int)); getchar(); for( int k=0; k<m ; k++) { scanf("%c",&c); topic[i][k]=c-'0'; } } Perform_BitwiseOR(n,m,topic); return 0; }
C
#define _GNU_SOURCE #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <sys/wait.h> #include <sys/types.h> #include <pthread.h> #include <sched.h> #include <signal.h> #define DIF 16 #define NUM_THREADS 4 #define STACK_SIZE (1024*12600) #pragma pack(2) // 2 bytes packaging typedef struct { unsigned char magic1; unsigned char magic2; unsigned int size; unsigned short int reserved1, reserved2; unsigned int pixel_offset; // image offset } Header; #pragma pack() // Default packaging typedef struct { unsigned int size; // Size of this header int cols, rows; // Image columns and rows unsigned short int planes; unsigned short int bits_per_pixel; // Bits per pixel unsigned int compression; unsigned int cmp_size; int x_scale, y_scale; unsigned int num_colors; unsigned int important_colors; } InfoHeader; typedef struct { unsigned char red; unsigned char green; unsigned char blue; } Pixel; typedef struct { Header header; InfoHeader infoheader; Pixel *pixel; } Image; Image source_image, dest_image; int load_bmp(char* filename, Image* image) { int totpixs = 0; FILE* fp = fopen(filename, "rb+"); if (fp == NULL) { return -1; } // Read header fread(&image->header, sizeof(Header), 1, fp); // Check if its a BMP file if (!(image->header.magic1 == 'B' && image->header.magic2 == 'M')) { return -1; } fread(&image->infoheader, sizeof(InfoHeader), 1, fp); // Check if it's a BMP file 24 bits uncompressed if (image->infoheader.bits_per_pixel != 24 || image->infoheader.compression) { return -1; } image->pixel = (Pixel*)malloc(sizeof(Pixel) * image->infoheader.cols * image->infoheader.rows); totpixs = image->infoheader.rows * image->infoheader.cols; for (int i = 0; i < totpixs; i += 512) { fread(image->pixel + i, sizeof(Pixel), 512, fp); } fclose(fp); return 0; } int save_bmp(char *filename, Image *image) { int totpixs; FILE* fp = fopen(filename,"wb"); if (fp == NULL) { return -1; } // Write header fwrite(&image->header, sizeof(Header), 1, fp); // Write header info fwrite(&image->infoheader, sizeof(InfoHeader), 1, fp); totpixs = image->infoheader.rows*image->infoheader.cols; for (int i = 0; i < totpixs; i += 512) { fwrite(image->pixel + i, sizeof(Pixel), 512, fp); } fclose(fp); return 0; } unsigned char black_and_white(Pixel p) { float red = (float) p.red, green = (float) p.green, blue = (float) p.blue; return (unsigned char) (0.3*red + 0.59*green + 0.11*blue); } int process_bmp(void* arg) { //printf("Arrived the function"); int image_rows, image_cols; int thread_id = *((int*)arg); Pixel *psrc, *pdst, *v0, *v1, *v2, *v3, *v4, *v5, *v6, *v7; image_rows = source_image.infoheader.rows; image_cols = source_image.infoheader.cols; // printf("Image rows: %d Image cols: %d", image_rows, image_cols); for (int i = 1; i < image_rows - 1; i++) { for (int j = 1; j < image_cols - 1; j++) { if ((i * (image_rows - 1) + j) % NUM_THREADS != thread_id) { continue; } psrc = source_image.pixel + image_cols*i + j; v0 = psrc - image_cols - 1; v1 = psrc - image_cols; v2 = psrc - image_cols + 1; v3 = psrc - 1; v4 = psrc + 1; v5 = psrc + image_cols - 1; v6 = psrc + image_cols; v7 = psrc + image_cols + 1; pdst = dest_image.pixel + image_cols*i + j; if (abs(black_and_white(*psrc) - black_and_white(*v0)) > DIF || abs(black_and_white(*psrc) - black_and_white(*v1)) > DIF || abs(black_and_white(*psrc) - black_and_white(*v2)) > DIF || abs(black_and_white(*psrc) - black_and_white(*v3)) > DIF || abs(black_and_white(*psrc) - black_and_white(*v4)) > DIF || abs(black_and_white(*psrc) - black_and_white(*v5)) > DIF || abs(black_and_white(*psrc) - black_and_white(*v6)) > DIF || abs(black_and_white(*psrc) - black_and_white(*v7)) > DIF) { pdst->red = 0; pdst->green = 0; pdst->blue = 0; } else { pdst->red = 255; pdst->green = 255; pdst->blue = 255; } } } return 0; } int main(int argc, char* argv[]) { int res, image_rows, image_cols; char namedest[80]; char filename[80]; long long start_ts; long long stop_ts; long long elapsed_time; int thread_ids[NUM_THREADS]; struct timeval ts; char *stack[NUM_THREADS]; char *stackTop[NUM_THREADS]; gettimeofday(&ts, NULL); start_ts = ts.tv_sec * 1000000 + ts.tv_usec; // Initial time if (argc < 2) { printf("Usage: ./main filename\n"); exit(-1); } strcpy(filename, argv[1]); strcpy(namedest, strtok(filename, ".")); strcat(filename, ".bmp"); strcat(namedest, "_P.bmp"); printf("Source file: %s\n", filename); printf("Dest file: %s\n", namedest); res = load_bmp(filename, &source_image); if (res == -1) { fprintf(stderr,"Error when opening the image\n"); exit(1); } image_rows = source_image.infoheader.rows; image_cols = source_image.infoheader.cols; printf("Processing image with %d rows and %d columns\n", image_rows, image_cols); // Initialize destination image memcpy(&dest_image, &source_image, sizeof(Image) - sizeof(Pixel*)); dest_image.pixel = (Pixel *)malloc(sizeof(Pixel) * image_rows * image_cols); for (int i = 0; i < NUM_THREADS; i++) { stack[i] = malloc(STACK_SIZE); if (stack[i] == NULL) { return -1; } stackTop[i] = stack[i] + STACK_SIZE; /* Assume stack grows downwards */ } for (int i = 0; i < NUM_THREADS; i++) { thread_ids[i] = i; clone(process_bmp, stackTop[i], CLONE_VM | SIGCHLD , (void*)&thread_ids[i]); } for (int i=0; i < NUM_THREADS; i++) { wait(NULL); } res = save_bmp(namedest, &dest_image); if (res == -1) { fprintf(stderr,"Error when writting the image\n"); exit(1); } gettimeofday(&ts, NULL); stop_ts = ts.tv_sec * 1000000 + ts.tv_usec; // Final time elapsed_time = stop_ts - start_ts; printf("Time: %2.3f seconds\n", (float)elapsed_time/1000000.0); return 0; }
C
#include <stm32f4_discovery.h> #include <os.h> #include <stdlib.h> // Sleeping barber problem #define BARBERS 2 // num of barbers #define CUSTOMERS 4 // num of chairs in the waiting room #define DELAY 256 // time constant OS_MTX(doors, mtxDefault); OS_SEM(barbers, 0); OS_SEM(customers, 0); OS_SEM(end_of_haircut, 0); int free_seats = CUSTOMERS; // num of free seats in the waiting room void cut_hair() { static cnt_t dly = 0; dly = (dly + 4) % DELAY; tsk_delay(dly * MSEC); sem_give(end_of_haircut); } void get_haircut() { LED_Tick(); sem_wait(end_of_haircut); } void barber() { for (;;) { sem_wait(customers); mtx_lock(doors); free_seats++; sem_give(barbers); mtx_unlock(doors); cut_hair(); } } void customer() { mtx_lock(doors); if (free_seats > 0) { free_seats--; sem_give(customers); mtx_unlock(doors); sem_wait(barbers); get_haircut(); } else { mtx_unlock(doors); } tsk_delete(SELF); } int main() { cnt_t dly; int i; srand(0); LED_Init(); for (i = 0; i < BARBERS; i++) tsk_new(1, barber); for (;;) { tsk_new(1, customer); dly = (unsigned)rand() % DELAY; tsk_delay(dly * MSEC); } }
C
#include <stdio.h> #include <sys/stat.h> #include <stdlib.h> #include <string.h> #include "md5.c" #define BLOCKSIZE 64 unsigned long b = 0; // length (bits) of input block unsigned long kLength = 0; // length (bits) of input key char *M; // Message char *k; // 密钥 char *KPlus; // 根据输入内容和密钥生成的数据块 char *Si; // K+ ^ ipad char *So; // K+ ^ opad #define ipad 0x36 // 00110110 #define opad 0x5c // 01011100 /** * 获取文件的大小,并设置初始的相关值 * @param inputFilename char* 输入文件名 * @param keyFilename char* 密钥文件名 * @return 1 | 0 ,其中0代表密钥不符合要求 */ int getFileSize(char *inputFilename, char *keyFilename); /** * 生成 K+ ,顺带生成 Si 和 So */ void generateKPlus(); /** * 哈希函数 * @param S unsigned char* 第一个字符串 * @param SLength unsigned long 第一个字符串的长度 * @param M unsigned char* 第二个字符串 * @param MLength unsigned long 第二个字符串的长度 * @return MD5_CTX 结构体 */ MD5_CTX Hash(unsigned char *S, unsigned long SLength, unsigned char *M, unsigned long MLength); /** * 释放内存 */ void freeAll(); int main(int argc, char *argv[]) { if (argc != 3) { printf("usage: ./a.out inputFile keyFile\n"); return 0; } else { FILE *inputFile, *keyFile; if (!getFileSize(argv[1], argv[2])) { printf("密钥和文本不匹配\n"); return 0; } inputFile = fopen(argv[1], "r"); keyFile = fopen(argv[2], "r"); fread(M, 1, b, inputFile); fread(k, 1, kLength, keyFile); generateKPlus(); printf("消息为:\n%s\n", M); // 第一次哈希 MD5_CTX firstResult = Hash(Si, BLOCKSIZE, M, b); // 第一次结果 unsigned char firstResultString[16]; // 第一次结果的字符串 MD5_Encode(firstResult.content, firstResultString, 4); printf("第一次结果:\n"); for (int i = 0; i < 4 * 4; i++) { printf("%02x", firstResultString[i]); } putchar('\n'); //第二次哈希 MD5_CTX secondResult = Hash(So, BLOCKSIZE, firstResultString, 16); // 第二次结果 unsigned char secondResultString[16]; // 第二次结果的字符串 printf("第二次结果:\n"); MD5_Encode(secondResult.content, secondResultString, 4); for (int i = 0; i < 4 * 4; i++) { printf("%02x", secondResultString[i]); } putchar('\n'); fclose(inputFile); fclose(keyFile); freeAll(); return 0; } } MD5_CTX Hash(unsigned char *S, unsigned long SLength, unsigned char *M, unsigned long MLength) { /** * 拼接两个字符串 * 不敢用 strcat() 怕有 0 的存在 */ unsigned char SM[MLength + SLength + 1]; SM[SLength + MLength] = 0; // 第一段 for (unsigned long i = 0; i < SLength; i++) { SM[i] = S[i]; } // 第二段 for (unsigned long i = 0; i < MLength; i++) { SM[i + SLength] = M[i]; } MD5_CTX res = MD5(SM, SLength + MLength); return res; } void freeAll() { free(M); free(k); free(KPlus); free(Si); free(So); } int getFileSize(char *inputFilename, char *keyFilename) { struct stat inputFileBuffer, keyFileBuffer; stat(inputFilename, &inputFileBuffer); stat(keyFilename, &keyFileBuffer); b = inputFileBuffer.st_size; // 消息大小 kLength = keyFileBuffer.st_size; // 密钥长度 printf("文件大小为 %ld 字节\n密钥长度为 %ld 字节\n", b, kLength); // 如果密钥不符合要求 if (BLOCKSIZE < kLength) { return 0; } else { M = (char *)malloc(b); k = (char *)malloc(BLOCKSIZE); return 1; } } void generateKPlus() { KPlus = (char *)malloc(BLOCKSIZE); // 右边补位0 for (unsigned long i = 0; i < kLength; i++) { KPlus[i] = k[i]; } for (unsigned long i = kLength; i < BLOCKSIZE; i++) { KPlus[i] = 0; } // 顺带获取 Si 和 So Si = (char *)malloc(BLOCKSIZE); So = (char *)malloc(BLOCKSIZE); for (unsigned long i = 0; i < BLOCKSIZE; i++) { Si[i] = KPlus[i] ^ ipad; So[i] = KPlus[i] ^ opad; } }
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <limits.h> /* int a = 5; void changeValue() { a = 10; } void process() { static int a = 5; a = a + 1; printf("%d\n", a); } void add(int* a, int b) { *a = *a + b; } */ //int a[3][3] = { {1,2,3}, {4,5,6}, {7,8,9} }; //int a[2][3][3] = { { {1,2,3}, {4,5,6}, {7,8,9} }, { {1,2,3}, {4,5,6}, {7,8,9} } }; int main(void) { /* printf("%d\n", a); changeValue(); printf("%d\n", a); */ /* int a = 7; if (1) { int a = 5; } printf("%d\n", a); */ /* process(); */ /* register int a = 10, i; for ( i = 0; i < a; i++) { printf("%d ", i); } */ /* int a = 7; add(&a, 10); printf("%d\n", a); */ /* int i, j; for ( i = 0; i < 3; i++) { for ( j = 0; j < 3; j++) { printf("%d ", a[i][j]); } printf("\n"); } */ /* int i, j, k; for (i = 0; i < 2; i++) { for (j = 0; j < 3; j++) { for ( k = 0; k < 3; k++) { printf("%d ", a[i][j][k]); } printf("\n"); } printf("\n"); } */ /* int a = 10; int b[10]; b = &a; */ /* int a[5] = { 1,2,3,4,5 }; int* b = a; printf("%d\n", b[2]); */ /* int a[5] = { 1,2,3,4,5 }; int i; for ( i = 0; i < 5; i++) { printf("%d ", *(a + i)); } */ /* double b[10]; printf("%d %d\n", b, b + 9); */ /* int a[5] = { 1,2,3,4,5 }; int* p = a; printf("%d\n", *(p++)); printf("%d\n", *(++p)); printf("%d\n", *(p+2)); */ int a[2][5] = { {1,2,3,4,5},{6,7,8,9,10} }; int (*p)[5] = a[1]; int i; for ( i = 0; i < 5; i++) { printf("%d ", p[0][i]); } system("pause"); return 0; }
C
#include "jackCompiler.h" static void del_source(void *source_void); static void del_token(void *token_void); void ft_free_sources(t_list **src_files) { if (src_files) { ft_lstclear(src_files, del_source); free(src_files); } } static void del_source(void *source_void) { t_srcFile *source = (t_srcFile *)source_void; if (source) { if (source->src_name) free(source->src_name); if (source->dst_name) free(source->dst_name); free(source); } } void ft_free_tokens(t_list **tokens) { if (tokens) { ft_lstclear(tokens, del_token); free(tokens); } } static void del_token(void *token_void) { t_token *token = (t_token *)token_void; if (token) { if (token->identifier) free(token->identifier); if (token->stringval) free(token->stringval); free(token); } }
C
/* ** list_insert.c for in /home/lejard_h/my_lib_c/list ** ** Made by hadrien lejard ** Login <[email protected]> ** ** Started on Fri Mar 7 15:39:47 2014 hadrien lejard ** Last update Thu Jul 10 13:44:59 2014 lejard_h */ #include <stdlib.h> #include "list.h" t_list *list_insert_after(t_list *elem, void *data) { t_list *new; if (elem == NULL) list_error("Null element."); if ((new = malloc(sizeof(*new))) == NULL) list_error("malloc failed."); new->data = data; new->prev = elem; new->next = elem->next; if (elem->next) elem->next->prev = new; elem->next = new; return (new); } t_list *list_insert_before(t_list **begin, t_list *elem, void *data) { t_list *new; if (elem == NULL) list_error("Null element."); if ((new = malloc(sizeof(*new))) == NULL) list_error("malloc failed."); new->data = data; new->prev = elem->prev; new->next = elem; if (elem->prev) elem->prev->next = new; else *begin = new; elem->prev = new; return (new); } t_list *list_insert_elem_after(t_list *elem, t_list *after) { if (elem == NULL) list_error("Null element."); if (elem->next) elem->next->prev = after; after->next = elem->next; after->prev = elem; elem->next = after; return (after); } t_list *list_insert_elem_before(t_list **begin, t_list *elem, t_list *before) { if (elem == NULL) list_error("Null element."); before->prev = elem->prev; before->next = elem; if (elem->prev) elem->prev->next = before; else *begin = before; elem->prev = before; return (before); }
C
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #define MAX_LENGTH 0xFF void print_array(uint8_t *array, uint8_t array_size) { int i; for( i = 0; i < array_size; i++) { printf("%d", array[i]); if(i < (array_size - 1)) { printf(","); } } printf("\n"); } uint8_t* rmNdub(uint8_t *input, uint8_t n, uint8_t input_length, uint8_t output[], uint8_t *output_length) { uint8_t temp[MAX_LENGTH] = { 0 }; uint8_t i = 0; if(input == NULL) { return NULL; } if(n >= MAX_LENGTH) { return NULL; } if(output == NULL) { output = (uint8_t*)malloc(sizeof(uint8_t) * MAX_LENGTH); } *output_length = 0; for(i = 0; i < input_length; i++) { if(++temp[input[i]] >= n) { continue; } else { output[*output_length] = input[i]; *output_length += 1; } } return output; } int main(int argc, char *argv[]) { /*** Input data ***/ uint8_t n = 3; uint8_t array[] = {1, 2, 2, 3, 5, 2, 4, 5, 5, 2}; /******************/ uint8_t *output_array = NULL; uint8_t output_length = 0; uint8_t array_length; array_length = sizeof(array)/sizeof(array[0]); printf("Input:\t"); print_array(array, array_length); output_array = rmNdub(array, n, array_length, output_array, &output_length); if(output_array == NULL) { printf("Something went wrong... \n"); return 0; } printf("Output:\t"); print_array(output_array, output_length); if(output_array != NULL) { free(output_array); } return 0; }
C
#include "NU32.h" // cache on, interrupts on, LED/button init, UART init #include "i2c_display.h" #include "accel.h" // the game of snake, on an oled display. eat those pixels! #define MAX_LEN WIDTH*HEIGHT typedef struct { int head; int tail; int rows[MAX_LEN]; int cols[MAX_LEN]; } snake_t; // hold the snake // direction of the snake typedef enum {NORTH = 0, EAST = 1, SOUTH = 2, WEST= 3} direction_t; // grow the snake in the appropriate direction, returns false if snake has crashed int snake_grow(snake_t * snake, direction_t dir) { int hrow = snake->rows[snake->head]; int hcol = snake->cols[snake->head]; ++snake->head; if(snake->head == MAX_LEN) { snake->head = 0; } switch(dir) { // move the snake in the appropriate direction case NORTH: snake->rows[snake->head] = hrow -1; snake->cols[snake->head] = hcol; break; case SOUTH: snake->rows[snake->head] = hrow + 1; snake->cols[snake->head] = hcol; break; case EAST: snake->rows[snake->head] = hrow; snake->cols[snake->head] = hcol + 1; break; case WEST: snake->rows[snake->head] = hrow; snake->cols[snake->head] = hcol -1; break; } // check for collisions with the wall or with itself and return 0, otherwise return 1 if(snake->rows[snake->head] < 0 || snake->rows[snake->head] >= HEIGHT || snake->cols[snake->head] < 0 || snake->cols[snake->head] >= WIDTH) { return 0; } else if(display_pixel_get(snake->rows[snake->head],snake->cols[snake->head]) == 1) { return 0; } else { display_pixel_set(snake->rows[snake->head],snake->cols[snake->head],1); return 1; } } void snake_move(snake_t * snake) { // move the snake by deleting the tail display_pixel_set(snake->rows[snake->tail],snake->cols[snake->tail],0); ++snake->tail; if(snake->tail == MAX_LEN) { snake->tail = 0; } } int main(void) { NU32_Startup(); display_init(); acc_setup(); while(1) { snake_t snake = {5, 0, {20,20,20,20,20,20},{20,21,22,23,24,25}}; int dead = 0; direction_t dir = EAST; char dir_key = 0; char buffer[3]; int i; int crow, ccol; int eaten = 1; int grow = 0; short acc[2]; // x and y accleration short mag; for(i = snake.tail; i <= snake.head; ++i) { // draw the initial snake display_pixel_set(snake.rows[i],snake.cols[i],1); } display_draw(); acc_read_register(OUT_X_L_M,(unsigned char *)&mag,2); srand(mag); // seed the random number generator with the magnetic field // (not the most random, but good enough for this game) while(!dead) { if(eaten) { crow = rand() % HEIGHT; ccol = rand() % WIDTH; display_pixel_set(crow,ccol,1); eaten = 0; } //determine direction based on largest magnitude accel and its direction acc_read_register(OUT_X_L_A,(unsigned char *)&acc,4); if(abs(acc[0]) > abs(acc[1])) { // move snake in direction of largest acceleration if(acc[0] > 0) { // prevent snake from turning 180 degrees, if(dir != EAST) { // resulting in an automatic self crash dir = WEST; } } else if( dir != WEST) { dir = EAST; } } else { if(acc[1] > 0) { if( dir != SOUTH) { dir = NORTH; } } else { if( dir != NORTH) { dir = SOUTH; } } } if(snake_grow(&snake,dir)) { snake_move(&snake); } else if(snake.rows[snake.head] == crow && snake.cols[snake.head] == ccol) { eaten = 1; grow += 15; } else { dead = 1; display_clear(); } if(grow > 0) { snake_grow(&snake,dir); --grow; } display_draw(); } } 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 */ typedef struct TYPE_6__ TYPE_1__ ; /* Type definitions */ typedef scalar_t__ png_uint_32 ; typedef TYPE_1__* png_structrp ; typedef int /*<<< orphan*/ png_byte ; struct TYPE_6__ {void* io_state; scalar_t__ chunk_name; } ; /* Variables and functions */ int /*<<< orphan*/ PNG_CSTRING_FROM_CHUNK (int /*<<< orphan*/ *,scalar_t__) ; void* PNG_IO_CHUNK_DATA ; void* PNG_IO_CHUNK_HDR ; void* PNG_IO_WRITING ; int /*<<< orphan*/ png_calculate_crc (TYPE_1__*,int /*<<< orphan*/ *,int) ; int /*<<< orphan*/ png_debug2 (int /*<<< orphan*/ ,char*,int /*<<< orphan*/ *,unsigned long) ; int /*<<< orphan*/ png_reset_crc (TYPE_1__*) ; int /*<<< orphan*/ png_save_uint_32 (int /*<<< orphan*/ *,scalar_t__) ; int /*<<< orphan*/ png_write_data (TYPE_1__*,int /*<<< orphan*/ *,int) ; __attribute__((used)) static void png_write_chunk_header(png_structrp png_ptr, png_uint_32 chunk_name, png_uint_32 length) { png_byte buf[8]; #if defined(PNG_DEBUG) && (PNG_DEBUG > 0) PNG_CSTRING_FROM_CHUNK(buf, chunk_name); png_debug2(0, "Writing %s chunk, length = %lu", buf, (unsigned long)length); #endif if (png_ptr == NULL) return; #ifdef PNG_IO_STATE_SUPPORTED /* Inform the I/O callback that the chunk header is being written. * PNG_IO_CHUNK_HDR requires a single I/O call. */ png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_HDR; #endif /* Write the length and the chunk name */ png_save_uint_32(buf, length); png_save_uint_32(buf + 4, chunk_name); png_write_data(png_ptr, buf, 8); /* Put the chunk name into png_ptr->chunk_name */ png_ptr->chunk_name = chunk_name; /* Reset the crc and run it over the chunk name */ png_reset_crc(png_ptr); png_calculate_crc(png_ptr, buf + 4, 4); #ifdef PNG_IO_STATE_SUPPORTED /* Inform the I/O callback that chunk data will (possibly) be written. * PNG_IO_CHUNK_DATA does NOT require a specific number of I/O calls. */ png_ptr->io_state = PNG_IO_WRITING | PNG_IO_CHUNK_DATA; #endif }
C
/* ** EPITECH PROJECT, 2019 ** MyFTP ** File description: ** Test file of the argument parser functions */ #include <criterion/criterion.h> #include "argument.h" Test(argument_parser, no_argument) { argument_t args = {}; int argc = 1; char **argv = malloc(sizeof(char *) * (argc + 1)); argv[0] = strdup("myftp"); argv[1] = NULL; args = parse_argument(argc, argv); cr_assert_eq(args.valid, false); } Test(argument_parser, helper_argument) { argument_t args = {}; int argc = 2; char **argv = malloc(sizeof(char *) * (argc + 1)); argv[0] = strdup("myftp"); argv[1] = strdup("-h"); argv[2] = NULL; args = parse_argument(argc, argv); cr_assert_eq(args.valid, true); cr_assert_eq(args.helper, true); } Test(argument_parser, regular_argument) { argument_t args = {}; int argc = 3; char **argv = malloc(sizeof(char *) * (argc + 1)); argv[0] = strdup("myftp"); argv[1] = strdup("8888"); argv[2] = strdup("./directory"); argv[3] = NULL; args = parse_argument(argc, argv); cr_assert_eq(args.valid, true); cr_assert_eq(args.helper, false); cr_assert_eq(args.port, 8888); cr_assert_str_eq(args.path, "./directory"); } Test(argument_parser, not_a_port) { argument_t args = {}; int argc = 3; char **argv = malloc(sizeof(char *) * (argc + 1)); argv[0] = strdup("myftp"); argv[1] = strdup("toto"); argv[2] = strdup("./directory"); argv[3] = NULL; args = parse_argument(argc, argv); cr_assert_eq(args.valid, false); }
C
#define _GNU_SOURCE #include <errno.h> #include <error.h> #include <fcntl.h> #include <inttypes.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #define PARAM_0 0x0001 #define PARAM_1 0x0002 #define PARAM_2 0x0004 // future proofing #define PARAM_3 0x0008 #define PARAM_4 0x0010 #define PARAM_5 0x0020 #define PARAM_6 0x0040 #define PARAM_7 0x0080 const int param_flags[] = {PARAM_0, PARAM_1, PARAM_2, PARAM_3, PARAM_4, PARAM_5, PARAM_6, PARAM_7}; size_t populateCode( int **code, char *input ) { char *end = input; size_t array_len = 1024; size_t code_len = 0; *code = malloc( array_len * sizeof( int ) ); if ( code == NULL ) error( EXIT_FAILURE, errno, "malloc" ); while ( *end != '\0' && *end != '\n' ) { ( *code )[code_len] = strtoimax( input, &end, 10 ); input = end + 1; code_len++; if ( code_len == array_len ) { array_len *= 2; int *tmp = realloc( *code, array_len ); if ( tmp == NULL ) error( EXIT_FAILURE, errno, "realloc" ); *code = tmp; } } return code_len; } void testOutOfBounds( size_t code_len, size_t position ) { if ( position >= code_len ) error( EXIT_FAILURE, 0, "INSTRUCTION POINTS BEYOND ARRAY, INDEX: %zu\n", position ); } int getInstruction( int code, size_t *flags ) { int ret = code % 100; code /= 100; int i = 0; while ( code > 0 ) { if ( code % 10 == 1 ) *flags |= param_flags[i]; code /= 10; i++; } return ret; } void compute( int *code, size_t code_len ) { int res = 0; int temp_param = 0; char *end = NULL; char *input = NULL; size_t input_len = 0; size_t flags = 0; int instruction = 0; for ( size_t i = 0; i < code_len; ) { instruction = getInstruction( code[i], &flags ); switch ( instruction ) { case 1: case 2: testOutOfBounds( code_len, i + 3 ); if ( flags & PARAM_0 ) { res = code[i + 1]; } else { testOutOfBounds( code_len, code[i + 1] ); res = code[code[i + 1]]; } if ( flags & PARAM_1 ) { temp_param = code[i + 2]; } else { testOutOfBounds( code_len, code[i + 2] ); temp_param = code[code[i + 2]]; } if ( instruction == 1 ) res += temp_param; else res *= temp_param; if ( flags & PARAM_2 ) { error( EXIT_FAILURE, 0, "LAST PARAM MUST BE IN MODE 0! Index: %zu", i ); } else { testOutOfBounds( code_len, code[i + 3] ); code[code[i + 3]] = res; } i += 4; break; case 3: testOutOfBounds( code_len, i + 1 ); // printf( "INPUT: " ); if ( flags & PARAM_0 ) { error( EXIT_FAILURE, 0, "LAST PARAM MUST BE IN MODE 0! Index: %zu", i ); } else { testOutOfBounds( code_len, code[i + 1] ); getline( &input, &input_len, stdin ); res = strtoimax( input, &end, 10 ); if ( *end != '\n' && *end != '\0' ) error( EXIT_FAILURE, 0, "GOT INPUT THAT'S NOT AN INTEGER: '%s'\n", input ); code[code[i + 1]] = res; } i += 2; break; case 4: testOutOfBounds( code_len, i + 1 ); if ( flags & PARAM_0 ) { printf( "%i\n", code[i + 1] ); } else { testOutOfBounds( code_len, code[i + 1] ); printf( "%i\n", code[code[i + 1]] ); } i += 2; break; case 5: case 6: testOutOfBounds( code_len, i + 2 ); if ( flags & PARAM_0 ) { temp_param = code[i + 1]; } else { testOutOfBounds( code_len, code[i + 1] ); temp_param = code[code[i + 1]]; } if ( ( instruction == 5 && temp_param != 0 ) || ( instruction == 6 && temp_param == 0 ) ) { if ( flags & PARAM_1 ) { i = code[i + 2]; } else { testOutOfBounds( code_len, code[i + 2] ); i = code[code[i + 2]]; } } else { i += 3; } break; case 7: case 8: testOutOfBounds( code_len, i + 2 ); if ( flags & PARAM_0 ) { res = code[i + 1]; } else { testOutOfBounds( code_len, code[i + 1] ); res = code[code[i + 1]]; } if ( flags & PARAM_1 ) { if ( instruction == 7 ) res = res < code[i + 2] ? 1 : 0; else res = res == code[i + 2] ? 1 : 0; } else { testOutOfBounds( code_len, code[i + 2] ); if ( instruction == 7 ) res = res < code[code[i + 2]] ? 1 : 0; else res = res == code[code[i + 2]] ? 1 : 0; } if ( flags & PARAM_2 ) { error( EXIT_FAILURE, 0, "LAST PARAM MUST BE IN MODE 0! Index: %zu", i ); } else { testOutOfBounds( code_len, code[i + 3] ); code[code[i + 3]] = res; } i += 4; break; case 99: return; default: error( EXIT_FAILURE, 0, "INCORRECT INSTRUCTION AT INDEX: %zu, INSTRUCTION IS: %i\n", i, code[i] ); } flags = 0; } } bool permutation( int *phase ) { bool permutation = true; for ( int i = 0; i < 5; i++ ) { for ( int j = 0; j < 5; j++ ) { if ( phase[i] == phase[j] && i != j ) { permutation = false; break; } } if ( !permutation ) break; } return permutation; } void increasePhase( int *phase ) { do { for ( int i = 0; i < 5; i++ ) { phase[i] += 1; if ( phase[i] == 5 ) phase[i] = 0; else break; } } while ( !permutation( phase ) ); } int main() { //--[ Initialize computer //]---------------------------------------------------- FILE *in = fopen( "input", "r" ); char *input = NULL; size_t input_len = 0; getline( &input, &input_len, in ); int *code = NULL; size_t code_len = populateCode( &code, input ); //--[ Compute thrusters //]------------------------------------------------------ int pipes_in[2]; if ( pipe( pipes_in ) == -1 ) error( EXIT_FAILURE, errno, "pipe" ); int pipes_out[2]; if ( pipe( pipes_out ) == -1 ) error( EXIT_FAILURE, errno, "pipe" ); int phase[5] = {0, 1, 2, 3, 4}; size_t maxphase = 0; size_t maxthrust = 0; int *tmp = malloc( code_len ); if ( tmp == NULL ) error( EXIT_FAILURE, errno, "malloc" ); memcpy( tmp, code, code_len ); const int *code_backup = tmp; char phase_input[2]; size_t pipe_read = 0; FILE *output = fdopen( pipes_in[0], "r" ); char *pipe_input = NULL; size_t pipe_size = 0; if ( output == NULL ) error( EXIT_FAILURE, errno, "fdopen" ); printf( "STARTING COMPUTING!\n" ); for ( int i = 0; i < 120; i++ ) { int pid = fork(); if ( pid > 0 ) { if ( dup2( pipes_in[1], STDOUT_FILENO ) == -1 ) error( EXIT_FAILURE, errno, "dup2" ); if ( dup2( pipes_out[0], STDIN_FILENO ) == -1 ) error( EXIT_FAILURE, errno, "dup2" ); close( pipes_in[0] ); close( pipes_out[1] ); compute( code, code_len ); memcpy( code, code_backup, code_len ); compute( code, code_len ); memcpy( code, code_backup, code_len ); compute( code, code_len ); memcpy( code, code_backup, code_len ); compute( code, code_len ); memcpy( code, code_backup, code_len ); compute( code, code_len ); exit( 0 ); } else if ( pid < 0 ) { error( EXIT_FAILURE, errno, "fork" ); } snprintf( phase_input, 2, "%i\n", phase[0] ); phase_input[1] = '\n'; write( pipes_out[1], phase_input, 2 ); write( pipes_out[1], "0\n", 2 ); pipe_read = getline( &pipe_input, &pipe_size, output ); snprintf( phase_input, 2, "%i\n", phase[1] ); phase_input[1] = '\n'; write( pipes_out[1], phase_input, 2 ); write( pipes_out[1], pipe_input, pipe_read ); pipe_read = getline( &pipe_input, &pipe_size, output ); snprintf( phase_input, 2, "%i\n", phase[2] ); phase_input[1] = '\n'; write( pipes_out[1], phase_input, 2 ); write( pipes_out[1], pipe_input, pipe_read ); pipe_read = getline( &pipe_input, &pipe_size, output ); snprintf( phase_input, 2, "%i\n", phase[3] ); phase_input[1] = '\n'; write( pipes_out[1], phase_input, 2 ); write( pipes_out[1], pipe_input, pipe_read ); pipe_read = getline( &pipe_input, &pipe_size, output ); snprintf( phase_input, 2, "%i\n", phase[4] ); phase_input[1] = '\n'; write( pipes_out[1], phase_input, 2 ); write( pipes_out[1], pipe_input, pipe_read ); pipe_read = getline( &pipe_input, &pipe_size, output ); size_t thrust = strtoul( pipe_input, NULL, 10 ); size_t phase_num = phase[0] + 10 * phase[1] + 100 * phase[2] + 1000 * phase[3] + 10000 * phase[4]; if ( thrust > maxthrust ) { maxthrust = thrust; maxphase = phase_num; } increasePhase( phase ); phase_num = phase[0] + 10 * phase[1] + 100 * phase[2] + 1000 * phase[3] + 10000 * phase[4]; } printf( "INPUT FOR MAX THRUSTERS: %05zu WHICH PRODUCES: %zu\n", maxphase, maxthrust ); close( pipes_in[1] ); close( pipes_in[0] ); close( pipes_out[1] ); close( pipes_out[0] ); free( code ); free( input ); }
C
static int depth_search(Coll * graph, DepNode * start, int *setno) { int i; int find = 0; start->setno = -3; for (i = 0; i < start->ndeps; i++) { DepNode *np = find_node(graph, start->deps[i]); if (!np) continue; if (np->in_cycle) continue; switch (np->setno) { case -1: /* unprocessed node */ depth_search(graph, np, setno); find++; break; case -3: /* cycle detected */ set_cycle(graph, np, np); break; default: /* procecced node */ break; } } if (!find) /* terminate node */ start->setno = (*setno)++; else /* rollback */ start->setno = -1; return find; }
C
#include<stdio.h> void printarr(int a[], int num) { int i; for(i=0;i<num;i++) printf("%d, ",a[i]); printf("\n"); } void insertion(int a[], int num) { int i, j, key; for(i=1;i<num;i++) { key = a[i]; j = i-1; while((j >= 0) &&(a[j] > key)) { a[j+1] = a[j]; j--; } a[j+1] = key; printarr(a,5); } } int main() { int arr[] = {4,5,3,6,2}; insertion(arr,5); printarr(arr,5); return 1; }
C
#ifndef MYSH_SHELL_RESOURCE_H #define MYSH_SHELL_RESOURCE_H #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <unistd.h> #include <errno.h> #include <termios.h> #include <sys/types.h> #include "mystring.h" typedef struct mysh_resource_tag { mysh_string current_dir; mysh_string home_dir; struct termios original_termios; int terminal_fd; bool is_interactive; pid_t group_id; void* first_job; } mysh_resource; static void mysh_set_curdir_name(mysh_resource* shell) { char* name = getcwd(NULL, 0); if (name == NULL) { return; } size_t name_len = strlen(name); if (name_len < shell->home_dir.length) { ms_assign_raw(&shell->current_dir, name); return; } int flag = 1; size_t i; for (i = 0; i < shell->home_dir.length; ++i) { if (name[i] != shell->home_dir.ptr[i]) { flag = 0; break; } } if (flag) { ms_reserve(&shell->current_dir, name_len - i + 1); shell->current_dir.length = name_len - i + 1; shell->current_dir.ptr[0] = '~'; for (size_t j = 0; j < name_len - i; ++j) { shell->current_dir.ptr[1 + j] = name[i + j]; } shell->current_dir.ptr[name_len - i + 1] = '\0'; } else { ms_assign_raw(&shell->current_dir, name); } free(name); } static void mysh_release_resource(mysh_resource* shell) { ms_relase(&shell->current_dir); ms_relase(&shell->home_dir); } #endif // MYSH_SHELL_RESOURCE_H
C
#include <stdio.h> #include <stdlib.h> #include "Graph.h" void keepfinding(Graph g, int src, int *x, int n){ for(int i = 0; i < n; i++){ if(GraphIsAdjacent(g,i,src) && !x[i]){ printf("%d ",i); x[i] = 1; keepfinding(g, i, x, n); } } } void depthFirstSearch(Graph g, int src){ int *x = calloc(GraphNumVertices(g),4); x[src] = 1; printf("%d ",src); keepfinding(g,src,x,GraphNumVertices(g)); free(x); }
C
typedef int Item; struct Node { Item item; Node* next; }; typedef Node* SinglyLinkedList; typedef Node* CircularLinkedList; struct DNode { Item item; DNode* prev; DNode* next; }; typedef DNode* DoublyLinkedList;
C
#include<stdio.h> int main(){ int N,i; int x[100000]={0}; int y[100000]={0}; int t[100000]={0}; scanf("%d",&N); for(i=0;i<N;i++){ scanf("%d %d %d",&t[i],&x[i],&y[i]); }//読み込み int flag =1; for(i=0;i<N;i++){ int dt=t[i+1]-t[i]; int dist =abs(x[i+1]-x[i])+abs(y[i+1]-y[i]); if(dt<dist){ flag=0; } if(dist%2!=dt%2){ flag=0; } } if(flag==1){ printf("Yes"); } else{ printf("No"); } }
C
/* * wrapper exp2(x) */ #include <float.h> #include "math.h" #include "math_private.h" static const double o_threshold= (double) DBL_MAX_EXP; static const double u_threshold= (double) (DBL_MIN_EXP - DBL_MANT_DIG - 1); double __exp2 (double x) /* wrapper exp2 */ { #ifdef _IEEE_LIBM return __ieee754_exp2 (x); #else double z; z = __ieee754_exp2 (x); if (_LIB_VERSION != _IEEE_ && __finite (x)) { if (x > o_threshold) /* exp2 overflow */ return __kernel_standard (x, x, 44); else if (x <= u_threshold) /* exp2 underflow */ return __kernel_standard (x, x, 45); } return z; #endif } weak_alias (__exp2, exp2) #ifdef NO_LONG_DOUBLE strong_alias (__exp2, __exp2l) weak_alias (__exp2, exp2l) #endif
C
bool sameline(P3 p1, P3 p2, P3 p3) { //判断共线 return sgn(det(p1, p2, p3).len())==0; } bool sameplane(P3 p1, P3, p2, P3 p3, P3 p4) { //判断共面 return sgn(dot(det(p1, p2, p3), p4-p3))==0; } bool on_segment(P3 p, P3 a1, P3 a2) { //判断是否在线段上;包含端点 if(!sameline(p, a1, a2)) return false; a1=a1-p, a2=a2-p; //若想不包含端点,需特判 p!=a1 && p!=a2 return sgn(a1.x*a2.x)<=0 && sgn(a1.y*a2.y)<=0 && sgn(a1.z*a2.z)<=0; } bool in_tri(P3 p, P3 s1, P3 s2, P3 s3) { //判断是否在三角形内;包含边界 double a=det(p,s1,s2).len() + det(p,s2,s3).len() + det(p,s3,s1).len(); double b=det(s1, s2, s3).len(); return sgn(a-b)==0; //若想不包含边界,需特判!sameline(p,s[i],s[i+1]) } bool sameside(P3 p1, P3 p2, P3 l1, P3 l2) { //平面两点是否在直线的同一侧 return sgn(dot(det(l1, l2, p1), det(l1, l2, p2)))>0; } bool sameside(P3 p1, P3 p2, P3 s1, P3 s2, P3 s3) { //两点是否在平面同一侧 P3 n=det(s1,s2,s3); return sgn(dot(n, p1-s1)*dot(n, p2-s1))>0; } bool parallel(P3 a1, P3 a2, P3 b1, P3 b2) { //直线是否平行 return sgn(det(a1-a2, b1-b2).len())==0; } bool parallel(P3 a1, P3 a2, P3 a3, P3 b1, P3 b2, P3 b3) { //平面是否平行 return sgn(det(det(a1,a2,a3), det(b1,b2,b3)).len())==0; } bool parallel(P3 p1, P3 p2, P3 a1, P3 a2, P3 a3) { //平面与直线是否平行 return sgn(dot(p1-p2, det(a1,a2,a3)))==0; } bool perp(P3 a1, P3 a2, P3 b1, P3 b2) { //直线是否垂直 return sgn(dot(a1-a2, b1-b2))==0; } bool perp(P3 a1, P3 a2, P3 a3, P3 b1, P3 b2, P3 b3) { //平面是否垂直 return sgn(dot(det(a1,a2,a3), det(b1,b2,b3)))==0; } bool perp(P3 p1, P3 p2, P3 a1, P3 a2, P3 a3) { //平面与直线是否垂直 return sgn(det(p1-p2, det(a1,a2,a3)).len())==0; } bool intersect(P3 a1, P3 a2, P3 b1, P3 b2) { //线段是否相交;不包括端点 return sameplane(a1,a2,b1,b2) && opposide(a1,a2,b1,b2) && opposide(b1,b2,a1,a2); } bool intersect(P3 l1, P3 l2, P3 s1, P3 s2, P3 s3) { //线段是否与三角形交 return !sameside(l1,l2,s1,s2,s3) && !sameside(s1,s2,l1,l2,s3) && !sameside(s2,s3,l1,l2,s1) && !sameside(s3,s1,l1,l2,s2); //包含边界;若想不包含边界,请用"opposide"代替"!sameside" } P3 intersect(P3 a1, P3 a2, P3 b1, P3 b2) { //直线交;需保证共面且不平行 double t=(a1.x-b1.x)*(b1.y-b2.y) - (a1.y-b1.y)*(b1.x-b2.x); t/=(a1.x-a2.x)*(b1.y-b2.y) - (a1.y-a2.y)*(b1.x-b2.x); return a1+(u2-u1)*t; } P3 proj(P3 p, P3 dir, P3 normal, P3 p0) { //p沿dir方向投影到平面 double a=dot(dir, normal); double b=dot(p-p0, normal); return p+dir*(-b/a); } bool intersect_line(P3 a1,a2,a3, P3 b1,b2,b3, P3 &l1,&l2) { //平面交 if(parallel(a1,a2,a3, b1,b2,b3)) return false; l1=parallel(b1,b2, a1,a2,a3) ? intersect(b2,b3, a1,a2,a3) : intersect(b1,b2, a1,a2,a3); l2=l1+det(det(a), det(b)); return true; } double dist_l(P3 p, P3 a1, P3 a2) { return det(p, a1, a2).len() / dist(a1, a2); } double dist_p(P3 p, P3 s1, P3 s2, P3 s3) { return fabs(dot(det(s), p-s1)) / det(s).len(); } double dist_lines(P3 a1, P3 a2, P3 b1, P3 b2) { //平行时有问题!!!! P3 n=det(a1-a2, b1-b2); return fabs(dot(u1-v1, n)) / n.len(); } double angle_cos(P3 ua,ub, P3 va,vb) { // 两直线形成的角的cos值 return dot(ua-ub, va-vb) / (ua-ub).len() / (va-vb).len(); } double angle_cos(P3 ua,ub,uc, P3 va,vb,vc) { // 两平面形成的角的cos值 return dot(det(u), det(v)) / det(u).len() / det(v).len(); }
C
#include<stdio.h> #include<stdlib.h> int a[200000]={}; void quicksort(int left,int right){ int k,l,r,i; if(left >= right) return; k=a[left];l=left;r=right; do{ while(a[r] >= k && r>l) r--; a[l] = a[r]; while(a[l] <= k && l<r) l++; a[r] = a[l]; }while(l<r); a[l]=k; quicksort(left,r-1); quicksort(l+1,right); return; } int main(){ int n,i; scanf("%d",&n); for(i = 1;i <= n;i++){ scanf("%d",&a[i]); } quicksort(1,n); for(i = 1;i <= n;i++){ printf("%d ",a[i]); } return 0; }
C
#include "mips.h" #include "mmu.h" #include "mipsop.h" #include <stdio.h> #include <string.h> void print_disas_string(uint32_t inst); // from mipsinst.c void print_regs(struct mips_regs *r) { int i; for (i=0; i<32; i++) { fprintf(stderr, "reg[%d]=%08x ", i, r->regs[i]); if (i%4==3) { fprintf(stderr, "\n"); } } fprintf(stderr, "pc=%08x\n", r->pc); } int debugger(struct mips_regs *r, struct mmu *m) { static char cmd[16]; char input[16], op[8]; uint32_t inst; uint32_t addr; printf("> "); fgets(input, sizeof(input), stdin); if (input[0]!='\n') { memcpy(cmd, input, sizeof(input)); } switch (cmd[0]) { case 'n': inst = *(uint32_t*)mmu_translate_addr(m, r->pc); fprintf(stderr, "%x: ", r->pc); print_disas_string(inst); mips_inst_exec(r, m, inst); return 1; case 'r': print_regs(r); return 1; case 'x': sscanf(cmd, "%s%x", op, &addr); fprintf(stderr, "%x: %x\n", addr, *(uint32_t*)mmu_translate_addr(m, addr)); return 1; case 'g': sscanf(cmd, "%s%x", op, &addr); while (r->pc!=addr) { inst = *(uint32_t*)mmu_translate_addr(m, r->pc); mips_inst_exec(r, m, inst); } return 1; case 'c': return 0; default: fprintf(stderr, "unknown debug command."); return 1; } }
C
/* * xbot: Just another IRC bot * * Written by Aaron Blakely <[email protected]> **/ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/select.h> #include <time.h> #include <errno.h> #include "config.h" #include "irc.h" #include "util.h" #include "events.h" static time_t trespond; int main() { int n; fd_set rd; struct irc_conn bot; struct timeval tv; init_events(); // Read the config bot = read_config(bot, "xbot.cfg"); // Connect to the server printf("Connecting to %s...\n", bot.host); irc_connect(&bot); irc_auth(&bot); for (;;) { FD_ZERO(&rd); FD_SET(0, &rd); FD_SET(fileno(bot.srv_fd), &rd); tv.tv_sec = 120; tv.tv_usec = 0; n = select(fileno(bot.srv_fd) + 1, &rd, 0, 0, &tv); if (n < 0) { if (errno == EINTR) continue; eprint("xbot: error on select()\n"); return 0; } else if (n == 0) { if (time(NULL) - trespond >= 300) { eprint("xbot shutting down: parse timeout\n"); return -1; } irc_raw(&bot, "PING %s", bot.host); continue; } if (FD_ISSET(fileno(bot.srv_fd), &rd)) { if (fgets(bot.in, sizeof bot.in, bot.srv_fd) == NULL) { eprint("xbot: remote host closed connection\n"); return 0; } irc_parse_raw(&bot, bot.in); trespond = time(NULL); } } return 0; }
C
#include<stdio.h> int main(int argc, char *argv[]) { int n, m; int i, a = 0, b = 0; int arr[44]; scanf(" %d", &n); for (i = 0; i < n; i++) scanf(" %d", arr + i); scanf(" %d", &m); for (i = 0; i < n; i++) { if ( !(m % arr[i]) ) a += arr[i]; if ( !(arr[i] % m) ) b += arr[i]; } printf("%d\n%d", a, b); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "redesocial.h" #include "interface.h" #include "amizades.h" #include "exercicios.h" int main() { TRedeSocial rede; TUsuarios user; int opcao; inicializar(&rede); do { mensagemMenu(); printf("\n\n\tDIGITE UMA OPCAO: "); fflush(stdin); scanf("%d", &opcao); switch (opcao) { case 1: moduloUm(&rede, user); break; case 2: moduloDois(&rede, user); break; case 3: //system("cls"); printf("\n\n\tAPERTE ENTER PARA FECHAR O PROGRAMA !"); fflush(stdin); getchar(); //system("pause); break; default: //system("cls"); printf("\n\n\tOPCAO INVALIDA !"); printf("\n\n\tPRESSIONE UMA TECLA PARA CONTINUAR !"); fflush(stdin); getchar(); //system("pause); } } while(opcao != 3); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "SingleLinkedList.h" void create(SingleLinkedList* l){ Node* header=malloc(sizeof(Node)); header->data=0; header->next=NULL; l->header=header; l->length=0; } void push(SingleLinkedList* l, int data) { Node* header = l->header; Node* newNode=malloc(sizeof(Node)); newNode->data=data; if (header->next==NULL) { header->next=newNode; newNode->next=NULL; l->lenght=l->length+1; } else{ Node *lastNode=l->header; while (lastNode->next != NULL){ lastNode = lastNode->next; } newNode->next=NULL; lastNode->next=newNode; l->length=l->length+1; } }
C
/** * MathAdditions.c * KosherCocoa 2 * * Created by Moshe Berman on 3/24/11. * Modified by Moshe Berman on 8/25/13. * * */ #include "trigonometry.h" /** toRadians * * A utility function for converting degrees to radians * * @param degrees The number of degrees to convert. * @return The number of radians that corresponds to the supplied number of degrees. */ double toRadians(double degrees){ return degrees * M_PI / 180.0; } /** * A utility function for converting radians to degrees * * */ double toDegrees(double radians){ return radians * 180.0 / M_PI; } /** * sin of an angle in degrees */ double sinDeg(double deg) { return sin(deg * 2.0 * M_PI / 360.0); } /** * acos of an angle, result in degrees */ double acosDeg(double x) { return acos(x) * 360.0 / (2 * M_PI); } /** * asin of an angle, result in degrees */ double asinDeg(double x) { return asin(x) * 360.0 / (2 * M_PI); } /** * tan of an angle in degrees */ double tanDeg(double deg) { return tan(deg * 2.0 * M_PI / 360.0); } /** * cos of an angle in degrees */ double cosDeg(double deg) { return cos(deg * 2.0 * M_PI / 360.0); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_print_digit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ealexa <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/13 16:27:47 by ealexa #+# #+# */ /* Updated: 2020/11/15 18:22:16 by ealexa ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/ft_printf.h" int ft_print_digit_zero(t_param *params) { if (params->width != -1) while (params->width >= params->length) { write(1, " ", 1); params->length++; } return (params->length - 1); } int ft_print_digit(t_param *params) { int res; if (params->flag_minus == '-') params->flag = '-'; params->digit = va_arg(*params->ap, int); params->buffer = ft_itoa(params->digit); params->length = ft_strlen(params->buffer); if (params->flag_empty == '1') params->width = params->length > params->precision ? params->length + 1 : params->precision + 1; if (params->precision == 0 && params->digit == 0) res = ft_print_digit_zero(params); else if (params->precision == -1) res = ft_print_digit_not_pris(params); else res = ft_print_digit_with_pris(params); free(params->buffer); return (res); } size_t ft_itoa_size_2(unsigned long n, unsigned long int *num) { size_t res; long tmp_n; res = 0; if (n < 0) { *num = n * (-1); res++; tmp_n = n * (-1); } else { *num = n; tmp_n = n; } while (tmp_n != 0) { tmp_n /= 10; res++; } return (res); } char *ft_itoa_long(unsigned long n) { unsigned long int tmp_n; size_t i; char *res; if (n == 0) return (ft_strdup("0")); i = ft_itoa_size_2(n, &tmp_n); res = malloc(sizeof(char) * (i + 1)); if (res != NULL) { res[i] = '\0'; while (tmp_n != 0) { res[--i] = ((tmp_n % 10) + '0'); tmp_n = tmp_n / 10; } if (i != 0) res[0] = '-'; } return (res); } int ft_print_unsigned(t_param *params) { int res; if (params->flag_minus == '-') params->flag = '-'; params->digit = va_arg(*params->ap, unsigned int); params->buffer = ft_itoa_long(params->digit); params->length = ft_strlen(params->buffer); if (params->precision == 0 && params->digit == 0) res = ft_print_digit_zero(params); else if (params->precision == -1) res = ft_print_digit_not_pris(params); else res = ft_print_digit_with_pris(params); free(params->buffer); return (res); }
C
#include<stdio.h> #include<math.h> double cubic(double n); int main(int argc, char* argv[]) { double input; printf("Enter the double datum to calc cubic :"); scanf_s("%lf", &input); cubic(input); printf("PROGRAM EXIT!\n"); return 0; } double cubic(double n) { double t = pow(n, 3); printf("The %lg's cubic is %lg!\n", n, t); return t; }
C
#include "stdafx.h" #include "stdlib.h" #include "string.h" #include "math.h" struct node{ int data; struct node *next; }; void addNode(struct node **root, int data){ struct node *temp = (struct node*)malloc(sizeof(struct node)); struct node *current = *root; temp->data = data; temp->next = NULL; if (current == NULL){ *root = temp; return; } else{ while (current->next != NULL) current = current->next; current->next = temp; } } void display(struct node *root){ struct node *current = root; while (current != NULL){ printf("%d\t", current->data); current = current->next; } } void rearrange(struct node **root){ struct node *odd = *root; struct node *e = odd->next; struct node *even = odd->next; while (odd->next != NULL && even->next!=NULL){ odd->next = odd->next->next; even->next = even->next->next; odd = odd->next; even = even->next; } odd->next = e; } int main(){ struct node *root = NULL; addNode(&root, 6); addNode(&root, 2); addNode(&root, 8); addNode(&root, 0); addNode(&root, 4); addNode(&root, 7); addNode(&root, 9); addNode(&root, 3); addNode(&root, 5); display(root); rearrange(&root); printf("\n"); display(root); return 0; }
C
void main() { int n,i=1,j; char str[51][32],t; scanf("%d",&n); while(i<=n) { scanf("%s",str[i]); i++; } for(i=1;i<=n;i++) { for(j=1;j<=32;j++) { if(str[i][j]=='e'&&str[i][j+1]=='r'&&str[i][j+2]=='\0') str[i][j]='\0'; else if(str[i][j]=='l'&&str[i][j+1]=='y'&&str[i][j+2]=='\0') str[i][j]='\0'; else if(str[i][j]=='i'&&str[i][j+1]=='n'&&str[i][j+2]=='g'&&str[i][j+3]=='\0') str[i][j]='\0'; } } for(i=1;i<=n;i++) { printf("%s\n",str[i]); } }