language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
# include <stdio.h> int main(){ int n = 5; //dynamic size char * pvowels = (char *) malloc(n * sizeof(char)); int i; //iterator pvowels[0] = 'A'; //store the value of char A to the 0th index of pvowels pvowels[1] = 'E'; *(pvowels + 2) = 'I'; //store the value of char I to the pointer of the 2nd index of pvowels pvowels[3] = 'O'; *(pvowels + 4) = 'U'; for(i = 0; i < n; i++) { printf("%c ", *(pvowels + i)); } printf("\n"); return 0; }
C
#include "method.h" int problem_129() { char str[20]; int i, j, len; printf("ڿ Է: "); gets(str); len = 0; for( i = 0 ; i < 20 ; i++) { if((str[i] >= 'a' && str[i] <= 'z') || str[i] == ' ' || (str[i]>='A'&&str[i] <='Z')) { len++; } } printf("ڿ=%d\n", len); for(i = len ; i > 0 ; i--) { for(j = 0; j < i ; j++) { printf("%c", str[j]); } printf("\n"); } return 0; }
C
#include <pebble.h> #define KEY_BUTTON 0 #define KEY_VIBRATE 1 #define BUTTON_UP 0 #define BUTTON_SELECT 1 #define BUTTON_DOWN 2 static Window *s_main_window; static TextLayer *s_text_layer; static void send(int key, int message) { DictionaryIterator *iter; app_message_outbox_begin(&iter); dict_write_int(iter, key, &message, sizeof(int), true); app_message_outbox_send(); } static void inbox_received_handler(DictionaryIterator *iterator, void *context) { Tuple *t = dict_read_first(iterator); while(t != NULL) { switch(t->key) { case KEY_VIBRATE: text_layer_set_text(s_text_layer, "Vibrate!"); vibes_short_pulse(); break; default: APP_LOG(APP_LOG_LEVEL_INFO, "unknown key: %d", (int)t->key); break; } t = dict_read_next(iterator); } } static void inbox_dropped_handler(AppMessageResult reason, void *context) { APP_LOG(APP_LOG_LEVEL_ERROR, "Message dropped"); } static void outbox_failed_handler(DictionaryIterator *iterator, AppMessageResult reason, void *context) { APP_LOG(APP_LOG_LEVEL_ERROR, "outbox send failed"); } static void outbox_sent_handler(DictionaryIterator *iterator, void *context) { APP_LOG(APP_LOG_LEVEL_INFO, "outbox send success"); } static void select_click_handler(ClickRecognizerRef recognizer, void *context) { send(KEY_BUTTON, BUTTON_SELECT); text_layer_set_text(s_text_layer, "select"); printf("select"); } static void up_click_handler(ClickRecognizerRef recognizer, void *context) { send(KEY_BUTTON, BUTTON_UP); text_layer_set_text(s_text_layer, "up"); printf("up"); } static void down_click_handler(ClickRecognizerRef recognizer, void *context) { send(KEY_BUTTON, BUTTON_DOWN); text_layer_set_text(s_text_layer, "down"); printf("down"); } static void click_config_provider(void *context) { window_single_click_subscribe(BUTTON_ID_SELECT, select_click_handler); window_single_click_subscribe(BUTTON_ID_UP, up_click_handler); window_single_click_subscribe(BUTTON_ID_DOWN, down_click_handler); } static void main_window_load(Window *window) { Layer *window_layer = window_get_root_layer(window); GRect bounds = layer_get_frame(window_layer); s_text_layer = text_layer_create(bounds); text_layer_set_font(s_text_layer, fonts_get_system_font(FONT_KEY_GOTHIC_28_BOLD)); text_layer_set_text(s_text_layer, "wassup"); text_layer_set_text_alignment(s_text_layer, GTextAlignmentCenter); layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_text_layer)); #ifdef PBL_ROUND text_layer_enable_screen_text_flow_and_paging(s_text_layer, 5); #endif } static void main_window_unload(Window *window) { text_layer_destroy(s_text_layer); } static void init(void) { app_message_register_inbox_received(inbox_received_handler); app_message_register_inbox_dropped(inbox_dropped_handler); app_message_register_outbox_failed(outbox_failed_handler); app_message_register_outbox_sent(outbox_sent_handler); app_message_open(app_message_inbox_size_maximum(), app_message_outbox_size_maximum()); s_main_window = window_create(); window_set_click_config_provider(s_main_window, click_config_provider); window_set_window_handlers(s_main_window, (WindowHandlers) { .load = main_window_load, .unload = main_window_unload, }); window_stack_push(s_main_window, true); } static void deinit(void) { window_destroy(s_main_window); } int main(void) { init(); app_event_loop(); deinit(); }
C
#define _CRT_SECURE_NO_WARNINGS 1 // 2、带头双向循环链表增删查改实现 typedef int LTDataType; typedef struct ListNode { LTDataType _data; struct ListNode* _next; struct ListNode* _prev; }ListNode; class List { public: List(); ~List(); ListNode* BuyNode(LTDataType x); void ListPushBack(LTDataType x); void ListPopBack(); void ListPushFront(LTDataType x); void ListPopFront(); ListNode* ListFind(LTDataType x); void ListRemove(LTDataType x); void ListPrint(); private: ListNode* _head; }; ListNode* List::BuyNode(LTDataType x) { ListNode* tmp = new ListNode; tmp->_data = x; tmp->_next = tmp->_prev = nullptr; return tmp; } List::List() { this->_head = this->BuyNode(0); this->_head->_next = this->_head; this->_head->_prev = this->_head; } List::~List() { ListNode* cur = this->_head->_next; while (cur != this->_head) { ListNode* next = cur->_next; ListNode* prev = cur->_prev; prev->_next = next; next->_prev = prev; delete cur; cur = next; } } void List::ListPushBack(LTDataType x) { ListNode* tmp = this->BuyNode(x); this->_head->_prev->_next = tmp; tmp->_next = this->_head; tmp->_prev = this->_head->_prev; this->_head->_prev = tmp; } void List::ListPrint() { if (this->_head->_next == this->_head) { cout << "链表为空" << endl; return; } ListNode* cur = this->_head->_next; while (cur != this->_head) { cout << cur->_data << "->"; cur = cur->_next; } cout << "NULL" << endl; } void List::ListPopBack() { ListNode* cur = this->_head->_prev; this->_head->_prev = cur->_prev; cur->_prev->_next = this->_head; delete cur; } void List::ListPushFront(LTDataType x) { ListNode* cur = this->_head->_next; ListNode* tmp = this->BuyNode(x); this->_head->_next = tmp; tmp->_next = cur; cur->_prev = tmp; tmp->_prev = this->_head; } void List::ListPopFront() { ListNode* cur = this->_head->_next; this->_head->_next = cur->_next; cur->_next->_prev = this->_head; delete cur; } ListNode* List::ListFind(LTDataType x) { ListNode* cur = this->_head->_next; while (cur != this->_head) { if (cur->_data == x) { return cur; } cur = cur->_next; } return nullptr; } void List::ListRemove(LTDataType x) { ListNode* cur = this->ListFind(x); ListNode* prev = cur->_prev; ListNode* next = cur->_next; prev->_next = next; next->_prev = prev; delete cur; } void test2() { List l; l.ListPushBack(0); l.ListPushBack(1); l.ListPushBack(2); l.ListPushBack(3); l.ListPrint(); //l.ListPopBack(); l.ListPrint(); l.ListPushFront(7); l.ListPopFront(); l.ListRemove(3); l.ListPrint(); l.~List(); l.ListPrint(); }
C
/* vmath.c 96-bit integer and floating point routines for vasm */ /* (c) in 2002 by Frank Wille */ #include "vasm.h" #include <math.h> static int96 one = { 1,0,0,0,0,0,0,0,0,0,0,0 }; unsigned char *int96_assign32(unsigned char *x,long val) { int i; for (i=0; i<4; i++) { x[i] = val & 0xff; val >>= 8; } memset(&x[4],(x[3] & 0x80)?0xff:0,8); return x; } unsigned char *int96_assign64(unsigned char *x,long long val) { int i; for (i=0; i<8; i++) { x[i] = val & 0xff; val >>= 8; } memset(&x[8],(x[7] & 0x80)?0xff:0,4); return x; } unsigned char *int96_add(unsigned char *x,unsigned char *y) { unsigned char s,v; int i; for (i=0,v=0; i<12; i++) { s = x[i] + y[i] + v; v = s<x[i] || s<y[i]; x[i] = s; } return x; } unsigned char *int96_add32(unsigned char *x,long val) { int96 y; return int96_add(x,int96_assign32(y,val)); } unsigned char *int96_add64(unsigned char *x,long long val) { int96 y; return int96_add(x,int96_assign64(y,val)); } unsigned char *int96_negate(unsigned char *x) { int i; for (i=0; i<12; i++) x[i] = ~x[i]; return int96_add(x,one); } unsigned char *int96_lshleft(unsigned char *x,int cnt) { unsigned short old=0,new; int i,sh; while (cnt > 0) { sh = (cnt > 8) ? 8 : cnt; for (i=0; i<12; i++) { new = (unsigned short)x[i] << sh; x[i] = (new & 0xff) | ((old >> 8) & 0xff); old = new; } cnt -= sh; } return x; } unsigned char *int96_lshright(unsigned char *x,int cnt) { unsigned short old=0,new; int i,sh; while (cnt > 0) { sh = (cnt > 8) ? 8 : cnt; for (i=11; i>=0; i--) { new = ((unsigned short)x[i]<<8) >> sh; x[i] = (old & 0xff) | ((new >> 8) & 0xff); old = new; } cnt -= sh; } return x; } unsigned char *int96_ashright(unsigned char *x,int cnt) { unsigned short new; unsigned short old = (x[11]>=0x80) ? 0xffff : 0; int i,sh; while (cnt > 0) { sh = (cnt > 8) ? 8 : cnt; for (i=11; i>=0; i--) { new = ((unsigned short)x[i]<<8) >> sh; x[i] = (old & 0xff) | ((new >> 8) & 0xff); old = new; } cnt -= sh; } return x; } unsigned char *int96_mulu(unsigned char *x,unsigned char *y) { int i,j; unsigned short m; unsigned char p[13]; int96 sum; memset(sum,0,12); memset(p,0,13); for (i=0; i<12; i++) { for (j=0; j<(12-i); j++) { m = (unsigned short)x[i] * (unsigned short)y[j]; p[i+j] = m & 0xff; p[i+j+1] = (m >> 8) & 0xff; int96_add(sum,p); p[i+j] = p[i+j+1] = 0; } } memcpy(x,sum,12); return x; } unsigned char *int96_muls(unsigned char *x,unsigned char *y) { int neg = 0; if (x[11] >= 0x80) { neg = 1; int96_negate(x); } if (y[11] >= 0x80) { neg ^= 1; int96_negate(y); } int96_mulu(x,y); if (neg) int96_negate(x); return x; } long double int96_conv2longdouble(unsigned char *x) { long double f = 0.0; long double m = 1.0; int i,neg=0; if (x[11] >= 0x80) { neg = 1; int96_negate(x); } for (i=0; i<12; i++) { f += (long double)x[i] * m; m *= 256.0; } return neg ? -f : f; } int int96_cntz(unsigned char *x) { int cnt = 0; int i; for (i=11; i>=0; i--) { unsigned char v = x[i]; unsigned char m = 0x80; for (m=0x80; m; m>>=1) { if (v & m) { i = -1; break; } cnt++; } } return cnt; } int int96_compare(unsigned char *x,unsigned char *y) { int96 cmp; int i; for (i=0; i<12; i++) cmp[i] = ~y[i]; int96_add(cmp,one); int96_add(cmp,x); for (i=0; i<12; i++) { if (cmp[i]) return cmp[11]>=0x80 ? -1 : 1; } return 0; } void int96_copybe(unsigned char *d,unsigned char *x,int len) { int i; for (i=len-1; i>=0; i--) *d++ = x[i]; } void int96_copyle(unsigned char *d,unsigned char *x,int len) { memcpy(d,x,len); }
C
#include <stdio.h> #include <assert.h> #define do_test(f) printf("test : %s ... ",#f);f(); void isPositive(); void isNegative(); int main() { printf("Start unit tests\n"); do_test(isPositive); do_test(isPositive); do_test(isPositive); do_test(isNegative); do_test(isPositive); return 0; } void isPositive(){ int i=1; assert(1==i); printf("passed\n"); } void isNegative(){ int i=1; assert(0==i); printf("passed\n"); }
C
#ifndef CLAMP_H_INCLUDED #define CLAMP_H_INCLUDED #include "typedefs.h" /*@ requires bound: lower < upper; assigns \nothing; ensures bound: lower <= \result <= upper; behavior lower_bound: assumes v < lower; assigns \nothing; ensures result: \result == lower; behavior between: assumes lower <= v <= upper; assigns \nothing; ensures result: \result == v; behavior upper_bound: assumes upper < v; assigns \nothing; ensures result: \result == upper; complete behaviors lower_bound, upper_bound, between; disjoint behaviors lower_bound, upper_bound, between; */ value_type clamp(value_type v, value_type lower, value_type upper); #endif /* CLAMP_H_INCLUDED */
C
/*JSTK-320111 a2_p1_m1.c Tudor Cristian Maiereanu t.maiereanu@jacobs-university.de*/ #include <stdio.h> #include <stdlib.h> int main() { int integer; printf("Enter the integer: "); scanf("%d", &integer); printf("The decimal notation of the integer you entered is %d\n", integer); printf("The octal notation of the integer you entered is %o\n", integer); printf("The hexadecimal notation of the integer you entered is %x\n", integer); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <curses.h> #include <string.h> #include "gol.h" void winDraw(struct GameOfLife *gol) { char* iterBuffer = malloc((gol->width + 1) * sizeof(char)); unsigned int y; clear(); sprintf(iterBuffer, "Iteration: %d", gol->numIteration); move(0, 0); addstr(iterBuffer); for(y = 0; y < gol->height; y++) { move(y + 1, 0); printw("%s", gol->grid[y]); } refresh(); free(iterBuffer); } void clearGrid(struct GameOfLife* gol){ unsigned int i,j; for(i = 0; i < gol->height; i++) for(j = 0; j < gol->width; j++) gol->grid[i][j] = cellDead; gol->numIteration = 0; } int main(int argc, char **argv) { struct GameOfLife gol; unsigned int width, height; int ch; int running = 1; MEVENT mouseEvent; /*initialise the curses screen*/ initscr(); cbreak(); /*Disable buffering of typed characters*/ noecho(); /*suppress echo of character*/ mousemask(ALL_MOUSE_EVENTS, NULL); keypad(stdscr, TRUE); /*capture special characters*/ if(argc == 1) { getmaxyx(stdscr, height, width); height--; golInit(&gol, height, width); } else if(argc == 3) { height = strtol(argv[1], NULL, 0); width = strtol(argv[2], NULL, 0); golInit(&gol, height, width); } else { return 1; } clear(); winDraw(&gol); while(running) { ch = wgetch(stdscr); switch(ch) { case 'q': running = 0; break; case 'n': golRun(&gol); winDraw(&gol); break; case 'c': clearGrid(&gol); winDraw(&gol); break; case KEY_MOUSE: if(getmouse(&mouseEvent) == OK && (mouseEvent.bstate & BUTTON1_PRESSED)) { golToggle(&gol, mouseEvent.x, mouseEvent.y - 1); winDraw(&gol); } break; case KEY_RESIZE: if (argc == 1) /*if no arguments were given, and it should therefore be on autoresize*/ { endwin(); refresh(); getmaxyx(stdscr, height, width); height--; golResize(&gol, height, width); winDraw(&gol); } } } /*run before ending*/ endwin(); golDisp(&gol); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <curses.h> #include <signal.h> #include <string.h> #include <math.h> #include <time.h> /* 4 * 1.ʾʱ䣬 * 2. * 3.ȡʱ * 4. */ WINDOW *wtime,*wnumb; main() { /* ʼ */ initscr(); int id=0; //3ӽ for(id;i<3;id++) { if(fork()) { // } else { //ӽ switch(id) { case 0: while(1) // { } break; case 1: while(1) //ʱ { } break; case 2: while(1) //𰴼 { } break; } } } //ѭˢ ʾʱ /* */ endwin(); }
C
/* * c_swi_handler.c: swi handler in c, call libc according to swi number * * Author: Shi Su <shis@andrew.cmu.edu> * Mengjin Yan <mengjinyan@cmu.edu> * * Date: Mon Oct 26 14:03:58 EDT 2015 */ #include <bits/swi.h> #include <types.h> #include <syscall.h> #include <lock.h> /* Dispatch the syscall to different lib function according to swi_num swi number and pointer to the register value on stack is passed from assembly swi handler */ void c_swi_handler(unsigned swi_num, unsigned* regs){ switch(swi_num){ case READ_SWI: { // cast unsigned address to buffer pointer char *buf = (char*)regs[1]; // call lib and put the return value back on stack regs[0] = read_syscall(regs[0], buf, regs[2]); break; } case WRITE_SWI: { char *buf = (char*)regs[1]; regs[0] = write_syscall(regs[0], buf, regs[2]); break; } case TIME_SWI: { // unsigned long to long? regs[0] = (unsigned) time_syscall(); break; } case SLEEP_SWI: { sleep_syscall(regs[0]); break; } case CREATE_SWI: { regs[0] = task_create((task_t*)regs[0], regs[1]); break; } case MUTEX_CREATE: { regs[0] = mutex_create(); break; } case MUTEX_LOCK: { regs[0] = mutex_lock(regs[0]); break; } case MUTEX_UNLOCK: { regs[0] = mutex_unlock(regs[0]); break; } case EVENT_WAIT: { regs[0] = event_wait(regs[0]); break; } default: invalid_syscall(regs[0]); } }
C
/** * gdiopt.c * Copyright (c) 2014-2015 SWAT */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stddef.h> #include <stdarg.h> #include <stdint.h> #include <unistd.h> #include <dirent.h> #include <sys/stat.h> #include <time.h> FILE *logfd = NULL; int bin2iso(const char *source, const char *target) { int seek_header, seek_ecc, sector_size; long i, source_length; char buf[2352]; const unsigned char SYNC_HEADER[12] = {0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0}; FILE *fpSource, *fpTarget; fpSource = fopen(source, "rb"); fpTarget = fopen(target, "wb"); if ((fpSource==NULL) || (fpTarget==NULL)) { return -1; } fread(buf, sizeof(char), 16, fpSource); if (memcmp(SYNC_HEADER, buf, 12)) { seek_header = 8; seek_ecc = 280; sector_size = 2336; } else { switch(buf[15]) { case 2: { seek_header = 24; // Mode2/2352 seek_ecc = 280; sector_size = 2352; break; } case 1: { seek_header = 16; // Mode1/2352 seek_ecc = 288; sector_size = 2352; break; } default: { fclose(fpTarget); fclose(fpSource); return -1; } } } fseek(fpSource, 0L, SEEK_END); source_length = ftell(fpSource)/sector_size; fseek(fpSource, 0L, SEEK_SET); for(i=0; i<source_length; i++) { fseek(fpSource, seek_header, SEEK_CUR); fread(buf, sizeof(char), 2048, fpSource); fwrite(buf, sizeof(char), 2048, fpTarget); fseek(fpSource, seek_ecc, SEEK_CUR); } fclose(fpTarget); fclose(fpSource); return 0; } int convert_gdi(char *ingdi, char *outgdi, const char *folder) { FILE *fr, *fw; int i, rc, track_no, track_count; unsigned long start_lba, flags, sector_size, offset; char fn_old[256], fn_new[256], full_fn_old[1024], full_fn_new[1024]; fr = fopen(ingdi, "r"); if(!fr) { printf("Can't open for read: %s\n", ingdi); fprintf (logfd, "Can't open for read: %s\n", ingdi); return -1; } fw = fopen(outgdi, "w"); if(!fw) { printf("Can't open for write: %s\n", outgdi); fprintf (logfd, "Can't open for write: %s\n", outgdi); fclose(fr); return -1; } printf("Converting %s\n", ingdi); fprintf (logfd, "Converting %s\n", ingdi); rc = fscanf(fr, "%d", &track_count); if(rc == 1) { fprintf(fw, "%d\n", track_count); for(i = 0; i < track_count; i++) { start_lba = flags = sector_size = offset = 0; memset(fn_new, 0, sizeof(fn_new)); memset(fn_old, 0, sizeof(fn_old)); rc = fscanf(fr, "%d %ld %ld %ld %s %ld", &track_no, &start_lba, &flags, &sector_size, fn_old, &offset); if (sector_size == 2048) continue; if(flags == 4) { if (sector_size != 2048) { int len = strlen(fn_old); strncpy(fn_new, fn_old, sizeof(fn_new)); fn_new[len - 3] = 'i'; fn_new[len - 2] = 's'; fn_new[len - 1] = 'o'; fn_new[len] = '\0'; sector_size = 2048; printf("Converting %s to %s ...\n", fn_old, fn_new); fprintf (logfd, "Converting %s to %s ...\n", fn_old, fn_new); snprintf(full_fn_old, 1024, "%s%s",folder, fn_old); snprintf(full_fn_new, 1024, "%s%s",folder, fn_new); if(bin2iso(full_fn_old, full_fn_new) < 0) { printf("Error!\n"); fclose(fr); fclose(fw); return -1; } unlink(full_fn_old); } } fprintf(fw, "%d %ld %ld %ld %s %ld\n", track_no, start_lba, flags, sector_size, (flags == 4 ? fn_new : fn_old), offset); } } fclose(fr); fclose(fw); unlink(ingdi); return 0; } int convert_folder(const char *infldr) { DIR *indir; struct dirent *de; struct stat st; char name[1024], oname[1024]; if (!(indir = opendir(infldr))) { printf("ERROR can't open directory %s\n", infldr); fprintf (logfd, "ERROR can't open directory %s\n", infldr); return -1; } while(de = readdir(indir)) { if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) continue; snprintf(name, 1024, "%s%s", infldr, de->d_name); stat(name, &st); if(S_ISREG(st.st_mode)) { int len = strlen(de->d_name); if (len < 5) continue; if (de->d_name[len-4] != '.' || de->d_name[len-3] != 'g' || de->d_name[len-2] != 'd' || de->d_name[len-1] != 'i' ) { continue; } if (!strcmp(de->d_name, "disc_optimized.gdi")) { continue; } snprintf(oname, 1024, "%sdisc_optimized.gdi", infldr); if (convert_gdi(name, oname, infldr)) fprintf (logfd, "ERROR: Can't optimize %s\n", name); } else if (S_ISDIR(st.st_mode)) { snprintf(name, 1024, "%s%s/", infldr, de->d_name); convert_folder(name); } } closedir(indir); return 0; } int main(int argc, char *argv[]) { if(argc < 2) { printf("GDI optimizer v0.2 by SWAT & megavolt85\n"); printf("Usage: %s input_folder\n", argv[0]); return 0; } logfd = fopen("log.txt", "at"); if (!logfd) { printf("ERROR can't create log file\n"); return -1; } struct tm *ptr; time_t lt; lt = time(NULL); ptr = localtime(&lt); fprintf (logfd, "%s------ LOG Starte'd ------\n\n", asctime(ptr)); convert_folder(argv[1]); fprintf (logfd, "\n\n------ LOG END ------\n\n"); fclose(logfd); return 0; }
C
/* Example * Description: Special file example. * Edited by : Georgi D. Sotirov, gdsotirov@gmail.com */ #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #define BUF_SZ 8192 int main() { char buf1[BUF_SZ]; char buf2[BUF_SZ]; int fd1; int fd2; int ofs; int diff = 0; /* shows if there a difference between files */ fd1 = open("/dev/dsk3", O_RDONLY); /* open special block device file */ fd2 = open("/dev/rdsk3", O_RDONLY); /* open special char device file */ lseek(fd1, (off_t)0, SEEK_END); /* seeking to the end of file 1 */ lseek(fd2, (off_t)0, SEEK_END); /* seeking to the end of file 2 */ read(fd1, buf1, sizeof(buf1)); /* read file 1 */ read(fd2, buf2, sizeof(buf2)); /* read file 2 */ for ( ofs = 0; ofs < sizeof(buf1); ofs++ ) { /* compare the two files */ if ( buf1[ofs] != buf2[ofs] ) { printf("There is a difference at offset %d.\n", ofs); diff = 1; } } if ( diff == 0 ) printf("The data match.\n"); return 0; }
C
/*----------------------------------------------------------- recouvrement de processus et attente de terminaison du fils -------------------------------------------------------------*/ #include <unistd.h> #include <stdio.h> #include <stdlib.h> main(int argc,char* argv[],char* arge[]) { switch (fork()) { case (pid_t) -1 : perror(""),exit(1);// break inutile case (pid_t) 0 : /* on est dans le processus fils */ execl("./fils","fils",NULL); printf("je rentre pas dedans");// ne l'écrit puisque l'execl lance un processus externe //au programme il fera donc un exit a la fin de l'execution du programme fils exit(1); default: /* on est dans le processus pere */ wait(NULL); // le pere attend que les processus fils soit terminer printf("je suis le pere \n"); } }
C
#include<stdio.h> main(){ int i,arr_A[4]={1,2,3,4}; for(i=0; i<4; i++) printf("%d \n",arr_A[i]); }
C
#include<stdio.h> #include<sys/wait.h> #include<unistd.h> #include<wait.h> int main(){ pid_t pid, pid1; pid = fork(); if(pid == 0){//incase child process execlp("/bin/ls", "ls", NULL); printf("print after execlp"); } else if(pid>0){//incase parent process wait(NULL); printf("Child complete\n"); } else{//incse error printf("failed to fork!"); return -1; } return 0; }
C
/* * timeouts and clock * * time.c * Changed: <2022-01-04 10:57:54 curt> */ #include <types.h> #include <sys/sys.h> #include <sys/proc.h> #include <sys/signal.h> long seconds = 0; /* system time */ int revel = 0; /* seconds to revelie for sleep system call */ char ticks = 0; extern char resched, swapping, memwant, /* idle */ ; extern struct proc *swapproc; /* * Clock interrupt service routine * 8 HERTZ clock * We assume that HERTZ is a power of 2. */ clock() { register struct proc *p; register int *sec; timein(); /* see below */ resched = 1; /* * Once per second stuff. * Bump the clock calendar * Do alarms & sleeps */ if (!(++ticks & 7)) { /* once a second */ sec = &seconds; /* avoid longs in interrupt code */ if (++sec[1] == 0) { /* NOT PORTABLE */ ++sec[0]; } if (--revel == 0) { /* see snooze in sys2.c */ wakeup(&revel); } if (memwant && !swapping && !(ticks & 31)) { run(swapproc); /* every 4 seconds */ } ei(); for (p = plist; p < plist + NPROC; p++) { if (p->mode & ALIVE) { p->time++; /* residency time */ if (p->alarm && (--p->alarm == 0)) { send(p, SIGALRM); } } } di(); } } /* * Timeout code. This is a simplified version for use with * only a few timeout slots. */ #define NTMOUTS 5 /* max simultaneous timeouts */ struct tmout { int (*func)(); int arg; unsigned int ticks; }; struct tmout tlist[NTMOUTS] = 0; /* timeout list */ /* * Called from the clock interrupt HERTZ times per second * to update the countdowns and invoke the functions * that are ready. In case the invocations take longer * than a clock period, the tmbusy flag prevents stumbling. */ timein() { static char tmbusy = 0; register struct tmout *t; if (tmbusy) return; tmbusy = 1; for (t = tlist; t < tlist + NTMOUTS; t++) if (t->func != 0 && --t->ticks == 0) { (*(t->func)) (t->arg); t->func = 0; } tmbusy = 0; } /* * Timeout(func, arg, ticks) arranges that after >= ticks, * the clock interrupt will in turn call (*func)(arg). */ timeout(func, arg, ticks) int (*func)(), arg, ticks; { register struct tmout *t; di(); for (t = tlist; t < tlist + NTMOUTS; t++) if (t->func == 0) { t->func = func; t->arg = arg; t->ticks = ticks + 1; ei(); return; } panic("Timeout slots are full"); } /* * vim: tabstop=4 shiftwidth=4 expandtab: */
C
/* Copyright (C) 2019-2020 JingWeiZhangHuai <jingweizhanghuai@163.com> Licensed under the Apache License, Version 2.0; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "morn_wave.h" void mWaveConvolve(MWave *src,float core[],int core_size,MWave *dst) { int i,j,k; int cn; int l; MWave *p; mException((INVALID_WAVE(src))||(INVALID_POINTER(core))||(core_size <= 0),EXIT,"invalid input"); p = dst; if(INVALID_POINTER(dst)) dst = mWaveCreate(src->channel,src->size,NULL); else mWaveRedefine(dst,src->size,src->channel,dst->data); l = core_size>>1; for(cn=0;cn<src->channel;cn++) { for(j=0;j<l;j++) { dst->data[cn][j] = 0.0; for(i=j-l,k=0;k<core_size;i++,k++) dst->data[cn][j] = src->data[cn][j] + src->data[cn][((i<0)?0:i)]*core[k]; } for(j=l;j<(src->size+l-core_size);j++) { dst->data[cn][j] = 0.0; for(i=j-l,k=0;k<core_size;i++,k++) dst->data[cn][j] = dst->data[cn][j] + src->data[cn][i]*core[k]; } for(;j<src->size;j++) { dst->data[cn][j] = 0.0; for(i=j-l,k=0;k<core_size;i++,k++) dst->data[cn][j] = src->data[cn][j] + src->data[cn][((i>=src->size)?(src->size-1):i)]*core[k]; } } if(p!=dst) { mWaveExchange(src,dst); mWaveRelease(dst); } } void mWaveDeBackground(MWave *src,MWave *dst,int win_length) { int i,cn; int sum; int l; MWave *p; mException((INVALID_WAVE(src))||(win_length <= 1),EXIT,"invalid input"); p = dst; if(INVALID_POINTER(dst)) dst = mWaveCreate(src->channel,src->size,NULL); else mWaveRedefine(dst,src->size,src->channel,dst->data); l = win_length>>1; win_length = (l<<1)+1; for(cn=0;cn<src->channel;cn++) { sum = src->data[cn][0]*l; for(i=0;i<=l;i++) sum = sum + src->data[cn][l]; for(i=0;i<l;i++) { dst->data[cn][i] = src->data[cn][i] - (sum/win_length); sum = sum - src->data[cn][0] + src->data[cn][i+l+1]; } for(;i<src->size -l-1;i++) { dst->data[cn][i] = src->data[cn][i] - (sum/win_length); sum = sum - src->data[cn][i-l] + src->data[cn][i+l+1]; } for(;i<src->size;i++) { dst->data[cn][i] = src->data[cn][i] - (sum/win_length); sum = sum - src->data[cn][i-l] + src->data[cn][src->size-1]; } } if(p!=dst) { mWaveExchange(src,dst); mWaveRelease(dst); } }
C
#include "stdio.h" #include "malloc.h" int* twoSum(int* numbers,int numberSize,int target,int* returnSize){ int i=0,j=numberSize-1; int* result=malloc(sizeof(int)*2); for(;i<numberSize-1;i++){ for(;j>i;j--){ int ret=numbers[i]+numbers[j]; if(ret==target){ result[0]=i+1; result[1]=j+1; *returnSize=2; return result; }else if(ret<target){ break; }else if(ret>target){ //useless continue; } } } return result; } int main(int argv,char* argc){ int nums[]={2,3,4}; int size=3; int target=6 ; int* result=twoSum(nums,size,target); printf("result=%d,%d\n",result[0],result[1]); return 0; }
C
#include "MLList.h" #include <stdio.h> #include <stdlib.h> void MLList_destroy(MLList *); void MLList_addLast(MLList *, const void *); bool MLList_remove(MLList *, int); void MLList_clear(MLList *); bool MLList_writeFile(const MLList *, const char *); bool MLList_readFile(MLList *, const char *); MLList_Node *MLList_getNode(const MLList *, const void *); void MLList_init(MLList *self, size_t elementSize, const void (*assign)(void *, const void *)) { // 在这里初始化没有用,因为函数里的self只是原来指针的副本而已 // 所以必须要保证self已经初始化 // if (self == NULL) // { // self = (MLList *)malloc(sizeof(MLList)); // } self->size = 0; self->head = self->tail = NULL; //注册各个函数指针 self->destroy = MLList_destroy; self->addLast = MLList_addLast; self->remove = MLList_remove; self->clear = MLList_clear; self->readFile = MLList_readFile; self->writeFile = MLList_writeFile; self->elementSize = elementSize; self->assign = assign; self->search = NULL; self->getNode = MLList_getNode; } void MLList_destroy(MLList *self) { MLList_clear(self); free(self); } void MLList_clear(MLList *self) { MLList_Node *curr = self->head; MLList_Node *temp; while (curr != NULL) { free((curr->element)); temp = curr; curr = curr->next; free(temp); } self->head = self->tail = NULL; self->size = 0; } // void MLList_addLast(MLList *self, const void *item) void MLList_addLast(MLList *self, const void *item) { MLList_Node *newNode = (MLList_Node *)malloc(sizeof(MLList_Node)); // newNode->element = malloc(sizeof(self->elementSize)); // 我去,sizeof(self->elementSize)相当于sizeof(size_t) == 8 newNode->element = malloc(self->elementSize); // 为element申请空间,很重要;不然element只是一个void*而已 // newNode->element = item; // 浅复制 self->assign(newNode->element, item); // 深复制 newNode->next = NULL; if (self->head == NULL) { self->head = self->tail = newNode; } else { MLList_Node *temp = self->tail; temp->next = newNode; self->tail = newNode; } self->size++; } bool MLList_remove(MLList *self, int index) { if (index < 0 || index >= self->size) { printf("Invalid index: [%d]\n", index); return false; } MLList_Node *removeNode; if (index == 0) { // free(self->head->element); // 释放深复制申请的内存 removeNode = self->head; if (self->head->next == NULL) { self->head = self->tail = NULL; } else { self->head = self->head->next; } } else { MLList_Node *prev = self->head; for (int i = 0; i < index - 1; i++) { prev = prev->next; } // free(prev->next->element); removeNode = prev->next; prev->next = prev->next->next; if (index == self->size - 1) { self->tail = prev; } } free(removeNode->element); free(removeNode); self->size--; return true; } bool MLList_writeFile(const MLList *self, const char *filePath) { FILE *fp = fopen(filePath, "wb"); // TODO: 判断文件打开是否成功 MLList_Node *curr = self->head; while (curr != NULL) { fwrite(curr->element, self->elementSize, 1, fp); curr = curr->next; } fclose(fp); return true; } bool MLList_readFile(MLList *self, const char *filePath) { FILE *fp = fopen(filePath, "rb"); // TODO: 判断文件打开是否成功 while (1) { void *element = malloc(self->elementSize); fread(element, self->elementSize, 1, fp); if (feof(fp)) { free(element); break; } self->addLast(self, element); free(element); } fclose(fp); return true; } MLList_Node *MLList_getNode(const MLList *self, const void *key) { if (self->search != NULL) for (MLList_Node *curr = self->head; curr != NULL; curr = curr->next) { if (self->search(curr->element, key)) { return curr; } } return NULL; }
C
/* * ===================================================================================== * * Filename: exec.c * * Description: shows exec * * Version: 1.0.0 * Created: 04/10/2018 09:40:05 AM * Revision: none * Compiler: gcc * * Author: Ovidiu - Dan Bogat [ic17b501], ic17b501@technikum-wien.at * ===================================================================================== */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <string.h> #include <errno.h> #include "exec.h" int main(int argc, char** argv) { argc=argc; argv=argv; pid_t fork_pid; char *const args[] = {"/bin/ls", "-l",NULL}; fork_pid = fork(); if(fork_pid == 0) { //Child process execv("/bin/ls",args); fprintf(stderr,"[FATAL] %s\n",strerror(errno)); exit(errno); }else if(fork_pid < 0) { //Fork failed fprintf(stderr,"[FATAL] fork() failed %s\n",strerror(errno)); exit(errno); }else{ //parent process } return (EXIT_SUCCESS); }
C
#include <stdio.h> #include <string.h> int main() { int i, len; int start, stop; char string[] = "The University of Aizu"; char *p, *q; len=strlen(string); printf("Please input start and stop numbers (1 - %d, start <= stop): ", len); scanf("%d%d", &start, &stop); /* 通常の配列添字を使い、配列要素を順次参照する方法 */ for(i = start - 1; i < stop; i++) { printf("%c",string[i]); } printf("\n"); /* ポインタ演算で参照するアドレスを変えていく方法 */ p = string; for(i = start - 1; i < stop; i++) { printf("%c",*(p + i)); } printf("\n"); /* ポインタ変数に格納されているアドレスそのものを変えていく方法 */ for(q = p + start - 1; q < p + stop; q++) { printf("%c",*q); } printf("\n"); printf("\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> int main(void) { pid_t pid; int i; int first_pid=getpid(); printf("pid:%d,PGID:%d\n",getpid(),getpgid(0)); for(i =0;i<3;i++) { if((pid= fork())<0) { fprintf(stderr,"fork: %s\n",strerror(errno)); exit(1); }else if(pid == 0) { setpgid(getpid(),first_pid); if(getppid()==first_pid) { if(setpgid(getpid(),getpid())<0) { fprintf(stderr,"setpgid: %s \n",strerror(errno)); exit(1); } } printf("pid:%d,PGID:%d\n",getpid(),getpgid(0)); }else { break; } } pause(); return 0; }
C
#include <stdio.h> #include <string.h> #include <cs50.h> #include <math.h> #include <stdlib.h> #include <ctype.h> int main(int argc, string argv[]){ int key; if(argc != 2){ printf("Usage: ./caesar key \n"); return 1; } else{ for(int i = 0; i < strlen(argv[1]); i++){ //printf("%c \n", argv[1][i]); if(!isdigit((int)argv[1][i])){ printf("Please provide a numeric key\n"); return 1; } } key = atoi(argv[1]); if(key < 1){ printf("If the key is a number, please provide a number greater or equal to 1 \n"); return 1; } } string cipher_text = ""; string plain_text = get_string("plaintext: "); printf("ciphertext: "); for(int i = 0; i < strlen(plain_text); i++){ int character = (int) plain_text[i]; int ci; //printf("Before, %c \n", plain_text[i]); if(isalpha(character)){ if(isupper(character)){ character -= 65; ci = (character + key) % 26; ci += 65; //printf("%c", (char) ci); } if(islower(character)){ character -= 97; ci = (character + key) % 26; ci += 97; } } else{ ci = character; } printf("%c", (char) ci); // printf("After, %c \n", ci); } printf("\n"); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* visu3.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: toliver <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/01/04 09:33:32 by toliver #+# #+# */ /* Updated: 2020/01/04 09:51:04 by toliver ### ########.fr */ /* */ /* ************************************************************************** */ #include "vm.h" void ft_set_color(t_visu_env *venv, int color) { SDL_Color *col; if (color < 0 || color >= COLORLIMIT) return ; col = &(venv->color[color]); SDL_SetRenderDrawColor(venv->renderer, col->r, col->g, col->b, col->a); } SDL_Color *ft_get_color(t_visu_env *venv, int color) { SDL_Color *col; if (color < 0 || color >= COLORLIMIT) return (NULL); col = &(venv->color[color]); return (col); } void ft_hex_to_buff(unsigned char value, char buf[3]) { buf[0] = value / 16 + (value / 16 < 10 ? '0' : 'a' - 10); buf[1] = value % 16 + (value % 16 < 10 ? '0' : 'a' - 10); buf[2] = 0; } int ft_get_color_from_player(int player) { if (player == -1) return (GREEN); else if (player == -2) return (BLUE); else if (player == -3) return (RED); else if (player == -4) return (CYAN); else if (player == 0) return (BRIGHT_GREEN); else return (WHITE); } void ft_display_winner(char *value, t_visu_env *venv) { SDL_Rect rect; SDL_Surface *surf; SDL_Texture *tex; rect.x = 1225; rect.y = 75; if (!(surf = TTF_RenderText_Blended(venv->font[NORMAL], value, *ft_get_color(venv, WHITE)))) return ; if (!(tex = SDL_CreateTextureFromSurface(venv->renderer, surf))) { SDL_FreeSurface(surf); return ; } SDL_FreeSurface(surf); TTF_SizeText(venv->font[NORMAL], value, &rect.w, &rect.h); SDL_RenderCopy(venv->renderer, tex, NULL, &rect); SDL_DestroyTexture(tex); SDL_RenderPresent(venv->renderer); }
C
#include <xc.h> #include "SPI.h" /******************************************************************************/ #define SPI_MODE0 0 #define SPI_MODE1 1 #define SPI_MODE2 2 #define SPI_MODE3 3 void SPI_init() { //Pinos(18F2550) TRISCbits.TRISC7 = 0; //SDO // TRISCbits.TRISC7 = 0; //SDO (18f4520) TRISBbits.TRISB1 = 0; //SCK // TRISCbits.TRISC3 = 0; //SCK (18f4520) TRISAbits.TRISA5 = 0; //SS //Modo SPI SSPSTATbits.SMP = 1; SSPSTATbits.CKE = 1; //Escrita da passagem ativa para inativa do clock SSPCON1bits.SSPEN = 1; //Hardware ligado SSPCON1bits.CKP = 1; //Estado inativo do clock alto SSPCON1bits.SSPM = 0b0010;//(Fosc/64) } unsigned char SPI_transfer(unsigned char data) { SSPBUF = data; while(!SSPSTATbits.BF); SSPSTATbits.BF = 0; return SSPBUF; }
C
#include "API.h" #include <ifaddrs.h> #include <sys/ipc.h> #include <sys/shm.h> typedef struct photo_{ int photo_id; char ** keyword_array;//pode ter mais que uma keyword char * photo_name; struct photo_ *next; } photo; typedef struct photo_memory_{ photo *firstPhoto; photo *lastPhoto; } photo_memory; photo_memory *photoList; int32_t global_photo_id; //this will be the address clients connect to struct sockaddr_in addr_4clients; bool in_ready = false;//bool for incoming thread readiness int my_peer_id = -125; float my_busy_lvl = 6.78; /*photo *photoListINIT(photo * first, photo * last){ photo *aux; if (first == NULL){ //empty list: initialize aux= (photo *) malloc(sizeof(photo)); if (aux == NULL){ perror("malloc"); exit(-1); } first = aux; last = aux; }else{ //list has at least one element: allocate for one more aux = (photo *) malloc(sizeof(photo)); if (aux == NULL){ perror("malloc"); exit(-1); } last->next = aux; last = aux;//lastPhoto aponta sempre para o ultimo peer. //assim, os peers são sempre adicionados ao fim da lista, ordenadamente } last->next = NULL; return aux; }*/ //thread that handles all incoming connections void *incoming_handler(void *arg){ socklen_t addr_size; int sock_fd_4clients, incoming_sock_fd; //inbound NetworkMessage *network_message_in; Content *content_in; //char c_in; int d_in = 0; char buf_in[MAX_MSG_SIZE]; //outbound NetworkMessage network_message_out; Content content_out; unsigned len_out; char *buf_out; bool flag_send = false; bool flag_broadcast = false; //aux variables for content_out int out_message_type; /*char out_ip[20], out_keyword[1024]; int out_port, out_peer_id, out_op_result, out_id_photo; float out_busy_lvl = 0; PeersList peers_list_out; Peer peer_out; Metadata metadata_out; */ puts("@incoming_handler"); //prepare my "outter" socket addr_4clients.sin_family = AF_INET; addr_4clients.sin_port = INIT_PORT + getpid();//randomize port addr_4clients.sin_addr.s_addr = INADDR_ANY; //socket that the peer will use for any incoming message sock_fd_4clients = socket(AF_INET, SOCK_STREAM, 0); if (sock_fd_4clients == -1){ perror("socket (incoming_handler):"); exit(-1); } printf("Incoming socket created..."); //prepare the socket to receive connections from anyone (1st gw then clients) int err = bind(sock_fd_4clients, (struct sockaddr *) &addr_4clients, sizeof(addr_4clients)); if (err == -1){ perror("bind (incoming_handler)"); exit(-1); } printf(" and binded.."); //10 ou 20 = length of incoming queue before accept if (listen(sock_fd_4clients, 20) == -1){ perror("listen (incoming_handler)"); exit(-1); } printf(" Listening..."); in_ready = true; struct sockaddr_in addr_incoming; addr_size = sizeof(struct sockaddr_in); puts("waiting @ accept..."); incoming_sock_fd = accept(sock_fd_4clients, (struct sockaddr *) &addr_incoming, &addr_size); if (incoming_sock_fd == -1){ perror("accept (incoming_handler)"); exit(-1); } printf("done accept\n"); while(1){ printf("@ incoming thread waiting for messages\n"); d_in = recv(incoming_sock_fd, &buf_in, MAX_MSG_SIZE, 0); //printf("secalhar não (na thread)\n"); printf("@ incoming thread received %d bytes from %s:%d \n", d_in, inet_ntoa(addr_incoming.sin_addr), ntohs(addr_incoming.sin_port)); if(d_in <= 0){ printf("I shouldn't be getting %d bytes from them.", d_in); getchar(); continue;//ignore message } //debug printf("buf_in = "); print_buffer((uint8_t *) buf_in, d_in); printf("unpacking buf_in..."); //unpack received buffer and populate structure network_message_in = network_message__unpack(NULL, d_in, (uint8_t *) buf_in); puts("done"); printf("Received message: UserType = %u | MessageType = %u\n", network_message_in->user_type, network_message_in->message_type);//debug if (network_message_in->content != NULL){ printf(" | Content = true\n"); }else{ printf(" | Content = false\n"); } //reinitialize structure content__init(&content_out); switch (network_message_in->user_type){ case 0://GW = 0 puts("Hello gateway, I shouldn't be getting messages from you here...I'm not going to process it"); break; case 1://PEER = 1 puts("hello my fellow peer!"); switch (network_message_in->message_type){ case 3://OP = 3 content_in = network_message_in->content; if (content_in == NULL){ puts("peer, didn't receive content..."); } else{ puts("received an operation message from another peer!"); if (!(content_in->has_op_type)){ puts("peer, no op_type?"); }else{ //doesn't need to send anything out, just update my own structures switch(content_in->op_type){ case 0: //new photo coming in! - updated on one of the peers break; case 1: //new keyword added to a photo: verify if we already have it... break; case 2: //delete a photo break; default: printf("peer, I wasn't supposed to receive this op_type = %d\n", content_in->op_type); break; } } } break; default: printf("peer, received a wrong message_type = %d\n", network_message_in->message_type); break; } break; case 2://CLIENT = 2 printf("Hello client, ");//debug switch (network_message_in->message_type){ case 0://CONNECT = 0 puts("received a connect message.");//debug flag_send = true; out_message_type = 0;//CONNECT = 0 content_out.has_op_result = true; content_out.op_result = 1; break; case 3://OP = 3 puts("received an operation message");//debug out_message_type = 3; flag_send = true; content_out.has_op_result = true; content_in = network_message_in->content; if(content_in == NULL){ puts("but it has no content! continuing..."); break; } switch (content_in->op_type){ case 0://ADD_PHOTO puts("gallery_add_photo - inserting new photo on list!"); //need to check if this peer already has a list of photos photo *new_photo = (photo *) malloc(sizeof(photo)); if (new_photo == NULL){ perror("malloc"); exit(-1); } if (photoList->firstPhoto == NULL){ //empty list: initialize puts("empty photo list"); photoList->firstPhoto = new_photo; photoList->lastPhoto = new_photo; }else{ puts("photo list initialized, adding new one"); //list has at least one element: allocate for one more photoList->lastPhoto->next = new_photo; photoList->lastPhoto = new_photo;//lastPhoto aponta sempre para o ultimo peer. //assim, os peers são sempre adicionados ao fim da lista, ordenadamente } photoList->lastPhoto->next = NULL; global_photo_id++; new_photo->photo_id = global_photo_id; puts("here I should notify peers that global_photo_id changed"); //BROADCAST MESSAGE TO ALL PEERS content_out.op_result = new_photo->photo_id;//teste break; case 1://ADD_KW puts("gallery_add_keyword()"); content_out.op_result = 1;//teste, conforme o enunciado break; case 2://DEL puts("gallery_delete_photo()"); content_out.op_result = 1;//teste, conforme o enunciado break; case 3://SEARCH puts("gallery_search_photo()"); content_out.op_result = 33;//teste, conforme o enunciado //HERE I SHOULD RETURN THE PHOTO_ID... break; case 4://GET_NAME puts("gallery_get_photo_name()"); content_out.op_result = 1;//teste, conforme o enunciado break; case 5://DOWNLOAD puts("gallery_get_photo()"); content_out.op_result = 1;//teste, conforme o enunciado break; default: printf("error op_type\n"); content_out.op_result = -1;//atenção que o erro a retornar tem break; //valores diferentes para cada função... } break; default: printf("client, you sent me an illegal message_type = %d\n", network_message_in->message_type);//debug break; } break; default: printf("something went wrong, received user_type = %d\n", network_message_in->user_type); break; } if (flag_send){ network_message__init(&network_message_out); network_message_out.user_type = 1;//PEER = 1 network_message_out.message_type = out_message_type; //content__init é sempre feito lá em cima network_message_out.content = &content_out; len_out = network_message__get_packed_size(&network_message_out); buf_out = (char *) malloc(len_out); if (buf_out == NULL){ perror("malloc"); exit(-1); } //pack it and send to gw network_message__pack(&network_message_out, (uint8_t *) buf_out); //debug printf("buf_out = "); print_buffer((uint8_t *) buf_out, len_out); printf("out_message_type: %d\n", network_message_out.message_type); printf("Press enter when ready to send buf_out to [%d] (2=client) ) @ %s:%d", network_message_in->user_type, inet_ntoa(addr_incoming.sin_addr), ntohs(addr_incoming.sin_port)); getchar(); send(incoming_sock_fd, buf_out, len_out, 0); puts("sent"); free(buf_out); } flag_send = false; // broadcast message to all other peers: send a photo and metadata if (flag_broadcast){ //NO TIME :( } flag_broadcast = false; puts("next!"); } // FALTA CAPTURAR CTRL-C close(sock_fd_4clients); } /* void *send_alive(void *gw_addr){ //thread that sends alive signal to server every 4 seconds -> qual é o tempo ideal? int gw_socket_alive; network_messages dumpeer_start_msg; //create a new, dedicated socket gw_socket_alive = socket(AF_INET, SOCK_DGRAM, 0); if (gw_socket_alive == -1){ perror("socket (4GW_alive)"); exit(-1); } dumpeer_start_msg.message_type = server_alive; while(1){ sendto(gw_socket_alive, &dumpeer_start_msg, sizeof(network_messages), 0, (const struct sockaddr *) &gw_addr, sizeof(gw_addr)); puts("send_alive here: just sent alive signal to GW");// comenta e descomenta para debug sleep(4); } capture ctrl-c... } */ int main(int argc, char const *argv[]){ struct in_addr gatewayIP; int gatewayPort; char gwIP[60], gwPort[60]; //this will be the gateway's address so I can be announced to clients struct sockaddr_in gw_addr; socklen_t socklen; //protobuf outbound NetworkMessage network_message_out; network_message__init(&network_message_out); network_message_out.user_type = 1;//PEER = 1, sempre o mesmo int len_out; char *buf_out; Content content_out; content__init(&content_out); //inbound NetworkMessage *network_message_in; Content *content_in; PeersList *peers_list_in; //other int d_in = 0; char buf_in[MAX_MSG_SIZE]; //threads pthread_t thr_id_incoming/*, thr_id_send_alive*/; int pt_error; int i = 0; //shared_memory para as fotos //key_t photoShmKEY; //char cwd[60];//para o ftok ficar com o path //int photoShmID; /* //tentativa de shared memory if (getcwd(cwd, sizeof(cwd)) == NULL){ perror("getcwd: "); //exit(-1); } //printf("path for cwd = %s\n", cwd);//depois apaga isto photoShmKEY = ftok(cwd, 'R');//le wild char appears //allocating 10 slots in shared memory photoShmID = shmget(photoShmKEY, sizeof(photo_memory), IPC_CREAT | 0666); if (photoShmID < 0){ perror("shmget (peer): "); exit(1); } //puts("Gateway received a shared memory able to hold 10 peer_list elements"); photoList = (photo_memory *) shmat(photoShmID, NULL, 0); if (photoList == (void *) -1){ printf("*** shmat error (gateway) ***\n"); exit(1); } */ photoList = malloc(10 * sizeof(photo)); photoList->firstPhoto = NULL; photoList->lastPhoto = NULL; // create a thread that handles all incoming messages pt_error = pthread_create(&thr_id_incoming, NULL, incoming_handler, NULL); if (pt_error != 0){ perror("pthread_create (incoming_handler): "); exit(-1); } //wait for thread to start listening socket - pthread_join() faria equivalene while(!in_ready){ puts("waiting for thread incoming_handler to start..."); sleep(1); } //Get Gateway info printf("what is the GW IP?\n"); if (fgets(gwIP, 60, stdin) != NULL){ //puts(gwIP);//debug if (inet_aton(gwIP, &gatewayIP) == 0){ perror("inet_aton : "); exit(-1); } } printf("what is the port? default = 7654\n"); if (fgets(gwPort, 60, stdin) != NULL){ puts(gwPort);//debug gatewayPort = atoi(gwPort); } inet_aton(gwIP, &gatewayIP); gatewayPort = atoi(gwPort); //printf("gw @ %s:%s\n", gwIP, gwPort);//debug printf("my port for clients: %d\n", ntohs(addr_4clients.sin_port)); //socket I use to sendto Gateway int gw_socket = socket(AF_INET, SOCK_DGRAM, 0); if (gw_socket == -1){ perror("socket (4GW): "); exit(-1); } //put it in the proper struct gw_addr.sin_family = AF_INET; gw_addr.sin_port = htons(gatewayPort); gw_addr.sin_addr = gatewayIP; socklen = sizeof(gw_addr); /* printf("My open port to be sent to gw: %d\ngw @ %s:%d\n", peer_msg_content_aux->port, inet_ntoa(gw_addr.sin_addr), ntohs(gw_addr.sin_port)); */ //populate structure network_message_out.message_type = 0;//CONNECT = 0 content_out.has_port = true; content_out.port = ntohs(addr_4clients.sin_port); //printf("sin_port:%d\ncontent_out.port:%d\n", addr_4clients.sin_port, content_out.port); printf("Packing my connect message to sendo to gateway (user_type = peer, msg_type = connect, content = {port = %d})...", content_out.port); network_message_out.content = &content_out; len_out = network_message__get_packed_size(&network_message_out); buf_out = (char *) malloc(len_out); if (buf_out == NULL){ perror("malloc"); exit(-1); } //pack it and send to gw network_message__pack(&network_message_out, (uint8_t *) buf_out); //debug printf("done\nmy buf_out = "); print_buffer((uint8_t *) buf_out, len_out); printf("Press enter when ready to send buf_out to gw @ %s:%d", inet_ntoa(gw_addr.sin_addr), ntohs(gw_addr.sin_port)); getchar(); //actual send sendto(gw_socket, buf_out, len_out, 0, (const struct sockaddr *) &gw_addr, socklen); printf("sent connect network_message to gw, awaiting response [still need to know my ID]...\n"); //já não vamos usar mais, limpa-se... free(buf_out); puts("waiting for incoming messages (clients, gw and other peers)..."); //initialize photo_id global_photo_id = 0; //printf("global_photo_id = %d\n", global_photo_id);//debug _ devia receber o ID e a quanto vai este valor if(photoList->firstPhoto == NULL) puts("photo_list uninitialized"); //create thread to handle send_alive /* pt_error = pthread_create(&thr_id_send_alive, NULL, send_alive, &gw_addr); if (pt_error != 0){ perror("pthread_create (send_alive): "); exit(-1); } */ //cycle dedicated for gw, to update peers_list while(1){ d_in = recvfrom(gw_socket, buf_in, MAX_MSG_SIZE, 0, (struct sockaddr *) &gw_addr, &socklen); printf("received %d bytes from %s:%d \n", d_in, inet_ntoa(gw_addr.sin_addr), ntohs(gw_addr.sin_port)); //debug printf("buf_in = "); print_buffer((uint8_t *) buf_in, d_in); //puts("in this message there should the PeersList, and on first, my id"); network_message_in = network_message__unpack(NULL, d_in, (uint8_t *) buf_in); printf("unpacked buf_in\n"); //verifications printf("Received message: UserType = %u | MessageType = %u", network_message_in->user_type, network_message_in->message_type); if (network_message_in->content != NULL){ printf(" | Content = true\n"); content_in = network_message_in->content; /*printf("content_in->ip = %s | content_in->port =%d\n", content_in->ip, content_in->port);//debug*/ if (!(content_in->has_peer_id)){ puts("didn't receive my id from gateway...."); }else{ my_peer_id = content_in->peer_id; } printf("my_peer_id = %d\n", my_peer_id); if (content_in->peers_list != NULL){ peers_list_in = content_in->peers_list; printf("total number of peers on the network = %lu\n", peers_list_in->n_peer); for(i = 0; i < peers_list_in->n_peer; i++){ printf("peer_id = %d | ", peers_list_in->peer[i]->peer_id); printf("%s:", peers_list_in->peer[i]->ip); printf("%d", peers_list_in->peer[i]->port); if (peers_list_in->peer[i]->peer_id == my_peer_id){ printf(" <- me"); } printf("\n"); } }else{ puts("didn't receive peers_list from gateway..."); } }else{ printf(" | Content = false\n"); } } //must handle this... close(gw_socket); puts("peer out, good bye cruel world"); exit(0); }
C
#include<stdio.h> struct a{ int a_a; int b_b; int c_c; }; struct A{ int a; int b; int c; struct a aaaa; struct a *aa; }; struct name{ char sei[5]; char mei[5]; }; struct line{ struct name Name[5]; }; int main(){ struct A A_[10]; struct A *A__ = A_; for(int i=0;i<10;i++){ A_[i].a = i; A_[i].b = i; A_[i].c = i; A_[i].aaaa.a_a = i; A_[i].aa = &(A_[i].aaaa); } struct a aaaaaa = A__->aaaa; struct a *aaaaaa___ = &aaaaaa; printf("%d\n",(&(A__->aaaa))->a_a); // printf("%d\n",(A__->aaaa)->a_a); struct line lines[10]; // lines[0].name[0] = 'a'; struct line *linesP = lines; printf("%s\n",(&(((linesP+0)->Name)[0]))->sei); // printf("%d\n",*(A__->aaaa)->a_a); return 0; }
C
// // main.c // lab5_task1 // // Created by Hamza Rehman on 10/20/19. // Copyright © 2019 Hamza Rehman. All rights reserved. // #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 10 typedef struct{ char *str; } STRING; STRING *file_read(int *n); void sort_string(STRING *list, int n); int main(int argc, const char * argv[]) { int n; STRING *list = file_read(&n); sort_string(list, n); printf("Sorted file:\n"); for(int i=0; i<n; i++){ printf("%s", list[i].str); } printf("\n"); // freeing dynamically allocated memory for(int i=0; i<n; i++){ free(list[i].str); } free(list); return 0; } STRING *file_read(int *n){ FILE *file; file = fopen("data.txt", "r"); if(file == NULL){ perror("Error opening file"); exit(EXIT_FAILURE); } while(fscanf(file, "%d", n)){ printf("1st line read successfullly.\n\n"); } STRING *list; list = (STRING *) malloc (*n * sizeof(STRING)); if(list == NULL){ perror("Error in memory allocation."); exit(EXIT_FAILURE); } char word[MAX]; /*word = malloc (*n * sizeof(char)); if(word == NULL){ perror("Error in memory allocation."); exit(EXIT_FAILURE); }*/ for(int i=0; i<*n; i++){ fgets(word, sizeof(word), file); list[i].str = strdup(word); } //free(word); fclose(file); return list; } void sort_string(STRING *list, int n){ char *temp; temp = (char *) malloc (n * sizeof(char)); for(int i=0; i<n; i++){ for(int j=i; j<n; j++){ if(strcmp(list[i].str, list[j].str) > 0){ temp = strdup(list[i].str); list[i].str = strdup(list[j].str); list[j].str = strdup(temp); } } } free(temp); return; }
C
#include<stdio.h> #include<conio.h> main() { int m,n,i,j,k,a[10][10],b[10]; clrscr(); printf("ENTER THE DIMENSIONS OF THE MATRIX :\n"); scanf("%d%d",&m,&n); printf("ENTER THE ELEMENTS\n"); for(i=0;i<n;i++) { for(j=0;j<m;j++) { printf("\na[%d][%d]= ",i,j); scanf("%d",&a[i][j]); } } printf("\nELEMENTS IN SINGLE DIMENSION IS AS FOLLOWS: \n"); k=0; for(i=0;i<n;i++) { for(j=0;j<m;j++) { b[k]=a[i][j]; printf("\n\tb[%d]=%d",k,b[k]); k++; } } getch(); }
C
#include "apue.h" #include <sys/wait.h> // waitpid() #include <unistd.h> // getcwd() #include <sys/param.h> // MAXHOSTNAMELEN #include <time.h> // localtime() #include <limits.h> // LOGIN_NAME_MAX int cuserid(); int main(void) { char buf[MAXLINE]; char hostname[MAXHOSTNAMELEN]; pid_t pid; int status; char *cwd; char username[LOGIN_NAME_MAX]; // L_cuserid is in the stdio.h if(cuserid(username) == 0) { fprintf(stderr, "can not find login name\n"); exit(1); } gethostname(hostname, MAXHOSTNAMELEN); cwd = getcwd(NULL, BUFSIZ); time_t T = time(NULL); struct tm tm = *localtime(&T); if(tm.tm_hour <13) printf("[%02d:%02d:%02dAM]%s@%s(%s)$ ",tm.tm_hour%12, tm.tm_min, tm.tm_sec, hostname, username, cwd); else printf("[%02d:%02d:%02dPM]%s@%s(%s)$ ",tm.tm_hour%12, tm.tm_min, tm.tm_sec, hostname, username, cwd); while(fgets(buf, MAXLINE, stdin)!=NULL) { if(buf[strlen(buf) - 1] == '\n') buf[strlen(buf) - 1] = 0; if((pid = fork()) < 0) { err_sys("fork error"); }else if(pid == 0) { execlp(buf, buf, (char*)0); err_ret("couldn't execute: %s", buf); exit(127); } if((pid = waitpid(pid, &status, 0)) < 0) err_sys("waitpid error"); if(tm.tm_hour <13) printf("[%02d:%02d:%02dAM]%s@%s(%s)$ ",tm.tm_hour%12, tm.tm_min, tm.tm_sec, hostname, username, cwd); else printf("[%02d:%02d:%02dPM]%s@%s(%s)$ ",tm.tm_hour%12, tm.tm_min, tm.tm_sec, hostname, username, cwd); } exit(0); }
C
#include "binary_trees.h" #include "111-bst_insert.c" /** * balance_avl - balance a node and two nodes below it * @node: pointer to the tree to rotate * Return: pointer to the new root node */ avl_t *balance_avl(avl_t *node) { if (!node->right && !node->left) return (node); if (!node->right) { if (!node->left->left) node->left = binary_tree_rotate_left((binary_tree_t *) node->left); if (node->left->left) { return ((avl_t *)binary_tree_rotate_right((binary_tree_t *) node)); } } else if (!node->left) { if (!node->right->right) node->right = binary_tree_rotate_right((binary_tree_t *) node->right); if (node->right->right) { return ((avl_t *)binary_tree_rotate_left((binary_tree_t *) node)); } } return (node); } /** * avl_insert - insert a node into avl_tree * This will insert into avl and rebalance the tree * @tree: double pointer to the root of the tree * @value: value to insert into a node * * Return: the new root of the tree */ avl_t *avl_insert(avl_t **tree, int value) { avl_t *node, *tmp_node, *tmp_parent; if (tree == NULL) return (NULL); tmp_node = node = (avl_t *)bst_insert((bst_t **) tree, value); while (tmp_node->parent != NULL) { tmp_parent = tmp_node->parent; if (tmp_parent->right == tmp_node) { tmp_node = balance_avl(tmp_node); tmp_node->parent = tmp_parent; tmp_parent->right = tmp_node; } else if (tmp_parent->left == tmp_node) { tmp_node = balance_avl(tmp_node); tmp_node->parent = tmp_parent; tmp_parent->left = tmp_node; } if (tmp_node->parent == NULL) break; tmp_node = tmp_node->parent; } *tree = tmp_node; return (node); }
C
// // Created by Hugor Chau on 9/28/20. // #include "../../../Include/doom_nukem.h" #include "../../../Include/map_struct.h" #include "../../../Include/renderer.h" void check_player_place(t_data *data) { uint32_t i; t_vec2 position; char flag; static int j = 0; i = 0; flag = FALSE; position = data->engine->player->position; while (i < data->engine->sectors_count) { if (is_inside(position.x, position.y, data->engine->sectors[i].render) % 2 == 1) { data->engine->player->current_sector = &data->engine->sectors[i]; flag = TRUE; break ; } i++; } if (flag == FALSE) { ft_putendl("ERROR!"); printf("%d\n", j); } j++; } void draw_sector_3d(t_sector *sector, uint32_t walls_count, t_data *data) { uint32_t i; t_wall *wall; i = 0; wall = sector->render->walls; while (i < walls_count) { // if (wall->type == WALL) draw_wall_3d(wall, data); if (wall->type == PORTAL || wall->type == WINDOW) { wall->portal_to->sector->render->walls = wall->portal_to->next; draw_sector_3d(wall->portal_to->sector, wall->portal_to->sector->render->walls_count - 1, data); } wall = wall->next; i++; } } void clear_bitmap(t_texture *texture) { uint32_t i; i = 0; while (i < texture->width * texture->height) { texture->bit_map[i] = 0x0; i++; } } void draw_3d(t_data *data) { int i; i = data->engine->sectors_count - 1; clear_bitmap(data->sdl->layers->draw_3d); check_player_place(data); while (i >= 0) { draw_sector_3d(&data->engine->sectors[i], data->engine->sectors[i].render->walls_count, data); i--; } draw_sector_3d(data->engine->player->current_sector, data->engine->player->current_sector->render->walls_count, data); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* op_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dlancar <dlancar@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/01/25 14:46:27 by dlancar #+# #+# */ /* Updated: 2017/01/25 14:49:12 by dlancar ### ########.fr */ /* */ /* ************************************************************************** */ #include "op.h" #include "vm.h" #include <ftio.h> #include <stdint.h> #include <stddef.h> int32_t swap_int32(int32_t val) { val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF); return ((val << 16) | ((val >> 16) & 0xFFFF)); } int check_param(t_op *op, t_op_data *data) { int i; i = -1; while (++i < op->nb_params) { if ((op->param_types[i] >> (data->param_pcodes[i] - 1)) % 2 == 0) return (0); if (data->param_pcodes[i] == REG_CODE && data->params[i] > 16) return (0); } return (1); } void dump_int32(int32_t *param, size_t size) { size_t i; i = 0; while (++i < size) { debug("0x%X\n", *(param + i)); } debug("\n"); } int is_register(t_process *process, t_op_data *data, int index) { int32_t ptype; int32_t param; int32_t pcode; ptype = process->current_instruction->param_types[index]; param = data->params[index]; pcode = data->param_pcodes[index]; return ((ptype == T_REG || ((ptype & T_REG) && pcode == REG_CODE)) && param > 0 && param <= REG_NUMBER); } int is_indirect(t_process *process, t_op_data *data, int index) { int32_t ptype; int32_t pcode; ptype = process->current_instruction->param_types[index]; pcode = data->param_pcodes[index]; return (ptype == T_IND || ((ptype & T_IND) && pcode == IND_CODE)); }
C
#include "satUtils.h" /** * spec: créé et initialise la structure Sat. * renvoie le pointeur de la structure. * auteur: Thomas Rieffel * verificateur: ?? * complexité: O(1) */ Sat* createSat(){ Sat *s = malloc(sizeof(Sat)); s->clausesCount = 0; s->differentsVerticesCount = 0; s->clauses = malloc(sizeof(Clause)); return s; } /** * spec: créé et initialise une clause. * Renvoie le pointeur de la clause. * auteur: Thomas Rieffel * verificateur: ?? * complexité: O(1) */ Clause* createClause(){ Clause *c = malloc(sizeof(Clause)); c->verticesCount = 0; c->vertices = malloc(sizeof(Vertex)); return c; } /** * spec: créé et initialise un vertex. * Renvoie le pointeur du vertex. * auteur: Thomas Rieffel * verificateur: ?? * complexité: O(1) */ Vertex* createVertex(int isNeg, edge edg){ if(isNeg > 1 || isNeg < 0) return NULL; Vertex *v = malloc(sizeof(Vertex)); v->isNegative = isNeg; v->edg = edg; return v; } /** * spec: Ajoute une clause dans une structure sat. * Avec s un pointeur Sat et c une Clause * auteur: Thomas Rieffel * verificateur: ?? * complexité: O(1) */ int addClauseInSat(Sat *s, Clause *c){ if(c == NULL || s == NULL) return 0; // Passage en 3-SAT ? /* if(c->verticesCount > 3){ Clause *c1 = createClause(); addVertexInClause() Clause *c2 = createClause(); for(int i=0 ; i< ; i++){ } }*/ s->clausesCount = s->clausesCount + 1; s->clauses = realloc(s->clauses, sizeof(Clause) * s->clausesCount); s->clauses[s->clausesCount-1] = *c; // deleteClause(c); return 1; } /** * spec: Ajoute un sommet dans une clause sat. * Avec s un pointeur Sat, c une Clause et v un sommet. * auteur: Thomas Rieffel * verificateur: ?? * complexité: O(1) */ int addVertexInClause(Sat *s, Clause *c, Vertex *v){ if(c == NULL || v == NULL) return 0; c->verticesCount += 1; //if(c->verticesCount > 3) return 0; //Pour 3 sats c->vertices = realloc(c->vertices, sizeof(Vertex) * c->verticesCount); c->vertices[c->verticesCount-1] = *v; if(s->differentsVerticesCount < v->edg){ s->differentsVerticesCount = v->edg; } deleteVertex(v); return 1; } /** * spec: Affiche le sommet donné. * Avec v un sommet et isFirst qui est à 1 si le sommet est le premier de la clause, 0 sinon. * auteur: ?? * verificateur: * complexité: */ void displayVertex(Vertex *v, int isFirst){ if(isFirst == 0) printf(" v "); if(v->isNegative == 0){ printf("%d", v->edg); } else{ printf("-%d", v->edg); } } /** * spec: Affiche le probleme Sat dans son ensemble. * Avec s un Sat. * parcourt chaque clause et les affiches * auteur: Thomas Rieffel * verificateur: * complexité: */ void displaySat(Sat* s){ printf("clausesCount : %d\n", s->clausesCount); printf("nbVertex : %d\n", s->differentsVerticesCount); for(int i=0; i<s->clausesCount; i++){ displayVertex(&s->clauses[i].vertices[0], 1); for(int y=1; y<s->clauses[i].verticesCount; y++){ displayVertex(&s->clauses[i].vertices[y], 0); } printf("\n"); } } /** * spec: transfère une structure Sat vers un fichier cnf. * parcourt le Sat et pour chaque clause créé une ligne et y met les littérraux * auteur: ?? * verificateur: * complexité: O(n) */ void satToFile(Sat* s, char* path){ FILE *file = fopen(path, "w+"); fprintf(file, "p cnf %d %d\n", s->differentsVerticesCount, s->clausesCount); for(int i=0 ; i<s->clausesCount ; i++){ for(int j=0 ; j<s->clauses[i].verticesCount ; j++){ if(s->clauses[i].vertices[j].isNegative == 1) fprintf(file, "-%d ", s->clauses[i].vertices[j].edg); else fprintf(file, "%d ", s->clauses[i].vertices[j].edg); } fprintf(file, "0\n"); } fclose(file); printf("SAT printed in %s\n", path); } /** * spec: Appel le solveur mini-sat. * auteur: Alexandre Tosi * verificateur: Thomas Rieffel */ void miniSolve(char* cnf, char* out){ pid_t pid; pid = fork(); if (pid == 0){ execlp("minisat", "minisat", cnf, out, NULL); } else{ wait(0); } printf("%s résolu et solution écrite dans %s\n", cnf, out); } //supprime la structure d'un vertex void deleteVertex(Vertex *v) { free(v); } //supprime la structure d'une clause et tous ses litérraux void deleteClause(Clause *c) { deleteVertex(c->vertices); free(c); } //supprime la structure sat et toutes ses clauses void deleteSat(Sat *s) { deleteClause(s->clauses); free(s); }
C
/* Aluno: Mateus Orsoni Cabral RA: 147349 Disciplina: MC202 turma H Os nomes de variáveis e de funções são eventualmente escritos em inglês apenas por uma questão de costume. Os comentários ao longo do código serão sempre em português. */ #include "lista.h" /* Funções que capturam as entradas do teclado e realizam as manipulações correspondentes */ void parseCodeA(Lista* listArray); void parseCodeC(Lista* listArray, int* listCount); void parseCodeD(Lista* listArray); void parseCodeE(Lista* listArray); void parseCodeF(Lista* listArray); void parseCodeI(Lista* listArray); void parseCodeJ(Lista* listArray, int* listCount); void parseCodeT(Lista* listArray); void parseCodeX(Lista* listArray); int main() { Lista listArray[MAX_MERCADOS]; int listCount = 0; int N; scanf("%d", &N); for (int i=0; i<N; i++) { char code; scanf(" %c", &code); switch (code) { case 65: // A parseCodeA(listArray); break; case 67: // C parseCodeC(listArray, &listCount); break; case 68: // D parseCodeD(listArray); break; case 69: // E parseCodeE(listArray); break; case 70: // F parseCodeF(listArray); break; case 73: // I parseCodeI(listArray); break; case 74: // J parseCodeJ(listArray, &listCount); break; case 84: // T parseCodeT(listArray); break; case 88: // X parseCodeX(listArray); break; default: break; } } // Imprime e em seguida destroi cada lista do vetor for (int index=0; index < listCount; index++) { if (listArray[index].primeiro != NULL) { printf("Lista %d:\n", index); imprimirLista(&listArray[index]); } destructList(&listArray[index]); } return 0; } void parseCodeA(Lista* listArray) { int index; char itemName[MAX_NOME]; scanf("%d", &index); scanf("%s", itemName); Item item = parseItemInput(); adicionarAntes(&listArray[index], item, itemName); } void parseCodeC(Lista* listArray, int* listCount) { Item item = parseItemInput(); // Busca a primeira lista vazia no vetor para adicionar o item for (int index=0; index<*listCount; index++) if (listArray[index].primeiro == NULL) { append(&listArray[index], item); return; } // Caso nenhuma lista vazia exista, uma nova é criada e recebe o item listArray[*listCount].primeiro = NULL; append(&listArray[*listCount], item); (*listCount)++; } void parseCodeD(Lista* listArray) { int index; char itemName[MAX_NOME]; scanf("%d", &index); scanf("%s", itemName); Item item = parseItemInput(); adicionarDepois(&listArray[index], item, itemName); } void parseCodeE(Lista* listArray) { int index, quantity; char itemName[MAX_NOME]; scanf("%d", &index); scanf("%s", itemName); scanf("%d", &quantity); diminuirQuantidade(&listArray[index], itemName, quantity); } void parseCodeF(Lista* listArray) { int index; scanf("%d", &index); Item item = parseItemInput(); adicionarFim(&listArray[index], item); } void parseCodeI(Lista* listArray) { int index; scanf("%d", &index); inverterLista(&listArray[index]); } void parseCodeJ(Lista* listArray, int* listCount) { int index_1, index_2; scanf("%d", &index_1); scanf("%d", &index_2); juntarListas(&listArray[index_1], &listArray[index_2]); //destructList(&listArray[index_2]); } void parseCodeT(Lista* listArray) { int index_1, index_2; char itemName_1[MAX_NOME], itemName_2[MAX_NOME]; scanf("%d", &index_1); scanf("%d", &index_2); scanf("%s", itemName_1); scanf("%s", itemName_2); trocarItens(&listArray[index_1], &listArray[index_2], itemName_1, itemName_2); } void parseCodeX(Lista* listArray) { int index; char itemName[MAX_NOME]; scanf("%d", &index); scanf("%s", itemName); excluirItem(&listArray[index], itemName); }
C
/** * @file ccnsyncslice.c * Utility to use the Sync library to create or delete sync configuration slices. * * A CCNx program. * * Copyright (C) 2012 Palo Alto Research Center, Inc. * * This work is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as published by the * Free Software Foundation. * This work is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <unistd.h> #include <ccn/ccn.h> #include <ccn/sync.h> #include <ccn/uri.h> void usage(char *prog) { fprintf(stderr, "%s [-hv] (create|delete) topo-uri prefix-uri [filter-uri]...\n" " topo-uri, prefix-uri, and the optional filter-uris must be CCNx URIs.\n", prog); exit(1); } int main(int argc, char **argv) { int opt; int res; char *prog = argv[0]; struct ccn *h; struct ccns_slice *slice; struct ccn_charbuf *prefix = ccn_charbuf_create(); struct ccn_charbuf *topo = ccn_charbuf_create(); struct ccn_charbuf *clause = ccn_charbuf_create(); struct ccn_charbuf *slice_name = ccn_charbuf_create(); struct ccn_charbuf *slice_uri = ccn_charbuf_create(); enum { CREATE = 0, DELETE = 1 } cmd = CREATE; unsigned verbose = 0; unsigned i; if (prefix == NULL || topo == NULL || clause == NULL || slice_name == NULL || slice_uri == NULL) { fprintf(stderr, "Unable to allocate required memory.\n"); exit(1); } while ((opt = getopt(argc, argv, "vh")) != -1) { switch (opt) { case 'v': verbose = 1; break; default: case 'h': usage(prog); break; } } argc -= optind; argv += optind; if (argc < 3) usage(prog); if (strcmp(argv[0], "create") == 0) cmd = CREATE; else if (strcmp(argv[0], "delete") == 0) cmd = DELETE; else usage(prog); slice = ccns_slice_create(); ccn_charbuf_reset(topo); if (0 > ccn_name_from_uri(topo, argv[1])) usage(prog); ccn_charbuf_reset(prefix); if (0 > ccn_name_from_uri(prefix, argv[2])) usage(prog); if (0 > ccns_slice_set_topo_prefix(slice, topo, prefix)) usage(prog); for (i = 3; i < argc; i++) { ccn_charbuf_reset(clause); if (0 > ccn_name_from_uri(clause, argv[i])) usage(prog); else if (0 > ccns_slice_add_clause(slice, clause)) usage(prog); } h = ccn_create(); res = ccn_connect(h, NULL); if (0 > res) { fprintf(stderr, "Unable to connect to ccnd.\n"); exit(1); } switch(cmd) { case CREATE: res = ccns_write_slice(h, slice, slice_name); break; case DELETE: ccns_slice_name(slice_name, slice); res = ccns_delete_slice(h, slice_name); break; } if (verbose || res < 0) { ccn_uri_append(slice_uri, slice_name->buf, slice_name->length, 1); printf("%s slice %s %s\n", cmd == CREATE ? "create" : "delete", ccn_charbuf_as_string(slice_uri), (res < 0) ? "failed" : "succeeded"); } ccns_slice_destroy(&slice); ccn_destroy(&h); ccn_charbuf_destroy(&prefix); ccn_charbuf_destroy(&topo); ccn_charbuf_destroy(&clause); ccn_charbuf_destroy(&slice_name); ccn_charbuf_destroy(&slice_uri); exit(res); }
C
/* * This is the file in which you will implement the functionality required by * the assignment. Make sure to add your name and @oregonstate.edu email * address below: * * Name: Reed Boeshans * Email: boeshanr@oregonstate.edu */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include "students.h" #include "dynarray.h" /* * This function should allocate and initialize a single student struct with * name, ID, and GPA data. * * Params: * name - a string containing the student's name. Note that you'll have to * make a copy of this string to store in the student struct instead of * storing this string directly. * id - an integer ID for the student * gpa - the student's GPA * * Return: * Should return a newly-allocated student structure whose fields are * initialized with the values provided. */ struct student* create_student(char* name, int id, float gpa) { struct student* new_student = malloc(sizeof(struct student)); int length = strlen(name)+1; new_student->name = malloc(length*sizeof(char)); strncpy(new_student->name, name, length); new_student->id = id; new_student->gpa = gpa; return new_student; } /* * This function should free all memory allocated by create_student() for a * single student. This function must free all relevant memory and cannot * result in a memory leak. * * Params: * student - a pointer to the student whose memory should be freed. This * function must free any memory allocated to the fields of this struct * as well as memory allocated for the struct itself. */ void free_student(struct student* student) { free(student->name); free(student); } /* * This function should create a struct student for each student represented * in the information provided in the function arguments, and it should store * those students in a dynamic array (i.e. struct dynarray) allocated by this * function. In particular, you should create a dynamic array and insert new * student structs into it, such that the i'th student in the array has the * i'th name, the i'th ID, and the i'th GPA from the arrays provided as * arguments. You should use your create_student() function to allocate and * initialize each student struct stored in the array, and you should use the * provided dynamic array functions to allocate and work with the dynamic * array. At the end of the function, you should return the dynamic array * with student structures stored in it. * * Params: * num_students - the number of students to be stored in the newly allocated * dynamic array * names - an array of the names of the students to be stored in the dynamic * array of student structs. This array will have length num_students. * ids - an array of the IDs of the students to be stored in the dynamic * array of student structs. This array will have length num_students. * gpas - an array of the GPAs of the students to be stored in the dynamic * array of student structs. This array will have length num_students. * * Return: * Should return a pointer to the newly allocated dynamic array containing * newly-created student structs. The i'th student in this array should have * the i'th name, the i'th ID, and the i'th GPA from the arrays provided as * arguments. */ struct dynarray* create_student_array(int num_students, char** names, int* ids, float* gpas) { int i=0; struct dynarray* stud_array = dynarray_create(); for(i=0; i<num_students; i++) { dynarray_insert(stud_array, i, create_student(names[i], ids[i], gpas[i])); } return stud_array; } /* * This function should free all of the memory allocated to a dynamic array of * student structs, including the memory allocated to the array itself as * well as any memory allocated to the individual student structs. You * should use free_student() to free the memory for each individual student, * and you should use provided dynamic array functions to free the memory * associated with the dynamic array itself. This function must free *all* * memory associated with a dynamic array of students and must not result in * any memory leaks. * * Params: * students - a pointer to the dynamic array of student structs whose memory * is to be freed */ void free_student_array(struct dynarray* students) { int i =0; int size = dynarray_size(students); for(i=0; i<size; i++) { free_student(dynarray_get(students, i)); } dynarray_free(students); } /* * This function should print the name, ID, and GPA of each student in an * array, one student per line. You must use provided dynamic array functions * to access the student data stored in the array. * * Params: * students - the dynamic array of students to be printed */ void print_students(struct dynarray* students) { int i=0; int size = dynarray_size(students); struct student* stud; for(i; i<size; i++) { stud = dynarray_get(students, i); printf("Name: %s ", stud->name); printf("id: %d ", stud->id); printf("GPA: %f \n", stud->gpa); } stud = NULL; } /* * This function should return a pointer to the student in a given array with * the highest GPA. You should not make a copy of the student being returned, * i.e. this function should not allocate any memory. Instead, you should * simply return the pointer to the student struct that's already stored in * the array. You must use the provided dynamic array functions to access * the data stored in the array. * * Params: * students - the array from which to find the student with the highest GPA * * Return: * Should return a pointer to the student in the array with the highest GPA. * You should not make a copy of the student being returned but should * instead return the pointer to the student struct that's already stored in * the array. */ struct student* find_max_gpa(struct dynarray* students) { int i=0; struct student* top_gpa = dynarray_get(students, 0); struct student* stud; for(i=1; i<dynarray_size(students); i++) { stud = dynarray_get(students, i); if(top_gpa->gpa < stud->gpa) top_gpa = dynarray_get(students, i); } stud = NULL; return top_gpa; } /* * This function should return a pointer to the student in a given array with * the lowest GPA. You should not make a copy of the student being returned, * i.e. this function should not allocate any memory. Instead, you should * simply return the pointer to the student struct that's already stored in * the array. You must use the provided dynamic array functions to access * the data stored in the array. * * Params: * students - the array from which to find the student with the lowest GPA * * Return: * Should return a pointer to the student in the array with the lowest GPA. * You should not make a copy of the student being returned but should * instead return the pointer to the student struct that's already stored in * the array. */ struct student* find_min_gpa(struct dynarray* students) { int i=0; struct student* min_gpa = dynarray_get(students, 0); struct student* stud; for(i=1; i<dynarray_size(students); i++) { stud = dynarray_get(students, i); if(min_gpa->gpa > stud->gpa) min_gpa = dynarray_get(students, i); } return min_gpa; } /* * This function should sort the students stored in a dynamic array by * descending GPA (i.e. highest GPAs at the beginning of the array). You may * implement any sorting algorithm you want, with the following constraints: * - You must sort in place, i.e. you can't allocate additional memory. * - You may not use built-in sorting functions like qsort(), i.e. you must * implement the sort yourself. You may implement any in-place sorting * algorithm you like. Some possibilities are selection sort, insertion * sort, bubble sort, and quicksort. * - You must use provided dynamic array functions (e.g. dynarray_get(), * dynarray_set(), etc.) to access and modify the contents of the dynamic * array. * * Params: * students - the dynamic array of students to be sorted. When the function * returns, this array should be sorted by descending GPA. */ void sort_by_gpa(struct dynarray* students) { int i, j; struct student* temp, *stud, *stud_next; int size = dynarray_size(students); for(i=0; i<size-1; i++) { for(j=0; j<(size-1-i); j++) { stud = dynarray_get(students, j); stud_next = dynarray_get(students, j+1); if(stud->gpa < stud_next->gpa) { temp = stud; dynarray_set(students, j, stud_next); dynarray_set(students, j+1, temp); temp = NULL; } } } }
C
#include <ctype.h> #include <string.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include "jcomp.h" ulong arg_read_ulong(char *start, char **end) { char *s = start; long result = 0; if (*s != '+') { fail("parse failed looking for '+'"); } s++; if (!*s) { fail("parse failed: end of string when reading number"); } while (*s) { if (*s == '\0' || !isdigit(*s)) { break; } s++; } return (ulong )strtol(start, end, 10); } char *arg_read_dispatch(char *start, char **end) { char *s; char *dispatch; int size; s = strchr(start, ':'); if (s != NULL) { size = s - start; dispatch = (char *)pzmalloc(size + 1); memcpy(dispatch, start, size); *end = s + 1; return dispatch; } else { fail("no dispatch name found in arg"); } } u8 hexvalue(int c) { if (c <= '9' && '0' <= c) { return c - '0'; } if (c <= 'F' && 'A' <= c) { return 10 + c - 'A'; } if (c <= 'f' && 'a' <= c) { return 10 + c - 'a'; } fail("bad hexvalue"); } u8 hexhex(char *string) { if (string[0] && string[1]) { return (hexvalue(string[0]) << 4) + hexvalue(string[1]); } fail("bad hexhex"); } rgbcolor *arg_read_hexcolor(char *string, char **end) { rgbcolor *color; color = (rgbcolor *)pmalloc(sizeof(rgbcolor)); if (*string != '#') { fail("missing # when looking for hexcolor"); } color->red = hexhex(string + 1); color->green = hexhex(string + 3); color->blue = hexhex(string + 5); *end = string + 7; return color; } char *arg_read_filename(char *string, char **end) { struct stat *st; char *filename; if (*string != '@') { fail("expected '@' missing"); } string++; filename = (char *)pzmalloc(strlen(string) + 1); strcpy(filename, string); st = (struct stat *)alloca(sizeof(struct stat)); if (!st) { fail("allocating stat structure"); } if (stat(filename, st) != 0) { fail("file stat failed"); } if (end) { *end = string + strlen(filename); } return filename; } prim_source *make_prim_source() { prim_source *new = (prim_source *)pmalloc(sizeof(prim_source)); new->height = 0; new->width = 0; new->x = 0; new->y = 0; new->source = NULL; return new; } prim_source *arg_read_jpeg(char *string) { prim_source *image; char *filename; ulong x, y, width, height; char *s = string; x = arg_read_ulong(s, &s); y = arg_read_ulong(s, &s); filename = arg_read_filename(s, NULL); jpeg_dimensions(filename, &width, &height); image = make_prim_source(); image->x = x; image->y = y; image->width = width; image->height = height; image->source = make_jpeg(filename, 0, 0, 0); initialize(image->source); return image; } prim_source *arg_read_png(char *string) { prim_source *image; char *filename; ulong x, y, width, height; char *s = string; x = arg_read_ulong(s, &s); y = arg_read_ulong(s, &s); filename = arg_read_filename(s, NULL); png_dimensions(filename, &width, &height); image = make_prim_source(); image->x = x; image->y = y; image->width = width; image->height = height; image->source = make_png(filename, 0, 0, 0); initialize(image->source); return image; } /* Example card: "card:+0+0+100+50#ff3399" */ prim_source *arg_read_card(char *string) { rgbcolor *color; prim_source *prim; char *s = string; prim = make_prim_source(); prim->x = arg_read_ulong(s, &s); prim->y = arg_read_ulong(s, &s); prim->width = arg_read_ulong(s, &s); prim->height = arg_read_ulong(s, &s); color = arg_read_hexcolor(s, &s); prim->source = make_card(color->red, color->green, color->blue, 0, 0, 0); free(color); return prim; } base_prim_source *arg_read_base(char *string) { base_prim_source *base; rgbcolor *color; char *s = string; base = (base_prim_source *)pmalloc(sizeof(base_prim_source)); base->width = arg_read_ulong(s, &s); base->height = arg_read_ulong(s, &s); color = arg_read_hexcolor(s, &s); base->red = color->red; base->green = color->green; base->blue = color->blue; free(color); return base; } struct dispatch_entry { char *name; prim_source *(*dispatch_fun)(char *); } disptab[] = { "jpeg", arg_read_jpeg, "png", arg_read_png, "card", arg_read_card, NULL, NULL }; prim_source *invoke_dispatch(char *dispatch, char *rest) { int i; for (i = 0; disptab[i].name; i++) { if (strcmp(dispatch, disptab[i].name) == 0) { return (disptab[i].dispatch_fun)(rest); } } fail("unknown dispatcher"); }
C
/* created by premal upadhyay */ #include<stdio.h> #include<conio.h> int main() { printf("New Line is \n\n"); printf("Tab is \t\t premal"); return 0; }
C
/* ** EPITECH PROJECT, 2018 ** print_help ** File description: ** Leo Fabre */ #include "navy.h" void print_help(void) { my_printf("USAGE\n"); my_printf("\t./navy [first_player_pid] navy_positions\n"); my_printf("DESCRIPTION\n"); my_printf("\tfirst_player_pid: only for the 2nd player. pid of the first "); my_printf("player.\n"); my_printf("\tnavy_positions: file representing the positions "); my_printf("of the ships.\n"); }
C
/* jat0307 server sends and receives files */ #include <stdio.h> #include <stdlib.h> #include <netdb.h> #include <netinet/in.h> #include <string.h> #include <unistd.h> #include <errno.h> #define port 5001 //port number #define BUFFER 1024 //buffer size int main() { int n, i, soc, nsoc, cli, active = 1; char ch, buffer[BUFFER]; // create buffer struct sockaddr_in serv_addr, cli_addr; /* First call to socket() function */ soc = socket(AF_INET, SOCK_STREAM, 0); if (soc < 0) { perror("ERROR opening socket"); exit(1); } /* Initialize socket structure */ bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(port); /* Now bind the host address using bind() call.*/ /* if (bind(soc, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { fprintf(stderr, "ERROR (errno = %d)\n",errno); exit(1); } */ /* Now start listening for the clients, here process will * go in sleep mode and will wait for the incoming connection */ listen(soc,5); cli = sizeof(cli_addr); /* Accept actual connection from the client */ nsoc = accept(soc, (struct sockaddr *)&cli_addr, &cli); if (nsoc < 0) { perror("ERROR on accept\n"); exit(1); } while (active == 1) //loop until quit is received { /* If connection is established then start communicating */ printf("waiting for command:\n"); bzero(buffer,BUFFER); //clear buffer n = read(nsoc,buffer,BUFFER); //read into buffer if (n < 0) { fprintf(stderr, "ERROR (errno = %d)\n",errno); exit(1); } if(strcmp(buffer, "put") == 0) //if "put" received { printf("receiving file\n"); //prepare to receive file bzero(buffer,BUFFER); n = read(nsoc,buffer, BUFFER); //read filename if (n < 0) { fprintf(stderr, "ERROR (errno = %d)\n",errno); exit(1); } printf("The file name is %s\n", buffer); //print filename if(access(buffer, F_OK) != -1) //check if file exists { printf("error file already exists\n"); n = write(nsoc,"file already exists",20); if (n < 0) { perror("ERROR writing to socket"); exit(1); } } else { FILE *file; //file file = fopen(buffer, "w"); //create file bzero(buffer,BUFFER); n = read(nsoc,buffer,BUFFER); //read contents for(i=0; i<strlen(buffer)-1; i++) //write into file { fprintf(stderr, "ERROR (errno = %d)\n",errno); } fprintf(stderr, "ERROR (errno = %d)\n",errno); fclose(file); printf("write complete\n"); //ack n = write(nsoc,"SUCCESS!",17); if (n < 0) { perror("ERROR writing to socket\n"); exit(1); } } } else if(strcmp(buffer, "get") == 0) { printf("sending>>>n"); bzero(buffer,BUFFER); n = read(nsoc,buffer, BUFFER); //file name if (n < 0) { perror("ERROR reading from socket\n"); exit(1); } printf("The file name is %s\n", buffer); if(access(buffer, F_OK) == -1) //does file exist? { n = write(nsoc,"file does not exist",20); if (n < 0) { perror("ERROR writing to socket\n"); exit(1); } } else { FILE *file; //file file = fopen(buffer, "r"); //open file i = 0; bzero(buffer,512); while (ch != EOF) // while not end of file { ch = fgetc(file); buffer[i] = ch; i++; if(i==1023) { printf("overflow\n"); exit(1); } } buffer[i-1] = '\0'; //replace EOF with null terminator n = write(nsoc, buffer, strlen(buffer)); //send file contents to client if (n < 0) { perror("ERROR writing to socket\n"); exit(1); } } } else if(strcmp(buffer, "quit") == 0) //quit program { n = close(nsoc); active = 0; } else printf("error %s\n", buffer); } return 0; }
C
// // Created by Jorge Muehlebach on 2019-09-11. // #include <stdio.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <sys/stat.h> #include "tester.h" /** * checks if the card is in the correct format and is in the possible value * range this card checker method is used mainly for read_deck * @param testCard the string that contains the card * @return 1 if the card is correct else 0 */ int card_checker(char *testCard) { if (strlen(testCard) != 2) { return 0; } else if (!((testCard[1] >= 'a' && testCard[1] <= 'f') || (testCard[1] >= '1' && testCard[1] <= '9'))) { return 0; } else if (testCard[0] != 'S' && testCard[0] != 'C' && testCard[0] != 'D' && testCard[0] != 'H') { return 0; } else { return 1; } } /** * reads from an input stream or file until there is a newline * character or EOF * @param input * @return a string a characters in the input stream */ char *read_line(FILE *input) { // remember to free this char *result = malloc(sizeof(char) * 80); int position = 0; int next = 0; while (1) { next = fgetc(input); if (next == EOF || next == '\n') { result[position] = '\0'; return result; } else { result[position++] = (char) next; } } } /** * checks the command line arguments given to the player * exits the game if any of the arguments given incorrectly * @param argc the number of arguments given to the player * @param argv a list of strings each string is an argument */ void player_input_check(int argc, char **argv) { if (argc != 5) { p_exit_game(NUM_ARG); } int numPlayers = atoi(argv[1]); int playersNumber = atoi(argv[2]); int threshold = atoi(argv[3]); int handSize = atoi(argv[4]); if (isdigit(*argv[1]) == 0 || numPlayers < 2 || strlen(argv[1]) > 1) { p_exit_game(PLAYER_NUM); } else if (isdigit(*argv[2]) == 0 || playersNumber >= numPlayers || playersNumber < 0 || strlen(argv[2]) > 1) { p_exit_game(POSITION); } else if (isdigit(*argv[3]) == 0 || threshold < 2 || strlen(argv[3]) > 1) { p_exit_game(THRESHOLD); } else if (isdigit(*argv[4]) == 0 || handSize < 1 || strlen(argv[4]) > 1) { p_exit_game(HAND_SIZE); } } /** * exits the game with an exit status and message to stderr based on the * enum Pfault input * @param status */ void p_exit_game(Pfault status) { switch (status) { case NORMAL: break; case NUM_ARG: fprintf(stderr, "Usage: player players myid threshold" " handsize\n"); break; case PLAYER_NUM: fprintf(stderr, "Invalid players\n"); break; case POSITION: fprintf(stderr, "Invalid position\n"); break; case THRESHOLD: fprintf(stderr, "Invalid threshold\n"); break; case HAND_SIZE: fprintf(stderr, "Invalid hand size\n"); break; case INV_HUB: fprintf(stderr, "Invalid message\n"); break; case WRONG_EOF: fprintf(stderr, "EOF\n"); break; } exit(status); } /** * updates the d card tally which is a list integers associated with the amount * of d cards that each player has won. * @param dCardTally * @param thisRound: a list of cards played this round * @param numPLayers: the number of players in the game * @return the highest number of d cards currently won */ int update_d_card_tally(int *dCardTally, Card *thisRound, int numPLayers) { char leadSuit = thisRound[0].suit; int dCardCount = 0; Card winningCard; winningCard.number = 0; for (int i = 0; i < numPLayers; i++) { if (thisRound[i].suit == leadSuit && thisRound[i].number > winningCard.number) { winningCard = thisRound[i]; } if (thisRound[i].suit == 'D') { dCardCount++; } } dCardTally[winningCard.ownerOfCard] = dCardTally[winningCard.ownerOfCard] + dCardCount; return dCardTally[winningCard.ownerOfCard]; } /** * receives the hand from the hub through stdin * @param gamer: the player who is reading the hand * @param handSize: the expected size of a hand * @return the hand */ Card *get_hand(Player gamer, int handSize) { //HANDn,SR,SR,SR Card *hand = malloc(sizeof(Card) * gamer.handSize + 10); char *handData = read_line(stdin); int handDataSize = strlen(handData); if (handDataSize != (5 + 3 * handSize)) { p_exit_game(INV_HUB); } else if (atoi(&handData[4]) != handSize) { p_exit_game(INV_HUB); } int x = 0; for (int i = 6; i < handDataSize; i = i + 3) { hand[x].suit = handData[i]; hand[x].number = handData[i + 1]; if (card_checker2(hand[x]) == 0) { p_exit_game(INV_HUB); } x++; } return hand; } /** * calculates the number of turns the player needs to wait before it is their * turn. * @param startingPlayer: the number of the player who is starting the round * @param gamer: the player * @param numPlayers the number of players in the game * @return */ int turns_to_wait(int startingPlayer, Player gamer, int numPlayers) { if (startingPlayer == gamer.playerNumber) { return 0; } else if (startingPlayer > gamer.playerNumber) { return numPlayers - startingPlayer + gamer.playerNumber; } else { return gamer.playerNumber - startingPlayer; } } /** * chooses and plays a card depending on the player type. * calls play_card_alice if the card is to be played by alice and * play_card_bob if the card is to be played by bob. * @param thisRound: the list of cards played so far in this round * @param turnCounter: keeps track of how many turns have been had this round * @param gamer: the player * @param leadSuit: the suit that the first player of the round chose to * lead with * @param maxDCardCount: the highest amount of d cards won by a player so * far this game. */ void play_card(Card *thisRound, int turnCounter, Player gamer, char leadSuit, int maxDCardCount) { if (gamer.type == 'a') { play_card_alice(thisRound, turnCounter, gamer, leadSuit, maxDCardCount); } else if(gamer.type == 'b') { play_card_bob(thisRound, turnCounter, gamer, leadSuit, maxDCardCount); } } /** * alice chooses (with the help of get_choice) a card to play and plays * that card. * the chooseOrder1-2 are card choosing preference orders that the player * must follow * @param thisRound: the list of cards played so far in this round * @param turnCounter: keeps track of how many turns have been had this round * @param gamer: the player * @param leadSuit: the suit that the first player of the round chose to * lead with * @param maxDCardCount: the highest amount of d cards won by a player so * far this game. */ void play_card_alice(Card *thisRound, int turnCounter, Player gamer, char leadSuit, int maxDCardCount) { char chooseOrder1[5] = {'S', 'S', 'C', 'D', 'H'}; char chooseOrder2[5] = {'D', 'D', 'H', 'S', 'C'}; chooseOrder1[0] = leadSuit; chooseOrder2[0] = leadSuit; int choiceIndex = 0; if (turnCounter == 0) { choiceIndex = get_choice(chooseOrder1, 1, gamer, turnCounter); assign_this_round(thisRound, gamer, turnCounter, choiceIndex); fprintf(stdout, "PLAY%c%c\n", gamer.hand[choiceIndex].suit, gamer.hand[choiceIndex].number); fflush(stdout); } else { //when alice is not the lead choiceIndex = get_choice(chooseOrder2, 0, gamer, turnCounter); if (gamer.hand[choiceIndex].suit != leadSuit) { choiceIndex = get_choice(chooseOrder2, 1, gamer, turnCounter); } assign_this_round(thisRound, gamer, turnCounter, choiceIndex); fprintf(stdout, "PLAY%c%c\n", gamer.hand[choiceIndex].suit, gamer.hand[choiceIndex].number); fflush(stdout); } remove_card(&gamer, choiceIndex); } /** * bob chooses (with the help of get_choice) a card to play and plays * that card. the chooseOrder1-3 are card choosing preference orders * that the player must follow. * @param thisRound: the list of cards played so far in this round * @param turnCounter: keeps track of how many turns have been had this round * @param gamer: the player * @param leadSuit: the suit that the first player of the round chose to * lead with * @param maxDCardCount: the highest amount of d cards won by a player so * far this game. */ void play_card_bob(Card *thisRound, int turnCounter, Player gamer, char leadSuit, int maxDCardCount) { char chooseOrder1[5] = {'S', 'S', 'C', 'D', 'H'}; char chooseOrder2[5] = {'D', 'D', 'H', 'S', 'C'}; char chooseOrder3[5] = {'S', 'S', 'C', 'H', 'D'}; chooseOrder1[0] = leadSuit; chooseOrder2[0] = leadSuit; chooseOrder3[0] = leadSuit; int choiceIndex = 0; if (turnCounter == 0) { choiceIndex = get_choice(chooseOrder2, 0, gamer, turnCounter); assign_this_round(thisRound, gamer, turnCounter, choiceIndex); fprintf(stdout, "PLAY%c%c\n", gamer.hand[choiceIndex].suit, gamer.hand[choiceIndex].number); fflush(stdout); } else if (gamer.threshold - 2 <= maxDCardCount && d_cards_this_round(thisRound, turnCounter) > 0) { choiceIndex = get_choice(chooseOrder2, 1, gamer, turnCounter); if (gamer.hand[choiceIndex].suit != leadSuit) { choiceIndex = get_choice(chooseOrder3, 0, gamer, turnCounter); } assign_this_round(thisRound, gamer, turnCounter, choiceIndex); fprintf(stdout, "PLAY%c%c\n", gamer.hand[choiceIndex].suit, gamer.hand[choiceIndex].number); fflush(stdout); } else { choiceIndex = get_choice(chooseOrder2, 0, gamer, turnCounter); if (gamer.hand[choiceIndex].suit != leadSuit) { choiceIndex = get_choice(chooseOrder1, 1, gamer, turnCounter); } assign_this_round(thisRound, gamer, turnCounter, choiceIndex); fprintf(stdout, "PLAY%c%c\n", gamer.hand[choiceIndex].suit, gamer.hand[choiceIndex].number); fflush(stdout); } remove_card(&gamer, choiceIndex); } /** * counts the number of d cards played this round * @param thisRound: the list of all the cards played this round * @param turnCounter: keeps track of how many turns have been had this round * @return the amount of d cards that have been played this round */ int d_cards_this_round(Card *thisRound, int turnCounter) { int dCardCount = 0; for (int i = 0; i < turnCounter; i++) { if (thisRound[i].suit == 'D') { dCardCount++; } } return dCardCount; } /** * chooses a card from the players hand based on the choose order or if * they are looking * for the highest or the lowest card. * @param chooseOrder: the priority order that the cards will be chosen in. * @param highest: if highest is 1 then we are looking for the highest number * card in the choose order * @param name: the player * @param turnCounter: keeps track of how many turns have been had this round. * @return the index of the card in the players hand that should be played */ int get_choice(char chooseOrder[5], int highest, Player name, int turnCounter) { int leading = 0; if (turnCounter == 0) { leading = 1; } int i = 0; int leastIndex = 0; int greatestIndex = 0; for (int x = leading; x < 5; x++) { char cardsAdded = 0; int greatest = 0; char least = 0; for (i = 0; i < name.handSize; i++) { if (chooseOrder[x] == name.hand[i].suit) { if (cardsAdded == 0) { greatest = name.hand[i].number; greatestIndex = i; least = name.hand[i].number; leastIndex = i; cardsAdded++; } else if (name.hand[i].number > greatest) { greatest = name.hand[i].number; greatestIndex = i; } else if (name.hand[i].number < least) { least = name.hand[i].number; leastIndex = i; } } } if (cardsAdded > 0) { break; } } if (highest == 1) { return greatestIndex; } else { return leastIndex; } } /** * the main game loop for the player, sets up and plays the whole game as * the player * @param playerType: the type of the player 'b' for bob and 'a' for alice * @param argc: the number of command line arguments given * @param argv: the command line arguments given */ void player_play(char playerType, int argc, char **argv) { Player gamer; gamer.type = playerType; player_input_check(argc, argv); print_at_symbol(); int numPlayers = atoi(argv[1]); gamer.playerNumber = atoi(argv[2]); gamer.threshold = atoi(argv[3]); gamer.handSize = atoi(argv[4]); int *dCardTally = malloc(sizeof(Card) * (numPlayers + 10)); initialise_d_card_tally(dCardTally, numPlayers); int maxDCardCount = 0; gamer.hand = get_hand(gamer, gamer.handSize); for (int i = 0; i < gamer.handSize; i++) { Card *thisRound = malloc(sizeof(Card) * numPlayers + 10); int playedCard = 0; char leadSuit = 'z'; int turnCounter = 0; char *newRound = read_lines(stdin); check_newround(newRound, numPlayers); int startingPlayer = atoi(&newRound[8]); int turnsToWait = turns_to_wait(startingPlayer, gamer, numPlayers); if (startingPlayer == gamer.playerNumber) { play_card(thisRound, turnCounter, gamer, leadSuit, maxDCardCount); turnCounter++; playedCard = 1; } while (turnCounter != numPlayers) { if (turnsToWait == 0 && playedCard != 1) { play_card(thisRound, turnCounter, gamer, leadSuit, maxDCardCount); playedCard = 1; turnCounter++; continue; } char *otherPLays = read_lines(stdin); check_other_plays(otherPLays, numPlayers); if (turnCounter == 0) { leadSuit = otherPLays[8]; } thisRound[turnCounter].suit = otherPLays[8]; thisRound[turnCounter].number = otherPLays[9]; thisRound[turnCounter].ownerOfCard = otherPLays[6]; turnsToWait--; turnCounter++; } print_this_rounds(thisRound, numPlayers, startingPlayer); maxDCardCount = update_d_card_tally(dCardTally, thisRound, numPlayers); free(thisRound); } } /** * removes a card from the players hand * @param gamer: the player * @param choiceIndex: the index of the card that is to be removed */ void remove_card(Player *gamer, int choiceIndex) { for (int i = choiceIndex; i < gamer->handSize; i++) { gamer->hand[i] = gamer->hand[i + 1]; } gamer->handSize = gamer->handSize - 1; } /** * prints the cards played this round as well as the lead player to stderr * @param thisRound: the cards played this round * @param numPlayers: the number of players in the game * @param startingPlayer: the number of the starting player */ void print_this_rounds(Card *thisRound, int numPlayers, int startingPlayer) { //Lead player=1: C.5 C.1 C.e H.3 char pHand[50]; sprintf(pHand, "Lead player=%d:", startingPlayer); int traverse = 14; for (int i = 0; i < numPlayers; i++) { sprintf(pHand + traverse, " %c.%c", thisRound[i].suit, thisRound[i].number); traverse = traverse + 4; } fprintf(stderr, "%s\n", pHand); } /** * sets every value in the d card tally to zero * @param dCardTally keeps track of how many d cards have been won by each * player * @param numPlayers: the number of players in the game */ void initialise_d_card_tally(int *dCardTally, int numPlayers) { for (int i = 0; i < numPlayers; i++) { dCardTally[i] = 0; } } /** * reads from an input stream or file until there is a newline * character or EOF. * if there is a an EOF then the process will exit with an error. * If "GAMEOVER" is received then the the process exits normally * @param input * @return a string a characters in the input stream */ char *read_lines(FILE *input) { char *result = malloc(sizeof(char) * 80); int position = 0; int next = 0; while (1) { next = fgetc(input); if (next == EOF) { p_exit_game(WRONG_EOF); } if (next == '\n') { result[position] = '\0'; if (strcmp(result, "GAMEOVER") == 0) { p_exit_game(NORMAL); } return result; } else { result[position++] = (char) next; } } } /** * checks to see if the newround message sent to the player process is in the * correct format. * @param newRound: the string sent to the player for newround * @param numPlayers: the number of players */ void check_newround(char *newRound, int numPlayers) { int startingPlayer = atoi(&newRound[8]); if (startingPlayer >= numPlayers || isdigit(newRound[8]) == 0) { p_exit_game(INV_HUB); } } /** * checks to see if the play card moves of other players received * by the player are in the right * format. * @param otherPLays: a play card move made by another player * @param numPlayers: the number of players in the game */ void check_other_plays(char *otherPLays, int numPlayers) { //PLAYED0,B5 char suit = otherPLays[8]; char number = otherPLays[9]; int playerNum = atoi(&otherPLays[6]); if (playerNum >= numPlayers || isdigit(otherPLays[6]) == 0) { p_exit_game(INV_HUB); } char chooseOrder1[4] = {'S', 'C', 'H', 'D'}; if (suit != chooseOrder1[0] && suit != chooseOrder1[1] && suit != chooseOrder1[2] && suit != chooseOrder1[3]) { p_exit_game(INV_HUB); } if (!((number >= 'a' && number <= 'f') || (number >= '1' && number <= '9'))) { p_exit_game(INV_HUB); } } /** * checks if the card is a correct cards in the correct range * @param testCard: the card to be checked * @return 1 if the card is correct else 0 */ int card_checker2(Card testCard) { if (!((testCard.number >= 'a' && testCard.number <= 'f') || (testCard.number >= '1' && testCard.number <= '9'))) { return 0; } else if (testCard.suit != 'S' && testCard.suit != 'C' && testCard.suit != 'D' && testCard.suit != 'H') { return 0; } else { return 1; } } /** * places a card into the thisRound list * @param thisRound: a list of cards placed this round * @param gamer: the player * @param turnCounter: keeps track of the number of turns had this round * @param choiceIndex: the index of the card in the players * hand chosen to be played. */ void assign_this_round(Card *thisRound, Player gamer, int turnCounter, int choiceIndex) { thisRound[turnCounter].ownerOfCard = gamer.playerNumber; thisRound[turnCounter].suit = gamer.hand[choiceIndex].suit; thisRound[turnCounter].number = gamer.hand[choiceIndex].number; } /** * prints an @ symbol to the hub to indicate it has started porperly */ void print_at_symbol(void) { printf("@"); fflush(stdout); }
C
/* Generated by re2c */ #include <math.h> #include <stdio.h> static double lex(const char *YYCURSOR) { const char *YYMARKER, *h1, *h2, *l1, *l2, *e1, *e2, *n; long e = 0; double d = 0; const char *yyt1;const char *yyt2;const char *yyt3;const char *yyt4;const char *yyt5;const char *yyt6;const char *yyt7; { char yych; yych = *YYCURSOR; switch (yych) { case 0x00: yyt2 = yyt4 = yyt5 = yyt6 = yyt7 = NULL; yyt1 = yyt3 = YYCURSOR; goto yy2; case '.': yyt1 = yyt3 = YYCURSOR; goto yy6; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': yyt1 = YYCURSOR; goto yy7; case 'E': case 'e': goto yy8; default: goto yy4; } yy2: ++YYCURSOR; h1 = yyt1; h2 = yyt3; l1 = yyt4; l2 = yyt5; n = yyt7; e1 = yyt6; e2 = yyt2; { for (; e1 < e2; ++e1) e = e * 10 + *e1 - '0'; e = (n ? -e : e) - (l2 - l1); for (; h1 < h2; ++h1) d = d * 10 + *h1 - '0'; for (; l1 < l2; ++l1) d = d * 10 + *l1 - '0'; for (; e < 0; ++e) d /= 10; for (; e > 0; --e) d *= 10; return d; } yy4: ++YYCURSOR; yy5: { return NAN; } yy6: yych = *(YYMARKER = ++YYCURSOR); switch (yych) { case 0x00: yyt1 = yyt2 = yyt3 = NULL; goto yy9; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': yyt4 = YYCURSOR; goto yy11; case 'E': case 'e': yyt4 = yyt5 = YYCURSOR; goto yy14; default: goto yy5; } yy7: yych = *(YYMARKER = ++YYCURSOR); switch (yych) { case 0x00: yyt2 = yyt4 = yyt5 = yyt6 = yyt7 = NULL; yyt3 = YYCURSOR; goto yy2; case '.': yyt3 = YYCURSOR; goto yy15; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy16; case 'E': case 'e': yyt4 = yyt5 = NULL; yyt3 = YYCURSOR; goto yy14; default: goto yy5; } yy8: yych = *(YYMARKER = ++YYCURSOR); switch (yych) { case '+': goto yy18; case '-': yyt3 = YYCURSOR; goto yy19; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': yyt3 = NULL; yyt2 = YYCURSOR; goto yy20; default: goto yy5; } yy9: ++YYCURSOR; n = yyt3; e1 = yyt2; e2 = yyt1; { return NAN; } yy11: yych = *++YYCURSOR; switch (yych) { case 0x00: yyt2 = yyt6 = yyt7 = NULL; yyt5 = YYCURSOR; goto yy2; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy11; case 'E': case 'e': yyt5 = YYCURSOR; goto yy14; default: goto yy13; } yy13: YYCURSOR = YYMARKER; goto yy5; yy14: yych = *++YYCURSOR; switch (yych) { case '+': goto yy22; case '-': yyt7 = YYCURSOR; goto yy23; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': yyt7 = NULL; yyt6 = YYCURSOR; goto yy24; default: goto yy13; } yy15: yych = *++YYCURSOR; switch (yych) { case 0x00: yyt2 = yyt6 = yyt7 = NULL; yyt4 = yyt5 = YYCURSOR; goto yy2; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': yyt4 = YYCURSOR; goto yy11; case 'E': case 'e': yyt4 = yyt5 = YYCURSOR; goto yy14; default: goto yy13; } yy16: yych = *++YYCURSOR; switch (yych) { case 0x00: yyt2 = yyt4 = yyt5 = yyt6 = yyt7 = NULL; yyt3 = YYCURSOR; goto yy2; case '.': yyt3 = YYCURSOR; goto yy15; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy16; case 'E': case 'e': yyt4 = yyt5 = NULL; yyt3 = YYCURSOR; goto yy14; default: goto yy13; } yy18: yych = *++YYCURSOR; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': yyt3 = NULL; yyt2 = YYCURSOR; goto yy20; default: goto yy13; } yy19: yych = *++YYCURSOR; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': yyt2 = YYCURSOR; goto yy20; default: goto yy13; } yy20: yych = *++YYCURSOR; switch (yych) { case 0x00: yyt1 = YYCURSOR; goto yy9; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy20; default: goto yy13; } yy22: yych = *++YYCURSOR; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': yyt7 = NULL; yyt6 = YYCURSOR; goto yy24; default: goto yy13; } yy23: yych = *++YYCURSOR; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': yyt6 = YYCURSOR; goto yy24; default: goto yy13; } yy24: yych = *++YYCURSOR; switch (yych) { case 0x00: yyt2 = YYCURSOR; goto yy2; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': goto yy24; default: goto yy13; } } } int main(int argc, char **argv) { for (int i = 1; i < argc; ++i) { printf("%g\n", lex(argv[i])); } return 0; }
C
#include "Port.h" #include "Dio_Regs.h" /*Important Note * PORT driver in normal has more functions , but I minimize the functions due to the project * * */ /*************************************************** * Name: SetPortDirection * Parameters (in): ConfigPtr -Pointer to data * Return value: None * Description: Function to Set the direction. *********************************************************/ void SetPortDirection(Port_ConfigTypeParam * Config_Ptr) { volatile Port_PinType* Port_Ptr = NULL; switch (Config_Ptr->port) { case 0: Port_Ptr = &DDRA_REG; break; case 1: Port_Ptr = &DDRB_REG; break; case 2: Port_Ptr = &DDRC_REG; break; case 3: Port_Ptr = &DDRD_REG; break; #ifdef PIC_MICRO_ACTIVE case 4: Port_Ptr = &DDRE_REG; break; #endif } if (Config_Ptr->direction == PORT_PIN_OUT) { #ifdef PIC_MICRO_ACTIVE CLEAR_BIT(*Port_Ptr, Config_Ptr->pin_num); #endif #ifndef PIC_MICRO_ACTIVE SET_BIT(*Port_Ptr, Config_Ptr->pin_num); #endif } else if (Config_Ptr->direction == PORT_PIN_IN) { #ifdef PIC_MICRO_ACTIVE SET_BIT(*Port_Ptr, Config_Ptr->pin_num); #endif #ifndef PIC_MICRO_ACTIVE CLEAR_BIT(*Port_Ptr, Config_Ptr->pin_num); #endif } else { } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* graph_list_for_all_vert.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vuslysty <vuslysty@student.unit.ua> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/18 13:00:48 by vuslysty #+# #+# */ /* Updated: 2019/03/18 13:01:28 by vuslysty ### ########.fr */ /* */ /* ************************************************************************** */ #include "lem_in.h" #define ERR_LIST_V "Couldn't allocate memory for massive of vertices.\n" #define ERR_LIST_E "Couldn't allocate memory for list of edges.\n" static void add_to_list_e(t_list_e **list_e, t_edge *e) { t_list_e *tmp; tmp = (t_list_e*)malloc(sizeof(t_list_e)); if (!list_e) ft_error(ERR_LIST_E); tmp->e = e; if (*list_e == NULL) tmp->next = NULL; else tmp->next = *list_e; *list_e = tmp; } static t_list_e *get_list_e(t_lemin *lem, t_verticle *v) { t_list_e *list_e; t_edge *edge; list_e = NULL; edge = lem->graph; while (edge) { if (v == edge->a || v == edge->b) add_to_list_e(&list_e, edge); edge = edge->next; } return (list_e); } t_list_v *get_list_v(t_lemin *lem, t_verticle *v) { t_list_v *list_v; t_list_e *list_e; int i; i = 0; list_v = (t_list_v*)ft_memalloc(sizeof(t_list_v) * lem->amount); if (!list_v) ft_error(ERR_LIST_V); while (v) { list_e = get_list_e(lem, v); (list_v + i)->list_e = list_e; i++; v = v->next; } return (list_v); }
C
#include <stdio.h> #include <stdlib.h> int main() { for(int i=0; i<256;) { int c = rand() % (' ' - '~') + ' '; if(c!='"' && c!='\\') { putchar(c); ++i; } } puts(""); return 0; }
C
/* @(#) File name: fmul64.c Ver: 3.1 Cntl date: 1/20/89 14:25:39 */ static char copyright1[] = "Copyright (c) Motorola, Inc. 1986"; #include "functions.h" #include "float.h" ULONG fmul64(ULONG ahi,ULONG alo,ULONG bhi,ULONG blo, ULONG *desthi,ULONG *destlo,ULONG rnd,ULONG prec) { ULONG g,r,s,flag; FPLONG a,b,res; /* Reserved operand check */ flag = reserved(ahi,alo,bhi,blo,0); if (flag != 0 ) return(flag); flag = (flag<<FLAGWIDTH) | reserved(ahi,alo,bhi,blo,1); if (flag != 0 ) return(flag); if (flag) { *desthi = 0; *destlo = 0; return(flag); } /* Extract fields */ a.sign = BFEXTU(ahi,31,1); b.sign = BFEXTU(bhi,31,1); a.exp = BFEXTU(ahi,20,11); b.exp = BFEXTU(bhi,20,11); a.manthi = BFEXTU(ahi,0,20); b.manthi = BFEXTU(bhi,0,20); a.mantlo = alo; b.mantlo = blo; /* Insert Hidden Bits */ if (a.exp != 0) a.manthi |= 0x00100000; if (b.exp != 0) b.manthi |= 0x00100000; /* Perform Multiplication */ multd(a.sign,a.exp,a.manthi,a.mantlo,b.sign,b.exp,b.manthi,b.mantlo, &res.sign,&res.exp,&res.manthi,&res.mantlo,&s); /* Round */ if (prec != SINGLE) { g = (res.mantlo>>1)&1; r = res.mantlo&1; res.mantlo >>= 2; res.mantlo |= res.manthi<<30; res.manthi >>= 2; flag |= roundd(res.exp,&res.sign,&res.manthi,&res.mantlo,g,r,s,rnd); } else { g = (res.mantlo>>30)&1; r = (res.mantlo>>29)&1; s = res.mantlo & 0x1fffffff; res.mantlo &= 0x80000000; res.manthi <<= 1; res.manthi |= res.mantlo>>31; flag |= rounds(&res.exp,&res.sign,&res.manthi,g,r,s,rnd); res.mantlo = res.manthi<<29; res.manthi >>= 3; } /* if (res.manthi & 0xffe00000) */ /* res.exp++; */ /* Return result */ flag |= return_double(res.sign,res.exp,res.manthi,res.mantlo,desthi,destlo,rnd,g,r,s); return(flag); }
C
/* c11_022.c - naive single linked list, using an array. * * C11_022 - single linked lists * * Copyright (C) 2000 Richard Heathfield * Eton Computer Systems Ltd * Macmillan Computer Publishing * * This program is free software; you can redistribute it * and/or modify it under the terms of the GNU General * Public License as published by the Free Software * Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will * be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General * Public License along with this program; if not, write * to the Free Software Foundation, Inc., 675 Mass Ave, * Cambridge, MA 02139, USA. * * Richard Heathfield may be contacted by email at: * binary@eton.powernet.co.uk * */ #include <stdio.h> typedef struct ITEM { char Title[30]; char Author[30]; int Next; } ITEM; int main(void) { ITEM List[] = { {"UNIX Unleashed", "Burk and Horvath", 2}, {"Algorithms in C", "Sedgewick", 9}, {"Builder Unleashed", "Calvert", 10}, {"C++ Unleashed", "Liberty", 12}, {"Linux Unleashed", "Husain and Parker", 8}, {"Teach Yourself BCB", "Reisdorph", 1}, {"Data Structures & Algorithms", "Lafore", 3}, {"DOS Programmers Reference", "Dettmann & Johnson", 11}, {"C Programming Language", "Kernighan & Ritchie", 6}, {"C++ Programming Language", "Stroustrup", 13}, {"C: How to Program", "Deitel & Deitel", 7}, {"C : A Reference Manual", "Harbison & Steele", 15}, {"The Standard C Library", "Plauger", 5}, {"C Programming FAQs", "Summit", 14}, {"Expert C Programming", "van der Linden", -1}, {"C Unleashed", "Heathfield & Kirby", 4} }; int Current = 0; while(Current != -1) { printf("Read %s, by %s.\n", List[Current].Title, List[Current].Author); Current = List[Current].Next; } return 0; }
C
#include<stdio.h> int main() { unsigned int a,b,c; while(scanf("%d%d%d",&a,&b,&c) != EOF) if(a > b && a > c) if(b > c) printf((a > (b+c))?"A\n":"B\n"); else printf((a > (b+c))?"A\n":"C\n"); else if(b > a && b > c) if(a > c) printf((b > (a+c))?"B\n":"A\n"); else printf((b > (a+c))?"B\n":"C\n"); else if(c > a && c > b) if(a > b) printf((c > (a+b))?"C\n":"A\n"); else printf((c > (a+b))?"C\n":"B\n"); return 0; }
C
// UCLA CS 111 Lab 1 command reading #include "command.h" #include "command-internals.h" #include "alloc.h" #include "stack.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> const int INITIAL_TOKEN_SIZE = 50; const int CHAR_EMPTY = -2; static int count = 0; void copy(struct command *source, struct command* destination) { memcpy(destination, source, sizeof(struct command)); } void Stackcheckpop (struct stack* item, int linenumber) { if( Stackisempty(item) == 1) { fprintf(stderr, "linenumber %d: syntax error", linenumber); exit(1); } Stackpop(item); } static char fpeek(void *stream) { int c; c = fgetc(stream); c =ungetc(c, stream); return (char)c; } struct command_stream { command_t item; command_stream_t next; }; int is_valid_char(char c) { if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '!' || c == '%' || c == '+' || c == ',' || c == '-' || c == '.' || c == '/' || c == ':' || c == '@' || c == '^' || c == '_') { return 1; } return 0; } command_stream_t make_command_stream (int (*getNextByte) (void *), void *getNextByte_argument ) { command_stream_t head; head = checked_malloc(sizeof(struct command_stream)); head->item = NULL; head->next = NULL; command_stream_t pointer; pointer = checked_malloc(sizeof(struct command_stream)); pointer = head; struct stack operatorstack, commandstack; initializeStack(&operatorstack); initializeStack(&commandstack); head->item = &commandstack.actualstack[0]; int linenumber = 1; int partofpreviousword = 0; int partofinput = 0; int partofoutput = 0; int endofword = 0; int numberofnewlinesinarow = 0; int restinginput = 0; int new = 0; int dontcountnewlinebecauseofandoror = 0; int e; char c; char d; while((e = getNextByte(getNextByte_argument)) != -1) //A = AND COMMAND, S = SIMPLE COMMAND, O = OR COMMAND, ; = SEQUENCE COMMAND, | = PIPELINE COMMAND, ( = SUBSHELL COMMAND, { c = (char) e; if(c == '\n') { restinginput = 0; partofpreviousword = 0; if (partofinput == 1 || partofoutput == 1) { fprintf(stderr, "linenumber %d: syntax error", linenumber); exit(1); } numberofnewlinesinarow++; if (numberofnewlinesinarow == 1 && dontcountnewlinebecauseofandoror == 0) { while(1) { d = getNextByte(getNextByte_argument); if (d == '&' || d == '|' || d == '(' || d == ')' || d == '<' || d == '>' || d == ';') { ungetc(d, getNextByte_argument); fprintf(stderr, "linenumber %d: syntax error", linenumber); exit(1); break; } if (d == -1) { new++; break; } if (d == '\n') { ungetc(d, getNextByte_argument); new++; break; } if (is_valid_char(d)) { ungetc(d, getNextByte_argument); break; } } if( new == 0) { c = ';'; // change \n to ; } } linenumber++; if (numberofnewlinesinarow == 2 && dontcountnewlinebecauseofandoror == 0) { while (Stackisempty(&operatorstack) == 0) { if (Stacktop(&operatorstack)->type == SUBSHELL_COMMAND) { copy(Stacktop(&commandstack), operatorstack.actualstack[operatorstack.top - 1].u.subshell_command); Stackcheckpop(&commandstack, linenumber); Stackcheckpop(&commandstack, linenumber); } else { operatorstack.actualstack[operatorstack.top - 1].u.command[1] = checked_malloc(sizeof(struct command)); operatorstack.actualstack[operatorstack.top - 1].u.command[0] = checked_malloc(sizeof(struct command)); copy(Stacktop(&commandstack), operatorstack.actualstack[operatorstack.top - 1].u.command[1]); Stackcheckpop(&commandstack, linenumber); copy(Stacktop(&commandstack), operatorstack.actualstack[operatorstack.top - 1].u.command[0]); Stackcheckpop(&commandstack, linenumber); } Stackpush(&commandstack, operatorstack.actualstack[operatorstack.top - 1].type); copy(Stacktop(&operatorstack), Stacktop(&commandstack)); Stackcheckpop(&operatorstack, linenumber); } pointer->item = malloc(sizeof(struct command)); numberofnewlinesinarow = 0; pointer->next = malloc(sizeof(struct command_stream)); copy(Stacktop(&commandstack), pointer->item); Stackcheckpop(&commandstack, linenumber); pointer = pointer->next; pointer->item = &commandstack.actualstack[0]; pointer->next = NULL; partofpreviousword = 0; partofinput = 0; partofoutput = 0; endofword = 0; numberofnewlinesinarow = 0; new = 0; dontcountnewlinebecauseofandoror = 0; } if (c != ';') { continue; } } if(c == '#') { while(getNextByte(getNextByte_argument) != '\n') {} linenumber++; numberofnewlinesinarow++; continue; } if(c == ' ') { if (fpeek(getNextByte_argument) == ' ') { continue; } if (fpeek(getNextByte_argument) != '\n') { numberofnewlinesinarow = 0; } if (is_valid_char(fpeek(getNextByte_argument)) == 0 && fpeek(getNextByte_argument) != '<' && fpeek(getNextByte_argument) != '>') { partofpreviousword = 0; } continue; } if(is_valid_char(c) == 1) { restinginput = 0; numberofnewlinesinarow = 0; dontcountnewlinebecauseofandoror = 0; if (partofinput == 1) { Stackinputpush(&commandstack, c); if (is_valid_char(fpeek(getNextByte_argument)) == 0) { partofinput = 0; restinginput++; resetinputoutput(&commandstack, 1); } continue; } if (partofoutput == 1) { Stackoutputpush(&commandstack, c); if (is_valid_char(fpeek(getNextByte_argument)) == 0) { partofoutput = 0; resetinputoutput(&commandstack, 0); } continue; } if (partofpreviousword == 0) { Stackpush(&commandstack, 'S'); } Stackcommandpush(&commandstack, c, partofpreviousword); if (is_valid_char(fpeek(getNextByte_argument)) == 0 || (int)fpeek(getNextByte_argument) == -1) { while(1) { d = getNextByte(getNextByte_argument); if (d != ' ') { ungetc(d, getNextByte_argument); break; } } partofinput = 0; partofoutput = 0; if (d == '&' || d == '|' || d == '(' || d == ')' || d == '<' || d == '>' || d == '\n') { endofword = 1; } incrementstackword(&commandstack, endofword); endofword = 0; } partofpreviousword = 1; continue; } if (partofpreviousword == 0 && (c == '<' || c == '>') && restinginput == 0) { fprintf(stderr, "linenumber %d: syntax error", linenumber); exit(1); } if(is_valid_char(c) == 0) { restinginput = 0; partofpreviousword = 0; partofinput = 0; numberofnewlinesinarow = 0; partofoutput = 0; char d = fpeek(getNextByte_argument); if (c == '&' && c != d) { fprintf(stderr, "linenumber %d: syntax error", linenumber); exit(1); } if (c == ';') { dontcountnewlinebecauseofandoror++; } if (c == '|' && d != c) { dontcountnewlinebecauseofandoror++; } if (d == c && d == '&') { c = 'A'; dontcountnewlinebecauseofandoror++; getNextByte(getNextByte_argument); } else if (d == c && d == '|') { c = 'O'; dontcountnewlinebecauseofandoror++; getNextByte(getNextByte_argument); } if (c == '(') { Stackpush(&operatorstack, c); continue; } if (c == '<') { if (dontcountnewlinebecauseofandoror > 0) { fprintf(stderr, "linenumber %d: syntax error", linenumber); exit(1); } partofinput = 1; continue; } if (c == '>') { if (dontcountnewlinebecauseofandoror == 1) { fprintf(stderr, "linenumber %d: syntax error", linenumber); exit(1); } partofoutput = 1; continue; } if (Stackisempty(&operatorstack) == 0) { if (c == ')') { while (Stacktop(&operatorstack)->type != SUBSHELL_COMMAND && Stackisempty(&operatorstack) == 0) { operatorstack.actualstack[operatorstack.top - 1].u.command[1] = checked_malloc(sizeof(struct command)); operatorstack.actualstack[operatorstack.top - 1].u.command[0] = checked_malloc(sizeof(struct command)); copy(Stacktop(&commandstack), operatorstack.actualstack[operatorstack.top - 1].u.command[1]); Stackcheckpop(&commandstack, linenumber); copy(Stacktop(&commandstack), operatorstack.actualstack[operatorstack.top - 1].u.command[0]); Stackcheckpop(&commandstack, linenumber); Stackpush(&commandstack, operatorstack.actualstack[operatorstack.top - 1].type); copy(Stacktop(&operatorstack), Stacktop(&commandstack)); Stackcheckpop(&operatorstack, linenumber); } if (Stackisempty(&operatorstack)) { fprintf(stderr, "linenumber %d: syntax error", linenumber); exit(1); } copy(Stacktop(&commandstack), operatorstack.actualstack[operatorstack.top - 1].u.subshell_command); Stackcheckpop(&commandstack, linenumber); Stackpush(&commandstack, operatorstack.actualstack[operatorstack.top - 1].type); copy(Stacktop(&operatorstack), Stacktop(&commandstack)); Stackcheckpop(&operatorstack, linenumber); continue; } if (c == ';') { while (Stacktop(&operatorstack)->type != SUBSHELL_COMMAND && Stackisempty(&operatorstack) == 0) { operatorstack.actualstack[operatorstack.top - 1].u.command[1] = checked_malloc(sizeof(struct command)); operatorstack.actualstack[operatorstack.top - 1].u.command[0] = checked_malloc(sizeof(struct command)); copy(Stacktop(&commandstack), operatorstack.actualstack[operatorstack.top - 1].u.command[1]); Stackcheckpop(&commandstack, linenumber); copy(Stacktop(&commandstack), operatorstack.actualstack[operatorstack.top - 1].u.command[0]); Stackcheckpop(&commandstack, linenumber); Stackpush(&commandstack, operatorstack.actualstack[operatorstack.top - 1].type); copy(Stacktop(&operatorstack), Stacktop(&commandstack)); Stackcheckpop(&operatorstack, linenumber); } Stackpush(&operatorstack, c); } if (c == 'A' || c == 'O') { while (Stacktop(&operatorstack)->type != SUBSHELL_COMMAND && Stacktop(&operatorstack)->type != SEQUENCE_COMMAND && Stackisempty(&operatorstack) == 0) { operatorstack.actualstack[operatorstack.top - 1].u.command[1] = checked_malloc(sizeof(struct command)); operatorstack.actualstack[operatorstack.top - 1].u.command[0] = checked_malloc(sizeof(struct command)); copy(Stacktop(&commandstack), operatorstack.actualstack[operatorstack.top - 1].u.command[1]); Stackcheckpop(&commandstack, linenumber); copy(Stacktop(&commandstack), operatorstack.actualstack[operatorstack.top - 1].u.command[0]); Stackcheckpop(&commandstack, linenumber); Stackpush(&commandstack, operatorstack.actualstack[operatorstack.top - 1].type); copy(Stacktop(&operatorstack), Stacktop(&commandstack)); Stackcheckpop(&operatorstack, linenumber); } Stackpush(&operatorstack, c); } if (c == '|') { while (Stacktop(&operatorstack)->type != AND_COMMAND && Stacktop(&operatorstack)->type != OR_COMMAND && Stacktop(&operatorstack)->type != SUBSHELL_COMMAND && Stacktop(&operatorstack)->type != SEQUENCE_COMMAND && Stackisempty(&operatorstack) == 0) { operatorstack.actualstack[operatorstack.top - 1].u.command[1] = checked_malloc(sizeof(struct command)); operatorstack.actualstack[operatorstack.top - 1].u.command[0] = checked_malloc(sizeof(struct command)); copy(Stacktop(&commandstack), operatorstack.actualstack[operatorstack.top - 1].u.command[1]); Stackcheckpop(&commandstack, linenumber); copy(Stacktop(&commandstack), operatorstack.actualstack[operatorstack.top - 1].u.command[0]); Stackcheckpop(&commandstack, linenumber); Stackpush(&commandstack, operatorstack.actualstack[operatorstack.top - 1].type); copy(Stacktop(&operatorstack), Stacktop(&commandstack)); Stackcheckpop(&operatorstack, linenumber); } Stackpush(&operatorstack, c); } } if (Stackisempty(&operatorstack) == 1) { Stackpush(&operatorstack, c); } } } while (Stackisempty(&operatorstack) == 0) { if (Stacktop(&operatorstack)->type == SUBSHELL_COMMAND) { copy(Stacktop(&commandstack), operatorstack.actualstack[operatorstack.top - 1].u.subshell_command); Stackcheckpop(&commandstack, linenumber); Stackcheckpop(&commandstack, linenumber); } else { operatorstack.actualstack[operatorstack.top - 1].u.command[1] = checked_malloc(sizeof(struct command)); operatorstack.actualstack[operatorstack.top - 1].u.command[0] = checked_malloc(sizeof(struct command)); copy(Stacktop(&commandstack), operatorstack.actualstack[operatorstack.top - 1].u.command[1]); Stackcheckpop(&commandstack, linenumber); copy(Stacktop(&commandstack), operatorstack.actualstack[operatorstack.top - 1].u.command[0]); Stackcheckpop(&commandstack, linenumber); } Stackpush(&commandstack, operatorstack.actualstack[operatorstack.top - 1].type); copy(Stacktop(&operatorstack), Stacktop(&commandstack)); Stackcheckpop(&operatorstack, linenumber); } return head; } command_t read_command_stream (command_stream_t s) { int i; for (i = 0; i < count; i++) { s = s->next; } count++; if (s == NULL) { return NULL; } return s->item; }
C
#include <stdio.h> /*Faça um programa para ler o horário (hora, minuto e segundo) de início e a duração, em segundos, de uma experiência biológica. O programa deve informar o horário (hora, minuto e segundo) de termino da mesma.*/ int main(void) { int hi, mi, si, sd; printf("Quando começou o experimento?(hh:mm:ss)\t"); scanf("%d:%d:%d", &hi, &mi, &si); printf("Qual foi o tempo de duração, em segundos?\t"); scanf("%d", &sd); printf("o experimento terminou ás:\t %d:%d:%d", hi+(sd/3600), mi+(sd%3600/60), si+(sd%3600%60)); return 0; }
C
#include<stdio.h> main() {int N,i ; for(N=2 ; N<=255 ; N++) { i=2 ; while (N%i!=0 && i<N ) i++ ; } printf("les entiers naturels premier N entre 1 et 255 sont %d\n",N); system("pause") ; }
C
#include <stdio.h> #include <stdlib.h> /** * main - a program that multiplies two numbers * @argc: argument that counts argument input * @argv: argument the strings in an array of char* * * Return: 0 */ int main(int argc, char *argv[]) { int num1, num2, mul; if (argc != 3) printf("Error\n"); else { num1 = atoi(argv[1]); num2 = atoi(argv[2]); mul = num1 *num2; printf("%d\n", mul); } return (0); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #define big long long int *gen_rand_alt(int *s, int n) { int i; for (i=0;i<n;i++) s[i] = (rand() % n); return s; } big *preprocess(int *partitionnumbers, big *list) { //list goes from 0 to 100, we want preprocess to as well, int goes from 0 to 100 int i; int j; big *glued = malloc(100*sizeof(big)); //initialize to zero for(i= 0; i < 100; i++) { glued[i] = 0; } for(i = 0; i < 100; i++) { j = partitionnumbers[i]; glued[j] += list[i]; } return glued; } int *altneighbor(int *new, int *s){ //copy s int i; for(i = 0; i < 100; i++) new[i] = s[i]; //choose a random position int pos = rand() % 100; //choose a random perturbation int perturb = (rand() % 99) + 1; new[pos] = (new[pos] + perturb) % 100; return new; } //Binary Heap Stuff //Throughout, A is an array implementing our heap //Returns the parent of A[i] int Parent(int i){ return i/2; //we actually return floor i/2 } //Returns left child int Left(int i){ return 2*i; } //Returns right child int Right(int i){ return 2*i+1; } big *Max_Heapify(big *A, int i, int heapsize) { int l = Left(i); int r = Right(i); int largest; if(l <= heapsize && A[l] > A[i]) { largest = l; } else{largest = i;} if( r <= heapsize && A[r] > A[largest] ) { largest = r; } if(largest == i) { //if the biggest is in spot i, do nothing return A; } else { //exchange A[i] and A[largest] big temp = A[i]; A[i] = A[largest]; A[largest] = temp; Max_Heapify(A, largest, heapsize); } } big *Heap_Extract_Max(big *A, int heapsize) { big max = A[1]; A[1] = A[heapsize]; //cheat and store the max value in the now empty last spot A[heapsize] = max; heapsize--; Max_Heapify(A, 1, heapsize); return A; } //remember to fucking manually decrement heapsize dude! big *Heap_Increase_Key(big *A, int i, big key){ A[i] = key; while(i > 1 && A[Parent(i)] < A[i]) { //exchange A[i], and A[parent(i)] big temp = A[i]; A[i] = A[Parent(i)]; A[Parent(i)] = temp; i = Parent(i); } //return our modified heap return A; } big *Max_Heap_Insert(big *A, big key, int heapsize) { //REMEMBER TO MANUALLY TOGGLE HEAPSIZES!!!! //add in one last element to the heap with value key A[heapsize+1] = key; //let it float up the heap appropriately return Heap_Increase_Key(A, heapsize+1, key); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* exec_tools.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ncolliau <ncolliau@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/01/21 11:17:16 by ncolliau #+# #+# */ /* Updated: 2015/02/24 13:59:23 by ncolliau ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_sh.h" extern char **g_env; int open_it(char *file, int redir) { int fd; if (redir == WRITE_END) { if (file[0] == '>') fd = open(file + 1, O_CREAT | O_RDWR | O_APPEND, 0664); else fd = open(file, O_CREAT | O_RDWR | O_TRUNC, 0664); } else fd = open(file, O_RDONLY); if (fd == -1) { ft_putstr_fd("ft_sh: open failed: ", 2); ft_putendl_fd(file, 2); } return (fd); } char *join_input_and_line(char *input, char *line) { char *tmp; tmp = input; input = ft_strtrijoin(input, line, "\n"); free(tmp); free(line); return (input); } char *get_input(char **stop) { int ret; char *input; char *line; size_t i; i = 0; input = ft_strdup(""); while (stop && stop[i]) { ret = 1; ft_putstr("> "); while ((ret = get_next_line(0, &line)) == 1 && ft_strequ(line, stop[i]) == 0) { input = join_input_and_line(input, line); ft_putstr("> "); } free(line); if (ret == 0) ft_putchar('\n'); else if (ret == -1) ft_putendl_fd("Error get_next_line", 2); i++; } return (input); } char *get_pipe(int old_pdes[2]) { char *pipe; char *tmp; char buf[2]; int ret; pipe = ft_strdup(""); close(old_pdes[WRITE_END]); while ((ret = read(old_pdes[READ_END], buf, 1)) != 0 && ret != -1) { buf[1] = '\0'; tmp = pipe; pipe = ft_strjoin(pipe, buf); ft_memset(buf, 0, 2); free(tmp); } close(old_pdes[READ_END]); return (pipe); } void put_in_stdin(char *input) { pid_t pid; int pdes[2]; pipe(pdes); pid = fork(); if (pid > 0) { wait(NULL); close(pdes[WRITE_END]); dup2(pdes[READ_END], STDIN_FILENO); } if (pid == 0) { close(pdes[READ_END]); dup2(pdes[WRITE_END], STDOUT_FILENO); ft_putstr(input); close(pdes[WRITE_END]); exit(EXIT_SUCCESS); } close(pdes[READ_END]); }
C
/* example-8.2 */ #include <stdio.h> #include <string.h> #include <ctype.h> int main(void) { char st[100]; int i,n,c_l,c_u,c_d; printf ("文字列を入れてください "); gets(st); n=strlen(st); c_l=c_u=c_d=0; for(i=0;i<n;i++) { if (islower(st[i])) c_l++; if (isupper(st[i])) c_u++; if (isdigit(st[i])) c_d++; } printf ("全文字数 %d 小文字 %d, 大文字 %d, 数字 %d\n",n,c_l,c_u,c_d); return 0; }
C
/** * @file cmf_object.h * * @brief cmf node/object APIs. * * @author Forrest.zhang */ #ifndef FZ_CMF_OBJECT_H #define FZ_CMF_OBJECT_H /* cmf node magic number */ #define CMF_NODE_MAGIC 0x13579BD0 /* cmf node type */ enum { CMF_PATH, CMF_SINGLE, CMF_TABLE, CMF_ATTR, CMF_EXEC, CMF_DIAG, }; /* cmf node functions */ typedef struct cmf_node_ops { int nid; /* the node ID */ cmf_config_func config_func; cmf_end_func end_func; cmf_exit_func exit_func; cmf_abort_func about_func; cmf_set_func set_func; cmf_unset_func unset_func; cmf_get_func get_func; cmf_parse_func parse_func; cmf_edit_func edit_func; cmf_del_func del_func; cmf_get_func get_func; cmf_show_func show_func; cmf_print_func print_func; } cmf_node_ops_t; /* cmf node */ typedef struct cmf_node { char name[CMF_NAMELEN];/* object name */ char desc[CMF_DESCLEN];/* object comment */ u_int32_t magic; /* object magic number */ u_int32_t nid; /* the unique id for node */ int type; /* node type */ int dtype; /* data type */ u_int16_t offset; /* node offset, for attr */ u_int16_t size; /* object storage size */ u_int16_t group; /* support max 255 group */ u_int8_t perm; /* object permision */ u_int8_t flags; /* flags: HA */ u_int16_t childs[CMF_CHILDMAX];/* the childs of objects */ u_int16_t nchild; /* childs number */ u_int16_t options[CLI_OPTMAX];/* option values */ u_int16_t noption; /* Option value for Attribute */ u_int32_t parent; /* the parent of this object */ u_int32_t sibling; /* next sibling node */ } cmf_node_t; /* cmf value */ typedef struct cmf_value { int nid; /* node id */ int vid; /* value id */ int len; /* the length */ char buf[0]; /* the value data */ } cmf_value_t; /* cmf multi-option */ typedef struct cmf_mulopt { char name[CMF_NAMELEN]; u_int32_t value; u_int32_t selected; } cmf_mulopt_t; /* cmf single option */ typedef struct cmf_opt { char name[CMF_NAMELEN]; int value; } cmf_opt_t; extern int cmf_add_node(cmf_node_t *node); extern int cmf_add_attr(cmf_node_t *node, cmf_node_t *attr); extern int cmf_add_opt(cmf_node_t *node, cmf_opt_t *opt); extern int cmf_add_mulopt(cmf_node_t *node, cmf_mulopt_t *opt); #endif /* end of FZ_CLI_OBJECT_H */
C
///////////////////////////////////////////////////////////////////////////////////////// // // Battery Methods // // We have a standard of status for all batteries, as a simple way of knowing how to handle them. // They are a system of ints, and are defined as follows: // - 0: All good / Above 50% // - 1: Okay / Above 20% but lower/equal to 50% // - 2: Bad / Lower/equal to 20% // It does not need to be in a sense of precentage, however it should follow ~ the same guidelines. // ///////////////////////////////////////////////////////////////////////////////////////// // TODO Modify these standards // Voltage standards for vex 7.2v batteries, in volts float okayVoltage = 7.2; // If above, 0. float badVoltage = 6.5; // If above, 1. If below, 2. // Gets the cortex battery voltage // RETURNS: // float: The voltage of the battery float getMainBatteryVoltage() { return nAvgBatteryLevel/1000.0; } // Gets the cortex battery status based on above defined standards // RETURNS: // int: Status of the battery int getMainBatteryStatus() { float cortexVoltage = getMainBatteryVoltage(); if (cortexVoltage > okayVoltage) return 0; if (cortexVoltage > badVoltage) return 1; return 2; } // Gets the backup battery voltage // RETURNS: // float: The voltage of the battery float getBackupBatteryVoltage() { return BackupBatteryLevel/1000.0; } // Gets the cortex battery status based on above defined standards // RETURNS: // int: Status of the battery int getBackupBatteryStatus() { float backupVoltage = getBackupBatteryVoltage(); if (backupVoltage > okayVoltage) return 0; if (backupVoltage > badVoltage) return 1; return 2; } // Gets the expander battery voltage // RETURNS: // float: The voltage of the battery float getExpanderBatteryVoltage() { // TODO Figure this out. I've read a billion different things. The above was found out through // -> manual math by figuring out the voltage on the cortex port, then comparing to the value // -> returned by the expander return (SensorValue[powerExpander]/2053.0)*100.0; } // Gets the expander battery status (Defined above) // RETURNS: // int: Status of the battery int getExpanderBatteryStatus() { float expanderVoltage = getExpanderBatteryVoltage(); if (expanderVoltage > okayVoltage) return 0; if (expanderVoltage > badVoltage) return 1; return 2; } ///////////////////////////////////////////////////////////////////////////////////////// // // Gyroscope/Angle Methods // ///////////////////////////////////////////////////////////////////////////////////////// // Simplifies raw gyro input (-3599 to 3599) to either 0-3599 or 0-359 // PARAMETERS: // int: The raw data from the gyro, retrieved like SensorValue[sensor] // bool: Whether or not to make from 3600 degrees (1/10th) to 360 degreess (single) // RETURNS: // int: The simplified degree // NOTE: If using simplifyTo360, please read NOTE of gyroToFloat below. int simplifyGyro(int degree, bool simplifyTo360) { int simplified = abs(degree); if (simplifyTo360) simplified = floor((((float)simplified)/10.0) + 0.5); // Make sure we don't round up to 360, a value gyro can't make if (simplified == 360) simplified = 0; return simplified; } // Simplifies raw gyro input (-3599 to 3599) to 0.0-359.99999... // PARAMETERS: // int: The raw data from the gyro, retrieved like SensorValue[sensor] // bool: Whether or not to make from 3600 degrees (1/10th) to 360 degreess (single) // RETURNS: // float: The simplified degree // NOTE: // - While similar to simplifyGyro, this method doesn't cut off the remainder of the division. // - For example, gyroToFloat(3137) = 313.7, but simplifyGyro(3137) returns 314 float gyroToFloat(int degree) { return ((float) abs(degree))/10.0; } // A simple function for degree to radian conversions // PARAMETERS: // float: A simplified degree like 180.7 (use gyroToFloat to simplify a gyro value) // RETURNS: // float: Provided degree in radians float degreeToRad(float degree){ return (degree*3.14)/180.0; } // Takes in the sides of a triangle and returns the angle made // PARAMETERS: // float: The x value of the joystick, or just x value of the triangle // float: The y value of the joystick, or just y value of the triangle // RETURNS: // float: The angle calculated from the joystick values float sidesToAngle(float sideOne, float sideTwo){ // When using with a controller, sideOne should be the X axis // and side two should be the y axis // If the value is 0,0, meaning joystick not moved, // return -1 to avoid errors, and allow caller to handle accordingly if(sideOne==0.0&&sideTwo==0.0){ return -1.0; } // Handle angles that fall on axis, to again avoid errors later if(sideOne==0.0||sideTwo==0.0){ if(sideOne==0.0){ if(sideTwo>0.0){ return 90.0; } else { return 270.0; } } else { if(sideOne>0.0){ return 0.0; } else { return 180.0; } } } float angle = atan(sideTwo/sideOne); angle = ((angle*180.0)/3.14); // Determine the quadrant of the angle, because of atan's range restrictions float quadrant = 0.0; if(angle>0.0){ if(sideOne<0.0&&sideTwo<0.0){ quadrant = 3.0; } else { quadrant = 1.0; } } else { if(sideOne<0.0){ quadrant = 2.0; } else { quadrant = 4.0; } } // CD sstands for Cardinal Direction float nearbyCD = (90.0*(quadrant-1.0)); float finalAngle = nearbyCD; // Place the angle in the proper place, besides just in atans range of quadrants 1 and 2 if(abs(sideOne)>=abs(sideTwo)){ finalAngle += abs(angle); } else { if(quadrant==1.0||quadrant==4.0){ if(quadrant==4.0){ finalAngle+=90.0; } finalAngle+=angle; } else { return (angle+180.0); } } return finalAngle; } ///////////////////////////////////////////////////////////////////////////////////////// // // Game time tracking Methods // ///////////////////////////////////////////////////////////////////////////////////////// // TODO: Change the following values to correct ones in millis const int autonTime = 1000; // Auton time in millis const int controlTime = 1000; // User control time in millis const int skillsTime = 1000; // Skills time in millis bool gamemode = false; // False = auton control, true = user control // Sets up the timer for game time tracking // PARAMETERS: // bool: What gamemode to use. False = auton control, true = user control void setupGameTimer(bool _gamemode) { gamemode = _gamemode; clearTimer(T3); } // Gets how long the game has been running // RETURNS: // int: Time the game has been running, in milliseconds int getGameTimeRunning() { return time1[T3]; } // Gets how long is left in the game // RETURNS: // int: Time the game has left, in milliseconds int getGameTime() { return time1[T3] - (gamemode ? controlTime : autonTime); } // Gets how long is left in the game, considering it's skills // RETURNS: // int: Time the skills match has left, in milliseconds int getSkillsTime() { return time1[T3]-skillsTime; } ///////////////////////////////////////////////////////////////////////////////////////// // // Error escapes // // Since this is a lib, we aren't going to use every method. Have a never called function to eliminate the warnings. // ///////////////////////////////////////////////////////////////////////////////////////// // THIS SHOULD NEVER BE CALLED. void sensorsErrorEscape() { sidesToAngle(0,0); getMainBatteryVoltage(); getMainBatteryStatus(); getBackupBatteryVoltage(); getBackupBatteryStatus(); getExpanderBatteryVoltage(); getExpanderBatteryStatus(); setupGameTimer(false); getGameTimeRunning(); getGameTime(); getSkillsTime(); simplifyGyro(0, false); degreeToRad(0.0); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/wait.h> extern int errno; // system error number void syserr(char * msg) // report error code and abort { fprintf(stderr,"%s: %s", strerror(errno), msg); //abort(errno); } pid_t runProcess(const char *cmd, const char *infilename, const char *outfilename){ pid_t pid; // process ID //int rc; // return code switch (pid = fork()) { case -1: //syserr("fork"); ; case 0: // execution in child process freopen(infilename,"r",stdin); freopen(outfilename,"w",stdout); execl(cmd, cmd, NULL); syserr("execl"); // error if return from exec printf("error"); } return pid; } int main (int argc, char ** argv) { runProcess("/usr/bin/sort", "input.txt","output.txt"); return 0; }
C
#include<stdio.h> int main() { char a,b,c; scanf("%c %c %c",&a,&b,&c); printf("%c,%c,%c",a,b,c); }
C
/* ** EPITECH PROJECT, 2019 ** print_option.c ** File description: ** print game option */ #include "my.h" #include "tetris.h" void print_escape_sequence(char *str) { int i = 0; while (str[i] != '\0') { if (str[i] == 27) my_putstr("^E"); else my_putchar(str[i]); i++; } my_putchar('\n'); } void print_option_next(tetris_t *tetris) { my_putstr("Next : "); if (tetris->opt->next) my_putstr("No\n"); else my_putstr("Yes\n"); my_putstr("Level : "); my_put_nbr(tetris->opt->level); my_putchar('\n'); my_putstr("Size : "); my_put_nbr(tetris->opt->size.x); my_putchar('*'); my_put_nbr(tetris->opt->size.y); my_putchar('\n'); } void print_option_flw(tetris_t *tetris) { if (my_strcmp(tetris->opt->drop, " ") == 0) my_putstr("Key Drop : (space)\n"); else { my_putstr("Key Drop : "); print_escape_sequence(tetris->opt->drop); } if (my_strcmp(tetris->opt->quit, " ") == 0) my_putstr("Key Quit : (space)\n"); else { my_putstr("Key Quit : "); print_escape_sequence(tetris->opt->quit); } if (my_strcmp(tetris->opt->pause, " ") == 0) my_putstr("Key pause : (space)\n"); else { my_putstr("Key Pause : "); print_escape_sequence(tetris->opt->pause); } print_option_next(tetris); } void print_option(tetris_t *tetris) { if (my_strcmp(tetris->opt->left, " ") == 0) { my_putstr("Key Left : (space)\n"); } else { my_putstr("Key Left : "); print_escape_sequence(tetris->opt->left); } if (my_strcmp(tetris->opt->right, " ") == 0) my_putstr("Key Right : (space)\n"); else { my_putstr("Key Right : "); print_escape_sequence(tetris->opt->right); } if (my_strcmp(tetris->opt->turn, " ") == 0) my_putstr("Key Turn : (space)\n"); else { my_putstr("Key Turn : "); print_escape_sequence(tetris->opt->turn); } print_option_flw(tetris); }
C
/* Author: Abraham Saiovici Specs: https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html */ #include "jclass.h" int read_class(jclass *class, char *file_name) { FILE *f = fopen(file_name, "rb"); if (!f) { printf("Error. Could not read from %s\n", file_name); return 0; } unsigned int magic = (unsigned int) read_bytes(f, 4); if(magic != MAGIC_NUM) { printf("Error. This file is not a Java class.\n"); return 0; } class->minor_ver = read_bytes(f, 2); class->major_ver = read_bytes(f, 2); class->cpool.cp_count = read_bytes(f, 2); class->cpool.entry = malloc(sizeof(cp_entry) * class->cpool.cp_count); read_cpool(class, f); class->acc_flag = read_bytes(f, 2); class->this_class = read_bytes(f, 2); class->super_class = read_bytes(f, 2); class->interface_count = read_bytes(f, 2); class->read_interfaces = malloc(sizeof(interface_info) * class->interface_count); read_interfaces(class, f); class->field_count = read_bytes(f, 2); class->fields = malloc(sizeof(field_info) * class->field_count); read_member_info(class, class->fields, f, class->field_count); class->method_count = read_bytes(f, 2); class->methods = malloc(sizeof(method_info) * class->method_count); read_member_info(class, class->methods, f, class->method_count); class->attr_count = read_bytes(f, 2); class->attributes = malloc(sizeof(attr_info) * class->attr_count); read_attr(f, class->attributes, class->attr_count); fclose(f); return 1; } void read_cpool(jclass *class, FILE *f) { int i; class->cpool.entry[0].info = NULL; for (i = 1; i < class->cpool.cp_count; i++) { unsigned char tag = fgetc(f); class->cpool.entry[i].tag = tag; switch (tag) { case UTF_8: { utf8_info *utf = malloc(sizeof(utf8_info)); utf->length = read_bytes(f, 2); utf->bytes = malloc(sizeof(char) * utf->length + 1); fread(utf->bytes, sizeof(char), utf->length, f); utf->bytes[utf->length] = 0; class->cpool.entry[i].info = (void *) utf; break; } case INTEGER: { case FLOAT: { int_info *fint = malloc(sizeof(int_info)); fint->bytes = read_bytes(f, 4); class->cpool.entry[i].info = (void *) fint; break; } } case LONG: { case DOUBLE: { long_info *dlong = malloc(sizeof(dlong)); dlong->bytes = read_bytes(f, 8); class->cpool.entry[i].info = (void *) dlong; i++; break; } } case CLASS: { class_info *classinfo = malloc(sizeof(class_info)); classinfo->cp_index = read_bytes(f, 2); class->cpool.entry[i].info = (void *) classinfo; break; } case STRING: { string_info *string = malloc(sizeof(string_info)); string->string_index = read_bytes(f, 2); class->cpool.entry[i].info = (void *) string; break; } case FIELD_REF: { case METHOD_REF: { case INTERFACE_METHOD_REF: { ref_info *refinfo = malloc(sizeof(ref_info)); refinfo->class_index = read_bytes(f, 2); refinfo->nt_index = read_bytes(f, 2); class->cpool.entry[i].info = (void *) refinfo; break; } } } case NAME_TYPE: { nt_info *ntinfo = malloc(sizeof(nt_info)); ntinfo->name_index = read_bytes(f, 2); ntinfo->desc_index = read_bytes(f, 2); class->cpool.entry[i].info = (void *) ntinfo; break; } } } } void read_interfaces(jclass *class, FILE *f) { int i; for (i = 0; i < class->interface_count; i++) { interface_info intr; intr.cp_index = read_bytes(f, 2); class->read_interfaces[i] = intr; } } void read_member_attr(jclass *class, member_info *fmr, FILE *f) { int i; for (i = 0; i < fmr->attr_count; i++) { attr_info attr; attr.name_index = read_bytes(f, 2); attr.attr_length = read_bytes(f, 4); attr.bytes = malloc(sizeof(char) * attr.attr_length); char *attr_name = ((utf8_info *) class->cpool.entry[attr.name_index].info)->bytes; if (strncmp("Code", attr_name, 4) == 0) { read_code_attr(class, f, fmr, &attr); fmr->attr[i] = attr; continue; } fread(attr.bytes, sizeof(char), attr.attr_length, f); fmr->attr[i] = attr; } } void read_code_attr(jclass *class, FILE *f, member_info *fmr, attr_info *attr) { fpos_t fpos; code_attr *code = malloc(sizeof(code_attr)); fgetpos(f, &fpos); code->max_stack = read_bytes(f, 2); code->max_locals = read_bytes(f, 2); code->code_length = read_bytes(f, 4); code->code = malloc(sizeof(unsigned char) * code->code_length + 1); fread(code->code, sizeof(unsigned char), code->code_length, f); code->code[code->code_length] = 0; code->excep_table_length = read_bytes(f, 2); code->table = malloc(sizeof(exception_table) * code->excep_table_length); int b; for (b = 0; b < code->excep_table_length; b++) { exception_table exc; exc.start_pc = read_bytes(f, 2); exc.end_pc = read_bytes(f, 2); exc.handler_pc = read_bytes(f, 2); exc.catch_type = read_bytes(f, 2); code->table[b] = exc; } code->attr_count = read_bytes(f, 2); code->attributes = malloc(sizeof(attr_info) * code->attr_count); for (b = 0; b < code->attr_count; b++) { attr_info attri; attri.name_index = read_bytes(f, 2); attri.attr_length = read_bytes(f, 4); read_bytes(f, attri.attr_length); code->attributes[b] = attri; } attr->info = (void *) code; parse_instr(class, code, fmr); fsetpos(f, &fpos); fread(attr->bytes, sizeof(char), attr->attr_length, f); } void read_member_info(jclass *class, member_info *c, FILE *f, unsigned short int count) { int i; for (i = 0; i < count; i++) { member_info fmi; fmi.acc_flags = read_bytes(f, 2); fmi.name_index = read_bytes(f, 2); fmi.desc_index = read_bytes(f, 2); fmi.attr_count = read_bytes(f, 2); fmi.attr = malloc(sizeof(attr_info) * fmi.attr_count); read_member_attr(class, &fmi, f); c[i] = fmi; } } void read_attr(FILE *f, attr_info *attri, unsigned short int attr_count) { int i; for (i = 0; i < attr_count; i++) { attr_info attr; attr.name_index = read_bytes(f, 2); attr.attr_length = read_bytes(f, 4); attr.bytes = malloc(sizeof(char) * attr.attr_length); fread(attr.bytes, sizeof(char), attr.attr_length, f); attri[i] = attr; } } /* Read high-endian unsigned data type of 'length' bytes starting from bytes+offset address*/ long double format_bytes(unsigned char *bytes, int offset, int length) { int i, ch = offset; long double res = 0; for (i = ((length - 1) * 8); i >= 0; i -= 8) { res += ((bytes[ch++] & 0xFF) << i); } return res; } /* Read high-endian unsigned data type of 'length' length from file */ long double read_bytes(FILE *f, int bytes) { int i; unsigned char *c = malloc(sizeof(unsigned char) * bytes); for (i = 0; i < bytes; i++) { c[i] = fgetc(f); } long double res = format_bytes(c, 0, bytes); free(c); return res; } void parse_instr(jclass *class, code_attr *code, method_info *method) { int i, instru, length; for (i = 0, instru = 0; i < code->code_length; instru++) { i += get_instr_size(code, i); } method->instr_count = instru; method->instructions = malloc(sizeof(instr) * instru); for (i = 0, instru = 0; i < code->code_length; instru++) { instr instruction; instruction.opcode = code->code[i]; method->instructions[instru] = instruction; i += get_instr_size(code, i); } }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #define NMax 300 int main() { int n; printf("Insert the number of strings!\n"); scanf("%d", &n); char *s=(char*)malloc(sizeof(char)*NMax); int maxLength=0; char *maxLengthString=(char*)malloc(sizeof(char)*NMax); printf("Insert the strings!\n"); for (int i=0; i<n; i++) { scanf("%s", s); int len=strlen(s); if (len>maxLength) { maxLength=len; strcpy(maxLengthString, s); } else if (len==maxLength && strcmp(maxLengthString, s)<0) { strcpy(maxLengthString, s); } } printf("The string is:\n%s", maxLengthString); return 0; }
C
#include <stdio.h> #define MAX_SIZE 10 typedef struct { int data[MAX_SIZE]; int front; int rear; }_queue; char isEmpty( _queue Q ){ if( Q.rear == Q.front ){ return 0; }else return -1; } char isFull( _queue Q ){ if( Q.rear == MAX_SIZE ){ return 0; }else return -1; } void add( _queue * Q, int data ){ if( isFull(*Q) == 0 ){ printf("Queue is Full!"); }else{ Q->data[Q->rear] = data; Q->rear++; } } int del( _queue * Q ){ int temp; if( isEmpty(*Q) == 0 ){ printf("Queue is Empty!"); }else{ temp = Q->data[Q->front]; Q->front++; return temp; } } int main(){ _queue Q={0,}; int i,data; while(1){ for( i=0; i<MAX_SIZE; i++) printf( "%d ", Q.data[i] ); printf("\n\nPlease input data to PUSH : "); scanf("%d",&data); add(&Q, data); if(isFull(Q) == 0) break; } printf("\nPOP\n"); printf("=================="); while(1){ data = del(&Q); printf("\n%d POP!",data); if(isEmpty(Q) == 0) break; } getchar(); getchar(); return 0; }
C
#include"queue.h" #include<malloc.h> #include<stdio.h> #include <string.h> #include "debug.h" //Queue *pqueue = NULL; Queue *QueueHead = NULL; Queue *queuehead = NULL; //add by mo 2020.07.11 /*һն*/ Queue *InitQueue() { Queue *pqueue = (Queue *)malloc(sizeof(Queue)); if(pqueue!=NULL) { pqueue->front = NULL; pqueue->rear = NULL; pqueue->size = 0; } return pqueue; } /*һ*/ void DestroyQueue(Queue *pqueue) { if(IsEmpty(pqueue)!=1) ClearQueue(pqueue); free(pqueue); } /*һ*/ void ClearQueue(Queue *pqueue) { while(IsEmpty(pqueue)!=1) { DeQueue(pqueue,NULL,NULL); } } /*ж϶ǷΪ*/ int IsEmpty(Queue *pqueue) { if(pqueue->front==NULL&&pqueue->rear==NULL&&pqueue->size==0) { //debug_printf("if :(pqueue->front==NULL):%d,(pqueue->rear==NULL):%d,pqueue->size = %d\n",pqueue->front==NULL,pqueue->rear==NULL,pqueue->size); return 1; } else { //debug_printf("else :(pqueue->front==NULL):%d,(pqueue->rear==NULL):%d,pqueue->size = %d\n",pqueue->front==NULL,pqueue->rear==NULL,pqueue->size); return 0; } } /*ضдС*/ int GetSize(Queue *pqueue) { return pqueue->size; } /*ضͷԪ*/ PNode GetFront(Queue *pqueue,Item *pitem,unsigned int *len) { if(IsEmpty(pqueue)!=1&&pitem!=NULL) { //*pitem = pqueue->front->data; memcpy(pitem,pqueue->front->data,pqueue->front->datalen); *len = pqueue->front->datalen; } return pqueue->front; } /*ضβԪ*/ PNode GetRear(Queue *pqueue,Item *pitem,unsigned int *len) { if(IsEmpty(pqueue)!=1&&pitem!=NULL) { //*pitem = pqueue->rear->data; memcpy(pitem,pqueue->rear->data,pqueue->rear->datalen); *len = pqueue->rear->datalen; } return pqueue->rear; } void Dequeue_specify(Queue *pqueue,Node *node) { Node *pre_node = pqueue->front; Node *cur_node = pqueue->front; if(IsEmpty(pqueue)) return ; while(cur_node != NULL) { if(cur_node == node) break; pre_node = cur_node; cur_node = cur_node->next; } //Ҳڵ if(cur_node == NULL) { return ; } //ҵڵ return ; } /*Ԫ,β*/ PNode EnQueue(Queue *pqueue,Item *item,unsigned int len) { int i = 0 ; //Item *item_data = (Item *)malloc(len + 24); PNode pnode = (PNode)malloc(sizeof(Node)+4); pnode->data = (Item *)malloc(len + 24); if(pnode == NULL || pnode->data == NULL) { perror("malloc"); queue_debug_printf("there is not enought memory for malloc!\n"); return NULL; } //pnode->data = item; //pnode->data = item_data; memcpy(pnode->data,item,len); pnode->datalen = len; pnode->next = NULL; if(IsEmpty(pqueue)) { QUEUE_DEBUG_PRINTF; pqueue->front = pnode; } else { QUEUE_DEBUG_PRINTF; pqueue->rear->next = pnode; } pqueue->rear = pnode; pqueue->size++; queue_debug_printf("pqueue->size = %d\n",pqueue->size); QUEUE_DEBUG_PRINTF; return pnode; } /*ͷԪس*/ PNode DeQueue(Queue *pqueue,Item *pitem,unsigned int *len) { int i; PNode pnode = pqueue->front; if(IsEmpty(pqueue) || pnode == NULL) return NULL; if(pitem == NULL || len == NULL) return NULL; memcpy(pitem,pnode->data,pnode->datalen); *len = pnode->datalen; //debug_printf("1:(pqueue->front==NULL):%d,(pqueue->rear==NULL):%d,pqueue->size = %d\n",pqueue->front==NULL,pqueue->rear==NULL,pqueue->size); pqueue->size--; pqueue->front = pnode->next; free(pnode->data); pnode->data = NULL; free(pnode); pnode = NULL; //debug_printf("2:(pqueue->front==NULL):%d,(pqueue->rear==NULL):%d,pqueue->size = %d\n",pqueue->front==NULL,pqueue->rear==NULL,pqueue->size); if(pqueue->front==NULL && pqueue->rear!=NULL && pqueue->size != 0) { //д־ //debug_printf("pqueue->front==NULL && pqueue->rear!=NULL && pqueue->size != 0\n"); } if(pqueue->size==0) { pqueue->rear = NULL; pqueue->front = NULL; } return pnode; } int Get_headlen(Queue *pqueue) { PNode pnode = pqueue->front; if(IsEmpty(pqueue)!=1&&pnode!=NULL) return pnode->datalen; else return 0; } #if 0 /*вԸvisit*/ void QueueTraverse(Queue *pqueue,void (*visit)(Item item)) { PNode pnode = pqueue->front; int i = pqueue->size; while(i--) { visit(pnode->data); pnode = pnode->next; } } #endif #if 0 void printf(Item i) { debug_printf("ýڵԪΪ%d\n",i); } main() { Queue *pq = InitQueue(); int i,item; debug_printf("0-9Ӳ£\n"); for(i=0;i<10;i++) { EnQueue(pq,i); GetRear(pq,&item); debug_printf("%d ",item); } debug_printf("\nӶͷβÿԪִprint\n"); QueueTraverse(pq,print); debug_printf("Ԫγв£\n"); for(i=0;i<10;i++) { DeQueue(pq,&item); debug_printf("%d ",item); } ClearQueue(pq); if(IsEmpty(pq)) debug_printf("\nÿճɹ\n"); DestroyQueue(pq); debug_printf("ѱ\n"); } #endif
C
#include<stdio.h> #include<stdlib.h> typedef struct node { int info; struct node *link; } node; node *front=NULL,*rear=NULL; void enqueue(int cap) { node *n; n=(node*)malloc(sizeof(node)); printf("Enter number to insert in node\n"); scanf("%d",&n->info); n->link=NULL; if(front==NULL && rear==NULL) front=rear=n; else { rear->link=n; rear=n; } } void dequeue() { node *temp=front; if(front==NULL && rear==NULL) printf("Empty queue\n"); else if(front==rear) front=rear=NULL; else front=front->link; free(temp); printf("Item deleted\n"); } void displayQueue() { node *temp=front; if(front==NULL && rear==NULL) { printf("Empty Queue\n"); } else { while(temp!=NULL) { printf("%d\n",temp->info); temp=temp->link; } } } void main() { int choice,cap,count=0; printf("Enter the capacity of the queue\n"); scanf("%d",&cap); while(1) { printf("1.Insert in Queue\n"); printf("2.Delete from Queue\n"); printf("3.Display Queue\n"); printf("4.Exit\n"); printf("\nEnter your choice\n"); scanf("%d",&choice); switch(choice) { case 1: if(cap==count) printf("Queue is FULL\n"); else { enqueue(cap); count++; } break; case 2: dequeue(); break; case 3: displayQueue(); break; case 4: exit(0); break; default: printf("Invalid choice\n"); break; } } }
C
#include <pthread.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #include <sys/time.h> struct _num_st { int start; int end; }; void *t_function(void *data) { int cnt, sum=0; struct _num_st *id; id = (struct _num_st *)data; // printf("id->start = %d, id->end = %d\n", id->start, id->end); for(cnt=id->start; cnt <= id->end; cnt++) { sum+=cnt; } return (void *)(sum); } int main() { struct timeval UTCtime_u_s, UTCtime_u_e, UTCtime_u_r ; struct _num_st st_num[2]; pthread_t p_thread[2]; int err; int status[2]; int a = 1; int b = 2; st_num[0].start = 1; st_num[0].end = 10000; st_num[1].start = 10001; st_num[1].end = 20000; gettimeofday(&UTCtime_u_s, NULL); if((err = pthread_create(&p_thread[0], NULL, t_function, (void *)&st_num[0]))<0) { perror("thread create error : "); exit(1); } if((err = pthread_create(&p_thread[1], NULL, t_function, (void *)&st_num[1])) < 0) { perror("thread create erro : "); exit(2); } pthread_join(p_thread[0], (void **)&status[0]); pthread_join(p_thread[1], (void **)&status[1]); gettimeofday(&UTCtime_u_e, NULL); if(UTCtime_u_e.tv_usec >= UTCtime_u_s.tv_usec) { UTCtime_u_r.tv_usec = UTCtime_u_e.tv_usec - UTCtime_u_s.tv_usec; UTCtime_u_r.tv_sec = UTCtime_u_e.tv_sec - UTCtime_u_s.tv_sec; } else { UTCtime_u_r.tv_usec = UTCtime_u_e.tv_usec - UTCtime_u_s.tv_usec + 100000; UTCtime_u_r.tv_sec = UTCtime_u_e.tv_sec - UTCtime_u_s.tv_sec -1; } printf("time : %ld sec %ld usec \n", UTCtime_u_r.tv_sec, UTCtime_u_r.tv_usec); printf("sum1 = %d\n", status[0]); printf("sum2 = %d\n", status[1]); printf("sum1 + sum 2 = %d\n", status[0]+status[1]); return 0; }
C
#include "holberton.h" /** * _memset - this function modify the memory of a pointer. * @s: pointer to modify. * @b: character to insert. * @n: number of bytes to modify. * Return: modify buffer. */ char *_memset(char *s, char b, unsigned int n) { unsigned int a; for (a = 0; a < n; a++) s[a] = b; return (s); }
C
/* Date : 14-2-2021 Aim : census structure Source : ansi c e10.12 */ #include <stdio.h> #include <stdlib.h> struct Census { char city[15]; long int population; float literacy; }; void readCities(struct Census c[], int n); void printCity(struct Census[], int); int compareName(const struct Census*, const struct Census*); int comparePopulation(const struct Census*, const struct Census*); int compareLiteracy(const struct Census*, const struct Census*); void sort(struct Census[], int ,int (*compare)(struct Census*, struct Census*)); void main() { struct Census c[5]; int n = 5; readCities(c,n); printf("\nSorted by name alphabeticaly:\n"); sort(c, n, compareName); printCity(c, n); printf("\nSorted by population:\n"); sort(c, n, comparePopulation); printCity(c, n); printf("\nSorted by literacy level:\n"); sort(c, n, compareLiteracy); printCity(c, n); } void readCities(struct Census c[], int n) { int i; for (i = 0; i < n; i++) { printf("Enter %dth city's name, population and literacy level:\n",i+1); fflush(stdin); gets(c[i].city); fflush(stdin); scanf("%ld",&c[i].population); fflush(stdin); scanf("%f",&c[i].literacy); } } void printCity(struct Census c[], int n) { int i; for (i = 0; i < n; i++) { printf("\nCity: %s\n",c[i].city); printf("Population: %ld\n",c[i].population); printf("Literacy level: %.2f\n",c[i].literacy); } } int compareName(const struct Census *c1, const struct Census *c2) { if (c1->city[0] > c2->city[0]) { return 1; } return 0; } int comparePopulation(const struct Census *c1, const struct Census *c2) { if (c1->population > c2->population) { return 1; } return 0; } int compareLiteracy(const struct Census *c1, const struct Census *c2) { if (c1->literacy > c2->literacy) { return 1; } return 0; } void sort(struct Census c[], int n, int (*compare)(struct Census*, struct Census*)) { struct Census temp; int i, j; for (i = 0; i < n; i++) { for (j = 0; j < n-i-1; j++) { if (compare(&c[j], &c[j+1])) { temp = c[j]; c[j] = c[j+1]; c[j+1] = temp; } } } }
C
#include "lcd_1602.h" static void delay_us(uint32_t delay){ delay*=32; while(delay--); } static void lcd_send_4bit(uint8_t data) { /* sending 4-bits to the 4 pins of lcd*/ if(data & 0x10) d4(1); else d4(0); // 0x10 == 0b10000 if(data & 0x20) d5(1); else d5(0); // 0x20 == 0b100000 if(data & 0x40) d6(1); else d6(0); // 0x40 == 0b1000000 if(data & 0x80) d7(1); else d7(0); // 0x80 == 0b10000000 } static void lcd_send(int8_t rs,uint8_t data) { /* sending data to lcd */ rs(rs); /* enable rs if data is to be sent otherwise if it is a command rs is set to zero */ rw(0); /* set rw to zero to make the lcd read data */ lcd_send_4bit(data); /* sending the upper 4 bits */ en(1); /* set enable to 1 */ delay_us(100); /* a delay of 100 us */ en(0); /* get enable signal low again to receive new data */ lcd_send_4bit(data<<4); /* send upper 4 bits of data */ en(1); /*set enable to one*/ delay_us(100); /* a delay of 100 us */ en(0); /*set enable to zero to mark ending of receiving data*/ } void lcd_data(char c) { /* sending charachter to be printed on LCD screen i.e. as data not command */ lcd_send(1,(uint8_t)c); } void lcd_init(void) { /* Initialize the lcd in 4-bits mode (Sending Control Commands) */ lcd_send(0,0x33); //upper 4 bits to initialize in 8bits mode first "That should be done by default" lcd_send(0,0x32); //lower 4 bits to iniitialize in 8bits mode first lcd_send(0,0x28); // iniitialize in 4 bits mode 4-bit mode (2 lines) lcd_send(0,0x0C); // clear the screen and turn the cursor off lcd_send(0,0x06); // increment the cursor "shift it to the right to appear on screen" lcd_send(0,0x01); // clear and display curson on screen } void lcd_clr(void) { /* API to clear the screen */ lcd_send(0,0x01); //sending 0x01 to clear screen HAL_Delay(2); //a delay to give chance for screen to update } void lcd_gotoxy(char x, char y) { /*send commant to move cursor in x and y direction*/ lcd_send(0,0x80+x+(y*0x40)); /*x represents shifting locations from the screen from the left*/ /*y represents shifting locations up and down*/ } void lcd_puts(char *text) { /*sending string to be printed on LCD*/ while(*text) { lcd_data(*text); /*sending charachter by charchter and ensures that sent charachter is identified as data*/ text++; /*point to next charachter in the string*/ } } void lcd_print_start(void) { /* print start menu to user */ HAL_Delay(500); lcd_clr(); lcd_gotoxy(0,0); lcd_puts("1 - Enter Pin"); lcd_gotoxy(0,1); lcd_puts("2 - New Pin"); } void lcd_input_menu (void) { /* asking user to input pin */ lcd_gotoxy(0,0); lcd_puts("Your Pin: "); }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ /* Variables and functions */ int /*<<< orphan*/ sprintf (unsigned char*,char*,unsigned char) ; int strlen (unsigned char*) ; void xpad_cat (unsigned char *fabuf, unsigned long int addr) { int i; unsigned char c; for (i = 0 ; i <= 3 ; ++i) { switch (i) { case (0): c = (unsigned char) ((addr & 0x000000ff) ); break; case (1): c = (unsigned char) ((addr & 0x0000ff00) >> 8); break; case (2): c = (unsigned char) ((addr & 0x00ff0000) >> 16); break; case (3): c = (unsigned char) ((addr & 0xff000000) >> 24); break; } if (c == 0xff) sprintf (fabuf + strlen (fabuf), "%c", c); sprintf (fabuf + strlen (fabuf), "%c", c); } return; }
C
#include "stdio.h" int main() { char palavra[] = "Laranja e muito normal!!!"; int i, array[20] = { 1, 3 }; for (i = 0; palavra[i] != '!'; i++) { printf("%c", palavra[i]); } printf("\n"); return 0; }
C
#include <math.h> #include <assert.h> int isPowerOfThree(int n) { if(n <= 0) return 0; int MAX_POWER_OF_THREE = (int)pow(3, 19); if(MAX_POWER_OF_THREE % n ==0) return 1; return 0; } int main() { assert(isPowerOfThree(-3) == 0); assert(isPowerOfThree(27) == 1); assert(isPowerOfThree(0) == 0); return 0; }
C
#include "brian.h" VOID PrintLargeInteger ( IN PLARGE_INTEGER LargeInt ) { printf( "%08lx:%08lx", LargeInt->HighPart, LargeInt->LowPart ); return; } ULONG AsciiToInteger ( IN PCHAR Ascii ) { BOOLEAN DoHex = FALSE; LONG Integer = 0; PCHAR c; while (*Ascii) { if (Integer == 0 && (*Ascii == 'x' || *Ascii == 'X')) { DoHex = TRUE; } else { if (DoHex) { *Ascii = (CHAR) toupper( *Ascii ); if (*Ascii < '0' || (*Ascii > '9' && (*Ascii < 'A' || *Ascii > 'F'))) { break; } Integer *= 16; Integer += ( *Ascii - ( *Ascii > '9' ? ('A' - 10) : '0' )); } else { if (*Ascii < '0' || *Ascii > '9') { break; } Integer *= 10; Integer += (*Ascii - '0'); } } Ascii++; } return Integer; } ULONGLONG AsciiToLargeInteger ( IN PCHAR Ascii ) { BOOLEAN DoHex = FALSE; ULONGLONG Integer = 0; PCHAR c; while (*Ascii) { if (Integer == 0 && (*Ascii == 'x' || *Ascii == 'X')) { DoHex = TRUE; } else { if (DoHex) { *Ascii = (CHAR) toupper( *Ascii ); if (*Ascii < '0' || (*Ascii > '9' && (*Ascii < 'A' || *Ascii > 'F'))) { break; } Integer *= 16; Integer += ( *Ascii - ( *Ascii > '9' ? ('A' - 10) : '0' )); } else { if (*Ascii < '0' || *Ascii > '9') { break; } Integer *= 10; Integer += (*Ascii - '0'); } } Ascii++; } return Integer; }
C
// Copyright (c) 2015 Nuxi, https://nuxi.nl/ // // SPDX-License-Identifier: BSD-2-Clause #include <errno.h> #include <pthread.h> #include <stdbool.h> #include <testing.h> #include <time.h> TEST(pthread_cond_timedwait, timedout) { pthread_mutex_t mutex; ASSERT_EQ(0, pthread_mutex_init(&mutex, NULL)); pthread_cond_t cond; ASSERT_EQ(0, pthread_cond_init(&cond, NULL)); // Attempt to wait on a timestamp that has already passed. ASSERT_EQ(0, pthread_mutex_lock(&mutex)); struct timespec ts = {.tv_sec = 1422982367}; ASSERT_EQ(ETIMEDOUT, pthread_cond_timedwait(&cond, &mutex, &ts)); ASSERT_EQ(0, pthread_mutex_unlock(&mutex)); ASSERT_EQ(0, pthread_cond_destroy(&cond)); ASSERT_EQ(0, pthread_mutex_destroy(&mutex)); } struct block { pthread_mutex_t mutex; pthread_cond_t cond; bool okay; }; static void *do_timedwait(void *arg) { // We must receive the signal within one second. struct timespec ts; ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts)); ++ts.tv_sec; struct block *block = arg; ASSERT_EQ(0, pthread_mutex_lock(&block->mutex)); while (!block->okay) ASSERT_EQ(0, pthread_cond_timedwait(&block->cond, &block->mutex, &ts)); ASSERT_EQ(0, pthread_mutex_unlock(&block->mutex)); return NULL; } static void do_sleep(void) { struct timespec ts = {.tv_sec = 0, .tv_nsec = 100000000L}; ASSERT_EQ(0, clock_nanosleep(CLOCK_MONOTONIC, 0, &ts)); } TEST(pthread_cond_timedwait, signalled) { // Let a single thread wait on the condition variable. struct block block; ASSERT_EQ(0, pthread_mutex_init(&block.mutex, NULL)); ASSERT_EQ(0, pthread_cond_init(&block.cond, NULL)); block.okay = false; pthread_t thread; ASSERT_EQ(0, pthread_create(&thread, NULL, do_timedwait, &block)); do_sleep(); // Call pthread_cond_signal() while holding the lock. ASSERT_EQ(0, pthread_mutex_lock(&block.mutex)); block.okay = true; ASSERT_EQ(0, pthread_cond_signal(&block.cond)); ASSERT_EQ(0, pthread_mutex_unlock(&block.mutex)); ASSERT_EQ(0, pthread_join(thread, NULL)); ASSERT_EQ(0, pthread_mutex_destroy(&block.mutex)); ASSERT_EQ(0, pthread_cond_destroy(&block.cond)); }
C
#include<stdio.h> #include<stdlib.h> struct Date { int day; int month; int year; }; struct Student { int st_roll_number; float st_marks; float st_attendance; struct Date st_date_of_birth; }; /*definition of instance variable*/ struct Student s1={10,56.78,80.96,{23,4,1995}}; /*Definition of instance of struct Date*/ struct Date d1={27,3,2021}; /*Following expressions can be used on RHS to read and on LHS to write s1.st_roll_number s1.st_marks s1.st_attendance s1.st_date_of_birth.day s1.st_date_of_birth.month s1.st_date_of_birth.year */ /*General Syntax of pointer variable: T* p; T=struct Date / struct Student int *p = &n; p -> pointer to int ->int* *p ->int */ struct Student *p_student; /* definition of pointer variable*/ struct Date *p_date; /*definition of pointer to struct Date*/ int main(void) { /*put address of instance variable to pointer variable*/ p_student = &s1; /* typeof(p_student)=struct Student* typeof(*p_student)=struct Student */ /* RHS - read */ printf("roll number(s1):%d\n",(*p_student).st_roll_number); printf("marks(s1):%.2f\n",(*p_student).st_marks); printf("attendance(s1):%.2f\n",(*p_student).st_attendance); printf("date of birth(s1):%d-%d-%d\n",(*p_student).st_date_of_birth.day, (*p_student).st_date_of_birth.month, (*p_student).st_date_of_birth.year); /*LHS - write*/ (*p_student).st_roll_number=67; (*p_student).st_marks=45.68; (*p_student).st_attendance=98.67; (*p_student).st_date_of_birth.day=21; (*p_student).st_date_of_birth.month=7; (*p_student).st_date_of_birth.year=2020; /*RHS - read*/ printf("roll number(s1):%d\n",(*p_student).st_roll_number); printf("marks(s1):%.2f\n",(*p_student).st_marks); printf("attendance(s1):%.2f\n",(*p_student).st_attendance); printf("date of birth(s1):%d-%d-%d\n",(*p_student).st_date_of_birth.day, (*p_student).st_date_of_birth.month, (*p_student).st_date_of_birth.year); p_date=&d1; /* put address of instance variable of struct Date into pointer to struct Date*/ printf("%d-%d-%d\n",p_date->day, p_date->month, p_date->year); /* p_date->day == (*p_date).day p_date->month == (*p_date).month p_date->year == (*p_date).year */ p_date->day=20; p_date->month=4; p_date->year=2022; printf("%d-%d-%d\n",p_date->day, p_date->month, p_date->year); return(0); }
C
#include <stdio.h> #include <windows.h> #include <conio.h> void clrscr(int x, int y, char c); // ڸ ϴ ڷ ä void gotoxy(int x, int y); // move cursor to (x, y) #define ScreenWidth 80 #define ScreenHeight 24 // Relative coordinate with respect to the center position int Block_x[4][4] = { // x coordinates { -1, 0, 0, 1}, // dir 0 { -1, 0, 0, 0}, // dir 1 { -1, 0, 0, 1}, // dir 2 { 0, 0, 0, 1} // dir 3 }; int Block_y[4][4] = { // y coordinates { 0, 0, -1, 0}, // dir 0 { 0, 0, 1, -1}, // dir 1 { 0, 0, 1, 0}, // dir 2 { -1, 0, 1, 0} // dir 3 }; void DrawBoundary(); void DrawBlock(int x, int y, int dir, char c); int main() { int x = ScreenWidth / 2, y = ScreenHeight / 2; int dir = 0; int oldx = -1, oldy = -1; int oldDir = -1; char key = 0; DrawBoundary(); DrawBlock(x, y, dir, 'O'); while(key != 27){ // ESC // save old coordinates and direction oldx = x, oldy = y; oldDir = dir; // read a key using getch() key = getch(); // update x, y, and dir according to the key switch(key){ //̵ case'i': if(dir==2){ if(y>2) y--;} else if(y>3) y--; break; case'j': if(dir==3){ if(x>2) x--;} else if(x>3) x--; break; case'k': if(dir==0){ if(y<23) y++;} else if(y<22) y++; break; case'l': if(dir==1){ if(x<79) x++;} else if(x<78) x++; break; //ȸ case'u': if(y==23||y==2) break; if(x==2||x==79) break; dir = (dir+1)%4; break; case'o': if(y==23||y==2) break; if(x==2||x==79) break; dir = (dir+3)%4; break; } DrawBlock(oldx, oldy, oldDir, ' '); // erase previous shape DrawBlock(x, y, dir, 'O'); // draw the shape using new coordinates and direction } return 0; } void DrawBoundary() { int i; for(i=1;i<25;i++) clrscr(1,i,'0'); for(i=1;i<25;i++) clrscr(80,i,'0'); for(i=1;i<81;i++) clrscr(i,1,'0'); for(i=1;i<81;i++) clrscr(i,24,'0'); return; } void DrawBlock(int x, int y, int dir, char c) // Draw the shape of a direction at (x, y) // c is the symbol to draw // If c == 'O', draw the shape. // If c == ' ', erase the shape. { int i=0; for(i=0; i<4; i++) { gotoxy(x + Block_x[dir][i], y + Block_y[dir][i]); putchar(c); } return; } void clrscr(int x, int y, char c) // ڸ ϴ ä { COORD Cur = {x - 1, y - 1}; unsigned long dwLen = 0; FillConsoleOutputCharacter(GetStdHandle(STD_OUTPUT_HANDLE), c, 1, Cur, &dwLen); } void gotoxy(int x, int y) // move cursor to (x, y) { COORD Pos = {x - 1, y - 1}; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), Pos); }
C
//Created by Rahul Goel #include <stdio.h> #include <math.h> const double pr = 0.00000001; const double pi = 3.141592653589; int main() { double a, h, x; scanf("%lf %lf %lf", &a, &h, &x); if(x<pr) printf("%0.10lf\n", 180.0); else if((double)x - (double)a*a*h/2 > -pr) { double value = (double)(2*h*a*a - 2*x)/(a*a*a); double start = 0, end = 90, guess; while(fabs(value - (double)tan(guess*pi/180))>pr) { guess = (start+end)/2; if(value-(double)tan(guess*pi/180)>=pr) start = guess; else end = guess; } printf("%0.10lf\n", guess); } else { double value = (double)(h*h*a)/(2*x); double start = 0, end = 90, guess; while(fabs(value - tan(guess*pi/180))>pr) { guess = (start+end)/2; if(value-tan(guess*pi/180)>=pr) start = guess; else end = guess; } printf("%0.10lf\n", guess); } return 0; }
C
#include<stdio.h> #include<unistd.h> #include<string.h> #include<stdlib.h> #include<errno.h> #include<sys/socket.h> #include<arpa/inet.h> #define MAXBUF 1024 #define QUEUE_NO 5 int main(int argc,char **argv){ int sockfd,clientfd,port,int_to_receive,int_to_send,two_x,x_sq,sum; struct sockaddr_in s_addr,c_addr; char buffer[MAXBUF]; printf("bhawana\n"); printf("CSIT\n"); printf("1841017103\n"); socklen_t socklen=(socklen_t)sizeof(struct sockaddr_in); if(argc<2) { printf("some of commandline arguments missing"); return -1; } sockfd=socket(AF_INET,SOCK_STREAM,0); if(sockfd ==-1){ printf("socket creation failed"); exit(errno); } printf("socket successfully created\n"); bzero(&s_addr,sizeof(s_addr)); s_addr.sin_family=AF_INET; port=atoi(argv[1]); s_addr.sin_port=htons(port); s_addr.sin_addr.s_addr=INADDR_ANY; if(bind(sockfd,(struct sockaddr*)&s_addr,sizeof(s_addr))!=0){ printf("socket creation failed..\n"); exit(errno); } if(listen(sockfd,QUEUE_NO)!=0){ printf("socketlisten..\n"); exit(errno); } clientfd=accept(sockfd,(struct sockaddr*)&c_addr,&socklen); printf("%s : %d connected\n",inet_ntoa(c_addr.sin_addr),ntohs(c_addr.sin_port)); read(clientfd,&int_to_receive,sizeof(int_to_receive)); printf("recieved from client: %d\n",int_to_receive); x_sq=int_to_receive*int_to_receive; two_x=2*int_to_receive; write(clientfd,&two_x,sizeof(two_x)); write(clientfd,&x_sq,sizeof(x_sq)); read(clientfd,&sum,sizeof(sum)); printf("sumof x2 and 2x recieved from client= %d\n",sum); close(clientfd); close(sockfd); return 0; }
C
#include<stdio.h> int main() { int i,count=0; char s[100]; gets(s); for(i=0;s[i]!=0;i++) { if(s[i]==' ') count=++count; else count=count; } printf("number of spaces:%d",count); return 0; }
C
#include <stdio.h> int fact(int n){ int i=0,fact=1; for(i=1;i<n+1;i++){ fact=fact*i; } return fact; } int main(){ int f,n; scanf("%d",&n); f=fact(n); printf("%d",f); return 1; }
C
#include "allonet/math.h" #include <math.h> #include <stdlib.h> #include <stdio.h> #include "mathc.h" allo_vector allo_vector_subtract(allo_vector l, allo_vector r) { return (allo_vector){{ l.x - r.x, l.y - r.y, l.z - r.z }}; } allo_vector allo_vector_add(allo_vector l, allo_vector r) { return (allo_vector) {{ l.x + r.x, l.y + r.y, l.z + r.z }}; } allo_vector allo_vector_mul(allo_vector l, allo_vector r) { return (allo_vector) {{ l.x * r.x, l.y * r.y, l.z * r.z }}; } extern allo_vector allo_vector_scale(allo_vector l, double r) { return (allo_vector) {{ l.x* r, l.y* r, l.z* r }}; } allo_vector allo_vector_div(allo_vector l, allo_vector r) { return (allo_vector) {{ l.x / r.x, l.y / r.y, l.z / r.z }}; } allo_vector allo_vector_normalize(allo_vector l) { float len = allo_vector_length(l); return len == 0.0 ? l : allo_vector_scale(l, 1.0 / len); } double allo_vector_dot(allo_vector l, allo_vector r) { return l.x * r.x + l.y * r.y + l.z * r.z; } double allo_vector_length(allo_vector l) { return sqrt(allo_vector_dot(l, l)); } double allo_vector_angle(allo_vector l, allo_vector r) { return acos(allo_vector_dot(l, r) / (allo_vector_length(l) * allo_vector_length(r))); } static const allo_m4x4 static_identity = {{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }}; allo_m4x4 allo_m4x4_identity() { return static_identity; } bool allo_m4x4_is_identity(allo_m4x4 m) { for(int i = 0; i < 16; i++) { if(m.v[i] != static_identity.v[i]) { return false; } } return true; } allo_m4x4 allo_m4x4_translate(allo_vector t) { return (allo_m4x4) {{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, t.x, t.y, t.z, 1 }}; } allo_m4x4 allo_m4x4_rotate(double phi, allo_vector axis) { // http://www.opengl-tutorial.org/assets/faq_quaternions/index.html#Q26 allo_m4x4 m = allo_m4x4_identity(); double rcos = cos(phi); double rsin = sin(phi); double u = axis.x, v = axis.y, w = axis.z; m.c1r1 = rcos + u * u * (1 - rcos); m.c1r2 = w * rsin + v * u * (1 - rcos); m.c1r3 = -v * rsin + w * u * (1 - rcos); m.c2r1 = -w * rsin + u * v * (1 - rcos); m.c2r2 = rcos + v * v * (1 - rcos); m.c2r3 = u * rsin + w * v * (1 - rcos); m.c3r1 = v * rsin + u * w * (1 - rcos); m.c3r2 = -u * rsin + v * w * (1 - rcos); m.c3r3 = rcos + w * w * (1 - rcos); return m; } #define rc(m, r, c) m.v[r*4 + c] allo_m4x4 allo_m4x4_concat(allo_m4x4 a, allo_m4x4 b) { allo_m4x4 m = allo_m4x4_identity(); mat4_multiply(m.v, a.v, b.v); return m; // this code is wrong?? for (int r = 0; r <= 3; r++) { for (int c = 0; c <= 3; c++) { rc(m, r, c) = rc(a, r, 0) * rc(b, 0, c) + rc(a, r, 1) * rc(b, 1, c) + rc(a, r, 2) * rc(b, 2, c) + rc(a, r, 3) * rc(b, 3, c); } } return m; } extern allo_m4x4 allo_m4x4_add(allo_m4x4 l, allo_m4x4 r) { allo_m4x4 m; for (int i = 0; i < 16; i++) { m.v[i] = l.v[i] + r.v[i]; } return m; } extern allo_m4x4 allo_m4x4_scalar_multiply(allo_m4x4 l, double r) { allo_m4x4 m; for (int i = 0; i < 16; i++) { m.v[i] = l.v[i] * r; } return m; } extern allo_m4x4 allo_m4x4_interpolate(allo_m4x4 l, allo_m4x4 r, double fraction) { return allo_m4x4_add(allo_m4x4_scalar_multiply(l, fraction), allo_m4x4_scalar_multiply(r, 1.0 - fraction)); } extern allo_m4x4 allo_m4x4_inverse(allo_m4x4 ma) { allo_m4x4 out; mat4_inverse(out.v, ma.v); return out; // this code seems to be correct, but I'm gonna use theirs anyway. double *m = ma.v; double* inv = out.v; inv[0] = m[5] * m[10] * m[15] - m[5] * m[11] * m[14] - m[9] * m[6] * m[15] + m[9] * m[7] * m[14] + m[13] * m[6] * m[11] - m[13] * m[7] * m[10]; inv[4] = -m[4] * m[10] * m[15] + m[4] * m[11] * m[14] + m[8] * m[6] * m[15] - m[8] * m[7] * m[14] - m[12] * m[6] * m[11] + m[12] * m[7] * m[10]; inv[8] = m[4] * m[9] * m[15] - m[4] * m[11] * m[13] - m[8] * m[5] * m[15] + m[8] * m[7] * m[13] + m[12] * m[5] * m[11] - m[12] * m[7] * m[9]; inv[12] = -m[4] * m[9] * m[14] + m[4] * m[10] * m[13] + m[8] * m[5] * m[14] - m[8] * m[6] * m[13] - m[12] * m[5] * m[10] + m[12] * m[6] * m[9]; inv[1] = -m[1] * m[10] * m[15] + m[1] * m[11] * m[14] + m[9] * m[2] * m[15] - m[9] * m[3] * m[14] - m[13] * m[2] * m[11] + m[13] * m[3] * m[10]; inv[5] = m[0] * m[10] * m[15] - m[0] * m[11] * m[14] - m[8] * m[2] * m[15] + m[8] * m[3] * m[14] + m[12] * m[2] * m[11] - m[12] * m[3] * m[10]; inv[9] = -m[0] * m[9] * m[15] + m[0] * m[11] * m[13] + m[8] * m[1] * m[15] - m[8] * m[3] * m[13] - m[12] * m[1] * m[11] + m[12] * m[3] * m[9]; inv[13] = m[0] * m[9] * m[14] - m[0] * m[10] * m[13] - m[8] * m[1] * m[14] + m[8] * m[2] * m[13] + m[12] * m[1] * m[10] - m[12] * m[2] * m[9]; inv[2] = m[1] * m[6] * m[15] - m[1] * m[7] * m[14] - m[5] * m[2] * m[15] + m[5] * m[3] * m[14] + m[13] * m[2] * m[7] - m[13] * m[3] * m[6]; inv[6] = -m[0] * m[6] * m[15] + m[0] * m[7] * m[14] + m[4] * m[2] * m[15] - m[4] * m[3] * m[14] - m[12] * m[2] * m[7] + m[12] * m[3] * m[6]; inv[10] = m[0] * m[5] * m[15] - m[0] * m[7] * m[13] - m[4] * m[1] * m[15] + m[4] * m[3] * m[13] + m[12] * m[1] * m[7] - m[12] * m[3] * m[5]; inv[14] = -m[0] * m[5] * m[14] + m[0] * m[6] * m[13] + m[4] * m[1] * m[14] - m[4] * m[2] * m[13] - m[12] * m[1] * m[6] + m[12] * m[2] * m[5]; inv[3] = -m[1] * m[6] * m[11] + m[1] * m[7] * m[10] + m[5] * m[2] * m[11] - m[5] * m[3] * m[10] - m[9] * m[2] * m[7] + m[9] * m[3] * m[6]; inv[7] = m[0] * m[6] * m[11] - m[0] * m[7] * m[10] - m[4] * m[2] * m[11] + m[4] * m[3] * m[10] + m[8] * m[2] * m[7] - m[8] * m[3] * m[6]; inv[11] = -m[0] * m[5] * m[11] + m[0] * m[7] * m[9] + m[4] * m[1] * m[11] - m[4] * m[3] * m[9] - m[8] * m[1] * m[7] + m[8] * m[3] * m[5]; inv[15] = m[0] * m[5] * m[10] - m[0] * m[6] * m[9] - m[4] * m[1] * m[10] + m[4] * m[2] * m[9] + m[8] * m[1] * m[6] - m[8] * m[2] * m[5]; double det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12]; if (det == 0) return allo_m4x4_identity(); det = 1.0 / det; for (int i = 0; i < 16; i++) out.v[i] = inv[i] * det; return out; } allo_vector allo_m4x4_transform(allo_m4x4 l, allo_vector r, bool positional) { return (allo_vector) {{ l.c1r1 * r.x + l.c2r1 * r.y + l.c3r1 * r.z + l.c4r1 * positional, l.c1r2 * r.x + l.c2r2 * r.y + l.c3r2 * r.z + l.c4r2 * positional, l.c1r3 * r.x + l.c2r3 * r.y + l.c3r3 * r.z + l.c4r3 * positional }}; } extern allo_vector allo_m4x4_get_position(allo_m4x4 l) { return allo_m4x4_transform(l, (allo_vector) {{ 0, 0, 0 }}, true); } extern allo_rotation allo_m4x4_get_rotation(allo_m4x4 l) { allo_rotation rot; double* m = l.v; rot.axis = allo_vector_normalize((allo_vector) {{ m[6] - m[9], m[8] - m[2], m[1] - m[4] }}); allo_vector lengths = {{ vec3_length(m + 0), vec3_length(m + 4), vec3_length(m + 8) }}; allo_vector diagonal = {{ m[0], m[5], m[10] }}; allo_vector scaled_diagonal = allo_vector_div(diagonal, lengths); rot.angle = acosf((scaled_diagonal.x + scaled_diagonal.y + scaled_diagonal.z - 1.) / 2.); return rot; } bool allo_m4x4_equal(allo_m4x4 a, allo_m4x4 b, double sigma) { for (int i = 0; i < 16; i++) if (fabs(a.v[i] - b.v[i]) > sigma) return false; return true; } extern char *allo_m4x4_string(allo_m4x4 m) { char *s = malloc(255); snprintf(s, 255, "\t%+.2f %+.2f %+.2f %+.2f\n\t%+.2f %+.2f %+.2f %+.2f\n\t%+.2f %+.2f %+.2f %+.2f\n\t%+.2f %+.2f %+.2f %+.2f", m.c1r1, m.c2r1, m.c3r1, m.c4r1, m.c1r2, m.c2r2, m.c3r2, m.c4r2, m.c1r3, m.c2r3, m.c3r3, m.c4r3, m.c1r4, m.c2r4, m.c3r4, m.c4r4 ); return s; } extern char *allo_vec_string(allo_vector l) { char *s = malloc(40); snprintf(s, 40, "%.2f %.2f %.2f", l.x, l.y, l.z ); return s; }
C
/* Written by Sam Keller, Simon Montague, and Will Herold Written on 10/25/2011 This is our main function that tests our parser */ #include <stdio.h> #include <stdlib.h> #include "parser.h" int main(){ //make a linked list LinkedList* tokens = malloc(sizeof(LinkedList)); LinkedList* tokenized = malloc(sizeof(LinkedList)); LinkedList* parseTree = malloc(sizeof(LinkedList)); LinkedList* leftoverTokens = NULL; int depth = 0; int depthCopy = 0; char *expression = malloc(256 * sizeof(char)); // go through the expression and tokenize it! while (fgets(expression, 256, stdin)){ tokenized = tokenize(expression); tokenized = ReverseIt(tokenized); tokens = append(leftoverTokens, tokenized); parseTree = parse(tokens, &depth); parseTree = ReverseIt(parseTree); //if the depth is less than zero, return a closed email if (depth < 0) { printf("syntax error: too many closed parens\n"); // Too many close parentheses. enum ERROR_TYPE closedError = tooManyClosed; return closedError; // if the depth is greater than zero, keep going } else if (depth > 0) { // There are more open parens than close parens, so these tokens are saved as leftovers. leftoverTokens = tokens; depthCopy = depth; depth = 0; }else { ConsCell* current = parseTree->head; depthCopy = 0; while (current != NULL){ printValue(current->car); current = current->cdr; } leftoverTokens = NULL; } } // if, at the end, we have too few closed parens, return an error. if (depthCopy > 0) { printf("syntax error: too few closed parens\n"); // Too few close parens at end of input. enum ERROR_TYPE closedError = tooFewClosed; return closedError; } printf("\n"); //This is just for asthetics in the terminal. free(expression); return 0; }
C
#include "frames.h" #include "bits.h" #include "stream.h" #include <string.h> void frames_init(frames_t* frames) { buffer_init(&(frames->buffer), sizeof(frame_t)); } void frames_release(frames_t* frames) { buffer_release(&(frames->buffer)); } void frames_add(frames_t* frames, const frame_t* in) { frame_t* temp = buffer_alloc(&(frames->buffer), 1); memcpy(temp, in, sizeof(frame_t)); } static uint32_t ti_compress(tile_index_t index, size_t bits) { uint32_t flags = (index & TILE_BITS_MASK) >> (32 - bits); uint32_t in = index & ~TILE_BITS_MASK; uint32_t out = index & (~0U >> (32-(bits-3))); uint32_t result = out | flags; return result; } static tile_index_t ti_uncompress(uint32_t in, size_t bits) { uint32_t flags = (in & (TILE_BITS_MASK >> (32 - bits))) << (32 - bits); uint32_t out = in & (~TILE_BITS_MASK) >> (32 - bits); uint32_t result = out | flags; return result; } size_t frames_load(const buffer_t* in, size_t offset, size_t count, frames_t* frames, size_t tile_bits) { frame_t last; memset(&last, 0xff, sizeof(last)); for (size_t i = 0; i < count; ++i) { frame_t* frame = buffer_alloc(&(frames->buffer), 1); frame_header_t header; memcpy(&header, buffer_get(in, offset), sizeof(header)); offset += sizeof(header); header.size = u16be(header.size); bits_t fbits; bits_init_read(&fbits, buffer_get(in, offset), header.size); offset += header.size; fprintf(stderr, "Loading frame %ld, %d bytes (%d bits per tile index)\n", i, header.size, tile_bits); for (size_t j = 0; j < FRAME_TILE_COUNT;) { uint8_t header = bits_read(&fbits, 8); uint8_t length = (header & 0x7f) + 1; if (header & 0x80) { memcpy(&(frame->tiles[j]), &(last.tiles[j]), length * sizeof(tile_index_t)); } else { for (size_t k = 0; k < length; ++k) { frame->tiles[j + k] = ti_uncompress(bits_read(&fbits, tile_bits), tile_bits); } } j += length; } last = *frame; } return offset; } void frames_save(buffer_t* out, const frames_t* frames, size_t tile_bits) { frame_t last; memset(&last, 0xff, sizeof(last)); bits_t fbits; bits_init_write(&fbits); for (size_t i = 0, n = buffer_count(&(frames->buffer)); i < n; ++i) { bits_reset(&fbits); const frame_t* curr = buffer_get(&(frames->buffer), i); const tile_index_t* li = last.tiles; const tile_index_t* ci = curr->tiles; const tile_index_t* first = NULL; int skipping = 0; for (size_t i = 0; i < (FRAME_WIDTH / TILE_WIDTH) * (FRAME_HEIGHT / TILE_HEIGHT); ++i, ++li, ++ci) { if (first && (ci - first) == 128) { uint8_t length = ((uint8_t)(ci - first))-1; if (skipping) { bits_write(&fbits, length|0x80, 8); } else { bits_write(&fbits, length, 8); for (; first < ci; ++first) bits_write(&fbits, ti_compress(*first, tile_bits), tile_bits); } first = NULL; skipping = 0; } if (!first) { first = ci; skipping = (*ci == *li) ? 1 : 0; } else { uint8_t length = ((uint8_t)(ci - first))-1; if (skipping && (*ci != *li)) { bits_write(&fbits, length|0x80, 8); first = ci; skipping = 0; } else if (!skipping && (*ci == *li)) { bits_write(&fbits, length, 8); for (; first < ci; ++first) bits_write(&fbits, ti_compress(*first, tile_bits), tile_bits); first = ci; skipping = 1; } } } if (first) { uint8_t length = ((uint8_t)(ci - first))-1; if (skipping) { bits_write(&fbits, length|0x80, 8); } else { bits_write(&fbits, length, 8); for (; first < ci; ++first) bits_write(&fbits, ti_compress(*first, tile_bits), tile_bits); } } bits_flush(&fbits); frame_header_t fheader; fheader.size = u16be(fbits.buf.size); buffer_add(out, &fheader, sizeof(frame_header_t)); buffer_add(out, fbits.buf.data, fbits.buf.size); memcpy(&last, curr, sizeof(frame_t)); } bits_release(&fbits); } void frames_remap_tiles(frames_t* frames, const tile_index_t* remaps) { for (size_t i = 0, n = buffer_count(&(frames->buffer)); i < n; ++i) { frame_t* frame = buffer_get(&(frames->buffer), i); for (size_t j = 0; j < FRAME_TILE_COUNT; ++j) { uint32_t in = frame->tiles[j]; uint32_t remap = remaps[(in & ~TILE_BITS_MASK)]; uint32_t out = (remap & ~TILE_BITS_MASK) | ((remap & TILE_BITS_MASK)^(in & TILE_BITS_MASK)); frame->tiles[j] = out; } } }
C
/** * @file ler_interface.h * @author André Santos, Helena Alves, Ricardo Branco * @date ?? */ #ifndef _LER_LOCALIDADE_H #define _LER_LOCALIDADE_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include "erros.h" #include "lista_ligada.h" #include "tabela_hash.h" #include "interface.h" #include "interaccao.h" #include "clientes.h" /** * A funcão 'ler_localidade' imprime no ecrã as informações necessária para inserir localidades e, posteriormente, lê as localidades que o utilizador quer inserir e depois insere-as, caso seja possível, através de uma função auxiliar. * @param 'listas' Tabela de Hash. */ int ler_localidade (THash*** listas); /** * A funcão 'remove_localidade' imprime no ecrã as informações necessária para remover localidades e, posteriormente, lê as localidades que o utilizador quer remover e depois remove-as, caso seja possível, através de uma função auxiliar. * @param 'listas' Tabela de Hash. */ int remove_localidade (THash*** listas); /** * A funcão 'ins_lig_localidade' imprime no ecrã as informações necessária para inserir ligações entre localidades e, posteriormente, lê as novas ligações que o utilizador quer inserir e depois insere-as, caso seja possível, através de uma função auxiliar. * @param 'listas' Tabela de Hash. */ int ins_lig_localidades (THash*** listas); /** * A funcão 'rem_lig_localidade' imprime no ecrã as informações necessária para remover ligações entre localidades e, posteriormente, lê as ligações que o utilizador quer remover e depois remove-as, caso seja possível, através de uma função auxiliar. * @param 'listas' Tabela de Hash. */ int rem_lig_localidades (THash*** listas); /** * A funcão 'edit_lig_localidade' imprime no ecrã as informações necessária para editar ligações entre localidades e, posteriormente, lê as modificações que o utilizador quer inserir e depois insere-as, caso seja possível, através de uma função auxiliar. * @param 'listas' Tabela de Hash. */ int edit_lig_localidades (THash*** listas); /** * A funcão 'ins_camiao' imprime no ecrã as informações necessária para inserir camiões e, posteriormente, lê os camiões que o utilizador quer inserir e depois insere-os, caso seja possível, através de uma função auxiliar. * @param 'listas' Tabela de Hash. */ int ins_camiao (THash*** listas); /** * A funcão 'rem_camiao' imprime no ecrã as informações necessária para remover camiões e, posteriormente, lê os camiões que o utilizador quer remover e depois remove-os, caso seja possível, através de uma função auxiliar. * @param 'listas' Tabela de Hash. */ int rem_camiao (THash*** listas); /** * A funcão 'edit_camiao' imprime no ecrã as informações necessária para editar camiões e, posteriormente, lê as modificações que o utilizador quer inserir e depois insere-as, caso seja possível, através de uma função auxiliar. * @param 'listas' Tabela de Hash. */ int edit_camiao (THash*** listas); /** * A funcão 'rem_clientes' imprime no ecrã as informações necessária para remover clientes e, posteriormente, lê os clientes que o utilizador quer remover e depois remove-os, caso seja possível, através de uma função auxiliar. * @param 'listas' Tabela de Hash. */ int rem_cliente (THash*** listas); /** * A funcão 'ins_clientes' imprime no ecrã as informações necessária para inserir clientes e, posteriormente, lê os clientes que o utilizador quer inserir e depois insere-os, caso seja possível, através de uma função auxiliar. * @param 'listas' Tabela de Hash. */ int ins_clientes (THash*** listas); /** * A funcão 'edit_clientes' imprime no ecrã as informações necessária para editar clientes e, posteriormente, lê as caracteristicas dos clientes que o utilizador quer editar e depois altera os campos do cliente, caso seja possível, através de uma função auxiliar. * @param 'listas' Tabela de Hash. */ int edit_clientes (THash*** listas); /** * A funcão 'procura_clientesc' Função que procura um cliente por numero de contribuinte * @param 'listas' Tabela de Hash. */ int procura_clientesc (THash*** listas); /** * A funcão 'procura_clientesn' Função que procura um cliente por nome. * @param 'listas' Tabela de Hash. */ int procura_clientesn (THash*** listas); /** * A funcão 'ins_pedido' imprime no ecrã as informações necessárias para inserir um pedido e, posteriormente, lê o pediso que o utilizador quer inserir e depois insere-os, caso seja possível, através de uma função auxiliar. * @param 'listas' Tabela de Hash. */ int ins_pedido (THash*** listas); /** * A funcão 'sair' * @param 'listas' Tabela de Hash. */ int sair(THash*** listas); /** * A funcão 'procura_camioesm' imprime no ecrã as informações necessárias para procurar um camião e, posteriormente, lê o camião que o utilizador quer procurar e depois apresenta as suas informações, caso seja possível, através de uma função auxiliar. * @param 'listas' Tabela de Hash. */ int procura_camioesm (THash*** listas); /** * A funcão 'procura_localidadesid' imprime no ecrã as informações necessárias para procurar uma localidade e, posteriormente, lê a localidade que o utilizador quer procurar e depois apresenta as suas informações, caso seja possível, através de uma função auxiliar. * @param 'listas' Tabela de Hash. */ int procura_localidadesid (THash*** listas); /** * A funcão 'procura_pedido' imprime no ecrã as informações necessárias para procurar um pedido e, posteriormente, lê o pedido que o utilizador quer procurar e depois apresenta as suas informações, caso seja possível, através de uma função auxiliar. * @param 'listas' Tabela de Hash. */ int procura_pedido (THash*** listas); #endif
C
// MDULE LOCATION // /sys/module/<module_name>/parameters // example: echo "1">/sys/module/simple/parameters/debug #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #define PID_LOCATION "/sys/module/signal_module/parameters/pid" #define BUFF_LEN 100 int main() { int fd; char buffer[BUFF_LEN]; int read_count; fd = open(PID_LOCATION, O_RDONLY); read_count = read(fd, buffer, BUFF_LEN); if (read_count > 0) { printf("%s", buffer); } else { printf("Nothing to print\n"); } close(fd); }
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_2__ TYPE_1__ ; /* Type definitions */ struct ExtInstruction {char flags; char* name; } ; struct ExtAuxRegister {char* name; unsigned char address; struct ExtAuxRegister* next; } ; struct TYPE_2__ {char** coreRegisters; char** condCodes; struct ExtAuxRegister* auxRegisters; struct ExtInstruction** instructions; } ; /* Variables and functions */ #define EXT_AUX_REGISTER 131 #define EXT_COND_CODE 130 #define EXT_CORE_REGISTER 129 #define EXT_INSTRUCTION 128 TYPE_1__ arc_extension_map ; int /*<<< orphan*/ cleanup_ext_map () ; scalar_t__ malloc (int) ; int /*<<< orphan*/ strcpy (char*,char*) ; scalar_t__ xmalloc (int) ; int arcExtMap_add(void *base, unsigned long length) { unsigned char *block = base; unsigned char *p = block; /* Clean up and reset everything if needed. */ cleanup_ext_map(); while (p && p < (block + length)) { /* p[0] == length of record p[1] == type of record For instructions: p[2] = opcode p[3] = minor opcode (if opcode == 3) p[4] = flags p[5]+ = name For core regs and condition codes: p[2] = value p[3]+ = name For aux regs: p[2..5] = value p[6]+ = name (value is p[2]<<24|p[3]<<16|p[4]<<8|p[5]) */ if (p[0] == 0) return -1; switch (p[1]) { case EXT_INSTRUCTION: { char opcode = p[2]; char minor = p[3]; char * insn_name = (char *) xmalloc(( (int)*p-5) * sizeof(char)); struct ExtInstruction * insn = (struct ExtInstruction *) xmalloc(sizeof(struct ExtInstruction)); if (opcode==3) opcode = 0x1f - 0x10 + minor - 0x09 + 1; else opcode -= 0x10; insn -> flags = (char) *(p+4); strcpy (insn_name, (char *) (p+5)); insn -> name = insn_name; arc_extension_map.instructions[(int) opcode] = insn; } break; case EXT_CORE_REGISTER: { char * core_name = (char *) xmalloc(((int)*p-3) * sizeof(char)); strcpy(core_name, (char *) (p+3)); arc_extension_map.coreRegisters[p[2]-32] = core_name; } break; case EXT_COND_CODE: { char * cc_name = (char *) xmalloc( ((int)*p-3) * sizeof(char)); strcpy(cc_name, (char *) (p+3)); arc_extension_map.condCodes[p[2]-16] = cc_name; } break; case EXT_AUX_REGISTER: { /* trickier -- need to store linked list to these */ struct ExtAuxRegister *newAuxRegister = (struct ExtAuxRegister *)malloc(sizeof(struct ExtAuxRegister)); char * aux_name = (char *) xmalloc ( ((int)*p-6) * sizeof(char)); strcpy (aux_name, (char *) (p+6)); newAuxRegister->name = aux_name; newAuxRegister->address = p[2]<<24 | p[3]<<16 | p[4]<<8 | p[5]; newAuxRegister->next = arc_extension_map.auxRegisters; arc_extension_map.auxRegisters = newAuxRegister; } break; default: return -1; } p += p[0]; /* move to next record */ } return 0; }
C
#include <.2014021_2014012.FileSystemAPI.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <stdint.h> #include <string.h> #include <stdio.h> #include <stdlib.h> /* File System Offsets in Bytes */ #define superOffset 0 * 1024 #define inodeBitmapOffset 4 * 1024 #define dataBitmapOffset 8 * 1024 #define inodeDataOffset 12 * 1024 #define dataOffset ( 12 + 4 * 128 ) * 1024 int createSFS(char* filename, int nbytes){ /*Return values : -1 : File not created -2 : Error while writing to file +ve value : File created as expected */ int return_value=open(filename, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); //Add O_CREAT if(return_value<0) return -1; int i,err; char data=0; for(i=0;i<nbytes;i++) { err=write(return_value,(void*)(&data),1); if(err!=1) return -2; } char* super_data; char sentimental[]="eyeNodeSFS"; super_data=(char*)malloc(sizeof(char)*(strlen(sentimental)+1)); strcpy(super_data,sentimental); writeData(return_value,0,(void*)super_data); return return_value; } int readData(int disk, int blockNum, void* block) { /*Return values : -1 : Error in lseek() -2 : Error in read() +ve number : Data read successfully */ int fourKB=4*1024; if(lseek(disk,blockNum*fourKB,SEEK_SET)<0) return -1; if(read(disk,block,fourKB)!=fourKB) return -2; //4KB Data Block return fourKB; } int writeData(int disk, int blockNum, void* block){ /*Return values : -1 : Error in lseek() -2 : Error in write() +ve number : Data written successfully */ int fourKB=4*1024; if(lseek(disk,blockNum*fourKB,SEEK_SET)<0) return -1; if(write(disk,block,fourKB)!=fourKB) return -2; //4KB Data Block return fourKB; } int writeFile(int disk, char* filename, void* block){ /*Return values : -1 : Error in lseek() -2 : Error in read() -3 : No space to write data -4 : No space to write inode entry -5 : Error writing to file 0 : File created successfully */ int actual_size,block_size,sixteenB; int j,i,k,blockNum,fourKB,data_space,inode_space; fourKB=4*1024; sixteenB=16; //Needs to be checked : actual_size=0; while(*(char*)(actual_size+block)!=0) actual_size++; block_size=actual_size/fourKB; if(actual_size%fourKB != 0) block_size++; // //Temporary : // block_size=1; // actual_size=fourKB; data_space=-1; char inode_space_block,data_space_block; inode_space=-1; char* dataBitmap; blockNum=dataBitmapOffset; dataBitmap=(char*)malloc(sizeof(char)*fourKB); //4KB data bitmap if(lseek(disk,blockNum,SEEK_SET)<0) return -1; if(read(disk,(void*)dataBitmap,fourKB) == -1){ // printf("Data Bitmap%s\n", (char*)dataBitmap); return -2; } // printf("First checkpoint\n"); //Find space in data_bitmap int maxContFound = 0; for(i = 0; i < fourKB; i++) { for(j = 0;j < 8; j++) { k = (unsigned char)dataBitmap[i]; // printf("Data bitmap is %d\n",k); int isSet = (128 >> j) & k; // printf("IsSet is %d\n",isSet); if (isSet == 0) maxContFound++; else maxContFound = 0; if(maxContFound==block_size) { data_space = (8 * i + j) - ( maxContFound -1); data_space_block = dataBitmap[ data_space / 8]; goto heaven; } } } heaven: if(data_space == -1) return -3; //No space for data //Find space for inode entry in inode_bitmap char* inodeBitmap; blockNum = inodeBitmapOffset; inodeBitmap = (char*)malloc(sizeof(char)*fourKB); //4KB inode bitmap if(lseek(disk,blockNum,SEEK_SET) < 0) return -1; if(read(disk,(void*)inodeBitmap,fourKB) == -1) return -2; // printf("Second checkpoint\n"); for(i=0;i<fourKB;i++) { for(j=0;j<8;j++) { k=(unsigned char)inodeBitmap[i]; // printf("I read %d\n",k); k=(128>>j)&k; if(k==0) { inode_space=(8 * i + j); inode_space_block=inodeBitmap[inode_space / 8]; //Get 8 bytes goto hell; } } } unsigned char yoda; int jedi; hell: if(inode_space==-1) return -4; //No space for inode entry //TESTED: //Set inode bitmap (inode_space) to one: yoda=inode_space_block; jedi=(int)yoda; // printf("Before : %d, want to %dth bit\n",jedi,(inode_space%8)); jedi=((128)>>(inode_space%8)) | jedi; //Setting 'inode_space%8'th bit // printf("After : %d\n",jedi); // printf("Inode_space/8 is %d\n",inode_space/8); if(lseek(disk,inodeBitmapOffset+(inode_space/8),SEEK_SET)<0) return -1; yoda=(char)jedi; if(write(disk,(void*)(&yoda),1)!=1) return -2; //Rewriting that whole byte (as it is tedious to rewrite individual bit) // printf("Third checkpoint\n"); //Checking if inode bit was actually set // unsigned char into; // lseek(disk,inodeBitmapOffset+(inode_space/8),SEEK_SET); // read(disk,(void*)(&into),1); // printf("Verified : %d\n",into); //TESTED: //Set data bitmap (data_space) to one {for now..need to set all data maps for input data}: yoda=data_space_block; jedi=(int)yoda; // printf("Before : %d, want to %dth bit\n",jedi,(inode_space%8)); jedi=((128)>>(data_space%8)) | jedi; //Setting 'data_space%8'th bit // printf("After : %d\n",jedi); if(lseek(disk,dataBitmapOffset+(data_space/8),SEEK_SET)<0) return -1; // printf("Data_space/8 is %d\n",data_space/8); yoda=(char)jedi; if(write(disk,(void*)(&yoda),1)!=1) return -2; ////Rewriting that whole byte (as it is tedious to rewrite individual bit) // printf("Fourth checkpoint\n"); // // Checking if inode bit was actually set // unsigned char into; // lseek(disk,inodeBitmapOffset+(inode_space/8),SEEK_SET); // read(disk,(void*)(&into),1); // printf("was there %d\n",into); //TESTED : //Write metadata to inode table if(lseek(disk,inodeDataOffset+inode_space*sixteenB,SEEK_SET)<0) return -1; if(write(disk,(void*)filename,8)!=8) return -2; //Setting 8 byte filename // printf("Fifth checkpoint\n"); // //Checking if filename was actually written: // lseek(disk,inodeDataOffset+inode_space*fourKB,SEEK_SET); // char* holla; // holla=(char*)malloc(sizeof(char)*8); // read(disk,(void*)holla,8); // int yoy=0; // printf("%s WTAF\n",holla); char* ex; ex=(char*)malloc(sizeof(char)*2); memcpy((void*)ex,(void*)(&data_space),2); //Copying starting block of file (data) if(write(disk,(void*)ex,2)!=2) return -2; //Setting 2 byte starting block of file // printf("Sixth checkpoint\n"); //free(ex); memcpy((void*)ex,(void*)(&block_size),2); //Copying number of blocks for file (data) if(write(disk,(void*)ex,2)!=2) return -2; //Setting 2 byte size of file (in blocks) // printf("Seventh checkpoint\n"); //free(ex); ex=(char*)malloc(sizeof(char)*4); memcpy((void*)ex,(void*)(&actual_size),4); //Copying actual file size (data) if(write(disk,(void*)ex,4)!=4) return -2; //Setting 4 blocks for file size // printf("Eigth checkpoint\n"); //Write data char* one_block; one_block=(char*)malloc(sizeof(char)*fourKB); // if(lseek(disk,dataOffset+(data_space*fourKB),SEEK_SET)<0) return -1; //Seek pointer to location where data is to be written // printf("Ninth checkpoint\n"); //Write 4KB at at time for(i=0;i<block_size;i++) { memcpy(one_block,((char*)block),fourKB); if(writeData(disk,(dataOffset/fourKB)+i+data_space,(void*)one_block)<0) return -5; //Error writing to file block=block+fourKB; //4KB at a time } return 0; } int readFile(int disk, char* filename, void* block){ /*Return values : -1 : Error in lseek() -2 : Error in read() -3 : File not found (in inode table) error -4 : Error reading from file 0 : Data read successfully */ int i,found; int fourKB=1024*4; int starting,file_size,n_blocks; char *name,*word; word=(char*)malloc(sizeof(char)*16); name=(char*)malloc(sizeof(char)*8); found=0; for(i=inodeDataOffset;i<dataOffset;i+=16) { if(lseek(disk,i,SEEK_SET)<0) return -1; if(read(disk,(void*)word,16)!=16) return -2; //4KB Data Block memcpy((void*)name,(void*)word,8); //Extract file name // printf("Read : %s\n",name); if(strcmp(name,filename) == 0) { found=1; memcpy((void*)(&starting),(void*)(word+8),2); memcpy((void*)(&n_blocks),(void*)(word+10),2); memcpy((void*)(&file_size),(void*)(word+12),4); printf("Starting block : %d\n",starting); printf("Number of blocks : %d\n",n_blocks); printf("Size of file : %dB\n",file_size); break; } } if(!found) return -3; int starting_block=starting+(dataOffset/fourKB); //Block 'number' // printf("Starting block %d\n",starting_block); if(lseek(disk,starting_block,SEEK_SET)<0) return -1; //Seek to starting of file char* one_block; one_block=(char*)malloc(sizeof(char)*fourKB); //Reading 4KB at a time : for(i=0;i<n_blocks;i++) { if(readData(disk,starting_block+i,(void*)one_block) == -1) return -4; memcpy((void*)(block+i*fourKB),(void*)one_block,fourKB); //Adding data to block, 4KB at a time } // read(disk,block,file_size); return 0; }
C
/********************************************************************************************** * * 结束线程:结束线程通常是由该线程自身发起的。 * pthread_exit(void *retval); * 以阻塞的方式等待thread指定的线程结束。 * int pthread_join(pthread_t thread, void **retval); * *********************************************************************************************/ #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include<malloc.h> #define checkResults(string, val) { \ if (val) { \ printf("Failed with %d at %s \n", val, string); \ exit(1); \ } \ } #define THREADGROUPSIZE 5 void *theThread(void *parm) { printf("Entered : Thread is %ld\n",pthread_self()); printf("Working : Thread is %ld\n",pthread_self()); sleep(15); printf("Dnoe : Thread is %ld\n",pthread_self()); return NULL; } int main(int argc,char **argv) { pthread_t thread[THREADGROUPSIZE]; void *status[THREADGROUPSIZE]; int rc = 0; printf("Create some new thread \n"); printf("Wait for worker threads to complete, release their resources\n"); for(int i = 0; i < THREADGROUPSIZE;i++) { rc = pthread_create(&thread[i], NULL, theThread, NULL); checkResults("pthread_create()\n", rc); } for (int i = 0; i < THREADGROUPSIZE; i++) { rc = pthread_join(thread[i], &status[i]); checkResults("pthread_join()\n", rc); } printf("Check all thread's results\n"); for (int i = 0; i < THREADGROUPSIZE; i++) { if (status[i] != NULL) { printf("Unexpected thread status\n"); } } printf("Main completed\n"); return 0; }
C
#define int ElemType typedef struct StackSq{ ElemType *stack; int top; int MaxSize; }StackSq; void InitStack(StackSq *S,int ms) { if(ms<0){ printf("ms is invalid!\n"); exit(1); } S->MaxSize = ms; S->stack=malloc(S->MaxSize*sizeof(ElemType)); if(!S->stack){ printf("no space!\n"); exit(1); } s->top = -1; } void Push(StackSq *S,ElemType x) { if(S->top==S->MaxSize) againMalloc(S); S->top++; S->stack[S->top]=x; } void againMalloc(StackSq *S) { ElemType *p; p = realloc(S->stack,2*S->MaxSize*sizeof(ElemType)); if(!p){ printf("no space!\n"); exit(1); } S->stack=p; S->MaxSize=2*S->MaxSize; } ElemType Pop(StackSq *S) { if(S->top==-1){ printf("stack if empty!\n"); exit(1); } S->top--; return S->stack[S->top+1]; } ElemType Peek(StackSq *S) { if(S->top==-1){ printf("stack if empty!\n"); exit(1); } return S->stack[S->top]; }
C
/* Using structure pointer without dynamic memory */ #include <stdio.h> struct Person { char name[20]; int age; char addr[100]; }; int main() { struct Person p1; struct Person *ptr; ptr = &p1; // allocate memory address of p1 into ptr ptr->age = 30; printf("age: %d\n", p1.age); printf("age: %d\n", ptr->age); return 0; }
C
/** * Copyright (c) 2013 by Tapti Palit, Kaustubh Gharpure. All rights reserved. */ #include<syscall.h> #include<stdlib.h> #include<common.h> #include<stdarg.h> #include<stdio.h> static char char_buffer[1024]; /* Temporary block to use. */ static char final_buffer[1024]; /* This will be sent to the kernel to be printed */ static int final_buffer_indx = 0x0; void reverse(char *str, int length) { int i=0, j = length-1; char tmp; while(i<j) { tmp = str[i]; str[i] = str[j]; str[j] = tmp; i++; j--; } } /* * This function will convert an unsigned 64 bit * pointer into string. */ void ltoa(u64int n, char* str) { int i = 0; while(n>0){ if (n%16 < 10){ str[i++] = '0'+n%16; } else { str[i++] = 65+(n%16-10); } n/=16; } // str[i++] = '0'; str[i++] = 'x'; str[i++] = '0'; str[i] = '\0'; reverse(str, i); return; } /* * This function will convert a 32 bit integer * into string. */ void itoa(s32int n, char* str, int base) { int i = 0; int sign = n<0?1:0; if (n<0) { str[i++] = '-'; n=-n; } else if (n == 0) { str[i++] = '0'; } /* We'll handle only base 10 and 16 */ while(n>0){ if (base == 10){ str[i++] = '0'+n%base; } else if (base == 16){ if (n%base <10){ str[i++] = '0'+n%base; } else { str[i++] = 65+(n%base-10); } } n/=base; } if (base == 16) { str[i++] = '0'; str[i++] = 'x'; str[i++] = '0'; } str[i] = '\0'; reverse(str+sign, i - sign); return; } void puts(const char* str) { while(*str != '\0'){ putchar(*str++); } } void putchar(const char c) { final_buffer[final_buffer_indx++] = c; } /* * This function invokes the itoa() function * to get a string representation of the integer. */ void putint(s32int n, int base) { char *str = char_buffer; itoa(n, str, base); puts(str); /* while(*(str+i) != '\0') { putchar(*(str+i)); i++; } */ } /* * This function invokes the ltoa() function * to get a string representation of a pointer. */ void putptr(u64int n) { char *str = char_buffer; ltoa(n, str); /* while(*(str+i) != '\0') { putchar(*(str+i)); i++; } */ puts(str); } int printf(const char *format, ...) { int i=0; char ch; va_list arguments; va_start (arguments, format); final_buffer_indx = 0; while((ch = *(format+i)) != '\0') { if(ch == '%') { i++; ch = *(format+i); switch(ch) { case 'c': putchar(va_arg(arguments, int)); break; case 'd': putint(va_arg(arguments, s32int), 10); break; case 'x': putint(va_arg(arguments, s32int), 16); break; case 's': puts(va_arg(arguments, char*)); break; case 'p': putptr(va_arg(arguments, u64int)); break; default: putchar(va_arg(arguments, int)); break; } } else { putchar(ch); } i++; } va_end(arguments); final_buffer[final_buffer_indx++] = 0; u64int buff_addr = (u64int)&final_buffer; register volatile u64int ret_val = 0; __asm__ __volatile__("movq %[s], %%rdi\n\t" : :[s]"m"(buff_addr)); __asm__ __volatile__("movq $0, %rax\n\t"); __asm__("int $0x80\n\t"); __asm__("movq %%rax, %[retVal]\n\t":[retVal]"=r"(ret_val)); final_buffer_indx = 0; return ret_val; }
C
#include <stdio.h> /* strcpy1: copy string 't' to string 's'. (array subscript version) */ int strcpy1(int *s, int *t) { int i; i = 0; while ((s[i] = t[i]) != '\0') i++; } /* strcpy2: copy string 't' to string 's'. (pointer version 1) */ int strcpy2(int *s, int *t) { while ((*s = *t) != '\0') { s++; t++; } } /* strcpy3: copy string 't' to string 's'. (pointer version 2) */ int strcpy3(int *s, int *t) { while ((*s++ = *t++) != '\0') ; } int main(void) { }
C
void readarray(int b[],int m) { int i; for(i=0;i<m;i++) { scanf("%d",&b[i]); } } void printarray(int b[],int m) { int i; for(i=0;i<m;i++) { printf("%d ",b[i]); } } int sumarray(int c[],int k) { int i,sum=0; for(i=0;i<k;i++) { sum+=c[i]; } return sum; }
C
/* ID: huajian2 LANG: C TASK: butter */ #include <stdio.h> #include <stdlib.h> #define INFINIT 300000 #define MAXN 800 int c, p, e; int pasture[MAXN]; int total_dis[MAXN]; int dis[MAXN][MAXN]; int main() { FILE *fin = fopen ("butter.in", "r"); FILE *fout = fopen ("butter.out", "w"); int i, j, k; int a, b, d; int min; /* initial */ for (i = 0; i < 800; i++) { pasture[i] = 0; total_dis[i] = 0; } for (i = 0; i < 800; i++) for (j = 0; j < 800; j++) dis[i][j] = INFINIT; /* read */ fscanf (fin, "%d %d %d", &c, &p, &e); for (i = 0; i < c; i++) { fscanf (fin, "%d", &a); ++pasture[a-1]; } for (i = 0; i < e; i++) { fscanf (fin, "%d %d %d", &a, &b, &d); --a; --b; dis[a][b] = dis[b][a] = d; } /* shortest path */ for (k = 0; k < p; k++) for (i = 0; i < p; i++) for (j = i+1; j < p; j++) if (dis[i][j] > dis[i][k] + dis[k][j]) dis[i][j] = dis[j][i] = dis[i][k] + dis[k][j]; /* total path */ for (i = 0; i < p; i++) for (j = 0; j < p; j++) if (i != j) total_dis[i] += dis[i][j] * pasture[j]; min = total_dis[0]; for (i = 0; i < p; i++) if (min > total_dis[i]) min = total_dis[i]; fprintf(fout, "%d\n", min); exit(0); }
C
/* ---------------------------------------------------------------------------- */ /* Copyright Digital TV Labs 2012 - 2013 */ /* ---------------------------------------------------------------------------- */ /* HTR 6.2.5: Change of CICAM_ID * Script name: license_625.c * Preconditions: * * Description: * - This script supports HTR 6.2.5. */ #include <picoc_cit.h> int main() { unsigned int eError = 0; uint32 eUriVersion; uint8 u8UriRL = 0; uint8 u8EventId = 0; uint8 *pu8LicenseLabel1 = "LicenseD1"; uint8 *pu8LicenseLabel2 = "LicenseD2"; cit_license_Object stLicenseEvt; printf("HTR 6.2.5.: Change of CICAM_ID \n"); /* Determine default URI version */ eError = cit_uri_GetDefaultUriVersion(&eUriVersion); if(eError != 0) { printf("Failed to determine default URI version URIv%d, eError: %d \n", eUriVersion, eError); return 0; } printf("Default URI version is URIv%d \n", eUriVersion); /* Initialise the test system's persistent settings */ eError = cit_lic_InitialiseNvram(); if(eError != 0) { printf("Failed to initialise persistent settings, eError: %d \n", eError); return 0; } printf("Persistent settings are initialised \n"); /* Set the default URI to Default_URI_004 */ eError = cit_uri_SetURIMessage(eUriVersion); u8UriRL = 0xFF; cit_uri_SetRL(&u8UriRL); if(eError != 0) { printf("Failed to initialise URI message, eError: %d \n", eError); return 0; } eError = cit_uri_SaveDefaultURI(); if(eError != 0) { printf("Failed to save default URI message in NVRAM, eError: %d \n", eError); return 0; } printf("Default URI is saved to NVRAM \n"); /* Configure the URI/License event (Region#1) */ memset(&stLicenseEvt, 0x00, sizeof(cit_license_Object)); stLicenseEvt.tdtTime.u8Hour = 12; stLicenseEvt.tdtTime.u8Min = 7; stLicenseEvt.tdtTime.u8Sec = 15; stLicenseEvt.u16ProgramNumber = 0x0002; stLicenseEvt.u8LicenseStatus = 0x00; cit_uri_SetURIMessage(eUriVersion); if(eUriVersion > 1) cit_uri_SetDOT(0x01); u8UriRL = 0xFF; cit_uri_SetRL(&u8UriRL); cit_uri_Read(stLicenseEvt.pu8URI); stLicenseEvt.u16LicenseSize = 0x200; stLicenseEvt.u8LicensePlayCount = 0x14; memcpy(stLicenseEvt.pu8LicenseLabel, pu8LicenseLabel1, 16); memcpy(stLicenseEvt.pu8PlaybackURI, stLicenseEvt.pu8URI, 8); stLicenseEvt.u8PlaybackDelay = 0; eError = cit_lic_WriteEventConfig(u8EventId, &stLicenseEvt); if(eError != 0) { printf("Failed to write URI-License event [%d], eError: %d \n", u8EventId, eError); return 0; } u8EventId++; /* Configure the URI/License event (Region#2)*/ memset(&stLicenseEvt, 0x00, sizeof(cit_license_Object)); stLicenseEvt.tdtTime.u8Hour = 12; stLicenseEvt.tdtTime.u8Min = 17; stLicenseEvt.tdtTime.u8Sec = 15; stLicenseEvt.u16ProgramNumber = 0x0002; stLicenseEvt.u8LicenseStatus = 0x00; cit_uri_SetURIMessage(eUriVersion); if(eUriVersion > 1) cit_uri_SetDOT(0x01); u8UriRL = 0xFF; cit_uri_SetRL(&u8UriRL); cit_uri_Read(stLicenseEvt.pu8URI); stLicenseEvt.u16LicenseSize = 0x100; stLicenseEvt.u8LicensePlayCount = 0x14; memcpy(stLicenseEvt.pu8LicenseLabel, pu8LicenseLabel2, 16); u8UriRL = 0x03; cit_uri_SetRL(&u8UriRL); cit_uri_Read(stLicenseEvt.pu8PlaybackURI); stLicenseEvt.u8PlaybackDelay = 0; eError = cit_lic_WriteEventConfig(u8EventId, &stLicenseEvt); if(eError != 0) { printf("Failed to write URI-License event [%d], eError: %d \n", u8EventId, eError); return 0; } u8EventId++; eError = cit_lic_ConfigureScheduler(); if(eError != 0) { printf("Failed to configure URI/License events, eError: %d \n", eError); return 0; } printf("Configured %d URI-License events \n", u8EventId); /* Enable logging */ eError = cit_lic_WriteModuleConfig(0x01, 0x00); if(eError != 0) { printf("Failed to enable logging, eError: %d \n", eError); return 0; } printf("Logs are enabled \n"); /* Print configuration */ cit_lic_PrintConfiguration(); /* Change CICAM_ID to CICAM_ID-1 */ eError = cit_SetCicamID(1); if(eError != 0) { printf("Failed to change CICAM_ID, eError: %d \n", eError); return 0; } printf("CICAM_ID is changed to CICAM_ID-1 \n"); eError = cit_SetHProfileFspValid(0x0); if (eError != 0) { printf("Fail to erase Host Profile Valid byte in MFS \n"); } printf("Please reboot CAM for changes to take effect.\n"); return 0; } main();
C
//ifdef.c -- wykorzystuje kompilacje warunkowa #include <stdio.h> #define TYLKO_SPRAWDZAM #define GRANICA 4 int main(void) { int i; int suma = 0; for (i = 1; i <= GRANICA; i++) { suma+= 2*i*i + 1; #ifdef TYLKO_SPRAWDZAM printf("i=%d, suma = %d\n", i, suma); #endif } printf("Suma koncowa = %d\n", suma); return 0; }
C
void setup() { pinMode(2, OUTPUT); pinMode(3, OUTPUT); pinMode(4, OUTPUT); pinMode(5, OUTPUT); pinMode(6, OUTPUT); pinMode(7, OUTPUT); pinMode(8, OUTPUT); pinMode(9, OUTPUT); } byte i; void loop() { for(i=9;i>=2;i--) { digitalWrite(i, HIGH); delay(100); // Wait for 1000 millisecond(s) digitalWrite(i, LOW); } for(i=2;i<=9;i++) { digitalWrite(i, HIGH); delay(100); // Wait for 1000 millisecond(s) digitalWrite(i, LOW); } }
C
// String a. Program to half your name into two and reverse it eg RAKESH will become KARHSE. #include<stdio.h> #include<string.h> void reverse(char s[]); int main() { char str[50]; printf(" Enter a string to divide hald and print in reverse order \n"); gets(str); reverse(str); getch(); } void reverse(char str[]) { char rev[50]; int i,j,len,mid; len=strlen(str); if(len%2==0) { mid=len/2; } else { mid=(len/2)+1; } i = mid-1; for(j=0;j<mid;j++) { rev[j]=str[i]; i--; } i=len-1; for(j=mid;j<len;j++) { rev[j]=str[i]; i--; } printf("\n Entered string is : %s \n Reversed String is %s", str,rev); }