language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include<stdio.h> #include<stdlib.h> void quicksort(long signed int a[],long signed int l,long signed int r) { if(r>l){ long signed int i, j, v, t; v = a[r]; i = l-1; j = r; for(;;) { while (a[++i] < v); while (a[--j] > v); if(i >= j) break; t = a[i]; a[i] = a[j]; a[j] = t; } t = a[i]; a[i] = a[r]; a[r] = t; quicksort(a, l, i - 1); quicksort(a, i + 1, r); } return; } int main(){ long int i,b,g,j,t,m,r,k,d; scanf("%d",&t); long signed int B[100],G[100],R[100],sumr,sumg,sumb; for(i=0;i<t;i++){ scanf("%d%d%d%d",&r,&g,&b,&m); for(j=0;j<r;j++) scanf("%d",&R[j]); for(j=0;j<g;j++) scanf("%d",&G[j]); for(j=0;j<b;j++) scanf("%d",&B[j]); quicksort(R,0,r); quicksort(G,0,g); quicksort(B,0,b); sumr=sumg=sumb=0; for(j=1;j<=m;j++){ for(k=0;k<r;k++){ sumr=sumr+R[k]; } for(k=0;k<g;k++){ sumg=sumg+G[k]; } for(k=0;k<b;k++){ sumb=sumb+B[k]; } if(R[r-1]>=G[g-1]&&R[r-1]>B[b-1]) { if(R[r-1]==G[g-1]){ if(sumr>sumg) {for(k=0;k<r;k++) R[k]=R[k]/2; } else for(k=0;k<g;k++) G[k]=G[k]/2; } else for(k=0;k<r;k++) R[k]=R[k]/2; } else if(G[g-1]>R[r-1]&&G[g-1]>=B[b-1]) { if(G[g-1]==B[b-1]){ if(sumg>sumb) {for(k=0;k<g;k++) G[k]=G[k]/2; } else for(k=0;k<b;k++) B[k]=B[k]/2; } else for(k=0;k<g;k++) G[k]=G[k]/2; } else if(B[b-1]>=R[r-1]&&B[b-1]>G[g-1]) { if(B[b-1]==R[r-1]){ if(sumb>sumr) {for(k=0;k<b;k++) B[k]=B[k]/2; } else for(k=0;k<r;k++) R[k]=R[k]/2; } else for(k=0;k<b;k++) B[k]=B[k]/2; } else if(R[r-1]==G[g-1]==B[b-1]){ if(sumr>=sumg&&sumr>sumb) {for(k=0;k<r;k++) R[k]=R[k]/2; } else if(sumg>sumr&&sumg>=sumb){ for(k=0;k<g;k++) G[k]=G[k]/2; } else if(sumb>=sumr&&sumb>sumg) {for(k=0;k<b;k++) B[k]=B[k]/2; } else for(k=0;k<r;k++) R[k]=R[k]/2; } } if(R[r-1]>=G[g-1]&&R[r-1]>B[b-1]) { d=R[r-1]; } else if(G[g-1]>R[r-1]&&G[g-1]>=B[b-1]) { d=G[g-1]; } else if(B[b-1]>=R[r-1]&&B[b-1]>G[g-1]) { d=B[b-1]; } printf("%d\n",d); } return 0; }
C
#include <lcom/lcf.h> #include <stdint.h> #include <stdio.h> #include "macro_mouse.h" #include "keyboard.h" #include "macro.h" #include "mouse.h" int bit_id_mouse = 12; int ih_mouse_fail; //checks if interrupt handler function was called properly uint8_t read_byte; //byte read during interrupts int (mouse_subscribe_int)(uint8_t *bit_no) { //bit_no is preserved bit_id_mouse = (int) *bit_no; return (sys_irqsetpolicy(MOUSE_IRQ, IRQ_REENABLE | IRQ_EXCLUSIVE, &bit_id_mouse)); } int (mouse_unsubscribe_int)() { return sys_irqrmpolicy(&bit_id_mouse); } void (mouse_ih)(){ uint8_t stat; //status register while( 1 ) { if (util_sys_inb(STAT_REG, &stat)){ih_mouse_fail = 1; break;} //gets status register value if( stat & OBF ) { //checks if output buffer is set if (((stat &(PAR_ERR | TO_ERR )) == 0)) { //Parity, Time Out and Mouse errors check if(util_sys_inb(OUT_BUF, &read_byte)) ih_mouse_fail = 1; //Reads byte value else ih_mouse_fail = 0; break; } else ih_mouse_fail = 1; break; } } } void set_struct(uint8_t array[], struct packet *pp){ //set bytes pp->bytes[0] = array[0]; pp->bytes[1] = array[1]; pp->bytes[2] = array[2]; //set delta variables if (array[0] & X_SIGN) pp->delta_x = array[1] - NEG_TO_POS; //x has negative sign else pp->delta_x = array[1]; //x has postive sign; if (array[0] & Y_SIGN) pp->delta_y = array[2] - NEG_TO_POS; //y has negative sign else pp->delta_y = array[2]; //y has positive sign //set first byte components pp->lb = array[0] & LB; pp->rb = (array[0] & RB); pp->mb = (array[0] & MB); pp->x_ov = (array[0] & X_OVFL); pp->y_ov = (array[0] & Y_OVFL); } int send_command(uint8_t port, uint8_t command){ uint8_t stat; //status register while( 1 ) { if (util_sys_inb(STAT_REG, &stat)) return 1; /*assuming it returns OK*/ /*loop while 8042 input buffer is not empty*/ if( (stat & IBF) == 0 ) { sys_outb(port, command); //sends read command to port 0x64 return 0; } else return 1; } } int receive_command(uint8_t* command){ uint8_t stat; //status register while( 1 ) { if (util_sys_inb(STAT_REG, &stat)) return 1; //gets status register value if( (stat & OBF)) { //checks if output buffer is set if (((stat & (PAR_ERR | TO_ERR)) == 0)) { //Parity and Time Out errors check if(util_sys_inb(OUT_BUF, command)) return 1; //reads command byte from port 0x60 return 0; } else return 1; } } return 0; } int mouse_command(uint8_t cmd){ while (1){ //sends 0xD4 to CTRL if (send_command(KBC_CMD_REG, WRT_BYTE_MOUSE)) return 1; //CMD to INB if (send_command(IN_BUF, cmd)) return 1; //receives ACK uint8_t received = 1; if (receive_command(&received)) return 1; if (received == NACK || received == ERROR) return 1; else if (received == ACK) return 0; //received está sempre a 0 } return 0; } int disable_mouse(){ uint8_t cmd = 1; if (send_command(KBC_CMD_REG, READ_COMMAND)) return 1; //enables reading if (receive_command(&cmd)) return 1; //receives KBC command byte cmd = cmd | MOU_DIS; //disables mouse if (send_command(KBC_CMD_REG, WRITE_COMMAND)) return 1; if (send_command(OUT_BUF, cmd)) return 1; //writes new KBC command byte return 0; } int enable_mouse_kbc(){ if (send_command(KBC_CMD_REG, WRITE_COMMAND)) return 1; if (send_command(OUT_BUF, minix_get_dflt_kbc_cmd_byte())) return 1; //writes new KBC command byte return 0; } int mouse_poll(uint16_t period, uint8_t cnt) { struct packet pp; uint8_t stat = 0; uint8_t packet[3]; //saves bytes read from interrupt calls int counter = 0; //keeps track of interrupt calls uint8_t packets_cnt = 0; bool check_read = false; while( packets_cnt < cnt ) { if (counter == 0 && !check_read) mouse_command(READ_DATA); if (util_sys_inb(STAT_REG, &stat))return 1; //gets status register value if( stat & OBF ) { //checks if output buffer is set if (((stat &(PAR_ERR | TO_ERR )) == 0)) { //Parity, Time Out and Mouse errors check if(util_sys_inb(OUT_BUF, &read_byte)) return 1; //Reads byte value check_read = true; } else return 1; } else{ tickdelay(micros_to_ticks(period)); continue; } if (!check_read) break; //checks if anything was received //checks if read_byte is the first byte of the packet if (counter == 0){ if (!(read_byte & FIRST_BYTE)) break; } packet[counter] = read_byte; counter++; if(counter == 3){ set_struct(packet, &pp); mouse_print_packet(&pp); counter = 0; check_read = false; packets_cnt++; } tickdelay(micros_to_ticks(period)); } return 0; } // - DFA - \\// int x_length = 0, y_length = 0; bool drawing_first = false,first_line_done = false,drawing_second = false; void RESET_LEN(){ x_length = 0; y_length = 0; } bool event_state_processing(struct packet *pp,uint8_t x_len,uint8_t tolerance){ enum EVENT event; static enum STATE state = Start; //Which event? - Defines the event that occurred if (pp->lb && !pp->rb && !pp->mb){ //only the left button on event = LeftDown; drawing_first = true; } else if (!pp->lb && !pp->rb && !pp->mb && drawing_first){ //Left button released event = LeftUp; drawing_first = false; } else if (!pp->lb && pp->rb && !pp->mb){ //only the right button on event = RightDown; if(first_line_done) drawing_second = true; } else if (pp->lb && !pp->rb && !pp->mb && drawing_second ){ //Left button released event = RightUp; drawing_second = false; } else if(!(!pp->lb && !pp->rb && !pp->mb)) event = WrongKey; //(pp->delta_y <= pp->delta_x) state = Start; switch(state){ case Start: printf("Start \n"); RESET_LEN(); if(event == LeftDown) state = Line1; break; case Line1: printf("Line1 \n"); if(event == LeftDown){ if((pp->delta_x < 0 && abs(pp->delta_x) > tolerance )||(pp->delta_y < 0 && abs(pp->delta_y) > tolerance)){ state = Start; } else { printf("ajncka \n"); printf("y_length: %d \n", y_length); printf("x_lenght: %d \n", x_length); if(y_length < x_length) { printf("wrong slope \n"); state = Start; } else { printf("GOT IN INCREMENT \n"); x_length += pp->delta_x; y_length += pp->delta_y; } } } else if(event == LeftUp) { printf("GOT IN \n"); printf("x: %d \n", x_length); printf("y: %d \n", y_length); printf("x > x_len: %d \n", x_length >= x_len); printf("slope: %d \n", y_length > x_length); if((x_length >= x_len && (y_length > x_length)) && (abs(pp->delta_x) <= tolerance && abs(pp->delta_y) <= tolerance )){ state = Vertex; first_line_done = true; } else state = Start; } else state = Start; //back to the Start state break; case Vertex: printf("Vertex \n"); if(event == RightDown){ state = Line2; RESET_LEN(); } else if(event == LeftDown || event == WrongKey) state = Start; break; case Line2: printf("Line2 \n"); if(event == RightDown){ if( abs(pp->delta_x) <= tolerance && abs(pp->delta_y) <= tolerance){ printf("x: %d \n", pp->delta_x); printf("y: %d \n", pp->delta_y); if (abs(pp->delta_y) <= pp->delta_x) state = Start; //Check slope for each packet x_length += pp->delta_x; } else state = Start; } else if(event == RightUp){ if((x_length >= x_len && abs(pp->delta_y) > pp->delta_x) && (abs(pp->delta_x) <= tolerance && abs(pp->delta_y) <= tolerance )){ return true; } else state = Start; } else state = Start; break; default: break; } return false; }
C
#include "buffers.h" #include "window.h" #include "vector.h" #include "app.h" #include "scene.h" #include <stdio.h> float color_buffer[MAX_WIN_H][MAX_WIN_W][4]; float depth_buffer[MAX_WIN_H][MAX_WIN_W]; int stencil_buffer[MAX_WIN_H][MAX_WIN_W]; POINT g_buffer[MAX_WIN_H][MAX_WIN_W]; float shadow_buffer[MAX_WIN_H][MAX_WIN_W]; /****************************************************************************/ /* clear functions */ /****************************************************************************/ /* clear color buffer with clear color (r, g, b, a) */ void clear_color_buffer (float r, float g, float b, float a) { for(int row = 0; row < window_height; row++) { for(int col = 0; col < window_width; col++) { color_buffer[row][col][R] = r; color_buffer[row][col][G] = g; color_buffer[row][col][B] = b; color_buffer[row][col][A] = a; } } } /* clear depth buffer by setting each pixel's depth to value */ void clear_depth_buffer (float value) { for(int row = 0; row < window_height; row++) { for(int col = 0; col < window_width; col++) { depth_buffer[row][col] = value; } } } /* clear every point in g buffer to r, g, b, a; and reset rendered_flag */ void clear_g_buffer(float r, float g, float b, float a) { for(int r = 0; r < window_height; r++) { for(int c = 0; c < window_width; c++) { set_vec4(g_buffer[r][c].color, r, g, b, a); g_buffer[r][c].rendered_flag = 0; } } } /* clear stencil buffer to -1 (invalid objectID) */ void clear_stencil_buffer(void) { for(int r = 0; r < window_height; r++) { for(int c = 0; c < window_width; c++) { stencil_buffer[r][c] = -1; } } } /****************************************************************************/ /* draw functions */ /****************************************************************************/ /* draw color buffer to screen using OpenGL */ void draw_color_buffer (void) { glBegin(GL_POINTS); for(int y = - window_height / 2; y < window_height / 2; y++) { for(int x = - window_width / 2; x < window_width / 2; x++) { int r = (int) (y + window_height / 2); int c = (int) (x + window_width / 2); glColor4f(color_buffer[r][c][R], color_buffer[r][c][G], color_buffer[r][c][B], color_buffer[r][c][A]); glVertex2f(x, y); } } glEnd(); } /* draw depth buffer to screen using OpenGL */ void draw_depth_buffer (void) { glBegin(GL_POINTS); for(int y = 0; y < window_height; y++) { for(int x = 0; x < window_width; x++) { glColor4f(depth_buffer[y][x], depth_buffer[y][x], depth_buffer[y][x], 1); glVertex2f(x - window_width / 2, y - window_height / 2); } } glEnd(); } /* for each px in g buffer, if wasn't rendered to, copy g buffer color to color buffer. else, perform lighting + other calculations */ void draw_g_buffer(void) { int save_deferred = current_rs.render_mode; current_rs.render_mode = 0; for(int r = 0; r < window_height; r++) { for(int c = 0; c < window_width; c++) { if(g_buffer[r][c].rendered_flag == 0) { cpy_vec4(color_buffer[r][c], g_buffer[r][c].color); } else { draw_point(&g_buffer[r][c]); } } } current_rs.render_mode = save_deferred; } /* draw stencil buffer in grayscale */ void draw_stencil_buffer(void) { glBegin(GL_POINTS); for(int y = 0; y < window_height; y++) { for(int x = 0; x < window_width; x++) { glColor4f((1 + stencil_buffer[y][x]) / (float) num_objects, (1 + stencil_buffer[y][x]) / (float) num_objects, (1 + stencil_buffer[y][x]) / (float) num_objects, 1); glVertex2f(x - window_width / 2, y - window_height / 2); } } glEnd(); } void copy_depth_to_shadow_buffer(void) { for(int r = 0; r < window_height; r++) { for(int c = 0; c < window_width; c++) { shadow_buffer[r][c] = depth_buffer[r][c]; } } } /* draw shadow buffer to screen using OpenGL */ void draw_shadow_buffer (void) { glBegin(GL_POINTS); for(int y = 0; y < window_height; y++) { for(int x = 0; x < window_width; x++) { glColor4f(shadow_buffer[y][x], shadow_buffer[y][x], shadow_buffer[y][x], 1); glVertex2f(x - window_width / 2, y - window_height / 2); } } glEnd(); }
C
#ifndef VECTOR_H #define VECTOR_H /* Initial vector capacity */ #define VECTOR_INIT_CAPACITY 10 struct vector { void **items; /* The internal array of the vector */ int capacity; /* The amount of elements the vector can currently keep track of */ int size; /* The current number of elements in the vector */ }; /* TODO move to separate file */ typedef struct vector vector; /* Grab the pointer to an allocated vector */ vector *vector_new(); // Dynamic allocation is needed for this data structure /* Dispose of a vector */ void vector_delete(vector *); /* Get the number of components in a vector */ int vector_size(vector *); /* Grab a pointer to the element in the vector with index i */ void *vector_get(vector *, int); /* Boolean if the vector contains no element */ int vector_empty(vector *); /* Resize the vector to a certain capacity */ void vector_resize(vector *, int); /* Push an element into the end of a vector */ void vector_add(vector *, void *); /* Set the element at index i */ void vector_set(vector *, int, void *); /* Remove the element at index i from the vector */ void vector_rm(vector *, int); #endif
C
#ifndef __VOTING_COORDINATOR_H__ #define __VOTING_COORDINATOR_H__ #include <stdio.h> #include <electionguard/voting/messages.h> #include <electionguard/voting/tracker.h> // @todo jwaksbaum What sort of assurances do we make about the // machine being shut off? How does it persist votes? typedef struct Voting_Coordinator_s *Voting_Coordinator; enum Voting_Coordinator_status { VOTING_COORDINATOR_SUCCESS, VOTING_COORDINATOR_INSUFFICIENT_MEMORY, VOTING_COORDINATOR_INVALID_BALLOT_ID, VOTING_COORDINATOR_INVALID_BALLOT, VOTING_COORDINATOR_UNREGISTERED_BALLOT, VOTING_COORDINATOR_DUPLICATE_BALLOT, VOTING_COORDINATOR_TIMED_OUT_BALLOT, VOTING_COORDINATOR_IO_ERROR, VOTING_COORDINATOR_SERIALIZE_ERROR, VOTING_COORDINATOR_DESERIALIZE_ERROR, }; /************************** INITIALIZATION & FREEING ***************************/ // @todo jwaksbaum Do we want to take in information about the ballot // formats so that we can validate that the ballots we receive are // well-formed? /** Create a new voting coordinator. */ struct Voting_Coordinator_new_r Voting_Coordinator_new(uint32_t num_selections); struct Voting_Coordinator_new_r { enum Voting_Coordinator_status status; Voting_Coordinator coordinator; }; /** Free a ballot box. */ void Voting_Coordinator_free(Voting_Coordinator coordinator); /****************** REGISTERING, CASTING & SPOILING BALLOTS *******************/ /** * Register a ballot with the coordinator so that it may be cast or * spoiled. */ enum Voting_Coordinator_status Voting_Coordinator_register_ballot(Voting_Coordinator coordinator, struct register_ballot_message message); /** Mark the ballot specified by ballot_id as cast. */ enum Voting_Coordinator_status Voting_Coordinator_cast_ballot(Voting_Coordinator coordinator, struct ballot_identifier ballot_id); /** Mark the ballot specified by ballot_id as spoiled. */ enum Voting_Coordinator_status Voting_Coordinator_spoil_ballot(Voting_Coordinator coordinator, struct ballot_identifier ballot_id); /** Get the tracker string for the given ballot_id */ char *Voting_Coordinator_get_tracker(Voting_Coordinator coordinator, struct ballot_identifier ballot_id); /***************************** EXPORTING BALLOTS ******************************/ // @todo jwaksbaum Do we want to return the number of bytes written? // @todo jwaksbaum What format is it writing in? /** Write all of the cast and spoiled ballots to out. */ enum Voting_Coordinator_status Voting_Coordinator_export_ballots(Voting_Coordinator coordinator, FILE *out); #endif /* __VOTING_COORDINATOR_H__ */
C
// print multiplication table using command line arguments. #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int counter, number; if(argc <= 1) { printf("you have forgot to type number to calculate multiplicaion table."); printf("\nEnter a number to print multiplicaion table: "); scanf("%d", &number); } else { number = atoi(argv[1]); } printf("The multiplicaion table of %d: \n", number); for(counter = 0; counter < 10; counter++) { printf("%d X %d = %d \n", number, counter + 1, number * (counter + 1)); } return 0; }
C
#include<stdio.h> int main() { long int a, b, h; double x; scanf("%ld%ld", &a, &b); x = (2.0 * a) / (double)b; if((x - (long int)x) > 0) printf("%ld",(long int)x + 1); else printf("%ld",(long int)x); return 0; }
C
#include <string.h> #include "header.h" int parse_params (int argc, char **argv, int numtags, cl_tag* t) { int ii, ij, status, count; /* Check validity of tags */ for (ii=0; ii<numtags; ii++) { if (strcmp(t[ii].name,"")==0) return TAGERR_NAME; if (t[ii].type > TAGTYPE_STRING) return TAGERR_TYPE; if (t[ii].data == NULL) return TAGERR_DATA; } /* Loop through command to find tags */ count = 0; for (ii=1; ii<argc; ii++) { /* Loop through each provided tag */ for (ij=0; ij<numtags; ij++) { /* Check parameter against tag */ if (strcmp(t[ij].name, argv[ii])==0) { status = parse_params_action(argv, ii, t[ij]); if (status<0) return status; ii += status; ij = numtags; count++; } } } return count; } /* Given a match of tag t and argv[ii], do something */ int parse_params_action (char **argv, int ii, cl_tag t) { int skip; skip = 0; switch (t.type) { case TAGTYPE_BOOL: *((int*)t.data) = 1; break; case TAGTYPE_INT: if (argv[ii+1]==NULL) return PARSE_ERROR; *((int*)t.data) = atoi(argv[ii+1]); skip = 1; break; case TAGTYPE_FLOAT: if (argv[ii+1]==NULL) return PARSE_ERROR; *((float*)t.data) = atof(argv[ii+1]); skip = 1; break; case TAGTYPE_STRING: if (argv[ii+1]==NULL) return PARSE_ERROR; strcpy((char*)t.data, argv[ii+1]); skip = 1; break; } return skip; } /* fgets leaves a trailing newline, this removes it */ void trim (char* str) { int len; len = strlen(str)-1; if (str[len] == '\n') str[len] = 0; }
C
const int MAX=1000; void primeit( double x[MAX], double y[MAX], double xp[MAX], double yp[MAX], int n, bool norm=false) { for(int i=1; i!=n-1; ++i) { double den = x[i+1] - x[i-1]; double num = y[i+1] - y[i-1]; xp[i-1] = x[i]; yp[i-1] = num/den; if(norm) yp[i-1] /= y[i]; //std::cout << x[i] << " " << y[i] << "|" << xp[i-1] << " " << yp[i-1] << std::endl; } return; } void primeit( TSpline *sp, double x[MAX], double y[MAX], double xp[MAX], double yp[MAX], int n, bool norm=false) { for(int i=1; i!=n-1; ++i) { double pre = 0.5*( x[i] + x[i-1] ); double pos = 0.5*( x[i+1] + x[i] ); double den = pos-pre; double num = sp->Eval(pos) - sp->Eval(pre); xp[i-1] = x[i]; yp[i-1] = num/den; if(norm) yp[i-1] /= y[i]; //std::cout << x[i] << " " << y[i] << "|" << xp[i-1] << " " << yp[i-1] << std::endl; } return; } double findLowEdge( double xval, double x[MAX], int size, bool reversed=false ) { int ret = -999; if(!reversed) { for(int i=0; i!=size; ++i) if(xval>x[i]) { ret = i; } } else { for(int i=size-1; i>=0; --i) if(xval<x[i]) { ret = i; } } return ret; } double findHighEdge( double xval, double x[MAX], int size ) { return findLowEdge(xval,x,size,true); } double threshold( int xstart, int xstop, double y[MAX], double thr, bool rising, bool reversed) { int ret = -999; if(!reversed) { for(int i=xstart; i<=xstop; ++i) if(rising&&y[i]>thr) { ret = i; break; } else if((!rising)&&(y[i]<thr)) { ret = i; break; } } else { for(int i=xstop; i>=xstart; --i) if(rising&&y[i]>thr) { ret = i; break; } else if((!rising)&&(y[i]<thr)) { ret = i; break; } } return ret; } double rising( int xstart, int xstop, double y[MAX], double thr, bool reversed=false ) { return threshold( xstart, xstop, y, thr, true, reversed); } int falling( int xstart, int xstop, double y[MAX], double thr, bool reversed=false ) { return threshold( xstart, xstop, y, thr, false, reversed); } int peak( int xstart, int xstop, double y[MAX], double &max) { int ret = -999; max = -999; for(int i=xstart; i<xstop; ++i) if(y[i]>max) { max = y[i]; ret = i; } return ret; } int floor( int xstart, int xstop, double y[MAX], double &min) { double ret = 999; min = 999; for(int i=xstart; i<xstop; ++i) if(y[i]<min) { min = y[i]; ret = i; } return ret; } int locatePointBelowZero( int xstart, int xstop, double y[MAX], int times) { double ret = xstart; int found = 0; for(int i=xstart; i<xstop; ++i) { if(y[i]<0) { found++; ret = i; } if(found==times) break; } if(found==times) return ret; return 999; } int compress(int n, double x[MAX], double y[MAX], double xx[MAX], double yy[MAX], double thr=0.1) { int nn = 0; for(int i=0; i<n; ++i) { xx[nn] = x[i]; yy[nn] = y[i]; if(i<n-1) if(x[i+1]-x[i]<thr) { // less than 100 mV -> merge xx[nn] = 0.5*(x[i] + x[i+1]); yy[nn] = 0.5*(y[i] + y[i+1]); i++; } nn++; } return nn; } int bvfinder(TString file="20200804_20.8C/HDR2-_Ch4_iLED-1-20200804-1128.csv", //20.8C looks fine (no lights) double merge=0.0005, double thrPrime=0.5, double rangeend=-1, bool gausInstead = false ) { gStyle->SetOptStat(0); int n=0; double volt[MAX]; //original double curr[MAX]; //original double volt0[MAX]; //compressed double curr0[MAX]; //compressed double volt1[MAX]; // primed normalized double curr1[MAX]; // primed normalized double volt2[MAX]; // doublePrimed double curr2[MAX]; // doublePrimed double sqrtc[MAX]; /////// // my clumsy way of extracting data from a csv file TString outfilestring = Form("outputfiles/%s",file.Data()); std::ifstream fin( outfilestring.Data() ); std::string line; int indexAt15 = 0; for(;;n++) { if(!std::getline(fin,line)) break; if(n>MAX) break; TString rline = line; TObjArray *lst = rline.Tokenize(","); volt[n] = ((TObjString*) lst->At(0))->GetString().Atof(); curr[n] = ((TObjString*) lst->At(1))->GetString().Atof()*1e6; // move to uA if(volt[n]<15) indexAt15 = n; } std::cout << "I read " << n << " pairs. My MAX stack was " << MAX << std::endl; // compressing int nn = 0; double xtemp1[MAX], xtemp2[MAX]; double ytemp1[MAX], ytemp2[MAX]; nn = compress(n,volt,curr,xtemp1,ytemp1,merge); std::cout << "**** nn=" << nn << std::endl; nn = compress(nn,xtemp1,ytemp1,xtemp2,ytemp2,merge); std::cout << "**** nn=" << nn << std::endl; nn = compress(nn,xtemp2,ytemp2,xtemp1,ytemp1,merge); std::cout << "**** nn=" << nn << std::endl; nn = compress(nn,xtemp1,ytemp1,xtemp2,ytemp2,merge); std::cout << "**** nn=" << nn << std::endl; nn = compress(nn,xtemp2,ytemp2,xtemp1,ytemp1,merge); std::cout << "**** nn=" << nn << std::endl; nn = compress(nn,xtemp1,ytemp1,xtemp2,ytemp2,merge); std::cout << "**** nn=" << nn << std::endl; nn = compress(nn,xtemp2,ytemp2,volt0,curr0,merge); std::cout << "**** nn=" << nn << std::endl; // transforming for(int i=0; i!=n; ++i) { curr[i] *= 1e3; // move to nA } for(int i=0; i!=nn; ++i) { sqrtc[i] = TMath::Sqrt(curr0[i]); // sqrt of current curr0[i] *= 1e3; // move to nA } /////// //primeit(volt, curr, volt1,curr1,n,true); //primeit(volt1,curr1,volt2,curr2,n-2); // create graphical objects TGraph *gr0 = new TGraph(n,volt,curr); TGraph *gr00 = new TGraph(nn,volt0,curr0); TSpline *sp00 = new TSpline3("sp00",gr00); primeit(sp00,volt0,curr0,volt1,curr1,nn,true); TGraph *gr1 = new TGraph(nn-2,volt1,curr1); TSpline *sp1 = new TSpline3("sp1",gr1); primeit(sp1,volt1,curr1,volt2,curr2,nn-2); TGraph *gr2 = new TGraph(nn-4,volt2,curr2); TSpline *sp2 = new TSpline3("sp2",gr2); TGraph *gr3 = new TGraph(nn,volt0,sqrtc); // finding first peak of primed int skipfirst = indexAt15; int xini, xend, xpea; ///////////////////// if(rangeend<0) { std::cout << "*** Trying to get the range automatically ***" << std::endl; std::cout << "start analysis from index " << skipfirst << " with threshold " << thrPrime << std::endl; xini = rising(skipfirst,nn-1,curr1,thrPrime); if(xini==-999) { std::cout << " * ERROR no rising crossing found for " << thrPrime << std::endl; exit(0); } xend = falling(xini,nn-1,curr1,thrPrime); if(xend==-999) { std::cout << " *ERROR no falling crossing found for " << thrPrime << std::endl; exit(0); } std::cout << "Starting range from " << xini << ": " << volt1[xini] << " and " << xend << ": " << volt1[xend] << std::endl; double thr; xpea = peak(xini,xend,curr1,thr); std::cout << "first peak found at " << xpea << ": " << volt1[xpea] << "(" << thr << ")" << std::endl; xini = rising(skipfirst,xpea,curr1,0.46*thr); xend = falling(xpea,nn-1,curr1,0.68*thr); std::cout << "Found potential range from " << xini << ": " << volt1[xini] << " and " << xend << ": " << volt1[xend] << std::endl; } else { std::cout << "*** manual range mode ***" << std::endl; xini = findLowEdge(thrPrime,volt1,nn-2); xend = findHighEdge(rangeend,volt1,nn-2); double thr; xpea = peak(xini,xend,curr1,thr); std::cout << "Found potential range from " << xini << ": " << volt1[xini] << " and " << xend << ": " << volt1[xend] << std::endl; std::cout << "first peak found at " << xpea << ": " << thr << std::endl; } //make sure that the range is at least three points from maximum if(xpea-xini < 4 ) xini = xpea-4; if(xend-xpea < 5 ) xend = xpea+5; if(xend>nn-2) xend = nn-2; std::cout << "Correcting range now from " << xini << ": " << volt1[xini] << " and " << xend << ": " << volt1[xend] << std::endl; //exit(0); // so it turns out that the second primed point by point is jumpy, thus my proposal is the following: // First: estimate the inflection point via a Landau fit to the primed function in the nominal range // Second: fit to a straight line the second-primed using a range centered on the previous estimate // Third: since for the sqrt(I) method, the range is crucial. I will use the first estimate to open range there too // here we go: // first: landau fit to the primed TF1 *fitLandau[100]; //plenty of fits int nfit1 = 0; double sx = 0; double sxx = 0; for(int ii=xini; ii<xpea-2; ++ii) { for(int jj=xend; jj>xpea+2; --jj) { //cout << "Landau fit: " << ii << " " << jj << std::endl; if(gausInstead) { fitLandau[nfit1] = new TF1(Form("fitGaus%d",nfit1),"[0]*TMath::Gaus(x,[1],[2])", volt1[ii], volt1[jj]); } else { fitLandau[nfit1] = new TF1(Form("fitLandau%d",nfit1),"[0]*TMath::Landau(x,[1],[2])", volt1[ii], volt1[jj]); } fitLandau[nfit1]->SetParameter(1,volt1[xpea]); fitLandau[nfit1]->SetParLimits(1,volt1[ii],volt1[jj]); fitLandau[nfit1]->SetParameter(2,1); fitLandau[nfit1]->SetParLimits(2,0.1,3); fitLandau[nfit1]->SetLineWidth(1); fitLandau[nfit1]->SetLineColor(kCyan-3); fitLandau[nfit1]->SetLineStyle(2); gr1->Fit( fitLandau[nfit1], "WWRQS", "", volt1[ii], volt1[jj] ); sx += fitLandau[nfit1]->GetParameter(1); sxx += fitLandau[nfit1]->GetParameter(1)*fitLandau[nfit1]->GetParameter(1); nfit1++; if(nfit1>100) break; } if(nfit1>100) break; } double landauMean = sx/nfit1; double landauStd = TMath::Sqrt(sxx*nfit1-sx*sx)/nfit1; cout << "* Number of Landau fits " << nfit1 << std::endl; cout << " MPV mean " << landauMean << " error " << landauStd << std::endl; //exit(0); // second: find peak position for second-primed and start range there for straight fit TF1 *fitStraight[100]; double thr; int xpea2P = peak(xini,xend,curr2,thr); double est = landauMean; int nfit2=0; sx = sxx = 0; for(int ii=0; ii<100; ++ii) { int jj = locatePointBelowZero(xpea2P,xend,curr2,nfit2+1); if(jj==999) break; //std::cout << "2Primed " << xpea2P << ": " << thr; //std::cout << " " << jj << std::endl; fitStraight[nfit2] = new TF1( Form("fitStraight%d",nfit2), Form("[0]+[1]*(x-%f)",est), volt1[xpea2P], volt1[jj] ); fitStraight[nfit2]->SetParameter(1,-10); fitStraight[nfit2]->SetParLimits(1,-1e6,0); fitStraight[nfit2]->SetLineWidth(1); fitStraight[nfit2]->SetLineColor(kOrange-3); fitStraight[nfit2]->SetLineStyle(2); gr2->Fit( fitStraight[nfit2], "WWRQS", "", volt1[xpea2P], volt1[jj] ); double xxx = fitStraight[nfit2]->GetX(0,1,100); if(TMath::IsNaN(xxx)) continue; //std::cout << xxx << std::endl; sx += xxx; sxx += xxx*xxx; nfit2++; } double straightMean=sx/nfit2; double straightStd = TMath::Sqrt(sxx*nfit2-sx*sx)/nfit2; double estimator1=straightMean; std::cout << "* Number of Straight fits " << nfit2 << std::endl; std::cout << " Inflection point estimated at " << straightMean << " error " << straightStd << std::endl; //exit(0); // third: estimating crossing point with zero from sqrt(I) // Note: this method is tricky as it depends strongly on the minimum Vbias used in the fit. // a totally arvitrary range is chosen here after having looked at all of the data // it seems to be that the amount of leakage current is non-negligible specially for the irradiated // SiPM but also is relatively strong in the nonirradiated ones. // The choice (whether good or not) is to use the Vbdwn found by the inflection point as the right limit // in the range and use as left limit the Voltage that correspond to 30% of the difference between the Sqrt{i} // at BreakdownInflection (Vbdwn1) and the Sqrt{I} of the Voltage that correspond to (Vbdwn1 - 1 Volt) assuming // that at the later Vbias we are below the real Vdown voltage. int xini3, xend3; xini3 = findLowEdge(landauMean-1.0,volt0,nn); // index at 1V below Vdwn1 xend3 = findLowEdge(landauMean,volt0,nn); float upperY = sqrtc[xend3]; float lowerY = sqrtc[xini3]; std::cout << " Reference current is " << lowerY+0.3*(upperY-lowerY) << std::endl; xini3 = findLowEdge( lowerY+0.3*(upperY-lowerY), sqrtc, nn ); // move to our choice xini3--; xend3++; //that works pretty well for unsubtracted distributions, for subtracted ones use this xini3 = findLowEdge(landauMean-0.2,volt0,nn); // 200mV xend3 = findLowEdge(landauMean+0.3,volt0,nn); // 300mV std::cout << " xini3 " << xini3 << ": " << volt0[xini3] << " xend3 " << xend3 << ": " << volt0[xend3] << std::endl; //exit(0); // TF1 *fitLinear[100]; int nfit3 = 0; sx = sxx = 0; int xcent = 0.5*(xini3+xend3); for(int ii=xini3; ii<xend3-2; ++ii) { for(int jj=ii+1; jj<xend3; ++jj) { fitLinear[nfit3] = new TF1(Form("fitLinear%d",nfit3),"[0]+[1]*x", 30/*volt1[ii]*/, volt1[jj]); fitLinear[nfit3]->SetLineWidth(1); fitLinear[nfit3]->SetLineColor(kGreen-3); fitLinear[nfit3]->SetLineStyle(2); gr3->Fit( fitLinear[nfit3], "WWRQS", "", volt0[ii], volt0[jj] ); double xxx = fitLinear[nfit3]->GetX(0,30,100); if(TMath::IsNaN(xxx)) continue; sx += xxx; sxx += xxx*xxx; nfit3++; if(nfit3>100) break; } if(nfit3>100) break; } double linearMean = sx/nfit3; double linearStd = TMath::Sqrt(sxx*nfit3-sx*sx)/nfit3; cout << "* Number of Linear fits " << nfit3 << std::endl; cout << " Linear mean " << linearMean << " error " << linearStd << std::endl; double estimator2=linearMean; std::cout << "Crossing estimated at " << estimator2 << std::endl; ///////////// // D O N E // ///////////// /////// // display all double max0, max1, max2, max3; double min0, min1, min2, min3; peak( 0,nn,curr0,max0); floor(0,nn,curr0,min0); peak( xini,xend,curr1,max1); floor(xini,xend,curr1,min1); peak( xini,xend,curr2,max2); floor(xini,xend,curr2,min2); peak( 0,xend3+3,sqrtc,max3); floor(2,xend3,curr0,min3); TLine *lin = new TLine(); lin->SetLineColor(kRed-3); TLatex *tex = new TLatex(); std::cout << "min " << min0 << " max0 " << max0 << std::endl; TCanvas *main = new TCanvas(); main->SaveAs( Form("%s_Figs.pdf[",outfilestring.Data()), "pdf" ); main->cd()->SetLogy(1); //TH2D *axis0 = new TH2D("axis0","IV-curve;Bias (V);I (nA)",100,0, volt[n-1]+2,10000,min0,max0); TH2D *axis0 = new TH2D("axis0","IV-curve;Bias (V);I (nA)",100,0, volt[n-1]+2,10000,0.1,max0); axis0->Draw(""); gr0->Draw("*SAME"); gr0->SetMarkerColor(kGreen-3); gr00->Draw("*SAME"); sp00->Draw("SAME"); gr0->GetYaxis()->SetTitle("I (nA)"); gr0->GetXaxis()->SetTitle("Bias (V)"); tex->SetTextSize(0.03); tex->DrawTextNDC(0.12,0.85,Form("%s",file.Data())); tex->SetTextSize(0.05); main->SaveAs( Form("%s_Figs.pdf",outfilestring.Data()), "pdf" ); TCanvas *main1 = new TCanvas("methods","",1600,600); main1->Divide(3,1,0.001,0.001); main1->cd(1); gr1->Draw("A*"); gr1->GetYaxis()->SetRangeUser(min1,max1); gr1->GetYaxis()->SetNdivisions(505); gr1->GetYaxis()->SetTitleOffset(1.2); for(int ii=0; ii!=nfit1; ++ii) fitLandau[ii]->Draw("SAME"); gr1->Draw("*SAME"); sp1->Draw("SAME"); lin->DrawLine(volt1[xini],-1,volt1[xini],+10); lin->DrawLine(volt1[xend],-1,volt1[xend],+10); gr1->GetXaxis()->SetRangeUser( volt1[xini]-2, volt1[xend]+2); tex->SetTextColor(kCyan-3); tex->DrawTextNDC(0.15,0.8,Form("%.2f (%.2f)",landauMean,landauStd)); main1->cd(2); gr2->Draw("A*"); gr1->GetYaxis()->SetRangeUser(min2,max2); gr2->GetYaxis()->SetNdivisions(505); gr2->GetYaxis()->SetTitleOffset(1.2); for(int ii=0; ii!=nfit2; ++ii) fitStraight[ii]->Draw("SAME"); gr2->Draw("*SAME"); gr2->GetXaxis()->SetRangeUser( volt1[xini]-2, volt1[xend]+2); tex->SetTextColor(kOrange-3); tex->DrawTextNDC(0.15,0.8,Form("%.2f (%.2f)",straightMean,straightStd)); //gr1->GetYaxis()->SetTitle("(dI / dV) / I"); gr1->GetYaxis()->SetTitle("d/dv Ln I"); gr1->GetXaxis()->SetTitle("Bias (V)"); //gr2->GetYaxis()->SetTitle("(d^{2} I / dV^{2}) / I"); gr2->GetYaxis()->SetTitle("d^{2}/dv^{2} Ln I"); gr2->GetXaxis()->SetTitle("Bias (V)"); gr1->SetTitle(""); gr2->SetTitle(""); sp2->Draw("SAME"); main1->cd(3); TH2D *axis3 = new TH2D("axis3",";Bias (V);#sqrt{ I (#muA) }", 100, volt1[xini]-3, volt1[xend3],10000,0,max3); axis3->Draw(""); axis3->GetYaxis()->SetNdivisions(505); axis3->GetYaxis()->SetTitleOffset(1.2); for(int ii=0; ii!=nfit3; ++ii) fitLinear[ii]->Draw("SAME"); gr3->Draw("*SAME"); tex->SetTextColor(kGreen-3); tex->DrawTextNDC(0.15,0.8,Form("%.2f (%.2f)",linearMean,linearStd)); main1->SaveAs( Form("%s_Figs.pdf",outfilestring.Data()), "pdf" ); /* TCanvas *main3 = new TCanvas(); //main3->SetLogy(1); gr0->Draw("A*"); gr0->SetTitle("IV-curve"); std::cout << "max0: " << max0 << std::endl; gr0->GetXaxis()->SetRangeUser( volt1[xini]-2, volt1[xend]+2); gr0->GetYaxis()->SetRangeUser( min3, max0 ); lin->SetLineColor(kGreen-3); tex->SetTextColor(kGreen-3); lin->DrawLine(linearMean-linearStd,0,linearMean-linearStd,max0); lin->DrawLine(linearMean+linearStd,0,linearMean+linearStd,max0); tex->DrawLatex(linearMean,0.90*max0,Form("%.1f #pm %.1f",linearMean,linearStd)); lin->SetLineColor(kCyan-3); tex->SetTextColor(kCyan-3); lin->DrawLine(landauMean-landauStd,0,landauMean-landauStd,max0); lin->DrawLine(landauMean+landauStd,0,landauMean+landauStd,max0); tex->DrawLatex(landauMean,0.95*max0,Form("%.1f #pm %.1f",landauMean,landauStd)); lin->SetLineColor(kOrange-3); tex->SetTextColor(kOrange-3); lin->DrawLine(straightMean-straightStd,0,straightMean-straightStd,max0); lin->DrawLine(straightMean+straightStd,0,straightMean+straightStd,max0); tex->DrawLatex(straightMean,0.90*max0,Form("%.1f #pm %.1f",straightMean,straightStd)); main3->SaveAs( Form("%s_Figs.pdf",outfilestring.Data()), "pdf" ); */ main1->SaveAs( Form("%s_Figs.pdf]",outfilestring.Data()), "pdf" ); /////// ///// Saving fit data ofstream fout( Form("%s_Fits.txt",outfilestring.Data()) ); fout << file.Data() << " "; fout << landauMean << " " << landauStd << " "; fout << straightMean << " " << straightStd << " "; fout << linearMean << " " << linearStd << std::endl; return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* size_hard.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ede-la-v <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/11/29 18:43:57 by ede-la-v #+# #+# */ /* Updated: 2017/12/14 15:43:35 by ede-la-v ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" static int nb_bit(int bit[5], int max) { int i; i = 0; while (bit[i] != -1) i++; if (i > max) return (0); i = 0; while (bit[i] != -1) write(1, &bit[i++], 1); return (i); } int ft_putwchar(int bit[5], wchar_t arg, int max) { if (arg < 0 || arg > 2097151) return (-1); else if ((arg > -1 && arg < 128) || MB_CUR_MAX < 2) bit[0] = arg; else if (arg < 2048 || MB_CUR_MAX < 3) { bit[0] = (0b11 << 6) | ((arg & 0b11111000000) >> 6); bit[1] = (0b1 << 7) | (arg & 0b00000111111); } else if (arg < 65536 || MB_CUR_MAX < 4) { bit[0] = (0b111 << 5) | ((arg & (0b1111 << 12)) >> 12); bit[1] = (0b1 << 7) | (arg & 0b111111 << 6) >> 6; bit[2] = (0b1 << 7) | (arg & 0b111111); } else { bit[0] = (0b1111 << 4) | ((arg & (0b1111 << 18)) >> 18); bit[1] = (0b1 << 7) | (arg & 0b111111 << 12) >> 12; bit[2] = (0b1 << 7) | (arg & 0b111111 << 6) >> 6; bit[3] = (0b1 << 7) | (arg & 0b111111); } return (nb_bit(bit, max)); } int ft_putwstr(wchar_t *str, int max) { int count; int bit[5]; int i; int j; int tmp; count = 0; i = 0; while (str[i] && count < max) { j = 0; while (j < 5) bit[j++] = -1; tmp = ft_putwchar(bit, str[i], max - count); if (tmp == -1) return (-1); if (tmp == 0) return (count); count += tmp; i++; } return (count); } wchar_t *fwint_t(va_list args, t_variable **lst) { wchar_t truc; wchar_t *truc2; (void)(**lst); truc = va_arg(args, int); truc2 = (wchar_t *)malloc(2 * sizeof(wchar_t)); truc2[0] = truc; truc2[1] = '\0'; return (truc2); } wchar_t *wchar_t_s(va_list args, t_variable **lst) { (void)(**lst); return (va_arg(args, wchar_t*)); }
C
/* writen by July from his book The method of Programming 题目描述: 给定一个字符串,要求将字符串前面的若干个字符移到字符串的尾部, 例如将字符串“abcdef”的前3个字符a,b,c移到字符串的尾部,那么 原字符串将变为"defabc",请写一个函数实现此功能 */ #include<stdio.h> //该方法时间复杂度为O(mn),空间复杂度为O(1) void LeftShiftOne(char *s, int n){ //保存第一个字符 char t = s[0]; for(int i = 1;i<n;i++){ s[i-1]=s[i]; } s[n-1] = t; } int main(){ char *s; int n,m; scanf("%s", s); scanf("%d", &n); scanf("%d", &m); while(m--){ LeftShiftOne(s, n); } printf("%s\n", s); return 1; }
C
#include "dominion.h" #include "dominion_helpers.h" #include <string.h> #include <stdio.h> #include "rngs.h" //numHandCards() test void assertTrue(int a, int b){ if(a==b) { printf("TEST SUCCESSFULLY COMPLETED\n"); } else{ printf("TEST FAILED\n"); } } int main() { struct gameState G, oG; int k[10] = {adventurer, council_room, feast, gardens, mine , smithy, great_hall, village, baron, steward}; int choice1 = 1, choice2 = 2, choice3 = 3, bonus = 0, handPos = 0, seed =2, counter=0, numbPlayers = 2, x = 1000, i, val, passFail = 1; initializeGame(numbPlayers, k, seed, &G); int player = whoseTurn(&G); int correctNumb = G.handCount[player]; printf("hand count %d\n", correctNumb); printf("\n *****TESTING numHandCard ***** \n"); //testing return value printf("\n TESTING RETURN VALUE:\n\n"); for (i = 0; i < x; i++) { memcpy(&oG, &G, sizeof(struct gameState)); val = numHandCards(&oG); player = whoseTurn(&oG); if (val != correctNumb) { passFail = 0; break; } } printf("Return Value: %d, Expected: %d \n\n", val, correctNumb); //testing after adding printf(" TESTING AFTER ADDING CARD:\n\n"); correctNumb = G.handCount[player]+1; for (i = 0; i < x; i++) { memcpy(&oG, &G, sizeof(struct gameState)); drawCard(player, &oG); val = numHandCards(&oG); player = whoseTurn(&oG); if (val != correctNumb) { passFail = 0; break; } } printf("Return Value: %d, Expected: %d \n\n", val, correctNumb); //testing after removing printf(" TESTING AFTER REMOVING CARD:\n\n"); correctNumb = G.handCount[player]-1; for (i = 0; i < x; i++) { memcpy(&oG, &G, sizeof(struct gameState)); discardCard(1,player, &oG,0); val = numHandCards(&oG); player = whoseTurn(&oG); if (val != correctNumb) { passFail = 0; break; } } printf("Return Value: %d, Expected: %d \n\n", val, correctNumb); assertTrue(passFail, 1); return 0; }
C
#include "header.h" // Function to Display All Present Node Record *search_node (Record *node) { Record *temp = node; int flag = 0; unsigned int num_id = 0; int index = 1; if (NULL != node) { // Calling Fuction to Take Search Element print ("\n Enter Node to Search: "); num_id = integer_input(); while (1) { if (temp->id == num_id) { flag = 1; print ("\n\n--> Node Present at Position: %d\n", index); print ("\n-- Details --"); // Calling Function to Print Node Details print_node (temp); } if (temp->next == node) { break; } temp = temp->next; index++; } } if (0 == flag) { print ("\n\n--> Node in Not Present with ID: %d\n", num_id); } return node; }
C
#include<stdio.h> #include<math.h> int main() { int side1, side2; float h, sq; scanf("%d %d", &side1, &side2); h = side1 * side1 + side2 * side2; sq = h / 2; int temp = 0; while(sq != temp) { temp = sq; sq = (h / temp + temp) / 2; } printf("area of triangle is :%f\n", sq); return 0; }
C
int length (LInt *l){ int r=0; while((*l) !=NULL){ r++; l=&((*l)->prox); } return r; } LInt parteAmeio (LInt *l){ LInt res=NULL,ir; int m=length(&(*l)); int i=1; int n; if (m%2!=0){ n=((m-1)/2); }else{ n=m/2; } if (n==0)return res; res=(*l); while (i<n){ (*l)=(*l)->prox; i++; } ir=(*l)->prox; (*l)->prox=NULL; (*l)=ir; return res; }
C
#include <unistd.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <commons/log.h> #include "memory.h" #include "ram.h" #include "cache.h" #include "../commons/structures.h" #include "../commons/declarations.h" #include "../commons/error_codes.h" void memory_init() { ram_init(); cache_init(); } void memory_destroy() { cache_destroy(); ram_destroy(); } void program_end(int PID) { ram_program_end(PID); cache_program_end(PID); } void* memory_read(int PID, int page, int offset, int size) { char* buffer = malloc(sizeof(char) * size); char* bufferStart = buffer; bool cacheMiss = false; // voy copiando en buffer cada pedazo de pagina // puede pasar que me pidan una instruccion que empieza en pag 1 y siga en pag 2 while (size > 0) { int currentPageSize = (size < (configMemory->frameSize - offset)) ? size : (configMemory->frameSize - offset); size -= currentPageSize; // esta en cache? cache_access_lock(); t_cache_entry* cacheEntry = cache_search(PID, page); if (cacheEntry) // cache hit { log_info(logMemory, "[cache hit] PID: %d, page: %d", PID, page); memcpy(bufferStart, cacheEntry->content + offset, currentPageSize); cache_access_unlock(); } else // cache miss { cache_access_unlock(); cacheMiss = true; char* ramFrame = ram_frame_lookup(PID, page); if (ramFrame == NULL) { // TODO: chequear que esto este bien free(buffer); buffer = NULL; break; } else { // cachear pthread_mutex_lock(&replaceLock); cache_cache_contents(PID, page, ramFrame); pthread_mutex_unlock(&replaceLock); // copiar desde ram lo que haya memcpy(bufferStart, ramFrame + offset, currentPageSize); } } bufferStart = bufferStart + currentPageSize; offset = 0; ++page; } if (cacheMiss) { log_info(logMemory, "[memory_read] cache miss page: %d, offset: %d, size: %d\nsleeping %d\n", page, offset, size, configMemory->responseDelay); // printf("[cacheMiss pid = %d] before sleep...\n", PID); usleep(configMemory->responseDelay /* in ms */ * 1000 /* in microsecs */); // printf("cacheMiss pid = %d] ...after sleep\n", PID); } return buffer; } int memory_write(int PID, int page, int offset, int size, void* buffer) { int wroteSize = 0; bool cacheMiss = false; while (size > 0) { int currentPageSize = (size < configMemory->frameSize - offset) ? size : (configMemory->frameSize - offset); size -= currentPageSize; // primero fijarse si existe el frame char* frame = ram_frame_lookup(PID, page); if (frame == NULL) return ERROR_MEMORY; // traer a cache si no esta cache_access_lock(); t_cache_entry* cacheEntry = cache_search(PID, page); if (cacheEntry) { // actualizar cache memcpy(cacheEntry->content + offset, buffer + wroteSize, currentPageSize); cache_access_unlock(); } else { cacheMiss = true; cache_access_unlock(); // dejar el lock de acceso porq necesito reemplazar o buscar pthread_mutex_lock(&replaceLock); // escribir en cache frame cacheEntry = cache_cache_contents(PID, page, frame); assert(cacheEntry != NULL || configMemory->cachePerProccess == 0); if (cacheEntry != NULL) memcpy(cacheEntry->content + offset, buffer + wroteSize, currentPageSize); // actualizar cache con lo q mandaron nuevo pthread_mutex_unlock(&replaceLock); } // actualizacion inmediata de ram memcpy(frame + offset, buffer + wroteSize, currentPageSize); wroteSize += currentPageSize; offset = 0; ++page; } if (cacheMiss) { log_info(logMemory, "[memory_write] cache miss page: %d, offset: %d, size: %d\nsleeping %d\n", page, offset, size, configMemory->responseDelay); // printf("[cacheMiss pid = %d] before sleep...\n", PID); usleep(configMemory->responseDelay /* in ms */ * 1000 /* in microsecs */); // printf("cacheMiss pid = %d] ...after sleep\n", PID); } return wroteSize; }
C
#include <stdio.h> typedef struct { unsigned a,b; }Razlomak; Razlomak skrati (Razlomak raz) { Razlomak rez = raz; int zaj, i; for (i=1; i<=raz.a && i<=raz.b;++i) { if(raz.a%i==0 && raz.b%i==0) zaj=i; } rez.a=raz.a/zaj; rez.b=raz.b/zaj; return rez; } Razlomak zbroji (Razlomak r, Razlomak r2) { Razlomak n,rez; n.a=(r.a*r2.b+r.b*r2.a); n.b=(r.b*r2.b); rez=skrati(n); return rez; } Razlomak oduzmi(Razlomak r, Razlomak r2) { Razlomak n,rez; n.a=(r.a*r2.b-r.b*r2.a); n.b=(r.b*r2.b); rez=skrati(n); return rez; } Razlomak pomnozi (Razlomak r, Razlomak r2) { Razlomak n,rez; n.a=(r.a*r2.a); n.b=(r.b*r2.b); rez=skrati(n); return rez; } Razlomak podijeli (Razlomak r, Razlomak r2) { Razlomak n,rez; n.a=(r.a*r2.b); n.b=(r.b*r2.a); rez=skrati(n); return rez; } int main(void) { Razlomak r={1,2}; Razlomak r2={1,3}; Razlomak rez=zbroji(r,r2); printf("Rezultat zbrajanja je %u/%u\n",rez.a,rez.b); Razlomak rez1=oduzmi(r,r2); printf("Rezultat oduzimanja je %u/%u\n",rez1.a,rez1.b); Razlomak rez2=pomnozi(r,r2); printf("Rezultat mnozenja je %u/%u\n",rez2.a,rez2.b); Razlomak rez3=podijeli(r,r2); printf("Rezultat dijeljenja je %u/%u\n",rez3.a,rez3.b); return 0; }
C
/* { dg-do run { target { lp64 || ilp32 } } } */ /* { dg-options "-fsanitize=float-cast-overflow -Wno-overflow" } */ /* { dg-additional-options "-ffloat-store" { target { ia32 } } } */ /* { dg-additional-options "-mieee" { target { { alpha*-*-* } || { sh*-*-* } } } } */ #include <limits.h> #include "float-cast.h" int main (void) { const double inf = __builtin_inf (); const double nan = __builtin_nan (""); volatile double d; volatile signed char sc; d = SCHAR_MIN; CHECK_BOUNDARY (sc, d); d = 0.0; CHECK_BOUNDARY (sc, d); d = SCHAR_MAX; CHECK_BOUNDARY (sc, d); CHECK_NONNUMBERS (sc); volatile unsigned char uc; d = UCHAR_MAX; CHECK_BOUNDARY (uc, d); d = 0.0; CHECK_BOUNDARY (uc, d); CHECK_NONNUMBERS (uc); volatile short int s; d = SHRT_MIN; CHECK_BOUNDARY (s, d); d = 0.0; CHECK_BOUNDARY (s, d); d = SHRT_MAX; CHECK_BOUNDARY (s, d); CHECK_NONNUMBERS (s); volatile unsigned short int us; d = USHRT_MAX; CHECK_BOUNDARY (us, d); d = 0.0; CHECK_BOUNDARY (us, d); CHECK_NONNUMBERS (us); volatile int i; d = INT_MIN; CHECK_BOUNDARY (i, d); d = 0.0; CHECK_BOUNDARY (i, d); d = INT_MAX; CHECK_BOUNDARY (i, d); CHECK_NONNUMBERS (i); volatile unsigned int u; d = UINT_MAX; CHECK_BOUNDARY (u, d); d = 0.0; CHECK_BOUNDARY (u, d); CHECK_NONNUMBERS (u); volatile long l; /* 64-bit vs 32-bit longs matter causes too much of a headache. */ d = 0.0; CHECK_BOUNDARY (l, d); CHECK_NONNUMBERS (l); volatile unsigned long ul; d = 0.0; CHECK_BOUNDARY (ul, d); CHECK_NONNUMBERS (ul); volatile long long ll; d = LLONG_MIN; CHECK_BOUNDARY (ll, d); d = 0.0; CHECK_BOUNDARY (ll, d); d = LLONG_MAX; CHECK_BOUNDARY (ll, d); CHECK_NONNUMBERS (ll); volatile unsigned long long ull; d = ULLONG_MAX; CHECK_BOUNDARY (ull, d); d = 0.0; CHECK_BOUNDARY (ull, d); CHECK_NONNUMBERS (ull); return 0; } /* { dg-output " -133 is outside the range of representable values of type 'signed char'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -129.5 is outside the range of representable values of type 'signed char'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -129 is outside the range of representable values of type 'signed char'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 128 is outside the range of representable values of type 'signed char'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 128.5 is outside the range of representable values of type 'signed char'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 132 is outside the range of representable values of type 'signed char'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* nan is outside the range of representable values of type 'signed char'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -?nan is outside the range of representable values of type 'signed char'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* inf is outside the range of representable values of type 'signed char'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -inf is outside the range of representable values of type 'signed char'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 256 is outside the range of representable values of type 'unsigned char'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 256.5 is outside the range of representable values of type 'unsigned char'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 260 is outside the range of representable values of type 'unsigned char'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -5 is outside the range of representable values of type 'unsigned char'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -1.5 is outside the range of representable values of type 'unsigned char'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -1 is outside the range of representable values of type 'unsigned char'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* nan is outside the range of representable values of type 'unsigned char'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -?nan is outside the range of representable values of type 'unsigned char'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* inf is outside the range of representable values of type 'unsigned char'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -inf is outside the range of representable values of type 'unsigned char'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -32773 is outside the range of representable values of type 'short int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -32769.5 is outside the range of representable values of type 'short int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -32769 is outside the range of representable values of type 'short int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 32768 is outside the range of representable values of type 'short int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 32768.5 is outside the range of representable values of type 'short int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 32772 is outside the range of representable values of type 'short int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* nan is outside the range of representable values of type 'short int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -?nan is outside the range of representable values of type 'short int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* inf is outside the range of representable values of type 'short int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -inf is outside the range of representable values of type 'short int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 65536 is outside the range of representable values of type 'short unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 65536.5 is outside the range of representable values of type 'short unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 65540 is outside the range of representable values of type 'short unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -5 is outside the range of representable values of type 'short unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -1.5 is outside the range of representable values of type 'short unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -1 is outside the range of representable values of type 'short unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* nan is outside the range of representable values of type 'short unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -?nan is outside the range of representable values of type 'short unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* inf is outside the range of representable values of type 'short unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -inf is outside the range of representable values of type 'short unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -2.14748e\\\+09 is outside the range of representable values of type 'int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -2.14748e\\\+09 is outside the range of representable values of type 'int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -2.14748e\\\+09 is outside the range of representable values of type 'int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 2.14748e\\\+09 is outside the range of representable values of type 'int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 2.14748e\\\+09 is outside the range of representable values of type 'int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 2.14748e\\\+09 is outside the range of representable values of type 'int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* nan is outside the range of representable values of type 'int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -?nan is outside the range of representable values of type 'int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* inf is outside the range of representable values of type 'int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -inf is outside the range of representable values of type 'int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 4.29497e\\\+09 is outside the range of representable values of type 'unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 4.29497e\\\+09 is outside the range of representable values of type 'unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 4.29497e\\\+09 is outside the range of representable values of type 'unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -5 is outside the range of representable values of type 'unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -1.5 is outside the range of representable values of type 'unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -1 is outside the range of representable values of type 'unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* nan is outside the range of representable values of type 'unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -?nan is outside the range of representable values of type 'unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* inf is outside the range of representable values of type 'unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -inf is outside the range of representable values of type 'unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* nan is outside the range of representable values of type 'long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -?nan is outside the range of representable values of type 'long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* inf is outside the range of representable values of type 'long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -inf is outside the range of representable values of type 'long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -5 is outside the range of representable values of type 'long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -1.5 is outside the range of representable values of type 'long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -1 is outside the range of representable values of type 'long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* nan is outside the range of representable values of type 'long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -?nan is outside the range of representable values of type 'long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* inf is outside the range of representable values of type 'long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -inf is outside the range of representable values of type 'long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 9.22337e\\\+18 is outside the range of representable values of type 'long long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 9.22337e\\\+18 is outside the range of representable values of type 'long long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 9.22337e\\\+18 is outside the range of representable values of type 'long long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 9.22337e\\\+18 is outside the range of representable values of type 'long long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 9.22337e\\\+18 is outside the range of representable values of type 'long long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 9.22337e\\\+18 is outside the range of representable values of type 'long long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 9.22337e\\\+18 is outside the range of representable values of type 'long long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 9.22337e\\\+18 is outside the range of representable values of type 'long long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 9.22337e\\\+18 is outside the range of representable values of type 'long long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 9.22337e\\\+18 is outside the range of representable values of type 'long long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 9.22337e\\\+18 is outside the range of representable values of type 'long long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 9.22337e\\\+18 is outside the range of representable values of type 'long long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 9.22337e\\\+18 is outside the range of representable values of type 'long long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 9.22337e\\\+18 is outside the range of representable values of type 'long long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 9.22337e\\\+18 is outside the range of representable values of type 'long long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* nan is outside the range of representable values of type 'long long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -?nan is outside the range of representable values of type 'long long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* inf is outside the range of representable values of type 'long long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -inf is outside the range of representable values of type 'long long int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 1.84467e\\\+19 is outside the range of representable values of type 'long long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 1.84467e\\\+19 is outside the range of representable values of type 'long long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 1.84467e\\\+19 is outside the range of representable values of type 'long long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 1.84467e\\\+19 is outside the range of representable values of type 'long long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 1.84467e\\\+19 is outside the range of representable values of type 'long long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 1.84467e\\\+19 is outside the range of representable values of type 'long long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 1.84467e\\\+19 is outside the range of representable values of type 'long long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 1.84467e\\\+19 is outside the range of representable values of type 'long long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 1.84467e\\\+19 is outside the range of representable values of type 'long long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 1.84467e\\\+19 is outside the range of representable values of type 'long long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 1.84467e\\\+19 is outside the range of representable values of type 'long long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 1.84467e\\\+19 is outside the range of representable values of type 'long long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 1.84467e\\\+19 is outside the range of representable values of type 'long long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 1.84467e\\\+19 is outside the range of representable values of type 'long long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* 1.84467e\\\+19 is outside the range of representable values of type 'long long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -5 is outside the range of representable values of type 'long long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -1.5 is outside the range of representable values of type 'long long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -1 is outside the range of representable values of type 'long long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* nan is outside the range of representable values of type 'long long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -?nan is outside the range of representable values of type 'long long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* inf is outside the range of representable values of type 'long long unsigned int'\[^\n\r]*(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]* -inf is outside the range of representable values of type 'long long unsigned int'" } */
C
/******************** (C) COPYRIGHT 2017 SOFT_SENSE PROJECT ********************************** * File Name : init_flash.c * Author : pangda_wang * Date First Issued : 2018/04/08 * Description : flashеIJʼ * version : v1.0 ******************************************************************************* * History: * DATE | VER | AUTOR | Description * 2018/04/6 | v1.0 | panda_wang | initial released *******************************************************************************/ #ifndef _INIT_FLASH_C_ #define _INIT_FLASH_C_ #include "init_flash.h" /************************************************* Function: vlut_para_value Description: ȡFLASHеIJȡʧܣдȱʡֵ Calls: read_flash_infm---ȡflashַָָϢ write_flash_infm---flashַָдϢ STMFLASH_ReadHalfWord---ȡflashַָϢ Called By: init_para_value---ʼ Input: Output: Return: Others: *************************************************/ void vlut_para_value(void) { uint16_t write_flash_success_flg; uint16_t para_value[HALF_LENGTH_PARA_FLASH_SAVE]={0}; printf("the code is running \r\nin the %s at the line %d \r\n",__FILE__ ,__LINE__ ); //ȡַָϢ,ַǷдı־ if(STMFLASH_ReadHalfWord(PARA_FLASH_SAVE_ADDR) == 0) //paraд룬ȫֱ { read_flash_infm(PARA_FLASH_SAVE_ADDR,para_value,HALF_LENGTH_PARA_FLASH_SAVE); } else//δд룬дȱʡֵȫֱ { para_value[0]=WRITE_FLASH_VALUE; para_value[1]=DEFAULT_DA_SIN_FREQ; para_value[2]=DEFAULT_SENSOR_SIN_FREQ; para_value[3]=DEFAULT_AD_SAMPLE_CYCLE; para_value[4]=DEFAULT_FILTER_DEEP; para_value[5]=DEFAULT_SINGLE_SAMPLE_NUM; write_flash_infm(PARA_FLASH_SAVE_ADDR,para_value,HALF_LENGTH_PARA_FLASH_SAVE); } //ȫֱṹ #ifdef OPEN_DEBUG saved_in_flash_para.da_sin_freq = para_value[1]; printf("da_sin_freq is %d \r\n",saved_in_flash_para.da_sin_freq); assert_param(IS_DA_SIN_FREQ_LEGAL(saved_in_flash_para.da_sin_freq)); saved_in_flash_para.sensor_sin_freq = para_value[2]; printf("sensor_sin_freq is %d \r\n",saved_in_flash_para.sensor_sin_freq); assert_param(IS_SENSOR_SIN_FREQ_LEGAL(saved_in_flash_para.sensor_sin_freq)); saved_in_flash_para.ad_sample_cycle = (uint8_t)para_value[3]; saved_in_flash_para.filter_deep = (uint8_t)para_value[4]; assert_param(IS_FILTER_DEEP_LEGAL(saved_in_flash_para.ad_sample_cycle)); saved_in_flash_para.single_channel_sample_num = (uint8_t)para_value[5]; assert_param(IS_SINGLE_SAMPLE_NUM(saved_in_flash_para.single_channel_sample_num)); #else saved_in_flash_para.da_sin_freq = para_value[1]; if(IS_DA_SIN_FREQ_LEGAL(saved_in_flash_para.da_sin_freq)==0) { saved_in_flash_para.da_sin_freq =DEFAULT_DA_SIN_FREQ; printf("da_sin_freq set err!! \r\nin the %s at the line %d \r\n",__FILE__ ,__LINE__ ); } saved_in_flash_para.sensor_sin_freq = para_value[2]; if(IS_SENSOR_SIN_FREQ_LEGAL(saved_in_flash_para.sensor_sin_freq)==0) { saved_in_flash_para.sensor_sin_freq =DEFAULT_SENSOR_SIN_FREQ; printf("sensor_sin_freq set err!! \r\nin the %s at the line %d \r\n",__FILE__ ,__LINE__ ); } saved_in_flash_para.ad_sample_cycle = (uint8_t)para_value[3]; saved_in_flash_para.filter_deep = (uint8_t)para_value[4]; if(IS_FILTER_DEEP_LEGAL(saved_in_flash_para.filter_deep)==0) { saved_in_flash_para.filter_deep = DEFAULT_FILTER_DEEP; printf("filter_deep set err!! \r\nin the %s at the line %d \r\n",__FILE__ ,__LINE__ ); } saved_in_flash_para.single_channel_sample_num = (uint8_t)para_value[5]; if(IS_FILTER_DEEP_LEGAL(saved_in_flash_para.single_channel_sample_num)==0) { saved_in_flash_para.single_channel_sample_num = DEFAULT_FILTER_DEEP; printf("single_channel_sample_num set err!! \r\nin the %s at the line %d \r\n",__FILE__ ,__LINE__ ); } #endif } /************************************************* Function: write_flash_infm Description: Calls: read_flash_infm---ȡflashַָϢ Called By: init_config---ʼú Input: addr ---дַ pbuf ---дָ num_to_write---дݸ() Output: Return: Others: *************************************************/ void write_flash_infm(u32 addr, uint16_t* pbuf, uint16_t num_to_write) { //int16_t init_para[]; STMFLASH_Write(addr,pbuf,num_to_write); } /************************************************* Function: read_flash_infm Description: ȡFLASHеIJȡʧܣдȱʡֵ Calls: Called By: vlut_para_value---ʼú Input: addr----ȡݵĵַ Output: Return: ָflashݵָ Others: *************************************************/ static void read_flash_infm(uint32_t addr,uint16_t*init_para, uint16_t read_value_half_num) { //uint16_t init_para[HALF_LENGTH_PARA_FLASH_SAVE]; STMFLASH_Read(addr,init_para,HALF_LENGTH_PARA_FLASH_SAVE); //return init_para; } #endif
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <getopt.h> #include <debian-installer/system/subarch.h> static struct option long_options[] = { {"guess", 0, 0, 0}, {0, 0, 0, 0} }; int main(int argc, char *argv[]) { const char *subarch; int guess = 0; while (1) { int option_index = 0; int c; c = getopt_long (argc, argv, "g", long_options, &option_index); if (c == -1) break; switch (c) { case 'g': guess = 1; break; default: continue; } } if (guess) subarch = di_system_subarch_analyze_guess(); else subarch = di_system_subarch_analyze(); if (!subarch) return EXIT_FAILURE; printf("%s/%s\n", CPU_TEXT, subarch); return 0; }
C
#include <stdio.h> //Faça um programa que receba o preço de um produto, calcule e mostre o novo preço, sabendo-se que este sofreu um desconto de 10%. int main(){ int v1; printf("A valor do produto eh:\n"); scanf("%d",&v1); int des = (v1) - (v1 * 10 / 100); printf("O produto com desconto de 10%% fica por:\n%d",des); return 0; }
C
#include <stdio.h> #define MAX_COUNT 100 + 1 int main() { int n=0, input[MAX_COUNT]={0}; scanf("%d", &n); for(int i=0; i<n; i++) { scanf("%d", &input[i]); } for(int i=0; i<n; i++) { printf("Pairs for %d:", input[i]); for(int j=1; j<=input[i]; j++) { if(j >= (input[i]-1)/2+1) break; if(j != 1) printf(","); printf(" %d %d", j, input[i]-j); } printf("\n"); } return 0; }
C
/* Navn: Ane Søgaard Jørgensen * Dato: 02/11-2018 * Beskrivelse: Afleveringsopgave 9. Rekursiv og iterativ funktioner, der finder palindromer. */ # include <stdio.h> # include <stdlib.h> # include <string.h> # define MAX_LEN 30 char *is_palindrome_iter(const char *); char *is_palindrome_rec(const char *); int main(void) { char str[MAX_LEN]; /* Prompter brugeren for et ord */ printf("Input et ord[MAX %d]: ", MAX_LEN); scanf("%s", str); printf("\n"); /* Kalder funktionerne */ printf("Rekursivt: %s\n", is_palindrome_rec(str)); printf("Iterativt: %s\n", is_palindrome_iter(str)); return 0; } /* Checker om en tekststreng er et palindrom, iterativt */ char *is_palindrome_iter(const char *array) { int SENTINEL = 0; int j = strlen(array) - 1; int i = 0; /* Bliver ved, indtil array[i] og array[j] ikke er det samme, * eller hvis i bliver større end j */ while (SENTINEL == 0) { if (i > j) { return "Ja!"; } else if (array[i] != array[j]) { return "Nej"; SENTINEL = 1; } else { i++; j--; } } return "Fejl\n"; } /* Checker om en tekststreng er et palindrom, rekursivt */ char *is_palindrome_rec(const char *array) { int j = strlen(array) - 1; int i = 0; char *temp = malloc(strlen(array) * sizeof(*temp)); /* Ved lige antal bogstaver i palindromet, bliver j -1. * Ved ulige antal bogstaver i palindromet, bliver j 0. * i vil blive 0 hver gang (hvis tekstrengen er et palindom) */ if (i >= j) { return "Ja!"; } else if (array[i] != array[j]) { return "Nej"; } else if (array[i] == array[j]) { /* Kopierer tekstrengen fra array, over i temp, uden det første og det sidste bogstav */ strncpy(temp, array + 1, j - 1); temp[j] = '\0'; return is_palindrome_rec(temp); } else { return "Fejl\n"; } }
C
#pragma once #include <stdlib.h> typedef int IndexType; typedef float ValueType; #define MAX_NMODES 8 #ifndef max #define max(a,b) ((a) > (b) ? (a) : (b)) #endif #ifndef min #define min(a,b) ((a) < (b) ? (a) : (b)) #endif //lo is inclusive, hi is exclusive typedef char hash_t; hash_t *hash_create (); void hash_set (hash_t *table, size_t key, size_t value); size_t hash_get (hash_t *table, size_t key, size_t value); void hash_clear (hash_t *table); void hash_destroy (hash_t *table); size_t random_range (size_t lo, size_t hi); double random_uniform (); void random_choose (size_t *samples, size_t n, size_t lo, size_t hi); void sort (size_t *stuff, size_t n); size_t search (const size_t *stuff, size_t lo, size_t hi, size_t key); size_t search_strict (const size_t *stuff, size_t lo, size_t hi, size_t key);
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_9__ TYPE_2__ ; typedef struct TYPE_8__ TYPE_1__ ; /* Type definitions */ struct TYPE_9__ {int /*<<< orphan*/ sample_rate; int /*<<< orphan*/ sample_fmt; int /*<<< orphan*/ channel_layout; } ; struct TYPE_8__ {int nb_samples; int /*<<< orphan*/ sample_rate; int /*<<< orphan*/ format; int /*<<< orphan*/ channel_layout; } ; typedef TYPE_1__ AVFrame ; typedef TYPE_2__ AVCodecContext ; /* Variables and functions */ int AVERROR_EXIT ; char* av_err2str (int) ; TYPE_1__* av_frame_alloc () ; int /*<<< orphan*/ av_frame_free (TYPE_1__**) ; int av_frame_get_buffer (TYPE_1__*,int /*<<< orphan*/ ) ; int /*<<< orphan*/ fprintf (int /*<<< orphan*/ ,char*,...) ; int /*<<< orphan*/ stderr ; __attribute__((used)) static int init_output_frame(AVFrame **frame, AVCodecContext *output_codec_context, int frame_size) { int error; /* Create a new frame to store the audio samples. */ if (!(*frame = av_frame_alloc())) { fprintf(stderr, "Could not allocate output frame\n"); return AVERROR_EXIT; } /* Set the frame's parameters, especially its size and format. * av_frame_get_buffer needs this to allocate memory for the * audio samples of the frame. * Default channel layouts based on the number of channels * are assumed for simplicity. */ (*frame)->nb_samples = frame_size; (*frame)->channel_layout = output_codec_context->channel_layout; (*frame)->format = output_codec_context->sample_fmt; (*frame)->sample_rate = output_codec_context->sample_rate; /* Allocate the samples of the created frame. This call will make * sure that the audio frame can hold as many samples as specified. */ if ((error = av_frame_get_buffer(*frame, 0)) < 0) { fprintf(stderr, "Could not allocate output frame samples (error '%s')\n", av_err2str(error)); av_frame_free(frame); return error; } return 0; }
C
#include <stdio.h> #include <stdlib.h> //DONE int main(int argc, char const *argv[]) { int c = -1; int steps = 0; while(c<=1){ printf("Input the number greater than 1\n"); scanf("%d",&c); if (c<=1) { printf("Number smaller or equal to 1\n"); continue; } while(c!=1){ if(c%2==0){ c/=2; }else{ c*=3; c++; } steps++; } break; } printf("Number of steps: %d\n",steps); return 0; }
C
#define N 4 int is_diag_dom( int mat[ ][N]); double fabs(double x); double sum=0,diag,temp; int check = 1;// The value which is outputted is_diag_dom(int mat[][N]){ for (int i=0; i<N;i++){ diag = mat[i][i];// Finds the diagonal element of the current row sum=0;// Resets the sum for (int j=0;j<N;j++){ if (j!=i){// Makes it so the diagonal element is not included into the sum temp = mat[i][j];//Stores the matrix element into a temporary double sum = sum + fabs(temp);// Sums each value in the row except for the diagonal } } if (fabs(diag)<sum){//Checks if the diagonal is bigger or not, and changes the check value depending check = 0; } } return check; }
C
/* ********************************* * Programa testador do TAD Pilha ********************************* */ #include <stdio.h> #include "pilha.h" int main() { // criando pilhas vazias Pilha *p = cria_pilha(); Pilha *p2 = cria_pilha(); // tentando imprimir a pilha (ainda vazia neste momento) imprime_pilha(p); // criando algumas pessoas apenas para testar (mais adequado seria carregar de um arquivo) Pessoa *pessoa1 = inicializaPessoa("pessoa1", 51, "rua da pessoa1"); Pessoa *pessoa2 = inicializaPessoa("pessoa2", 63, "rua da pessoa2"); Pessoa *pessoa3 = inicializaPessoa("pessoa3", 10, "rua da pessoa3"); Pessoa *pessoa4 = inicializaPessoa("pessoa4", 70, "rua da pessoa4"); Pessoa *pessoa5 = inicializaPessoa("pessoa5", 20, "rua da pessoa5"); Pessoa *pessoa6 = inicializaPessoa("pessoa6", 30, "rua da pessoa6"); Pessoa *pessoa7 = inicializaPessoa("pessoa7", 40, "rua da pessoa7"); Pessoa *pessoa8 = inicializaPessoa("pessoa8", 45, "rua da pessoa8"); Pessoa *pessoa9 = inicializaPessoa("pessoa9", 65, "rua da pessoa9"); Pessoa *pessoa10 = inicializaPessoa("pessoa10", 67, "rua da pessoa10"); Pessoa *pessoa11 = inicializaPessoa("pessoa11", 13, "rua da pessoa11"); //Insere os pessoas na pilha push(pessoa1, p); push(pessoa2, p); push(pessoa3, p); push(pessoa4, p); push(pessoa5, p); push(pessoa6, p); push(pessoa7, p); push(pessoa8, p); push(pessoa9, p); push(pessoa10, p); push(pessoa11, p); //pessoa11 vai ficar na pilha p2 push(pessoa11, p2); printf("---------- Imprime pilha-----------\n"); //Imprime a pilha com todas as pessoas imprime_pilha(p); imprime_pilha(p2); // Retira pessoa da pilha p e coloca na pilha p2 push(pop(p), p2); imprime_pilha(p); imprime_pilha(p2); //libera a memória ocupada pelas pilhas p = destroi_pilha(p); p2 = destroi_pilha(p2); }
C
/* * redirect_rewrite.c * * Created on: Apr 15, 2013 * Author: Sebastian Mäki */ #include "redirect_rewrite.h" #include "urldecode.h" /* The default buffer size is the maximum path portion size * that IE can handle, so we should never have to realloc */ #define BUF_SIZE 2048 /* In case we do have to realloc, do it in increments of 512 bytes*/ #define INCR_SIZE 512 #define DEBUG unsigned int allocatedSize = BUF_SIZE; char *content; matcher matchers[] = { { "//.*.google.[^/]+/url", /* The regexp pattern to find a match */ "url", /* The query parameter which holds the destination url */ {{NULL},{NULL}}, 0 }, { "//.*.facebook.com/l.php", "u", {{NULL},{NULL}}, 0 }, /* Add your own matchers in here */ }; #define NUM_MATCHERS sizeof matchers / sizeof matchers[0] //#ifndef DEBUG int main(int argc, char **argv) { openlog("redirect_rewrite", LOG_PID|LOG_CONS, LOG_USER); compile_patterns(); /* Allocate some memory */ content = (char*) malloc(sizeof(char) * BUF_SIZE); memset (content,0,sizeof(char) * BUF_SIZE); /* Check if the memory couldn't be allocated; if it's the case, handle the problem as appropriate. */ if (NULL == content) { #ifdef DEBUG perror("Could not allocate memory"); #endif return EXIT_FAILURE; } unsigned int n = 0; unsigned int localAllocatedSize, oldSize; localAllocatedSize = allocatedSize; memset (content,0,sizeof(char) * localAllocatedSize); int c; while((c = fgetc(stdin)) != EOF){ if(n==localAllocatedSize){ oldSize = localAllocatedSize; localAllocatedSize += INCR_SIZE; allocatedSize = localAllocatedSize; content = (char*) realloc(content, sizeof(char) * localAllocatedSize); if (NULL == content) { perror("Could not allocate memory"); exit(1); } if(oldSize<localAllocatedSize) memset (content+oldSize,0,sizeof(char) * INCR_SIZE); } /* Read line into contents */ if (c != '\n'){ content[n] = c; n++; continue; } n=0; //printf("[X]Content %s \n\n", content); /* Grab the text up to the space character */ char* channel = strtok (content, " "); char* url; if(channel != NULL){ url = match(channel); /* Grab more text up to the next space character * and try to get a redirect url match */ char* original_url; if(NULL == url){ original_url = strtok (NULL, " "); if(NULL != original_url){ url = match(original_url); } printf("%s ", channel); } if(NULL == url){ printf("\n"); fflush(stdout); }else{ if(NULL != url){ char buffer[2048]; printf("302:%s\n", url); fflush(stdout); sprintf (buffer, "Redirecting: %s", url); syslog(LOG_INFO, buffer); }else{ printf("\n"); fflush(stdout); } } }else{ syslog(LOG_INFO, "No url found"); } memset (content,0,sizeof(char) * localAllocatedSize); } closelog(); return EXIT_SUCCESS; } void compile_patterns(){ unsigned int valid_matchers = 0; unsigned int x=0; while(x < NUM_MATCHERS){ char pattern[strlen(matchers[x].parameter) + 15]; sprintf(pattern, "[?,&]%s=([^&]+)", matchers[x].parameter); //query and redirect url matching matchers[x].valid = !regcomp(&matchers[x].regex.url, pattern, REG_EXTENDED) && !regcomp(&matchers[x].regex.redirect, matchers[x].pattern, REG_EXTENDED); //count valid matchers if(matchers[x].valid) valid_matchers++; x++; } } char* match(char *url){ char *b; unsigned int x=0; while(x < NUM_MATCHERS){ if( !(regexec(&matchers[x].regex.redirect, url, 0, NULL, 0)) ){ b = (char *)getParam(url, matchers[x].regex.url); return b; } x++; } return NULL; } char* getParam(char *url, regex_t prm){ unsigned int maxGroups = 2; regmatch_t cm[maxGroups]; char * decoded; decoded = NULL; if(!regexec(&prm, url, maxGroups, cm, 0)){ if ((int)cm[1].rm_so != (int)-1){ char sourceCopy[strlen(url) + 1]; strcpy(sourceCopy, url); sourceCopy[cm[1].rm_eo] = 0; decoded = url_decode(sourceCopy + cm[1].rm_so); } } return decoded; }
C
/* * license and disclaimer for the use of this source code as per statement below * Lizenz und Haftungsausschluss f� die Verwendung dieses Sourcecodes siehe unten */ #include "ring.h" #include "../DynamicMemory.h" void ring_construct(ring_t* ring) { ring->current = 0; ring->begin = 0; } static void putIn(ring_t* ring, slelement_t* prev, slelement_t* elem) { if (ring->begin == 0) // Ring is empty { elem->next = elem; ring->current = elem; } else { elem->next = prev->next; prev->next = elem; } } static void takeOut(ring_t* ring, slelement_t* prev) { if (prev->next == prev) // Just one element in ring { ring->begin = 0; ring->current = 0; } else { if (prev->next == ring->begin) ring->begin = prev->next->next; if (prev->next == ring->current) ring->current = prev->next->next; prev->next = prev->next->next; } } bool ring_insert(ring_t* ring, void* data, bool single) { if (single && ring->begin != 0) // check if an element with the same data is already in the ring { slelement_t* current = ring->current; slelement_t* begin = current; do { if (current->data == data) { return (false); } current = current->next; } while (current != begin); } slelement_t* item = AllocateMemory(sizeof(slelement_t)); if (item) { item->data = data; putIn(ring, ring->current, item); return (true); } return (false); } bool ring_isEmpty(const ring_t* ring) { return (ring->begin == 0); } bool ring_deleteFirst(ring_t* ring, void* data) { if (ring->begin == 0) return (false); slelement_t* current = ring->current; slelement_t* begin = current; do { if (current->next->data == data) // next element will be deleted { slelement_t* temp = current->next; takeOut(ring, current); FreeMemory(temp); return (true); } current = current->next; } while (current != begin); return (false); } void ring_move(ring_t* dest, ring_t* source, void* data) { if (source == 0 || dest == 0 || source->begin == 0) return; slelement_t* prev = source->begin; slelement_t* begin = prev; slelement_t* current = prev->next; do { if (current->data == data) // Found. Take it out. { takeOut(source, prev); break; } prev = current; current = current->next; } while (prev != begin); // Insert it to dest ring. putIn(dest, dest->current, current); } /* * Copyright (c) 2009-2014 The PrettyOS Project. All rights reserved. * * http://www.prettyos.de * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
C
/* * vtrr.h * * Created on: Jun 4, 2020 * Author: krad2 */ #ifndef INCLUDE_SCHEDULERS_VTRR_H_ #define INCLUDE_SCHEDULERS_VTRR_H_ #include <stdint.h> #include <stddef.h> #include <stdbool.h> #include <limits.h> #include "rbtree.h" #ifdef __cplusplus extern "C" { #endif /*-----------------------------------------------------------*/ /** * @name Virtual-time round-robin scheduling management structures. * @{ */ typedef struct sched_vtrr_client { unsigned int shares; /* thread priority */ unsigned int runs_left; /* number of quanta left to go */ unsigned int fin_time; /* virtual timestamp for VTRR allocation computations */ unsigned int timestep; /* virtual progress amount for each timestep */ rbnode rq_entry; /* red-black tree entry for sorted order */ } vtrr_client_t; typedef struct sched_vtrr_mgr { unsigned int shares; /* total number of slices to hand out per cycle */ unsigned int runs_left; /* number of slices remaining before a new scheduling cycle */ unsigned int group_time; /* virtual timestamp for thread progress comparisons */ unsigned int timestep; /* virtual progress amount for each timestep */ rbtree_rcached rq; /* red-black tree for sorted threads, maximum is cached */ rbnode *curr_max; /* pointer to the highest priority runnable thread */ rbnode *curr_cli; /* pointer to the currently running thread */ rbnode *next_cli; /* pointer to the thread scheduled for the next timeslice */ } vtrr_mgr_t; /** @} */ /*-----------------------------------------------------------*/ /** * @name Simple container_of() semantic macros provided to access threads through their bookkeeping. * @{ */ #define __vtrr_entry(ptr) rb_entry((ptr), vtrr_client_t, rq_entry) #define vtrr_entry(ptr) __vtrr_entry((ptr)) #define vtrr_active_client(mptr) __vtrr_entry((mptr)->curr_cli) #define vtrr_next_client(mptr) __vtrr_entry((mptr)->next_cli) /** @} */ /*-----------------------------------------------------------*/ /** * @name VTRR wrapper functions. * @{ */ /** * @brief Initializes a blank VTRR manager for thread installation. * @param[in] sched Pointer to a vtrr_mgr_t instance. */ void vtrr_init(vtrr_mgr_t *sched); /** * @brief Adds a new thread to the VTRR run queue. * @param[in] sched Pointer to a vtrr_mgr_t instance. * @param[in] priority Thread scheduling priority. */ void vtrr_add(vtrr_mgr_t *sched, vtrr_client_t *client, unsigned int priority); /** * @brief Adds an already-initialized thread to the run queue. * @details does not allocate a thread. * @param[in] sched Pointer to a vtrr_mgr_t instance. * @param[in] client Thread to be added. */ void vtrr_register(vtrr_mgr_t *sched, vtrr_client_t *client); /** * @brief Removes an already-initialized thread from the run queue. * @details does not deallocate thread. * @param[in] sched Pointer to a vtrr_mgr_t instance. * @param[in] client Thread to be removed. */ void vtrr_deregister(vtrr_mgr_t *sched, vtrr_client_t *client); /** * @brief Updates thread position in the run queue. * @details does not deallocate thread. * @param[in] sched Pointer to a vtrr_mgr_t instance. * @param[in] client Thread to be updated. * @param[in] priority New thread priority. */ void vtrr_reregister(vtrr_mgr_t *sched, vtrr_client_t *client, unsigned int priority); /** * @brief Readies the VTRR manager for timeslicing. * @details At least 1 thread must be installed for the manager to start. */ void vtrr_start(vtrr_mgr_t *sched); /** * @brief Kills the VTRR manager and cleans the run queue. */ void vtrr_end(vtrr_mgr_t *sched); /** * @brief Schedules the next thread in VTRR-logical order. */ void vtrr_run(vtrr_mgr_t *sched); /** * @brief Invokes vtrr_run() to change the active thread in VTRR-logical order. */ void vtrr_yield(vtrr_mgr_t *sched); /** * @brief Changes the active thread to the highest priority runnable thread if it is higher priority than the active thread. */ void vtrr_yield_higher(vtrr_mgr_t *sched); /** @} */ #ifdef __cplusplus } #endif #endif /* INCLUDE_SCHEDULERS_VTRR_H_ */
C
#include<stdio.h> #include<stdlib.h> #define maxStudents 250; //void rollNumberDetails(int); struct student; void yearOfJoining(int,int,struct student*[]); typedef struct student { int rollNumber; char nameStudent[20]; char nameDepartment[20]; char nameCourse[20]; int yearJoining; }student ; int main () { int numberOfStudents,i,year; student *p[250]; printf("Enter the number of studnets\n"); scanf("%d",&numberOfStudents); for ( i=0 ;i<numberOfStudents;i++) { p[i]=(student*) malloc(sizeof(student)); printf("Roll Number "); scanf ("%d",& p[i]->rollNumber); printf("Name "); scanf ("%s", p[i]->nameStudent); printf("Department "); scanf ("%s", p[i]->nameDepartment); printf("Course "); scanf ("%s", p[i]->nameCourse); printf("year of joining "); scanf ("%d",& p[i]->yearJoining); } printf("Enter the year\n"); scanf("%d",&year); yearOfJoining(year,numberOfStudents,p); return 0; } void yearOfJoining( int year, int number ,student *p[]) { int i; for ( i=0;i<number;i++) { if (p[i]->yearJoining==year) printf("\n %s\n",p[i]->nameStudent); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* tags_and_links.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sgarry <sgarry@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/09/03 16:49:37 by sgarry #+# #+# */ /* Updated: 2019/09/12 10:48:44 by sgarry ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/asm.h" void tags_and_links_1(int i, t_comand_asm *b, t_arg *c) { int res; res = 0; while (b && b->num_line <= i) { res += b->weight; if (b->next) b = b->next; else break ; } if (b->num_line < i) { c->value = res; } else if (b->num_line == i) { res -= b->weight; c->value = res; } if (b->previous) b = b->previous; if (b->previous && b->num_line == i) res -= b->weight; c->value = res; } void tags_and_links_2(int i, t_comand_asm *b, t_arg *c) { int res; res = 0; if (b->previous) { b = b->previous; while (b && b->num_line >= i) { res -= b->weight; b = b->previous; } } c->value = res; } void tags_and_links_3(t_pars_asm *a, t_arg *c) { while (a->link_asm) { if (!(ft_strcmp(a->link_asm->link_name, c->name_label))) break ; a->link_asm = a->link_asm->next; } if (!(a->link_asm)) { ft_putstr("\033[31mNon-existent link\033[m\n"); free_parse_asm(&a); exit(0); } } void tags_and_links_4(t_pars_asm *a, t_arg *c, t_comand_asm *b) { if (a->link_asm->num_line - b->num_line > 0) tags_and_links_1(a->link_asm->num_line, b, c); else tags_and_links_2(a->link_asm->num_line, b, c); } void tags_and_links(t_pars_asm *a) { t_comand_asm *b; t_arg *c; t_link_asm *start; t_comand_asm *start1; b = a->comand_asm; start = a->link_asm; while (b) { c = b->arg; while (c) { if (c->name_label) { tags_and_links_3(a, c); start1 = b; tags_and_links_4(a, c, b); a->link_asm = start; b = start1; } c = c->next; } b = b->next; } }
C
/****************** CLIENT CODE ****************/ #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include <errno.h> int main(int argc , char *argv[]) { int port = 8888; if (argc > 1) { port = atoi(argv[1]); printf("Port number: %d\n", port); //port = 1234 } char ipaddress[] = "127.0.0.1"; if (argc > 2) { strcpy(ipaddress, argv[2]); printf("IP Address: %s\n", ipaddress); //ipaddress = "192.168.0.2"; } int clientSocket; char buffer[1024]; struct sockaddr_in serverAddr; socklen_t addr_size; /*---- Create the socket. The three arguments are: ----*/ /* 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */ clientSocket = socket(PF_INET, SOCK_STREAM, 0); /*---- Configure settings of the server address struct ----*/ /* Address family = Internet */ serverAddr.sin_family = AF_INET; /* Set port number, using htons function to use proper byte order */ serverAddr.sin_port = htons(port); /* Set IP address to localhost */ serverAddr.sin_addr.s_addr = inet_addr(ipaddress); /* Set all bits of the padding field to 0 */ memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero); /*---- Connect the socket to the server using the address struct ----*/ addr_size = sizeof serverAddr; int res = connect(clientSocket, (struct sockaddr *) &serverAddr, addr_size); if(res != 0) { printf("Error connecting to the server: %s\n", strerror(errno)); close(clientSocket); return -1; } printf("Client connected to the server.\n"); /*---- Read the message from the server into the buffer ----*/ //recv(clientSocket, buffer, 1024, 0); printf("Enter message : "); scanf("%s" , buffer); send(clientSocket , buffer , strlen(buffer) , 0); printf("Message Sent\n"); /*---- Print the received message ----*/ //printf("Data received: %s",buffer); close(clientSocket); return 0; }
C
/* * * MOR ActionLog AGI script * Copyright Mindaugas Kezys / Kolmisoft 2012 * * v1.0 * * 2012.07.06 v1.0 Initial release * * This AGI updates DB ivr_action_log with the info from IVR */ #include <stdio.h> #include <stdarg.h> #include <mysql.h> #include <mysql/errmsg.h> #include <time.h> #include <sys/stat.h> #include "mor_agi_functions.c" /* Main function */ int main(int argc, char *argv[]) { char buff[100] = ""; char str[100] = ""; int i; time_t now; char script_time[30] = ""; MYSQL_RES *result; MYSQL_ROW row; char *variable; char *value; // variables char ivr_msg[100] = ""; char uniqueid[100] = ""; if ( time(&now) != (time_t)(-1) ){ struct tm *mytime = localtime(&now); if ( mytime ) { strftime(script_time, sizeof script_time, "%Y-%m-%d %T", mytime); } } AGITool_Init(&agi); sprintf(str, "Script executed at: %s", script_time); AGITool_verbose(&agi, &res, str, 0); // DB connection read_config(); // sprintf(str, "Host: %s, dbname: %s, user: %s, psw: %s, port: %i", dbhost, dbname, dbuser, dbpass, dbport); // AGITool_verbose(&agi, &res, str, 0); if (!mysql_connect()) { AGITool_verbose(&agi, &res, "ERROR! Not connected to database.", 0); AGITool_Destroy(&agi); return 0; } else { //AGITool_verbose(&agi, &res, "Successfully connected to database.", 0); } AGITool_get_variable2(&agi, &res, "UNIQUEID", uniqueid, sizeof(uniqueid)); AGITool_get_variable2(&agi, &res, "IVR_TXT", ivr_msg, sizeof(ivr_msg)); sprintf(str, "UniqueID: %s, IVR MSG: %s", uniqueid, ivr_msg); AGITool_verbose(&agi, &res, str, 0); /* put action into DB */ sprintf(sqlcmd, "INSERT INTO ivr_action_logs (created_at, action_text, uniqueid) VALUES ('%s', '%s', '%s');", script_time, ivr_msg, uniqueid); mysql_query(&mysql, sqlcmd); AGITool_Destroy(&agi); mysql_close(&mysql); return 0; }
C
#include<stdio.h> #include<stdlib.h> typedef struct elemento_pilha{ char info; struct elemento_pilha *prox; }elemento_pilha; elemento_pilha *topo; elemento_pilha* cria_pl(void){ return NULL; } void push(char dado){ elemento_pilha *novo; novo = (elemento_pilha *)malloc(sizeof(elemento_pilha)); if(novo == NULL){ printf("\nMemoria insuficiente!\n"); return; } novo->info = dado; novo->prox = topo; topo = novo; } char pop() { elemento_pilha *aux; char x; if(topo == NULL){ printf("\npilha vazia!Remocao invalida!\n"); exit(1); }else{ x = topo->info; aux = topo; topo = topo->prox; free(aux); return (x); } } char showtop(){ if(topo == NULL){ printf("\nPilha vazia!\n"); exit(1); }else return (topo->info); } void imprimepilha_din(){ elemento_pilha *q; int i = 1; q = topo; if(topo == NULL){ printf("\ttopo %c%c%c NULL",196 , 196, 16); }else{ while(q != NULL){ if(q == topo){ printf("\n\t\t%c%c%c%c%c%c%c\n",218,196, 196, 196, 194, 196, 191); if(q->prox != NULL){ printf("\ttopo %c%c%c%c %c %c %c%c%c\n",196 , 196, 16 ,179 ,q->info ,179 ,179, 196, 191); printf("\t\t%c%c%c%c%c%c%c %c\n", 192, 196, 196, 196, 193, 196, 217, 179); printf("\t\t %c%c%c%c%c\n",218 , 196, 196, 196, 217); printf("\t\t %c",31); }else{ printf("\ttopo %c%c%c%c %c %c %c%c%c%c NULL\n",196 , 196, 16 ,179 ,q->info ,179 ,179, 196, 196, 16); printf("\t\t%c%c%c%c%c%c%c\n", 192, 196, 196, 196, 193, 196, 217); } }else{ printf("\n\t\t%c%c%c%c%c%c%c\n",218,196, 196, 196, 194, 196, 191); if(q->prox != NULL){ printf("\t\t%c %c %c %c%c%c\n",179 ,q->info ,179 ,179, 196, 191); printf("\t\t%c%c%c%c%c%c%c %c\n", 192, 196, 196, 196, 193, 196, 217, 179); printf("\t\t %c%c%c%c%c\n",218 , 196, 196, 196, 217); printf("\t\t %c",31); }else{ printf("\t\t%c %c %c %c%c%c%c NULL\n",179 ,q->info ,179 ,179, 196, 196, 16); printf("\t\t%c%c%c%c%c%c%c\n", 192, 196, 196, 196, 193, 196, 217); } } q = q->prox; } } }
C
/* Nmeros perfeitos */ /**************************************************************/ /* Computacao Cientifica - EEL 7021 /* Grupo 9B /* Bruno Luiz da Silva Matricula:11103495 /* Vincius Bernardi Matricula:11100737 /* Exercicio 4 /**************************************************************/ #include <stdlib.h> #include <stdio.h> main() { unsigned long int input_Qnt,a=5,b,aux=1,soma=0; printf("------------------------ Gerador de numeros perfeitos ------------------------- \n"); printf("Quantos numeros perfeitos voce deseja? "); scanf("%d",&input_Qnt); printf("->Numero perfeitos: \n"); while(input_Qnt>0) { soma = 0; for(b=1;b<=a/2;b++) { //Inicia loop para encontrar divisores if(a%b == 0) {soma=soma+b; /*printf("divisor detectado: %d \n",b);*/ } //Se o resto for 0 ento soma "soma" "b" } if(a == soma) { printf("-->%d \n",a); input_Qnt--;} //else printf("nao-perfeito: %d \n",a); //Imprime nmeros no perfeitos a++; } printf("\n"); system("pause"); }
C
#include <stdio.h> typedef struct //三階方陣結構 { float element[3][3]; }matrix; const matrix I = {1,0,0,0,1,0,0,0,1}; //三階單位矩陣 float three_det(matrix A); //三階方陣行列式 //........................三階方陣的加減乘.........................// matrix matrix_add(matrix A, matrix B); //三階方陣加法 matrix matrix_sub(matrix A, matrix B); //三階方陣減法 matrix coe_multi(matrix A, float c); //三階方陣乘係數 matrix matrix_multi(matrix A, matrix B); //兩個三階方陣相乘 //.................................................................// void print_matrix(matrix A); //印出三階方陣 matrix inv(matrix A); //三階方陣反矩陣(根據Cayley-Hamilton定理) void find_LU(matrix A, matrix *L, matrix *U); //尋找LU矩陣
C
#include<stdio.h> #include<string.h> int x; int main(){ char str_arr[20][20]={"water","air","milk","coffee"}; for(int i=0;i<10;i++){ for(int j=0;j<10;j++){ printf("%c",str_arr[i][j]); } printf("\n"); } return 0; }
C
/** ****************************************************************************** * File Name : main.h * Description : This file contains the common defines of the application ****************************************************************************** */ #ifndef __MAIN_H #define __MAIN_H /* Includes ------------------------------------------------------------------*/ #include <stdint.h> #include <string.h> #include <stdio.h> #include "board.h" /* FreeRTOS+CLI definitions. */ /* Dimensions a buffer into which command outputs can be written. The buffer * can be declared in the CLI code itself, to allow multiple command consoles to * share the same buffer. For example, an application may allow access to the * command interpreter by UART and by Ethernet. Sharing a buffer is done purely * to save RAM. Note, however, that the command console itself is not re-entrant, * so only one command interpreter interface can be used at any one time. For * that reason, no attempt at providing mutual exclusion to the buffer is * attempted. */ #define configCOMMAND_INT_MAX_OUTPUT_SIZE 512 /* Dimensions the buffer into which input characters are placed. */ #define cmdMAX_INPUT_SIZE 60 /* DEL acts as a backspace. */ #define cmdASCII_DEL (0x7F) /* Const messages output by the command console. */ #define pcWelcomeMessage "FreeRTOS CLI server.\r\nEnter 'help' to view a list of available commands.\r\n\r\n>>\r\n" #define pcEndOfOutputMessage "\r\n[Press ENTER to execute the previous command again]\r\n>>\r\n" #define pcNewLine "********************************************************************************\r\n" /* */ #define ENCODER_PB ( 1 << 0 ) // push button #define ENCODER_FW ( 1 << 1 ) // forward rotation #define ENCODER_BW ( 1 << 2 ) // backward rotation void _Error_Handler(char *, int); #define Error_Handler() _Error_Handler(__FILE__, __LINE__) #endif /* __MAIN_H */
C
#include <stdio.h> #define true 1 #define false 0 #define is_leaf(n)\ { ((n == NULL) ? true : false) } int main() { char* c = NULL; int bools = is_leaf(c); printf("result : %s\n", is_leaf(c) ? "true" : "false"); return 0; }
C
#include "array.h" #include <stdio.h> #include <malloc.h> int main (void){ Array a = array_new(10); for (int i = 0; i < 100; i++){ array_insertBack(&a, 2); } array_print(a); array_destroy(a); return 0; }
C
#include <stdio.h> #include <math.h> #include <cs50.h> int main(int argc, const char * argv[]) { float total = 0, cents, change; int quarters = 0, dimes = 0, nickels = 0, pennies = 0; printf("How much change are you owed? \n"); change = GetFloat(); if (change <= .0) { printf("Bogus amount, try again:\n"); change = GetFloat(); } cents = (int) round(change * 100); do { //nested do-while loop. while (cents >= 25) { cents = cents - 25; quarters++; total++; } while (cents >= 10) { cents = cents - 10; dimes++; total++; } while (cents >= 5) { cents = cents - 5; nickels++; total++; } while (cents >= 1) { cents = cents - 1; pennies++; total++; } } while (cents!=0); { } printf("%.f\n", total++); return 0; }
C
#include <stdio.h> #include <sys/time.h> #include "timebreak.h" /* Created for us by rpcgen - has everything we need ! */ int timebreak( CLIENT *clnt, long *sec) { int *result; result = timebreak_1(sec,clnt); if (result==NULL) { fprintf(stderr,"Trouble calling remote procedure timebreak\n"); exit(0); } return(*result); } long int getTimeout(CLIENT *clnt){ int *result; result = connect_1(NULL,clnt); if (result==NULL) { fprintf(stderr,"Trouble calling remote procedure connect\n"); exit(0); } // get timeout struct timeval tv; clnt_control(clnt, CLGET_TIMEOUT, &tv); printf("%li\n", tv.tv_sec); long int timeout = tv.tv_sec; return(timeout); } int main( int argc, char *argv[]) { CLIENT *clnt; if (argc!=2) { fprintf(stderr,"Usage: %s hostname \n",argv[0]); exit(0); } clnt = clnt_create(argv[1], TIMEBREAK_PROG, TIMEBREAK_VERSION, "tcp"); /* Make sure the create worked */ if (clnt == (CLIENT *) NULL) { clnt_pcreateerror(argv[1]); exit(1); } long int i = getTimeout(clnt); timebreak(clnt, &i); return(0); }
C
#include <fcntl.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #define MAX_NUM 50000 // Dealing with the array void swap(int *xp, int *yp); void printArray(); void writeArray(char *file); void generateArray(); // Dealing with the threads + mutex for accessing global arr void *minSelectionSort(); void *maxSelectionSort(); pthread_mutex_t arr_mutex = PTHREAD_MUTEX_INITIALIZER; void normalSelectionSort(); int *arr; int main() { srand(time(NULL)); arr = malloc(sizeof(int[MAX_NUM])); printf("Created new array of %d integer values \n", MAX_NUM); generateArray(); clock_t begin = clock(); /* pthread_t threads[2]; pthread_create(&threads[1], NULL, minSelectionSort, NULL); pthread_create(&threads[2], NULL, maxSelectionSort, NULL); pthread_join(threads[1], NULL); pthread_join(threads[2], NULL); */ normalSelectionSort(); clock_t end = clock(); printf("Time to sort array: %f seconds\n", (double)(end - begin) / CLOCKS_PER_SEC); writeArray("sort.txt"); return 0; } void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } void generateArray(){ int i = 0; for(i; i < MAX_NUM; i++) { arr[i] = MAX_NUM-i; } writeArray("orig.txt"); for(i = MAX_NUM-1; i >= 0 ; i--) { int r = (rand() % MAX_NUM); int s = (rand() % MAX_NUM); swap(&arr[r], &arr[s]); } writeArray("shuf.txt"); } void writeArray(char* file) { umask(0); FILE* des = fopen(file, "w"); //using FOPEN to use FPRINTF // fopen validation - remove if not wanted/needed if(des < 0) { printf("Open File Error\n"); exit(0); } lseek((long)des, 0, SEEK_SET); int i; printf("Writing to \"%s\"...", file); for(i =0; i<MAX_NUM; i++) { lseek((long)des, 0, SEEK_CUR); char str[20]; //string buffer sprintf(str, "%d: %d", i, arr[i]); //format string to print fprintf(des, "%s\n", str); //print str to file } fclose(des); printf("Complete\n"); } void printArray() { int i; for(i = 0; i < MAX_NUM; i++) { printf("%d, ", arr[i]); } printf("\n"); } void *minSelectionSort() { /* GOAL: * This thread will find the minimal value in the array, and * place it at the min_index */ int i, j, min_index; int min = MAX_NUM+1; for(i = 0; i < min/2; i++) { //pthread_mutex_lock(&arr_mutex); min_index = i; for(j = i+1; j < MAX_NUM; j++){ if(arr[j] < arr[min_index]){ min_index = j; } } //printf("Minimum value %d, placing at front \n", arr[min_index], arr[i]); pthread_mutex_lock(&arr_mutex); swap(&arr[min_index], &arr[i]); //printArray(); pthread_mutex_unlock(&arr_mutex); } } void *maxSelectionSort() { /* GOAL: * This thread will find the maximal value in the array, and * place it at the max_index */ int i, j, max, max_index; int final = MAX_NUM+1; for (i = MAX_NUM-1; i > 0; i--) { //pthread_mutex_lock(&arr_mutex); max = arr[i]; max_index = i; for (j = 0; j < i; j++) { if (arr[j] > max) { max = arr[j]; max_index = j; } } if (max > arr[i]) { pthread_mutex_lock(&arr_mutex); //printf("Maximum value %d, placing at end \n", arr[max_index], arr[i]); swap(&arr[max_index], &arr[i]); //printArray(); pthread_mutex_unlock(&arr_mutex); } //pthread_mutex_unlock(&arr_mutex); } } void normalSelectionSort(){ /* GOAL: * This thread will find the minimal value in the array, and * place it at the min_index */ int i, j, min_index; int min = MAX_NUM+1; for(i = 0; i < min; i++) { //pthread_mutex_lock(&arr_mutex); min_index = i; for(j = i+1; j < MAX_NUM; j++){ if(arr[j] < arr[min_index]){ min_index = j; } } //printf("Minimum value %d, placing at front \n", arr[min_index], arr[i]); swap(&arr[min_index], &arr[i]); //printArray(); } }
C
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <math.h> #include <pthread.h> # define MAX_THREADS 16 # define INTEGRAL_TOP 1 # define INTEGRAL_BOTTOM 0 static int id; pthread_t threads[MAX_THREADS]; double pi_parts[MAX_THREADS]; /* Formula for PI calculation */ double formula(double x) { return (4 * atan(x)); } /* Singlethread PI number calculation */ double singlethread_pi(void) { return (formula(INTEGRAL_TOP) - formula(INTEGRAL_BOTTOM)); } /* Multithread PI number calculation */ void iterate_pi(void) { static double start; static double end; start = (double)id * (INTEGRAL_TOP - INTEGRAL_BOTTOM) / MAX_THREADS; end = (double)(id + 1) * (INTEGRAL_TOP - INTEGRAL_BOTTOM) / MAX_THREADS; pi_parts[id] = formula(end) - formula(start); id++; } double multithread_pi(void) { int i; double result; i = 0; result = 0.0; while (i < MAX_THREADS) { pthread_create(&threads[i], NULL, (void *(*)(void *))iterate_pi, NULL); pthread_join(threads[i], NULL); i++; } i = 0; while (i < MAX_THREADS) { result += pi_parts[i]; i++; } return (result); } int main() { printf("Singlethread PI = %.10f\n", singlethread_pi()); printf("Multithread PI = %.10f", multithread_pi()); return (0); }
C
#include "clientUtils.h" void Handshake(const int *sockPtr, struct addrinfo *servAddr, Pacote **pacote){ send_msg(sockPtr, servAddr, pacote, SYN); recv_msg(sockPtr, servAddr, pacote); send_msg(sockPtr, servAddr, pacote, ACK); } void recv_msg(const int *sockPtr, struct addrinfo *servAddr, Pacote **pkt){ Pacote* pacote = malloc(sizeof(Pacote)); socklen_t servAddrLen = sizeof(*servAddr); char buffer[20] = "\0"; ssize_t numBytesRcvd = recvfrom(*sockPtr, buffer, sizeof(Pacote), 0, (struct sockaddr *) servAddr, &servAddrLen); if (numBytesRcvd < 0){ DieWithSystemMessage("recvfrom() falhou"); } Decode(buffer, numBytesRcvd, pacote, NONE); fprintf(stdout, "[RECV] SEQ = %d, ACK = %d, ID = %d, %d", pacote->sequenceNumber, pacote->ACKNumber, pacote->connID, pacote->flags); **pkt = *pacote; } void send_msg(const int *sockPtr, struct addrinfo *servAddr, Pacote **pacote, Flags flag){ Pacote *pkt; switch (flag){ case SYN: pkt = constroiPacote(INIT_SEQ_CLIENT, 0, 0, SYN, NULL); break; case ACK: pkt = constroiPacote(INIT_SEQ_CLIENT + 1, (*pacote)->sequenceNumber + 1, (*pacote)->connID, ACK, NULL); break; case FIN: pkt = constroiPacote((*pacote)->ACKNumber, 0, (*pacote)->connID, FIN, NULL); break; default: break; } uint8_t outbuf[sizeof(Pacote)]; size_t reqSize = Encode(pkt, outbuf, sizeof(Pacote), 0, NONE); ssize_t numBytes = sendto(*sockPtr, outbuf, reqSize, 0, servAddr->ai_addr, servAddr->ai_addrlen); if (numBytes < 0) DieWithSystemMessage("sendto() falhou"); else if (numBytes != reqSize) DieWithUserMessage("sendto() error", "enviou número inexperado de bytes"); **pacote = *pkt; } void UDPSocketClient(char *port, char *hostname, int* const sockPtr, struct addrinfo **servAddrPtr){ struct addrinfo addrCriteria; memset(&addrCriteria, 0, sizeof(addrCriteria)); addrCriteria.ai_family = AF_UNSPEC; addrCriteria.ai_socktype = SOCK_DGRAM; addrCriteria.ai_protocol = IPPROTO_UDP; struct addrinfo *servAddr; int rtn = getaddrinfo(hostname, port, &addrCriteria, &servAddr); if(rtn != 0) DieWithUserMessage("getaddrinfo() falhou", gai_strerror(rtn)); int sock = socket(servAddr->ai_family, servAddr->ai_socktype, servAddr->ai_protocol); if (sock < 0) DieWithSystemMessage("socket() falhou"); *sockPtr = sock; *servAddrPtr = servAddr; } void sendUDP(char *filename, const int *sockPtr, struct addrinfo *servAddr, Pacote **pacote, Flags flag){ Pacote *pkt; char buffer[MAXSTRINGLENGTH] = "\0"; size_t bufferLen; FILE *file; file = fopen(filename, "r"); machineStates estado = NONE; switch (flag) { case SYN: bufferLen = strlen(buffer); pkt = constroiPacote(INIT_SEQ_CLIENT, 0, 0, SYN, constroiPayload(buffer, bufferLen)); estado = NONE; break; case ACK: //fgets(buffer, MAXSTRINGLENGTH, file); bufferLen = strlen(buffer); pkt = constroiPacote((*pacote)->ACKNumber, (*pacote)->sequenceNumber + 1, (*pacote)->connID, ACK, constroiPayload(buffer, bufferLen)); estado = NONE; break; default: break; } uint8_t outbuf[BUFSIZE]; // fprintf(stdout, "SEQ = %d, ACK = %d, ID = %d, %d", pkt->sequenceNumber, // pkt->ACKNumber, pkt->connID, pkt->flags); size_t reqSize = Encode(pkt, outbuf, BUFSIZE, bufferLen, estado); ssize_t numBytes = sendto(*sockPtr, outbuf, reqSize, 0, servAddr->ai_addr, servAddr->ai_addrlen); if (numBytes < 0) DieWithSystemMessage("sendto() falhou"); else if (numBytes != reqSize) DieWithUserMessage("sendto() error", "enviou número inexperado de bytes"); **pacote = *pkt; //return estado; } void recvUDP(const int *sockPtr, struct addrinfo *servAddr, Pacote **pkt, Flags flag){ Pacote* pacote = malloc(sizeof(Pacote)); socklen_t servAddrLen = sizeof(*servAddr); machineStates state = NONE; char buffer[BUFSIZE] = "\0"; ssize_t numBytesRcvd = recvfrom(*sockPtr, buffer, BUFSIZE, 0, (struct sockaddr *) servAddr, &servAddrLen); if (numBytesRcvd < 0){ DieWithSystemMessage("recvfrom() falhou"); } switch (flag) { case SYN_ACK: Decode(buffer,numBytesRcvd, pacote, state); break; // case ACK: // state = EXIT; //não é permanente // default: break; } //Decode(buffer,numBytesRcvd, pacote, state); **pkt = *pacote; }
C
#include<math.h> #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include"rdm.h" #define I 5.644079999999997 //compute integral of 6-x^2-y^2-z^2-u^2-v^2 double f(double x,double y,double z,double u,double v) { return 6.-x*x-y*y-z*z-u*u-v*v; } int main() { //prepare a file to write data FILE* integral=NULL; integral=fopen("multi_variable.txt","w+"); fprintf(integral,"N\tIntegral\tErr\t1/sqrt(N)\n"); int N=0; double sum=0;//sum over f(xi) double x[5]={9/10.0, 4/5.0, 9/10.0, 2.0, 13/10.0};//generate random numbers in [0,x[i]] for(int i=1;i<=7;i++){ sum=0; N=(int) pow(10,i); //N=10,100,1000,..,10^7 double* xi; xi=(double*)malloc(sizeof(double)*5*N); rdm(5*N,xi,1); for(int j=0;j<5*N;j+=5) { sum+=f(x[j%5]*xi[j],x[(j+1)%5]*xi[j+1],x[(j+2)%5]*xi[j+2],x[(j+3)%5]*xi[j+3], x[(j+4)%5]*xi[j+4])*x[0]*x[1]*x[2]*x[3]*x[4]; } fprintf(integral,"%8d\t%.8e\t%.8e\t%.8e\n",N,sum/N,fabs(sum/N-I),1/sqrt(N)); free(xi); } fclose(integral); return 0; }
C
/* Este programa serve para ilustrar algumas funcionalidades da biblioteca ncurses, que é uma versão para Linux mais poderosa que a coino do windows. Ela serve para criar displays que podem servir, mais adiante, para criação d jogos simples. Será utilizada no trabalho final da cadeira de Algoritmos e Programação. No momento de compilar, usar: gcc tela.c -o tela -lncurses -lm, para poder acessar as funções da biblioteca - aqui,tanto a curses como a math. */ #include <stdio.h> #include <ncurses.h> #include <curses.h> #include <math.h> #define SAIDA 0 int main(){ char entrada = 'a'; int x, y, i; initscr(); //Cria uma tela. //raw(); //keypad(stdscr, TRUE); cbreak(); //Permite sair da tela com ctrl+z, o que ajuda muito enquanto estiver testando coisas //printw("Teste"); //getch(); //Serve para ler um caracter do teclado, mas, também serve para que o programa não rode antes de o usuário clicar qualquer coisa. //if(getch() == KEY_UP) printw("UP"); //Abaixo, eu fiz uma idiotice para mostrar como é possível animar coisas utilizando essa biblioteca. Certamente existem outras formas, mas essa eu criei agora e funciona. //Bola 1________________________________________________________________________________________ for(int j = 0; j < 50; j++){ for(i = 0; i < 100; i++) mvprintw(11 + 8*sin(i), 11 + 8*cos(i) + j, "."); //Cria um desenho getch(); for(i = 0; i < 100; i++){ //Cria o mesmo desenho, pr cima do anterior, ma invisível. attron(A_INVIS); mvprintw(11 + 8*sin(i), 11 + 8*cos(i) + j, "."); attroff(A_INVIS); } getch(); for(i = 0; i < 100; i++) mvprintw(11 + 8*sin(i), 11 + 8*cos(i) + j+1, "."); //Cria o mesmo desenho, visível, um pixel adiante. } //Repete a ação acima, só pra fazer um desenho idiota. //Bola 2________________________________________________________________________________________ for(int j = 0; j < 50; j++){ for(i = 0; i < 100; i++) mvprintw(31 + 8*sin(i), 11 + 8*cos(i) + j, "."); getch(); for(i = 0; i < 100; i++){ attron(A_INVIS); mvprintw(31 + 8*sin(i), 11 + 8*cos(i) + j, "."); attroff(A_INVIS); } getch(); for(i = 0; i < 100; i++) mvprintw(31 + 8*sin(i), 11 + 8*cos(i) + j+1, "."); } //move(10, 20); //Isso apenas moveria o cursor para essa posição. getch(); for (i = 0; i < 50; i++){ mvprintw(15, 67+i, "."); getch(); /*attron(A_STANDOUT); mvprintw(15, 65+i, "."); attroff(A_STANDOUT); //getch(); mvprintw(15, 65+i, "."); //getch();*/ } for (i = 0; i < 50; i++){ mvprintw(24, 65+i, "."); //getch(); } for (i = 0; i < 1000; i++){ mvprintw(20 + 4*sin(i/200.),120 + 4*cos(i/100.), "."); //getch(); } for(i = 0; i < 5; i++) getch(); endwin(); //Sempre fechar a janela que criou! return 0; }
C
#include <math.h> #include <stdio.h> #include "tad_lista.h" #include <stdlib.h> struct lista{ int qtd;//quem diferencia a lista de um vetor. Com ela //controlamos em tempo de execução quantos elementos nossa lista possui int tam_inicial;//vai guardar o tamanho inicial int aux;//vai guardar a atualização do tamanho inicial struct aluno *dados; }; Lista* cria_lista(int qtd_inicial){ Lista *li=calloc(1, sizeof(Lista));//caso dê falha, retorna NULL; if(li!=NULL) li->qtd=0;//iniciando o TAD com a lista com 0 elementos li->tam_inicial=qtd_inicial; li->aux=li->tam_inicial; li->dados=calloc(qtd_inicial,sizeof(struct aluno)); return li; } void libera_lista(Lista*li){ free(li->dados); free(li); } int consulta_lista_pos(Lista*li, int pos, struct aluno *al){ //retorna um inteiro para verificação, e passa os dados do aluno para um ponteiro do tipo aluno; if(li==NULL || pos <= 0 || pos>li->qtd) return -1; *al=li->dados[pos-1]; //copiando para *al o conteúdo daquela posição passada return 0; } int consulta_lista_mat(Lista* li, int mat, struct aluno *al){//consulta os dados da lista pela matricula passada e copia para struct aluno os dados da matricula consultada if(li==NULL) return -1; int i = 0; while(i<li->qtd && li->dados[i].matricula != mat) i++; if( i == li->qtd)//elemento não encontrado return -1; *al=li->dados[i]; return 0; } int insere_lista_final(Lista* li, struct aluno al){ int aux=li->tam_inicial; if(li==NULL) return -1; if(li->qtd==li->aux){ li->aux+=aux; li->dados=realloc(li->dados, li->aux * sizeof(struct aluno)); if(li->dados==NULL) return -1; } li->dados[li->qtd]=al; li->qtd++; return 0; } int insere_lista_inicio(Lista*li, struct aluno al){ int aux=li->tam_inicial; if(li==NULL) return -1; if(li->qtd==li->aux){ li->aux+=aux; li->dados=realloc(li->dados, li->aux * sizeof(struct aluno)); if(li->dados==NULL) return -1; } int i; for(i=li->qtd; i>=0; i--) li->dados[i+1]=li->dados[i]; li->dados[0]=al; li->qtd++; return 0; } int insere_lista_ordenada(Lista* li, struct aluno al){ int aux=li->tam_inicial; if(li==NULL) return -1; if(li->qtd==li->aux){ li->aux+=aux; li->dados=realloc(li->dados, li->aux * sizeof(struct aluno)); if(li->dados==NULL) return -1; } int k, i =0; while(i<li->qtd && li->dados[i].matricula<al.matricula) i++; for(k=li->qtd-1; k>=i; k--) li->dados[k+1] = li->dados[k]; li->dados[i]=al; li->qtd++; return 0; } int compactar_lista(Lista* li){ if(li==NULL) return -1; int num = ceil(li->qtd/ li->tam_inicial) * li->tam_inicial; if (li->qtd > num) li->dados = realloc(li->dados, num * sizeof(struct aluno)); return 0; li->aux=num; } int remove_lista(Lista *li, int mat){ if(li==NULL) return -1; if(li->qtd == 0) return -1; int k, i=0; while(i<li->qtd && li->dados[i].matricula !=mat) i++; if(i==li->qtd)//elemento não encontrado return 0; for(k=i; k<li->qtd-1; k++) li->dados[k]=li->dados[k+1]; li->qtd--; return 0; } int remove_lista_otimizado(Lista *li, int mat){ if(li==NULL) return -1; if(li->qtd == 0) return -1; int i=0; while(i<li->qtd && li->dados[i].matricula !=mat) i++; if(i==li->qtd)//elemento não encontrado return 0; li->qtd--; li->dados[i] = li->dados[li->qtd]; return 0; } int remove_lista_inicio(Lista *li){ if(li==NULL) return -1; if(li->qtd==0) return -1; int k = 0; for(k=0; k<li->qtd-1; k++) li->dados[k]=li->dados[k+1]; li->qtd --; return 0; } int remove_lista_final(Lista*li){ if(li==NULL) return -1; if(li->qtd==0) return -1; li->qtd--; return 0; } int tamanho_lista(Lista*li){ if(li==NULL) return -1; else return li->qtd; } int lista_cheia(Lista*li){ if(li==NULL) return -1; return (li->qtd==li->tam_inicial); } int lista_vazia(Lista *li){ if(li==NULL) return -1; return (li->qtd == 0); } int imprime_lista(Lista* li){ if(li==NULL) return -1; int i; for(i=0;i<li->qtd; i++){ printf("Matricula: %d\n",li->dados[i].matricula); printf("Nome: %s\n",li->dados[i].nome); printf("Notas: %f %f %f\n", li->dados[i].n1, li->dados[i].n2,li->dados[i].n3); printf("----------------------------------\n"); } return 0; }
C
// // main.c // quick_sort // // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #include <stdio.h> #include <time.h> int quick_sort(int array[], int p, int r); int partition(int array[], int p, int q); int quick_sort(int array[], int p, int r) { if (p < r) { int q = partition(array, p, r); quick_sort(array, p, q-1); quick_sort(array, q+1, r); } return 0; } int partition(int array[], int p, int q) { int x = array[p]; int i = p; for (int j = p + 1; j <= q; j++) { if (array[j] <= x) { i = i + 1; int tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } int tmp = array[p]; array[p] = array[i]; array[i] = tmp; return i; } int a[10000000]; int main (int argc, const char * argv[]) { int n = 0; int i = 0; while (scanf("%d", &a[n]) != EOF) n++; int t1 = clock(); quick_sort(a, 0, n-1); int t2 = clock(); printf("%d\n",t2-t1); //for (i = 0; i < n; i++) // printf("%d\n", a[i]); return 0; }
C
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<malloc.h> #include<math.h> char operation[6][10]={"FILL(1)","FILL(2)","DROP(1)","DROP(2)","POUR(1,2)","POUR(2,1)"}; struct queue{ int a; int b; int fa; int step; char op[10]; }q[1000000]; int v[105][105]; int main(){ int num1,num2,c; while(~scanf("%d%d%d",&num1,&num2,&c)){ int head,tail; head=0; tail=0; q[head].a=0; q[head].b=0; q[head].fa=-1; q[head].step=0; q[head].op[0]='\0'; v[q[head].a][q[head].b]=1; tail++; int flag; int i,j; flag=0; while(head<tail){ //printf("1\n"); if(q[head].a!=num1&&v[num1][q[head].b]==0){ v[num1][q[head].b]=1; q[tail].a=num1; q[tail].b=q[head].b; q[tail].fa=head; q[tail].step=q[head].step+1; strcpy(q[tail].op,operation[0]); tail++; if(q[tail-1].a==c||q[tail-1].b==c){ flag=1; break; } } if(q[head].b!=num2&&v[q[head].a][num2]==0){ v[q[head].a][num2]=1; q[tail].b=num2; q[tail].a=q[head].a; q[tail].fa=head; q[tail].step=q[head].step+1; strcpy(q[tail].op,operation[1]); tail++; if(q[tail-1].a==c||q[tail-1].b==c){ flag=1; break; } } if(q[head].a!=0&&v[0][q[head].b]==0){ v[0][q[head].b]=1; q[tail].a=0; q[tail].b=q[head].b; q[tail].fa=head; q[tail].step=q[head].step+1; strcpy(q[tail].op,operation[2]); tail++; if(q[tail-1].a==c||q[tail-1].b==c){ flag=1; break; } } if(q[head].b!=0&&v[q[head].a][0]==0){ v[q[head].a][0]=1; q[tail].b=0; q[tail].a=q[head].a; q[tail].fa=head; q[tail].step=q[head].step+1; strcpy(q[tail].op,operation[3]); tail++; if(q[tail-1].a==c||q[tail-1].b==c){ flag=1; break; } } if(q[head].a!=0){ int t1=q[head].a; int t2=q[head].b; while(t1!=0&&t2<num2){ t1--; t2++; } if(v[t1][t2]==0){ v[t1][t2]=1; q[tail].a=t1; q[tail].b=t2; q[tail].fa=head; q[tail].step=q[head].step+1; strcpy(q[tail].op,operation[4]); tail++; if(q[tail-1].a==c||q[tail-1].b==c){ flag=1; break; } } } if(q[head].b!=0){ int t1=q[head].a; int t2=q[head].b; while(t2!=0&&t1<num1){ t2--; t1++; } if(v[t1][t2]==0){ v[t1][t2]=1; q[tail].a=t1; q[tail].b=t2; q[tail].fa=head; q[tail].step=q[head].step+1; strcpy(q[tail].op,operation[5]); tail++; if(q[tail-1].a==c||q[tail-1].b==c){ flag=1; break; } } } head++; //printf("%d %d\n",head,tail); } int move[100000]; if(flag){ printf("%d\n",q[tail-1].step); int t=0; //move[0]=q[tail].fa; int p=tail-1; for(t=0;t<q[tail-1].step;t++){ move[t]=p; //printf("%d %d\n",p,t); //t++; p=q[p].fa; } for(t=t-1;t>=0;t--){ //t--; printf("%s\n",q[move[t]].op); //t--; } //printf("%s\n",q[move[t]].op); } else printf("impossible\n"); for(i=0;i<101;i++){ for(j=0;j<101;j++){ v[i][j]=0; } } } return 0; }
C
bool isSubsequence(char * s, char * t){ for (int i = 0; i < strlen(t); i++) { if (*s == t[i]) s++; } return *s == '\0'; }
C
#include <stdio.h> #include <stdlib.h> #include "include/queue.h" void main() { int i; Initqueue(); printf("the queue is empty? %d\n",is_empty()); enqueue(1); enqueue(2); enqueue(4); printf("the queue is empty? %d\n",is_empty()); printf("the length of queue is :%d\n",queuetraverse()); printf("top number in the queue is %d\n",gethead()); printf("dequeue number is %d\n",dequeue()); Destroyqueue(); printf("the queue is empty? %d\n",is_empty()); }
C
#include <stdio.h> int main() { int num[10]={1,5,9,4,8,3,0,2,6,7},*a,*b; a=&num[2];//storing the address of num[2] in variable a b=&num[6];//storing the address of num[6] in variable b printf("a = %d\n",a); printf("b = %d\n",b); printf("a-b = %d\n",b-a);//prints the number of elements between the two elements indicated by the pointers printf("*a-*b = %d\n",*a-*b);//prints the difference in value of the two elements return 0; }
C
# include <stdio.h> # include <sys/types.h> # include <sys/stat.h> # include <unistd.h> # include <fcntl.h> # include "../../sb.h" main (int argc, char *argv[] ) { int fd , acc_no; Account acc; if ( argc != 2 ) do_exit ( 1, "Usage: balance <acc_no> \n" ); fd = open ( "info.data", O_RDONLY ); acc_no = atoi ( argv[1] ); if ( fd < 0 ) printf ( "open failed\n" ); lseek ( fd, (acc_no -1 ) * sizeof ( acc ), SEEK_SET ); read ( fd, &acc, sizeof ( acc ) ); if ( acc_no != acc.acc_no ) do_exit ( 2, "No user with account no \n" ); printf ( "%d %s %s %d\n", acc.acc_no, acc.name, acc.phone, acc.balance ); close ( fd ); return 0; }
C
#include <planck/kmalloc.h> #include <arch/earlyoutput.h> #include <stdint.h> #include <string.h> extern void *__brk_base, *__brk_limit; static uintptr_t brk_base; static uintptr_t brk_limit; void KiAllocInitialize() { brk_base = (uintptr_t)&__brk_base; brk_limit = (uintptr_t)&__brk_limit; } void *malloc(size_t size) { uintptr_t ptr = brk_base; brk_base += size; if (brk_base > brk_limit) KeEarlyOutput("WARNING: sbrk limit reached!"); return (void *)ptr; } void *malloc_page_aligned(size_t size) { uintptr_t ptr = brk_base; ptr &= 0xfffffffffffff000; ptr += 0x1000; brk_base += ptr - brk_base + size; if (brk_base > brk_limit) KeEarlyOutput("WARNING: sbrk limit reached!"); return (void *)ptr; } void *realloc(void *address, size_t size) { return NULL; } void *calloc(size_t size) { void *ptr = malloc(size); memset(ptr, 0, size); return ptr; } void free(void *address) { if (address >= brk_base && address <= brk_limit) return; }
C
/** * @brief It implements the set * * @file set.c * @author Julia Simon y Miguel Rodriguez * @version 1.0 * @date 14-02-2018 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../include/set.h" /** * @brief Estructura del set */ struct _Set { Id id[MAX_ID]; /*!< identificador del objeto */ int nId; /*!< numero de ids */ }; Set* set_create() { Set *newSet = NULL; int i=0; newSet = (Set *) malloc(sizeof (Set)); if (newSet == NULL) return NULL; for(i=0; i<MAX_ID;i++){ newSet->id[i] = 0; } newSet->nId = 0; return newSet; } STATUS set_destroy(Set* set) { if (!set) return ERROR; free(set); set = NULL; return OK; } Id set_get_Id(Set * set, int i){ if(!set || i > set->nId || i < 0) return NO_ID; return set->id[i]; } int set_get_nId(Set* set){ if(!set) return -1; return set->nId; } size_t set_get_size(){ return sizeof(struct _Set); } STATUS set_add(Set* set, Id id){ if(set == NULL || id == NO_ID) return ERROR; set->id[set->nId] = id; set->nId++; return OK; } STATUS set_del(Set* set, Id id){ int i = 0, j = 0; if(set == NULL || id == NO_ID) return ERROR; for(i=0; i<set->nId; i++){ if(set->id[i] == id){ for(j=i; j<set->nId; j++){ set->id[j] = set->id[j+1]; } set->nId--; } } return OK; } STATUS set_print(Set* set) { int i = 0; if (!set) return ERROR; fprintf(stdout, "--> set (nId: %d)\n", set->nId); if(set->nId == 0) return OK; fprintf(stdout, "--> set (Id: "); for(i=0; i<set->nId; i++) fprintf(stdout, "%ld ",set->id[i]); fprintf(stdout, ")\n"); return OK; }
C
#include <stdio.h> //To convert Centigrade to Fahrenheit void main() { float Ct,Fh; printf("Enter the Temperature in Centigrade:\n"); scanf("%f",&Ct); Fh=(Ct*1.8)+32.0; printf("The Temperature in Fahrenheit:%f",Fh); }
C
#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> /** * @Author Megan Thomas & Cody Krueger * @Date 24 SEP 2018 * CIS 457 Data Comm * PRJ 1-A UDP Echo Client with Sliding Window * **/ int isValidIpAddress(char *ipAddress); int main(int argc, char **argv){ //Create Socket int sockfd = socket(AF_INET,SOCK_DGRAM,0); if (sockfd<0){ printf("There was an ERROR(1) creating the socket\n"); //**does a n\ cause a problem here? return 1; } //Port Num printf("Port Number: "); char sPort[1000]; fgets(sPort, 1000, stdin); int portNum = atoi (sPort); //for testing --------------- ** // int portNum = 9874; // printf("9874 \n"); if(portNum < 1023 || portNum > 49152){ printf("Try again with valid port number\n"); return 0; } //IP Address printf("IP Address: "); char addr[100]; fgets(addr, 100, stdin); char *pos; if ((pos=strchr(addr, '\n')) != NULL){ *pos = '\0'; } //for testing --------------- ** // char addr[] = "127.0.0.1"; // printf("%s \n", addr); if(!(isValidIpAddress(addr))){ printf("Try again with a valid IP address\n"); return 0; } //Socket Struct struct sockaddr_in serveraddr; serveraddr.sin_family = AF_INET; serveraddr.sin_port = htons(portNum); serveraddr.sin_addr.s_addr=inet_addr(addr); //File Request unsigned int len = sizeof(serveraddr); printf("File: "); char fName[1000]; fgets(fName, 1000, stdin); //char *pos; if ((pos=strchr(fName, '\n')) != NULL){ *pos = '\0'; } sendto(sockfd,fName,strlen(fName)+1, 0,(struct sockaddr*)&serveraddr, len); //New File Creation printf("New file name: "); char newFName[1000]; fgets(newFName, 1000, stdin); if ((pos=strchr(newFName, '\n')) != NULL){ *pos = '\0'; } FILE* newFile; newFile = fopen(newFName, "w+"); // fclose(newFile); //Recieving Data int packetSize = 1001; int numBytes; //char fContents[10]; char* fContents; char ident = 'a'; fContents = (char*)malloc(packetSize*sizeof(char)); int count = 0; while (0 < (numBytes = recvfrom(sockfd, fContents, packetSize+1, 0,(struct sockaddr*)&serveraddr, &len))) { //printf("%s\n", fContents ); newFile = fopen(newFName, "a"); //fputs(fContents, newFile); fwrite(fContents+1, 1, numBytes-1, newFile); fclose(newFile); // ident = fContents[0]; // printf("%c", ident); // //reply for packet recieved // sendto(sockfd, ident, 1, 0,(struct sockaddr*)&serveraddr, len); free(fContents); char* fContents; fContents = (char*)malloc(packetSize*sizeof(char)); } free(fContents); close(sockfd); } //method to check if a string is an valid ip address //source: https://stackoverflow.com/questions/791982/determine-if-a-string-is-a-valid-ipv4-address-in-c int isValidIpAddress(char *ipAddress) { struct sockaddr_in sa; int result = inet_pton(AF_INET, ipAddress, &(sa.sin_addr)); return result != 0; } /** //Sliding Window------------------------------------------------- //Window char min_c = '0'; char max_c = '4'; int MIN = 0; int MAX = 4; while (min_c < packetNum < max_c) { //recieve packets TODO if (packetNum == min_c) { //send ack TODO //adjust window bounds MIN++; MAX++; min_c = (MIN%10) + 48; max_c = (MAX%10) + 48; } //for v2 //if duplicate packet (ie below min) //discard packet and resend ack for recieved packet } //------------------------------------------------------------ **/
C
#include <wiringPi.h> #define DEL 10 void clear() { for (int i = 0; i < 8; i++) { digitalWrite(i, LOW); delay(DEL); } } void range(int time) { for (int i = 0; i< 8; i++) { digitalWrite(i, HIGH); delay(time); digitalWrite(i, LOW); delay(time); } } void blinkAll(int time) { for (int i = 0; i < 8; i++) { digitalWrite(i, HIGH); } delay(time); } int main (void) { wiringPiSetup (); clear(); while(1) { range(500); blink(1000); } return 0; }
C
/* * ===================================================================================== * * Filename: struct_rational.c * * Description: 结构体习题2-有理数结构体 * * Version: 1.1 * Created: Tuesday, December 31, 2013 09:45:45 CST * Revision: none * Compiler: gcc * * Author: Li_Mao (lm), cfanmaoli@gmail.com * Organization: * * ===================================================================================== */ #include <stdio.h> #include <math.h> struct rational { long int x,y; }; long int get_gdc(long int a, long int b) /* 注意调用的时候传0进来 */ { long int c; if(a<0 || b<0) { a = labs(a); b = labs(b); } if(a < b) { c = a; a = b; b = c; } if(a%b == 0) { return b; } else return get_gdc(b, a%b); } struct rational make_rational(long int a, long int b) { struct rational c; if(b < 0) { b = -b; a = -a; } if(a == 0) { c.x = a; c.y = b; } else { long int gdc; gdc = get_gdc(a, b); if(gdc == 1) { c.x = a; c.y = b; } c.x = a/gdc; c.y = b/gdc; } return c; } void print_rational(struct rational a) { if(a.x<0 || a.y<0) printf("-%ld/%ld\n", labs(a.x), labs(a.y)); else printf("%ld/%ld\n", a.x, a.y); } long int mol_part(struct rational a) { return a.x; } long int den_part(struct rational a) { return a.y; } struct rational add_rational(struct rational a, struct rational b ) { return make_rational(mol_part(a) * den_part(b) + mol_part(b) * den_part(a), den_part(a) * den_part(b)); } struct rational sub_rational(struct rational a, struct rational b ) { return make_rational(mol_part(a) * den_part(b) - mol_part(b) * den_part(a), den_part(a) * den_part(b)); } struct rational mul_rational(struct rational a, struct rational b ) { return make_rational(mol_part(a) * mol_part(b), den_part(a) * den_part(b)); } struct rational div_rational(struct rational a, struct rational b ) { if(b.x == 0) { printf("除数为零,跳过除法运算"); return; } else return make_rational(mol_part(a) * den_part(b), den_part(a) * mol_part(b)); } int main(void) { long int a1, a2, b1, b2; S: printf("请以分数形式输入2个有理数\n"); scanf("%ld/%ld %ld/%ld", &a1, &a2, &b1, &b2); printf("=============================================================\n"); if(a2 == 0 || b2 ==0) { printf("分母不能为0\n"); goto S; } else { struct rational a = make_rational(a1, a2); struct rational b = make_rational(b1, b2); print_rational(add_rational(a, b)); print_rational(sub_rational(a, b)); print_rational(mul_rational(a, b)); print_rational(div_rational(a, b)); } return 0; }
C
#include "struct.h" #include "lem_in.h" /* ** JUST FOR TESTING********************** */ void print_input(t_input *input) { t_input *copy; copy = input; printf("\n---PRINT INPUT---\n"); while (copy) { printf("%s\n", copy->line); copy = copy ? copy->next : NULL; } // printf("CMD = %s\n", stor->cmd ? (stor->cmd == 1 ? "START_SIG" : "END_SIG") : "NO_SIG"); // char *str = "##end"; // if (str == "##ende") // printf("\nYES\n"); } void print_room(t_room *room) { if (!room) return; printf("\n---PRINT ROOM---\n"); printf("name = %s\n", room->name); if (room->suur_type != 0) printf("suur type = %s\n", room->suur_type == 1 ? "IN" : "OUT"); else printf("suur type = %s\n", "None"); printf("x = %d\n", room->coord[0]); printf("y = %d\n", room->coord[1]); printf("level = %d\n", room->level); printf("vertex_size = %d\n", room->vertex_size); printf("num_links = %d\n", room->num_links); // printf("input links = %d\n", room->input_links); // printf("output links = %d\n", room->output_links); // printf("visit = %d\n", room->visit); printf("is_link = %s\n", room->links ? "YES" : "NO"); t_link *lcopy; if (room->links) { lcopy = room->links; while (lcopy) { printf("room->links->name = %s\n", lcopy ? lcopy->room->name : NULL); lcopy = lcopy->next; } } t_link *out; if (room->output) // && room->output_links) { // printf("room output ct = %d\n", room->output_links); out = room->output; while (out) { printf("room->output->name = %s\t suur = %d edge_size = %d\n", out->room->name, out->room->suur_type, out->edge_size); out = out->next; } } t_link *in; if (room->input) // && room->input_links) { // printf("room input ct = %d\n", room->input_links); in = room->input; while (in) { printf("room->input->name = %s\t suur = %d edge_size = %d\n", in->room->name, in->room->suur_type, in->edge_size); in = in ? in->next : NULL; } // printf("check\n"); } } void print_room_list(t_frame *stor, t_room *room) { t_room *copy; printf("we are here\n"); if (!room) return; copy = room; while (copy) { print_room(copy); copy = copy ? copy->next : NULL; } if (stor) { printf("\n---PRINT STOR---\n"); printf("\nnum_rooms = %d\n", stor->num_rooms); printf("start = %s num_links = %d\n", stor->start->name, stor->start->num_links); printf("end = %s num_links = %d\n", stor->end->name, stor->end->num_links); } } void print_path(t_path *path, int ct) { t_link *copy; int i; i = 0; copy = path->start; if (!path) return; printf("\n----- PRINT PATH #%d | len = %d -----\n", ct, path->len); while (copy) { printf("room_%d = %s\tants = %d\n", i, copy->room->name, copy->room->ants); copy = copy->next; i++; } } void printf_path_rev(t_path * path, int ct) { t_link *copy; int i; i = 0; copy = path->end; if (!path) return; printf("\n----- PRINT PATH REV #%d | len = %d -----\n", ct, path->len); while (copy) { printf("room_%d = %s\tants = %d\n", i, copy->room->name, copy->room->ants); copy = copy->prev; i++; } } void print_path_list(t_frame *stor) { t_path *copy; int ct; ct = 1; copy = stor->paths; if (!copy) return; while (copy) { print_path(copy, ct); // printf_path_rev(copy, ct); // printf("path = %s\n", copy->end->room->name); printf("----- ants_togo = %d -----\n", copy->ants_togo); copy = copy->next; ct++; } } /* ** Funcs to emulate bsf levels ** Work only with correct map with no forks and unuseless links */ void set_levels(t_frame *stor) { t_room *room; t_link *link; int i; link = stor->start->links; while (link) { i = 1; room = link->room; // printf("out | room->name = %s\n", room ? room->name : NULL); while (room && ft_strcmp(room->name, stor->end->name)) { // printf("room->name = %s\n", room->name); // printf("room->next = %s\n", room->links->next->room->name); room->level = i++; room = room->links->next->room; } link = link->next; } // printf("\n***** IN SET LEVELS*****\n"); // print_room_list(stor, stor->map); } void cur_state(t_path *path, t_frame *stor) { t_link *print; print = path->end; if (path->ants_togo) { printf("PATH CURRENT STATE\n"); printf("path %s togo %d on_work %d pass %d\n", path->end->room->name, path->ants_togo, path->on_work, path->ants_pass); while (print) { printf("room = %s is ants = %d ant_name = %d\n", print->room->name, print->room->ants, print->room->ant_name); print = print->prev; } } }
C
#include "meminfo.h" /********************auxiliary functions definitions**********************/ void print_mallinfostats(struct mallinfo minfo); void *mem_get_mallinfo(void *arg); int get_type(char *line); int find_index(long long int *array); long long int get_mmap_size(char *line, Mem_info *mem_info); int find_addr(long long int *array, long long int addr); long long int get_munmap_size(char *line, Mem_info *mem_info); long long int get_brk_size(char *line, long long int *brk_ptr); long long int get_shm_size(char *line); /*************************************************************************/ void print_stats(Mem_info *mem_info, char *option) { printf("---------------------mem_info--------------------- KB MB PAGES\n"); long long int mem_start = mem_info->mmap_mem_start + mem_info->brk_start; printf("Memory for starting the process: %6lld%11lld%14lld\n", KB(mem_start), MB(mem_start), PAGE(mem_start)); printf("Memory allocated with mmap: %6lld%11lld%14lld\n", KB(mem_info->mmap_mem_usr), MB(mem_info->mmap_mem_usr), PAGE(mem_info->mmap_mem_usr)); printf("Memory released with munmap: %6lld%11lld%14lld\n", KB(mem_info->munmap_mem), MB(mem_info->munmap_mem), PAGE(mem_info->munmap_mem)); printf("Memory allocated with brk: %6lld%11lld%14lld\n", KB(mem_info->brk_usr), MB(mem_info->brk_usr), PAGE(mem_info->brk_usr)); printf("Shared memory: %6lld%11lld%14lld\n\n", KB(mem_info->shm_mem), MB(mem_info->shm_mem), PAGE(mem_info->shm_mem)); if(strcmp(option, "-mallinfo") != 0) return; print_mallinfostats(*mem_info->minfo); } Mem_info *mem_generate(char *prog_name, char* option) { PAGESIZE = getpagesize(); Mem_info *mem_info = calloc(1, sizeof(Mem_info)); pthread_t tid; if(strcmp(option, "-mallinfo") == 0) { CALL_CORRECT(pthread_create(&tid, NULL, &mem_get_mallinfo, NULL), 0, "pthread_create"); } int pid = fork(); if(pid == 0) { if(execlp("strace", "strace", "-e", "trace=memory,ipc", "-o", FLOGNAME, prog_name, (char*)NULL) == -1) { exit(-1); } } struct mallinfo *minfo; if(strcmp(option, "-mallinfo") == 0) { CALL_CORRECT(pthread_join(tid, (void **)(&minfo)), 0, "pthread_join") if(minfo == NULL) return NULL; } int status; wait(&status); if(!WIFEXITED(status) || WEXITSTATUS(status) == -1) return NULL; FILE* log_file; CALL(log_file, fopen(FLOGNAME, "r"), NULL, "open"); mem_info->log_file = log_file; mem_info->minfo = minfo; mem_info->start = true; return mem_info; EXIT_BGN return NULL; EXIT_END } void mem_getstats(Mem_info *mem_info) { char *line = NULL; size_t len = 0; while(getline(&line, &len, mem_info->log_file) != -1) { switch(get_type(line)) { case MMAP: if(mem_info->start) mem_info->mmap_mem_start += get_mmap_size(line, mem_info); else mem_info->mmap_mem_usr += get_mmap_size(line, mem_info); break; case MUNMAP: mem_info->start=false; mem_info->munmap_mem += get_munmap_size(line, mem_info); break; case BRK: if(mem_info->start) mem_info->brk_start += get_brk_size(line, &mem_info->brk_ptr); else mem_info->brk_usr += get_brk_size(line, &mem_info->brk_ptr); break; case SHM: mem_info->shm_mem += get_shm_size(line); default: continue; } } } void mem_sendtoque() { mqd_t qd; CALL(qd, mq_open(QUEUENAME, O_WRONLY), -1, "mq_open");; struct mallinfo minfo; minfo = mallinfo(); char *mes = (char*) &minfo; CALL_CHECK(mq_send(qd, mes, SIZE, 1), -1, "mq_send"); mq_close(qd); EXIT_BGN return; EXIT_END } void mem_clean(Mem_info* mem_info) { if(mem_info != NULL) { fclose(mem_info->log_file); free(mem_info); unlink(FLOGNAME); } } /*********************auxuliary functions***********************/ void *mem_get_mallinfo(void *arg) { mqd_t qd; struct mq_attr mqattr; mqattr.mq_msgsize = SIZE; mqattr.mq_maxmsg = 2; CALL(qd, mq_open(QUEUENAME, O_RDWR | O_CREAT, 0666, &mqattr), -1, "mq_open"); struct mallinfo *minfo; static char mes[SIZE]; unsigned int prio; CALL_CHECK(mq_receive(qd, mes, SIZE, &prio), -1, "mq_receive"); minfo = (struct mallinfo*) mes; mq_close(qd); mq_unlink(QUEUENAME); return (void*)(minfo); EXIT_BGN mq_unlink(QUEUENAME); return NULL; EXIT_END } void print_mallinfostats(struct mallinfo minfo) { printf("---------------------mallinfo--------------------- KB MB PAGES\n"); printf("Memory allocated with mmap: %6d%11d%14d\n", KB(minfo.hblkhd), MB(minfo.hblkhd), PAGE(minfo.hblkhd)); printf("Memory allocated with brk: %6d%11d%14d\n", KB(minfo.arena), MB(minfo.arena), PAGE(minfo.arena)); printf("Total allocated space: %6d%11d%14d\n", KB(minfo.uordblks), MB(minfo.uordblks), PAGE(minfo.uordblks)); printf("Total free space: %6d%11d%14d\n", KB(minfo.fordblks), MB(minfo.fordblks), PAGE(minfo.fordblks)); printf("Top-most, releasable space: %6d%11d%14d\n\n", KB(minfo.keepcost), MB(minfo.keepcost), PAGE(minfo.keepcost)); } int get_type(char *line) { if(strncmp(line, "mmap", 4) == 0) return MMAP; if(strncmp(line, "brk", 3) == 0) return BRK; if(strncmp(line, "munmap", 6) == 0) return MUNMAP; if(strncmp(line, "shmget", 6) == 0) return SHM; return -1; } int find_index(long long int *array) { for(int i=0; i<20; i++) { if(array[i] == 0) { return i; } } return -1; } long long int get_mmap_size(char *line, Mem_info *mem_info) { line = strpbrk(line, ","); line++; char *end; long long int size = strtoll(line, &end, 0); line = end; for(int i=0; i<3; i++) { line = strpbrk(line, ","); line++; } long int fd = strtol(line, &end, 0); line = strpbrk(end, "="); line++; long long int addr = strtoll(line , NULL, 0); if(addr <=0 || fd != -1) { return 0; } mem_info->mmap_addr[find_index(mem_info->mmap_addr)] = addr; return size; } int find_addr(long long int *array, long long int addr) { for(int i=0; i<20; i++) { if(array[i]==addr) { return i; } } return 0; } long long int get_munmap_size(char *line, Mem_info *mem_info) { line = strpbrk(line, "("); line++; char *end; long long int addr = strtoll(line, &end, 0); line = end; line++; long long int size = strtoll(line, &end, 0); int ind = find_addr(mem_info->mmap_addr, addr); if(!ind) return 0; mem_info->mmap_addr[ind] = 0; return size; } long long int get_brk_size(char *line, long long int *brk_ptr) { line = strpbrk(line, "("); line++; char *end; long long int arg = strtoll(line, &end, 0); line = strpbrk(end, "="); line++; long long int ptr = strtoll(line, NULL, 0); if(arg) { long long int tmp = *brk_ptr; *brk_ptr = ptr; return (ptr - tmp); } else { *brk_ptr = ptr; return 0; } } long long int get_shm_size(char *line) { line = strpbrk(line, ","); line++; long long int size = strtoll(line, NULL, 0); return size; }
C
//#include <stdio.h> // //int main() //{ // for (int i = 0; i < 10; i++) { // printf("%d ", i); // if (i == 5) { // break; // } // } // printf("\n"); // // double money = 0; // printf("请输入您要取的钱数:"); // while (1) { // scanf("%lf", &money); // if (money > 0) { // break; // } // printf("输入错误,请重新输入:"); // } // printf("%.2lf\n", money); // // //输入整数 输出所有整数的和 // int sum = 0; // int num; // while (1) { // printf("请输入一个整数:"); // scanf("%d", &num); // if (num == 0) { // break; // } // sum += num; // } // printf("sum=%d\n", sum); // // return 0; //}
C
#include<stdio.h> int main() { FILE *fptr; char ch; int n; fptr=fopen("myfile.txt","w"); scanf("%c%d",&ch,&n); fprintf(fptr,"%c%d",ch,n); fclose(fptr); return 0; }
C
#include <iostream> using namespace std; int main() { int lbDzieci(0); if (lbDzieci > 0) { cout << "Masz dzieci. Brawo!" << endl; } else { cout << "Ojej, nie masz dzieci?" << endl; } cout << "Koniec programu" << endl; return 0; }
C
/** Copyright 2018 Andrew Cunningham, andyham@uw.edu, 1610973 Abhyudaya Gupta CSE 474 SU 2018 Lab 3 Defines many constants needed for initialization and declares many functions */ #include "header.h" // defines some header functions used in main.c void Enable_All_GPIO(void) { SYSCTL_RCGCGPIO |= 0x1F; int n = 500; while(n--){} } // initlize the onboard portF LED // initialize the two onboard switches void PortF_LED_Init() { CONTROL_REGISTER = 0x20; //power on port F F_LOCK = 0x4C4F434B; //unlock value defined on datasheet F_CR = 0xFF; //enables us to write to PUR F_DATA_DIRECTION = 0x0E; //0b0110 switches in, LED out F_PUR = 0x11; //0b100 F_D_A = 0x1F; //0b11111 set all the ports to digital } // initialize the offboard switches in PA5 and PA6 void Switch_Init(void) { volatile unsigned long delay; CONTROL_REGISTER |= 0x0000001; // activate the clock for port a delay = CONTROL_REGISTER; // allow time for the clock to start // no need to unlock GPIO PORTA PORTA_ANALOG &= ~0x60; // disable analog on PA5 and PA6 PORTA_CONTROL &= 0x00F00000; // PCTL GPIO on PA5 and PA6 PORTA_DIRECTION &= ~0x60; // set PA5, PA6 Direction to input PORTA_FUNCTION &= ~0x60; // PA5 PA6 regular port function PORTA_DIGITAL |= 0x60; // PA5 PA6 port set to digital } void PortC_LED_Init(void) { volatile unsigned long delay = 0; CONTROL_REGISTER |= 0x04; // activate clock for Port C while(delay < 100) {delay++;} GPIO_PORTC_AMSEL_R &= ~(0x70); // 0000xxxx analog GPIO_PORTC_DEN_R |= 0x70; // 1111xxxx digital enable GPIO_PORTC_DIR_R |= 0x70; // 1111xxxx output GPIO_PORTC_PCTL_R &= ~(0xFFFF0000); GPIO_PORTC_AFSEL_R &= ~(0x70); GPIO_PORTC_DATA_R &= ~(0x70); // turn them off } // initialize the offboard LED in PA2, PA3, PA4 void LED_Init(void) { volatile unsigned long delay; CONTROL_REGISTER |= 0x01; // activate clock for Port A delay = CONTROL_REGISTER; // allows time for clock to start // no need to unlock PA2 PORTA_CONTROL &= 0x00000F00; // regular GPIO PORTA_ANALOG &= ~0x1C; // disable analog function for PA2 PORTA_DIRECTION |= 0x1C; // PA2 set direction to output PORTA_FUNCTION &= ~0x1C; // PA2 regular port funcion PORTA_DIGITAL |= 0x1C; // PA2 enable digital port } // initialize timer0 to trigger after clockspeedmhz time as passed // designed to be used in conjunction with that clockspeed void Timer_Init(int clockspeedmhz) { RCGCTIMER |= 0x01; // enable the timer Timer0_CTL &= ~0x01; // lock the timer Timer0_CFG &= ~07; // set the 32 bit configuration Timer0_TnMR |= 0x02; // configure TnMR field to A Timer0_TnMR &= ~0x01; Timer0_TnMR &= ~0x20; //Timer0_TnILR = 0x00F42400; // start interval 16,000000 Timer0_TnILR = (clockspeedmhz * 1000000); Timer0_INTERRUPT |= 0x11; // turn on the interrupt Timer0_FLAG |= 0x00000001; // clear timeout flag Timer0_CTL |= 0x00000001; // unlock the timer timer } void Interrupt_Init(void) { INTERRUPT_ENABLE |= (1<<19); // enable timer interrupt PORTF_EDGE_SENSITIVE &= ~0x11; // makes bit 0 and 4 edge sensitive PORTF_TRIGGER_CONTROL &= ~0x11; // trigger is controlled by iev PORTF_TRIGGER_SIDE = ~0x11; // falling trigger level INTERRUPT_ENABLE |= (1<<30); // enable switch interrupt INTERRUPT_PRIORITY = (3<<28); // set switch interrupt priority 3 PORTF_FLAG |= 0x11; // clear any prior interrupts PORTF_MASK |= 0x11; // unmask interrupts } // sets the CPU clock at speed MHz void PLL_Init(int speed) { // step 1, enable the 31 bit RCC2 |= (0x80000000); // step 2, bypass PLL, bit 11 = 0 RCC2 |= (1<<11); // step 3, select crystal, bits 10-6 10101 RCC |= 0x540; // 0b10101000000 RCC &= 0x57F; // 0b10101111111 // step 4, select oscillator source RCC2 &= ~(0x70); // 0b0001111 // step 5, activate PLL by bit 13 to 0 RCC2 &= ~(1<<13); // step 6, set system divider, bit 30 to 1 RCC2 |= (1<<30); // step 7, set sys divider 28-22 to 0x4 // step 7a, this is followup RCC |= (1<<22); // sart the mask int rcc2mask = ~(0x1FC00000); RCC2 &= rcc2mask; int n = (400 / speed) - 1; RCC2 |= (n<<22); // step 8, wait for PLL to lock do {} while ((RCC & 0x20) == 0x20); // step 8b, disable bypass RCC2 &= ~(1<<11); } // set up the thermometer void ADC_Andrew_Init(void) { // enable clock on RCGCADC SYSCTL_RCGCADC_ADC |= 0x01; // disable the sample sequencer ADC0_ACTSS_ADC &= ~(1<<3); // configure the multiplexer to be 0b0101 ADC0_EMUX_ADC &= ~(15<<12); ADC0_EMUX_ADC |= (5<<12); // update bit 5 of the timer to allow ADC to be triggered by timer Timer0_CTL |= (1<<5); // update SSCTL3 to be 0b0111 ADC0_SSCTL3_ADC &= ~(0xF); ADC0_SSCTL3_ADC |= 0xE; // update IM to mask seq 3 ADC0_IM_ADC |= (1<<3); // Jeff's extra step ADC0_ISC_ADC |= (1<<3); ADC0_DCISC_ADC |= (1<<3); // enable the sample sequencer ADC0_ACTSS_ADC |= (1<<3); // start a new conversion ADC0_PSSI_ADC |= (1<<3); } // set up uart 0 void UART0_INIT(int ibrd, int fbrd) { SYSCTL_RCGCUART_R |= 0x1; // enable UART 0 SYSCTL_RCGCGPIO |= (1<<0); GPIO_PORTA_AFSEL_R |= (1<<1)|(1<<0); GPIO_PORTA_PCTL_R |= (1<<0)|(1<<4); GPIO_PORTA_DEN_R |= (1<<0)|(1<<1); // setup UART0 UART0_CTL_R &= ~(1<<0); // disable while configuring UART0_IBRD_R = ibrd; // set the integer part of the BRD UART0_FBRD_R = fbrd; // set the fractional part of the BRD UART0_LCRH_R |= (0x3<<5); // write 0x06 UART0_CC_R = 0x0; // sets source clock to 16MHZ UART0_CTL_R = (1<<0)|(1<<8)|(1<<9); // enable the uart } char UART0_ReadChar() { while ((UART0_FR_R & (1<<4)) != 0); // flag check the receive is complete return UART0_DR_R; // read that data } void UART0_WriteChar(char c) { while ((UART0_FR_R & (1<<5)) != 0); // flag check the transmitter is complete UART0_DR_R = c; // write that char to the data } void UART0_WriteString(char* s) { while (*s) { // while not null terminator UART0_WriteChar(*(s++)); // write/print that char to the data } }
C
#include <stdio.h> #include <string.h> /* 1) Alice and Bob agree on an elliptic curve EE over a Field FqFq and a basepoint P∈E/FqP∈E/Fq. (Easily done) 2) Alice generates a (random) secret kAkA and computes PA=kAPPA=kAP. Point Arithmetic 3) Bob generates a (random) secret kBkB and computes PB=kBPPB=kBP. 4) Alice and Bob exchange PAPA and PBPB. 5) Alice and Bob compute PAB=kaPB=kbPAPAB=kaPB=kbPA. The secret kAkA and kBkB is a random value ∈{1,...,n−1}∈{1,...,n−1} where nn is the order of the group generated by PP. */ /* TODO: modular_inverse montgomery multiplication (if I feel like a fast boi) Elgamel's Figure out most significant bit of modulus stuff */ typedef struct Point_t{ int x; int y; } Point point_operation(Point A, Point B,int s){ Point temp; temp.x = s^2 - A.x - B.x; temp.y = s(A.x - ret_x) - A.y; return {temp.x, temp.y}; // I know this doesn't compile but you get the point and its easier in verilog } // generates shared secret Point Pa_generator(int k, Point G, int p){ // ok now do this in hardware // eqn: y^3 = x^2 + ax + b // if odd add 1, double regardless Point temp; temp.x = P.x; temp.y = P.y; while(k>0){ if(k%2 == 0){ int s = (3(temp.x^2) + a)*(inv_mod(2*temp.y)) % p; temp = point_operation(temp, temp, s); k >>= 1; } else{ int s = (G.y - temp.y)*inv_mod(G.x-temp.x) % p; temp = point_operation(G, temp, s); k--; } } } void modulus(int k, int n){ int out = k; if(MSBk == 1) while(out < 0) out += n; else while(out>n) out -= n; } // Elgamel's crap void elgamal_encrypt(Point public_key, int n, int message){ /* ENCRYPTION: Choose random 1 < k < n. C1 = kG, C2 = kPub. Pm is f(m), i.e. <m, f(m)> (y^2 = x^3 + 7; maybe don't use y^2?) Ciphertext is <C1, C2 + Pm>. Maybe use C1 = bob_point and C2 = shared point? For secp256k1, it would be <bob_point, shared_point + <m, m+7>>*/ } void elgamal_decrypt(Point public_key, int n, int ciphertext){ /* DECRYPTION: */ /* From <C, D> (C1, C2+Pm) calc C' = priv_key*C. Pm = D - C' = (k(xP) + Pm) - (x(kP)) m = inv(f(m)); */ } int main(){ // y^2 = x^3 + ax + b // domain parameters {a, b, n, G} int alice = rand() % n; int bob = rand() % n; char message[128]; int message_num = 0; scanf("Insert message: %s", message); message_num = asciify(message[i]); Point point_alice = Pa_generator(alice, G, p); Point point_bob = Pa_generator(bob, G, p); Point shared_key = Pa_generator(alice, point_bob, p); Point cipher = {} elgamal_encrypt(); elgamal_decrypt(); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include"funcoes.h" struct filmess{ //depois de usar a strtok passa pra string int codigo; char titulo[100]; int ano; int quantidade; char genero[10]; }vetor[42]; int carregar(){ FILE *arquivo; int n; //numero total de filmes int c=0;//codigo do filme char texto[116]; //guarda o texto lido em uma linha do arquivo char titulo[100]; //guarda o titulo do filme retirado da string "texto" char ano[5]; //guarda o ano do filme retirado da string "texto" char quantidade; //guarda a quantidade em estoque retirado da string "texto" char genero[10]; //guarda o genero do filme retirado da string "texto" int a; // usado para correcao de digitos do ano int b; // quantidade int y; //contador da posic�o da string "texto" int x=0; if((arquivo=fopen("entrada.txt", "rt"))==NULL){ printf("Erro ao abrir o arquivo!"); } /********************************************************************************************************************************/ fseek(arquivo,0,SEEK_SET); //botando o ponteiro no inicio fscanf(arquivo, "%d \n", &n); //colocando o 41 na variavel n while(fscanf(arquivo, "%[^\n]\n", texto)!=EOF){ //le o arquivo, linha por linha salvando cada linha na string texto y=0; //STRING DE TEXTO while(texto[y]!=';'){ //le o texto da string ate o ; titulo[y]=texto[y]; //coloca tudo lido ate o ; na string titulo, letra por letra y++; } titulo[y]='\0'; //delimita os espa�os de memoria usados pelo titulo y++; //corrige a posicao do y (pulando o caracter do ;) x=0; //STRING DE ANO (deve ser alterada para int depois) while(texto[y]!=';'){ //le o texto da linha ate o proximo ; ano[x]=texto[y]; //coloca tudo lido ate o ; na string ano, letra por letra y++; x++; } y++; //corrige a posicao do y (pula o caracter do ;) a = atoi(ano); //converte o ano para int //STRING DA QUANTIDADE EM ESTOQUE (deve ser alterado para int depois) while(texto[y]!=';'){ //le o texto da linha at� o proximo ; quantidade=texto[y]; y++; x++; } y++; //corrige a posicao do y (pula o caracter do ;) x=0; //STRING QUE SALVA O GENERO DO FILME while(texto[y]!='\0'){ //le o texto da linha at� o proximo ; genero[x]=texto[y]; x++; y++; } genero[x]='\0'; //delimita os espa�os de memoria usados pelo titulo strcpy(vetor[c].titulo, titulo); vetor[c].ano = a; vetor[c].quantidade = quantidade - '0'; //passando quantidade pra int strcpy(vetor[c].genero, genero); vetor[c].codigo = c; c++; } fclose(arquivo); return n; //retornando o total para usar no backup } /********************************************************************************************************************************/ void locar(){ FILE *arquivo; int i=0, cod, unidade; if((arquivo=fopen("entrada.txt", "r+"))==NULL){ printf("Erro ao abrir o arquivo!"); } else{ printf("Insira o código do filme:\n"); scanf("%d", &cod); while((vetor[i].codigo != cod) && (i<41)){ i++; } if(vetor[i].codigo == cod){ printf("Quantas unidades você deseja locar?\n"); scanf("%d", &unidade); if(unidade > vetor[i].quantidade){ printf("Essa quantidade não está disponível. Possuímos apenas %d unidades.\n", vetor[i].quantidade); }else{ printf("Sua locação foi realizada com sucesso!!!\n\n"); vetor[i].quantidade = vetor[i].quantidade - unidade; printf("Nosso acervo possui %d unidades restantes do filme %s.\n", vetor[i].quantidade, vetor[i].titulo); } } else{ printf("Código não encontrado, tente novamente.\n"); } fclose(arquivo); } } /********************************************************************************************************************************/ void entregar(){ FILE *arquivo; int i=0, cod, unidade; if((arquivo=fopen("entrada.txt", "r+"))==NULL){ printf("Erro ao abrir o arquivo!"); } else{ printf("Insira o código do filme:\n"); scanf("%d", &cod); while((vetor[i].codigo != cod) && (i<41)){ i++; } if(vetor[i].codigo == cod){ printf("Quantas unidades você está entregando?\n"); scanf("%d", &unidade); printf("Sua entrega foi realizada com sucesso!!!\n\n"); vetor[i].quantidade = vetor[i].quantidade + unidade; printf("Nosso acervo possui %d unidades restantes do filme %s.\n", vetor[i].quantidade, vetor[i].titulo); } else{ printf("Código não encontrado, tente novamente.\n"); } fclose(arquivo); } } /********************************************************************************************************************************/ int buscacodigo(){ __fpurge(stdin); FILE *arquivo; int cod; int i=0; printf("Insira o código:\n"); scanf("%d", &cod); if((arquivo=fopen("entrada.txt", "r+"))==NULL){ printf("Erro ao abrir o arquivo!"); } else{ while((vetor[i].codigo != cod) && (i<41)){ i++; } if(vetor[i].codigo == cod){ imprimir(i); }else{ printf("Desculpe, não encontramos esse código no nosso acervo.\n"); } } fclose(arquivo); return 0; } /********************************************************************************************************************************/ int buscanome(){ __fpurge(stdin); FILE *arquivo; char nome[100]; int i=0; printf("Insira o título:\n"); scanf("%[^\n]s", &nome); //precisou de [^\n] para salvar apos o espaço if((arquivo=fopen("entrada.txt", "r+"))==NULL){ printf("Erro ao abrir o arquivo!"); } else{ while((strcasecmp(vetor[i].titulo, nome)!=0) && (i<41)){ i++; } if(strcasecmp(vetor[i].titulo, nome)==0){ imprimir(i); }else{ printf("Desculpe, não encontramos esse título no nosso acervo.\n"); } } fclose(arquivo); return 0; } /********************************************************************************************************************************/ int buscaano(){ __fpurge(stdin); FILE *arquivo; int ano; int i=0, controle=0; printf("Insira o ano:\n"); scanf("%d", &ano); if((arquivo=fopen("entrada.txt", "r+"))==NULL){ printf("Erro ao abrir o arquivo!"); } else{ while(i<41){ if(vetor[i].ano == ano){ imprimir(i); i++; controle++; }else{ i++; } } } if(controle=0){ printf("Não encontramos título algum com esse ano.\n"); } fclose(arquivo); return 0; } /********************************************************************************************************************************/ int buscagenero(){ __fpurge(stdin); FILE *arquivo; char genero[10]; int i=0, controle=0; printf("Insira o genero:\n"); scanf("%s", &genero); if((arquivo=fopen("entrada.txt", "r+"))==NULL){ printf("Erro ao abrir o arquivo!"); } else{ while(i<41){ if(strcasecmp(vetor[i].genero, genero)==0){ imprimir(i); i++; controle++; }else{ i++; } } } if(controle=0){ printf("Não encontramos título algum com esse genero.\n"); } fclose(arquivo); return 0; } /********************************************************************************************************************************/ int imprimir(int i){ //funcao utilizada na busca para imprimir todos os filmes que estao dentro da informa�ao digitada pelo usuario FILE *arquivo; if((arquivo=fopen("entrada.txt", "rt"))==NULL){ printf("Erro ao abrir o arquivo!"); } printf("\nCODIGO: %d\n", vetor[i].codigo); printf("TITULO: %s\n", vetor[i].titulo); printf("ANO: %d\n", vetor[i].ano); printf("QUANTIDADE: %d\n", vetor[i].quantidade); printf("GENERO: %s\n\n", vetor[i].genero); fclose(arquivo); return 0; } /********************************************************************************************************************************/ int buscar(){ //funcao que pergunta ao usuario o tipo de busca que ele deseja fazer __fpurge(stdin); int opcao=0; while(opcao != 5){ printf("\n\n\nPor qual modo você deseja pesquisar no nosso acervo?\n"); printf("1 - Pesquisa por código\n"); printf("2 - Pesquisa por título\n"); printf("3 - Pesquisa por ano\n"); printf("4 - Pesquisa por gênero\n"); printf("5 - Sair da busca\n"); scanf("%d", &opcao); switch(opcao){ case 1: buscacodigo(); break; case 2: buscanome(); break; case 3: buscaano(); break; case 4: buscagenero(); break; case 5: printf("Voltando para o menu principal...\n"); break; default: printf("Opção inválida, tente novamente.\n"); break; } } return 0; } /********************************************************************************************************************************/ void imprimirtudo(){ __fpurge(stdin); FILE *arquivo; int c=0; if((arquivo=fopen("entrada.txt", "rt"))==NULL){ printf("Erro ao abrir o arquivo!"); } while(c<41){ printf("\nCODIGO: %d\n", vetor[c].codigo); printf("TITULO: %s\n", vetor[c].titulo); printf("ANO: %d\n", vetor[c].ano); printf("QUANTIDADE: %d\n", vetor[c].quantidade); printf("GENERO: %s\n\n", vetor[c].genero); c++; } fclose(arquivo); } /********************************************************************************************************************************/ void imprimirselecao(){ //procedimento que pergunta o tipo de impress�o int op=0, n; n = carregar(); while(op != 3){ printf("\n\n\nSelecione o tipo de impressão\n"); printf("1 - Imprimir acervo completo\n"); printf("2 - Imprimir por nome do filme\n"); printf("3 - Voltar ao programa principal\n"); scanf("%d", &op); switch(op){ case 1: imprimirtudo(); break; case 2: buscanome(); //reutilizamos a funcao de busca por titulo j� que ela faz a mesma coisa que precisamos aqui break; case 3: printf("Voltando ao menu principal...\n"); break; default: printf("Opção inválida, tente novamente.\n"); break; } } } /********************************************************************************************************************************/ void salvar(int i, FILE *arquivobackup){ //funcao que salva, � utilizada nas duas formas de backup char string[116]; sprintf(string, "%s;%d;%d;%s\n", vetor[i].titulo, vetor[i].ano, vetor[i].quantidade, vetor[i].genero); fprintf(arquivobackup, "%s", string); //salvando cada linha do arquivo printf("%s", string); } /********************************************************************************************************************************/ int backup(int n){ //backup do acervo inteiro atualiza, recebe o numero de filmes "n" como parametro FILE *arquivobackup; char total[3]; int i; if((arquivobackup=fopen("entrada_backup.txt", "w+"))==NULL){ printf("Erro ao abrir o arquivo!"); } else{ sprintf(total, "%d\n", n); //salvando o total de filmes na string "total" printf("%s", total); fprintf(arquivobackup, "%s", total); //gravando na primeira linha do arquivo o total de filmes for(i=0; i<41; i++){ salvar(i, arquivobackup); //funcao que salva em um arquivo baseada na posicao do vetor e ponteiro } } fclose(arquivobackup); } /********************************************************************************************************************************/ int backup_ano(FILE *arquivobackup2){ //funcao que procura os filmes por ano e os salva em um arquivo __fpurge(stdin); int ano; int i=0, controle=0; printf("Insira o ano:\n"); scanf("%d", &ano); while(i<41){ if(vetor[i].ano == ano){ salvar(i, arquivobackup2); i++; controle++; }else{ i++; } } if(controle=0){ printf("O arquivo de backup está vazio, não encontramos titulo algum com esse ano.\n"); } return 0; } /********************************************************************************************************************************/ int backup_genero(FILE *arquivobackup2){ //funcao que procura os filmes por ano e os salva em um arquivo __fpurge(stdin); char genero[10]; int i=0, controle=0; printf("Insira o genero:\n"); scanf("%s", &genero); while(i<41){ if(strcasecmp(vetor[i].genero, genero)==0){ //strcasecmp serve para ignorar se a letra � maiuscula ou minuscula salvar(i, arquivobackup2); i++; controle++; }else{ i++; } } if(controle=0){ printf("O arquivo de backup está vazio, não encontramos título algum com esse genero.\n"); } return 0; } /********************************************************************************************************************************/ int backupselect(int n){ FILE *arquivobackup2; char string[116], total[3]; int i, op=0; if((arquivobackup2=fopen("filmes_backup.txt", "w+"))==NULL){ printf("Erro ao abrir o arquivo!"); } else{ while(op!=1){ //se selecionar para sair ou imprimir, o op fica com o valor de 1 e sa�mos, isso foi feito para n�o ficar repetindo ap�s a pessoas selecionar 1 ou 2 __fpurge(stdin); printf("Selecione o tipo de pesquisa:\n"); printf("1 - Pesquisa por ano\n"); printf("2 - Pesquisa por genero\n"); printf("3 - Voltar ao programa principal\n"); scanf("%d", &op); switch(op){ case 1: backup_ano(arquivobackup2); //chamando a funcao que busca por ano e salva os filmes em um arquivo de texto op = 1; break; case 2: backup_genero(arquivobackup2); //chamando a funcao que busca por genero e salva os filmes em um arquivo de texto op = 1; break; case 3: printf("Voltando ao menu principal...\n"); op = 1; break; default: printf("Opção inválida, tente novamente.\n"); break; } } } fclose(arquivobackup2); } /********************************************************************************************************************************/
C
#ifndef __XORSHIFT #define __XORSHIFT #include <stdint.h> struct xorshift { typedef uint_fast32_t result_type; /* The state must be seeded so that it is not everywhere zero. */ uint64_t s[2]; xorshift() { s[0] = 1234567; s[1] = 7654321; } void seed(uint64_t s1, uint64_t s2) { s[0] = s1; s[1] = s2; } uint32_t min() { return 0; } uint32_t max() { return 4294967295; } uint32_t operator () () { return sample(); } uint32_t sample() { uint64_t x = s[0]; uint64_t const y = s[1]; s[0] = y; x ^= x << 23; // a s[1] = x ^ y ^ (x >> 17) ^ (y >> 26); // b, c return s[1] + y; } void discard() { sample(); } }; #endif
C
#include <stdio.h> int main() { int n, teste, qtddiv=0, i; scanf("%d", &n); if(n<0) { printf("Numero Invalido!"); } else { for(i=1; i<=n; i++) { teste=n/i; if(n%i==0) { qtddiv++; } } if(qtddiv==2) { printf("PRIMO"); } else { printf("NAO PRIMO"); } } return 0; }
C
// // spo2_algo.c // CIndexOut // // Created by 倪申雷 on 2021/2/20. // #include "spo2_algo.h" #include <stdlib.h> #include <string.h> // AddressSanitizer (detects addressability issues) int doSpo2Algo(void) { int spo2_size = 10; Student* spo2_array = (Student*)malloc((spo2_size) * sizeof(Student)); // 将某一块内存中的内容全部设置为指定的值 memset(spo2_array, 0, spo2_size * sizeof(Student)); for (int index = 0; index < spo2_size; index++) { spo2_array[index].number = index; spo2_array[index].age = 20; /// 添加friends, friends的最大个数为4 for (int friendIndex = 0; friendIndex < 5; friendIndex ++) { spo2_array[index].friends[friendIndex] = friendIndex; } } free(spo2_array); return 0; }
C
#ifndef PC_2018_07_RESPONSE_H #define PC_2018_07_RESPONSE_H #include <stdint.h> #include <stdbool.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <netdb.h> #include <arpa/inet.h> #include <netinet/in.h> #include "buffer.h" #include "lib.h" struct response { uint8_t * mediaType; bool chunked; uint8_t * headers; int header_length; int body_length; int status_code; bool compressed; }; enum response_state{ response_version, response_status_code, response_headers, response_desired_header, response_length, response_media_type, response_encoding, response_enter, // apartir de aca están done response_done, // y apartir de aca son considerado con error response_error }; struct response_parser { struct response *response; enum response_state state; /** cuantos bytes tenemos que leer*/ uint8_t n; /** cuantos bytes ya leimos */ uint8_t i; /**buffer auxiliar*/ char* buffer; }; /** inicializa el parser */ void response_parser_init (struct response_parser *p); /** entrega un byte al parser. retorna true si se llego al final */ enum response_state response_parser_feed (struct response_parser *p, const uint8_t c); void response_log(); /** * Permite distinguir a quien usa parser_feed si debe seguir * enviando caracters o no. * * En caso de haber terminado permite tambien saber si se debe a un error */ bool response_is_done(const enum response_state st, bool *errored); void response_close(struct response_parser *p); /** * por cada elemento del buffer llama a `response_parser_feed' hasta que * el parseo se encuentra completo o se requieren mas bytes. * * @param errored parametro de salida. si es diferente de NULL se deja dicho * si el parsing se debió a una condición de error */ enum response_state response_consume(buffer *b, struct response_parser *p, bool *errored); bool body_is_done(struct response_parser *p, int length); void increase_body_length(struct response_parser *p, int length); void parser_headers(struct response_parser *p, uint8_t * ptr); bool chunked_is_done(uint8_t * buffer, int length); #endif
C
#include "mytimer.h" /* time-out parameter */ struct itimerval p_timeout; /* functions that are related to the timer */ void init_timer(void *function) { memset(&p_timeout, 0, sizeof(p_timeout)); p_timeout.it_value.tv_sec = 0; p_timeout.it_value.tv_usec = 0; p_timeout.it_interval.tv_sec = 0; p_timeout.it_interval.tv_usec = 0; signal(SIGALRM, function); /* p_timeout.it_interval.tv_sec = 0; p_timeout.it_interval.tv_usec = TIMEOUT_VAL; */ } /* the timer is in micro second */ void start_timer(int interval) { p_timeout.it_value.tv_usec = interval; if (setitimer(ITIMER_REAL, &p_timeout, NULL)) exit(errno); } void stop_timer() { p_timeout.it_value.tv_usec = 0; if (setitimer(ITIMER_REAL, &p_timeout, NULL)) exit(errno); }
C
/* SPDX-License-Identifier: GPL-2.0 */ /* * Copyright (c) 2015 National Instruments * * (C) Copyright 2015 * Joe Hershberger <joe.hershberger@ni.com> */ #ifndef __ETH_RAW_OS_H #define __ETH_RAW_OS_H #define IFNAMSIZ 16 /** * struct eth_sandbox_raw_priv - raw socket session * * sd: socket descriptor - the open socket during a session * host_ifname: interface name on the host to use for sending our packets * host_ifindex: interface index number on the host * device: struct sockaddr_ll - the host interface packets move to/from * local: 1 or 0 to select the local interface ('lo') or not * local_bindsd: socket descriptor to prevent the kernel from sending * a message to the server claiming the port is * unreachable * local_bind_udp_port: The UDP port number that we bound to */ struct eth_sandbox_raw_priv { int sd; char host_ifname[IFNAMSIZ]; unsigned int host_ifindex; void *device; int local; int local_bind_sd; unsigned short local_bind_udp_port; }; /* A struct to mimic if_nameindex but that does not depend on Linux headers */ struct sandbox_eth_raw_if_nameindex { unsigned int if_index; /* Index of interface (1, 2, ...) */ char *if_name; /* Null-terminated name ("eth0", etc.) */ }; /* Enumerate host network interfaces */ struct sandbox_eth_raw_if_nameindex *sandbox_eth_raw_if_nameindex(void); /* Free the data structure of enumerated network interfaces */ void sandbox_eth_raw_if_freenameindex(struct sandbox_eth_raw_if_nameindex *ptr); /* * Check if the interface named "ifname" is a localhost interface or not. * ifname - the interface name on the host to check * * returns - 0 if real interface, 1 if local, negative if error */ int sandbox_eth_raw_os_is_local(const char *ifname); /* * Look up the name of the interface based on the ifindex populated in priv. * * Overwrite the host_ifname member in priv based on looking up host_ifindex * * returns - 0 if success, negative if error */ int sandbox_eth_raw_os_idx_to_name(struct eth_sandbox_raw_priv *priv); int sandbox_eth_raw_os_start(struct eth_sandbox_raw_priv *priv, unsigned char *ethmac); int sandbox_eth_raw_os_send(void *packet, int length, struct eth_sandbox_raw_priv *priv); int sandbox_eth_raw_os_recv(void *packet, int *length, const struct eth_sandbox_raw_priv *priv); void sandbox_eth_raw_os_stop(struct eth_sandbox_raw_priv *priv); #endif /* __ETH_RAW_OS_H */
C
#include "snake.h" /** @file wprowadzenie_wypisanie_nicku.c \brief Przechowuje definicje funkcji odpowiedzialnych za rysowanie klawiatury, pobranie i wypisanie nicku. */ /** * \fn void wypisz_nick(BITMAP * bufor, char * nick, int dlugosc_nicku) * \brief Funkcja wypisuje nick zawarty w tablicy nick[]. * \param bufor, wskaznik na bitmape, ktora sluzy do podwojnego buforowania. * \param nick, wskaznik na tablice zawierajaca nick gracza * \param dlugosc_nicku, ilosc elementow w tablicy nick[] */ void wypisz_nick(BITMAP * bufor, char * nick, int dlugosc_nicku){ int i, x=580; FONT* cz_wyniki; cz_wyniki = load_font("tekst_wyn.PCX", default_palette, NULL); sprawdzenie_czcionek(cz_wyniki); textprintf_ex( bufor, cz_wyniki, 520, 200, makecol( 68, 232, 187), - 1, "Nick:" ); for(i=0;i<dlugosc_nicku;i++){ textprintf_ex( bufor, cz_wyniki, x, 200, makecol( 68, 232, 187), - 1, "%c", nick[i]); x+=20; } destroy_font(cz_wyniki); } /** * \fn void rys_klaw(int ascii, FONT * czcionka_klaw, BITMAP * litery, BITMAP * bufor) * \brief Funkcja rysuje klawiature ekranowa alfabetyczne. * \param ascii, kod ascii pierwszej rysowanej litery. * \param czcionka_klaw, wskaznik na czcionke, uzywanej do wypisania liter na klawiszach. * \param litery, wskaznik na bitmape ktora sluzy za klawisze. * \param bufor, wskaznik na bitmape ktora sluzy do podwojnego buforowania. */ void rys_klaw(int ascii, FONT * czcionka_klaw, BITMAP * litery, BITMAP * bufor){ int i=0, xz=300, yz=400; for(;i<10;i++){ clear_to_color( litery, makecol( 247, 244, 159)); textprintf_ex( litery, czcionka_klaw, 20, 11, makecol( 0, 0, 0 ), - 1, "%c", i+ascii); blit( litery, bufor, 0, 0, xz, yz, litery->w, litery->h ); xz+=60; } xz=300; yz+=60; for(;i<19;i++){ clear_to_color( litery, makecol( 247, 244, 159)); textprintf_ex( litery, czcionka_klaw, 20, 11, makecol( 0, 0, 0 ), - 1, "%c", i+ascii); blit( litery, bufor, 0, 0, xz, yz, litery->w, litery->h ); xz+=60; } clear_to_color( litery, makecol( 247, 244, 159)); textprintf_ex( litery, font, 3, 15, makecol( 0, 0, 0 ), - 1, "Back"); textprintf_ex( litery, font, 3, 22, makecol( 0, 0, 0 ), - 1, "space"); blit( litery, bufor, 0, 0, xz, yz, litery->w, litery->h ); yz+=60; xz=330; clear_to_color( litery, makecol( 247, 244, 159)); textprintf_ex( litery, font, 5, 20, makecol( 0, 0, 0 ), - 1, "Shift"); blit( litery, bufor, 0, 0, xz, yz, litery->w, litery->h ); xz+=60; for(;i<26;i++){ clear_to_color( litery, makecol( 247, 244, 159)); textprintf_ex( litery, czcionka_klaw, 20, 11, makecol( 0, 0, 0 ), - 1, "%c", i+ascii); blit( litery, bufor, 0, 0, xz, yz, litery->w, litery->h ); xz+=60; } clear_to_color( litery, makecol( 247, 244, 159)); textprintf_ex( litery, font, 5, 20, makecol( 0, 0, 0 ), - 1, "Enter"); blit( litery, bufor, 0, 0, xz, yz, litery->w, litery->h ); blit( bufor, screen, 0, 0, 0, 0, 1280, 720 ); } /** * \fn void pob_nick(char * nick) * \brief Funkcja pobiera i zapisuje nick na tablicy nick[], nick może mieć maksymalnie 10 elementow. * \param nick, wskaznik na tablice zawierajaca nick gracza */ void pob_nick(char * nick){ BITMAP * bufor; bufor = create_bitmap( 1280, 720); sprawdzenie_bitmap(bufor); FONT * czcionka_klaw; czcionka_klaw = load_font("klawiatura.PCX", default_palette, NULL); sprawdzenie_czcionek(czcionka_klaw); BITMAP * litery; litery = create_bitmap(50,50); sprawdzenie_bitmap(litery); int i=0, xz=300, yz=400, ascii=97, dlugosc_nicku=0; do{ clear_to_color( bufor, makecol( 0, 0, 80 ) ); wypisz_nick(bufor,nick,dlugosc_nicku); rys_klaw(ascii,czcionka_klaw,litery,bufor); xz=300; yz=400; if(mouse_b==1){ for(;i<10;i++){ if(mouse_x<xz+60 && mouse_x>xz && mouse_y<yz+60 && mouse_y>yz){ nick[dlugosc_nicku]= i+ascii; dlugosc_nicku++; } xz+=60; } xz=300; yz+=60; for(;i<19;i++){ if(mouse_x<xz+60 && mouse_x>xz && mouse_y<yz+60 && mouse_y>yz){ nick[dlugosc_nicku]= i+ascii; dlugosc_nicku++; } xz+=60; } if(mouse_x<xz+60 && mouse_x>xz && mouse_y<yz+60 && mouse_y>yz){ if(dlugosc_nicku!=0){ dlugosc_nicku--; } } yz+=60; xz=330; if(mouse_x<xz+60 && mouse_x>xz && mouse_y<yz+60 && mouse_y>yz){ if(ascii==97){ ascii=65; } else ascii=97; } xz+=60; for(;i<26;i++){ if(mouse_x<xz+60 && mouse_x>xz && mouse_y<yz+60 && mouse_y>yz){ nick[dlugosc_nicku]= i+ascii; dlugosc_nicku++; } xz+=60; } if(mouse_x<xz+60 && mouse_x>xz && mouse_y<yz+60 && mouse_y>yz){ if(nick[0]==NULL){ allegro_message( "Proszê wprowadziæ nick." ); } else{ if(dlugosc_nicku==6 || dlugosc_nicku == 7 || dlugosc_nicku == 8){ nick[dlugosc_nicku]='\0'; } dlugosc_nicku=10; } } } mouse_b=0; i=0; if(dlugosc_nicku==9){ textprintf_ex( bufor, font, 3, 3, makecol( 0, 0, 255 ), - 1, "Została do dyspozycji ostatnia litera po jej wybraniu pobieranie nicku zakonczy sie." ); } blit( bufor, screen, 0, 0, 0, 0, 1280, 720 ); }while(dlugosc_nicku!=10); destroy_bitmap(bufor); destroy_bitmap(litery); destroy_font(czcionka_klaw); }
C
#include "tl_process.h" #include "tl_thread.h" #include <stdlib.h> #include <stdio.h> static volatile int value = 0; static tl_mutex* mutex; static tl_monitor* mon; static void* mutex_thread( void* arg ) { tl_sleep( 100 ); if( !tl_mutex_lock( mutex, 1000 ) ) exit( EXIT_FAILURE ); if( !tl_mutex_lock( mutex, 1000 ) ) exit( EXIT_FAILURE ); value += 5; tl_mutex_unlock( mutex ); tl_mutex_unlock( mutex ); return arg; } static void* mon_thread( void* arg ) { if( !tl_monitor_lock( mon, 5000 ) ) exit( EXIT_FAILURE ); if( !tl_monitor_wait( mon, 5000 ) ) exit( EXIT_FAILURE ); value += 5; tl_monitor_unlock( mon ); return arg; } int main( void ) { void *a = (void*)0xDEADBEEF, *b = (void*)0xCAFEBABE; tl_thread *t0, *t1; /* mutex & thread */ mutex = tl_mutex_create( 1 ); t0 = tl_thread_create( mutex_thread, a ); t1 = tl_thread_create( mutex_thread, b ); if( !tl_thread_join( t0, 5000 ) ) return EXIT_FAILURE; if( !tl_thread_join( t1, 5000 ) ) return EXIT_FAILURE; if( tl_thread_get_return_value( t0 ) != a ) return EXIT_FAILURE; if( tl_thread_get_return_value( t1 ) != b ) return EXIT_FAILURE; if( value!=10 ) return EXIT_FAILURE; tl_thread_destroy( t0 ); tl_thread_destroy( t1 ); tl_mutex_destroy( mutex ); /* monitor & thread */ mon = tl_monitor_create( ); value = 0; t0 = tl_thread_create( mon_thread, a ); t1 = tl_thread_create( mon_thread, b ); tl_sleep( 100 ); tl_monitor_lock( mon, 5000 ); tl_monitor_notify_all( mon ); tl_monitor_unlock( mon ); if( !tl_thread_join( t0, 5000 ) ) return EXIT_FAILURE; if( !tl_thread_join( t1, 5000 ) ) return EXIT_FAILURE; if( tl_thread_get_return_value( t0 ) != a ) return EXIT_FAILURE; if( tl_thread_get_return_value( t1 ) != b ) return EXIT_FAILURE; if( value!=10 ) return EXIT_FAILURE; tl_monitor_destroy( mon ); tl_thread_destroy( t0 ); tl_thread_destroy( t1 ); /* monitor & thread */ mon = tl_monitor_create( ); value = 0; t0 = tl_thread_create( mon_thread, a ); t1 = tl_thread_create( mon_thread, b ); tl_sleep( 100 ); tl_monitor_lock( mon, 5000 ); tl_monitor_notify( mon ); tl_monitor_notify( mon ); tl_monitor_unlock( mon ); if( !tl_thread_join( t0, 5000 ) ) return EXIT_FAILURE; if( !tl_thread_join( t1, 5000 ) ) return EXIT_FAILURE; if( tl_thread_get_return_value( t0 ) != a ) return EXIT_FAILURE; if( tl_thread_get_return_value( t1 ) != b ) return EXIT_FAILURE; if( value!=10 ) return EXIT_FAILURE; tl_monitor_destroy( mon ); tl_thread_destroy( t0 ); tl_thread_destroy( t1 ); return EXIT_SUCCESS; }
C
//pic12f683 // https://www.youtube.com/watch?v=hkW5O5FCzMg // Button turn on LED //Binary converter: http://www.binaryconvert.com/convert_signed_char.html unsigned char i = 0; void main(void) { TRISIO = 0b00000010; // TRISIO = 0x02; CMCON0 = 0b00000111; //Shutting of comparative module ANSEL = 0; // tells micrcontroller if the port is analog or digital GPIO.B0 = 1; // Turning on port 0 while(1==1) { i = GPIO.B1; if(i == 0) { GPIO.B2 = 0; } if(i == 1) { GPIO.B2 = 1; } Delay_ms(500); } }
C
// °F to °c and K #include <stdio.h> #include <conio.h> void Temperatures (double Fahrenheit); int main (void) { double F; printf("input a Temperatures in °F"); printf("(float)\n:"); scanf("%lf",&F); // printf(" test %d %f",F,F); // getch(); while (F>0) { Temperatures(F); F = 0; scanf("%lf",&F); } printf("bye\n"); return 0; } void Temperatures (double Fahrenheit) { double Celsius,Kelvin; const float E_C = 1.8; const float ADD = 32.0; const float K = 273.16; Celsius = E_C * Fahrenheit +ADD; Kelvin = Celsius * K; printf("%.2f °F = %.2f °C = %.2f K.\n", Fahrenheit,Celsius,Kelvin); printf("Continue (word to quit):"); }
C
// Recursive solution, Time Limit Exceeded int climbStairs(int n) { if(n <= 2) { return n; } else { return climbStairs(n-1) + climbStairs(n-2); } } // DP solution int climbStairs(int n) { vector<int> result(n+1, 0); result[1] = 1; result[2] = 2; for(int i = 3; i <= n; i++) { result[i] = result[i-1] + result[i-2]; } return result[n]; }
C
#include <stdio.h> #include <stdlib.h> #define T 5 int main() { int * pint; int * paux; pint = (int*) calloc(T, sizeof(int*)); for(int i=0; i<T; i++) { printf("%d\n",*(pint+i)); } pint = (int*) malloc(sizeof(int)*T);/**< asigno espacio en memoria del heap para el puntero*/ if(pint==NULL) { printf("\nNo hay espacio en memoria!!"); exit(0); } else { for(int i=0; i<T; i++) { printf("Ingrese un numero: "); scanf("%d", pint+i); } printf("\nNumeros ingresados\n"); for(int i=0; i<T; i++) { printf("%d\n",*(pint+i)); } } paux= (int*)realloc(pint,sizeof(int)*(T+5));/**< asigno mas memoria, se usa auxiliar para evitar perder datos*/ if(paux==NULL) { printf("\nNo hay mas espacio para reasignar!"); } else { pint = paux; for(int i=T; i<T+5; i++) { printf("Ingrese nuevos numeros:"); scanf("%d", pint+i); } printf("\nNumeros ingresados\n"); for(int i=0; i<T+5; i++) { printf("%d\n",*(pint+i)); } } free(pint);/**< para liberar la asignacion del puntero a la dir de memoria del heap cuando ya no se lo utiliza*/ free(paux); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #define MAXLINES 5000 #define BUFSIZE 10000 #define LINES 10 char *line[MAXLINES]; int readlines(char *lineptr[], char *buf, int nlines); void printlines(char *lien[], int nlines, int n); int main(int argc, const char * argv[]) { int n, nlines; char buf[BUFSIZE]; if (argc > 2 && argc == 1) { printf("error: wrong parametr\n"); n = LINES; } else n = abs(atoi(argv[1])); if ((nlines = readlines(line, buf, MAXLINES)) >= 0) { system("clear"); printlines(line, nlines, n); return 0; } else { printf("error: input too big to sort\n"); return 1; } return 0; } #define MAXLEN 1000 int getLine(char *, int); int readlines(char *lineptr[], char *buf, int maxlines) { int len, nlines = 0; char *p = buf, line[MAXLEN]; char *stop = buf + BUFSIZE; while((len = getLine(line, MAXLEN)) > 0) if (nlines >= maxlines || p+len > stop) return -1; else { line[len-1] = '\0'; strcpy(p, line); lineptr[nlines++] = p; p += len; } return nlines; } void printlines(char *line[], int nlines, int n) { int i = 0; int quans; if (n < nlines) { line += (nlines-n); quans = n; } else quans = nlines; for (i = 0; i < quans ; i++) printf("%s\n", *line++); } int getLine(char *line, int len) { int i = 0; char c; for (i = 0; (c=getchar()) != EOF &&c != '\n' && i < len-1; i++) *line++ = c; if (c == '\n') { *line = '\0'; i++; } return i; }
C
//This program receives an integer as a parameter and modifies the array elements by multiplying each one by 10 //Pointers are to be used for the putpose of this program //this program uses the principle of passing by address(reference) #include <stdio.h> void MUL_BY_10(int *arr); //i is a counter //n is the number of elements in the array int i, n; int arr[50];//initialising the array int main(void) { printf("Please enter how many elements you would like for your array\n");//prompting the user to input the number of elements for the array scanf("%d", &n);//reading in the integer for the number of elements printf("Enter elements:\n");//prompting the user to fill the array for(i = 0; i < n; ++i) scanf("%d", arr + i);//reading in the array elements MUL_BY_10(arr);//calling the function to multiply all the array elements by 10 return 0; } //function to multiply each of the array elements by 10 void MUL_BY_10(int *arr) { printf("The array after multiplication has been completed is: \n"); for(int i = 0; i < n; ++i) printf("%d\n", *(arr + i)*10);//printing out the resulting array after the elements have been multiplied }
C
#include<stdio.h> #include "array_util.h" int sum_ints(int L[], int size) { int i; int S = 0; for (i = 0; i < size; i++) { S = S + L[i]; } return S; } int main(void) { int fibo_list[10]; int idx; int S; fibo_list[0] = 1; fibo_list[1] = 1; for (idx = 2; idx < 10; idx++) { fibo_list[idx] = fibo_list[idx - 1] + fibo_list[idx - 2]; } print_ints(fibo_list, 10); S = sum_ints(fibo_list, 10); printf("soma: %d\n", S); }
C
#ifndef _IP_SET_COUNTER_H #define _IP_SET_COUNTER_H /* Copyright (C) 2015 Jozsef Kadlecsik <kadlec@blackhole.kfki.hu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifdef __KERNEL__ static inline void ip_set_add_bytes(u64 bytes, struct ip_set_counter *counter) { atomic64_add((long long)bytes, &(counter)->bytes); } static inline void ip_set_add_packets(u64 packets, struct ip_set_counter *counter) { atomic64_add((long long)packets, &(counter)->packets); } static inline u64 ip_set_get_bytes(const struct ip_set_counter *counter) { return (u64)atomic64_read(&(counter)->bytes); } static inline u64 ip_set_get_packets(const struct ip_set_counter *counter) { return (u64)atomic64_read(&(counter)->packets); } static inline bool ip_set_match_counter(u64 counter, u64 match, u8 op) { switch (op) { case IPSET_COUNTER_NONE: return true; case IPSET_COUNTER_EQ: return counter == match; case IPSET_COUNTER_NE: return counter != match; case IPSET_COUNTER_LT: return counter < match; case IPSET_COUNTER_GT: return counter > match; } return false; } static inline void ip_set_update_counter(struct ip_set_counter *counter, const struct ip_set_ext *ext, u32 flags) { if (ext->packets != ULLONG_MAX && !(flags & IPSET_FLAG_SKIP_COUNTER_UPDATE)) { ip_set_add_bytes(ext->bytes, counter); ip_set_add_packets(ext->packets, counter); } } static inline bool ip_set_put_counter(struct sk_buff *skb, const struct ip_set_counter *counter) { return nla_put_net64(skb, IPSET_ATTR_BYTES, cpu_to_be64(ip_set_get_bytes(counter)), IPSET_ATTR_PAD) || nla_put_net64(skb, IPSET_ATTR_PACKETS, cpu_to_be64(ip_set_get_packets(counter)), IPSET_ATTR_PAD); } static inline void ip_set_init_counter(struct ip_set_counter *counter, const struct ip_set_ext *ext) { if (ext->bytes != ULLONG_MAX) atomic64_set(&(counter)->bytes, (long long)(ext->bytes)); if (ext->packets != ULLONG_MAX) atomic64_set(&(counter)->packets, (long long)(ext->packets)); } #endif /* __KERNEL__ */ #endif /* _IP_SET_COUNTER_H */
C
// // Created by camek on 12/02/2020. // #include "lowerCase.h" #include "ctype.h" #include <stdio.h> void toLowerCase(char sentence[MAX_CHAR]) { int i; for(i = 0; sentence[i] != '\0'; i++) // runs until null terminator is present { sentence[i] = (char) tolower((int)sentence[i]); // casts the char to an ascii value and uses tolower function to make lowercase. } }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> int main() { #ifdef TKD freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif unsigned int n, res; while(1) { scanf("%u", &n); if(n==0) break; res = sqrt(n); if(res*res==n) printf("yes\n"); else printf("no\n"); } return 0; }
C
extern int reverse(int x) { int num=0; for(;x>0;) { num=(num*10) + (x%10); x/=10; } return num; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <netdb.h> #include <pthread.h> #define PORT "80" #define HOSTNAME NULL #define MAX_CONNECTIONS 10 const char header[] = "HTTP/1.1 200 OK\nContent-Type: text/html\r\n\r\n"; char *get_ip(struct sockaddr_in* si) { unsigned char *ipa = (unsigned char*)&si->sin_addr.s_addr; char *ip = (char*) malloc(16 * sizeof(char)); sprintf(ip, "%d.%d.%d.%d", ipa[0], ipa[1], ipa[2], ipa[3]); return ip; } int create_server(void) { static const int yes = 1; struct addrinfo hints, *res; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; if (HOSTNAME == NULL) { // use local network assigned IP instead of 127.0.0.1 hints.ai_flags = AI_PASSIVE; } assert(getaddrinfo(HOSTNAME, PORT, &hints, &res) == 0); int sockfd; // local socket file descriptor // filter through the linked list of results until a connectable socket is found while (res != NULL) { sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (sockfd != -1) { printf("opened socket connection\n"); break; } close(sockfd); res = res->ai_next; } assert(sockfd != -1); // attempt to close an existing socket if it conflicts with sockfd assert(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == 0); // bind to socket before listening for connections assert(bind(sockfd, res->ai_addr, res->ai_addrlen) == 0); assert(listen(sockfd, MAX_CONNECTIONS) == 0); freeaddrinfo(res); return sockfd; } typedef struct peer_t { int fd; struct sockaddr_storage addr; socklen_t addrlen; char *ip; } peer_t; peer_t *create_peer(int sockfd) { peer_t *peer = (peer_t*) malloc(sizeof(peer_t)); peer->addrlen = sizeof(peer->addr); peer->fd = accept(sockfd, (struct sockaddr*)&peer->addr, &peer->addrlen); assert(peer->fd != -1); peer->ip = get_ip((struct sockaddr_in*)&peer->addr); return peer; } void *handle(void *peerp) { peer_t *peer = peerp; char buf[1024]; memset(buf, 0, sizeof(buf) * sizeof(char)); printf("%s connected\n", peer->ip); while (read(peer->fd, buf, sizeof(buf) * sizeof(char)) > 0) { if (buf[0] != -1) { puts(buf); } memset(buf, 0, sizeof(buf) * sizeof(char)); // TODO parse headers/look for HTTP header termination string break; } char message[] = "<h1>Hello</h1>"; char *body = (char*) malloc(sizeof(header) + sizeof(message)); strncat(body, header, sizeof(header)); strncat(body, message, sizeof(message)); send(peer->fd, body, strlen(body), 0); close(peer->fd); free(peer->ip); free(peer); free(body); pthread_exit(0); } int main(void) { int sockfd = create_server(); pthread_t thread; while (1) { peer_t *peer = create_peer(sockfd); pthread_create(&thread, NULL, handle, peer); } close(sockfd); return 0; }
C
/** *_strncat - concatenates two strings *@dest: pointer parameter destination *@src: pointer parameter source *@n: parameter integer number *Return: destination variable */ char *_strncat(char *dest, char *src, int n) { int i = 0, j = 0, x = 0, k = 0, y = 0; while (dest[i]) i++; while (src[y]) y++; if (n < y) { n += i; for (j = i; j < n; j++) { dest[j] = src[x]; x++; } } else { n = i + y; for (k = i; k < n; k++) { dest[k] = src[x]; x++; } } return (dest); }
C
#include <stdio.h> #include <math.h> // Nhap vao 2 day so, tinh gia tri theo cong thuc int main() { float x[100], y[100]; int n, i; float s1, s2; // Nhap du lieu cho mang printf("Nhap so phan tu: "); scanf("%d", &n); for (i = 0; i < n; i++) { printf("Nhap x[%d]: ", i); scanf("%f", &x[i]); printf("Nhap y[%d]: ", i); scanf("%f", &y[i]); } s1 = 0; s2 = 0; for (i = 0; i < n; i++) { s1 += cos(x[i])*sin(y[i]); s2 += (x[i] - y[i]) * (x[i] - y[i]); } s2 = sqrt(s2); printf("s1 = %f\n", s1); printf("s2 = %f\n", s2); return 0; }
C
/* ========================================================================== */ /* === CHOLMOD/MATLAB/mread mexFunction ===================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/MATLAB Module. Copyright (C) 2005-2006, Timothy A. Davis * http://www.suitesparse.com * MATLAB(tm) is a Trademark of The MathWorks, Inc. * -------------------------------------------------------------------------- */ /* [A Z] = mread (filename, prefer_binary) * * Read a sparse or dense matrix from a file in Matrix Market format. * * All MatrixMarket formats are supported. * The Matrix Market "integer" format is converted into real, but the values * are preserved. The "pattern" format is converted into real. If a pattern * matrix is unsymmetric, all of its values are equal to one. If a pattern is * symmetric, the kth diagonal entry is set to one plus the number of * off-diagonal nonzeros in row/column k, and off-diagonal entries are set to * -1. * * Explicit zero entries are returned as the binary pattern of the matrix Z. */ #include "cholmod_matlab.h" /* maximum file length */ #define MAXLEN 1030 void mexFunction ( int nargout, mxArray *pargout [ ], int nargin, const mxArray *pargin [ ] ) { void *G ; cholmod_dense *X = NULL ; cholmod_sparse *A = NULL, *Z = NULL ; cholmod_common Common, *cm ; Long *Ap = NULL, *Ai ; double *Ax, *Az = NULL ; char filename [MAXLEN] ; Long nz, k, is_complex = FALSE, nrow = 0, ncol = 0, allzero ; int mtype ; /* ---------------------------------------------------------------------- */ /* start CHOLMOD and set parameters */ /* ---------------------------------------------------------------------- */ cm = &Common ; cholmod_l_start (cm) ; sputil_config (SPUMONI, cm) ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ if (nargin < 1 || nargin > 2 || nargout > 2) { mexErrMsgTxt ("usage: [A Z] = mread (filename, prefer_binary)") ; } if (!mxIsChar (pargin [0])) { mexErrMsgTxt ("mread requires a filename") ; } mxGetString (pargin [0], filename, MAXLEN) ; sputil_file = fopen (filename, "r") ; if (sputil_file == NULL) { mexErrMsgTxt ("cannot open file") ; } if (nargin > 1) { cm->prefer_binary = (mxGetScalar (pargin [1]) != 0) ; } /* ---------------------------------------------------------------------- */ /* read the matrix, as either a dense or sparse matrix */ /* ---------------------------------------------------------------------- */ G = cholmod_l_read_matrix (sputil_file, 1, &mtype, cm) ; fclose (sputil_file) ; sputil_file = NULL ; if (G == NULL) { mexErrMsgTxt ("could not read file") ; } /* get the specific matrix (A or X), and change to ZOMPLEX if needed */ if (mtype == CHOLMOD_SPARSE) { A = (cholmod_sparse *) G ; nrow = A->nrow ; ncol = A->ncol ; is_complex = (A->xtype == CHOLMOD_COMPLEX) ; Ap = A->p ; Ai = A->i ; if (is_complex) { /* if complex, ensure A is ZOMPLEX */ cholmod_l_sparse_xtype (CHOLMOD_ZOMPLEX, A, cm) ; } Ax = A->x ; Az = A->z ; } else if (mtype == CHOLMOD_DENSE) { X = (cholmod_dense *) G ; nrow = X->nrow ; ncol = X->ncol ; is_complex = (X->xtype == CHOLMOD_COMPLEX) ; if (is_complex) { /* if complex, ensure X is ZOMPLEX */ cholmod_l_dense_xtype (CHOLMOD_ZOMPLEX, X, cm) ; } Ax = X->x ; Az = X->z ; } else { mexErrMsgTxt ("invalid file") ; } /* ---------------------------------------------------------------------- */ /* if requested, extract the zero entries and place them in Z */ /* ---------------------------------------------------------------------- */ if (nargout > 1) { if (mtype == CHOLMOD_SPARSE) { /* A is a sparse real/zomplex double matrix */ Z = sputil_extract_zeros (A, cm) ; } else { /* input is full; just return an empty Z matrix */ Z = cholmod_l_spzeros (nrow, ncol, 0, CHOLMOD_REAL, cm) ; } } /* ---------------------------------------------------------------------- */ /* prune the zero entries from A and set nzmax(A) to nnz(A) */ /* ---------------------------------------------------------------------- */ if (mtype == CHOLMOD_SPARSE) { sputil_drop_zeros (A) ; cholmod_l_reallocate_sparse (cholmod_l_nnz (A, cm), A, cm) ; } /* ---------------------------------------------------------------------- */ /* change a complex matrix to real if its imaginary part is all zero */ /* ---------------------------------------------------------------------- */ if (is_complex) { if (mtype == CHOLMOD_SPARSE) { nz = Ap [ncol] ; } else { nz = nrow * ncol ; } allzero = TRUE ; for (k = 0 ; k < nz ; k++) { if (Az [k] != 0) { allzero = FALSE ; break ; } } if (allzero) { /* discard the all-zero imaginary part */ if (mtype == CHOLMOD_SPARSE) { cholmod_l_sparse_xtype (CHOLMOD_REAL, A, cm) ; } else { cholmod_l_dense_xtype (CHOLMOD_REAL, X, cm) ; } } } /* ---------------------------------------------------------------------- */ /* return results to MATLAB */ /* ---------------------------------------------------------------------- */ if (mtype == CHOLMOD_SPARSE) { pargout [0] = sputil_put_sparse (&A, cm) ; } else { pargout [0] = sputil_put_dense (&X, cm) ; } if (nargout > 1) { pargout [1] = sputil_put_sparse (&Z, cm) ; } /* ---------------------------------------------------------------------- */ /* free workspace */ /* ---------------------------------------------------------------------- */ cholmod_l_finish (cm) ; cholmod_l_print_common (" ", cm) ; }
C
//calcAsFunction #include<stdio.h> #include <stdlib.h> float add(int,int); float subtract(int,int); float multiple(int,int); float divide(int,int); int main() { int a,b; float result; char op; printf("Enter two numbers :\n"); scanf("%d %d",&a,&b); printf("Enter +, -, *, /: "); scanf(" %c",&op); switch(op) { case '+' : result = add(a,b); break; case '-' : result = subtract(a,b); break; case '*' : result = multiple(a,b); break; case '/' : result = divide(a,b); break; default: printf("Invalid"); exit(0); } printf("The result is %f ",result); return 0; } float add(int a,int b) { return (a+b); } float subtract(int a,int b) { return (a-b); } float multiple(int a,int b) { return (a*b); } float divide(int a,int b) { return (a/b); }
C
#include <assert.h> #include <complexe.h> #include <mnblas.h> #include <stdio.h> int main(int argc, char const *argv[]) { printf("TEST DES FONCTIONS BLAS1 COPY :\n"); // ---- FLOAT ---- float af[5] = {1.0, 2.0, 3.0, 4.0, 5.0}; float bf[5]; mncblas_scopy(5, af, 1, bf, 1); int i; for (i = 0; i < 5; i++) { assert(af[i] == bf[i]); } // ---- DOUBLE ---- double ad[5] = {1.0, 2.0, 3.0, 4.0, 5.0}; double bd[5]; mncblas_dcopy(5, ad, 2, bd, 1); for (i = 0; i < 2; i++) { assert(ad[i * 2] == bd[i]); } // ---- COMPLEXE FLOAT ---- complexe_float_t afc[5]; complexe_float_t bfc[5]; for (i = 0; i < 5; i++) { afc[i].imaginary = i; afc[i].real = i; } mncblas_ccopy(4, afc, 1, bfc, 1); for (i = 0; i < 4; i++) { assert(complexe_equal_float(afc[i], bfc[i])); } bfc[4].imaginary = 0; bfc[4].real = 0; assert(!complexe_equal_float(afc[4], bfc[4])); // ---- COMPLEXE DOUBLE ---- complexe_double_t adc[5]; complexe_double_t bdc[5]; for (i = 0; i < 5; i++) { adc[i].imaginary = i; adc[i].real = i; } mncblas_zcopy(5, adc, 1, bdc, 2); for (i = 0; i < 2; i++) { assert(complexe_equal_double(adc[i], bdc[i * 2])); } printf("OK\n"); }
C
/* 输入人名和对应人名买的书籍金额,要求输入根据花费金额大小的人名排行 如输入:名字长度20以内 3 A B C 4 A 1000 B 1000 B 2000 C 2000 输出: B C A 只使用了数组和字符串交换函数 */ #include <stdio.h> #include <string.h> int main(void){ int n, m; scanf("%d", &n); //输入人名个数 char name[n][20]; //名字数组 char book[20]; //临时储存人名变量 int price; //临时储存金额变量 int money[n]; //金额数组 int i, j; //外层和内层循环变量 for (i = 0; i < n; i++){ scanf("%s", name[i]); } for (i = 0; i < n; i++){ //金额数组初始化为零 money[i] = 0; } scanf("%d", &m); //输入金额输入次数 for (i = 0; i < m; i++){ scanf("%s %d", book, &price); for (j = 0; j < n; j++){ if (strcmp(book, name[j]) == 0) //找到对应人名,进行金额累加 money[j] += price; } } //得到和人名数组匹配的金额数组 for (i = 0; i < n - 1; i++){ //对金额数组进行冒泡排序,循环n-1次 for (j = 0; j < n - 1; j++){ if (money[j] < money[j+1]){ price = money[j]; strcpy(book, name[j]); //交换字符串变量,把后一项赋值给前项 money[j] = money[j+1]; strcpy(name[j], name[j+1]); money[j+1] = price; strcpy(name[j+1], book); } } } for (i = 0; i < n; i++){ printf("%s\n", name[i]); } return 0; } //用相同的方法换成结构数组 #include <stdio.h> #include <string.h> struct read { char name[20]; int money; }; //定义一个结构 int main(void){ int n, m; scanf("%d", &n); //输入人名个数 char people[20]; //临时储存人名变量 int price; //临时储存金额变量 int i, j; //外层和内层循环变量 struct read list[n]; //定义结构数组 for (i = 0; i < n; i++){ scanf("%s", list[i].name); //注意!调用结构数组中的数据时[i]跟在数组名list后面而不是变量name后面 } for (i = 0; i < n; i++){ //金额数组初始化为零 list[i].money = 0; } scanf("%d", &m); //输入金额输入次数 for (i = 0; i < m; i++){ scanf("%s %d", people, &price); for (j = 0; j < n; j++){ if (strcmp(people, list[j].name) == 0) //找到对应人名,进行金额累加 list[j].money += price; } } //得到和人名数组匹配的金额数组 for (i = 0; i < n - 1; i++){ //对金额数组进行冒泡排序,循环n-1次 for (j = 0; j < n - 1; j++){ if (list[j].money < list[j+1].money){ price = list[j].money; strcpy(people, list[j].name); //交换字符串变量,把后一项赋值给前项 list[j].money = list[j+1].money; strcpy(list[j].name, list[j+1].name); list[j+1].money = price; strcpy(list[j+1].name, people); } } } for (i = 0; i < n; i++){ printf("%s\n", list[i].name); } return 0; }
C
#ifndef DATASTRUCTURES_BS_TREE_H_ #define DATASTRUCTURES_BS_TREE_H_ #define BST_LINE_T "|--- " #define BST_LINE_L "'--- " #define BST_LINE_I "| " #define BST_BLANK " " typedef int (*tree_cmp_fn)(void *, void *); typedef void (*tree_traverse_fn)(void *, void *); typedef struct tree_node tree_node; struct tree_node { tree_node *left, *right, *parent; void *value; }; typedef struct bst bst; struct bst { tree_cmp_fn cmp; tree_node *root; }; typedef void (*tree_print_fn)(tree_node *); bst *bst_create(tree_cmp_fn cmp); void bst_destroy(bst* tree); tree_node *bst_search_node(bst *tree, void *value); void bst_insert_node(bst *tree, tree_node *node); void bst_replace_node(bst *tree, tree_node *u, tree_node *v); tree_node *bst_minimum(tree_node *node); tree_node *bst_maximum(tree_node *node); tree_node *bst_predecessor(tree_node *x); tree_node *bst_sucessor(tree_node *x); int bst_max_depth(tree_node *node); void bst_traverse(bst *tree, tree_traverse_fn fn, void *param); void bst_print(bst *tree, tree_print_fn fn); static void bst_print_helper(tree_node *node, tree_print_fn fn, int indent); static void bst_sub_traverse(tree_node *node, tree_traverse_fn fn, void *param); static void bst_subtree_destroy(tree_node *node); void bst_left_rotate(bst *tree, tree_node *x); void bst_right_rotate(bst *tree, tree_node *y); #endif // DATASTRUCTURES_BS_TREE_H_
C
#include "srt_quick.h" #include "srt_tools.h" int part(char **a, int lo, int hi) { char *pivot = a[(lo+hi)/2]; int i = lo-1, j = hi+1; while(i < j) { do ++i; while(cmp(pivot, a[i])); do --j; while(cmp(a[j], pivot)); if(i < j) swp(&a[i], &a[j]); } return j; } void srt_quick(char **a, int lo, int hi) { if(lo < hi) { int p = part(a, lo, hi); srt_quick(a, lo, p); srt_quick(a, p+1, hi); } }
C
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { int n; scanf("%d", &n); int row; row = (n*n) - ((n-1)*(n-1)); for (int i=1;i<=row;i++) { for (int j=1;j<=row;j++) { int r,c; int diff; if(row % 2 == 0) { diff = row/2; } if (row % 2 == 1) { diff = row/2 + 1; } r = abs(diff - i) + 1; c = abs(diff - j) + 1; int max; if(r>=c) { printf("%d ",r); } if (c>r) { printf("%d ",c); } } printf("\n"); } return 0; }
C
/** * Zentralbung 10 * * Frage 1 * * Schreiben Sie ein vollstndiges C-Programm welches Personendaten erfasst und in eine Textdatei schreibt. * Erfasst werden sollen der Nachname und das Geburtsjahr der Personen. Es soll zunchst eine Textdatei * erstellt werden und der Nutzer gefragt werden, ob er Daten eingeben mchte. Nachdem Daten eingegeben * wurden, werden alle Eintrge der Textdatei ausgeben. * * Zum Beispiel: * * +---------------+-------------------------------------------------------------------+ * | Eingabe | Result | * +---------------+-------------------------------------------------------------------+ * | 1 | Wollen Sie einen Eintrag in ihr Adressbuch machen? Ja(1) Nein(0) | * | Amberg 1977 | Nachname Geburtsjahr? | * | 1 | | * | Schmidt 1965 | Wollen Sie einen Eintrag in ihr Adressbuch machen? Ja(1) Nein(0) | * | 0 | Nachname Geburtsjahr? | * | | | * | | Wollen Sie einen Eintrag in ihr Adressbuch machen? Ja(1) Nein(0) | * | | | * | | 1. Eintrag: | * | | Amberg, 1977 | * | | | * | | 2. Eintrag: | * | | Schmidt, 1965 | * +---------------+-------------------------------------------------------------------+ * * I/O-Operationen in <stdio.h> * * +----------+-------------------------------------------------------------------------+ * | Funktion | Snytax | * +----------+-------------------------------------------------------------------------+ * | fopen | FILE* fopen(const char * szFilename, const char * szMode) | * | | | * | | Oeffne bzw. erstelle eine Datei. | * | | | * | | Parameter: | * | | szFiename : Name der zu oeffnenden Datei | * | | szMode : Zugriffsart (r,w,a,r+,w+,a+,t,b) | * | | t : textmode, translate mode ("rt", "at+") | * | | b : binary mode ("rb", "ab+") | * | | | * | | Rueckgabewert: | * | | ZEIGER auf Datei. Sonst NULL, wenn Datei nicht erstellt werden kann | * | | oder Datei nicht existiert. * +----------+-------------------------------------------------------------------------+ * | fputs | int fputs(const char * str, FILE * stream) | * | | | * | | Zeilenweise Ausgabe. Schreibt string (= Array von char) auf den Stream. | * | | Schreibt eine Zeile auf den Stream. | * | | | * | | Bei Erfolg gibt fputs eine NICHT-NEGATIVE Ganzzahl (0,1,..) zurueck. | * +----------+-------------------------------------------------------------------------+ * | fputc | int fputc(int char, FILE * stream) | * | | | * | | Zeichenweise Ausgabe auf den Stream. Schreibt ein char auf den Stream. | * +----------+-------------------------------------------------------------------------+ * | fgets | char *fgets(char * str, int n, FILE * stream) | * | | | * | | Zeilenweise Lesen. Liest vom Stream maximale n Zeichenanzahl. | * | | Liest eine Zeile vom Stream nur bis zum naechsten Newline (\n). | * +----------+-------------------------------------------------------------------------+ * | fgetc | int fgetc(FILE * stream) | * | | | * | | Zeichenweise Eingabe. Liest ein (weiteres) char vom Stream. | * +----------+-------------------------------------------------------------------------+ * | fprintf | int fprintf(FILE * stream, const char * format, ...) | * | | | * | | fprintf(stdout, "Hello World!\n"); | * | | | * | | int tag = 10, monat = 12, jahr = 2008; | * | | fprintf(stdout, "Heute ist der %d/%d/%d.", tag, monat, jahr); | * | | | * | | Formatierte Ausgabe. Analog zu printf, nur dass der Stream gewhlt | * | | werden kann. Der Stream ist: stdin, stdout, stderr. | * +----------+-------------------------------------------------------------------------+ * | fscanf | int fprintf(FILE * stream, const char * format, ...) | * | | | * | | int tag, monat, jahr; | * | | printf("Welches Datum ist heute? "); | * | | fscanf(stdin, "%d/%d/%d", &tag, &monat, &jahr); | * | | | * | | Formatierte Eingabe. Analog zu scanf, nur dass der Stream gewhlt | * | | werden kann. Der Stream ist: stdin, stdout, stderr. | * +----------+-------------------------------------------------------------------------+ * | scanf | int scanf(const char * format, ...) | * | | | * | | Formatierete Eingabe. Liest formatierte Inputs aus dem stdin-Stream. | * | | Ist quivalent zu: | * | | fscanf(stdin, ...) == scanf(...) | * +----------+-------------------------------------------------------------------------+ * | fwrite | size_t fwrite(const void *puffer, size_t size, size_t n, FILE *stream) | * | | | * | | Blockweise Ausgabe. Schreibt n Bloecke jeweils der Groesse size von der | * | | Adresse <puffer> auf den Ausgabe-Stream <stream>. | * | | Kurz: Schreibt n*sizeof(size_t) auf den Ausgabe-Stream. | * | | | * | | size_t steht fuer NICHT-NEGATIVE Werte, z.B. usigned int | * | | | * | | Rueckgabewert (Typ size_t): | * | | Wird erfolgreich geschrieben, ist Rueckgabewert genau die Anzahl n | * | | der Bloecke. Sonst gibt es Fehler, g.d.w. Rueckgabewert ungleich n. | * +----------+-------------------------------------------------------------------------+ * | fread | size_t fread(void *puffer, size_t size, size_t n, FILE *stream) | * | | | * | | Blockweise Eingabe. Liest n Bloecke jeweils der Groesse size aus dem | * | | Eingabe-Stream in die Adresse von puffer. | * | | Kurz: Liest n*sizeof(size_t) aus dem Stream in puffer. | * | | | * | | Rueckgabewert (size_t): | * | | Wird erfolgreich eingelesen, ist Rueckgabewert gleich der Anzahl n | * | | der Bloecke. Wird EOF erreicht oder gibt es Fehler, dann ist | * | | Rueckgabewert ungleich n. | * +----------+-------------------------------------------------------------------------+ * | fclose | int fclose(FILE * stream) | * | | | * | | Schliesst den Stream bzw. eine Datei. | * | | | * | | Rueckgabewert (int): | * | | 0 wird zurckgegeben, wenn der Stream (Datei) erfolgreich geschlossen | * | | wird. Sonst wird EOF zurueckgegeben. | * +----------+-------------------------------------------------------------------------+ * | feof | int feof(FILE * stream) | * | | | * | | EOF (End of File) Flag = Kennzeichnet das Ende einer Datei. | * | | feof testet auf EOF, d.h. ob Ende einer Datei (Stream) erreicht ist. | * | | | * | | Rueckgabewert (int): | * | | Liefert 0 zurueck, solange Dateiende nicht erreicht ist. Sonst 0. | * +----------+-------------------------------------------------------------------------+ * * Compile: * gcc -Wall -std=gnu99 -pedantic <quelldatei.c> -o <output.exe> * * -std=c90 -pedantic * -std=c89 -pedantic * -std=c99 -pedantic * -std=gnu99 -pedantic */ #include <stdio.h> #define MAX 30 typedef struct { char szNachname[MAX]; int iGeburtsjahr; }PERSON; int main() { //Dateien ffnen/erstellen FILE* Datei; if((Datei = fopen("neutst.of", "w")) == NULL) { printf("Datei konnte nicht erstellt werden"); return 1; } PERSON Person[5]; int i = 0; int j = 0; int iEintrag = 0; do { printf("Wollen Sie einen Eintrag in ihr Adressbuch machen? Ja(1) Nein(0)"); scanf("%i", &iEintrag); if(iEintrag == 1) { printf("\nNachname Geburtsjahr?\n\n"); scanf("%s" "%i", Person[i].szNachname, &Person[i].iGeburtsjahr); //Schreiben in Datei fprintf(Datei, "\n\n%s %i", Person[i].szNachname, Person[i].iGeburtsjahr); ++i; } }while(iEintrag); //Datei schliessen fclose(Datei); //Datei ffnen im Lesemodus if((Datei = fopen("neutst.of", "r")) == NULL) { printf("Datei konnte nicht erstellt werden"); return 1; } //Auslesen aus Datei i=0; while(feof(Datei) == 0) { if(fscanf(Datei, "%s" "%i", Person[i].szNachname, &Person[i].iGeburtsjahr) == 0) { printf("Fehler beim Einlesen der Datei!"); return 1; } ++i; } for(j = 0; j < i; j++) { printf("\n\n%i. Eintrag:\n%s, %i", j+1, Person[j].szNachname, Person[j].iGeburtsjahr); } //Datei schliessen fclose(Datei); return 0; }