language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#ifndef __Math__ #define __Math__ double saturate(double val){ return max(0,min(val, 1)); } double smoothStep(double edge0, double edge1, double x) { double t = saturate((x - edge0) / (edge1 - edge0)); return t * t * (3.0 - 2.0 * t); } double interpolateCos(double t){ return (cos(PI + saturate(t) * PI) +1) / 2; } double dRandom() { return random(0, 100000) / 100000. ; } #endif
C
#include<stdio.h> int factorial (int); int main() { int user_input = 0; printf("Enter number: "); scanf("%d", &user_input); printf("Factorial of %d is: %d\n", user_input, factorial(user_input)); } int factorial (int i) { if (i > 0) return i*factorial(i-1); else return 1; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include "historique.h" void ajoutListeHistorique (int action, float valeur, listeHistorique liste) { Historique* nouvelleAction = (Historique*)malloc(sizeof(Historique)); nouvelleAction->action = action; nouvelleAction->valeurPrecedente = valeur; nouvelleAction->actionPrecedente = liste->actionPrecedente; (liste->actionPrecedente) = nouvelleAction; } Historique* initHistorique (listeHistorique historique) { Historique* premiereAction = (Historique*)malloc(sizeof(Historique)); premiereAction->action = -1; premiereAction->valeurPrecedente = -1; premiereAction->actionPrecedente = NULL; return premiereAction; }
C
#include <stdio.h> #include <stdlib.h> #include "decoder.h" void read_file(){ char *hexa; int num, instruction = 0, opcode_num, option, a = 0, contador = 0, i = 0; int valid = 0; hexa = (char *)calloc(10000000, sizeof(char)); FILE *arquivo; arquivo = fopen("dados.txt","r"); if(arquivo == NULL){ printf("Arquivo não encontrado!\n"); exit(1); } while(fgets(hexa, 10000000, arquivo) != NULL){ /* writing content to stdout */ //puts(hexa); sscanf(hexa, "%x", &num); /* while(hexa[i] != '\n'){ for(i = 0; i < 10000000; i++){ if((hexa[i] == '0' || hexa[i] == '1' || hexa[i] == '2' || hexa[i] == '3' || hexa[i] == '4' || hexa[i] == '5' || hexa[i] == '6' || hexa[i] == '7' || hexa[i] == '8' || hexa[i] == '9' || hexa[i] == 'a' || hexa[i] == 'b' || hexa[i] == 'c' || hexa[i] == 'd' || hexa[i] == 'e' || hexa[i] == 'f'|| hexa[i] == 'A' || hexa[i] == 'B' || hexa[i] == 'C'|| hexa[i] == 'D'|| hexa[i] == 'E'|| hexa[i] == 'F')){ valid++; } } } if(valid != 4){ printf("Instrução inválida.\n"); } */ while(hexa[a] != '\n'){ contador++; a++; } if(contador > 4 || contador < 4){ printf("Instrução inválida!\n"); printf("\n"); } else{ printf("Value in hexa: %x\n", num); opcode_num = opcode(instruction, num); printf("Decoded instruction:\n"); instruction_decoder(instruction, opcode_num, num); printf("\n"); } contador = 0; a = 0; } free(hexa); fclose(arquivo); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "sums.h" int sumline(const char* line) { if(line == NULL) /* null guard */ { return 0; } if(strlen(line) == 0) /* trivial case */ { return 0; } int sum = 0; /* running total */ unsigned int pos = 0; /* current position in line */ char* elem = NULL; /* pointer to temp string */ for(unsigned int i=0;i<strlen(line);i++) { if((line[i] == ELEM_DELIM || line[i] == LINE_DELIM) && pos > 0) { elem = calloc(pos + 2, sizeof(char)); /* allocate element str */ strncpy(elem, &line[i-pos], pos + 2); /* copy element into str */ sum += atoi(elem); /* add to sum */ free(elem); /* free element string */ pos = 0; /* reset position */ } pos++; /* increment position */ } return sum; } void sumfile(FILE* in, FILE* out) { if(in == NULL || out == NULL) { return; } long in_size = 0; /* size of input file */ /* determine size of input file */ fseek(in, 0, SEEK_END); in_size = ftell(in); rewind(in); char* in_data = calloc(in_size, sizeof(char)); /* file data */ int bytes_read = fread(in_data, sizeof(char), in_size, in); /* read in */ unsigned int pos = 0; /* position in the file */ char* line = NULL; /* pointer for storing line */ for(int i=0;i<bytes_read;i++) { if(in_data[i] == LINE_DELIM && pos > 0) { line = calloc(pos + 2, sizeof(char)); /* allocate space */ strncpy(line, &in_data[i-pos], pos + 1); /* copy into string */ fprintf(out, "%d\n", sumline(line)); /* write out */ free(line); /* free line string */ pos = 0; /* reset position */ } pos++; /* increment position */ } free(in_data); }
C
/************************** frame.c ******************************************/ /* Subor: frame.c - */ /* Projekt: Implementacia interpretu ifj16 */ /* Varianta zadania: a/2/II */ /* Meno, login: Tomáš Strych xstryc05 */ /* Radoslav Pitoňák xpiton00 */ /* Andrej Dzilský xdzils00 */ /* Milan Procházka xproch91 */ /* Ondřej Břínek xbrine03 */ /******************************************************************************/ #include "frame.h" #include "garbage_collector.h" /* START OF HASH TABLE */ //Hash function //return hash_code, the place where the item will be stored //int hash_code ( string key ) { // int ret_val = 1; // for (int i = 0; i < key.length; i++) // ret_val += key.str[i]; // return (ret_val % HASH_TABLE_SIZE); //} //initialize hash table //function return pointer on initialized table f_table * frame_table_init() { f_table * frame_table = (f_table *) gc_alloc_pointer(sizeof(f_table) + sizeof(f_item *)*HASH_TABLE_SIZE ); if ( frame_table != NULL) { for (int i = 0; i < HASH_TABLE_SIZE; i++) { frame_table->items[i] = NULL; //every element pointer is set on NULL } } else { return NULL; } frame_table->size = HASH_TABLE_SIZE; //set size on maxsize of hash_table return frame_table; } //finding item in hash_table //when you find searched item, pointer where the pointer to found item will be stored, //if item is not found, pointer has undefined value int frame_table_search(f_table *frame_table,string *key, f_item **item) { if (frame_table != NULL) { f_item *searched = frame_table->items[hash_code(*key)]; while (searched != NULL) { if(strcmp(searched->key.str,key->str) == 0) //item is found { if (item != NULL) { *item = searched; //set pointer } return HASH_SEARCH_OK; } searched = searched->next; //if not found go found to the next pointer } return HASH_SEARCH_FAIL; } return HASH_SEARCH_FAIL; } //allocate place for new item and insert new item to hash_table int frame_table_insert(f_table *frame_table, string *key, f_item **item) { f_item * inserted; if (frame_table_search(frame_table,key,item) == HASH_SEARCH_OK) { return HASH_INSERT_FOUND; //on key position exist another item } inserted = gc_alloc_pointer(sizeof(f_item)); //allocate memory for new item if (inserted != NULL) { inserted->next = frame_table->items[hash_code(*key)]; //next item will be the actual item if ((duplicate_str(&inserted->key,key)) != STR_OK ) { return HASH_INSERT_ALLOC_ERR; } if (item != NULL) { *item = inserted; //pointer where pointer to inserted item will be stored (only if exists) } frame_table->items[hash_code(*key)] = inserted; //actual item is inserted item return HASH_INSERT_OK; } else { return HASH_INSERT_ALLOC_ERR; } }
C
#include <stdio.h> #include <float.h> int main(void) { int cost = 12.99; double d1 = 1.0 / 3.0; float f1 = 1.0 / 3.0; printf("%.6f,%.6f,%d,%f\n", d1, f1, cost, cost); printf("%.12f,%.12f\n", d1, f1); printf("%.16Lf,%.16Lf\n", d1, f1); printf("%f,%f\n", FLT_DIG, DBL_DIG); getchar(); return 0; }
C
//======================================================================================== // lib eeprom 24Cxx // // 14/05/21 Jonny zez //======================================================================================== #include "EEPROM.h" #include "math.h" #include "string.h" // Define the I2C extern I2C_HandleTypeDef hi2c2; #define EEPROM_I2C &hi2c2 // EEPROM endereço #define EEPROM_ADDR 0xA0 #define PAGE_SIZE 8 // tamanho do end. #define PAGE_NUM 64 // tamanho da memoria //======================================================================================= uint8_t bytes_temp[4]; //definição de tamanho uint16_t bytestowrite (uint16_t size, uint16_t offset) { if ((size+offset)<PAGE_SIZE) return size; else return PAGE_SIZE-offset; } //======================================================================================= void EEPROM_Write (uint16_t page, uint16_t offset, uint8_t *data, uint16_t size) { int paddrposition = log(PAGE_SIZE)/log(2); uint16_t startPage = page; uint16_t endPage = page + ((size+offset)/PAGE_SIZE); uint16_t numofpages = (endPage-startPage) + 1; uint16_t pos=0; for (int i=0; i<numofpages; i++) { uint16_t MemAddress = startPage<<paddrposition | offset; uint16_t bytesremaining = bytestowrite(size, offset); HAL_I2C_Mem_Write(EEPROM_I2C, EEPROM_ADDR, MemAddress, 1, &data[pos], bytesremaining, 1000); startPage += 1; offset=0; size = size-bytesremaining; pos = bytesremaining; HAL_Delay (5); } } //======================================================================================= void float2Bytes(uint8_t * ftoa_bytes_temp,float float_variable) { union { float a; uint8_t bytes[4]; } thing; thing.a = float_variable; for (uint8_t i = 0; i < 4; i++) { ftoa_bytes_temp[i] = thing.bytes[i]; } } float Bytes2float(uint8_t * ftoa_bytes_temp) { union { float a; uint8_t bytes[4]; } thing; for (uint8_t i = 0; i < 4; i++) { thing.bytes[i] = ftoa_bytes_temp[i]; } float float_variable = thing.a; return float_variable; } //======================================================================================= void EEPROM_Write_NUM (uint16_t page, uint16_t offset, float data) { float2Bytes(bytes_temp, data); EEPROM_Write(page, offset, bytes_temp, 4); } //======================================================================================= float EEPROM_Read_NUM (uint16_t page, uint16_t offset) { uint8_t buffer[4]; EEPROM_Read(page, offset, buffer, 4); return (Bytes2float(buffer)); } //======================================================================================= void write_eeprom(uint16_t end, uint8_t data) { HAL_I2C_Mem_Write(EEPROM_I2C, EEPROM_ADDR, end, 1, &data, 1, 1); HAL_Delay (5); } //======================================================================================= uint8_t read_eeprom(uint16_t end) { uint8_t dado; HAL_I2C_Mem_Read(EEPROM_I2C, EEPROM_ADDR, end, 1, &dado, 1, 1); HAL_Delay (1); return (dado); } void EEPROM_Read (uint16_t page, uint16_t offset, uint8_t *data, uint16_t size) { int paddrposition = log(PAGE_SIZE)/log(2); uint16_t startPage = page; uint16_t endPage = page + ((size+offset)/PAGE_SIZE); uint16_t numofpages = (endPage-startPage) + 1; uint16_t pos=0; for (int i=0; i<numofpages; i++) { uint16_t MemAddress = startPage<<paddrposition | offset; uint16_t bytesremaining = bytestowrite(size, offset); HAL_I2C_Mem_Read(EEPROM_I2C, EEPROM_ADDR, MemAddress, 1, &data[pos], bytesremaining, 10); startPage += 1; offset=0; size = size-bytesremaining; pos = bytesremaining; } } //======================================================================================= void EEPROM_PageErase (uint16_t page) { int paddrposition = log(PAGE_SIZE)/log(2); uint16_t MemAddress = page<<paddrposition; uint8_t data[PAGE_SIZE]; memset(data,0xff,PAGE_SIZE); HAL_I2C_Mem_Write(EEPROM_I2C, EEPROM_ADDR, MemAddress, 1, data, PAGE_SIZE, 1000); HAL_Delay (5); }
C
/*--------------------------------------------------------------------------- * Helper functions to handle the current object. * *--------------------------------------------------------------------------- */ #ifndef I_CURRENT_OBJECT__ #define I_CURRENT_OBJECT__ #include "driver.h" #include "lwobject.h" #include "object.h" #include "simulate.h" /*-------------------------------------------------------------------------*/ static INLINE object_t * get_current_object () /* Returns the current object if it is indeed an object, * otherwise return NULL. */ { if (current_object.type == T_OBJECT) return current_object.u.ob; return NULL; } /* get_current_object() */ /*-------------------------------------------------------------------------*/ static INLINE lwobject_t * get_current_lwobject () /* Returns the current lightweight object if it is indeed a lightweight * object, otherwise return NULL. */ { if (current_object.type == T_LWOBJECT) return current_object.u.lwob; return NULL; } /* get_current_lwobject() */ /*-------------------------------------------------------------------------*/ static INLINE bool is_current_object (svalue_t ob) /* Returns true if the given object is the same as the current object. */ { if (ob.type != current_object.type) return false; switch (ob.type) { case T_OBJECT: return ob.u.ob == current_object.u.ob; case T_LWOBJECT: return ob.u.lwob == current_object.u.lwob; default: return false; } } /* is_current_object() */ /*-------------------------------------------------------------------------*/ static INLINE void clear_current_object () /* Set current_object to 0. */ { current_object = (svalue_t){ T_NUMBER, {}, {.number = 0} }; } /* clear_current_object() */ /*-------------------------------------------------------------------------*/ static INLINE void set_current_object (object_t *ob) /* Sets the current object to <ob>. */ { if (!ob) clear_current_object(); else put_object(&current_object, ob); } /* set_current_object() */ /*-------------------------------------------------------------------------*/ static INLINE void set_current_lwobject (lwobject_t *lwob) /* Sets the current object to <lwob>. */ { if (!lwob) clear_current_object(); else put_lwobject(&current_object, lwob); } /* set_current_lwobject() */ /*-------------------------------------------------------------------------*/ static INLINE bool is_current_object_destructed () /* Returns true if the current object is a regular object that has been * destructed, otherwise (for living or lightweight objects) return false. */ { if (current_object.type == T_OBJECT) return (current_object.u.ob->flags & O_DESTRUCTED) != 0; return false; } /* is_current_object_destructed() */ /*-------------------------------------------------------------------------*/ static INLINE program_t * get_current_object_program () /* Returns the program from the current object. */ { switch (current_object.type) { case T_OBJECT: return current_object.u.ob->prog; case T_LWOBJECT: return current_object.u.lwob->prog; case T_NUMBER: return NULL; default: fatal("Illegal type for current object.\n"); } } /* get_current_object_program() */ /*-------------------------------------------------------------------------*/ static INLINE svalue_t * get_current_object_variables () /* Returns the variables from the current object. */ { switch (current_object.type) { case T_OBJECT: return current_object.u.ob->variables; case T_LWOBJECT: return current_object.u.lwob->variables; case T_NUMBER: return NULL; default: fatal("Illegal type for current object.\n"); } } /* get_current_object_variables() */ /*-------------------------------------------------------------------------*/ static INLINE wiz_list_t * get_current_user () /* Returns the user of the current object. */ { switch (current_object.type) { case T_OBJECT: return current_object.u.ob->user; case T_LWOBJECT: return current_object.u.lwob->user; case T_NUMBER: return NULL; default: fatal("Illegal type for current object.\n"); } } /* get_current_user() */ /*-------------------------------------------------------------------------*/ static INLINE wiz_list_t * get_current_eff_user () /* Returns the effective user of the current object. */ { switch (current_object.type) { case T_OBJECT: return current_object.u.ob->eff_user; case T_LWOBJECT: return current_object.u.lwob->eff_user; case T_NUMBER: return NULL; default: fatal("Illegal type for current object.\n"); } } /* get_current_user() */ /*-------------------------------------------------------------------------*/ static INLINE void assign_object_svalue_no_free (svalue_t *dest, svalue_t ob, const char* where) /* Writes the object <ob> into <dest> and increments the reference count. * This is used preferably over assign_svalue_no_free(), when destructed * objects should stay and not become zero. * <where> is used for debugging output. */ { *dest = ob; switch (ob.type) { case T_OBJECT: ref_object(ob.u.ob, where); break; case T_LWOBJECT: ref_lwobject(ob.u.lwob); break; case T_NUMBER: break; default: fatal("Illegal type for object.\n"); } } /* assign_object_svalue_no_free() */ /*-------------------------------------------------------------------------*/ static INLINE void assign_object_svalue (svalue_t *dest, svalue_t ob, const char* where) /* Writes the object <ob> into <dest> and increments the reference count. * The contents of <dest> will be freed before. (Contrary to assign_svalue() * here lvalues in <dest> will be ignored.) * <where> is used for debugging output. */ { switch (dest->type) { case T_OBJECT: free_object(dest->u.ob, where); break; case T_LWOBJECT: free_lwobject(dest->u.lwob); break; case T_NUMBER: case T_INVALID: break; default: free_svalue(dest); break; } assign_object_svalue_no_free(dest, ob, where); } /* assign_object_svalue() */ /*-------------------------------------------------------------------------*/ static INLINE void assign_current_object_no_free (svalue_t *dest, const char* where) /* Writes the current object into <dest> and increments the reference count. * This is used preferably over assign_svalue_no_free(), when destructed * objects should stay and not become zero. * <where> is used for debugging output. */ { assign_object_svalue_no_free(dest, current_object, where); } /* assign_current_object_no_free() */ /*-------------------------------------------------------------------------*/ static INLINE void assign_current_object (svalue_t *dest, const char* where) /* Writes the current object into <dest> and increments the reference count. * The contents of <dest> will be freed before. (Contrary to assign_svalue() * here lvalues in <dest> will be ignored.) * <where> is used for debugging output. */ { assign_object_svalue(dest, current_object, where); } /* assign_current_object() */ /*-------------------------------------------------------------------------*/ static INLINE bool object_svalue_eq (svalue_t a, svalue_t b) /* Compare two object svalues and return true, if they are the same. */ { if (a.type != b.type) return false; switch (a.type) { case T_OBJECT: return a.u.ob == b.u.ob; case T_LWOBJECT: return a.u.lwob == b.u.lwob; case T_NUMBER: return true; default: fatal("Illegal type for object value.\n"); } } /* object_svalue_eq() */ /*-------------------------------------------------------------------------*/ static INLINE int object_svalue_cmp (svalue_t a, svalue_t b) /* Compare two object svalues and returns a value: * < 0: if a < b * = 0: if a == b * > 0: if a > b */ { if (a.type != b.type) return a.type < b.type ? -1 : 1; switch (a.type) { case T_OBJECT: return (int)(a.u.ob - b.u.ob); case T_LWOBJECT: return (int)(a.u.lwob - b.u.lwob); case T_NUMBER: return 0; default: fatal("Illegal type for object value.\n"); } } /* object_svalue_cmp() */ /*-------------------------------------------------------------------------*/ #define push_current_object(sp,where) assign_current_object_no_free(++(sp),(where)) #endif /* I_CURRENT_OBJECT__ */
C
#include <stdlib.h> #include "ll_ili9341_init.h" #include "ll_spi_ili9341.h" #include "ll_spi_dma_io.h" #include "spi_tft.h" #include "font24.h" #include "font20.h" #include "font16.h" #include "font12.h" #include "font8.h" uint16_t dsp_width; uint16_t dsp_height; extern uint32_t dma_spi_part; uint8_t frame_buffer[4096] = {0}; typedef struct { uint16_t TextColor; uint16_t BackColor; sFONT *pFont; } DSP_DrawPropTypeDef; DSP_DrawPropTypeDef lcdprop; static inline void push_color(uint16_t color) { static uint8_t p_color[2]; p_color[0] = (color>>8); p_color[1] = (color & 0xFF); dsp_write_data(p_color, 2); } void dsp_set_addr_window(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2) { // column address set static uint8_t addr_x[4]; static uint8_t addr_y[4]; addr_x[0] = x1>>8; addr_x[1] = x1; addr_x[2] = x2>>8; addr_x[3] = x2; addr_y[0] = y1>>8; addr_y[1] = y1; addr_y[2] = y2>>8; addr_y[3] = y2; dsp_send_command(0x2A); // column address set dsp_write_data(addr_x, 4); dsp_send_command(0x2B); // row address set dsp_write_data(addr_y, 4); dsp_send_command(0x2C); // write to RAM } void dsp_draw_pixel(int x, int y, uint16_t color) { if((x<0)||(y<0)||(x>=dsp_width)||(y>=dsp_height)) return; dsp_set_addr_window(x,y,x,y); push_color(color); } void dsp_draw_fast_v_line(int16_t x, int16_t y, int16_t h, uint16_t color) { // Rudimentary clipping if((x >= dsp_width) || (y >= dsp_height || h < 1)) return; if((y + h - 1) >= dsp_height) { h = dsp_height - y; } if(h < 2 ) { dsp_draw_pixel(x, y, color); return; } dsp_set_addr_window(x, y, x, y + h - 1); // -- for(uint16_t i = 0;i<h*2;i+=2) { frame_buffer[i] = color>>8; frame_buffer[i+1] = color>>8; } dsp_write_data(frame_buffer, h*2); } void dsp_draw_fast_h_line(int16_t x, int16_t y, int16_t w, uint16_t color) { // Rudimentary clipping if((x >= dsp_width) || (y >= dsp_height || w < 1)) return; if((x + w - 1) >= dsp_width) { w = dsp_width - x; } if(w < 2 ) { dsp_draw_pixel(x, y, color); return; } dsp_set_addr_window(x, y, x + w - 1, y); // -- for(uint16_t i = 0;i<w*2;i+=2) { frame_buffer[i] = color>>8; frame_buffer[i+1] = color>>8; } dsp_write_data(frame_buffer, w*2); } /* * Draw lines faster by calculating straight sections and drawing them with fastVline and fastHline. */ void dsp_draw_line(int16_t x0, int16_t y0,int16_t x1, int16_t y1, uint16_t color) { if((y0 < 0 && y1 <0) || (y0 > dsp_height && y1 > dsp_height)) return; if((x0 < 0 && x1 <0) || (x0 > dsp_width && x1 > dsp_width)) return; if(x0 < 0) x0 = 0; if(x1 < 0) x1 = 0; if(y0 < 0) y0 = 0; if(y1 < 0) y1 = 0; if(y0 == y1) { if(x1 > x0) { dsp_draw_fast_h_line(x0, y0, x1 - x0 + 1, color); } else if(x1 < x0) { dsp_draw_fast_h_line(x1, y0, x0 - x1 + 1, color); } else { dsp_draw_pixel(x0, y0, color); } return; } else if(x0 == x1) { if(y1 > y0) { dsp_draw_fast_v_line(x0, y0, y1 - y0 + 1, color); } else { dsp_draw_fast_v_line(x0, y1, y0 - y1 + 1, color); } return; } bool steep = abs(y1 - y0) > abs(x1 - x0); if(steep) { swap(x0, y0); swap(x1, y1); } if(x0 > x1) { swap(x0, x1); swap(y0, y1); } int16_t dx, dy; dx = x1 - x0; dy = abs(y1 - y0); int16_t err = dx / 2; int16_t ystep; if(y0 < y1) { ystep = 1; } else { ystep = -1; } int16_t xbegin = x0; if(steep) { for(; x0 <= x1; x0++) { err -= dy; if(err < 0) { int16_t len = x0 - xbegin; if(len) { dsp_draw_fast_v_line (y0, xbegin, len + 1, color); // writeVLine_cont_noCS_noFill(y0, xbegin, len + 1); } else { dsp_draw_pixel(y0, x0, color); // dsp_draw_pixel_cont_noCS(y0, x0, color); } xbegin = x0 + 1; y0 += ystep; err += dx; } } if(x0 > xbegin + 1) { // writeVLine_cont_noCS_noFill(y0, xbegin, x0 - xbegin); dsp_draw_fast_v_line(y0, xbegin, x0 - xbegin, color); } } else { for(; x0 <= x1; x0++) { err -= dy; if(err < 0) { int16_t len = x0 - xbegin; if(len) { dsp_draw_fast_h_line(xbegin, y0, len + 1, color); // writeHLine_cont_noCS_noFill(xbegin, y0, len + 1); } else { dsp_draw_pixel(x0, y0, color); // dsp_draw_pixel_cont_noCS(x0, y0, color); } xbegin = x0 + 1; y0 += ystep; err += dx; } } if(x0 > xbegin + 1) { // writeHLine_cont_noCS_noFill(xbegin, y0, x0 - xbegin); dsp_draw_fast_h_line(xbegin, y0, x0 - xbegin, color); } } } void dsp_fill_rect(uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint16_t color) { for (uint16_t i = x; i < x + w; i++) { dsp_draw_fast_v_line(i, y, h, color); } } void dsp_fill_screen(uint16_t color) { dsp_fill_rect(0, 0, dsp_width, dsp_height, color); } void dsp_draw_rect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color) { dsp_draw_fast_h_line(x, y, w, color); dsp_draw_fast_h_line(x, y + h - 1, w, color); dsp_draw_fast_v_line(x, y, h, color); dsp_draw_fast_v_line(x + w - 1, y, h, color); } void drawCircleHelper(int16_t x0, int16_t y0, int16_t r, uint8_t cornername, uint16_t color) { int16_t f = 1 - r; int16_t ddF_x = 1; int16_t ddF_y = -2 * r; int16_t x = 0; int16_t y = r; while (x < y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; if (cornername & 0x4) { dsp_draw_pixel(x0 + x, y0 + y, color); dsp_draw_pixel(x0 + y, y0 + x, color); } if (cornername & 0x2) { dsp_draw_pixel(x0 + x, y0 - y, color); dsp_draw_pixel(x0 + y, y0 - x, color); } if (cornername & 0x8) { dsp_draw_pixel(x0 - y, y0 + x, color); dsp_draw_pixel(x0 - x, y0 + y, color); } if (cornername & 0x1) { dsp_draw_pixel(x0 - y, y0 - x, color); dsp_draw_pixel(x0 - x, y0 - y, color); } } } void dsp_draw_circle(int16_t x0, int16_t y0, int16_t r, uint16_t color) { int16_t f = 1 - r; int16_t ddF_x = 1; int16_t ddF_y = -2 * r; int16_t x = 0; int16_t y = r; dsp_draw_pixel(x0, y0 + r, color); dsp_draw_pixel(x0, y0 - r, color); dsp_draw_pixel(x0 + r, y0, color); dsp_draw_pixel(x0 - r, y0, color); while (x < y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; dsp_draw_pixel(x0 + x, y0 + y, color); dsp_draw_pixel(x0 - x, y0 + y, color); dsp_draw_pixel(x0 + x, y0 - y, color); dsp_draw_pixel(x0 - x, y0 - y, color); dsp_draw_pixel(x0 + y, y0 + x, color); dsp_draw_pixel(x0 - y, y0 + x, color); dsp_draw_pixel(x0 + y, y0 - x, color); dsp_draw_pixel(x0 - y, y0 - x, color); } } void fillCircleHelper(int16_t x0, int16_t y0, int16_t r, uint8_t corners, int16_t delta, uint16_t color) { int16_t f = 1 - r; int16_t ddF_x = 1; int16_t ddF_y = -2 * r; int16_t x = 0; int16_t y = r; int16_t px = x; int16_t py = y; delta++; // Avoid some +1's in the loop while (x < y) { if (f >= 0) { y--; ddF_y += 2; f += ddF_y; } x++; ddF_x += 2; f += ddF_x; // These checks avoid double-drawing certain lines, important // for the SSD1306 library which has an INVERT drawing mode. if (x < (y + 1)) { if (corners & 1) dsp_draw_fast_v_line(x0 + x, y0 - y, 2 * y + delta, color); if (corners & 2) dsp_draw_fast_v_line(x0 - x, y0 - y, 2 * y + delta, color); } if (y != py) { if (corners & 1) dsp_draw_fast_v_line(x0 + py, y0 - px, 2 * px + delta, color); if (corners & 2) dsp_draw_fast_v_line(x0 - py, y0 - px, 2 * px + delta, color); py = y; } px = x; } } void fillCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color) { dsp_draw_fast_v_line(x0, y0 - r, 2 * r + 1, color); fillCircleHelper(x0, y0, r, 3, 0, color); } void drawRoundRect(int16_t x, int16_t y, int16_t w, int16_t h, int16_t r, uint16_t color) { int16_t max_radius = ((w < h) ? w : h) / 2; // 1/2 minor axis if (r > max_radius) r = max_radius; // smarter version dsp_draw_fast_h_line(x + r, y, w - 2 * r, color); // Top dsp_draw_fast_h_line(x + r, y + h - 1, w - 2 * r, color); // Bottom dsp_draw_fast_v_line(x, y + r, h - 2 * r, color); // Left dsp_draw_fast_v_line(x + w - 1, y + r, h - 2 * r, color); // Right // draw four corners drawCircleHelper(x + r, y + r, r, 1, color); drawCircleHelper(x + w - r - 1, y + r, r, 2, color); drawCircleHelper(x + w - r - 1, y + h - r - 1, r, 4, color); drawCircleHelper(x + r, y + h - r - 1, r, 8, color); } void fillRoundRect(int16_t x, int16_t y, int16_t w, int16_t h, int16_t r, uint16_t color) { int16_t max_radius = ((w < h) ? w : h) / 2; // 1/2 minor axis if (r > max_radius) r = max_radius; // smarter version dsp_fill_rect(x + r, y, w - 2 * r, h, color); // draw four corners fillCircleHelper(x + w - r - 1, y + r, r, 1, h - 2 * r - 1, color); fillCircleHelper(x + r, y + r, r, 2, h - 2 * r - 1, color); } void DrawEllipse(int16_t x0, int16_t y0, int16_t rx, int16_t ry, uint16_t color) { if (rx < 2) return; if (ry < 2) return; int16_t x, y; int32_t rx2 = rx * rx; int32_t ry2 = ry * ry; int32_t fx2 = 4 * rx2; int32_t fy2 = 4 * ry2; int32_t s; for (x = 0, y = ry, s = 2 * ry2 + rx2 * (1 - 2 * ry); ry2 * x <= rx2 * y; x++) { dsp_draw_pixel(x0 + x, y0 + y, color); dsp_draw_pixel(x0 - x, y0 + y, color); dsp_draw_pixel(x0 - x, y0 - y, color); dsp_draw_pixel(x0 + x, y0 - y, color); if (s >= 0) { s += fx2 * (1 - y); y--; } s += ry2 * ((4 * x) + 6); } for (x = rx, y = 0, s = 2 * rx2 + ry2 * (1 - 2 * rx); rx2 * y <= ry2 * x; y++) { dsp_draw_pixel(x0 + x, y0 + y, color); dsp_draw_pixel(x0 - x, y0 + y, color); dsp_draw_pixel(x0 - x, y0 - y, color); dsp_draw_pixel(x0 + x, y0 - y, color); if (s >= 0) { s += fy2 * (1 - x); x--; } s += rx2 * ((4 * y) + 6); } } void FillEllipse(int16_t x0, int16_t y0, int16_t rx, int16_t ry, uint16_t color) { if (rx < 2) return; if (ry < 2) return; int16_t x, y; int32_t rx2 = rx * rx; int32_t ry2 = ry * ry; int32_t fx2 = 4 * rx2; int32_t fy2 = 4 * ry2; int32_t s; for (x = 0, y = ry, s = 2 * ry2 + rx2 * (1 - 2 * ry); ry2 * x <= rx2 * y; x++) { dsp_draw_fast_h_line(x0 - x, y0 - y, x + x + 1, color); dsp_draw_fast_h_line(x0 - x, y0 + y, x + x + 1, color); if (s >= 0) { s += fx2 * (1 - y); y--; } s += ry2 * ((4 * x) + 6); } for (x = rx, y = 0, s = 2 * rx2 + ry2 * (1 - 2 * rx); rx2 * y <= ry2 * x; y++) { dsp_draw_fast_h_line(x0 - x, y0 - y, x + x + 1, color); dsp_draw_fast_h_line(x0 - x, y0 + y, x + x + 1, color); if (s >= 0) { s += fy2 * (1 - x); x--; } s += rx2 * ((4 * y) + 6); } } void fillTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint16_t color) { int16_t a, b, y, last; // Sort coordinates by Y order (y2 >= y1 >= y0) if (y0 > y1) { swap(y0, y1); swap(x0, x1); } if (y1 > y2) { swap(y2, y1); swap(x2, x1); } if (y0 > y1) { swap(y0, y1); swap(x0, x1); } if (y0 == y2) { // Handle awkward all-on-same-line case as its own thing a = b = x0; if (x1 < a) a = x1; else if (x1 > b) b = x1; if (x2 < a) a = x2; else if (x2 > b) b = x2; dsp_draw_fast_h_line(a, y0, b - a + 1, color); return; } int16_t dx01 = x1 - x0, dy01 = y1 - y0, dx02 = x2 - x0, dy02 = y2 - y0, dx12 = x2 - x1, dy12 = y2 - y1; int32_t sa = 0, sb = 0; // For upper part of triangle, find scanline crossings for segments // 0-1 and 0-2. If y1=y2 (flat-bottomed triangle), the scanline y1 // is included here (and second loop will be skipped, avoiding a /0 // error there), otherwise scanline y1 is skipped here and handled // in the second loop...which also avoids a /0 error here if y0=y1 // (flat-topped triangle). if (y1 == y2) last = y1; // Include y1 scanline else last = y1 - 1; // Skip it for (y = y0; y <= last; y++) { a = x0 + sa / dy01; b = x0 + sb / dy02; sa += dx01; sb += dx02; /* longhand: a = x0 + (x1 - x0) * (y - y0) / (y1 - y0); b = x0 + (x2 - x0) * (y - y0) / (y2 - y0); */ if (a > b) swap(a, b); dsp_draw_fast_h_line(a, y, b - a + 1, color); } // For lower part of triangle, find scanline crossings for segments // 0-2 and 1-2. This loop is skipped if y1=y2. sa = (int32_t)dx12 * (y - y1); sb = (int32_t)dx02 * (y - y0); for (; y <= y2; y++) { a = x1 + sa / dy12; b = x0 + sb / dy02; sa += dx12; sb += dx02; /* longhand: a = x1 + (x2 - x1) * (y - y1) / (y2 - y1); b = x0 + (x2 - x0) * (y - y0) / (y2 - y0); */ if (a > b) swap(a, b); dsp_draw_fast_h_line(a, y, b - a + 1, color); } } void drawTriangle(int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint16_t color) { dsp_draw_line(x0, y0, x1, y1, color); dsp_draw_line(x1, y1, x2, y2, color); dsp_draw_line(x2, y2, x0, y0, color); } void dsp_set_text_color(uint16_t color) { lcdprop.TextColor=color; } void dsp_set_back_color(uint16_t color) { lcdprop.BackColor=color; } void dsp_set_font(sFONT *pFonts) { lcdprop.pFont=pFonts; } void dsp_draw_char(uint16_t x, uint16_t y, uint8_t c) { uint32_t i = 0, j = 0; uint16_t height, width; uint16_t y_cur = y; uint8_t offset; uint8_t *c_t; uint8_t *pchar; uint32_t line=0; height = lcdprop.pFont->Height; width = lcdprop.pFont->Width; offset = 8 *((width + 7)/8) - width; c_t = (uint8_t*) &(lcdprop.pFont->table[(c-' ') * lcdprop.pFont->Height * ((lcdprop.pFont->Width + 7) / 8)]); for(i = 0; i < height; i++) { pchar = ((uint8_t*)c_t + (width + 7)/8 * i); switch(((width + 7)/8)) { case 1: line = pchar[0]; break; case 2: line = (pchar[0]<< 8) | pchar[1]; break; case 3: default: line = (pchar[0]<< 16) | (pchar[1]<< 8) | pchar[2]; break; } for(j = 0; j < width; j++) { if(line & (1 << (width- j + offset- 1))) { frame_buffer[(i*width + j) * 2] = lcdprop.TextColor >> 8; frame_buffer[(i*width + j)*2+1] = lcdprop.TextColor & 0xFF; } else { frame_buffer[(i*width + j)*2] = lcdprop.BackColor >> 8; frame_buffer[(i*width + j)*2+1] = lcdprop.BackColor & 0xFF; } } y_cur++; } dsp_set_addr_window(x, y, x+width-1, y+height-1); // -- dsp_write_data(frame_buffer,(uint32_t) width * height * 2); } void dsp_string(uint16_t x,uint16_t y, char *str) { while(*str) { dsp_draw_char(x,y,str[0]); x+=lcdprop.pFont->Width; (void)*str++; } } void dsp_set_rotation(uint8_t r) { dsp_send_command(0x36); switch(r) { case 0: dsp_send_data(0x48); dsp_width = 240; dsp_height = 320; break; case 1: dsp_send_data(0x28); dsp_width = 320; dsp_height = 240; break; case 2: dsp_send_data(0x88); dsp_width = 240; dsp_height = 320; break; case 3: dsp_send_data(0xE8); dsp_width = 320; dsp_height = 240; break; } } void dsp_fonts_ini(void) { Font8.Height = 8; Font8.Width = 5; Font12.Height = 12; Font12.Width = 7; Font16.Height = 16; Font16.Width = 11; Font20.Height = 20; Font20.Width = 14; Font24.Height = 24; Font24.Width = 17; lcdprop.BackColor=DSP_BLACK; lcdprop.TextColor=DSP_GREEN; lcdprop.pFont=&Font16; }
C
void write(int n, float b) { int i; int len; len = 0; for (i = 0; i < n; i = i + 1) { len = n + 1; } } int main(int argc) { int n; float b; b = 0.0; n = 128; write(n, b); return 0; }
C
#include <stdio.h> #include <string.h> #include <student_info_system/base.h> #include <student_info_system/util.h> int show_menu(const menu *menus, size_t menu_num, char *exist_str) { int tmp; int choose = 0; short invalid_input = 1; char _exist_str[255], hint[40], r_hint[40]; if (exist_str == NULL) sprintf(_exist_str, "%d. quit\n", menu_num + 1); else sprintf(_exist_str, "%d. %s\n", menu_num + 1, exist_str); sprintf(hint, "Please input your select: (1-%d): ", menu_num + 1); sprintf(r_hint, "Please input valid select: (1-%d): ", menu_num + 1); while (choose != menu_num) { CLEAR(); for (int i = 1; i <= menu_num; ++i) { printf("%d. %s\n", i, menus[i - 1].content); } printf(_exist_str); printf(hint); while (1) { choose = getchar(); CLEAR_STDIN_WITH_PRE(choose); choose -= '1'; if (choose < menu_num && choose >= 0) { tmp = menus[choose].funtion(); if (tmp) return tmp; break; } else if (choose == menu_num) break; else printf(r_hint); } } return 0; } int input_str( char *str, const unsigned int max_length, const char *first_remind, const char *last_remind, const char *warn_remind ) { int tmp; size_t index = 0; printf(first_remind); while (index < max_length && (tmp = getchar()) != '\n') str[index++] = (char)tmp; while (index == max_length && getchar() != '\n') { CLEAR_STDIN(); index = 0; fprintf(stderr, warn_remind); printf(last_remind); while (index < max_length && (tmp = getchar()) != '\n') str[index++] = (char)tmp; } str[index] = '\0'; return 0; }
C
#include<stdio.h> #include<stdlib.h> int main() { /* this program is awesome */ int a,b,c,d,e,f,g; // right //printf("") scanf("%d %d",&a,&b); printf("%d %d\n",a+b,a-b); }
C
#include <yaml.h> #include "myaml.h" #include "utils.h" #include <stdlib.h> #include <string.h> #include <assert.h> #include <stdarg.h> void dump_myaml_t(struct myaml_t *t, int level) { char header[30]; int i = 0; if (!t) return; snprintf(header, 20, "%.*s", level * 2, " "); switch (t->type) { case MYAML_OBJECT: printf("\n%s=> Object\n", header); while (t->keys[i]) { printf("%s %s: ", header, t->keys[i]); dump_myaml_t(t->childs[i], level + 1); i++; } break; case MYAML_ARRAY: printf("\n%s=> Array\n", header); while (t->childs[i]) { printf("%s %d: ", header, i); dump_myaml_t(t->childs[i], level + 1); i++; } break; case MYAML_SCALAR: printf("%s\n", t->value); break; case MYAML_NULL: printf("null\n"); break; } } void dump_myaml_type(enum myaml_type t) { } static void dump_token(yaml_token_t *token) { switch (token->type) { case YAML_NO_TOKEN: printf("YAML_NO_TOKEN\n"); break; case YAML_STREAM_START_TOKEN: printf("YAML_STREAM_START_TOKEN\n"); break; case YAML_STREAM_END_TOKEN: printf("YAML_STREAM_END_TOKEN\n"); break; case YAML_VERSION_DIRECTIVE_TOKEN: printf("YAML_VERSION_DIRECTIVE_TOKEN\n"); break; case YAML_TAG_DIRECTIVE_TOKEN: printf("YAML_TAG_DIRECTIVE_TOKEN\n"); break; case YAML_DOCUMENT_START_TOKEN: printf("YAML_DOCUMENT_START_TOKEN\n"); break; case YAML_DOCUMENT_END_TOKEN: printf("YAML_DOCUMENT_END_TOKEN\n"); break; case YAML_BLOCK_SEQUENCE_START_TOKEN: printf("YAML_BLOCK_SEQUENCE_START_TOKEN\n"); break; case YAML_BLOCK_MAPPING_START_TOKEN: printf("YAML_BLOCK_MAPPING_START_TOKEN\n"); break; case YAML_BLOCK_END_TOKEN: printf("YAML_BLOCK_END_TOKEN\n"); break; case YAML_FLOW_SEQUENCE_START_TOKEN: printf("YAML_FLOW_SEQUENCE_START_TOKEN\n"); break; case YAML_FLOW_SEQUENCE_END_TOKEN: printf("YAML_FLOW_SEQUENCE_END_TOKEN\n"); break; case YAML_FLOW_MAPPING_START_TOKEN: printf("YAML_FLOW_MAPPING_START_TOKEN\n"); break; case YAML_FLOW_MAPPING_END_TOKEN: printf("YAML_FLOW_MAPPING_END_TOKEN\n"); break; case YAML_BLOCK_ENTRY_TOKEN: printf("YAML_BLOCK_ENTRY_TOKEN\n"); break; case YAML_FLOW_ENTRY_TOKEN: printf("YAML_FLOW_ENTRY_TOKEN\n"); break; case YAML_KEY_TOKEN: printf("YAML_KEY_TOKEN\n"); break; case YAML_VALUE_TOKEN: printf("YAML_VALUE_TOKEN\n"); break; case YAML_ALIAS_TOKEN: printf("YAML_ALIAS_TOKEN\n"); break; case YAML_ANCHOR_TOKEN: printf("YAML_ANCHOR_TOKEN\n"); break; case YAML_TAG_TOKEN: printf("YAML_TAG_TOKEN\n"); break; case YAML_SCALAR_TOKEN: printf("YAML_SCALAR_TOKEN %s\n", token->data.scalar.value); break; } } /* ** Parser */ struct parser { yaml_parser_t *parser; yaml_token_t token; }; static struct myaml_t *myaml_parse(struct parser *parser); static yaml_token_t *parser_next_token(struct parser *parser) { yaml_token_delete(&parser->token); yaml_parser_scan(parser->parser, &parser->token); //dump_token(&parser->token); return &parser->token; } static yaml_token_t *parser_get_token(struct parser *parser) { return &parser->token; } static struct myaml_t *myaml_parse_scalar(struct parser *parser) { struct myaml_t *result = calloc(sizeof(struct myaml_t), 1); result->type = MYAML_SCALAR; result->value = strdup((const char *)parser_get_token(parser)->data.scalar.value); parser_next_token(parser); return result; } static struct myaml_t *myaml_parse_indentless_sequence(struct parser *parser) { yaml_token_t *token; struct myaml_t *result = calloc(sizeof(struct myaml_t), 1); result->type = MYAML_ARRAY; result->childs = calloc(sizeof(char *), 50); int stop = 0; token = parser_get_token(parser); while (!stop) { if (token->type != YAML_BLOCK_ENTRY_TOKEN) { return result; } token = parser_next_token(parser); append_to_array((void **)result->childs, myaml_parse(parser)); } return result; } static struct myaml_t *myaml_parse_sequence(struct parser *parser) { yaml_token_t *token; struct myaml_t *result = calloc(sizeof(struct myaml_t), 1); result->type = MYAML_ARRAY; result->childs = calloc(sizeof(char *), 50); int stop = 0; token = parser_get_token(parser); while (!stop) { switch (token->type) { case YAML_BLOCK_END_TOKEN: case YAML_FLOW_SEQUENCE_END_TOKEN: token = parser_next_token(parser); stop = 1; break; case YAML_BLOCK_ENTRY_TOKEN: case YAML_FLOW_ENTRY_TOKEN: case YAML_FLOW_SEQUENCE_START_TOKEN: token = parser_next_token(parser); if (token->type == YAML_KEY_TOKEN || token->type == YAML_BLOCK_END_TOKEN) { append_to_array((void **)result->childs, myaml_null()); break; } append_to_array((void **)result->childs, myaml_parse(parser)); break; case YAML_NO_TOKEN: case YAML_BLOCK_SEQUENCE_START_TOKEN: token = parser_next_token(parser); break; default: printf("Unknown type for sequence! "); dump_token(token); token = parser_next_token(parser); } } return result; } static struct myaml_t *myaml_parse_object(struct parser *parser) { yaml_token_t *token; struct myaml_t *result = calloc(sizeof(struct myaml_t), 1); result->type = MYAML_OBJECT; result->childs = calloc(sizeof(char *), 50); result->keys = calloc(sizeof(char *), 50); int stop = 0; token = parser_get_token(parser); while (!stop) { switch (token->type) { case YAML_KEY_TOKEN: token = parser_next_token(parser); assert(token->type == YAML_SCALAR_TOKEN); append_to_array((void **)result->keys, strdup((const char *)token->data.scalar.value)); token = parser_next_token(parser); break; case YAML_VALUE_TOKEN: token = parser_next_token(parser); if (token->type == YAML_KEY_TOKEN || token->type == YAML_BLOCK_END_TOKEN || token->type == YAML_FLOW_MAPPING_END_TOKEN) { if (token->type == YAML_BLOCK_END_TOKEN) stop = 1; append_to_array((void **)result->childs, myaml_null()); break; } append_to_array((void **)result->childs, myaml_parse(parser)); break; case YAML_BLOCK_END_TOKEN: case YAML_FLOW_MAPPING_END_TOKEN: stop = 1; case YAML_BLOCK_ENTRY_TOKEN: case YAML_FLOW_ENTRY_TOKEN: case YAML_BLOCK_MAPPING_START_TOKEN: case YAML_FLOW_MAPPING_START_TOKEN: case YAML_NO_TOKEN: token = parser_next_token(parser); break; default: printf("Unknown type for object! "); dump_token(token); token = parser_next_token(parser); } } return result; } static struct myaml_t *myaml_parse(struct parser *parser) { yaml_token_t *token = parser_get_token(parser); switch (parser_get_token(parser)->type) { case YAML_BLOCK_MAPPING_START_TOKEN: case YAML_FLOW_MAPPING_START_TOKEN: return myaml_parse_object(parser); case YAML_BLOCK_SEQUENCE_START_TOKEN: case YAML_FLOW_SEQUENCE_START_TOKEN: return myaml_parse_sequence(parser); case YAML_BLOCK_ENTRY_TOKEN: //indentless sequence return myaml_parse_indentless_sequence(parser); case YAML_SCALAR_TOKEN: return myaml_parse_scalar(parser); case YAML_STREAM_START_TOKEN: case YAML_DOCUMENT_START_TOKEN: case YAML_NO_TOKEN: parser_next_token(parser); return myaml_parse(parser); case YAML_STREAM_END_TOKEN: return 0; default: printf("Unknown for type parse ! "); dump_token(token); } return 0; } struct myaml_t *myaml_loadf(FILE *conf) { yaml_parser_t parser; struct parser mparse; if (!yaml_parser_initialize(&parser)) { printf("Failed to init yaml parser!\n"); } if (!conf) { printf("Failed to open conf file !\n"); } yaml_parser_set_input_file(&parser, conf); mparse.parser = &parser; yaml_parser_scan(&parser, &mparse.token); struct myaml_t *result = myaml_parse(&mparse); yaml_parser_delete(&parser); return result; } struct myaml_t *myaml_loads(char *str) { yaml_parser_t parser; struct parser mparse; if (!yaml_parser_initialize(&parser)) { printf("Failed to init yaml parser!\n"); } yaml_parser_set_input_string(&parser, str, strlen(str)); mparse.parser = &parser; yaml_parser_scan(&parser, &mparse.token); struct myaml_t *result = myaml_parse(&mparse); yaml_parser_delete(&parser); return result; } /* ** User fonctions */ int myaml_array_size(struct myaml_t *obj) { if (obj->type != MYAML_ARRAY) return -1; return array_len((void **)obj->childs); } struct myaml_t *myaml_array_get(struct myaml_t *obj, int index) { assert(index < myaml_array_size(obj)); return obj->childs[index]; } struct myaml_t *myaml_null(void) { static struct myaml_t *result = 0; if (!result) { result = calloc(sizeof(struct myaml_t), 1); result->type = MYAML_NULL; } return result; } struct myaml_t *myaml_object_get(struct myaml_t *obj, char *key) { if (obj->type != MYAML_OBJECT) return 0; int i = 0; while (obj->keys[i]) { if (strcmp(obj->keys[i], key) == 0) return obj->childs[i]; i++; } return 0; } char *myaml_scalar_value(struct myaml_t *obj) { if (obj->type != MYAML_SCALAR) return 0; return obj->value; } void myaml_free(struct myaml_t *f) { int i = 0; switch (f->type) { case MYAML_OBJECT: while (f->keys[i]) { free(f->keys[i]); myaml_free(f->childs[i]); i++; } free(f->keys); free(f->childs); break; case MYAML_ARRAY: while (f->childs[i]) { myaml_free(f->childs[i]); i++; } free(f->childs); break; case MYAML_SCALAR: free(f->value); break; case MYAML_NULL: return; } free(f); } /* ** Pack / Unpack */ struct unpacker { const char *fmt; char error[255]; va_list *ap; }; static int unpack(struct myaml_t *f, struct unpacker *unpacker); static char next_token(struct unpacker *unpacker) { //printf("next_token old: %c", unpacker->fmt[0]); do { unpacker->fmt = unpacker->fmt + 1; } while (strchr("{}[]asi?r", unpacker->fmt[0]) == 0 && unpacker->fmt[0]); //printf(" new: %c\n", unpacker->fmt[0]); return unpacker->fmt[0]; } static char get_token(struct unpacker *unpacker) { return unpacker->fmt[0]; } static int unpack_array(struct myaml_t *f, struct unpacker *unpacker) { assert(!f || f->type == MYAML_ARRAY); int stop = 0; next_token(unpacker); int i = 0; while (get_token(unpacker) != ']') { struct myaml_t *child = f ? myaml_array_get(f, i++) : 0; if (!child) { sprintf(unpacker->error, "No child %d!", i); return 1; } if (unpack(child, unpacker)) return 1; } next_token(unpacker); return 0; } static int unpack_object(struct myaml_t *f, struct unpacker *unpacker) { assert(!f || f->type == MYAML_OBJECT); int stop = 0; next_token(unpacker); while (get_token(unpacker) != '}') { if (get_token(unpacker) != 's') { sprintf(unpacker->error, "ERROR! Excepted 's', got '%c'", get_token(unpacker)); return 1; } next_token(unpacker); int required = 1; if (get_token(unpacker) == '?') { required = 0; next_token(unpacker); } char *key = va_arg(*unpacker->ap, char *); struct myaml_t *child = f ? myaml_object_get(f, key) : 0; if (!child && required) { sprintf(unpacker->error, "No child %s!", key); return 1; } if (unpack(child, unpacker)) return 1; } next_token(unpacker); return 0; } static int unpack_autoarray(struct myaml_t *s, struct unpacker *unpacker) { assert(get_token(unpacker) == 'a'); next_token(unpacker); if (!s) { //Empty array I guess next_token(unpacker); return 0; } char ***starget; int array_size; int i; switch (get_token(unpacker)) { case 's': starget = va_arg(*unpacker->ap, char ***); array_size = myaml_array_size(s); *starget = calloc(sizeof(char *), array_size + 1); i = 0; while (i < array_size) { (*starget)[i] = strdup(s->childs[i]->value); i++; } break; default: sprintf(unpacker->error, "Error, unsupported type for auto array '%c'", get_token(unpacker)); return 1; } next_token(unpacker); return 0; } static int unpack_raw(struct myaml_t *s, struct unpacker *unpacker) { assert(get_token(unpacker) == 'r'); struct myaml_t **target = va_arg(*unpacker->ap, struct myaml_t **); *target = s; next_token(unpacker); return 0; } static int unpack_scalar(struct myaml_t *s, struct unpacker *unpacker) { assert(!s || s->type == MYAML_SCALAR); if (s) { char **starget; int *itarget; switch (get_token(unpacker)) { case 's': starget = va_arg(*unpacker->ap, char **); *starget = strdup(s->value); break; case 'i': itarget = va_arg(*unpacker->ap, int *); *itarget = atoi(s->value); break; default: sprintf(unpacker->error, "Error, unknown scalar '%c'", get_token(unpacker)); return 1; } } else va_arg(*unpacker->ap, void *); next_token(unpacker); return 0; } static int unpack(struct myaml_t *f, struct unpacker *unpacker) { switch (get_token(unpacker)) { case '{': return unpack_object(f, unpacker); case '[': return unpack_array(f, unpacker); case 's': case 'i': return unpack_scalar(f, unpacker); case 'r': return unpack_raw(f, unpacker); case 'a': return unpack_autoarray(f, unpacker); default: sprintf(unpacker->error, "Error, unknown type in unpack '%c'", get_token(unpacker)); return 1; } } int myaml_unpack(struct myaml_t *f, const char *fmt, ...) { struct unpacker unpacker; va_list ap_copy; memset(&unpacker, 0, sizeof(struct unpacker)); va_start(ap_copy, fmt); unpacker.fmt = fmt; unpacker.ap = &ap_copy; int result = unpack(f, &unpacker); va_end(ap_copy); if (strlen(unpacker.error) > 0) { printf("Unpacking failed! %s\n", unpacker.error); } return result; }
C
//Write a program to generate Armstrong number. #include<stdio.h> void main() { int r; long int number=0,c,sum=0,temp; printf("Enter an integer upto which you want to find armstrong numbers\n"); scanf("%ld",&number); printf("Following armstrong numbers are found from 1 to %ld\n",number); for(c=1;c<=number;c++) { temp=c; while(temp!=0) { r=temp%10; sum=sum+r*r*r; temp=temp/10; } if(c==sum) printf("%ld\n",c); sum=0; } }
C
#include <stdio.h> int main(){ char *str = "OfdlDSA|3tXb32~X3tX@sX`4tXtz"; int key=0; for(int i=0;i<=28;i++){ // key = (key+1) ^ 0x7; printf("%c",str[i]^7); } // printf("%s",str); /* OfdlDSA|3tXb32~X3tX@sX`4tXtz 0x1이랑 0x17을 바꾸면서 반복 check 함수 - key 에 들어갈 수 있는 값은 7 아니면 0 */ }
C
#ifndef DIGIT_H #define DIGIT_H /* Data Structures */ // Stores a single digit and its label. typedef struct Digit { float* pixels; // vector of length numPixels that holds data arry, in row major format int label; // set to -1 if unlabelled int numRows; int numCols; int numPixels; } Digit; // Stores an array of digits, and the length of the array. typedef struct DigitSet { Digit** digits; int numDigits; int numRows; int numCols; int numPixels; } DigitSet; /* Functions */ // Creates a new digit object. Digit* NewDigit(int numRows, int numCols); // Frees the memory associated with a digit object. void FreeDigit(Digit* digit); // Creates a new digit set. DigitSet* NewDigitSet(int numDigits, int numRows, int numCols); // Frees the memory associated with a digit set. If freeDigits is true, we // also call FreeDigit on each of our digits. void FreeDigitSet(DigitSet* digitSet, bool freeDigits); // Loads a digit set from disk. DigitSet* LoadDigits(char* imageFilename, char* labelFilename); // Saves a digit set to disk. It saves the digits in the range [start, end]. void SaveDigits(DigitSet* digitSet, char* imageFilename, char* labelFilename, int start, int end); // Prints an ASCII version of the digit to stdout. void PrintDigit(Digit* digit); #endif
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <time.h> #include <getopt.h> #include <errno.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #include "fileutils.h" #include <sodium.h> #include "keyfiles.h" int fileno(FILE *); struct parameters { short int benchmark; int benchmark_count; char *filename; char *pk_fname; char *out_name; }; void print_usage(FILE * stream, int exit_code, char *prog) { fprintf(stream, "Usage: %s [options] FILENAME PUBLICKEY\n", prog); fprintf(stream, "Options:\n"); fprintf(stream, " -h, --help Show this help\n"); fprintf(stream, " --bench COUNT Run the encryption COUNT times and\n" " print only benchmarks to stdout\n"); fprintf(stream, " -o, --out FNAME Output ciphertext to FNAME\n"); exit(exit_code); } int parse_opt(int argc, char **argv, struct parameters *opts) { int option_index; int c; struct option long_options[] = { {"help", no_argument, NULL, 'h'}, {"bench", required_argument, NULL, 0}, {"out", required_argument, NULL, 'o'}, {NULL, 0, NULL, 0} }; char *program_name = argv[0]; while (1) { option_index = 0; c = getopt_long(argc, argv, "ho:", long_options, &option_index); if (c == -1) break; switch (c) { case 0: /* long option without a short arg */ if (strcmp("bench", long_options[option_index].name) == 0) { opts->benchmark = 1; if (!sscanf(optarg, "%d", &opts->benchmark_count)) { fprintf(stderr, "'%s' is not a valid integer\n", optarg); return 2; } if (opts->benchmark_count < 1) { fprintf(stderr, "-b must be >= 1, got %d instead\n", opts->benchmark_count); return 2; } } break; case 'h': print_usage(stdout, 0, program_name); break; case 'o': opts->out_name = calloc(strlen(optarg) + 1, sizeof(char)); strncpy(opts->out_name, optarg, strlen(optarg)); break; case '?': break; default: break; } } if (argc - optind != 2) { fprintf(stderr, "Wrong number of arguments\n"); return 2; } if(!(opts->out_name || opts->benchmark)) { fprintf(stderr, "Either --bench or --out is required\n"); return 2; } if(opts->out_name && opts->benchmark) { fprintf(stderr, "--bench and --out are mutually exclusive\n"); return 2; } if (optind < argc) { int argnumber = 0; while (optind + argnumber < argc) { switch (argnumber) { case 0: opts->filename = argv[optind + argnumber++]; break; case 1: opts->pk_fname = argv[optind + argnumber++]; break; } } } return 0; } int main(int argc, char **argv) { if (sodium_init() == -1) { return 11; } unsigned char *c; int cipher_fd = fileno(stdout); unsigned char *plain = NULL; long plain_len; struct parameters params; params.benchmark = 0; params.benchmark_count = 1; params.pk_fname = NULL; params.out_name = NULL; int parse_ret = parse_opt(argc, argv, &params); if (parse_ret) { print_usage(stderr, parse_ret, argv[0]); } unsigned char pk[crypto_box_PUBLICKEYBYTES]; if (pk_read(params.pk_fname, pk)) { fprintf(stderr, "Error reading public key\n"); return 1; } plain_len = file_mmapwhole(params.filename, &plain); if (plain_len < 0 || !plain) { if (plain) { munmap(plain, plain_len); } fprintf(stderr, "Error reading file\n"); return 1; } if (!params.benchmark) { if (params.out_name != NULL) { cipher_fd = open(params.out_name, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR); free(params.out_name); if(cipher_fd == -1) { fprintf(stderr, "Error opening output file (%s)", strerror(errno)); munmap(plain, plain_len); return 1; } } lseek(cipher_fd, plain_len + crypto_box_SEALBYTES - 1, SEEK_SET); write(cipher_fd, "", 1); lseek(cipher_fd, 0, SEEK_SET); c = mmap(0, plain_len + crypto_box_SEALBYTES, PROT_READ | PROT_WRITE, MAP_SHARED, cipher_fd, 0); if(c == MAP_FAILED) { fprintf(stderr, "Error opening output buffer: %s\n", strerror(errno)); munmap(plain, plain_len); return 1; } memset(c, '\0', plain_len + crypto_box_SEALBYTES); const int r = crypto_box_seal(c, plain, plain_len, pk); munmap(c, plain_len + crypto_box_SEALBYTES); if (r != 0) { fprintf(stderr, "Error %d occured\n", r); munmap(plain, plain_len); return 1; } } else { time_t starttime = time(NULL); c = calloc(plain_len + crypto_box_SEALBYTES, sizeof(char)); for (int i = 0; i < params.benchmark_count; i++) { crypto_box_seal(c, plain, plain_len, pk); } free(c); fprintf(stderr, "Time per cycle: %.3f\n", (double) (time(NULL) - starttime) / params.benchmark_count); } return 0; }
C
#include "state.h" #include "gpio.h" #include "climate.h" #include <stdlib.h> #include <stdio.h> struct HouseState init_state() { struct HouseState state; get_sensor_data(&(state.temperature), &(state.humidity)); state.lamp01 = read_device(LAMP01); state.lamp02 = read_device(LAMP02); state.lamp03 = read_device(LAMP03); state.lamp04 = read_device(LAMP04); state.air01 = read_device(AIR01); state.air02 = read_device(AIR02); init_guarded_device_state(&(state.presence01), PRESENCE01); init_guarded_device_state(&(state.presence02), PRESENCE02); init_guarded_device_state(&(state.open01), OPEN01); init_guarded_device_state(&(state.open02), OPEN02); init_guarded_device_state(&(state.open03), OPEN03); init_guarded_device_state(&(state.open04), OPEN04); init_guarded_device_state(&(state.open05), OPEN05); init_guarded_device_state(&(state.open06), OPEN06); return state; } void get_air_lamps_state(struct HouseState *state) { state->lamp01 = read_device(LAMP01); state->lamp02 = read_device(LAMP02); state->lamp03 = read_device(LAMP03); state->lamp04 = read_device(LAMP04); state->air01 = read_device(AIR01); state->air02 = read_device(AIR02); } void get_climate_state(struct HouseState *state) { get_sensor_data(&(state->temperature), &(state->humidity)); } void init_guarded_device_state(GuardedDevice *device, int device_flag) { device->alarm_activated = 0; device->state = read_device(device_flag); } int get_guarded_device_state(GuardedDevice *device, int device_flag) { device->state = read_device(device_flag); if (device->state && !device->alarm_activated) { device->alarm_activated = 1; return 1; } else if (!device->state && device->alarm_activated) { device->alarm_activated = 0; } return 0; } int get_presence_sensors_state(struct HouseState *state) { int trigger_alarm = 0; trigger_alarm = trigger_alarm || get_guarded_device_state(&(state->presence01), PRESENCE01); trigger_alarm = trigger_alarm || get_guarded_device_state(&(state->presence02), PRESENCE02); return trigger_alarm; } int get_open_sensors_state(struct HouseState *state) { int trigger_alarm = 0; trigger_alarm = trigger_alarm || get_guarded_device_state(&(state->open01), OPEN01); trigger_alarm = trigger_alarm || get_guarded_device_state(&(state->open02), OPEN02); trigger_alarm = trigger_alarm || get_guarded_device_state(&(state->open03), OPEN03); trigger_alarm = trigger_alarm || get_guarded_device_state(&(state->open04), OPEN04); trigger_alarm = trigger_alarm || get_guarded_device_state(&(state->open05), OPEN05); trigger_alarm = trigger_alarm || get_guarded_device_state(&(state->open06), OPEN06); return trigger_alarm; } char *state_to_string(struct HouseState *state) { char *message = malloc(68 * sizeof(char)); sprintf( message, "%.2f, %.2f, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d", state->temperature, state->humidity, state->lamp01, state->lamp02, state->lamp03, state->lamp04, state->air01, state->air02, state->presence01.state, state->presence02.state, state->open01.state, state->open02.state, state->open03.state, state->open04.state, state->open05.state, state->open06.state ); return message; }
C
#include <stdio.h> #include <stdlib.h> int n,k; int f91(int); int main() { while(scanf("%d", &n),n!=0) { k=f91(n); printf("f91(%d) = %d\n",n,k); } return 0; } int f91(int n) { if(n<=100) return f91(f91(n+11)); else return n-10; }
C
//Diógenes Silva Pedro 11883476 void algoritmo1(int *values, int N){ int i, j = 0; //a int tmp; for (i = 0; i < N; i++){ //1. (a+b) 2. n.(2a+b) = a + b + 2an + bn for (j = 0; j < N; j++){ //1. n(a+b) 2. n(n.(2a+b)) = an + bn + 2an² + bn² if (values[j] > values[j+1]){ //n(n(a + b)) = a.n² + b.n² tmp = values[j+1]; //n(n(2a)) = 2a.n² values[j+1] = values[j]; //n(n(2a)) = 2a.n² values[j] = tmp; //n(n(a)) = a.n² } } } } //f(n) = a + (a+b) + n.(2a+b) + n(a+b) + n(n.(2a+b)) + n(n(a+b)) + n(n(2a)) + n(n(2a)) + n(n(a)) //f(n) = a + a + b + 2an + bn + an + bn + 2an² + bn² + a.n² + b.n² + 2a.n² + 2a.n² + a.n² //f(n) = 8an² + 2bn² + 3an + 2bn + 2a + b //Denotando todas as variáveis com tempos aproximadamente iguais temos a = b = K, logo: //f(n) = 10Kn² + 5Kn + 3K
C
#include <signal.h> #include <unistd.h> #include <stdlib.h> void foo (void); void bar (void); void subroutine (int); void handler (int); void have_a_very_merry_interrupt (void); int main () { foo (); /* Put a breakpoint on foo() and call it to see a dummy frame */ have_a_very_merry_interrupt (); return 0; } void foo (void) { } void bar (void) { *(char *)0 = 0; /* try to cause a segfault */ /* On MMU-less system, previous memory access to address zero doesn't trigger a SIGSEGV. Trigger a SIGILL. Each arch should define its own illegal instruction here. */ #if defined(__arm__) asm(".word 0xf8f00000"); #elif defined(__TMS320C6X__) asm(".word 0x56454313"); #else #endif } void handler (int sig) { subroutine (sig); } /* The first statement in subroutine () is a place for a breakpoint. Without it, the breakpoint is put on the while comparison and will be hit at each iteration. */ void subroutine (int in) { int count = in; while (count < 100) count++; } void have_a_very_merry_interrupt (void) { signal (SIGALRM, handler); alarm (1); sleep (2); /* We'll receive that signal while sleeping */ }
C
#include "xdvi-config.h" #include "dl_list.h" size_t dl_list_len(struct dl_list *list) { size_t len = 0; struct dl_list *ptr; for (ptr = list; ptr != NULL; ptr = ptr->next, len++) { ; } return len; } /* Insert item to the list and return the result. */ struct dl_list * dl_list_insert(struct dl_list *list, void *item) { struct dl_list *new_elem = xmalloc(sizeof *new_elem); new_elem->item = item; new_elem->next = NULL; new_elem->prev = NULL; if (list == NULL) { list = new_elem; } else { /* append after current position */ struct dl_list *ptr = list; new_elem->next = ptr->next; new_elem->prev = ptr; if (ptr->next != NULL) ptr->next->prev = new_elem; ptr->next = new_elem; } return new_elem; } /* Return head of the list. */ struct dl_list * dl_list_head(struct dl_list *list) { for (; list != NULL && list->prev != NULL; list = list->prev) { ; } return list; } /* Put a new item at the front of the list (current front is passed in first argument) and return its position. */ struct dl_list * dl_list_push_front(struct dl_list *list, void *item) { struct dl_list *new_elem = xmalloc(sizeof *new_elem); new_elem->item = item; new_elem->next = NULL; new_elem->prev = NULL; if (list != NULL) { /* prepend to current position */ new_elem->next = list; list->prev = new_elem; } return new_elem; } /* Truncate list so that current pointer is the last element. */ struct dl_list * dl_list_truncate(struct dl_list *list) { struct dl_list *ptr = list->next; struct dl_list *save; list->next = NULL; while (ptr != NULL) { save = ptr->next; free(ptr); ptr = save; } return list; } /* Truncate list at the head (i.e. remove the first element from it - head must be passed to this list), and return the result. */ struct dl_list * dl_list_truncate_head(struct dl_list *list) { struct dl_list *ptr = list->next; if (list->next != NULL) list->next->prev = NULL; free(list); return ptr; } /* If the item pointed to by *list isn't the head of the list, remove it, set *list to the previous item, and return True. Else return False. */ Boolean dl_list_remove_item(struct dl_list **list) { struct dl_list *ptr = *list; /* item to remove */ if (ptr->prev == NULL) return False; ptr->prev->next = ptr->next; if (ptr->next != NULL) ptr->next->prev = ptr->prev; /* update list */ *list = (*list)->prev; /* remove item */ free(ptr); return True; } void dl_list_apply(struct dl_list *list, void (*func)(const void *item)) { struct dl_list *ptr; for (ptr = list; ptr != NULL; ptr = ptr->next) { func(ptr->item); } } /* Remove all items matching compare_func() from list. Must be called with a pointer to the head of the list, which is also returned. Returns the number of removed items in `count'. */ struct dl_list * dl_list_remove(struct dl_list *list, const void *item, int *count, void **removed_item, Boolean (*compare_func)(const void *item1, const void *item2)) { struct dl_list *ptr = list; while (ptr != NULL) { struct dl_list *next = ptr->next; if (compare_func(ptr->item, item)) { /* match */ *removed_item = ptr->item; (*count)++; if (ptr->prev != NULL) { ptr->prev->next = ptr->next; } else { /* removed first element */ list = list->next; } if (ptr->next != NULL) ptr->next->prev = ptr->prev; free(ptr); ptr = NULL; } ptr = next; } return list; }
C
#ifndef UTIL_H__ #define UTIL_H__ #define __USE_BSD 1 #define INPUT_WIDTH 7000 #define INPUT_HEIGHT 7000 #include <stdio.h> #include <time.h> #include <sys/time.h> void** alloc_2d(size_t y_size, size_t x_size, size_t element_size); #define TIME_IT(ROUTINE_NAME__, LOOPS__, ACTION__)\ {\ printf(" Timing '%s' started\n", ROUTINE_NAME__);\ struct timeval tv;\ struct timezone tz;\ const clock_t startTime = clock();\ gettimeofday(&tv, &tz); long GTODStartTime = tv.tv_sec * 1000000 + tv.tv_usec;\ for (int loops = 0; loops < (LOOPS__); ++loops)\ {\ ACTION__;\ }\ gettimeofday(&tv, &tz); long GTODEndTime = tv.tv_sec * 1000000 + tv.tv_usec;\ const clock_t endTime = clock();\ const clock_t elapsedTime = endTime - startTime;\ const double timeInMilliseconds = (elapsedTime*1000/(double)CLOCKS_PER_SEC);\ printf(" GetTimeOfDay Time (for %d iterations) = %g ms\n", LOOPS__, (double)(GTODEndTime - GTODStartTime)/1000.0 );\ printf(" Clock Time (for %d iterations) = %g ms\n", LOOPS__, timeInMilliseconds );\ printf(" Timing '%s' ended\n", ROUTINE_NAME__);\ } #endif
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 */ struct sort_list_item {scalar_t__ str; int /*<<< orphan*/ ka; } ; struct key_value {scalar_t__ k; } ; /* Variables and functions */ scalar_t__ bws_memsize (scalar_t__) ; struct key_value* get_key_from_keys_array (int /*<<< orphan*/ *,size_t) ; int keys_array_size () ; size_t keys_num ; size_t sort_list_item_size(struct sort_list_item *si) { size_t ret = 0; if (si) { ret = sizeof(struct sort_list_item) + keys_array_size(); if (si->str) ret += bws_memsize(si->str); for (size_t i = 0; i < keys_num; ++i) { const struct key_value *kv; kv = get_key_from_keys_array(&si->ka, i); if (kv->k != si->str) ret += bws_memsize(kv->k); } } return (ret); }
C
#include<stdio.h> #include<stdlib.h> struct node{ int data; struct node* next; }; int main() { struct node* head = NULL; push(&head,4); push(&head,5); push(&head,6); push(&head,7); swap(&head,6,5); show(head); } void push(struct node** head,int num) { struct node* new_node = (struct node*)malloc(sizeof(struct node)); new_node->data = num; new_node->next = NULL; new_node->next= (*head); (*head) = new_node; } void show(struct node* node) { while(node!=NULL) { printf(" %d ",node->data); node= node->next; } } void swap(struct node** head,int x,int y) { if(x==y) return; struct node* temp = *head; while(temp!=NULL) { if(temp->data==x) temp->data = y; else if(temp->data==y) temp->data = x; temp = temp->next; } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct{ char nome[50]; char endereco[100]; int matricula; } estudante; int main(void){ int num, i; printf("Digite o número de posições: "); scanf("%d", &num); estudante * p = (int *)calloc(num, sizeof(estudante)); if(!p) printf("Memória Insuficiente.\n"); for(i=0;i<num;i++){ __fpurge(stdin); printf("Digite o %dº nome: ",i+1); fgets((p+i)->nome,50,stdin); printf("Digite o %dº endereço: ",i+1); fgets((p+i)->endereco,50,stdin); printf("Digite a %dº matricula: ",i+1); scanf("%d", &(p+i)->matricula); __fpurge(stdin); } for(i=0;i<num;i++){ printf("\nPosição: %p\n", (p+i)); printf("Nome: %s", (p+i)->nome); printf("Endereço: %s", (p+i)->endereco); printf("Matricula: %d\n", (p+i)->matricula); } free(p); return 0; }
C
#include <stdio.h> int main(void) { int prviDanTin, drugiDanTin, treciDanTin, cetvrtiDanTin, prviDanTan, drugiDanTan, treciDanTan, cetvrtiDanTan; printf("Unesi koliko je Tin napravio koraka za 1. dan: "); scanf("%d", &prviDanTin); printf("Unesi koliko je Tin napravio koraka za 2. dan: "); scanf("%d", &drugiDanTin); printf("Unesi koliko je Tin napravio koraka za 3. dan: "); scanf("%d", &treciDanTin); printf("Unesi koliko je Tin napravio koraka za 4. dan: "); scanf("%d", &cetvrtiDanTin); printf("Unesi koliko je Tan napravio koraka za 1. dan: "); scanf("%d", &prviDanTan); printf("Unesi koliko je Tan napravio koraka za 2. dan: "); scanf("%d", &drugiDanTan); printf("Unesi koliko je Tan napravio koraka za 3. dan: "); scanf("%d", &treciDanTan); printf("Unesi koliko je Tan napravio koraka za 4. dan: "); scanf("%d", &cetvrtiDanTan); if (prviDanTin > prviDanTan) printf("Tin\n"); else printf("Tan\n"); if (drugiDanTin > drugiDanTan) printf("Tin\n"); else printf("Tan\n"); if (treciDanTin > treciDanTan) printf("Tin\n"); else printf("Tan\n"); if (cetvrtiDanTin > cetvrtiDanTan) printf("Tin\n"); else printf("Tan\n"); return 0; }
C
#include <stdlib.h> #include <stdio.h> int b[3], g[3], c[3]; int bgc(int a1, int a2, int a3) { /*printf("b%d g%d c%d\n", b[a1],g[a2],c[a3]);*/ return b[a1] + g[a2] + c[a3]; } int main() { int count; while (scanf("%d %d %d %d %d %d %d %d %d", b, g, c, b+1, g+1, c+1, b+2, g+2, c+2) == 9) { int best, n, sum; char * o = "BCG"; best = bgc(0,2,1); if ((n = bgc(0,1,2)) > best) { best = n; o = "BGC"; } if ((n = bgc(1,2,0)) > best) { best = n; o = "CBG"; } if ((n = bgc(2,1,0)) > best) { best = n; o = "CGB"; } if ((n = bgc(1,0,2)) > best) { best = n; o = "GBC"; } if ((n = bgc(2,0,1)) > best) { best = n; o = "GCB"; } sum = b[0]+b[1]+b[2]+c[0]+c[1]+c[2]+g[0]+g[1]+g[2]; printf("%s %d\n", o, sum-best); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <locale.h> #include <math.h> void main(){ setlocale(LC_ALL, ""); // Variaveis int escolha, valor01, valor02, valor03, soma, sub, div, mult, raiz; // op��es de escolhas matematicas printf("Escolha uma das opcoes abaixo:" "\n 1: Soma de 3 Valores " "\n 2: Soma de 2 Valores" "\n 3: Subtracao de 2 Valores" "\n 4: Divisao de 2 Valores" "\n 5: Multiplicacao de 2 Valores" "\n 6: Multiplicacao de 3 Valores" "\n 7: Raiz Quadrada de 1 Valor(OBS.: Nao pode ser negativo): "); // escolha de opera��o matematica scanf("%d", &escolha); switch(escolha){ case 1: printf("\nOpcao escolhida foi a soma de 3 valores, digite o primeiro valor: "), scanf("%d", &valor01); printf("Digite o segundo valor "), scanf("%d", &valor02); printf("Digite o terceiro valor "), scanf("%d", &valor03); soma = valor01 + valor02 + valor03; printf("O resultado da soma de %d com %d com %d � %d", valor01, valor02, valor03, soma); break; case 2: printf("\nOpcao escolhida foi a soma de 2 valores, digite o primeiro valor: "), scanf("%d", &valor01); printf("Digite o segundo valor "), scanf("%d", &valor02); soma = valor01 + valor02; printf("O resultado da soma de %d com %d = %d", valor01, valor02, soma); break; case 3: printf("\nOpcao escolhida foi a subtracao de 2 valores, digite o primeiro valor: "), scanf("%d", &valor01); printf("Digite o segundo valor "), scanf("%d", &valor02); sub = valor01 - valor02; printf("O resultado da subtracao de %d com %d = %d", valor01, valor02, sub); break; case 4: printf("\nOpcao escolhida foi a divisso de 2 valores, digite o primeiro valor: "), scanf("%d", &valor01); printf("Digite o segundo valor "), scanf("%d", &valor02); div = valor01 / valor02; printf("O resultado da divisso de %d com %d = %d", valor01, valor02, div); break; case 5: printf("\nOpcao escolhida foi a multiplicacao de 2 valores, digite o primeiro valor: "), scanf("%d", &valor01); printf("Digite o segundo valor "), scanf("%d", &valor02); mult = valor01 * valor02; printf("O resultado da multipicacao de %d com %d = %d", valor01, valor02, mult); break; case 6: printf("\nOpcao escolhida foi a multiplicacao de 3 valores, digite o primeiro valor: "), scanf("%d", &valor01); printf("Digite o segundo valor "), scanf("%d", &valor02); printf("Digite o terceiro valor "), scanf("%d", &valor03); mult = valor01 * valor02 * valor03; printf("O resultado da multiplicacao de %d com %d com %d = %d", valor01, valor02, valor03, mult); break; case 7: printf("\nOpcao escolhida foi a raiz quadrada de um valor, digite o primeiro valor: "), scanf("%d", &valor01); switch (valor01 > 0) raiz = sqrt(valor01); printf("O resultado da raiz quadrada de %d = %d", valor01, raiz); break; default: printf("O valor inserido e invalido"); break; break; } system("pause"); }
C
#include "function_pointers.h" /** * array_iterator - Entry point * @array: Array of numbers * @size: Size of array * @action: Function pointer to function * * Description: I dont know * Return: Nothing */ void array_iterator(int *array, size_t size, void (*action)(int)) { unsigned int i = 0; if ((size != 0) && (array != 0) && (action != 0)) { for (i = 0 ; i < size ; i++) { (*action)(array[i]); } } }
C
/* * ===================================================================================== * * Filename: branch1.c * * Description: Basics of branching * * Version: 1.0 * Created: 01/30/2018 08:51:46 AM * Revision: none * Compiler: gcc * * Author: Trevor Culp (), [email protected] * Organization: WSU * * ===================================================================================== */ #include <stdio.h> #include <math.h> // Constants // Function Prototypes // Main Function int main() { int age = 0; int temp = 0; //request user input printf("How old are you?\n"); scanf("%d", &age); printf("You are %d years old.\n", age); //do not add a semicolon at the end of if statement if (age >= 18) //if true,go inside the block { printf("You can vote.\n"); } else // do not use (), Default case of FALSE case. { temp = 18 - age; printf("You have %d years to vote.\n", temp); } if (age >= 21) { printf("You can buy alcohol.\n"); } else { temp = 21 - age; printf("You have %d years to buy alcohol.\n", temp); } if (age >= 65) { printf("You can retire.\n"); } else { temp = 65 - age; printf("You have %d years to retire.\n", temp); } if (age == 35) { printf("You are at the special age %d.\n", age); } printf("Adios amigo.\n"); return 0; } // Function Definitions
C
#include<stdlib.h> #include<stdio.h> #include<string.h> #include<math.h> #include"post_stats.h" void read_post_samples(char* file_name,live_point* psamps,unsigned long num_post_samps,unsigned num_dim) { FILE* infile; unsigned long i; unsigned j; double val; infile=fopen(file_name,"r"); if(infile!=NULL) { for(i=0;i<num_post_samps;++i) { if(feof(infile)) break; for(j=0;j<num_dim;++j) { fscanf(infile,"%le",&val); psamps[i].x[j]=val; } fscanf(infile,"%le",&val); psamps[i].log_lik=val; fscanf(infile,"%le",&val); psamps[i].log_weight=val; } if(i!=num_post_samps) { printf("\t ERROR! Number of posterior samples in %s (%ld) \n\t!= Number of posterior samples expected (%ld) (aborting!)\n",file_name,i,num_post_samps); exit(-1); } fclose(infile); } else { printf("Unable to open file: %s\n",file_name); exit(-1); } } void print_post_stats(live_point* psamps,unsigned long num_post_samps,double logz,unsigned num_dim) { double* mom1=(double*)malloc(num_dim*sizeof(double)); double* mom2=(double*)malloc(num_dim*sizeof(double)); double* weight=(double*)malloc(num_post_samps*sizeof(double)); unsigned i,j; /*memset(mom1,0,num_dim*sizeof(double));*/ /*memset(mom2,0,num_dim*sizeof(double));*/ for(i=0;i<num_dim;++i) { mom1[i]=0.; mom2[i]=0.; } for(i=0;i<num_post_samps;++i) { weight[i]=exp(psamps[i].log_weight-logz); for(j=0;j<num_dim;++j) { mom1[j]+=weight[i]*psamps[i].x[j]; mom2[j]+=weight[i]*psamps[i].x[j]*psamps[i].x[j]; } } printf("\n\nPosterior Statistics\n"); /*printf("--------------------------------------------------------------------------\n");*/ printf("Dimension Mean Standard Deviation\n"); printf("--------------------------------------------------------------------------\n"); for(i=0;i<num_dim;++i) { printf("%4d %12.10e %12.10e\n",i,mom1[i],sqrt(mom2[i]-mom1[i]*mom1[i])); } /*printf("--------------------------------------------------------------------------\n");*/ free(mom1); free(mom2); free(weight); } void print_max_like_estimate(live_point* lvpnts,unsigned num_live,unsigned num_dim) { unsigned best=0; unsigned i; for(i=0;i<num_live;++i) { if(lvpnts[i].log_lik>lvpnts[best].log_lik) { best=i; } } printf("\nMax Like parameters\n"); printf("Dimension Value\n"); printf("--------------------------------------------------------------------------\n"); for(i=0;i<num_dim;++i) { printf("%4d %12.10e\n",i,lvpnts[best].x[i]); } } /* * Write sampling and posterior statistics to a file */ void write_stats_file(live_point* psamps,unsigned long num_post_samps,live_point* lvpnts, unsigned num_live,unsigned num_dim,double logz,double dlogz,double H,char* stats_file_name) { double* mom1=(double*)malloc(num_dim*sizeof(double)); double* mom2=(double*)malloc(num_dim*sizeof(double)); double* weight=(double*)malloc(num_post_samps*sizeof(double)); unsigned i,j; unsigned best=0; FILE* outfile; /*memset(mom1,0,num_dim*sizeof(double));*/ /*memset(mom2,0,num_dim*sizeof(double));*/ /*calculate the mean and stadnard deviation*/ for(i=0;i<num_dim;++i) { mom1[i]=0.; mom2[i]=0.; } for(i=0;i<num_post_samps;++i) { weight[i]=exp(psamps[i].log_weight-logz); for(j=0;j<num_dim;++j) { mom1[j]+=weight[i]*psamps[i].x[j]; mom2[j]+=weight[i]*psamps[i].x[j]*psamps[i].x[j]; } } /*find the maximum likelihood */ for(i=0;i<num_live;++i) { if(lvpnts[i].log_lik>lvpnts[best].log_lik) { best=i; } } /*write statistics */ outfile=fopen(stats_file_name,"w"); if(outfile!=NULL) { fprintf(outfile,"Number of iterates = %d\n",num_post_samps); fprintf(outfile,"Evidence: log(Z) = %g +/- %g\n",logz,dlogz); fprintf(outfile,"Information: H = %g nats(= %g bits)\n",H,H/log(2.)); fprintf(outfile,"\n\nPosterior Statistics\n"); fprintf(outfile,"Dimension Mean Standard Deviation\n"); fprintf(outfile,"--------------------------------------------------------------------------\n"); for(i=0;i<num_dim;++i) { fprintf(outfile,"%4d %12.10e %12.10e\n",i,mom1[i],sqrt(mom2[i]-mom1[i]*mom1[i])); } fprintf(outfile,"\nMaximum Likelihood Parameters\n"); fprintf(outfile,"Dimension Value\n"); fprintf(outfile,"--------------------------------------------------------------------------\n"); for(i=0;i<num_dim;++i) { fprintf(outfile,"%4d %12.10e\n",i,lvpnts[best].x[i]); } fclose(outfile); } else { printf("Unable to open file: %s (aborting)\n",stats_file_name); } }
C
#include <stdio.h> int getMax (int *list, int n); //program sorts a user given list of numbers, and //organizes them in accending order. int main (void) { int n = 0; //number to be sorted int i = 0; //counter int list[n]; //array of numbers to be sorted int max = 0; //holds the arrays max index number from function getMax int temp; int j = 0; //counter int tempHolder = 0; //holds the index while swapping //gets how many numbers need to be sorted printf("Input how many numbers you need sorted: "); scanf("%d", &n); //gets the list of numbers to sort printf("Input your list of numbers, one at a time, in any order: "); for (i = 0; i < n; ++i) { scanf("%d", &list[i]); if ((i < n) && (n - (i + 1) > 0)) { printf("%d more number(s)", n - (i + 1)); } } temp = n; for (j = temp - 1; j >= 0; --j) { //invokes function getMax max = getMax (list, j + 1); //printf("%d\n", max); tempHolder = list[max]; list[max] = list[j]; list[j] = tempHolder; } //prints new array of sorted numbers for (i = 0; i < n; ++i) { printf("%d ", list[i]); } printf("\n"); return 0; } // gets the max value's index in list[n] int getMax (int *list, int n) { int tempMax; int i = 0; int j = 0; int index; tempMax = list[0]; for (i = 1; i < n; ++i) { if (list[i] > tempMax) { tempMax = list[i]; } } for (j = 0; j < n; ++j) { if (list[j] == tempMax) { index = j; break; } } return index; }
C
#include <stdio.h> #include <conio.h> #define BASE_YEAR 1900 int is_leap(int year); long date_to_num(int day, int month, int year); int which_day(int day, int month, int year); void display_calender(int month, int year); int month_day[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; char *month_name[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; int main(void) { int i, year; for (;;) { printf("enter year :"); scanf("%d", &year); if (year < BASE_YEAR) printf("year must be grater than %d\n", BASE_YEAR); else break; } for (i = 1; i < 13; i++) { display_calender(i, year); if (i % 3 == 0) { printf("\npress any key to continue\n"); getchar(); //clrscr(); } } return 0; } /**************************************************/ int is_leap(int year) { return (year % 4 == 0 && year % 100 != 0 || year % 400 == 0); } /**************************************************/ long date_to_number(int day, int month, int year) { int i; long total = day; for (i = BASE_YEAR; i < year; i++) total += 365 + is_leap(i); for (i = 0; i < month - 1; i++) total += month_day[i] + (i == 1 && is_leap(year)); return total; } /**************************************************/ int which_day(int day, int month, int year) { long i = date_to_number(day, month, year); return (int)(i % 7); } /**************************************************/ void display_calender(int month, int year) { int first_day = which_day(1, month, year); int total_day = month_day[month - 1]; int i; if (month - 1 == 1) total_day += is_leap(year); printf("Sun Mon Tue Wed Thu Fri Sat"); printf(" %s %4d\n", month_name[month - 1], year); printf("---------------------------------\n"); for (i = 0; i < first_day; i++) printf(" "); for (i = 1; i <= total_day; i++) { printf("%-5d", i); if ((i + first_day) % 7 == 0) putchar('\n'); } printf("\n"); }
C
#include<stdio.h> int main() { int i,a[100],b[100],n,num,m; printf("input how many nums in array\n"); scanf("%d",&m); printf("input %d nums\n",m); for(i = 0; i < m; i++) { scanf("%d",&a[i]); //ԭ } printf("array you input is:\n"); for(i = 0; i < m; i++) { printf("%d ",a[i]); //ԭ } printf("\n-----------------------------------------\n"); printf("λú\n"); scanf("%d %d",&n,&num); //ղλú printf("you'll insert %d to %dth\n",num,n); for(i = 0;i < n-1; i++) { b[i] = a[i]; //λǰ丳µ } b[n-1] = num; //ָλò for(i = n; i < m+1; i++) { b[i] = a[i-1]; //λú ͬ¸µ } for(i = 0;i < m+1; i++) { printf("%d ",b[i]); //Ԫص } return 0; }
C
// %%cpp alarm_handle.c // %run gcc -g alarm_handle.c -o alarm_handle.exe // %run ./alarm_handle.exe ; echo $? # выводим так же код возврата #include <unistd.h> #include <stdio.h> #include <signal.h> #include <sys/types.h> static void handler(int signum) { static char buffer[100]; int size = snprintf(buffer, sizeof(buffer), "Get signal %d, do nothing\n", signum); write(2, buffer, size); // можно использовать системные вызовы, они async-signal safe // fprintf(stderr, "Get signal %d, do nothing\n", signum); // А вот это уже использовать нелья // exit(0); // нельзя // _exit(0); // можно } int main() { sigaction(SIGALRM, // лаконичный способ использования структуры, но не совместим с С++ &(struct sigaction){ .sa_handler = handler, // можно писать SIG_IGN или SIG_DFL .sa_flags = SA_RESTART // используйте всегда. Знаю, что waitpid очень плохо себя ведет, когда прерывается сигналом }, NULL); alarm(1); pause(); printf("Is this command unreachable?\n"); // достижима ли эта команда? return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> int main(int argc, char *argv[]) { int *x = NULL; printf("x is %p\n", x); free(x); printf("x is %p\n", x); }
C
///////////////////////////////////////////////////////////// // // Write a program which accept file name from user and print // number of occurrence of Particular cWord in that file. // ///////////////////////////////////////////////////////////// //Header #include<stdio.h> #include<fcntl.h> #include<stdlib.h> #define NAMESIZE 20 #define BLOCKSIZE 1024 //Prototype int WordCount( char [] , char []); //Driver Function int main( char argc , char *argv[] ) //Enter file name by cmd line argu. { int iRet = 0; //Create character array for storing name of file //char Fname[NAMESIZE] = {'\0'}; /* //Accept Name File from user printf("Enter the name of file[with extension] :"); scanf("%s",Fname); */ if( argc != 3) { printf("File name and cWord is required.\n"); return 0; } iRet = WordCount( argv[1] , argv[2] ); if( iRet != -1 || iRet != 0) { printf("Count of Word [%s] in a File %s is :%d.\n",argv[2],argv[1],iRet); } else { printf("Entered Word is not found.\n"); } return 0; } //////////////////////////////////////////////////////////// // // Name :WordCount // Input :char [] , char [] // Returns :int // Description :Compute particular cWord count using // library functions. // Author :Rushikesh Godase // Date :5 Sep 2020 // //////////////////////////////////////////////////////////// int WordCount( char Fname[] , char cWord[]) { if( Fname == NULL ) { printf("Invalid Input.\n"); return -1; } //create file pointer FILE *fp = NULL; int iCnt = 0 , i = 0 , j = 0; //Create Buffer char cBuffer[BLOCKSIZE] = {'\0'}; //Clean Buffer memset( cBuffer , 0 , BLOCKSIZE); //open file by using fopen fp = fopen( Fname , "r" ); //check whether file is open or not if( fp == NULL ) { printf("Unable to open %s File.\n",Fname); exit(1); } while( (fgets( cBuffer , BLOCKSIZE , fp)) != NULL ) { for( i=0; cBuffer[i] != '\0'; i++) { j=0; while( (cWord[j] != '\0') && (cBuffer[i] == cWord[j]) ) { i++; j++; } if( j == strlen(cWord) ) { iCnt++; } } memset( cBuffer , 0 , BLOCKSIZE ); } fclose(fp); return iCnt; } /* OUTPUT : Count of Word [include] in a File CountWordOccurLib.c is :3. Count of Word [if] in a File CountWordOccurLib.c is :5. Count of Word [int] in a File CountWordOccurLib.c is :14. */
C
#include <armux/memory.h> #include <stdlib.h> #include <stdio.h> Byte readMemBlockByte(void *memBlock, UWord addr) { ARMMemBlock *block; block = (ARMMemBlock *)memBlock; return block->memory[addr - block->base_addr]; } Halfword readMemBlockHalfword(void *memBlock, UWord addr, Endianess end) { ARMMemBlock *block; block = (ARMMemBlock *)memBlock; UWord result = 0; UWord initAddr = addr - block->base_addr; UWord currAddr; int i; currAddr = initAddr; if(end == LittleEndian) { for(i = 0; i < 2; i++) { result |= block->memory[currAddr + i] << i * 8; } } else { for(i = 1; i >= 0; i--) { result |= block->memory[currAddr + 1 - i] << i * 8; } } return result; } Word readMemBlockWord(void *memBlock, UWord addr, Endianess end) { ARMMemBlock *block; block = (ARMMemBlock *)memBlock; UWord result = 0; UWord initAddr = addr - block->base_addr; UWord currAddr; int i; currAddr = initAddr; if(end == LittleEndian) { for(i = 0; i < 4; i++) { result |= (block->memory[currAddr + i] << i * 8) & (0xff << (i * 8)); } } else { for(i = 3; i >= 0; i--) { result |= (block->memory[currAddr + 3 - i] << i * 8) & (0xff << (i * 8)); } } return result; } void writeMemBlockByte(void *memBlock, UWord addr, Byte value) { ARMMemBlock *block; block = (ARMMemBlock *)memBlock; block->memory[addr - block->base_addr] = value; } void writeMemBlockHalfword(void *memBlock, UWord addr, Halfword value, Endianess end) { ARMMemBlock *block; block = (ARMMemBlock *)memBlock; UWord initAddr = addr - block->base_addr; UWord currAddr; int i; currAddr = initAddr; if(end == LittleEndian) { for(i = 0; i < 2; i++) { block->memory[initAddr + i] = (value & (0x000000FF << (i * 8))) >> (i * 8); } } else { for(i = 1; i >= 0; i--) { block->memory[initAddr + 1 - i] = (value & (0x000000FF << (i * 8))) >> (i * 8); } } } void writeMemBlockWord(void *memBlock, UWord addr, Word value, Endianess end) { ARMMemBlock *block; block = (ARMMemBlock *)memBlock; UWord initAddr = addr - block->base_addr; UWord currAddr; int i; currAddr = initAddr; if(end == LittleEndian) { for(i = 0; i < 4; i++) { block->memory[currAddr + i] = (value & (0x000000FF << (i * 8))) >> (i * 8); } } else { for(i = 3; i >= 0; i--) { block->memory[currAddr + 3 - i] = (value & (0x000000FF << (i * 8))) >> (i * 8); } } } ARMMemBlock *new_mem_block(Word base_addr, UWord size) { int i; ARMMemBlock *block = malloc(sizeof(ARMMemBlock)); block->base_addr = base_addr; block->size = size; block->memory = malloc(sizeof(size)); block->device = NULL; for(i = 0; i < size; i++) { block->memory[i] = 0; } block->readByte = &readMemBlockByte; block->readHalfword = &readMemBlockHalfword; block->readWord = &readMemBlockWord; block->writeByte = &writeMemBlockByte; block->writeHalfword = &writeMemBlockHalfword; block->writeWord = &writeMemBlockWord; return block; } ARMMemBlock *new_mem_block_shm(Word base_addr, Word size, char *addr) { ARMMemBlock *block = malloc(sizeof(ARMMemBlock)); block->base_addr = base_addr; block->size = size; block->memory = addr; block->device = NULL; block->readByte = &readMemBlockByte; block->readHalfword = &readMemBlockHalfword; block->readWord = &readMemBlockWord; block->writeByte = &writeMemBlockByte; block->writeHalfword = &writeMemBlockHalfword; block->writeWord = &writeMemBlockWord; return block; } ARMMemNode *new_mem_node(void *node) { ARMMemNode *root; root = malloc(sizeof(ARMMemNode)); root->value = node; root->next = NULL; return root; } void add_mem_block(ARMMemNode* root, void *mem_block) { ARMMemNode *node; node = root; while(node->next != NULL) node = node->next; node->next = mem_block; } /* * Implementation for ARM memory system */ Byte readInterByte(MemInterface *inter, UWord addr) { ARMMemNode *iter = inter->root; ARMMemInterface *mem; Byte result; while(iter != NULL) { mem = iter->value; if(mem->base_addr <= addr && (addr < (mem->base_addr + mem->size))) { if(mem->device != NULL) { mem->device->lock(mem->device); } result = mem->readByte(mem, addr); if(mem->device != NULL) { mem->device->unlock(mem->device); } return result; } iter = iter->next; } return 0; } Halfword readInterHalfword(MemInterface *inter, UWord addr, Endianess end) { ARMMemNode *iter = inter->root; ARMMemInterface *mem; Halfword result; while(iter != NULL) { mem = iter->value; if(mem->base_addr <= addr && addr < (mem->base_addr + mem->size)) { if(mem->device != NULL) { mem->device->lock(mem->device); } result = mem->readHalfword(mem, addr, end); if(mem->device != NULL) { mem->device->unlock(mem->device); } return result; } iter = iter->next; } return 0; } Word readInterWord(MemInterface *inter, UWord addr, Endianess end) { ARMMemNode *iter = inter->root; ARMMemInterface *mem; Word result; while(iter != NULL) { mem = iter->value; if(mem->base_addr <= addr && addr < (mem->base_addr + mem->size)) { if(mem->device != NULL) { mem->device->lock(mem->device); } result = mem->readWord(mem, addr, end); if(mem->device != NULL) { mem->device->unlock(mem->device); } return result; } iter = iter->next; } return 0; } void writeInterByte(MemInterface *inter, UWord addr, Byte value) { ARMMemNode *iter = inter->root; ARMMemInterface *mem; while(iter != NULL) { mem = iter->value; if(mem->base_addr <= addr && addr < (mem->base_addr + mem->size)) { if(mem->device != NULL) { mem->device->lock(mem->device); } mem->writeByte(mem, addr, value); if(mem->device != NULL) { mem->device->unlock(mem->device); mem->device->tellWritten(mem->device, addr - mem->base_addr); } return; } iter = iter->next; } } void writeInterHalfword(MemInterface *inter, UWord addr, Halfword value, Endianess end) { ARMMemNode *iter = inter->root; ARMMemInterface *mem; while(iter != NULL) { mem = iter->value; if(mem->base_addr <= addr && addr < (mem->base_addr + mem->size)) { if(mem->device != NULL) { mem->device->lock(mem->device); } mem->writeHalfword(mem, addr, value, end); if(mem->device != NULL) { mem->device->unlock(mem->device); mem->device->tellWritten(mem->device, addr - mem->base_addr); } return; } iter = iter->next; } } void writeInterWord(MemInterface *inter, UWord addr, Word value, Endianess end) { ARMMemNode *iter = inter->root; ARMMemInterface *mem; while(iter != NULL) { mem = iter->value; if(mem->base_addr <= addr && addr < (mem->base_addr + mem->size)) { if(mem->device != NULL) { mem->device->lock(mem->device); } mem->writeWord(mem, addr, value, end); if(mem->device != NULL) { mem->device->unlock(mem->device); mem->device->tellWritten(mem->device, addr - mem->base_addr); } return; } iter = iter->next; } } MemInterface *memInterface() { MemInterface *inter; inter = malloc(sizeof(MemInterface)); inter->root = new_mem_node(new_mem_block(0, 65536 * 2)); inter->readByte = readInterByte; inter->readHalfword = readInterHalfword; inter->readWord = readInterWord; inter->writeByte = writeInterByte; inter->writeHalfword = writeInterHalfword; inter->writeWord = writeInterWord; return inter; }
C
#include <stdio.h> #include <conio.h> #include <stdlib.h> struct Registro { int valor; struct Registro *prox; }; struct Registro *aux, *inicio = NULL, *final = NULL; /*funo responsvel por criar a lista*/ struct Registro* cria(void) { return NULL; } /* funo com tipo de retorno ponteiro para estrutura, realizando insero pelo final*/ struct Registro* insere_final() { int x; printf("Entre com um numero inteiro: "); scanf("%i",&x); aux = (struct Registro*) malloc (sizeof(struct Registro)); aux->valor = x; aux -> prox = (struct Registro *) NULL; if(inicio == NULL) inicio = final = aux; // No existe elemento anterior e portanto h apenas um elemento na lista. Assim inicio e final so o mesmo elemento da lista. else { final -> prox = aux; // O elemento incluido se torna o ultimo elemento da lista. Assim o prox aponta para o elemento incluido. final = aux; } return inicio; } /* funo que verifica o estado da lista: retorno 1 se vazia ou 0 se no vazia*/ int lista_vazia(struct Registro *lista) { if(lista == NULL) return 1; else return 0; } /* funo responsvel por imprimir o contedo da lista */ void visualiza_lista_final(struct Registro *lista) { /* verifica se a lista est vazia*/ if(!lista_vazia(lista)) { aux = lista; while(aux != (struct Registro *) NULL) { // Enquando o aux for diferente de NULL. Note que aux atualizado com o ponteiro para o proximo elemento. printf("Valor da Lista: %i\n", aux->valor); aux = aux -> prox; // Atualiza aux com o ponteiro para o proximo elemento. } } /* indica que a lista est vazia*/ else printf("\nTentou imprimir uma lista vazia!"); getch(); } /* funo que busca um elemento na lista*/ struct Registro* busca(struct Registro* lista, int busca) { int achou = 0; // Assume que o elemento nao existe na lista, inicializando o flag com 0 if(!lista_vazia(lista)) { // Se a lista nao estiver vazia inicia a busca for(aux=lista;aux!=NULL;aux=aux->prox) { // Percorre a lista a partir do primeiro elemento ate que o proximo elemento seja NULL if(aux->valor == busca) { // Se o campo valor do elemento for igual a busca entao atualiza o flag para 1 achou = 1; printf ("Valor encontrado! %d", busca); } } if(!achou) // Ao final da busca, verifica se achou e caso tenha encontrado imprime mensagem printf("Valor nao encontrado.\n"); } else { printf("\nTentou buscar de uma lista vazia"); // Se a lista nao exister preenchida exibe mensagem informando lista vazia } getch(); return NULL; } /* funo para excluir registros da lista*/ struct Registro* excluir(struct Registro *lista, int valor) { /* ponteiro para elemento anterior */ struct Registro *ant = NULL; /* ponteiro para percorrer a lista */ aux = lista; if(!lista_vazia(lista)) { /* procura elemento na lista, guardando anterior */ while(aux!= NULL && aux->valor != valor) { ant = aux; aux = aux->prox; } /* verifica se achou o elemento */ if(aux == NULL) { printf("\nNao foi possivel a exclusao. Elemento nao encontrado!"); getche(); return lista; } /* retira elemento */ if(ant == NULL) lista = aux->prox; // Se o elemento excluido for o primeiro elemento da lista entao o inicio da lista aponta para o elemento seguinte else ant->prox = aux->prox; // Se o elemento excluido nao for o primeiro, faz o elemento anterior apontar para o proximo elemento da lista /* Libera a memoria alocada para o elemento excluido. Neste momento o elemento no faz mais parte da lista e pode ser exlcuido. */ free(aux); printf("Elemento removido com sucesso!\n"); getche(); /* Retorna a lista atualizada, sem o elemento que foi excluido */ return lista; } else { printf("\nTentou remover de uma lista vazia"); getche(); return lista; } } /* Programa Principal - Funcao Main */ main() { /* Variaveis para opcao do menu, para o elemento a ser excluido e para o elemento a ser localizado pela busca */ int op, vremover, vbuscar; /* Variavel para apontar para o primeiro elemento da lista */ struct Registro *lista; /* Cria a lista inicialmente vazia */ lista = cria(); /* Enquanto o usuario nao escolher a opcao 5 para sair do programa, as opes escolhidas sao executadas */ while(op != 5) { /* Imprime o menu principal do programa */ system("cls"); printf("\nPrograma Para Manipulacao de Listas Ligadas"); printf("\n1 - Inserir no Final da Lista"); printf("\n2 - Visualizar Lista"); printf("\n3 - Buscar Elemento na Lista"); printf("\n4 - Excluir Elemento"); printf("\n5 - Sair do Programa"); /* Le a opcao do usuario */ printf("\nEntre com a Opcao Desejada: "); scanf("%i",&op); /* Conforme a opo escolhida execuca a funcao solicitada que pode ser para inserir, listar, buscar ou remover um elemento da lista */ switch(op) { case 1: lista = insere_final(); break; case 2: visualiza_lista_final(lista); break; case 3: printf("Entre com o valor que se deseja buscar: "); scanf("%d",&vbuscar); busca(lista,vbuscar); break; case 4: printf("Entre com o valor que deseja remover: "); scanf("%i",&vremover); lista = excluir(lista, vremover); break; case 5: exit(1); } } }
C
#include "jutil.h" #ifndef abs #define abs(a) ((a) >= 0 ? (a) : -(a)) #endif #define VERBOSE void checkSTREAMresults (REAL* a, REAL* b, REAL* c, int iNumElements, int iNumIterations) { REAL aj,bj,cj,scalar; REAL aSumErr,bSumErr,cSumErr; REAL aAvgErr,bAvgErr,cAvgErr; double epsilon; ssize_t j; int k,ierr,err; /* reproduce initialization */ aj = 1.0; bj = 2.0; cj = 0.0; /* a[] is modified during timing check */ aj = 2.0E0 * aj; /* now execute timing loop */ scalar = 3.0; for (k=0; k<iNumIterations; k++) { cj = aj; bj = scalar*cj; cj = aj+bj; aj = bj+scalar*cj; } //printf("aj = %.6f, bj = %.6f, cj = %.6f\n", aj, bj, cj); /* accumulate deltas between observed and expected results */ aSumErr = 0.0; bSumErr = 0.0; cSumErr = 0.0; for (j=0; j<iNumElements; j++) { aSumErr += abs(a[j] - aj); bSumErr += abs(b[j] - bj); cSumErr += abs(c[j] - cj); // if (j == 417) printf("Index 417: c[j]: %f, cj: %f\n",c[j],cj); // MCCALPIN } aAvgErr = aSumErr / (REAL) iNumElements; bAvgErr = bSumErr / (REAL) iNumElements; cAvgErr = cSumErr / (REAL) iNumElements; if (sizeof(REAL) == 4) { epsilon = 1.e-6; } else if (sizeof(REAL) == 8) { epsilon = 1.e-13; } else { printf("WEIRD: sizeof(REAL) = %lu\n",sizeof(REAL)); epsilon = 1.e-6; } err = 0; if (abs(aAvgErr/aj) > epsilon) { err++; printf ("Failed Validation on array a[], AvgRelAbsErr > epsilon (%e)\n",epsilon); printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",aj,aAvgErr,abs(aAvgErr)/aj); ierr = 0; for (j=0; j<iNumElements; j++) { if (abs(a[j]/aj-1.0) > epsilon) { ierr++; #ifdef VERBOSE if (ierr < 10) { printf(" array a: index: %ld, expected: %e, observed: %e, relative error: %e\n", j,aj,a[j],abs((aj-a[j])/aAvgErr)); } #endif } } printf(" For array a[], %d errors were found.\n",ierr); } if (abs(bAvgErr/bj) > epsilon) { err++; printf ("Failed Validation on array b[], AvgRelAbsErr > epsilon (%e)\n",epsilon); printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",bj,bAvgErr,abs(bAvgErr)/bj); printf (" AvgRelAbsErr > Epsilon (%e)\n",epsilon); ierr = 0; for (j=0; j<iNumElements; j++) { if (abs(b[j]/bj-1.0) > epsilon) { ierr++; #ifdef VERBOSE if (ierr < 10) { printf(" array b: index: %ld, expected: %e, observed: %e, relative error: %e\n", j,bj,b[j],abs((bj-b[j])/bAvgErr)); } #endif } } printf(" For array b[], %d errors were found.\n",ierr); } if (abs(cAvgErr/cj) > epsilon) { err++; printf ("Failed Validation on array c[], AvgRelAbsErr > epsilon (%e)\n",epsilon); printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",cj,cAvgErr,abs(cAvgErr)/cj); printf (" AvgRelAbsErr > Epsilon (%e)\n",epsilon); ierr = 0; for (j=0; j<iNumElements; j++) { if (abs(c[j]/cj-1.0) > epsilon) { ierr++; #ifdef VERBOSE if (ierr < 10) { printf(" array c: index: %ld, expected: %e, observed: %e, relative error: %e\n", j,cj,c[j],abs((cj-c[j])/cAvgErr)); } #endif } } printf(" For array c[], %d errors were found.\n",ierr); } if (err == 0) { printf ("Solution Validates: avg error less than %e on all three arrays\n",epsilon); } #ifdef VERBOSE printf ("Results Validation Verbose Results: \n"); printf (" Expected a(1), b(1), c(1): %f %f %f \n",aj,bj,cj); printf (" Observed a(1), b(1), c(1): %f %f %f \n",a[1],b[1],c[1]); printf (" Rel Errors on a, b, c: %e %e %e \n",abs(aAvgErr/aj),abs(bAvgErr/bj),abs(cAvgErr/cj)); #endif if(err == 0) printf("PASS\n"); else printf("FAIL\n"); }
C
#include "deque.h" #include <assert.h> int main() { Deque *deque = deque__create(); deque__print(deque); deque__push_back(deque, 1); deque__push_front(deque, 99); deque__print(deque); deque__push_back(deque, 2); deque__push_back(deque, 3); deque__push_front(deque, 98); deque__push_front(deque, 97); deque__push_front(deque, 96); deque__push_front(deque, 95); deque__print(deque); deque__push_front(deque, 94); deque__push_back(deque, 4); deque__push_back(deque, 5); deque__push_back(deque, 6); deque__push_back(deque, 7); deque__push_back(deque, 8); deque__push_back(deque, 9); deque__print(deque); assert(deque__pop_front(deque) == 94); assert(deque__pop_back(deque) == 9); deque__print(deque); assert(deque__pop_front(deque) == 95); assert(deque__pop_front(deque) == 96); assert(deque__pop_front(deque) == 97); assert(deque__pop_front(deque) == 98); assert(deque__pop_front(deque) == 99); assert(deque__pop_front(deque) == 01); deque__print(deque); deque__destroy(deque); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <termios.h> #include <inttypes.h> #include <string.h> #include <sys/types.h> #include <sys/time.h> #include <sys/select.h> #include <sys/ioctl.h> #include "serial.h" int uart0_filestream = -1; void serial_init(void) { uart0_filestream = open(PORTNAME, O_RDWR | O_NOCTTY | O_NDELAY); if (uart0_filestream == -1) { //TODO error handling... } } void serial_config(void) { struct termios options; tcgetattr(uart0_filestream, &options); options.c_cflag = B9600 | CS8 | CLOCAL | CREAD; options.c_iflag = IGNPAR; options.c_oflag = 0; options.c_lflag = ICANON; tcflush(uart0_filestream, TCIFLUSH); tcsetattr(uart0_filestream, TCSANOW, &options); } void serial_println(const char *line, int len) { if (uart0_filestream != -1) { char *cpstr = (char *)malloc((len+1) * sizeof(char)); strcpy(cpstr, line); cpstr[len-1] = '\r'; cpstr[len] = '\n'; int count = write(uart0_filestream, cpstr, len+1); if (count < 0) { //TODO: handle errors... } free(cpstr); } } // Read a line from UART. int serial_readln(char *buffer) { int bytes_read = 0; struct timeval timeout = {.tv_sec = 0, .tv_usec = 0}; fd_set input_fdset; FD_ZERO(&input_fdset); FD_SET(uart0_filestream, &input_fdset); switch (select(uart0_filestream + 1, &input_fdset, NULL, NULL, &timeout)) { case -1: perror("Select failed"); break; case 0: // Nothing available to read break; default: { ioctl(uart0_filestream, FIONREAD, &bytes_read); int bytes_recv = bytes_read; while (bytes_recv > 0) { if (read(uart0_filestream, (void *)(buffer), 1) < 0) perror("Error reading UART buffer"); if (*buffer == '\n') { *buffer++ = '\0'; break; } buffer++; bytes_recv--; } break; } }; return bytes_read; } void serial_close(void) { close(uart0_filestream); }
C
#include <stdlib.h> /** * alloc_grid - Create a 2 dimensionals array * @width: Width of grid, aka # of columns * @height: Height of grid, aka # of rows * * Return: Pointer to 2D array, NULL if it fails */ int **alloc_grid(int width, int height) { int **grid; int a, b; a = 0; if (width <= 0 || height <= 0) return (NULL); grid = malloc(height * sizeof(*grid)); if (grid == NULL) { free(grid); return (NULL); } while (a < height) { grid[a] = malloc(width * sizeof(**grid)); if (grid[a] == NULL) { a--; while (a >= 0) { free(grid[a]); a--; } free(grid); return (NULL); } b = 0; while (b < width) { grid[a][b] = 0; b++; } a++; } a = 0; return (grid); }
C
#include <pthread.h> #include <malloc.h> int thread_flag; pthread_mutex_t thread_flag_mutex; /* Allocate a temporary buffer. */ void* allocate_buffer (size_t size){ return malloc (size); } /* Deallocate a temporary buffer. */ void deallocate_buffer (void* buffer){ free (buffer); } void do_work (){ /* Allocate a temporary buffer. */ void* temp_buffer = allocate_buffer (1024); /* Register a cleanup handler for this buffer, to deallocate it in case the thread exits or is cancelled. */ pthread_cleanup_push (deallocate_buffer, temp_buffer); /* Do some work here that might call pthread_exit or might be cancelled... */ /* Unregister the cleanup handler. Because we pass a nonzero value, this actually performs the cleanup by calling deallocate_buffer. */ pthread_cleanup_pop (1); } void initialize_flag (){ pthread_mutex_init (&thread_flag_mutex, NULL); thread_flag = 0; } /* Calls do_work repeatedly while the thread flag is set; otherwise spins. */ void* thread_function (void* thread_arg){ while (1) { int flag_is_set; /* Protect the flag with a mutex lock. */ pthread_mutex_lock (&thread_flag_mutex); flag_is_set = thread_flag; pthread_mutex_unlock (&thread_flag_mutex); if (flag_is_set) do_work (); /* Else don't do anything. Just loop again. */ } return NULL; } /* Sets the value of the thread flag to FLAG_VALUE. */ void set_thread_flag (int flag_value){ /* Protect the flag with a mutex lock. */ pthread_mutex_lock (&thread_flag_mutex); thread_flag = flag_value; pthread_mutex_unlock (&thread_flag_mutex); } int main(){ /*pthread_t thread; initialize_flag(); pthread_create (&thread, NULL, &thread_function, NULL); pthread_join (thread, NULL);*/ //Aqui debemos realizar los pasos necesarios para trabajar con los hilos //Por ahora no hacemos nada //thread_function(NULL); return 0; }
C
#include "signal_handler_thread.h" #include <stdio.h> #include "signal.h" #include "uart.h" void signalHandlerThread(void* arg) { signal_handler_thread_t* this = (signal_handler_thread_t*)arg; char input[16]; osStatus_t status; while (1) { if (status != osOK) continue; if (UARTPeek('\r') < 0) { osThreadYield(); continue; } UARTgets(input, sizeof(input)); signal_t signal; if (!signalParse(&signal, input)) { #ifdef DEBUG printf("Error: Invalid signal %s\n", input); #endif continue; } do { status = osMessageQueuePut(this->args.queue, &signal, 0, osWaitForever); } while (status != osOK); osThreadYield(); } }
C
#include <stdio.h> int main() { /* * struct <结构体名> { * <成员类型> <成员名>; * ... * } <结构体变量>; * */ // 定义结构体变量 /* * 结构体也是内存中的一片空间 * 结构体在内存中占用的地址头(Person)就是结构体中第一个变量的地址(name) * */ struct Person { char *name; int age; char *id; }; // 不赋值初始化的时候所有的值都是默认值,由编译器决定 struct Person person = {}; // 全赋值初始化 struct Person person1 = {"helisi", 22, "173080092"}; // 对结构体指定变量初始化 struct Person person2 = {.name = "helisi", .id = "173080092"}; // 对结构体指定变量赋值 person2.age = 22; printf("%d\n", sizeof(person)); printf("%d\n", sizeof(typeof(struct Person))); // 定义结构体指针 struct Person *person3 = &person2; // 访问变量 printf(person2.name); //变量访问 printf(person3->name); //变量指针访问 /* * 定义结构体变量并命名 * */ typedef struct Person_1 { char *name; int age; char *id; } Person_1; // 创建并初始化,其余操作相同 Person_1 person_1 = {"helisi", 22, "173080092"}; /* * 结构体嵌套 * */ typedef struct Company { char *name; char *id; char *company_location; } Company; typedef struct Employee{ char *name; int age; char *id; struct Company *company; struct Company company2; struct { int extra; char *extra_s; } extra_value; } Employee; Company company = {"abc", 1, "xx-xx-xx-xx"}; Employee employee = {"helisi", 22, "173080092", .company = &company, .company2 = { "def", 2, "yy-yy-yy-yy" }}; // 访问嵌套结构体变量 puts(employee.company->name); puts(employee.extra_value.extra); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main() { int *p = 0x5DC; printf("p = Hexadecimal: %p Decimal: %d\n",p,p); // Incrementa p em uma posição p++; printf("p = Hexadecimal: %p Decimal: %d\n",p,p); // Incrementa p em 15 posições/ avança 15 posições de 4 bytes na memória p = p + 15; printf("p = Hexadecimal: %p Decimal: %d\n",p,p); // Decrementa p em 2 posições/ retrocede duas posições de 4 bytes na memoria p - p - 2; printf("p = Hexadecimal %p Decimal: %d\n",p,p); return 0; }
C
#include "utils.h" ino_t get_ino(const char *path) { struct stat buf; if (stat(path, &buf) != 0) return 0; uid_t uid = getuid(); if (buf.st_uid != uid && uid != 0) return -1; return buf.st_ino; } bool is_dir(const char *path) { struct stat buf; stat(path, &buf); return S_ISDIR(buf.st_mode); } char *compute_MD5(const char *text) { MD5_CTX md5; MD5_Init(&md5); MD5_Update(&md5, text, strlen(text)); unsigned char hex[MD5_DIGEST_LENGTH]; MD5_Final(hex, &md5); char *result = (char *) malloc((MD5_DIGEST_LENGTH * 2 + 1) * sizeof(char)); for (int i = 0; i < MD5_DIGEST_LENGTH; i++) { sprintf(result + 2 * i, "%02X", hex[i]); } result[MD5_DIGEST_LENGTH * 2] = '\0'; return result; } unsigned get_unsigned_length(unsigned long num) { unsigned length = 0; while (num) { num /= 10; length++; } return length; } int iter_callback(struct ext2_dir_entry *dirent, int offset EXT2FS_ATTR((unused)), int blocksize EXT2FS_ATTR((unused)), char *buf EXT2FS_ATTR((unused)), void *private) { struct walk_struct *ws = (struct walk_struct *) private; struct ext2_inode inode; if (strcmp(".", dirent->name) == 0 || strcmp("..", dirent->name) == 0) return 0; for (int i = 0; i < ws->inodes_num; i++) { if (ws->inodes[i] == dirent->inode) { ws->left_num--; if (!ws->parent_name) { ext2fs_get_pathname(fs, ws->dir, 0, &ws->parent_name); } ext2fs_read_inode(fs, dirent->inode, &inode); if (!LINUX_S_ISDIR(inode.i_mode)) printf("%u\t%s/%.*s\n", ws->inodes[i], ws->parent_name, ext2fs_dirent_name_len(dirent), dirent->name); else printf("%u\t\033[1;34m%s/%.*s\033[0m\n", ws->inodes[i], ws->parent_name, ext2fs_dirent_name_len(dirent), dirent->name); } } return 0; } bool print_filenames(ext2_ino_t inodes[], int length) { if (!length) return false; errcode_t err; struct walk_struct ws; ws.inodes = inodes; ws.inodes_num = length; ws.left_num = length; err = ext2fs_open("/dev/sda1", 0, 0, 0, unix_io_manager, &fs); if (err) { com_err("print_filenames", err, "while open filesystem"); return false; } printf("\n\033[1mInode\tPathname\033[0m\n"); struct ext2_inode inode; ext2_ino_t ino; ext2_inode_scan scan = 0; ext2fs_open_inode_scan(fs, 0, &scan); do { err = ext2fs_get_next_inode(scan, &ino, &inode); } while (err == EXT2_ET_BAD_BLOCK_IN_INODE_TABLE); while (ino) { if (!inode.i_links_count || inode.i_dtime || !LINUX_S_ISDIR(inode.i_mode)) { goto next; } ws.dir = ino; ws.parent_name = NULL; ext2fs_dir_iterate(fs, ino, 0, NULL, iter_callback, (void *) &ws); ext2fs_free_mem(&ws.parent_name); if (!ws.left_num)break; next: do { err = ext2fs_get_next_inode(scan, &ino, &inode); } while (err == EXT2_ET_BAD_BLOCK_IN_INODE_TABLE); } ext2fs_close_inode_scan(scan); ext2fs_close(fs); return true; }
C
#include "holberton.h" /** * _strstr - Entry point * @haystack: the char for print * @needle: null character or needle * Return: return a variable */ char *_strstr(char *haystack, char *needle) { int i; while (*haystack) { for (i = 0; needle[i]; i++) { if (needle[i] != haystack[i]) break; } if (!needle[i]) return (haystack); haystack++; } return (0); }
C
//#include <string.h> //#include <stdio.h> //#include <time.h> //#include <stdlib.h> //#include <ctype.h> // // //#include "array.h" //#include "dict.h" // //#define NUM_ARGC 2 //#define NO_ENOUGH_NUM_ARGC 1 //#define CANT_READ_DICT 2 //#define CANT_REPLACE_WORDS 3 // //#define LINE_BUFFER 256 //#define WORD_BUFFER 256 // //Dict* read_dict(char* path); //int replace_words(Dict* dict, char* path); // //int main(int argc, char* argv[]) //{ // srand(time(NULL)); // Initialization, should only be called once. // // int have_src_dest = argc > NUM_ARGC; // if (0 == have_src_dest) // { // printf("Please enter source and destination file paths"); // return NO_ENOUGH_NUM_ARGC; // } // // char* dest_path = argv[1]; // char* dict_path = argv[2]; // // Dict* dict = read_dict(dict_path); // // if (NULL == dict) // { // printf("Can't read the dict file"); // return CANT_READ_DICT; // } // // if (replace_words(dict, dest_path)) // { // printf("Can't replace words"); // return CANT_REPLACE_WORDS; // } // // loop over all the words in the dest file // // // set all the words // // dict_free(dict); // // return 0; //} // //int replace_words(Dict* dict, char* path) //{ // FILE* fp; // if (NULL != fopen_s(&fp, path, "r")) // { // return NULL; // } // // fseek(fp, 0L, SEEK_END); // unsigned long long file_size = ftell(fp) - 1; // rewind(fp); // // char* old_file_buff = malloc(sizeof(char) * file_size); // if (NULL == old_file_buff) // { // return -1; // } // // fread(old_file_buff, sizeof(char), file_size, fp); // // fclose(fp); // // // get word - 2 // // check if have - 1 // // random get it from the list - 3 // // // // change the word and add padding/remove padding // // if have too much - // // if have too little - // // if (NULL != fopen_s(&fp, path, "w")) // { // free(old_file_buff); // return -1; // } // // unsigned long long space_index = 0; // char word_buffer[WORD_BUFFER] = { 0 }; // int word_i = 0; // while (space_index < file_size) // { // if (isspace(old_file_buff[space_index]) || space_index == file_size - 1) // or end of file // { // char* word = word_buffer; // if (strlen(word)) // { // if (dict_find(dict, word)) // { // List* list = dict_get(dict, word); // int size = list->size; // int random_index = rand() & size; // if (random_index) // { // Node* first = list_first(list); // random_index--; // while (random_index) // { // first = list_next(first); // random_index--; // } // word = first->data; // } // } // fwrite(word, sizeof(char), strlen(word) * sizeof(char), fp); // } // char space[1] = { old_file_buff[space_index] }; // fwrite(space, sizeof(char), 1 * sizeof(char), fp); // // memset(word_buffer, 0, word_i); // word_i = 0; // } // else // { // word_buffer[word_i] = old_file_buff[space_index]; // word_i++; // } // space_index++; // } // // fclose(fp); // // free(old_file_buff); // // return 0; //} // //// mine ////int hash_str(char* str, int size) ////{ //// int result = 0; //// for (int size_of_key_word = 0; size_of_key_word < size; size_of_key_word++) //// { //// result += str[size_of_key_word] + str[size_of_key_word] * size_of_key_word; //// } //// return result; ////} // //inline unsigned long hash_str(unsigned char* str) //{ // unsigned long hash = 5381; // int c; // // while (c = *str++) // { // hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ // } // // return hash; //} // //unsigned long hash_str_void(void* str) //{ // return hash_str((unsigned char*)str); //} // //int strcmp_void(void* str1, void* str2) //{ // return strcmp((char*)str1, (char*)str2); //} // //void str_destory_void(void* str) //{ // free((char*)str); //} // //void list_destroy_void(void* array) //{ // return list_destroy((List*)array, str_destory_void); //} // //char* cut_str(char* buffer, int start_index, int endIndex) //{ // int len = endIndex - start_index; // char* value = (char*)malloc(sizeof(char) * (len + 1)); // add null // if (NULL == value) // { // return NULL; // } // memcpy(value, &(buffer[start_index]), len); // value[len] = 0; // // return value; //} // //List* read_values(char* buffer, int start_index) //{ // List* list = list_init(); // if (NULL == list) // { // return NULL; // } // // int word_index = 0; // int line_index = 0; // while (1) // { // char c = buffer[word_index + start_index + line_index]; // if (0 == c || '\n' == c) // { // char* value = cut_str(buffer, start_index + line_index, start_index + line_index + word_index); // if (NULL == value) // { // free(list); // return NULL; // } // // list_add(list, value); // return list; // } // else if (',' == c) // { // char* value = cut_str(buffer, start_index + line_index, start_index + line_index + word_index); // if (NULL == value) // { // free(list); // return NULL; // } // // list_add(list, value); // line_index += word_index + 1; // word_index = 0; // } // else // { // word_index++; // } // } //} // //int size_of_key(char* buffer) //{ // int buffer_index = -1; // while (1) // { // buffer_index++; // if (buffer[buffer_index] == ':') // { // return buffer_index; // } // } //} // //// return key, value //DictPair* read_line(FILE* file) //{ // char line[LINE_BUFFER] = { 0 }; // // if (fgets(line, sizeof(line), file)) // { // int buffer_index = size_of_key(line); // // if (0 == buffer_index) // { // return NULL; // } // // char key_value[256]; // // char* key = (char*)malloc(sizeof(char) * buffer_index + 1); // 1 for null // if (NULL == key) // { // return NULL; // } // // memcpy(key, line, buffer_index); // key[buffer_index] = 0; // // List* values = read_values(line, buffer_index + 1); // pass the : // if (NULL == values) // { // free(key); // return NULL; // } // // return _init_pair(key, values); // } // else // { // return NULL; // } //} // //Dict* read_dict(char* path) //{ // DictFunctions dictFunc; // dictFunc.hash_func = hash_str_void; // dictFunc.comp_func = strcmp_void; // dictFunc.destory_value = list_destroy_void; // dictFunc.destory_key = str_destory_void; // Dict* dict = init_dict(dictFunc); // // if (NULL == dict) // { // return NULL; // } // // FILE* fp; // if (NULL != fopen_s(&fp, path, "r")) // { // return NULL; // } // // DictPair* new_pair; // while (new_pair = read_line(fp)) // { // dict_insert_pair(dict, new_pair); // if (dict_find(dict, new_pair->key)) // { // printf("FIND"); // } // } // // fclose(fp); // // return dict; //} int main() { printf("fasfasf"); }
C
#include <stdio.h> int main() { int a=0, i=1, n=0, raz=0; scanf("%d", &n); for(i=1; i<=n; i++) { scanf("%d", &a); a=a*(-1); raz=raz+a; } printf("%d\n",raz); return 0; }
C
#include <stdio.h> #include <unistd.h> #include <string.h> #include <errno.h> static int usage() { fprintf(stderr,"rmdir <directory>\n"); return -1; } int rmdir_main(int argc, char *argv[]) { int symbolic = 0; int ret; if(argc < 2) return usage(); while(argc > 1) { argc--; argv++; ret = rmdir(argv[0]); if(ret < 0) { fprintf(stderr, "rmdir failed for %s, %s\n", argv[0], strerror(errno)); return ret; } } return 0; }
C
#ifndef __SEQLIST_H__ #define __SEQLIST_H__ #include <stdbool.h> typedef int DataType; ////̬˳ #define Dynamic_List #define DEFAULT_CAPACITY 3 #define DEFAULT_ADD 2 typedef struct SeqList { DataType *data;// int sz;//Ч int capacity;// }SeqList, *pSeqList; ////̬˳ //#define static_List // //#define MAX 100 //typedef struct SeqList //{ // DataType data[MAX]; // int sz; //}SeqList, *pSeqList; void InitSeqList(pSeqList ps); //ʼ void DestroySeqList(pSeqList ps); // void PushBack(pSeqList ps, DataType d); //β void PrintSeqList(const pSeqList ps); // void PopBack(pSeqList ps); //βɾ void PushFront(pSeqList ps, DataType d); //ͷ void PopFront(pSeqList ps); //ͷɾ void PosInsert(pSeqList ps, int pos, DataType d); //ָԪ void DataInsert(pSeqList ps, DataType src, DataType d); //ָԪǰԪ void Sort(pSeqList ps); // int BinarySearch(pSeqList ps, DataType d); // int Find(pSeqList ps, DataType d); // void Remove(pSeqList ps, DataType d); //ɾĵһd void RemoveALL(pSeqList ps, DataType d); //ɾеd int SeqList_Size(const pSeqList ps); //˳ݸ bool SeqListEmpty(const pSeqList ps); //˳ǷΪ bool SeqListFull(const pSeqList ps); //˳ǷΪ void test(); //Գ #endif //__SEQLIST_H__
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "estructuragenerica.h" #define TAMANIO 10 #define OCUPADO 0 #define LIBRE 1 int eGen_init( eGenerica listado[],int limite) { int retorno = -1; int i; if(limite > 0 && listado != NULL) { retorno = 0; for(i=0; i<limite; i++) { listado[i].estado= LIBRE; listado[i].idGenerica= 0; } } return retorno; } int eGen_buscarLugarLibre(eGenerica listado[],int limite) { int retorno = -1; int i; if(limite > 0 && listado != NULL) { retorno = -2; for(i=0;i<limite;i++) { if(listado[i].estado == LIBRE) { retorno = i; break; } } } return retorno; } int eGen_siguienteId(eGenerica listado[],int limite) { int retorno = 0; int i; if(limite > 0 && listado != NULL) { for(i=0; i<limite; i++) { if(listado[i].estado == OCUPADO) { if(listado[i].idGenerica>retorno) { retorno=listado[i].idGenerica; } } } } return retorno+1; } int eGen_buscarPorId(eGenerica listado[] ,int limite, int id) { int retorno = -1; int i; if(limite > 0 && listado != NULL) { retorno = -2; for(i=0;i<limite;i++) { if(listado[i].estado == OCUPADO && listado[i].idGenerica == id) { retorno = i; break; } } } return retorno; } int eGen_mostrarUno(eGenerica parametro) { printf("\n %s - %d - %d",parametro.nombre,parametro.idGenerica,parametro.estado); } int eGen_mostrarListado(eGenerica listado[],int limite) { int retorno = -1; int i; if(limite > 0 && listado != NULL) { retorno = 0; for(i=0; i<limite; i++) { if(listado[i].estado==OCUPADO) { eGen_mostrarUno(listado[i]); } } } return retorno; } int eGen_mostrarListadoConBorrados(eGenerica listado[],int limite) { int retorno = -1; int i; if(limite > 0 && listado != NULL) { retorno = 0; for(i=0; i<limite; i++) { if(listado[i].estado==LIBRE) { printf("\n[LIBRE]"); } eGen_mostrarUno(listado[i]); } } return retorno; } int eGen_alta(eGenerica listado[],int limite) { int retorno = -1; char nombre[50]; int id; int indice; if(limite > 0 && listado != NULL) { retorno = -2; indice = eGen_buscarLugarLibre(listado,limite); if(indice >= 0) { retorno = -3; id = eGen_siguienteId(listado,limite); //if(!getValidString("Nombre?","Error","Overflow", nombre,50,2)) // { retorno = 0; int i=0; printf("ingrese nombre:"); setbuf(stdin,NULL ); scanf("%s",nombre); printf("ingrese la contraseña"); scanf("%d",&id); while(nombre[i]!='\0') { if((nombre[i]!='') &&(nombre[i]<'a' || nombre[i]>'z') &&(nombre[i]>'A' || nombre[i]>'Z') && (id[i]<'0' || id[i]>'9')) { return 0 ; i++; }else { printf("ERROR, ingrese los datos correctamente"); } } strcpy(listado[indice].nombre,nombre); listado[indice].idGenerica = id; listado[indice].estado = OCUPADO; // } } } return retorno; }
C
#include <stdio.h> main(){ int c, condition; condition = (c = getchar()) != EOF; switch (condition) { case 1: printf("El valor es 1\n"); break; case 0: printf("El valor es 0\n"); break; default: printf("El valor es otro\n"); } }
C
#ifndef JUSTPOINT_H #define JUSTPOINT_H /************************************************************************************ * PROTOTIPOS DE FUNCIONES ***********************************************************************************/ void checkname(const char* name,const char* mainname); /*Funcion que se encarga de verificar la veracidad del nombre, tiene incorporado un mensaje de error en caso de ser distinto el nombre del archivo (mainname) y el nombre del ejecutable (name)*/ int checkpar(int argc,char *argv[]); /*Funcion que se encarga de detectar y ordenar todos los parametros enviados por la terminal. Devuelve la cantidad de parametros que fueron encontrados*/ int checkopt(int argc,char* argv[]); /*Funcion que se encarga de detectar y ordenar todas las opciones enviadas por la terminal. Devuelve la cantidad de opciones que fueron encontradas */ /************************************************************************************ * CONSTANTES ***********************************************************************************/ #define O_MAX 10 /************************************************************************************ * VARIABLES UTILIZABLES ***********************************************************************************/ extern char * opciones[2][O_MAX]; extern char * parametros [O_MAX]; /*Elegimos hacer las variables globales para que en un futuro si se las necesita, sea mas facil utilizar dichos parametros*/ #endif
C
#include "functions.h" /****************************************************************************** 1- INITIALISATION D'UN RECTANGLE ******************************************************************************/ Rectangle * createRectangle(float hauteur, float largeur, float x, float y, float xfin, float yfin, float puissance){ Rectangle * rect = calloc(1, sizeof(Rectangle)); rect->hauteur = hauteur; rect->largeur = largeur; rect->x = x; rect->y = y; rect->xfin = xfin; rect->yfin = yfin; rect->puissance = puissance; return rect; } /****************************************************************************** 2- COLLISION ******************************************************************************/ int collisionDroite(Rectangle* perso, Rectangle* newObs){ if((perso->x + perso->largeur > newObs->x - 0.6) && (perso->x + perso->largeur <= newObs->x) && (perso->y <= newObs->y + newObs->hauteur) && (perso->y + perso->hauteur >= newObs->y)) { return 1; } return 0; } int collisionGauche(Rectangle* perso, Rectangle* newObs){ if((perso->x < newObs->x + newObs->largeur + 0.6) && (perso->x >= newObs->x + newObs->largeur) && (perso->y <= newObs->y + newObs->hauteur) && (perso->y + perso->hauteur >= newObs->y)) { return 1; } return 0; } int collisionBas(Rectangle* perso, Rectangle* newObs, int *hauteurArret){ if((perso->x + perso->largeur > newObs->x) && (perso->x < newObs->x + newObs->largeur) && (perso->y <= newObs->y + newObs->hauteur) && (perso->y >= newObs->y + newObs->hauteur - 3)) { *hauteurArret = newObs->y + newObs->hauteur; return 1; } return 0; } int collisionHaut(Rectangle* perso, Rectangle* newObs){ if((perso->x + perso->largeur > newObs->x) && (perso->x < newObs->x + newObs->largeur) && (perso->y + perso->hauteur >= newObs->y - 1) && (perso->y < newObs->y + newObs->hauteur - 1)) { return 1; } return 0; } /****************************************************************************** 3- DETECTION FIN DE NIVEAU ******************************************************************************/ int arrive(Rectangle * perso){ int end = 0; if((perso->x > perso->xfin) && (perso->x < perso->xfin + perso->largeur) && (perso->y == perso->yfin)){ end = 1; } else{ end = 0; } return end; } int finNiveau(Rectangle* perso[], int nbPerso, int fin[], int menu){ int cpt = 0, i; for(i = 0; i < nbPerso; i++){ if(fin[i]) cpt ++; } if(cpt == nbPerso){ menu = menu + 1; if(menu > 3){ menu = 0; } } return menu; } /****************************************************************************** 4- FONCTIONS POUR DESSINER ******************************************************************************/ void drawRepere(){ glBegin(GL_LINES); glColor3ub(255,0,0); glVertex2f(0,0); glVertex2f(0,1); glColor3ub(0,255,0); glVertex2f(0,0); glVertex2f(1,0); glEnd(); } void drawPersonnage(Rectangle * perso){ glBegin(GL_QUADS); glVertex2f(perso->x, perso->y); glVertex2f(perso->x + perso->largeur, perso->y); glVertex2f(perso->x + perso->largeur, perso->y + perso->hauteur); glVertex2f(perso->x, perso->y + perso->hauteur); glEnd(); } void drawFinish(Rectangle * perso){ glLineWidth(4); glBegin(GL_LINE_LOOP); glVertex2f(perso->xfin, perso->yfin); glVertex2f(perso->xfin + perso->largeur + 1, perso->yfin); glVertex2f(perso->xfin + perso->largeur + 1, perso->yfin + perso->hauteur + 1); glVertex2f(perso->xfin, perso->yfin + perso->hauteur + 1); glEnd(); } void drawObstacle(Rectangle * newObs){ glBegin(GL_QUADS); glVertex2f(newObs->x, newObs->y); glVertex2f(newObs->x + newObs->largeur, newObs->y); glVertex2f(newObs->x + newObs->largeur, newObs->y + newObs->hauteur); glVertex2f(newObs->x, newObs->y + newObs->hauteur); glEnd(); } void drawFleche(Rectangle * perso){ glBegin(GL_TRIANGLES); glVertex2f(perso->x + ((perso->largeur) / 2), perso->y + perso->hauteur); glVertex2f(perso->x + ((perso->largeur) / 2) + 1, perso->y + perso->hauteur + 1); glVertex2f(perso->x + ((perso->largeur) / 2) - 1, perso->y + perso->hauteur + 1); glEnd(); } void reshape(int winWidth, int winHeight) { glViewport(0, 0, winWidth, winHeight); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(-40., 40., -20*(winHeight/(float)winWidth), 60*(winHeight/(float)winWidth)); } void setVideoMode(int winWidth, int winHeight) { if(NULL == SDL_SetVideoMode(winWidth, winHeight, BIT_PER_PIXEL, SDL_OPENGL | SDL_RESIZABLE)) { fprintf(stderr, "Impossible d'ouvrir la fenetre. Fin du programme.\n"); exit(EXIT_FAILURE); } reshape(winWidth,winHeight); glClear(GL_COLOR_BUFFER_BIT); glClearColor(0.2, 0.5, 0.5, 1); } int drawNumberLevel(int level, GLuint textureId){ //glClear(GL_COLOR_BUFFER_BIT); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, textureId); glBegin(GL_QUADS); glColor3f(1, 1, 1); glTexCoord2f(0, 1); glVertex2f(-40, -15); glTexCoord2f(1, 1); glVertex2f(40, -15); glTexCoord2f(1, 0); glVertex2f(40, 45); glTexCoord2f(0, 0); glVertex2f(-40, 45); glEnd(); glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_TEXTURE_2D); return 0; } int drawBackground(GLuint textureId){ //glClear(GL_COLOR_BUFFER_BIT); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, textureId); glBegin(GL_QUADS); glColor3f(1, 1, 1); glTexCoord2f(0, 1); glVertex2f(-80, -30); glTexCoord2f(1, 1); glVertex2f(80, -30); glTexCoord2f(1, 0); glVertex2f(80, 90); glTexCoord2f(0, 0); glVertex2f(-80, 90); glEnd(); glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_TEXTURE_2D); return 0; } int drawPause(){ SDL_Surface* image = image = IMG_Load("pause.png"); if(image == NULL) { fprintf(stderr, "Impossible de charger l'image \n"); return EXIT_FAILURE; } GLuint textureId; glGenTextures(1, &textureId); glBindTexture(GL_TEXTURE_2D, textureId); glEnable(GL_BLEND); //la couleur de l'objet va être (1-alpha_de_l_objet) * couleur du fond et (le_reste * couleur originale) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image->w, image->h, 0, GL_BGRA, GL_UNSIGNED_BYTE, image->pixels); glBindTexture(GL_TEXTURE_2D, 0); SDL_FreeSurface(image); //glClear(GL_COLOR_BUFFER_BIT); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, textureId); glBegin(GL_QUADS); glColor3f(1, 1, 1); glTexCoord2f(0, 1); glVertex2f(-40, -15); glTexCoord2f(1, 1); glVertex2f(40, -15); glTexCoord2f(1, 0); glVertex2f(40, 45); glTexCoord2f(0, 0); glVertex2f(-40, 45); glEnd(); glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_TEXTURE_2D); return 0; } /****************************************************************************** 5- FONCTION POUR DÉPLACER LA CAMÉRA ******************************************************************************/ void mouvementCamera(Rectangle* perso, int windowWidth, int windowHeight, float* centreX, float* centreY){ float xRapport, yRapport; float distanceCentreX, distanceCentreY; if(perso){ distanceCentreX = perso->x - (*centreX); distanceCentreY = perso->y - (*centreY); xRapport = 0.01*windowWidth; yRapport = 0.01*windowHeight; if(distanceCentreX > xRapport){ (*centreX) += +1 * (distanceCentreX - xRapport) / 10; } else if (distanceCentreX < (-xRapport)){ (*centreX) -= -1 * (distanceCentreX + xRapport) / 10; } if(distanceCentreY > yRapport){ (*centreY) += +1 * (distanceCentreY - yRapport) / 10; } else if (distanceCentreY < (-yRapport)){ (*centreY) -= -1 * (distanceCentreY + yRapport) / 1; } glTranslatef(-(*centreX), -(*centreY), 0.0); } }
C
#include <stdio.h> #include <stdlib.h> #include <locale.h> #include <string.h> #define lb fpurge(stdin) #define lt system("clear") #include "tema.h" #include "escolha.h" #include "inserir.h" #include "errou.h" int main () { printf("\033[34m"); //cor da fonte azul int menu=0; while(menu!=2){ // primeiro while // Declaração das variáveis char *palavra1=(char*) malloc (80* sizeof(char)); char palavra[80]; char palavraAux[80]; char letra; char letrasEntradas[26]; int cont=0; int op=0; int n=0; int chance=6; int achou=0; char *t=(char*) malloc (30* sizeof(char)); int erro=0; int LE=0; setlocale(LC_ALL, "Portuguese"); if(!n>0) { //Escolher o tema t=tema(&op); printf("Tema: %s\n",t); lt; // escolher a palavra de acordo com o tema da forca if(op==1) palavra1 = escolherAstronomia(); if(op==2) palavra1 = escolherFruta (); if(op==3) palavra1 = escolherCidade(); if(op==4) palavra1 = escolherPais(); if(op==5) palavra1 = escolherProfissao(); else printf("Opção inválida\n"); } lt; for(cont=0; cont<strlen(palavra1); cont++) palavra[cont]=palavra1[cont]; /*passando para "palavra", a palavra recebida da função*/ for(cont=0; cont<strlen(palavra1); cont++) palavraAux[cont] = palavra[cont];/*passando para "palavraAux", a palavra recebida em palavra*/ for(cont=0; cont<strlen(palavra1); cont++) palavra[cont] = '_'; /*prenchendo "palavra" com um underline*/ lt; // segundo while while(n<strlen(palavra1)) {// Enquanto tamanho da palavra maior que "n" if(n<strlen(palavra1)) //1º if {// Se o tamanho da palavra for maior que "n" for(cont=0; cont<strlen(palavra); cont++) { // 2º for // Inserindo a primeira letra if(LE==0)//Verificando o Valor em LE { //se LE for 0 letrasEntradas recebe um hifen for(cont=0;cont<26;cont++) letrasEntradas[cont]='-'; letrasEntradas[25]='\0'; } //chamada da função inserir letra=inserir(palavra); //passando para "letrasEntradas" o caracter em letra letrasEntradas[LE]=letra; LE+=2;//incrementando LE de 2 em 2 // Verificando se a letra foi está na palavra for(cont=0; cont<strlen(palavra); cont++) { //3º for if(letra==palavraAux[cont]) {//2º if palavra[cont] = letra; n++; achou=1; } // Chaves do 2º if }// Chaves do 3º for if(achou != 1) {// 3º if chance--; n=naoAchou( chance, n,palavraAux,letra); }//Chaves do 3º if if(n==strlen(palavra)) printf("\033[46mParabéns, a palavra era:\033[40m\n"); if(n<1000) { if(n<strlen(palavra)) printf("\033[46mTema: %s\033[40m\n",t); printf("%s\n\n",palavra); printf("\033[46mLetras entradas:\n\033[40m\033[41m\033[30m%s\n\033[34m\033[40m\n",letrasEntradas); } achou = 0; }// Chaves do 2º for } // Chaves do 1º if }// segundo while lb; getchar(); lt; menuFinal(&menu); if(menu!=2) { for(cont=0; cont<strlen(palavra); cont++) { lb; palavra[cont]=NULL; lb; palavraAux[cont]=NULL; // palavra1[cont]=NULL; } } lt; if(menu!=1) break; }// primeiro while }// Chaves do main
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <sys/sem.h> #include <sys/ipc.h> #include <sys/shm.h> #include <string.h> #include <sys/resource.h> #define TAMBUF 1024 #define CANTMSJS 1000 /* Sale del programa emitiendo un error */ void error(char *error); union semun { int val; struct semid_ds *buf; unsigned short *array; struct seminfo *__buf; }; int main() { union semun ctlSem; struct sembuf opSem; opSem.sem_num = 0; opSem.sem_flg = 0; int semIniA, semIniB; semIniB = semget(ftok(".", 'i'), 1, IPC_CREAT | 0660); semIniA = semget(ftok(".", 'j'), 1, IPC_CREAT | 0660); ctlSem.val = 0; semctl(semIniB, 0, SETVAL, ctlSem); opSem.sem_op = 1; semop(semIniB, &opSem, 1); printf("Esperando ProcesoA...\n"); opSem.sem_op = -1; semop(semIniA, &opSem, 1); printf("ProcesoA detectado\n"); int shmid = shmget(ftok(".", 'z'), TAMBUF*sizeof(char), 0660); if (shmid==-1) { error("No se pudo crear la memoria compartida"); } char *mensaje = (char*)shmat(shmid,NULL,0); char mensajeTmp[TAMBUF]; int sem1, sem2; sem1 = semget(ftok(".", 'x'), 1, 0660); sem2 = semget(ftok(".", 'y'), 1, 0660); if (sem1==-1 || sem2==-1) { error("No se pudo crear algun semaforo"); } int i; for( i=0; i<CANTMSJS; i++ ) { //printf("Leyendo proceso B %d\n",i); opSem.sem_op = -1; semop(sem2, &opSem, 1); strcpy(mensajeTmp, mensaje); //printf("Leyo proceso B %d\n",i); if (i==0) //printf("%s\n",mensajeTmp); //sleep(3); //printf("Escribiendo proceso B %d\n",i); strcpy(mensaje, mensajeTmp); opSem.sem_op = 1; semop(sem1, &opSem, 1); //printf("Escribio proceso B %d\n",i); } return 0; } void error(char *error) { fprintf(stderr, "Error: %s (%d, %s)\n", error, errno, strerror(errno)); exit(EXIT_FAILURE); }
C
#include <stdio.h> int main() { unsigned long long int ve[61]; int i, con, con1; ve[0] = 0; ve[1] = 1; for ( i = 2; i < 61; ++i) { ve[i] = ve[i-1] + ve[i-2]; } scanf("%d", &con); for ( i = 0; i < con; ++i) { scanf("%d", &con1); printf("Fib(%d) = %lld\n", con1, ve[con1]); } return 0; }
C
// // day03.c // 42_C_piscine // // Created by 游宗諭 on 2020/8/10. // Copyright © 2020 游宗諭. All rights reserved. // #include "day03.h" #include "ft_putchar.h" void test_day03(void) { int nbr = 0; ft_ft(&nbr); printf("%d",nbr); ft_putchar('\n'); int a = 1; int b = 2; ft_swap(&a, &b); printf("%d,%d",a,b); ft_putchar('\n'); }
C
//Atta Ebrahimi #include "mymalloc.h" #include <unistd.h> #include <stdio.h> //Keeps track of beginning and end void *base = NULL; void *curr_pos = NULL; //Represents doubly linked list used to keep track of memory typedef struct metadata_node *block; struct metadata_node { int chunk_size; //stores size of mallocd region in bytes int free_flag; //space free if 0, otherwise not free block next; //store next node block prev; //store previous node char data_ptr[1]; //stores pointer to block that stores metadata void *ptr; }; //Finds block block find_block ( int size ) { block b = curr_pos; //loop to find free area while ( b && !(b->free_flag) && (b->chunk_size <= size) ) { /* * (1) If pointer is not null at the end keep going * (2) If end is reached go back to where we started * (3) NULL if no space found. */ if (b != NULL) { b = b->next; }else { b = base; if(b == curr_pos) return NULL; } } curr_pos = sbrk(0); //return that address if appropriate space was found for requested size return b; } //Expands heap if no empty space block extend_heap ( block last, int s ) { block b; b = sbrk(0); if( sbrk( sizeof(struct metadata_node) +s ) == (void*)-1 ) return (NULL); b->chunk_size = s; b->next = NULL; if( last != NULL ) last->next = b; b->free_flag = 0; return (b); } void *my_nextfit_malloc( int size ) { block b; block last; if( base != NULL ) { last = curr_pos; b = find_block(size); if(b != NULL ) { //Set to free if b != NULL b->free_flag = 0; }else{ b = extend_heap (last ,size); if ( b == NULL ) return(NULL); } } else { b = extend_heap(NULL, size); if( b == NULL ) return NULL; //keep track of current position and base base = b; curr_pos = b; } return (b->data_ptr); } block free_block( void *p ) { char *tmp; tmp = p; return (p = tmp -= sizeof(struct metadata_node)); } //Checks if pointer is on the heap to validate int valid( void *p ) { if (base) if(p>base && p<sbrk(0)) return (p == (free_block(p)) -> ptr); return (0); } //Coalesce to eliminate fragmentation block coalesce( block b) { if (b->next && b->next->free_flag){ b->chunk_size += sizeof(struct metadata_node) +b->next->chunk_size; b->next = b->next->next; if(b->next) b->next->prev = b; } return (b); } void my_free( void *ptr ) { block b; if ( valid(ptr) ) { b = free_block(ptr); b->free_flag = 1; if(b->prev && b->prev->free_flag) b = coalesce(b->prev); if(b->next) coalesce(b); else { if(b->prev) b->prev->next = NULL; else base = NULL; brk(b); } } }
C
#include<stdio.h> #include<conio.h> #include<stdlib.h> typedef struct tr { int item; struct tr* left; struct tr* right; }bst; bst *save, *ptr,*parent,*node; int ter=0,terrec=0,n=0; void display(bst *ptr, int level){ int i; if(ptr!=NULL){ display(ptr->right, level+1); printf("\n"); for (i = 0; i < level; i++) printf(" "); printf("%d", ptr->item); display(ptr->left, level+1); } } void create(bst *tree,int x) { tree->left=tree->right=NULL; tree->item=x; } void insert(bst *tree,int x) { ptr=(bst *)malloc(sizeof(bst)); ptr->left=ptr->right=NULL; ptr->item=x; node=tree; while(node!=NULL) { parent=node; if(x<(node->item)) { node=node->left; } else { node=node->right; } } if(x<parent->item) { parent->left=ptr; } else { parent->right=ptr; } } void inorder(bst *p) { if(p!=NULL) { inorder(p->left); printf("\t%d",p->item); inorder(p->right); } } void preorder(bst *p) { if(p!=NULL) { printf("\t%d",p->item); preorder(p->left); preorder(p->right); } } void postorder(bst *p) { if(p!=NULL) { postorder(p->left); postorder(p->right); printf("\t%d",p->item); } } int main() { int choice,x; char ans; bst *root; clrscr(); printf("A Program By Chanpreet Singh\n"); printf("\n 1.Create"); printf("\n 2.Insert"); printf("\n 3.Inorder"); printf("\n 4.Preorder"); printf("\n 5.Postorder"); printf("\n 6.display"); do { fflush(stdin); printf("\nEnter Choice "); scanf("%d",&choice); switch(choice) { case 1: root=(bst *)malloc(sizeof(bst)); printf("\n Enter no "); scanf("%d",&x); create(root,x); break; case 2: printf("\n Enter no "); scanf("%d",&x); insert(root,x); break; case 3: inorder(root); break; case 4: preorder(root); break; case 5: postorder(root); break; case 6: display(root,1); } fflush(stdin); printf("\nWant to Continue "); scanf("%c",&ans); }while(ans=='y'); getch(); return 0; }
C
#include <stdio.h> #include <stdlib.h> void swap(int *a, int *b, int *c) { *b ^= *c; *c ^= *b; *b ^= *c; *a ^= *b; *b ^= *a; *a ^= *b; } /* * Al llamar al programa se piden tres caracteres a, b y c, * se llama a la funcion swap con estos caracteres, * y finalmente se imprime el valor actual de las variables * donde se guardaron los caracteres. */ int main(void) { int _a, _b, _c; int *a = &_a, *b = &_b, *c = &_c; printf("a: "); *a = getchar(); getchar(); //Tira el caracter \n printf("b: "); *b = getchar(); getchar(); //Tira el caracter \n printf("c: "); *c = getchar(); swap(a,b,c); putchar('\n'); printf("a: %c\n", *a); printf("b: %c\n", *b); printf("c: %c\n", *c); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #define MAXCHAR 1000 void main() { FILE *p,*fsym,*fop,*fl; char label[100],opcode[100],operand[100],c,optab[100]; int value,locctr,sa=0,otp,op1,len; p = fopen("input.txt","r"); fsym = fopen("symtab.txt","w"); fl = fopen("length.txt","w"); fscanf(p,"%s %s %d",label,opcode,&value); // while (fgets(str, MAXCHAR, p) != NULL) // { // fscanf(p, "%s %s %d", label, opcode,&value); // printf("%s %s %d\n",label,opcode,value); // if(strcmp(opcode,"START")==0) // { // locctr = value; // // locctr = value; // } // else // locctr = 0; // Unsuccesful method to read each file if(strcmp(opcode,"START") == 0) { sa = value; locctr = sa; printf("\t%s\t%s\t%d\n",label,opcode,value); } else locctr=0; fscanf(p,"%s%s",label,opcode); // While not end of file, search assembly file while(!feof(p)) { fscanf(p,"%s",operand); printf("\n%d\t%s\t%s\t%s\n",locctr,label,opcode,operand); if(strcmp(label,"-") != 0) { // Insert into symtab fprintf(fsym,"\n%d\t%s\n",locctr,label); } fop=fopen("optab1.txt","r"); // Search OPTAB FOR OPCODE while(!feof(fop)) { fscanf(fop,"%s %d",optab,&otp); // printf(" %s %s",opcode,optab); if(strcmp(opcode,optab)==0) { locctr=locctr+3; } } fclose(fop); if(strcmp(opcode,"WORD")==0) { locctr=locctr+3; } else if(strcmp(opcode,"RESW")==0) { op1=atoi(optab); locctr=locctr+(3*op1); } else if(strcmp(opcode,"BYTE")==0) { if(optab[0]=='X') locctr=locctr+1; else { len=strlen(optab)-2; locctr=locctr+len; } } else if(strcmp(opcode,"RESB")==0) { op1=atoi(optab); locctr=locctr+op1; } fscanf(p,"%s%s",label,opcode); } if(strcmp(opcode,"END")==0) { printf("Program length =\n%d",locctr-sa); fprintf(fl,"%d",locctr-sa); } fclose(p); fclose(fsym); }
C
/** * @file log.c * @author malin * @mail [email protected] * @time 二 10/13 16:59:19 2015 */ #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <stdarg.h> #include <stdio.h> #include "log.h" #include "../util/vector.h" #include "../algo/str.h" int logger_init(logger *log, int flag, const char *out) { log->flag = flag; log->out = open(out, O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR); if (log->out == -1) { return ERR_LOGGER_CREATE_FILE; } // initail buffer int retCode = buffer_init(&(log->buf), 0); if (retCode > 0) { close(log->out); return retCode; } // create and initial the attributes for lock pthread_mutexattr_t mtx_attr; retCode = pthread_mutexattr_init(&mtx_attr); if (retCode > 0) { return retCode; } retCode = pthread_mutexattr_settype(&mtx_attr, PTHREAD_MUTEX_ERRORCHECK); if (retCode > 0) { return retCode; } // initial lock retCode = pthread_mutex_init(&(log->lock), &mtx_attr); pthread_mutexattr_destroy(&mtx_attr); if (retCode > 0) { close(log->out); return retCode; } return 0; } int logger_destroy(logger *log) { int out_ret_code = close(log->out); if (out_ret_code == -1) { return ERR_LOGGER_DESTROY_FILE; } int buffer_ret_code = buffer_destroy(&(log->buf)); if (buffer_ret_code > 0) { return buffer_ret_code; } int lock_ret_code = pthread_mutex_destroy(&(log->lock)); if (lock_ret_code > 0) { return lock_ret_code; } return 0; } static int lock(logger *log) { return pthread_mutex_lock(&(log->lock)); } static int unlock(logger *log) { return pthread_mutex_unlock(&(log->lock)); } static int append_time_element(buffer *buf, vector *tsp, unsigned int index) { void *str = NULL; int retCode = v_get_ptr(tsp, index, &str); if (retCode > 0) { return retCode; } retCode = buffer_append(buf, str, strlen((char*)str)); if (retCode > 0) { return retCode; } return buffer_append(buf, " ", 1); } static int format_time(logger *log) { vector tsp; vector_init(&tsp, 0); time_t ti = time(NULL); char *time_str = (char*)(ctime(&(ti))); str_split(time_str, " \n", &tsp); int retCode = 0; if (log->flag & DATE) { // append month if ((retCode = append_time_element(&(log->buf), &tsp, 1)) > 0) { return retCode; } // append day if ((retCode = append_time_element(&(log->buf), &tsp, 2)) > 0) { return retCode; } // append year if ((retCode = append_time_element(&(log->buf), &tsp, 4)) > 0) { return retCode; } } if (log->flag & TIME) { // append time if ((retCode = append_time_element(&(log->buf), &tsp, 3)) > 0) { return retCode; } } return 0; } static int append_path_element(buffer *buf, const char *str) { int retCode = buffer_append(buf, (void*)str, strlen(str)); if (retCode) { return retCode; } return buffer_append(buf, " ", 1); } static int format_file_path(logger *log, const char *filename, int line) { int retCode = 0; if (log->flag & SFILE) { if ((retCode = buffer_append(&(log->buf), "[", 1)) > 0) { return retCode; } if ((retCode = append_path_element(&(log->buf), filename)) > 0) { return retCode; } char line_buf[20]; if ((retCode = append_path_element(&(log->buf), itoa(line, line_buf, 10))) > 0) { return retCode; } buffer_reduce(&(log->buf), 1); if ((retCode = buffer_append(&(log->buf), "] ", 2)) > 0) { return retCode; } } return 0; } static int format_tag(buffer *buf, const char *tag) { int retCode = 0; if ((retCode = buffer_append(buf, "[", 1)) > 0) { return retCode; } if ((retCode = buffer_append(buf, (void*)tag, strlen(tag))) > 0) { return retCode; } if ((retCode = buffer_append(buf, "] ", 2)) > 0) { return retCode; } return retCode; } static int output(logger *log, const char *tag, const char *content, const char *filename, int line) { int retCode = 0; lock(log); if ((retCode = format_time(log)) > 0) { unlock(log); return retCode; } if ((retCode = format_file_path(log, filename, line)) > 0) { unlock(log); return retCode; } if ((retCode = format_tag(&(log->buf), tag)) > 0) { unlock(log); return retCode; } retCode = buffer_append(&(log->buf), (void*)content, strlen(content)); if (retCode > 0) { unlock(log); return retCode; } retCode = buffer_append(&(log->buf), "\n", 1); if (retCode > 0) { unlock(log); return retCode; } if (buffer_size(&(log->buf)) > THR) { unlock(log); return logger_flush(log); } return unlock(log); } int logger_printf_execute(logger *log, const char *filename, int line, const char *format, ...) { //TODO log will be trunc if length exceed 2048 va_list start; va_start(start, format); char buf[2048]; vsnprintf(buf, 2048, format, start); return output(log, "INFO", buf, filename, line); } int logger_warnf_execute(logger *log, const char *filename, int line, const char *format, ...) { //TODO log will be trunc if length exceed 2048 va_list start; va_start(start, format); char buf[2048]; vsnprintf(buf, 2048, format, start); return output(log, "WARN", buf, filename, line); } int logger_errorf_execute(logger *log, const char *filename, int line, const char *format, ...) { //TODO log will be trunc if length exceed 2048 va_list start; va_start(start, format); char buf[2048]; vsnprintf(buf, 2048, format, start); return output(log, "ERORR", buf, filename, line); } int logger_flush(logger *log) { lock(log); size_t size = buffer_size(&(log->buf)); int retCode = write(log->out, buf_to_str(&(log->buf)), size); if (retCode == -1) { unlock(log); return retCode; } if ((retCode = buffer_reduce(&(log->buf), size)) > 0) { unlock(log); return retCode; } return unlock(log); } int logger_flag(logger *log) { return log->flag; } int logger_set_flag(logger *log, int flag) { int old_flag = log->flag; log->flag = flag; return old_flag; } int logger_set_output(logger *log, const char *out) { int retCode; if ((retCode = close(log->out)) > 0) { return retCode; } if ((log->out = open(out, O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR)) == -1) { return ERR_LOGGER_CREATE_FILE; } return 0; }
C
#pragma once #include <stddef.h> #ifdef __cplusplus extern "C" { #endif // These are possible errors that can happen with mmap_s3 #define MMAP_S3_OK 0 // everything went okay #define MMAP_S3_ERRNO 1 // some syscall failed, use "errno" to check how #define MMAP_S3_NOT_FOUND 4 // bucket or key not found #define MMAP_S3_PERMISSION_ERROR 5 // we are not allowed to read from S3 #define MMAP_S3_INVALID_S3URL 7 // the S3 url is invalid // These errors are defined but they should never happen; only if our // library is buggy or S3 is not conforming to its protocol in some way. #define MMAP_S3_IOERROR 2 // I/O error while downloading #define MMAP_S3_CONTENT_LENGTH_NOT_RETURNED 3 // No content length returned from S3 #define MMAP_S3_NO_BODY_RETURNED 6 // S3 GET request didn't include body #define MMAP_S3_UNKNOWN 7 // Some error happened we have not categorized. // Memory maps an S3 object. Returns a pointer to it or MAP_FAILED. Reading // from the pointer will trigger downloads from S3 on-demand. // // If 'err' is not NULL, an error code of MMAP_S3_* is filled into it if // something bad happens. // // If 'sz' is not NULL, it will be filled with the size of the mapping. You // probably really want to use it or you won't know how far returned // pointer will be valid. // // If any errors happen while you are touching the returned pages, the // program will call abort(). // // The returned pointer is read-only. // // Unmap the region with munmap_s3(). const void* mmap_s3(const char* s3url, size_t* sz, int* err); // Unmaps a region previously mapped with mmap_s3(). // // Returns -1 if the pointer is unrecognized and then does nothing. // Otherwise returns 0 and the memory is released. // // Note: this call may take some time to complete because it has to stop // threads that are potentially quite busy. Usually it's just hundreds of // milliseconds. int munmap_s3(const void* ptr); // Takes an error code and turns it into a string that can be displayed. const char* mmap_s3_errstr(int err); #ifdef __cplusplus } // extern "C" #endif
C
#pragma once #include "Material.h" #include "Date.h" #include "DynamicArray.h" #include <string.h> typedef struct { Material* _material; char* _operationType; }Operation; Operation* createOperation(Material* material, char* operationType); void destroyOperation(Operation* operation); Operation* copyOperation(Operation* operation); char* getOperationType(Operation* operation); Material* getMaterial(Operation* operation);; typedef struct { Operation* _operations[100]; int _length; }OperationStack; OperationStack* createOperationStack(); void destroyOperationStack(OperationStack* s); void push(OperationStack* s, Operation* o); Operation* pop(OperationStack* s); int isEmpty(OperationStack* s); int isFull(OperationStack* s); void testStack();
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_part_of_the_stack.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hcharlsi <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/05/17 17:24:12 by hcharlsi #+# #+# */ /* Updated: 2021/05/17 17:24:13 by hcharlsi ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" t_stacks *ft_part_of_the_stack(t_stacks **stack) { t_stacks *part_of_the_stack; t_stacks *stack_el_copy; part_of_the_stack = NULL; while ((*stack) && (*stack)->was_in_b < 1) { stack_el_copy = ft_lstnew((*stack)->value, (*stack)->index_in_sort_arr, (*stack)->was_in_b); ft_lstadd_back(&part_of_the_stack, stack_el_copy); ft_lstdel(stack); //free(stack_el_copy); (*stack) = (*stack)->next; } return (part_of_the_stack); }
C
#include<stdio.h> int main() { int x,y; scanf("%4d %3d",&x,&y); printf("%d %d\n",x,y); }
C
//Dhruv Modi //110009086 //14-April-2020 //server.c #include <stdio.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/signal.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> void servicePlayers(int TOTO,int TITI, int zs){ //function called when child process of server is created char m1[255],m2[255]; //variables to store the value of dice int exi=0; int p1=0,p2=0; //p1= total of toto, p2= total of titi if(zs==0) //Display nothing on server { while(exi==0){ write(TOTO, "You can now play" , strlen("You can now play")+1); //send message to client 1 for rolling the dice if(!read(TOTO, m1, 255)){ //read the responded dice value from the client close(TOTO); fprintf(stderr,"Bye, client dead, wait for a new client\n"); exit(0); } p1=p1+atoi(m1); //add the dice value to the total value if(p1>=100) //if the total value of client 1 is 100 close all the connections announcing client 1 the winner { write(TOTO, "Game over: you won the game" , strlen("Game over: you won the game")+1); //announce client 1 winner write(TITI, "Game over: you lost the game" , strlen("Game over: you lost the game")+1); //announce client 2 loser close(TOTO); //close connection close(TITI); //close connection exit(0); } write(TITI, "You can now play" , strlen("You can now play")+1); //send message to client 2 for rolling the dice if(!read(TITI, m2, 255)){ //read the responded dice value from the client close(TITI); fprintf(stderr,"Bye, client dead, wait for a new client\n"); exit(0); } p2=p2+atoi(m2); //add the dice value to the total value if(p2>=100)//if the total value of client 2 is 100 close all the connections announcing client 2 the winner { write(TITI, "Game over: you won the game" , strlen("Game over: you won the game")+1); //announce client 2 winner write(TOTO, "Game over: you lost the game" , strlen("Game over: you lost the game")+1); //announce client 1 loser close(TOTO); //close connection close(TITI); //close connection exit(0); } } } else //Display everything on server { while(exi==0){ write(TOTO, "You can now play" , strlen("You can now play")+1); //send message to client 1 for rolling the dice if(!read(TOTO, m1, 255)){ //read the responded dice value from the client close(TOTO); fprintf(stderr,"Bye, client dead, wait for a new client\n"); exit(0); } p1=p1+atoi(m1); //add the dice value to the total value fprintf(stderr,"TOTO got %s\n",m1); if(p1>=100) //if the total value of client 1 is 100 close all the connections announcing client 1 the winner { fprintf(stderr,"-------------------------------\nTOTO WON\n-----------------------------"); write(TOTO, "Game over: you won the game" , strlen("Game over: you won the game")+1); write(TITI, "Game over: you lost the game" , strlen("Game over: you lost the game")+1); close(TOTO); close(TITI); exit(0); } write(TITI, "You can now play" , strlen("You can now play")+1); //send message to client 2 for rolling the dice if(!read(TITI, m2, 255)){ //read the responded dice value from the client close(TITI); fprintf(stderr,"Bye, client dead, wait for a new client\n"); exit(0); } p2=p2+atoi(m2); //add the dice value to the total value fprintf(stderr,"TITI got %s\n\n",m2); fprintf(stderr,"TOTO= %d\n",p1); fprintf(stderr,"TITI= %d\n\n------------------------\n",p2); if(p2>=100) //if the total value of client 2 is 100 close all the connections announcing client 2 the winner { fprintf(stderr,"-------------------------------\nTITI WON\n-----------------------------"); write(TITI, "Game over: you won the game" , strlen("Game over: you won the game")+1); write(TOTO, "Game over: you lost the game" , strlen("Game over: you lost the game")+1); close(TOTO); close(TITI); exit(0); } } } } int main(int argc, char *argv[]){ int sd, client1, client2, portNumber; socklen_t len; struct sockaddr_in servAdd; if(argc != 3){ //check if the command is written in proper format printf("Call model: %s <Port #> <visiblity>\n", argv[0]); exit(0); } if ((sd=socket(AF_INET,SOCK_STREAM,0))<0){ fprintf(stderr, "Cannot create socket\n"); exit(1); } servAdd.sin_family = AF_INET; servAdd.sin_addr.s_addr = htonl(INADDR_ANY); sscanf(argv[1], "%d", &portNumber); servAdd.sin_port = htons((uint16_t)portNumber); bind(sd,(struct sockaddr*)&servAdd,sizeof(servAdd)); listen(sd, 5); while(1){ printf("Waiting for players to connect"); client1=accept(sd,(struct sockaddr*)NULL,NULL); printf("Got TOTO\n"); client2=accept(sd,(struct sockaddr*)NULL,NULL); printf("Got TITI\n"); if(!fork()) //CREATE CHILD PROCESS { servicePlayers(client1,client2,atoi(argv[2])); } close(client1); close(client2); } }
C
#include <stdio.h> #include <stdlib.h> struct Array{ int A[10]; int size; int length; }; void Append(struct Array *arr, int x){ if (arr->length < arr->size){ arr->A[arr->length++] = x; } } void Insert(struct Array *arr, int index, int x){ int i; if(index >= 0 && index <= arr->length){ for(i = arr->length; i > index; i--){ arr->A[i] = arr->A[i-1]; } arr->A[index] = x; arr->length++; } } int Delete (struct Array *arr, int index){ int x = 0; int i; if(index >= 0 && index <= arr->length-1){ x = arr->A[index]; for(i = index; i < arr->length-1; i++){ arr->A[i] = arr->A[i+1]; } arr->length--; return x; } return 0; } void Display(struct Array arr){ int i; printf("\nElements are\n"); for (i = 0; i < arr.length; i++){ printf("%d ", arr.A[i]); } } void Swap(int *x, int *y){ int tempo; tempo = *x; *x = *y; *y = tempo; } int BinarySearch(struct Array arr, int key){ int low = 0; int mid; int high = arr.length-1; while(low <= high){ mid = (low + high) / 2; if(key == arr.A[mid]){ return mid; } else if(key < arr.A[mid]){ high = mid - 1; } else{ low = mid + 1; } } return -1; } int RBinSearch(int a[], int low, int high, int key){ int mid; if(low <= high){ mid = (low + high) / 2; if(key == a[mid]){ return mid; } else if(key < a[mid]){ return RBinSearch(a, low, mid-1, key); } else{ return RBinSearch(a, mid+1, high, key); } } return -1; } int Get(struct Array arr, int index){ if(index >= 0 && index < arr.length){ return arr.A[index]; } return -1; } int Max(struct Array arr){ int max = arr.A[0]; int i; for(i = 1; i < arr.length; i++){ if(arr.A[i] > max){ max = arr.A[i]; } } return max; } int Min(struct Array arr){ int min = arr.A[0]; int i; for(i = 1; i < arr.length; i++){ if(arr.A[i] < min){ min = arr.A[i]; } } return min; } int Sum(struct Array arr){ int s = 0; int i; for(i = 0; i < arr.length; i++){ s += arr.A[i]; } return s; } float Avg(struct Array arr){ return (float) Sum(arr)/arr.length; } void Set(struct Array *arr, int index, int x){ if(index >= 0 && index < arr->length){ arr->A[index] = x; } } void InsertSort(struct Array *arr, int x){ int i = arr->length-1; if(arr->length == arr->size){ return; } while(i >= 0 && arr->A[i] > x){ arr->A[i+1] = arr->A[i]; i--; } arr->A[i+1] = x; arr->length++; } int isSorted(struct Array arr){ int i; for(i = 0; i < arr.length-1; i++){ if(arr.A[i] > arr.A[i+1]){ return 0; } } return 1; } void Rearrange(struct Array *arr){ int i; int j; i = 0; while(i < j){ while(arr->A[i] < 0) i++; while(arr->A[j] >= 0) j--; if(i < j) Swap(&arr->A[i], &arr->A[j]); } } int main(){ struct Array arr = {{2,3,5,10,15}, 10,5}; struct Array arr2 = {{2,3,5,10,15}, 10,5}; struct Array arr3 = {{0,-34,35,-1,6,-8}, 10,6}; InsertSort(&arr, 4); printf("InsertSort\n"); Display(arr); printf("\nIs Sorted?: "); printf("%d\n", isSorted(arr2)); printf("Rearrange, negatives to left side"); Rearrange(&arr3); Display(arr3); return 0; }
C
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #define NUM_FILOS 5 pthread_mutex_t forks[NUM_FILOS]; void actions(){sleep(1+rand()%5);} void *life(void *ptID){ long tid = (long) ptID; srand(time(NULL)+tid); if(NUM_FILOS<2){ printf("No puedo comer tan poquito %ld\n ",tid); exit(-1); } while (1) { // Pensar printf("Voy a pensar un rato %ld\n ",tid); actions(); printf("Tengo hambre %ld\n ",tid); if(tid%2 == 0){ pthread_mutex_lock(&forks[tid]); printf("Tengo más hambre, me comeré el plato de mi amigo la derecha %ld\n ",tid); pthread_mutex_lock(&forks[(tid+1)%NUM_FILOS]); printf("Tengo tanta hambre que me robaré y me comeré el plato de mi amigo a la izquierda %ld\n ",tid); // Comer printf("Tengo hambre %ld\n ",tid); actions(); printf("Regresaré los tenedores a su sitio %ld\n ",tid); pthread_mutex_unlock(&forks[tid]); pthread_mutex_unlock(&forks[(tid+1)%NUM_FILOS]); }else{ pthread_mutex_lock(&forks[(tid+1)%NUM_FILOS]); printf("Tengo tanta hambre que me robaré y me comeré el plato de mi amigo a la izquierda %ld\n ",tid); pthread_mutex_lock(&forks[tid]); printf("Tengo más hambre, me comeré el plato de mi amigo la derecha %ld\n ",tid); // Comer printf("Tengo hambre %ld\n ",tid); actions(); printf("Regresaré los tenedores a su sitio %ld\n ",tid); pthread_mutex_unlock(&forks[tid]); pthread_mutex_unlock(&forks[(tid+1)%NUM_FILOS]); } } } int main (int argc, char *argv[]){ pthread_t threads[NUM_FILOS]; int rc; long t; for(t=0; t<NUM_FILOS; t++){ printf("In main: creating thread %ld\n", t); rc = pthread_create(&threads[t], NULL, life, (void *)t); if (rc){ printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } } /* Last thing that main() should do */ pthread_exit(NULL); }
C
/* Evaluate U.S. readability grade computed by the Coleman-Liau formula */ #include <stdio.h> #include <cs50.h> #include <math.h> int count_letters(string text); //count letters in a text int count_words(string text); // count words in a text int count_sentences(string text); // count sentences in a text // calculates average of total (value1 =) {letters, senteces} per 100 (value2 =) words float average(int value1, int value2, int per_number_of); int readability(string text); // evaluate index for readability of the text int main(void) { string text = get_string("Test: "); //Promts text from user int grade = readability(text); //gets the readability index if (grade < 1) { printf("Before Grade 1\n"); } else if (grade >= 1 && grade <= 16) { printf("Grade %i\n", grade); } else { printf("Grade 16+\n"); } return 0; } /* count the number of: - letters, - words, and - sentences in the text */ //function counts the number of letters int count_letters(string text) { int count = 0; for (int i = 0; text[i] != '\0'; i++) { if (text[i] >= 65 && text[i] <= 90) // count the number of characters from 'a' to 'z' { count ++; } else if (text[i] >= 97 && text[i] <= 122) // count the number of characters from 'A' to 'Z' { count++; } } return count; } //function counts the number of words int count_words(string text) { int count = 0; int space = 32; for (int i = 0; text[i] != '\0'; i++) { if (text [i] == space) //count the number of spaces in the text { count ++; } } return count + 1; } //function counts the number of senteces int count_sentences(string text) { int count = 0; int punktum = 46; int question = 63; int exclamait = 33; for (int i = 0; text[i] != '\0'; i++) { if (text [i] == punktum) //count the number of characters equal to '.' in the text { count ++; } else if (text [i] == question) //count the number of characters equal to '?' in the text { count ++; } else if (text [i] == exclamait) //count the number of characters equal to '!' in the text { count ++; } } return count; } // compute average number of value 1 per_number_of value2 float average(int value1, int value2, int per_number_of) { return ((float) value1 * per_number_of) / value2; } //compute the readability index by the Coleman-Liau formula int readability(string text) { int letters = count_letters(text); // gets number of letters from function count_letters() int words = count_words(text); // gets number of words from function count_words() int sentences = count_sentences(text); // gets number of sentences from function count_sentences() const float const1 = 0.0588; //first constant from the Coleman-Liau formula const float const2 = 0.296; //second constant from the Coleman-Liau formula const float const3 = 15.8; //third constant from the Coleman-Liau formula float L = average(letters, words, 100); //compute average number of letter per 100 words float S = average(sentences, words, 100); //compute average number of sentences per 100 words float index = const1 * L - const2 * S - const3; // compute readability index return round(index); }
C
#include<stdio.h> #include<string.h> void stringconvert(char s[], int n){ char c[500][500]; int row=0, column=0, flag=1; int i, j; for(i=0; i<strlen(s); i++){ c[row][column] = s[i]; if(row == n-1){ flag = 0; } if(row == 0){ flag = 1; } if(flag){ row++; } else { row--; column++; } } for(i=0;i<n;i++){ for(j=0;j<=column;j++){ if(c[i][j]){ printf("%c", c[i][j]); } } } } void main(){ char s[1000]; int n; printf("Enter s: "); scanf("%s", s); printf("Enter n: "); scanf("%d", &n); stringconvert(s, n); }
C
static int cmp(int *a, int *b) { return *a - *b; } static inline int get(char *a, int n) { return (a[n / 8] >> (n % 8)) & 1; } static inline void set(char *a, int n) { a[n / 8] |= 1 << (n % 8); } int main() { int N, M, i, *k; char *res; #ifdef ONLINE_JUDGE scanf("%d%d", &N, &M); k = malloc(M * sizeof(int)); for (i = 0; i < M; ++i) { scanf("%d", k + i); } #else N = 17; M = 3; k = malloc(M * sizeof(int)); k[0] = 4; k[1] = 3; k[2] = 1; #endif qsort(k, M, sizeof(int), cmp); res = malloc(N / 8 + 1); memset(res, 0, N / 8 + 1); int current; for (current = k[0]; current <= N; ++current) { int canInv = 0; int j; for (j = 0; j < M; ++j) { int move = k[j]; if (current > move) { canInv = get(res, current - move) == 0; } if (canInv) { break; } } if (canInv) { set(res, current); } } free(k); printf("%d\n", 2 - get(res, N)); free(res); return 0; }
C
#include "boot.h" #define SECTSIZE 512 void bootMain(void) { /* 加载内核至内存,并跳转执行 */ char* buf = (char*)0x400000; /* loading kMain.elf to memory */ for(int i=0; i<200; i++){ readSect((void*)(buf + i*SECTSIZE), i+1); } struct ELFHeader *elf = (struct ELFHeader*) buf; struct ProgramHeader *ph,*eph; ph = (struct ProgramHeader*)((char*)elf + elf->phoff); eph = ph + elf->phnum; for(; ph < eph; ph++){ if(ph->type == 1){ //PT_LOAD // buf+ph->off: the offset of this segment in the ELF file // ph->vaddr : the vaddr of the first byte of this segment for(int i=0; i< ph->filesz; i++) *((char*)ph->vaddr+i) = *((char*)buf + ph->off + i); if(ph->filesz < ph->memsz){ for(int i = ph->filesz; i < ph->memsz; i++) *((char*)ph->vaddr+i) = 0; } } } void (*entry)(void); entry = (void*)elf->entry; entry(); }/* int loader(char* buf){ struct ELFHeader *elf = (void*) buf; struct ProgramHeader *ph,*eph; ph = (void*)elf + elf->phoff; eph = ph + elf->phnum; for(; ph < eph; ph++){ if(ph->type == 1){ //PT_LOAD for(int i=0; i< ph->filesz; i++) *((char*)ph->vaddr+i)=*((char*)ph->off+i); if(ph->filesz < ph->memsz){ for(int i= ph->filesz; i<ph->memsz; i++) *((char*)ph->vaddr+i) = 0; } } } int entry = elf->entry; return entry; }*/ void waitDisk(void) { // waiting for disk while((inByte(0x1F7) & 0xC0) != 0x40); } void readSect(void *dst, int offset) { // reading a sector of disk int i; waitDisk(); outByte(0x1F2, 1); outByte(0x1F3, offset); outByte(0x1F4, offset >> 8); outByte(0x1F5, offset >> 16); outByte(0x1F6, (offset >> 24) | 0xE0); outByte(0x1F7, 0x20); waitDisk(); for (i = 0; i < SECTSIZE / 4; i ++) { ((int *)dst)[i] = inLong(0x1F0); } }
C
/** * @file Joy_state.h * @brief Joystick state operations */ #ifndef JOY_STATE_H #define JOY_STATE_H /** * @brief joystick directions */ typedef enum { LEFT, RIGHT, UP, DOWN, NEUTRAL, } Dir; /** * @brief joystick state */ typedef struct Joy_state { int x; // -100 -> 100 int y; // -100 > 100 Dir dir; } Joy_state; /** * @brief joystick Get joystick states * @param joy_state Struct containing the joystick state * @return x position of the joystick state scaled for use as servo value */ int Joy_state_get_servo_value(Joy_state joy_state); #endif
C
/* union-test3.c -- test copying data into H/EDB's with union Jim Raines, 16Nov99 Result: The union ub2 works fine but writing to edb2.abEDB doesn't seem to read out right from edb2.h.d.X. I think it is an alignment problem in that the union byte2 isn't really only one byte long. */ #include <stdio.h> #define BYTE unsigned char int main(int argc, char *argv[]){ int i,j; struct edbheader { BYTE id0; /* first identifier of E/HDB */ BYTE id1; /* second identifier of E/HDB */ union{ BYTE r; /* raw */ struct bfByte2 { unsigned int numsf : 5; /* bytes 0-4: number of subframes */ unsigned int dbid : 1; /* byte 5: 0 for EDB ; 1 for HDB */ unsigned int sfif : 1; /* byte 6: 0 ==> 37 bytes per subframe; 1 ==> 40 */ unsigned int highbitrate : 1;/* byte 7: 1 ==>high bit rate; 0 ==> low bit rate*/ } d; /* decoded */ } byte2; BYTE filler[797]; }; union{ BYTE abEDB[800]; struct edbheader h; } edb2; edb2.abEDB[0] = 0x14; edb2.abEDB[1] = 0x6f; edb2.abEDB[2] = 104; /* numsf=8, dbid=1,sfif=1,hbr=0*/ for(i=0; i < 3 ; i++) printf("%d ",edb2.abEDB[i]); printf("\n"); printf("byte0 %d byte1 %d byte2 %d %d %d %d\n", edb2.h.id0,edb2.h.id1, edb2.h.byte2.d.numsf,edb2.h.byte2.d.dbid,edb2.h.byte2.d.sfif, edb2.h.byte2.d.highbitrate); /* accessing through nearest union */ edb2.h.byte2.r = 104; /* numsf=8, dbid=1,sfif=1,hbr=0*/ printf("byte0 %d byte1 %d byte2 %d %d %d %d\n", edb2.h.id0,edb2.h.id1, edb2.h.byte2.d.numsf,edb2.h.byte2.d.dbid,edb2.h.byte2.d.sfif, edb2.h.byte2.d.highbitrate); }
C
/** * Polytech Marseille * Case 925 - 163, avenue de Luminy * 13288 Marseille CEDEX 9 * * Ce fichier est l'oeuvre d'eleves de Polytech Marseille. Il ne peut etre * reproduit, utilise ou modifie sans l'avis express de ses auteurs. */ /** * @author GAUDARD Damien <[email protected]> * @author AIT SAID Anaïs <[email protected]> */ /** * Projet algorithmique */ #include "fichier.h" #include <stdio.h> #include <stdlib.h> /*On definit des macros pour recuperer les 8 premiers ou derniers bits d'un entier.*/ #define derniers_bits 255 #define premiers_bits 2147483648 static FILE * fichier_initial = NULL; static FILE * fichier_final = NULL; static tpb buffer = NULL; /*Initialise le buffer. */ void initialisation_buffer() { buffer = (tpb)malloc(sizeof(t_buffer)); buffer->info = 0; buffer->nbr_bits = 0; } /*Ouvre le fichier initial. */ int ouvrir_fichieri(char* nom_fichier_initial) { fichier_initial = fopen(nom_fichier_initial, "rb"); //"rb" signifie qu'on va ouvrir un //fichier binaire en lecture. if (fichier_initial == NULL) return 0; else return 1; } /*Ouvre le fichier final. */ int ouvrir_fichierf(char* nom_fichier_final) { fichier_final = fopen(nom_fichier_final, "wb"); //"wb" signifie qu'on va ouvrir un //fichier binaire en ecriture. if (fichier_final == NULL) return 0; else return 1; } /*Ferme le fichier initial. */ void fermer_fichieri() { fclose(fichier_initial); } /*Ferme le fichier final. */ void fermer_fichierf() { fclose(fichier_final); } /*Recupere et renvoie le prochain caractere du fichier initial. */ unsigned int recup_caractere() { assert(fichier_initial != NULL); return fgetc(fichier_initial); } /*Ecrit un caractere dans le fichier final. */ void ecrire_caractere(int caractere) { assert(fichier_final != NULL); fprintf(fichier_final, "%c", caractere); } /*Recupere et renvoie le code binaire du caractere contenu dans le buffer */ unsigned int recup_cb_caractere() { unsigned int a = 0; /*on recupere les bits du prochain caractere*/ a = recup_caractere(); /*on met les bits dans le buffer*/ buffer->info = (buffer->info) << (TAILLE_CARACTERE); buffer->nbr_bits = buffer->nbr_bits + TAILLE_CARACTERE; buffer->info = (buffer->info) | a; /*on met les 8 premiers bits du buffer dans a*/ a = (buffer->info) >> (buffer->nbr_bits - TAILLE_CARACTERE); a = (a & derniers_bits); /*on reajuste la taille du buffer*/ buffer->nbr_bits = buffer->nbr_bits - TAILLE_CARACTERE; return a; } /*Recupere et renvoie le cobinaire d'une feuille de l'arbre de huffman */ tpb recup_cb_feuille(tpa a) { tpb tmp = NULL; tmp = (tpb)malloc(sizeof(t_buffer)); /*initialisation du temporaire*/ tmp->info = tmp->info & 0; tmp->nbr_bits = 0; /*on parcourt tout l'arbre, donc tant qu'on est pas remonte jusqu'a la racine*/ while(pere(a) != NULL) { if(fils_gauche(pere(a)) == a) { tmp->info = tmp->info >> 1; (tmp->nbr_bits)++; }else{ tmp->info = tmp->info >> 1; tmp->info = tmp->info | premiers_bits; (tmp->nbr_bits)++; } a = pere(a); } /*on decale le temporaire*/ tmp->info = tmp->info >> (32-(tmp->nbr_bits)); return tmp; } /*Ecrit le code binaire d'un caractere dans le buffer. La fonction prend en paramètre *un pointeur sur un buffer contenant le code binaire a ecrire. */ void ecrire_cb(tpb code_binaire) { tpb tmp = NULL; tmp = (tpb)malloc(sizeof(t_buffer)); /*on met dans le buffer les bits de code_binaire*/ buffer->info = (buffer->info) << (code_binaire->nbr_bits); buffer->info = (buffer->info) | (code_binaire->info); buffer->nbr_bits = (buffer->nbr_bits) + (code_binaire->nbr_bits); while(buffer->nbr_bits > TAILLE_CARACTERE) { /*on decale (a droite) vers les 8dernier bits du buffer*/ tmp->info = (buffer->info) >> (buffer->nbr_bits - TAILLE_CARACTERE); ecrire_caractere(tmp->info); /*on remet le buffer a la taille sans le caractere ecrit*/ buffer->nbr_bits = (buffer->nbr_bits) - TAILLE_CARACTERE; } free(tmp); } /*Recuper et renvoie une feuille de l'arbre de huffman en regardant le code binaire *contenu dans le buffer. */ tpa recup_feuille(tpa a) { unsigned int tmp = 0; while(!est_feuille(a)) { if((buffer->nbr_bits) == 0) { tmp = recup_caractere(); buffer->info = (buffer->info) << TAILLE_CARACTERE; buffer->nbr_bits = (buffer->nbr_bits) + TAILLE_CARACTERE; buffer->info = (buffer->info) | tmp; } /*on recupere le dernier bit du buffer*/ tmp = (buffer->info) >> (buffer->nbr_bits - 1); tmp = tmp & (int)1; if(tmp == 1) a = fils_droit(a); else a = fils_gauche(a); (buffer->nbr_bits)--; } return a; } /*Ecrit le caractere contenu dans le buffer dans le fichier final afin de liberer le buffer*/ void libere_buffer() { /*on ecrit le code binaire du caractère de fin de fichier*/ ecrire_cb(recup_cb_feuille(ptr_feuille(A-1))); buffer->info = buffer->info << (TAILLE_CARACTERE - buffer->nbr_bits); /*on ecrit les dernier bits du buffer*/ ecrire_caractere(buffer->info); }
C
/** @file mutex_type.h * @brief This file defines the type for mutexes. */ #ifndef _MUTEX_TYPE_H #define _MUTEX_TYPE_H typedef struct mutex { int valid; int lock; int tid; int count; int count_lock; } mutex_t; #endif /* _MUTEX_TYPE_H */
C
/* ATmega 2560, arduino */ #define F_CPU 16000000 #define LED 5 #include <avr/io.h> #include <util/delay.h> #include <avr/interrupt.h> char timer_count = 0; char max_timer_count = 30; void run_timer() { OCR0A = 0xFF; // 8-bit counter OCR0B = 0x00; TIMSK0 |= (1 << OCIE0A); // compare interrupt TCCR0A = 0x02; // CTC TCCR0B = 0x05; // prescaler 1/1024 timer_count = 0; } char led_state = 0; ISR (TIMER0_COMPA_vect) { ++timer_count; if (timer_count >= max_timer_count) { timer_count = 0; led_state ^= 1; if (led_state) PORTC |= (1 << LED); else PORTC &= ~(1 << LED); } } void init() { // -------------------- external interrupts ------------------------ EIMSK = 0x01; // b 0 0 0 0 0 0 0 1 // 0 0 0 0 0 0 0 - INT7 - INT1 // 1 - Enable INT0 EICRA = 0x02; // b 0 0 0 0 0 0 1 0 // 1 0 - creating interrupt by falling (11111111100000000) // ---------------------- peripheral ------------------------------- DDRC |= (1 << LED); // led out PORTC |= (1 << LED); // enabled as default sei(); } int main() { init(); run_timer(); while (1) { } }
C
#include<stdio.h> int fib(int a) { if (a==0) return 0; if (a==1) return 1; return fib(a-1)+fib(a-2); } void main() { int i,n,s=0; printf("Enter no of elements"); scanf("%d",&n); printf("the series is:: "); for(i=0;i<n;i++) printf("%3d",fib(i)); printf("\n"); }
C
// // exp_mpi.c // // Created by Alina Shipitsyna on 09.04.2020. // Copyright © 2020 Alina Shipitsyna. All rights reserved. // #include "mpi.h" #include <stdio.h> #include <math.h> #include <stdlib.h> /*--------------------------------------------------------------------------------------------------------------------------------------------------------------------*/ long double Fact(long int n){ if (n == 0) return 1; else return n*Fact(n-1); } long int N = 100000; int main(int argc, const char * argv[]) { int myid, nprocs; long int n; double start_time, finish_time; double frac_sum=0; double result=0; int i; MPI_Status status; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); MPI_Comm_rank(MPI_COMM_WORLD, &myid); printf("PROGMPI: nprocs=%d myid=%d\n", nprocs, myid); fflush(stdout); if(myid == 0) start_time = MPI_Wtime(); for (i = myid; i <= N; i += nprocs){ if(i == 0) frac_sum += 1; else frac_sum += 1 / Fact(i); } if (myid == 0){ result = frac_sum; for (i = 1; i < nprocs; i++){ MPI_Recv(&frac_sum, 1, MPI_DOUBLE, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status); result = result + frac_sum; } } else{ MPI_Send(&frac_sum, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD); } if (myid == 0){ printf("Exp = %f \n", (float)result); finish_time = MPI_Wtime(); printf("Time: %f \n", (float)(finish_time - start_time)); } fflush(stdout); MPI_Finalize(); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<arpa/inet.h> void terminateSocket(int sockfd) { close(sockfd); } int * createClientSocket() { int result , sockfd; struct sockaddr_in address; sockfd = socket(AF_INET,SOCK_STREAM,0); address.sin_family = AF_INET ; address.sin_addr.s_addr = inet_addr("10.86.0.132"); address.sin_port = htons(10201); result = connect(sockfd,(struct sockaddr *)&address , sizeof(address)); int res[]={result,sockfd}; int * ptr = res ; return ptr ; } void performClientTask(int sockfd) { int noe = 0 ; printf("How many numbers ?\n"); scanf("%d",&noe); int ch[256]; printf("Enter the numbers\n"); for(int j=0;j<=noe-1;j++) { scanf("%d",&ch[j]); } ch[noe]=-1 ; write(sockfd,ch,256); printf("Sorted array back from server is \n"); while(1) { read(sockfd,ch,sizeof(ch)); for(int i=0;i<=noe-1;i++) { printf("%d ",ch[i]); } printf("\n"); int id ; read(sockfd,id,sizeof(id)); printf("The process id is %d\n",id); bzero(ch,sizeof(ch)); break; } terminateSocket(sockfd); } int main() { while(1) { char c ; printf("c to continue or q to quit\n"); scanf("%c",&c); if(c=='q') { exit(0); } int * res = createClientSocket(); int result = *(res); int sockfd = *(res+1); if(result==-1) { //printf("In"); perror("\nclient error\n"); exit(1); } performClientTask(sockfd); } }
C
/* advance */ #include <ansi.h> #include <attribute.h> inherit F_CLEAN_UP; void create() { seteuid(getuid()); } int add_attribute(object me, string attr, int amount) { if( me->query_point("attribute") < amount ) { write("AݩIƤALkɤHݩʡC\n"); return 1; } if( me->query_attr(attr, 1) + amount > ATTRVAL_MAX ) { write("Aݩ " + attr + " LkɳohAW"+ chinese_number(ATTRVAL_MAX) +"C\n"); return 1; } me->add_point("attribute", -amount); me->set_attr(attr, me->query_attr(attr, 1) + amount); write(HIY"Aݩ " + attr + " " + chinese_number(amount) + "IFI\n"NOR); return 1; } int add_state(object me, string state, int amount) { if( me->query_point("score") < amount ) { write("AIƤALkɤHAC\n"); return 1; } if( me->query_stat_maximum(state) + amount > 9999 ) { write("AA " + state + " LkɳohAWEdEʤEQEC\n"); return 1; } me->add_point("score", -amount); me->advance_stat(state, amount); me->heal_stat(state, amount); write(HIY"AA " + state + " "+ chinese_number(amount) +"IFI\n"NOR); return 1; } int add_skill(object me, string skill, int amount) { int i; if( me->query_point("skill") < amount ) { write("AޯIƤALkɤHޯWC\n"); return 1; } if( me->query_skill_ability(skill) + amount > 10 ) { write("Aޯ " + skill + " LkɳohAޯḬQIC\n"); return 1; } me->add_point("skill", -amount); for(i=1;i<=amount;i++) me->add_skill_ability(skill); write(HIY"Aޯ " + skill + " W" + chinese_number(amount*20) + "ŤFI\n"NOR); return 1; } void add_level(object me) { if( me->query_level() >= CLASS_D(me->query_class())->getMaxLV() ) { write("AŤwgF¾~WFC\n"); return; } if( me->query_point("learn") < CLASS_D(me->query_class())->getLvUpExp(me) ) { write("ADzIƤ " + CLASS_D(me->query_class())->getLvUpExp(me) + " LkɵšC\n"); return; } me->add_point("learn", -CLASS_D(me->query_class())->getLvUpExp(me)); me->add("level",1); CLASS_D(me->query_class())->advance_level(me); RACE_D(me->query_race())->advance_level(me); write(HIY"AŴɦ " + me->query_level() + " šC\n"NOR); } int main(object me, string arg) { int amount; if( !arg ) return notify_fail("AQɤHOH\n"); if( sscanf(arg, "%s for %d", arg, amount) != 2 ) amount = 1; if( amount < 0 ) return notify_fail("AQCHOH\n"); // ɤH if( arg == "level" ) { add_level(me); return 1; } if( arg == "check" ) { if( me->query_level() >= CLASS_D(me->query_class())->getMaxLV() ) return notify_fail("AŤwgF¾~WFC\n"); write("Ŵɦ " + (me->query_level()+1) + " šAݭn " + CLASS_D(me->query_class())->getLvUpExp(me) + " IDzIơC\n"); return 1; } // ɤHݩ if( arg == "str" || arg == "con" || arg == "dex" || arg == "int" ) { add_attribute(me, arg, amount); return 1; } // ɤHA if( arg == "ap" || arg == "hp" || arg == "mp" ) { add_state(me, arg, amount); return 1; } // ɤHޯ if( me->query_skill(arg, 1) ) { add_skill(me, arg, amount); return 1; } write("S " + arg + " oݩʡBAΧޯAALkɥOC\n"); return 1; } int help() { write(@TEXT O榡G advance <ݩʡBAΧޯ> [for <I>] oӫOiHɤHOC ҡG advance level ɤH advance check ˵HɵŻݭnDzI advance str ɤHOqݩ1IAϥΫᦩ@IݩI advance con for 3 ɤHݩ3IAϥΫᦩTIݩI advance dex ɤHӱݩ1IAϥΫᦩ@IݩI advance int for 2 ɤHzݩ2IAϥΫᦩGIݩI advance ap ɤH믫ȪA1IAϥΫᦩ@II advance hp for 50 ɤHOȪA50IAϥΫᦩQII advance mp ɤHdJԪA1IAϥΫᦩ@II advance combat ޯcombat@IAޯW20 advance dodge for 3 ޯdodgeTIAޯW60 TEXT); return 1; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* render.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lshellie <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/22 13:28:43 by lshellie #+# #+# */ /* Updated: 2020/02/29 15:50:00 by lshellie ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/wolf3d.h" void draw(t_wolf3d *wlf, t_ray *ray, int x, double step) { int y; double tex_pos; tex_pos = (ray->start - H / 2.0 + ray->line / 2.0) * step; while (ray->start <= ray->end) { if ((int)tex_pos >= wlf->text[ray->hit].height) y = (int)tex_pos % wlf->text[ray->hit].height - 1; else y = (int)tex_pos; tex_pos += step; wlf->img->data[wlf->x + ray->start * wlf->img->size_line / 4] = wlf->text[ray->hit].buf[x + y * wlf->text[ray->hit].height]; ++ray->start; } } void manage_texture(t_wolf3d *wlf, t_ray *ray) { double wallx; int textx; double step; if (ray->side == 0) wallx = wlf->pos.y + ray->dir.y * ray->dist; else wallx = wlf->pos.x + ray->dir.x * ray->dist; wallx -= floor(wallx); textx = (int)(wallx * wlf->text[ray->hit].width); if (ray->side == 0 && ray->dir.x > 0) textx = wlf->text[ray->hit].width - textx - 1; if (ray->side == 1 && ray->dir.y < 0) textx = wlf->text[ray->hit].width - textx - 1; step = 1.0 * wlf->text[ray->hit].height / ray->line; draw(wlf, ray, textx, step); } void draw_line(t_wolf3d *wlf, t_ray *ray) { if (ray->side == X_SIDE) ray->dist = (ray->map_x - wlf->pos.x + (1.0 - ray->step_x) / 2.0) / ray->dir.x; else ray->dist = (ray->map_y - wlf->pos.y + (1.0 - ray->step_y) / 2.0) / ray->dir.y; ray->line = (int)(H / ray->dist); ray->start = H / 2 - ray->line / 2; ray->end = H / 2 + ray->line / 2; if (ray->start < 0) ray->start = 0; if (ray->end >= H) ray->end = H - 1; manage_texture(wlf, ray); } void get_hit(t_wolf3d *wlf, t_ray *ray, t_vect2d side) { while (ray->hit == 0 && ray->map_x > 0 && ray->map_x < wlf->map.width - 1 && ray->map_y > 0 && ray->map_y < wlf->map.heigth - 1) { if (side.x < side.y) { side.x += ray->delta_x; ray->side = X_SIDE; ray->map_x += ray->step_x; } else { side.y += ray->delta_y; ray->side = Y_SIDE; ray->map_y += ray->step_y; } ray->hit = wlf->map.map[ray->map_y][ray->map_x]; } } void cast_ray(t_wolf3d *wlf, t_ray *ray) { t_vect2d side; side.x = ray->dir.x >= 0 ? (1.0 - wlf->pos.x + ray->map_x) * ray->delta_x : (wlf->pos.x - ray->map_x) * ray->delta_x; side.y = ray->dir.y >= 0 ? (1.0 - wlf->pos.y + ray->map_y) * ray->delta_y : (wlf->pos.y - ray->map_y) * ray->delta_y; ray->step_x = ray->dir.x >= 0 ? 1 : -1; ray->step_y = ray->dir.y >= 0 ? 1 : -1; get_hit(wlf, ray, side); if (ray->hit <= 0) return ; ray->hit = get_texture_id(ray->hit, ray->side, ray->step_x, ray->step_y); draw_line(wlf, ray); }
C
#include <sys/ioctl.h> #include <time.h> #include <assert.h> #include <errno.h> #include <math.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <ncurses.h> #define FPS 20 #define PROB_IGNITION 0.001 /* f */ #define PROB_GROWTH 0.025 /* p */ #define CMD_BUF_SIZE 50 #define die(...) do {fprintf(stderr, __VA_ARGS__); exit(EXIT_FAILURE);} while (0) struct offset { int row; int col; }; static const struct offset offsets[] = { {-1, -1}, {-1, 0}, {-1, 1}, { 0, -1}, { 0, 1}, { 1, -1}, { 1, 0}, { 1, 1}, }; enum state { EMPTY, TREE, BURN, }; struct Cell { enum state state; }; typedef struct World World; struct World { unsigned int id; unsigned int gen; unsigned int rows; unsigned int cols; float f; float p; struct Cell **grid; World *next; World *prev; }; static const unsigned int n_neighbors = sizeof(offsets) / sizeof(struct offset); static struct timespec timespec_of_float(const double n) { double integral; double fractional; struct timespec t; fractional = modf(n, &integral); t.tv_sec = (int) integral; t.tv_nsec = (int) (1E9 * fractional); return t; } static int is_probable(const float probability) { return probability >= drand48(); } static World * world_create( const unsigned int gen, const unsigned int rows, const unsigned int cols, const float f, const float p ) { /* * IDs help us spot ancestry bugs, like a missing next/prev pointer. */ static unsigned int id = 0; World *w; unsigned int r; unsigned int k; w = calloc(1, sizeof(World)); w->id = id++; w->gen = gen; w->rows = rows; w->cols = cols; w->f = f; w->p = p; w->grid = calloc(rows, sizeof(struct Cell*)); w->next = NULL; w->prev = NULL; for (r = 0; r < w->rows; r++) w->grid[r] = calloc(cols, sizeof(struct Cell)); for (r = 0; r < w->rows; r++) for (k = 0; k < w->cols; k++) w->grid[r][k].state = EMPTY; return w; } static void world_init(World *w) { unsigned int r; unsigned int k; for (r = 0; r < w->rows; r++) for (k = 0; k < w->cols; k++) w->grid[r][k].state = is_probable(w->p) ? TREE : EMPTY; } static void world_print(const World *w, const unsigned int playing) { unsigned int r; unsigned int k; enum state s; int ci; /* COLOR_PAIR index */ for (k = 0; k < w->cols; k++) mvprintw(0, k, " "); mvprintw( 0, 0, "%s | gen: %d | id: %d | p: %.3f | f: %.3f | p/f: %3.f | FPS: %d", (playing ? ">" : "="), w->gen, w->id, w->p, w->f, (w->p / w->f), FPS ); for (r = 0; r < w->rows; r++) { for (k = 0; k < w->cols; k++) { s = w->grid[r][k].state; ci = s + 1; if (s == BURN) attron(A_BOLD); attron(COLOR_PAIR(ci)); mvprintw(r + 1, k, " "); attroff(COLOR_PAIR(ci)); if (s == BURN) attroff(A_BOLD); } } refresh(); } static unsigned int world_pos_is_inbounds(World *w, unsigned int row, unsigned int col) { return row < w->rows && col < w->cols; } static World * world_next(World *w0) { unsigned int r; unsigned int k; unsigned int o; /* offset index */ unsigned int nr; /* neighbor's row */ unsigned int nk; /* neighbor's col */ unsigned int n; /* neighbors burning */ enum state s0; enum state s1; struct offset off; World *w1 = w0->next; if (w1) return w1; w1 = world_create(w0->gen + 1, w0->rows, w0->cols, w0->f, w0->p); w1->prev = w0; w0->next = w1; for (r = 0; r < w0->rows; r++) for (k = 0; k < w0->cols; k++) { s0 = w0->grid[r][k].state; n = 0; for (o = 0; o < n_neighbors; o++) { off = offsets[o]; nr = r + off.row; nk = k + off.col; if (world_pos_is_inbounds(w0, nr, nk)) if (w0->grid[nr][nk].state == BURN) n++; } switch (s0) { case BURN: s1 = EMPTY; break; case TREE: if (n > 0) { s1 = BURN; break; } if (is_probable(w0->f)) { s1 = BURN; break; } s1 = TREE; break; case EMPTY: if (is_probable(w0->p)) { s1 = TREE; break; } s1 = EMPTY; break; default: assert(0); } w1->grid[r][k].state = s1; } return w1; } static void world_destroy_future(World *w) { /* * After changing a world parameter, we must remove at least its * consequent, child worlds, since they are no longer valid under the * new parameters and must be re-computed. * * TODO: Should the current world be re-computed as well? * TODO: Perhaps world_next should take these parameters instead of this function? * TODO: Recompute if params are diff from parent? */ World *cur; World *tmp; for (cur = w->next; cur != NULL; ) { tmp = cur->next; free(cur); cur = tmp; } w->next = NULL; } int main() { int control_timeout = -1; int playing = 0; const struct timespec interval = timespec_of_float(1.0 / FPS); const struct winsize winsize; char cmd[CMD_BUF_SIZE]; World *w; float tmp_p; float tmp_f; srand48(time(NULL)); if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize) < 0) die("ioctl: errno = %d, msg = %s\n", errno, strerror(errno)); w = world_create( 0, winsize.ws_row - 1, /* Leave room for the status line. */ winsize.ws_col, PROB_IGNITION, PROB_GROWTH ); world_init(w); memset(cmd, '\0', CMD_BUF_SIZE); initscr(); noecho(); start_color(); init_pair(EMPTY + 1, COLOR_BLACK, COLOR_BLACK); init_pair(TREE + 1, COLOR_GREEN, COLOR_GREEN); init_pair(BURN + 1, COLOR_RED , COLOR_RED); control_timeout = -1; for (;;) { world_print(w, playing); control: timeout(control_timeout); switch (getch()) { case 'p': if (playing) { control_timeout = -1; playing = 0; } else { control_timeout = 0; playing = 1; } goto forward; case 'f': goto forward; case 'b': goto back; case 's': goto stop; case ':': goto command; default: if (playing) goto forward; else goto control; } command: timeout(-1); mvprintw(winsize.ws_row - 1, 0, ":"); refresh(); echo(); mvgetstr(winsize.ws_row - 1, 1, cmd); if (sscanf(cmd, "f %f", &tmp_f) == 1) { w->f = tmp_f; world_destroy_future(w); } else if (sscanf(cmd, "p %f", &tmp_p) == 1) { w->p = tmp_p; world_destroy_future(w); } memset(cmd, '\0', CMD_BUF_SIZE); noecho(); timeout(control_timeout); forward: w = world_next(w); goto delay; back: if(w->prev) w = w->prev; goto delay; delay: if (nanosleep(&interval, NULL) < 0 && errno != EINTR) die("nanosleep: %s", strerror(errno)); } stop: endwin(); return 0; }
C
// To calculate successive fibonacci number #include<stdio.h> long int fibonacci(int count); int main() { int count; auto n; printf("How many fibonacci numbers?="); scanf("%d",&n); printf("\n"); for(count=1;count<=n;++count) printf("\n i=%2d\tF=%ld",count ,fibonacci(count)); getch(); } long int fibonacci(int count) { static long int f1=1, f2=1, f; //use of static variables f=(count<3)?1:f1+f2; f2=f1; f1=f; return (f); }
C
// When a button is pressed, change the speed of an LED blink from 100ms to 1000ms. #include <avr/io.h> // Include neccesary libraries #include <util/delay.h> int main(void) // Main function { DDRB |= 1 << PINB0; // Data Direction Register for PortB; sets Pin0 (LED) output DDRB &= ~(1 << PINB1); // Data Direction Register for PortB; sets Pin1 (button) to input PORTB |= 1 << PINB1; // Sets Pin1 to high (5v) since it is reading while (1) { PORTB ^= 1 << PINB0; // XOR gate to toggle between setting Pin0 to high and low if (bit_is_clear(PINB, 1)) // If the button is pressed (pin0 switches to 0v) { _delay_ms(100); // Delay of 0.1 second per toggle } else { _delay_ms(1000); // Delay of 1 second per toggle } } }
C
#include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/wait.h> #include <arpa/inet.h> #include <netinet/in.h> #include <netdb.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <errno.h> #define PATH_MAX 0x100 #define REQUEST_MAX 0x100 #define RESPONSE_TEMPLATE(body) \ "<!DOCTYPE html>\n" \ "<html>\n" \ " <head>\n" \ " <meta charset=\"utf-8\">\n" \ " </head>\n" \ " <body>\n" \ " <p>"body"</p>\n" \ " </body>\n" \ "</html>\n" /** * Utility */ void recvline(int fd, char *buf, int size) { char c; memset(buf, 0, size); for (int i = 0; i != size; i++) { if (read(fd, &c, 1) <= 0) exit(1); if (c == '\r') { if (read(fd, &c, 1) <= 0) exit(1); if (c == '\n') { break; } else { buf[i] = '\r'; buf[++i] = c; } } else { buf[i] = c; } } } void http_response(int fd, char *status, char *content, int length) { if (length < 0) length = strlen(content); dprintf(fd, "HTTP/1.1 %s\r\n", status); dprintf(fd, "Content-Length: %d\r\n", length); dprintf(fd, "Connection: close\r\n"); dprintf(fd, "Content-Type: text/html; charset=UTF-8\r\n\r\n"); write(fd, content, length); } /** * HTTP server */ void http_saba(int sock) { char *p; char path[PATH_MAX]; char request[REQUEST_MAX+1]; struct stat st; /* Receive request header */ recvline(sock, request, REQUEST_MAX); /* Check request method */ p = strtok(request, " "); if (memcmp(p, "GET", 3) != 0) { http_response(sock, "405 Method Not Allowed", RESPONSE_TEMPLATE("404 Method Not Allowed 🙅‍️"), -1); return; } /* Check path */ p = strtok(NULL, " "); if (p[0] != '/') { http_response(sock, "400 Bad Request", RESPONSE_TEMPLATE("400 Bad Request 🤮"), -1); return; } if (strstr(p, "..")) { http_response(sock, "451 Unavailable For Legal Reasons", RESPONSE_TEMPLATE("451 Hacking Attempt 👮"), -1); return; } /* Check file */ strcpy(path, "./html"); if (p[1] == '\0') strncat(path, "/index.html", PATH_MAX-1); else strncat(path, p, PATH_MAX-1); if (stat(path, &st) != 0) { http_response(sock, "404 Not Found", RESPONSE_TEMPLATE("404 Not Found 🔍"), -1); return; } /* Read file */ char *content = calloc(sizeof(char), st.st_size); if (content == NULL) { http_response(sock, "500 Internal Server Error", RESPONSE_TEMPLATE("500 Internal Server Error 😇"), -1); return; } int fd = open(path, O_RDONLY); if (fd < 0) { free(content); http_response(sock, "500 Internal Server Error", RESPONSE_TEMPLATE("500 Internal Server Error 😇"), -1); return; } read(fd, content, st.st_size); /* Make response */ http_response(sock, "200 OK", content, st.st_size); free(content); } /** * Entry point */ int main() { int sockfd, yes=1; struct sockaddr_in server_addr; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); exit(1); } memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_port = htons(9080); if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&yes, sizeof(yes)) < 0) { perror("setsockopt"); exit(1); } if (bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) { perror("bind"); close(sockfd); exit(1); } if (listen(sockfd, 10)) { perror("listen"); close(sockfd); exit(1); } while (1) { int fd, client_len, pid, cpid, status; struct sockaddr_in client_addr; client_len = sizeof(client_addr); if ((fd = accept(sockfd, (struct sockaddr*)&client_addr, &client_len)) < 0) { perror("accept"); exit(1); } pid = fork(); if (pid == -1) { perror("fork"); exit(1); } else if (pid == 0) { /* HTTP server */ alarm(30); http_saba(fd); exit(0); } else { while ((cpid = waitpid(-1, &status, WNOHANG)) > 0); if (cpid < 0 && errno != ECHILD) { perror("waitpid"); exit(1); } } close(fd); } }
C
#include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> int main(int ac, char *av[]){ int sock; // descriptor del socket struct sockaddr_in dest; // direccion del destinatario unsigned int dest_len; // tamanio de la estructura de direccion struct hostent *hp; // host entity information (datos del host donde estoy corriendo) int nb; // cantidad de bytes transmitidos o recibidos char buf[512]; // buffer de recepcion // verifica los argumentos de la linea de comandos if(ac != 4){ printf("invocar %s <ip_o_nombre_servidor> <puerto_servidor> <mensaje>\n", av[0]); return -1; } // crea un socket del tipo datagaram (UDP) en el dominio INET (internet) sock = socket(AF_INET, SOCK_DGRAM, 0); if(sock < 0){ perror(strerror(errno)); return -1; } // inicializa la direccion dest.sin_family = AF_INET; dest.sin_port = htons(atoi(av[2])); // busca la direccion del servidor hp = gethostbyname(av[1]); if(!hp){ perror(strerror(errno)); return -1; } // copia la direccion IP memcpy(&dest.sin_addr, hp->h_addr, hp->h_length); // transmite el mensaje nb = sendto(sock, av[3], strlen(av[3])+1, 0, (struct sockaddr*)&dest, sizeof(dest)); printf("sendto: (%s) [%d bytes]\n", av[3], nb); // recibe el eco dest_len = sizeof(dest); nb = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr*)&dest, &dest_len); buf[nb] = '\0'; printf("data: (%s) [%d bytes]\n", buf, nb); // cierra el socket close(sock); return 0; }
C
/*Вычислить значение функции D=(e^(-1/6)*√(a^2+ln⁡|b| )-tga)/(〖2cos〗^2 a^3 )*/ #include <stdio.h> #include <math.h> #include <locale.h> /*библиотека языков*/ int main() { setlocale(LC_ALL, "Rus");/*подключение русского языка*/ double a , b , D, k, z; do { printf("a="); fflush(stdin); } while (scanf("%lf" , &a) != 1); /*безопасный ввод*/ do { printf("b="); fflush(stdin); } while (scanf("%lf" , &b) != 1); /*безопасный ввод*/ k = sqrt(pow(a, 2)+logf(fabs(b))); /*вспомогательная переменная*/ z = 2*pow(cos(pow(a, 3)), 2); /*вспомогательная переменная*/ if(a>=0 && z != 0 && b != 0){ /*проверка на ООФ*/ D = ((exp(-1/6)*k-tan(a)*pow(10,6))/z); /*вычисление D*/ printf("D=%lf", D); } else printf("Не принадлежит ОДЗ"); /*сообщение*/ return 0; }
C
#ifndef COREATOMIC_H #define COREATOMIC_H /** @return whether the alignedDatum FAILED to increment. * The most common reason for a failure would be that an interrupt occurred during the operation. If you are sure the cause of failure isn't permanent then: do{}while(atomic_increment(arg)); */ extern "C" bool atomic_increment(unsigned &alignedDatum); /** @return whether the alignedDatum FAILED to decrement */ extern "C" bool atomic_decrement(unsigned &alignedDatum); /** @return whether the following logic succeeded, not whether it actually decremented: if datum is not zero decrement it */ extern "C" bool atomic_decrementNotZero(unsigned &alignedDatum); /** @return whether the following logic succeeded, not whether it actually incremented: if datum is not all ones then increment it */ extern "C" bool atomic_incrementNotMax(unsigned &alignedDatum); /** @returns 1 if the value was zero in which case it is still 0, else blocks until decrement and returns 0 (regardless of decremented value) */ extern "C" bool atomic_decrementNowZero(unsigned &alignedDatum); /** @returns whether the value was zero before increment, if datum is all ones then left all ones. */ extern "C" bool atomic_incrementWasZero(unsigned &alignedDatum); /** @return whether the following logic succeeded, if datum IS zero then replace it with given value */ extern "C" bool atomic_setIfZero(unsigned &alignedDatum,unsigned value); //to keep the pretty printer from expanding the do{} to multiple lines: #define BLOCK do{} #endif // COREATOMIC_H
C
//square of number using function #include<stdio.h> int squarenum(int a);//function prototype declaration int main() { int a,s; printf("enter the number:"); scanf("%d",&a); s=squarenum(a);//function call printf("s=%d\n",s); return 0; } int squarenum(int a)//function definition { int s; s=a*a; return(s); }
C
int main() { int n; scanf("%d",&n); int k=1,sum=0; while(k<=n) { sum+=k; k++; if(sum==n) { printf("YES"); return 0; } } printf("NO"); return 0; }
C
#define NOCCARGC /* no argument count passing */ extern char *Umemptr; /* ** Return the number of bytes of available memory. ** In case of a stack overflow condition, if 'abort' ** is non-zero the program aborts with an 'S' clue, ** otherwise zero is returned. */ avail(abort) int abort; { char x; if(&x < Umemptr) { if(abort) exit('M'); return (0); } return (&x - Umemptr); }
C
#include "holberton.h" /** * *_strcpy - counting the length of a string *@dest: value waited from the main.c *@src: root * Return: Always 0. */ char *_strcpy(char *dest, char *src) { int c; for (c = 0; src[c]; c++) { dest[c] = src[c]; } dest[c] = '\0'; return (dest); }