language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> int reverse(int x) { int res=0; while(x!=0) { int tmp=x%10; x=x/10; res=res*10+tmp; } return res; } int main() { int x=123; printf("x=%d,\t x_inv=%d\n",x,reverse(x)); x=-123; printf("x=%d,\t x_inv=%d\n",x,reverse(x)); x=120; printf("x=%d,\t x_inv=%d\n",x,reverse(x)); return 0; }
C
/* -*- Mode: C; tab-width: 8; c-basic-offset: 2; indent-tabs-mode: nil; -*- */ #include "util.h" static void breakpoint(void) { int break_here = 1; (void)break_here; } int main(void){ sleep(1); breakpoint(); atomic_puts("EXIT-SUCCESS"); return 0; }
C
/* SPDX-License-Identifier: GPL-2.0 */ #include <stdio.h> #include <stdlib.h> #include "graph.h" struct vertex { enum color { white, gray, black } color; int data; int hops; }; static int same(const void *d1, const void *d2) { const struct vertex *v1 = d1, *v2 = d2; return v1->data == v2->data; } int main(void) { const struct test { const char *const name; int vertices_size; struct vertex vertices[8]; int edges_size; struct edge { struct vertex from, to; } edges[16]; int want_vcount; int want_ecount; struct path { struct vertex from, to; } path; int want_path_size; int want_path[16]; } *t, tests[] = { { .name = "two vertices directed graph, 1 -> 2", .vertices_size = 2, .vertices = {{.data = 1}, {.data = 2}}, .edges_size = 1, .edges = {{{.data = 1}, {.data = 2}}}, .want_vcount = 2, .want_ecount = 1, .path = {{.data = 1}, {.data = 2}}, .want_path_size = 2, .want_path = {1, 2}, }, { .name = "two vertices directed graph, 1 <- 2", .vertices_size = 2, .vertices = {{.data = 1}, {.data = 2}}, .edges_size = 1, .edges = {{{.data = 1}, {.data = 2}}}, .want_vcount = 2, .want_ecount = 1, .path = {{.data = 2}, {.data = 1}}, .want_path_size = 1, .want_path = {2}, }, {.name = NULL}, }; int fail = 0; for (t = tests; t->name; t++) { struct graph g; int i, ret; ret = graph_init(&g, same, NULL); if (ret == -1) goto perr; for (i = 0; i < t->vertices_size; i++) { ret = graph_ins_vertex(&g, &t->vertices[i]); if (ret == -1) goto perr; } for (i = 0; i < t->edges_size; i++) { ret = graph_ins_edge(&g, &t->edges[i].from, &t->edges[i].to); if (ret == -1) goto perr; } if (graph_vcount(&g) != t->want_vcount) { fprintf(stderr, "%s: unexpected vertex count:\n\t- want: %d\n\t- got: %d\n", t->name, t->want_vcount, graph_vcount(&g)); goto err; } if (graph_ecount(&g) != t->want_ecount) { fprintf(stderr, "%s: unexpected edge count:\n\t- want: %d\n\t- got: %d\n", t->name, t->want_ecount, graph_ecount(&g)); goto err; } for (i = 0; i < t->edges_size; i++) { struct vertex *got = (struct vertex *)&t->edges[i].to; ret = graph_rem_edge(&g, &t->edges[i].from, (void **)&got); if (ret == -1) goto perr; } for (i = 0; i < t->vertices_size; i++) { struct vertex *got = (struct vertex *)&t->vertices[i]; ret = graph_rem_vertex(&g, (void **)&got); if (ret == -1) goto perr; } if (graph_vcount(&g)) { fprintf(stderr, "%s: unexpected final vertex count:\n\t- want: 0\n\t- got: %d\n", t->name, graph_vcount(&g)); goto err; } if (graph_ecount(&g)) { fprintf(stderr, "%s: unexpected final edge count:\n\t- want: 0\n\t- got: %d\n", t->name, graph_ecount(&g)); goto err; } graph_destroy(&g); continue; perr: perror(t->name); err: fail++; } if (fail) exit(EXIT_FAILURE); exit(EXIT_SUCCESS); }
C
#include<stdio.h> int qiu(int n){ if(n<4){ return 1; }else{ return qiu(n-1)+qiu(n-3); } } int main(void){ int n; scanf("%d",&n); int nums = qiu(n); printf("%d\n",nums); return 0; }
C
#include <stdio.h> #include <string.h> int main() { char string[500]; scanf("%[^\n]", string); printf("%d\n", (int) strlen(string)); return(0); }
C
//void fun(int *a,int n){ // int i; // for(i=0;i<n;i++) // printf("%d\n",a[i]); //} //int main(){ // int a[5]={1,2,3,4,5}; // fun(a,5); //} //void fun(int a[],int n){ // int i; // for(i=0;i<7;i++) // printf("%d\n",a[i]); //} //int main(){ // int a[5]={1,2,3,4,5}; // fun(a,5); //} //void fun(int *a,int n){ //// int i; //// for(i=0;i<n;i++) //// printf("%d\n",a[i]); // //// a[1]=22; //} //int main(){ // int a[5]={1,2,3,4,5}; // fun(a,5); // printf("%d",a[1]); //}
C
//BUBBLE SORT #include <stdio.h> int main() { int i,j,n; printf("enter the size of the array\n"); scanf("%d",&n); char a[n],temp; printf("enter the characters into the array\n"); for(i=0;i<=n-1;i++) scanf(" %c",&a[i]); for(i=0;i<=n-2;i++) for(j=0;j<=n-i-1;j++) { if(a[j]>a[j+1]) { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } printf("the array in sorted order is \n"); for(i=0;i<=n-1;i++) printf("%c",a[i]); return(0); }
C
#include <stdlib.h> #include <stdio.h> #include "card.h" #include "cardlist.h" #include "memwatch.h" /* * purpose : create a new circularly linked list * input : None * returns : An intitalized circularly linked list */ List list_create(){ return NULL; } /* * purpose : create a new node with a link, a private function * input : new_card - the card to insert into the node * next - the node to link this one to. Links to itself if NULL * return : a new node for the list */ static Node* create_node(Card new_card, Node *next){ Node *new_node = (Node *) malloc(sizeof(Node)); if (new_node == NULL){ perror("malloc"); return NULL; } new_node->data=new_card; //make this node circular instead of defaulting to NULL if (next != NULL){ new_node->next=next; } else { new_node->next=new_node; } return new_node; } /* * purpose : add a card to the start of the list * input : list - a pointer to the list to add to * new_card - the card to add to the list * return : 1 if successful */ int list_add_start(List *list, Card new_card){ if (*list == NULL){ //The list is empty, so the node we create is the whole thing *list = create_node(new_card,*list); if (*list == NULL){ return 0; } } else { //The list has an element, so go to the begining and add it there (*list)->next = create_node(new_card, (*list)->next); if ((*list)->next == NULL){ return 0; } } return 1; } /* * purpose : Add a node to the end of the list * input : list - a pointer to the list to add to * new_card - the card to add * return : 1 if successful. */ int list_add_end(List *list, Card new_card){ // in a circularly linked list, adding to the end is the same as // adding to the begining, but you shift where you point if (list_add_start(list, new_card) == 1){ *list=(*list)->next; return 1; } else { return 0; } } /* * purpose : Find a card in the list * input : list - the list to search * needle - the card to find * comparitor - function to be used to compare two cards. Return 0 on match. * return : the card found or INVALID_CARD */ Card list_find(List list, Card needle, int (*comparitor)(Card,Card)){ Node *curr; // start at the begining and go till yo uget back to the end for( curr=list->next; curr != list; curr = curr->next){ if(comparitor(curr->data,needle)==0){ return curr->data; } } //if you get to the end, check if it's the one if(comparitor(curr->data,needle)==0){ return curr->data; } return INVALID_CARD; } /* * purpose : delete the searched or card * input : list - a pointer to the list to delete from * needle - the card to delete * return : none */ void list_delete(List *list, Card needle){ Node *prev=*list; Node *curr; if (*list == NULL){ return; } //in a circularly link list, start at the start and go till the end for( curr=(*list)->next; curr != *list; curr = curr->next){ if(card_compare(curr->data,needle)==0){ break; } prev = curr; } //once you have wrapped around, check if the end is the one if (curr == *list && card_compare(curr->data,needle)!=0){ return; } if (prev == curr){ //this was the last item in the list *list=NULL; } else { //remove the one we found prev->next=curr->next; } if (curr == *list){ //if we removed the last item in the list, shuft the tail pointer back *list=prev; } free(curr); } /* * purpose : free the list * input : list - a pointer to the list to free * return : none */ void list_free(List *list){ Node *prev=*list; Node *curr; if (*list == NULL){ return; } //start at the start and go to the end in a circular list for( curr=(*list)->next; curr != *list; curr = curr->next){ free(prev); prev = curr; } free(prev); } /* * purpose : print out all the cards in the list * input : list - the list to print * return : nothing (printing to the screen is a side effect) */ void list_print(List list){ Node *curr; if (list == NULL){ return; } //start at the start and go to the end in a circular list for( curr=list->next; curr != list; curr = curr->next){ card_print(curr->data); printf(","); } card_print(curr->data); }
C
// The following code was written by Aman Patel // January 28, 2020 // CSCI-C 291 #include<stdio.h> int main(void) { // Initialization of all statistical variables int totalAll = 0; int totalInternational = 0; int totalDomestic = 0; int totalWeekly = 0; int totalHourly = 0; int totalCommission = 0; int totalPiece = 0; int currentNumber; unsigned char currentPaycode; printf("\nWelcome to the Salary Calculator"); // while loop continues until the paycode entered is Q or q (quit) while(currentPaycode != 'Q' && currentPaycode != 'q') { printf("\nPlease enter one of the following codes:\n\n\t\t\tWeekly Workers (W or w)\n\t\t\tHourly Workers (H or h)\n\t\t\tCommission Workers (C or c)\n\t\t\tPieceworkers (P or p)\n\t\t\tQuit (Q or q)\n"); scanf(" %c", &currentPaycode); // checks if first paycode is Q or q if (currentPaycode == 'Q' || currentPaycode == 'q') { printf("\nFinal Statistics:\nTotal for All employees: %d\nTotal for International employees: %d\nTotal for Domestic employees: %d\nTotal for Weekly Workers: %d\nTotal for Hourly Workers: %d\nTotal for Commission Workers: %d\nTotal for Pieceworkers: %d\n\n", totalAll, totalInternational, totalDomestic, totalWeekly, totalHourly, totalCommission, totalPiece); break; } printf("Enter the number of employees of that type: "); scanf(" %d", &currentNumber); // initialization of variables specific to each employee int currentHours; int currentSalary; char currentBackground; int currentWeekly; int currentHourly; int currentPiece; int currentPieceValue; int numberOfItems; int doWhileIterator = 0; int j = 0; int i; // compares value of currentPaycode to cases switch(currentPaycode) { case 'W': for (i = 0; i < currentNumber; i++) { printf("Enter the number of hours Employee %d worked: ", i + 1); scanf(" %d", &currentHours); printf("Enter the weekly salary for Employee %d: ", i + 1); scanf(" %d", &currentWeekly); printf("If the worker is international, please enter (I or i). Otherwise, enter (D or d): "); scanf(" %c", &currentBackground); // checks if the employee is international if (currentBackground == 'I' || currentBackground == 'i') { if (currentHours > 20) { printf("\nEmployee %d worked too many hours this week.\n", i + 1); currentHours = 20; } currentSalary = currentWeekly; // edits values of all relevant statistics and prints the current employees weekly wage totalAll = totalAll + currentSalary; totalInternational = totalInternational + currentSalary; totalWeekly = totalWeekly + currentSalary; printf("\nEmployee %d earned $%d this week.\n\n", i + 1, currentSalary); } else if (currentBackground == 'D' || currentBackground == 'd') { currentSalary = currentWeekly; totalAll = totalAll + currentSalary; totalDomestic = totalDomestic + currentSalary; totalWeekly = totalWeekly + currentSalary; printf("\nEmployee %d earned $%d this week.\n\n", i + 1, currentSalary); } else { printf("Invalid input"); } } break; case 'w': while(j < currentNumber) { printf("Enter the number of hours Employee %d worked: ", j+1); scanf(" %d", &currentHours); printf("Enter the weekly salary for Employee %d: ", j+1); scanf(" %d", &currentWeekly); printf("If the worker is international, please enter (I or i). Otherwise, enter (D or d): "); scanf(" %c", &currentBackground); if (currentBackground == 'I' || currentBackground == 'i') { if (currentHours > 20) { printf("\nEmployee %d worked too many hours this week.\n", j+1); currentHours = 20; } currentSalary = currentWeekly; totalAll = totalAll + currentSalary; totalInternational = totalInternational + currentSalary; totalWeekly = totalWeekly + currentSalary; printf("\nEmployee %d earned $%d this week.\n\n", j + 1, currentSalary); } else if (currentBackground == 'D' || currentBackground == 'd') { currentSalary = currentWeekly; totalAll = totalAll + currentSalary; totalDomestic = totalDomestic + currentSalary; totalWeekly = totalWeekly + currentSalary; printf("\nEmployee %d earned $%d this week.\n\n", j + 1, currentSalary); } else { printf("Invalid input"); } j++; } break; case 'H': for (i = 0; i < currentNumber; i++) { printf("Enter the number of hours Employee %d worked: ", i + 1); scanf(" %d", &currentHours); printf("Enter the hourly wage for Employee %d: ", i + 1); scanf(" %d", &currentHourly); printf("If the worker is international, please enter (I or i). Otherwise, enter (D or d): "); scanf(" %c", &currentBackground); if (currentBackground == 'I' || currentBackground == 'i') { if (currentHours > 20) { printf("\nEmployee %d worked too many hours this week.\n", i + 1); currentHours = 20; } currentSalary = currentHourly; totalAll = totalAll + currentSalary; totalInternational = totalInternational + currentSalary; totalHourly = totalHourly + currentSalary; printf("\nEmployee %d earned $%d this week.\n\n", i + 1, currentSalary); } else if (currentBackground == 'D' || currentBackground == 'd') { currentSalary = currentHourly; totalAll = totalAll + currentSalary; totalDomestic = totalDomestic + currentSalary; totalHourly = totalHourly + currentSalary; printf("\nEmployee %d earned $%d this week.\n\n", i + 1, currentSalary); } else { printf("Invalid input"); } } break; case 'h': while(j < currentNumber) { printf("Enter the number of hours Employee %d worked: ", j+1); scanf(" %d", &currentHours); printf("Enter the hourly wage for Employee %d: ", j+1); scanf(" %d", &currentHourly); printf("If the worker is international, please enter (I or i). Otherwise, enter (D or d): "); scanf(" %c", &currentBackground); if (currentBackground == 'I' || currentBackground == 'i') { if (currentHours > 20) { printf("\nEmployee %d worked too many hours this week.\n", j+1); currentHours = 20; } if (currentHours > 10) { currentSalary = (10 * currentHourly) + (1.5 * (currentHours - 10) * currentHourly); } else { currentSalary = (currentHourly * currentHours); } totalAll = totalAll + currentSalary; totalInternational = totalInternational + currentSalary; totalHourly = totalHourly + currentSalary; printf("\nEmployee %d earned $%d this week.\n\n", j + 1, currentSalary); } else if (currentBackground == 'D' || currentBackground == 'd') { if (currentHours > 10) { currentSalary = (10 * currentHourly) + (1.5 * (currentHours - 10) * currentHourly); } else { currentSalary = (currentHourly * currentHours); } totalAll = totalAll + currentSalary; totalDomestic = totalDomestic + currentSalary; totalHourly = totalHourly + currentSalary; printf("\nEmployee %d earned $%d this week.\n\n", j + 1, currentSalary); } else { printf("Invalid input"); } j++; } break; case 'C': for (i = 0; i < currentNumber; i++) { printf("Enter the number of hours Employee %d worked: ", i + 1); scanf(" %d", &currentHours); printf("If the worker is international, please enter (I or i). Otherwise, enter (D or d): "); scanf(" %c", &currentBackground); if (currentBackground == 'I' || currentBackground == 'i') { if (currentHours > 20) { printf("\nEmployee %d worked too many hours this week.\n", i + 1); currentHours = 20; } currentSalary = (currentHours * 7.1) + 250; totalAll = totalAll + currentSalary; totalInternational = totalInternational + currentSalary; totalCommission = totalCommission + currentSalary; printf("\nEmployee %d earned $%d this week.\n\n", i + 1, currentSalary); } else if (currentBackground == 'D' || currentBackground == 'd') { currentSalary = (currentHours * 7.1) + 250; totalAll = totalAll + currentSalary; totalDomestic = totalDomestic + currentSalary; totalCommission = totalCommission + currentSalary; printf("\nEmployee %d earned $%d this week.\n\n", i + 1, currentSalary); } else { printf("Invalid input"); } } break; case 'c': do { printf("Enter the number of hours Employee %d worked: ", doWhileIterator + 1); scanf(" %d", &currentHours); printf("If the worker is international, please enter (I or i). Otherwise, enter (D or d): "); scanf(" %c", &currentBackground); if (currentBackground == 'I' || currentBackground == 'i') { if (currentHours > 20) { printf("\nEmployee %d worked too many hours this week.\n", doWhileIterator + 1); currentHours = 20; } currentSalary = (currentHours * 7.1) + 250; totalAll = totalAll + currentSalary; totalInternational = totalInternational + currentSalary; totalCommission = totalCommission + currentSalary; printf("\nEmployee %d earned $%d this week.\n\n", doWhileIterator + 1, currentSalary); } else if (currentBackground == 'D' || currentBackground == 'd') { currentSalary = (currentHours * 7.1) + 250; totalAll = totalAll + currentSalary; totalDomestic = totalDomestic + currentSalary; totalCommission = totalCommission + currentSalary; printf("\nEmployee %d earned $%d this week.\n\n", doWhileIterator + 1, currentSalary); } else { printf("Invalid input"); } doWhileIterator++; } while(doWhileIterator < currentNumber); doWhileIterator = 0; break; case 'P': do { printf("Enter the number of pieces Employee %d produced: ", doWhileIterator + 1); scanf(" %d", &currentPiece); printf("Enter the value of each piece for Employee %d: ", doWhileIterator + 1); scanf(" %d", &currentPieceValue); printf("If the worker is international, please enter (I or i). Otherwise, enter (D or d): "); scanf(" %c", &currentBackground); if (currentBackground == 'I' || currentBackground == 'i') { currentSalary = currentPiece * currentPieceValue; totalAll = totalAll + currentSalary; totalInternational = totalInternational + currentSalary; totalPiece = totalPiece + currentSalary; printf("\nEmployee %d earned $%d this week.\n\n", doWhileIterator + 1, currentSalary); } else if (currentBackground == 'D' || currentBackground == 'd') { currentSalary = currentPiece * currentPieceValue; totalAll = totalAll + currentSalary; totalDomestic = totalDomestic + currentSalary; totalPiece = totalPiece + currentSalary; printf("\nEmployee %d earned $%d this week.\n\n", doWhileIterator + 1, currentSalary); } else { printf("Invalid input"); } doWhileIterator++; } while (doWhileIterator < currentNumber); doWhileIterator = 0; break; case 'p': while(j < currentNumber) { printf("Enter the number of pieces Employee %d produced: ", j + 1); scanf(" %d", &currentPiece); printf("Enter the value of each piece for Employee %d: ", j + 1); scanf(" %d", &currentPieceValue); printf("If the worker is international, please enter (I or i). Otherwise, enter (D or d): "); scanf(" %c", &currentBackground); if (currentBackground == 'I' || currentBackground == 'i') { if (currentHours > 20) { printf("\nEmployee %d worked too many hours this week.\n", j+1); currentHours = 20; } currentSalary = currentPiece * currentPieceValue; totalAll = totalAll + currentSalary; totalInternational = totalInternational + currentSalary; totalPiece = totalPiece + currentSalary; printf("\nEmployee %d earned $%d this week.\n\n", j + 1, currentSalary);; } else if (currentBackground == 'D' || currentBackground == 'd') { currentSalary = currentPiece * currentPieceValue; totalAll = totalAll + currentSalary; totalDomestic = totalDomestic + currentSalary; totalPiece = totalPiece + currentSalary; printf("\nEmployee %d earned $%d this week.\n\n", j + 1, currentSalary);; } else { printf("Invalid input"); } j++; } break; default : // if the given paycode is not one of the preceding 8 cases, "Invalid paycode" is printed printf("Invalid paycode"); } } }
C
#include "avr.h" #include "lcd.h" #define DDR DDRB #define PORT PORTB #define RS_PIN 0 #define RW_PIN 1 #define EN_PIN 2 /*sets the direction of the avr to output (11111111) */ static inline void set_data(unsigned char x) { PORTD = x; DDRD = 0xff; } /*sets DDRD as a input then return the input pin */ static inline unsigned char get_data(void) { DDRD = 0x00; return PIND; } /*NOP() is just used to burn cpu cycles, this NOP() function is defined directly within the AVR */ static inline void sleep_700ns(void) { NOP(); NOP(); NOP(); } static unsigned char input(unsigned char rs) { unsigned char d; if (rs) SET_BIT(PORT, RS_PIN); else CLR_BIT(PORT, RS_PIN); SET_BIT(PORT, RW_PIN); get_data(); SET_BIT(PORT, EN_PIN); sleep_700ns(); d = get_data(); CLR_BIT(PORT, EN_PIN); return d; } /*output function, used to actually write to the lcd, we need to set */ static void output(unsigned char d, unsigned char rs) { if (rs) SET_BIT(PORT, RS_PIN); else CLR_BIT(PORT, RS_PIN); CLR_BIT(PORT, RW_PIN); set_data(d); SET_BIT(PORT, EN_PIN); sleep_700ns(); CLR_BIT(PORT, EN_PIN); } /*safe way to write to the lcd while we keep reading, however if it is busy, then the write will wait thats why we have the while loop, it will read if it can, if not it will wait*/ static void write(unsigned char c, unsigned char rs) { while (input(0) & 0x80); output(c, rs); } /*specific initialization methods, needed to configure the lcd*/ void lcd_init(void) { SET_BIT(DDR, RS_PIN); SET_BIT(DDR, RW_PIN); SET_BIT(DDR, EN_PIN); avr_wait(16); output(0x30, 0); avr_wait(5); output(0x30, 0); avr_wait(1); write(0x3c, 0); write(0x0c, 0); write(0x06, 0); write(0x01, 0); } void lcd_clr(void) { write(0x01, 0); } /*used to move the lcd position, the lcd is made up of two rows*/ void lcd_pos(unsigned char r, unsigned char c) { unsigned char n = r * 40 + c; write(0x02, 0); while (n--) { write(0x14, 0); } } void lcd_put(char c) { write(c, 1); } /*puts1 used the data program space to store the chars allows us to store more on the AVR but the draw back is that it is slower access time*/ void lcd_puts1(const char *s) { char c; while ((c = pgm_read_byte(s++)) != 0) { write(c, 1); } } /*simplier write to lcd method */ void lcd_puts2(const char *s) { char c; while ((c = *(s++)) != 0) { write(c, 1); } }
C
#include <msp430.h> #include <stdint.h> #include "led_control.h" // Transmit codes to send long pulse (1) and short pulse (0). #define HIGH_CODE (0xF0) // b11110000 #define LOW_CODE (0xC0) // b11000000 // Board size #define NUM_LEDS 128 #define COLUMNS 8 #define ROWS 16 // LED colors #define OFF 0 #define RED 1 #define GREEN 2 #define BLUE 3 #define RED_FADE_1 4 #define RED_FADE_2 5 #define RED_FADE_3 6 #define BLUE_FADE_1 7 #define BLUE_FADE_2 8 #define BLUE_FADE_3 9 #define GREEN_FADE_1 10 #define GREEN_FADE_2 11 #define GREEN_FADE_3 12 #define YELLOW 13 #define PURPLE 14 #define BRIGHTNESS 3 // WS2812 LEDs require GRB format typedef struct { unsigned char green; unsigned char red; unsigned char blue; } LED; LED expanded_color = {0, 0, 0}; // Single object colors are expaded into. /* Sets the color of the led at index led in led_board * encoded into one byte. */ void set_color(unsigned int led, uint8_t color, uint8_t *led_board) { led_board[led] = color; } /* Expands the encoded color at index led in led_board to 8 bit hexadecimal * for SPI transmission. */ void expand_color(unsigned int led, uint8_t *led_board) { expanded_color.red = 0x00; expanded_color.green = 0x00; expanded_color.blue = 0x00; switch (led_board[led]) { case RED: expanded_color.red = (0x08 * BRIGHTNESS); break; case GREEN: expanded_color.green = (0x08 * BRIGHTNESS); break; case BLUE: expanded_color.blue = (0x08 * BRIGHTNESS); break; case RED_FADE_1: expanded_color.red = (0x04 * BRIGHTNESS); break; case RED_FADE_2: expanded_color.red = (0x02 * BRIGHTNESS); break; case RED_FADE_3: expanded_color.red = (0x01 * BRIGHTNESS); break; case BLUE_FADE_1: expanded_color.blue = (0x04 * BRIGHTNESS); break; case BLUE_FADE_2: expanded_color.blue = (0x02 * BRIGHTNESS); break; case BLUE_FADE_3: expanded_color.blue = (0x01 * BRIGHTNESS); break; case GREEN_FADE_1: expanded_color.green = (0x04 * BRIGHTNESS); break; case GREEN_FADE_2: expanded_color.green = (0x02 * BRIGHTNESS); break; case GREEN_FADE_3: expanded_color.green = (0x01 * BRIGHTNESS); break; case YELLOW: expanded_color.red = (0x12 * BRIGHTNESS); expanded_color.green = (0x09 * BRIGHTNESS); break; case PURPLE: expanded_color.red = (0x08 * BRIGHTNESS); expanded_color.blue = (0x08 * BRIGHTNESS); break; default: break; } } /* Sets the color of all LEDs on the board to black. */ void clear_strip(uint8_t *led_board) { fill_strip(OFF, led_board); } /* Sets every LED on the board to the same color. * Transmits the updated board state. */ void fill_strip(uint8_t color, uint8_t *led_board) { int i; for (i = 0; i < NUM_LEDS; i++) { set_color(i, color, led_board); } refresh_board(led_board); // refresh strip } /* Writes the contents of LED_BOARD to the grid of WS2812 LEDs. * * These LEDs transmit and interpret information via an NRZ protocol. This * requires transmitting each bit as a long (550 - 850) or short * (200 - 500) pulse representing a 1 or a 0 respectively. * * SPI is used for to send a number of 1's set by the macros HIGH_CODE and * LOW_CODE for timing purposes. * * After writing the entire contents of LED_BOARD, this function delays for * 50us to ensure future calls overwrite the current LED board state. (50us * delay communicates end of new data). */ void refresh_board(uint8_t *led_board) { // Disable interrupts to avoid normal SPI driven protocols. __bic_SR_register(GIE); // send RGB color for every LED unsigned int i, j; for (i = 0; i < NUM_LEDS; i++) { expand_color(i, led_board); unsigned char *rgb = (unsigned char *)&expanded_color; // get GRB color for this LED // Transmit the colors in GRB order. for (j = 0; j < 3; j++) { // Mask out the MSB of each byte first. unsigned char mask = 0x80; // Send each of the 8 bits as long and short pulses. while (mask != 0) { // Wait on the previous transmission to complete. while (!(IFG2 & UCA0TXIFG)) ; if (rgb[j] & mask) { UCA0TXBUF = HIGH_CODE; // Send a long pulse for 1. } else { UCA0TXBUF = LOW_CODE; // Send a short pulse for 0. } mask >>= 1; // Send the next bit. } } } // Delay for at least 50us to send RES code and signify end of transmission. __delay_cycles(800); // Re-enable interrupts __bis_SR_register(GIE); }
C
#include <stdio.h> void fun(a,b) { printf("a=%d,b=%d\n",a,b); } main() { int m=5; fun(m+3, m++); }
C
// UCLA CS 111 Lab 1 command reading #include <string.h> #include "command.h" #include "command-internals.h" #include <stdio.h> #include <stdlib.h> #include <error.h> #define PRECEDENCE_SEMI_NEWLINE 1 #define PRECEDENCE_AND_OR 2 #define PRECEDENCE_PIPE 3 #define INITIAL_SIZE 1024 typedef struct commandNode *command_node_t; typedef struct opstack *OpStackNode; typedef struct comstack *comStackNode; typedef struct op operator; struct op { int precedence; char *data; }; struct commandNode { command_t rootCommand; //root of tree command_node_t next; }; struct command_stream { command_node_t head; command_node_t tail; }; struct opstack { operator *data; OpStackNode next; }; struct comstack { command_t data; comStackNode next; }; comStackNode comStackHead; OpStackNode opStackHead; command_stream_t comStreamT; bool newTreeFlg2 = false; void popAndCombine(); bool inputFlg2 = false; bool outputFlg2 = false; char* substring(char* s, int l); command_node_t addToCommandStream(command_t newNode) { //if steam is empty command_node_t temp=(command_node_t)checked_malloc(sizeof(struct commandNode)); temp->rootCommand=newNode; if (!comStreamT->head) { comStreamT->head = temp; comStreamT->tail = temp; } //if stream is not empty, add to end of stream else { comStreamT->tail->next = temp; comStreamT->tail = comStreamT->tail->next; comStreamT->tail->next=NULL; } } OpStackNode popOp() { OpStackNode tmp = opStackHead; //tmp->next=(OpStackNode)checked_malloc(sizeof(struct opstack)); if(tmp) { opStackHead=opStackHead->next; tmp->next=NULL; } return tmp; } void pushOp(OpStackNode current) { current->next=opStackHead; opStackHead=current; } comStackNode popCom() { comStackNode tmp = comStackHead; //tmp->next=(comStackNode)checked_malloc(sizeof(struct comstack)); if(tmp) { comStackHead=comStackHead->next; tmp->next=NULL; } return tmp; } void pushCom(comStackNode cur) { cur->next=comStackHead; comStackHead=cur; } char handleCharacter(char c, char prev, int flgFirst); void reallocate(); void growTree(char* tmp, bool newTreeFlg, bool inputFlg, bool outputFlg); char* tempArray; int globalFlg=0; int twoConsNewLines=0; bool lastSentOp=false; bool lastOr=false; bool lastAnd=false; command_stream_t make_command_stream (int (*get_next_byte) (void *), void *get_next_byte_argument) { int c; tempArray=(char*)checked_malloc(sizeof(char)*INITIAL_SIZE); comStackHead=(comStackNode)checked_malloc(sizeof(struct comstack)); opStackHead=(OpStackNode)checked_malloc(sizeof(struct opstack)); comStreamT=(command_stream_t)checked_malloc(sizeof(struct command_stream)); opStackHead->next=NULL; comStackHead->next=NULL; comStreamT->head=NULL; comStreamT->tail=NULL; int index=0; char prev=' '; while(1) { c=get_next_byte(get_next_byte_argument); //test: printf("\n Next byte is %c",c); if(c==EOF) { if(lastSentOp) error (2, 0, "not implemented"); if(globalFlg) { if(twoConsNewLines) { if(strcmp(tempArray," ")!=0) { while(tempArray[0]==' ') tempArray++; while(tempArray[strlen(tempArray)-1]==' ') tempArray[strlen(tempArray)-1]='\0'; growTree(tempArray,1,0,0); } } else { if(strcmp(tempArray," ")!=0) { while(tempArray[0]==' ') tempArray++; while(tempArray[strlen(tempArray)-1]==' ') tempArray[strlen(tempArray)-1]='\0'; growTree(tempArray,0,0,0); } } } else { if(strcmp(tempArray," ")!=0) { while(tempArray[0]==' ') tempArray++; while(tempArray[strlen(tempArray)-1]==' ') tempArray[strlen(tempArray)-1]='\0'; growTree(tempArray,0,0,0); } } //test: printf("\n reached end of file."); while(opStackHead->data){ popAndCombine(); } //add tree to stream command_t nodeToAdd = popCom()->data; addToCommandStream(nodeToAdd); //clear stacks comStackHead = NULL; opStackHead = NULL; newTreeFlg2 = false; break; } if(index==0) { if(c==";"||c=='<'||c=='>'||c==')'||c=='|'||c=='&'||c=='`') { error (1, 0, "not implemented"); } prev=handleCharacter(c,'-',index); //test: printf("\n Previous charcter is %c",prev); if(prev==' ') index=0; if(prev==';') { prev=' '; index=0; } } else { prev=handleCharacter(c,prev,index); //test: printf("\n Previous charcter is %c",prev); } index++; } return comStreamT; } command_t read_command_stream (command_stream_t s) { if(s->head) { command_t returnValue=s->head->rootCommand; command_node_t tmp=s->head; s->head=s->head->next; free(tmp); return returnValue; } return NULL; } bool comment=false; int reallocSize=1024; int reallocCheck=0; int outputGlobalFlag=0; int inputGlobalFlag=0; int inputGlobalFlag2=0; int outputGlobalFlag2=0; char handleCharacter(char c, char prev, int flgFirst) { if(c=='|'&&prev=='|'&&lastOr) { error (1, 0, "|||"); exit(0); } if(c=='&'&&prev=='&'&&lastAnd) { error (1, 0, "&&&"); exit(0); } lastOr=false; lastAnd=false; if(c=='<'&&prev=='<') { error (1, 0, "<<"); exit(0); } if(c=='>'&&prev=='>') { error (1, 0, ">>"); exit(0); } if(comment&&c!='\n') { return c; } else if(comment&&c=='\n') { comment=false; return c; } if(c=='#') { comment=true; return c; } if(c=='>')//> { lastSentOp=true; outputGlobalFlag=1; if(prev=='\n')//\n > { twoConsNewLines=0; globalFlg=0; return c; } return c; } if(c=='<')//< { lastSentOp=true; inputGlobalFlag=1; if(prev=='\n')//\n < { twoConsNewLines=0; globalFlg=0; return c; } return c; } if(flgFirst!=0) { if(c!=';'&&c!='|'&&c!='&'&&c!='('&&c!=')'&&c!='<'&&c!='>'&&c!='\n')//if current is not a special character { if(prev!=';'&&prev!='|'&&prev!='&'&&prev!='('&&prev!=')'&&prev!='<'&&prev!='>'&&prev!='\n')//if current is not a special character and previous is not a special character { tempArray[reallocCheck++]=c; //realloc if(reallocCheck==reallocSize) { reallocate(); } return c; } else if(prev=='\n')//\n a { if(globalFlg)//a \n b or a \n \n b { if(twoConsNewLines)// a \n \n b { if(strcmp(tempArray," ")!=0) { while(tempArray[0]==' ') tempArray++; while(tempArray[strlen(tempArray)-1]==' ') tempArray[strlen(tempArray)-1]='\0'; growTree(tempArray, 1,inputGlobalFlag,outputGlobalFlag); } lastSentOp=false; memset(tempArray,0,strlen(tempArray)); reallocCheck=0; globalFlg=0; //reallocSize=512; //reallocate(); tempArray=(char*)checked_malloc(sizeof(char)*INITIAL_SIZE); tempArray[reallocCheck++]=c; return c; } else//a \n b { if(c==' ') { return prev; } if(strcmp(tempArray," ")!=0) { while(tempArray[0]==' ') tempArray++; while(tempArray[strlen(tempArray)-1]==' ') tempArray[strlen(tempArray)-1]='\0'; growTree(tempArray, 0,inputGlobalFlag,outputGlobalFlag); } lastSentOp=false; memset(tempArray,0,strlen(tempArray)); reallocCheck=0; //reallocSize=512; globalFlg=0; //reallocate(); tempArray=(char*)checked_malloc(sizeof(char)*INITIAL_SIZE); growTree(";",0,inputGlobalFlag,outputGlobalFlag); tempArray[reallocCheck++]=c; return c; } } else//| \n a or | \n \n a { if (twoConsNewLines)//| \n a { twoConsNewLines=0; if(strcmp(tempArray," ")!=0) { while(tempArray[0]==' ') tempArray++; while(tempArray[strlen(tempArray)-1]==' ') tempArray[strlen(tempArray)-1]='\0'; growTree(tempArray, 0,inputGlobalFlag,outputGlobalFlag); } lastSentOp=false; memset(tempArray,0,strlen(tempArray)); reallocCheck=0; //reallocSize=512; //reallocate(); tempArray=(char*)checked_malloc(sizeof(char)*INITIAL_SIZE); tempArray[reallocCheck++]=c; return c; } else//| \n \n a { twoConsNewLines=0; if(strcmp(tempArray," ")!=0) { while(tempArray[0]==' ') tempArray++; while(tempArray[strlen(tempArray)-1]==' ') tempArray[strlen(tempArray)-1]='\0'; growTree(tempArray, 0,inputGlobalFlag,outputGlobalFlag); } lastSentOp=false; memset(tempArray,0,strlen(tempArray)); reallocCheck=0; //reallocSize=512; //reallocate(); tempArray=(char*)checked_malloc(sizeof(char)*INITIAL_SIZE); tempArray[reallocCheck++]=c; return c; } } } else//if current is not special character and previous is a special character { if(prev=='>')//> a { if(strcmp(tempArray," ")!=0) { while(tempArray[0]==' ') tempArray++; while(tempArray[strlen(tempArray)-1]==' ') tempArray[strlen(tempArray)-1]='\0'; growTree(tempArray, 0,inputGlobalFlag,outputGlobalFlag); } lastSentOp=false; memset(tempArray,0,strlen(tempArray)); reallocCheck=0; //reallocSize=512; //reallocate(); tempArray=(char*)checked_malloc(sizeof(char)*INITIAL_SIZE); tempArray[reallocCheck++]=c; //realloc return c; } else if(prev=='<')//< a { if(strcmp(tempArray," ")!=0) { while(tempArray[0]==' ') tempArray++; while(tempArray[strlen(tempArray)-1]==' ') tempArray[strlen(tempArray)-1]='\0'; growTree(tempArray, 0,inputGlobalFlag,outputGlobalFlag); } lastSentOp=false; memset(tempArray,0,strlen(tempArray)); reallocCheck=0; //reallocSize=512; //reallocate(); tempArray=(char*)checked_malloc(sizeof(char)*INITIAL_SIZE); tempArray[reallocCheck++]=c; return c; } else//| a { if(strcmp(tempArray," ")!=0) { while(tempArray[0]==' ') tempArray++; while(tempArray[strlen(tempArray)-1]==' ') tempArray[strlen(tempArray)-1]='\0'; growTree(tempArray, 0,inputGlobalFlag,outputGlobalFlag); } lastSentOp=false; memset(tempArray,0,strlen(tempArray)); reallocCheck=0; //reallocSize=512; //reallocate(); tempArray=(char*)checked_malloc(sizeof(char)*INITIAL_SIZE); tempArray[reallocCheck++]=c; //realloc return c; } } } else//if current is a special character { //if current is a special character and previous is not if(prev!=';'&&prev!='|'&&prev!='&'&&prev!='('&&prev!=')'&&prev!='<'&&prev!='>'&&prev!='\n') { if(c=='\n') //a \n { lastSentOp=false; globalFlg=1; return c; } else//a | { if(strcmp(tempArray," ")!=0) { while(tempArray[0]==' ') tempArray++; while(tempArray[strlen(tempArray)-1]==' ') tempArray[strlen(tempArray)-1]='\0'; growTree(tempArray, 0,inputGlobalFlag,outputGlobalFlag); } lastSentOp=true; memset(tempArray,0,strlen(tempArray)); reallocCheck=0; //reallocSize=512; //reallocate(); tempArray=(char*)checked_malloc(sizeof(char)*INITIAL_SIZE); tempArray[reallocCheck++]=c; //realloc return c; } } else //if current is a special character and previous is a special character { if(c=='\n'&&prev!='\n')//| \n { globalFlg=0; lastSentOp=true; return c; } else if(c=='\n'&&prev=='\n')//\n \n { lastSentOp=false; twoConsNewLines=1; if(globalFlg) { return c; } else { return c; } } else if((c=='|'&&prev=='|')||(c=='&'&&prev=='&'))//|| or && { if(reallocCheck==reallocSize) { reallocate(); } if(c=='|'&&prev=='|') { lastOr=true; } if(c=='&'&&prev=='&') { lastAnd=true; } lastSentOp=false; tempArray[reallocCheck++]=c; //realloc return c; } else// { if(prev=='\n')//\n | { if(twoConsNewLines)//a \n \n | or | \n \n ; { if(globalFlg)//a \n \n | { error (1, 0, "a \n \n |"); exit(0); if(reallocCheck==reallocSize) { reallocate(); } lastSentOp=true; globalFlg=0; tempArray[reallocCheck++]=c; //realloc return c; } else//| \n \n ; { error (1, 0, "| \n \n ; not implemented"); exit(0); } } else//a \n | or | \n ; { if (globalFlg)//a \n | { error (1, 0, "a \n |"); exit(0); lastSentOp=true; memset(tempArray,0,strlen(tempArray)); reallocCheck=0; //reallocSize=512; //reallocate(); tempArray=(char*)checked_malloc(sizeof(char)*INITIAL_SIZE); tempArray[reallocCheck++]=c; globalFlg=0; //realloc return c; } else//| \n ; { error (1, 0, "| \n ; not yet implemented"); exit(0); } } } else//| ; { error (1, 0, "| ; "); exit(0); } } } } } else { if(c==' ') { return c; } if(c=='\n') { lastSentOp=true; c=';'; return c; } else if(c!=';'&&c!='|'&&c!='&'&&c!='('&&c!=')'&&c!='<'&&c!='>'&&c!='\n')//if current is not a special character { lastSentOp=false; if(reallocCheck==reallocSize) { reallocate(); } tempArray[reallocCheck++]=c; return c; } else { error (1, 0, "two consecutive special characters not implemented"); exit(0); } } } void reallocate() { reallocSize*=2; tempArray=(char*)checked_realloc(tempArray,reallocSize); } void growTree(char* tmp, bool newTreeFlg, bool inputFlg, bool outputFlg) { //reset shit inputGlobalFlag=0; outputGlobalFlag=0; twoConsNewLines=0; //local com shit command_t curCom; curCom=(command_t)checked_malloc(sizeof(struct command)); comStackNode comNode; comNode=(comStackNode)checked_malloc(sizeof(struct comstack)); comNode->data=(command_t)checked_malloc(sizeof(struct command)); comNode->next=(comStackNode)checked_malloc(sizeof(struct comstack)); //local op shit operator* curOp; curOp=(operator*)checked_malloc(sizeof(struct op)); OpStackNode opNode; opNode=(OpStackNode)checked_malloc(sizeof(struct opstack)); opNode->data=(operator*)checked_malloc(sizeof(struct op)); opNode->next=(OpStackNode)checked_malloc(sizeof(struct opstack)); if (newTreeFlg2){ //reached end of entire command //pop and combine the rest of the shit while(opStackHead->data) popAndCombine(); //add tree to stream command_t nodeToAdd = popCom()->data; addToCommandStream(nodeToAdd); //malloc stacks free(comStackHead); free(opStackHead); comStackHead=(comStackNode)checked_malloc(sizeof(struct comstack)); opStackHead=(OpStackNode)checked_malloc(sizeof(struct opstack)); comStackHead->next=NULL; opStackHead->next=NULL; newTreeFlg2 = false; } //determine if tmp is an operator //if it is an operator, set fields of curOp if (strcmp(tmp,"(")==0){ curOp->data = substring(tmp, strlen(tmp)); curOp->precedence = 0; //opNode->data = (op*)checked_relloc(sizeof(curOp)); opNode->data = curOp; opNode->next = NULL; pushOp(opNode); } else if (strcmp(tmp,")")==0){ //while not matching ( while (strcmp(opStackHead->data->data,"(")!=0){ //pop and combine shit popAndCombine(); if (!opStackHead->data) error (1, 0, "no matching parenthesis"); } //create subshell command and push it to command stack curCom->type = SUBSHELL_COMMAND; curCom->u.subshell_command = comStackHead->data; //pop here before setting subshell_cmd? comNode->data = curCom; comNode->next = NULL; pushCom(comNode); } else if (strcmp(tmp,"|")==0){ curOp->data = substring(tmp, strlen(tmp)); curOp->precedence = PRECEDENCE_PIPE; opNode->data = curOp; opNode->next = NULL; if (opStackHead->data){ //if op stack is not empty //while next operator on stack has greater or equal precedence than curOp while (opStackHead->data->precedence >= curOp->precedence && strcmp(opStackHead->data->data,"(")!=0){ //pop and combine shit popAndCombine(); if (!opStackHead->data) break; } } pushOp(opNode); } else if (strcmp(tmp,"||")==0 || strcmp(tmp,"&&")==0){ curOp->data = substring(tmp, strlen(tmp)); curOp->precedence = PRECEDENCE_AND_OR; opNode->data = curOp; opNode->next = NULL; if (opStackHead->data){ //if op stack is not empty //while next operator on stack has greater or equal precedence than tmp while (opStackHead->data->precedence >= curOp->precedence && strcmp(opStackHead->data->data,"(")!=0){ //pop and combine shit popAndCombine(); if (!opStackHead->data) break; } } pushOp(opNode); } else if (strcmp(tmp,";")==0) { curOp->data = substring(tmp, strlen(tmp)); curOp->precedence = PRECEDENCE_SEMI_NEWLINE; opNode->data = curOp; opNode->next = NULL; if (opStackHead->data){ //if op stack is not empty //while next operator on stack has greater or equal precedence than tmp while (opStackHead->data->precedence >= curOp->precedence && strcmp(opStackHead->data->data,"(")!=0){ //pop and combine shit popAndCombine(); if (!opStackHead->data) break; } } pushOp(opNode); } //tmp is a simple command else { if (inputFlg2){ //set tmp as the input of the top of command stack then push it back on command stack comNode = popCom(); comNode->data->input = substring(tmp, strlen(tmp)); pushCom(comNode); inputFlg2 = false; } else if (outputFlg2){ //set tmp as output of the top of command stack then push it back on command stack comNode = popCom(); comNode->data->output = substring(tmp, strlen(tmp)); pushCom(comNode); outputFlg2 = false; } else{ //initialize command and push on command stack curCom=NULL; curCom=(command_t)checked_malloc(sizeof(struct command)); curCom->type = SIMPLE_COMMAND; //initialize command's words //if(!curCom->u.word) curCom->u.word=(char**)checked_malloc(sizeof(char*)*sizeof(tmp)); int i=0, j=0, wordCounter=0; for(i=0;i<strlen(tmp)-1;i++) { if(tmp[i]==' '||i==0) { for(j=i+1;j<strlen(tmp);j++) { if(tmp[i]==' '&&tmp[j]==' '&&j-i==1) { break; } if(i==0&&tmp[j]==' ') { //memcpy(curCom->u.word[wordCounter],&tmp[i+1],j-i+1); //curCom->u.word[wordCounter] = &tmp[i+1]; //curCom->u.word[wordCounter++][j-i+1]='\0'; curCom->u.word[wordCounter++]=substring(&tmp[i],j-i); i=j-1; break; } else if(tmp[j]==' '&&i!=0) { //memcpy(curCom->u.word[wordCounter],&tmp[i+1],j-i+1); //curCom->u.word[wordCounter] = &tmp[i+1]; //curCom->u.word[wordCounter++][j-i+1]='\0'; curCom->u.word[wordCounter++]=substring(&tmp[i+1],j-i-1); i=j-1; break; } else if(j==strlen(tmp)-1) { //memcpy(curCom->u.word[wordCounter],&tmp[i+1],j-i+1); //curCom->u.word[wordCounter] = &tmp[i+1]; //curCom->u.word[wordCounter++][j-i+1]='\0'; if(i==0) curCom->u.word[wordCounter++]=substring(&tmp[i],j-i+1); else curCom->u.word[wordCounter++]=substring(&tmp[i+1],j-i); i=j-1; break; } } } } if(strlen(tmp)==1) curCom->u.word[0]=substring(tmp,strlen(tmp)); comNode->data = curCom; comNode->next = NULL; pushCom(comNode); } } if (newTreeFlg) newTreeFlg2 = true; if (inputFlg) inputFlg2 = true; if (outputFlg) outputFlg2 = true; } void popAndCombine(){ //initialize new opStackNode OpStackNode operNode; operNode=(OpStackNode)checked_malloc(sizeof(struct opstack)); operNode->data=(operator*)checked_malloc(sizeof(struct op)); operNode->next=(OpStackNode)checked_malloc(sizeof(struct opstack)); operNode=popOp(); //define command command_t currentCom; currentCom=(command_t)checked_malloc(sizeof(struct command)); comStackNode commandNode; commandNode=(comStackNode)checked_malloc(sizeof(struct comstack)); if (strcmp(operNode->data->data,"|")==0) currentCom->type = PIPE_COMMAND; if (strcmp(operNode->data->data,"||")==0) currentCom->type = OR_COMMAND; if (strcmp(operNode->data->data,"&&")==0) currentCom->type = AND_COMMAND; if (strcmp(operNode->data->data,";")==0) currentCom->type = SEQUENCE_COMMAND; //pop two commands and combine them to be a new command currentCom->u.command[1] = popCom()->data; currentCom->u.command[0] = popCom()->data; //push new combined command onto command stack commandNode->data = currentCom; commandNode->next = NULL; pushCom(commandNode); } char* substring(char* s, int l) { char *sub=malloc(l+1); int c=0; while(c<l) { *(sub+c)=s[c]; c++; } *(sub+c)='\0'; return sub; }
C
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <pthread.h> void print_prime_factors(uint64_t n) { uint64_t i = 0; uint64_t nPrime = n; printf("%ju: ", n); for( i = 2 ; i <= nPrime ; i ++) { if(nPrime%i == 0) { nPrime = nPrime/i; printf("%ju ", i); i = 1; } else if(nPrime < 2) { break; } } printf("\r\n"); } void* print_prime_factors_thread(void* n) { uint64_t x = *((uint64_t*)n); print_prime_factors(x); return NULL; } int main(void) { FILE* primeList; primeList = fopen("primes2.txt", "r"); pthread_t ta; pthread_t tb; if(primeList == NULL) { perror("erreur ouverture fichier"); exit(-1); } char line1[60]; char line2[60]; int fin = 1; while(fin == 1) { fin = 0; if(fgets(line1, 60, primeList) != NULL) { fin = 1; uint64_t i1 = atoll(line1); pthread_create (&ta, NULL, print_prime_factors_thread, &i1); } if(fgets(line2, 60, primeList) != NULL) { fin = 1; uint64_t i2 = atoll(line2); pthread_create (&tb, NULL, print_prime_factors_thread, &i2); } pthread_join (ta, NULL); pthread_join (tb, NULL); } return 0; }
C
// // point2d.h // ComputacionGrafica // // Created by Alejandro Larraondo on 10/9/19. // Copyright © 2019 Alejandro Larraondo. All rights reserved. // #ifndef point2d_h #define point2d_h struct Point2d { float x,y; Point2d(float x, float y){ this->x = x; this->y = y; } Point2d& operator=(const Point2d& other) { x=other.x; y=other.y; return *this; } Point2d& operator+(const Point2d& other) { x = x + other.x; y = y + other.y; return *this; } Point2d& operator-(const Point2d& other) { x = x - other.x; y = y - other.y; return *this; } Point2d& operator*(const Point2d& other) { x = x * other.x; y = y * other.y; return *this; } void rotate(float angle){ x = ( x * cos(angle) ) - ( y * sin(angle) ); y = ( x * sin(angle) ) + ( y * cos(angle) ); } }; #endif /* point2d_h */
C
#include<stdio.h> int main() { char a[1000]; int b[10] = {0,0,0,0,0,0,0,0,0,0}; int i = 0, j = 0, k =0; scanf("%s", a); while(a[i]){ i++; } for(j = 0; j < i; j++){ for(k = 0; k < 10; k++){ if(a[j] - '0' == k){ b[k]++; } } } for(i = 0; i < 10; i++){ if(b[i] != 0){ printf("%d:%d\n", i, b[i]); } } return 0; }
C
#include <errno.h> #include <stdio.h> #include <dirent.h> #include <sys/stat.h> #include <string.h> #include <stdbool.h> typedef struct{ ino_t inode; char names[128]; nlink_t links; }File; unsigned int cnt = 0; bool found = 0; File A[128]; struct stat es; struct dirent *de; int main(){ DIR *dir=opendir("tmp"); while((de=readdir(dir))!=0){ char fileName[32]; strcpy(fileName, "tmp/"); strcat(fileName, de->d_name); if(stat(fileName, &es)!=0) return ENOENT; found=0; for(int i=0;i<cnt;i++){ if(A[i].inode==es.st_ino){ found=1; strcat(strcat(A[i].names, ", "), de->d_name); A[i].links++; break; } } if(found) continue; File x; x.links=1; x.inode=es.st_ino; strcpy(x.names, de->d_name); A[cnt++]=x; } closedir(dir); for(int j=0;j<cnt;j++) if(A[j].links>1) printf("The files %s are linked and have inode: %llu\n", A[j].names, A[j].inode); return 0; }
C
/* Problem : Find number of paths going from top left to bottom right only moving right and down */ /* From combinatorics the formula is m + n choose m */ /* for m = n = 20 40 choose 20 */ /* 40! / 20! * 20! */ /* => 40*39*...*21 / 20 * 19 * .. */ /* => 2^10 * 39 * 37 * ... * 21 / 10! */ /* You can further simplify it to 2^3 39 * 37 * .. * 21 / 23850 */ /* but for sake of clarity I've left it as before */ #include <stdio.h> unsigned long power(unsigned int base ,unsigned int expon){ unsigned int i ; unsigned long prod = 1 ; for (i = 0; i < expon ; i++) { prod *= base ; } return prod ; } unsigned long factorial(unsigned int x){ unsigned long prod = 1 ; unsigned long i ; for (i = 1; i <= x; i++) { prod *= i ; } return prod ; } int main(void){ unsigned long prod = 1 ; unsigned long i ; for (i = 39; i >= 21; i-=2) { prod *= i ; } unsigned long z = power(2,10); unsigned long x = prod ; unsigned long y = factorial(10) ; unsigned long long result = (z * x) / y ; printf("Answer : %lld \n",result); return 0 ; }
C
#include <stdio.h> int main(void) { int N; int a; int b; scanf("%d", &N); for(int i=0; i<N; i++) { scanf("%d %d",&a,&b); printf("%d\n",a+b); } return (0); }
C
#define _GNU_SOURCE #ifdef __APPLE__ #define _XOPEN_SOURCE #endif #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #ifdef _WIN32 #include <stdio.h> #include <fcntl.h> int pipe(int pipefd[2]) { return _pipe(pipefd, BUFSIZ, O_BINARY); } #endif #include "pipe_sem.h" // Initializes a semaphore and sets its initial value. Initial value may not be // less than 0. Sets errno and returns NULL if initialization failed. pipe_sem_t* pipe_sem_init(int value) { if (value < 0) { errno = EINVAL; return NULL; } // Allocate semaphore. pipe_sem_t* sem = (pipe_sem_t*) malloc(sizeof(pipe_sem_t)); if (!sem) { errno = ENOMEM; return NULL; } // Initialize the pipe. if (pipe(*sem) != 0) { free(sem); return NULL; } // Set the value. int i; for (i = 0; i < value; i++) { pipe_sem_signal(*sem); } return sem; } // Releases the semaphore resources. void pipe_sem_dispose(pipe_sem_t* sem) { close(*sem[0]); close(*sem[1]); free(sem); } // Performs a wait operation on the semaphore. void pipe_sem_wait(pipe_sem_t sem) { // Block the thread by reading from pipe. char buf[1]; read(sem[0], buf, 1); } // Performs a signal operation on the semaphore. void pipe_sem_signal(pipe_sem_t sem) { write(sem[1], "1", 1); }
C
#include <stdio.h> //////////////// ַ ///////////////////////////////// /////////////////////////////////////////////////////////////// void ABC(int *p, int N) { int i, temp, *q; temp = *p; for (q = p; q< p+N; q++) { if (*p < *(q + 1)) { // ڸ ִ밪 temp = *(q+1); *(q+1) = *p; *p = temp; } } } int main(void) { int data[10], i, *p; for (p=data; p<data+10; p++) { scanf("%d", p); } for (p=data, i = 0; p<data + 9; i++,p++) { ABC(p, 10 - i); // } for (p = data; p<data + 10; p++) { printf(" %d", *p); } return 0; }
C
#include <stdio.h> #include <string.h> int main(int argc, char **args) { if (argc == 3){ if (strlen(args[1]) != strlen(args[2])) printf("Error!!!"); else { int len = strlen(args[1]); char c; while ((c = getchar()) != EOF){ int i; for (i = 0; i < len; ++i){ if (args[1][i] == c){ c = args[2][i]; break; } } putchar(c); } } } else printf("Error!!!\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define STACK 10 /* size of stack */ int main(int argc, char **argv) { int stack[STACK] = {0}; int *sp = &stack[0]; int a, b; for (++argv; *argv != NULL; ++argv) { switch (*(*argv)) { /* first byte of argv[1] */ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': negative_number: if (sp >= stack + STACK) { fprintf(stderr, "error: stack full\n"); break; } *sp++ = atoi(*argv); break; case '+': if (sp - stack < 2) { fprintf(stderr, "error: <2 operands stacked\n"); break; } a = *--sp; a += *--sp; *sp++ = a; break; case '*': case 'x': if (sp - stack < 2) { fprintf(stderr, "error: <2 operands stacked\n"); break; } a = *--sp; a *= *--sp; *sp++ = a; break; case '-': if (*(*argv + 1) != '\0') /* next byte of argument */ goto negative_number; if (sp - stack < 2) { fprintf(stderr, "error: <2 operands stacked\n"); break; } a = *--sp; b = *--sp; *sp++ = b - a; break; case '/': if (sp - stack < 2) { fprintf(stderr, "error: <2 operands stacked\n"); break; } if (*(sp - 1)) { /* check that divisor is not zero */ a = *--sp; b = *--sp; *sp++ = b / a; break; } fprintf(stderr, "error: divide by zero\n"); break; default: fprintf(stderr, "invalid input: %s\n", *argv); break; } } printf("%d\n", *stack); /* *stack or *--sp? ... */ int i; for (i = 0, sp = &stack[0]; i < STACK; ++i, *++sp) { fprintf(stderr, "%d %d\n", i, *sp); } return 0; } /* While there are input tokens left Read the next token from input. If the token is a value Push it onto the stack. Otherwise, the token is an operator (operator here includes both operators and functions). It is known a priori that the operator takes n arguments. If there are fewer than n values on the stack (Error) The user has not input sufficient values in the expression. Else, Pop the top n values from the stack. Evaluate the operator, with the values as arguments. Push the returned results, if any, back onto the stack. If there is only one value in the stack That value is the result of the calculation. Otherwise, there are more values in the stack (Error) The user input has too many values. */
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ struct parser {char* cmd; size_t idx; int len; } ; typedef char WCHAR ; /* Variables and functions */ int /*<<< orphan*/ ERR (char*) ; __attribute__((used)) static int get_int( struct parser *parser ) { const WCHAR *p = &parser->cmd[parser->idx]; int i, ret = 0; for (i = 0; i < parser->len; i++) { if (p[i] < '0' || p[i] > '9') { ERR("should only be numbers here!\n"); break; } ret = (p[i] - '0') + ret * 10; } return ret; }
C
#include <stdio.h> #include "gmp.h" #include <time.h> #include "point.h" /* convert affine point to projective point */ void afftopro(PROJECTIVE_POINT R, const AFFINE_POINT P) { mpz_set(R->X, P->x); mpz_set(R->Y, P->y); mpz_set_ui(R->Z, 1); } /* convert projective point to affine point */ void protoaff(AFFINE_POINT R, const PROJECTIVE_POINT P, const mpz_t N) { mpz_t inv; mpz_init(inv); mpz_invert(inv, P->Z, N); mpz_mul(R->x, P->X, inv); mpz_mul(R->y, P->Y, inv); mpz_mod(R->x, R->x, N); mpz_mod(R->y, R->y, N); mpz_clear(inv); } /* convert projective point to extended point */ void protoext(EXTENDED_POINT R, const PROJECTIVE_POINT P, const mpz_t N) { /* (X:Y:Z) -> (XZ:YZ:XY:Z^2) */ mpz_mul(R->X, P->X, P->Z); mpz_mod(R->X, R->X, N); mpz_mul(R->Y, P->Y, P->Z); mpz_mod(R->Y, R->Y, N); mpz_mul(R->T, P->X, P->Y); mpz_mod(R->T, R->T, N); mpz_pow_ui(R->Z, P->Z, 2); mpz_mod(R->Z, R->Z, N); } /* convert extended point to projective point */ void exttopro(PROJECTIVE_POINT R, const EXTENDED_POINT P) { mpz_set(R->X, P->X); mpz_set(R->Y, P->Y); mpz_set(R->Z, P->Z); } void protomon(MONTGOMERY_POINT R, const PROJECTIVE_POINT P, const PROJECTIVE_POINT P1, const PROJECTIVE_POINT P2, const mpz_t a, const mpz_t b, const mpz_t N) {//projective座標がkPの時のy座標をmontgomery曲線のkpの時のy座標に変更 mpz_t A,B,C,D,E,F,G,H,I,J,K,L,inv; mpz_inits(A,B,C,D,E,F,G,H,I,J,K,L,inv,NULL); //A = P1->X * P->X = x1*x mpz_mul_mod(A,P1->X,P->X,N); //B = A + 1 = x1*x+1 mpz_add_ui(B,A,1); //C = P1->X + P->X = x1+x mpz_add(C,P1->X,P->X); //D = a * 2 = 2a mpz_mul_ui(D,a,2); //E = C + D = x1+x+2a mpz_add(E,C,D); //F = B * E = (x1*x+1)*(x1+x+2a) mpz_mul_mod(F,B,E,N); //G = F - D = (x1*x+1)*(x1+x+2a)-2a mpz_sub(G,F,D); //H = P1->X - P->X = (x1-x) mpz_sub(H,P1->X,P->X); //H = H * H = (x1-x)^2 mpz_mul_mod(H,H,H,N); //I = H * P2->X = (x1-x)^2*x2 mpz_mul_mod(I,H,P2->X,N); //J = G - I = (x1*x+1)*(x1+x+2a)-2a-(x1-x)^2*x2 mpz_sub(J,G,I); //K = b * 2 = 2b mpz_mul_ui(K,b,2); //L = K * P->Y = 2b*y mpz_mul(L,K,P->Y); //R->Y = J / L = (x1*x+1)*(x1+x+2a)-2a-(x1-x)^2*x2 / 2b*y mpz_invert(inv,L,N); mpz_mul_mod(R->Y,J,inv,N); mpz_clears(A,B,C,D,E,F,G,H,I,J,K,L,inv,NULL); } void exttomon(MONTGOMERY_POINT R, const EXTENDED_POINT P,const mpz_t N) {//Edwards曲線でのX,Y座標をmontgomery曲線でのX,Z座標に変換 mpz_t add,sub; mpz_inits(add,sub,NULL); //add = P->Y + 1 = y+1 mpz_add_ui(add,P->Y,1); //sub = P->Y - 1 = y-1 mpz_sub_ui(sub,P->Y,1); //sub = 1 / sub = 1/(y-1) mpz_invert(sub,sub,N); //R->X = add * sub = (y+1)*{1/(y-1)} = (y+1)/(y-1) mpz_mul_mod(R->X,add,sub,N); //R->Z = 1 mpz_set_ui(R->Z,1); mpz_clears(add,sub,NULL); } void montgomery_coefficient (mpz_t A, mpz_t B,const mpz_t d, const mpz_t N) {//montgomery曲線の係数A,Bをedward曲線のdから算出 mpz_t C,D; mpz_inits(C,D,NULL); //C = d - 1 mpz_sub_ui(C,d,1); //D = d + 1 mpz_add_ui(D,d,1); //D = D * -1 = -d-1 mpz_mul_ui(D,D,-1); //D = 1 / D = 1/(-d-1) mpz_invert(D,D,N); //C = C * 2 = 2*(d-1) mpz_mul_ui(C,C,2); //A = C * D = 2*(d-1)/(-d-1) mpz_mul_mod(A,C,D,N); //B = D * 4 = 4*(-d-1) mpz_mul_ui(B,D,4); mpz_clears(C,D,NULL); }
C
#include<stdio.h> int a,b,c; int val(int k,int base) { int i,v=0,h=1,b=1; for(i=0;i<7;i++) { v+=(k/h%10)*b; h*=10; b*=base; } return v; } int findmaxd(int m) { int maxd=0,i,d; int h=1; for(i=0;i<7;i++) { d=m/h%10; h*=10; if(d>maxd) maxd=d; } return maxd; } main() { int t; scanf("%d",&t); while(t--) { int dig,maxdig=0,i,r=0; scanf("%d%d%d",&a,&b,&c); dig=findmaxd(a); if(maxdig<dig) maxdig=dig; dig=findmaxd(b); if(maxdig<dig) maxdig=dig; dig=findmaxd(c); if(maxdig<dig) maxdig=dig; for(i=maxdig+1;i<=16;i++) if(val(a,i)*val(b,i)==val(c,i)) break; if(i<=16) r=i; printf("%d\n",r); } }
C
#include <stdio.h> #include <stdlib.h> int Check(int d[], int n); int Check1(int d[], int n); int main(int argc, char const *argv[]) { int d[8] = {1, -2, 3, -4, 5, -6, 7, -8}; printf("%d %d\n", Check(d, 8), Check1(d, 8)); return 0; } int Check(int d[], int n) { int flag = 1; for(int i = 0; i < n - 1 && flag != 0; i++) { if(abs(d[i]) >= abs(d[i + 1])) flag = 0; if(d[i] * d[i + 1] > 0) //相乘大于零,同号 flag = 0; } return flag; } int Check1(int d[], int n) { int i = 0; while(i < n - 1) { if(abs(d[i]) < abs(d[i + 1]) && d[i] * d[i + 1] < 0) i++; else return 0; } return 1; }
C
/* * These tests implement examples provided in the following documents: * Focusses on AES-128 because DESFire AES only uses 128-bit keys * * NIST Special Publication 800-38B * Recommendation for Block Cipher Modes of Operation: The CMAC Mode for Authentication * May 2005 */ #include <string.h> #include "../mifare/mifare.h" #include "../mifare/mifare_crypto.h" #include "../mifare/mifare_key.h" #include "test_general.h" uint8_t key_data[] = { /* DESFire AES only uses 128-bit keys */ 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c }; void test_mifare_desfire_aes_generate_subkeys(void) { uint8_t sk1[] = { 0xfb, 0xee, 0xd6, 0x18, 0x35, 0x71, 0x33, 0x66, 0x7c, 0x85, 0xe0, 0x8f, 0x72, 0x36, 0xa8, 0xde }; uint8_t sk2[] = { 0xf7, 0xdd, 0xac, 0x30, 0x6a, 0xe2, 0x66, 0xcc, 0xf9, 0x0b, 0xc1, 0x1e, 0xe4, 0x6d, 0x51, 0x3b }; mifare_desfire_key key; MifareAesKeyNew(&key, key_data); CmacGenerateSubkeys(&key); assert_equal_memory(sk1, 16, key.cmac_sk1, 16, "AES-128 Generate Subkeys: Wrong sub-key 1"); assert_equal_memory(sk2, 16, key.cmac_sk2, 16, "AES-128 Generate Subkeys: Wrong sub-key 2"); } void test_mifare_desfire_aes_cmac_empty(void) { mifare_desfire_key key; uint8_t ivect[16]; uint8_t expected_cmac[] = { 0xbb, 0x1d, 0x69, 0x29, 0xe9, 0x59, 0x37, 0x28, 0x7f, 0xa3, 0x7d, 0x12, 0x9b, 0x75, 0x67, 0x46 }; uint8_t my_cmac[16]; MifareAesKeyNew(&key, key_data); CmacGenerateSubkeys(&key); memset(ivect, 0, sizeof (ivect)); Cmac(&key, ivect, NULL, 0, my_cmac); assert_equal_memory(expected_cmac, 16, my_cmac, 16, "AES-128 empty msg: Wrong CMAC"); } void test_mifare_desfire_aes_cmac_128(void) { mifare_desfire_key key; uint8_t ivect[16]; uint8_t message[] = { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a }; uint8_t expected_cmac[] = { 0x07, 0x0a, 0x16, 0xb4, 0x6b, 0x4d, 0x41, 0x44, 0xf7, 0x9b, 0xdd, 0x9d, 0xd0, 0x4a, 0x28, 0x7c }; uint8_t my_cmac[16]; MifareAesKeyNew(&key, key_data); CmacGenerateSubkeys(&key); memset(ivect, 0, sizeof (ivect)); Cmac(&key, ivect, message, 16, my_cmac); assert_equal_memory(expected_cmac, 16, my_cmac, sizeof(message), "AES-128 128 bit msg: Wrong CMAC"); } void test_mifare_desfire_aes_cmac_320(void) { mifare_desfire_key key; uint8_t ivect[16]; uint8_t message[] = { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a, 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51, 0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11 }; uint8_t expected_cmac[] = { 0xdf, 0xa6, 0x67, 0x47, 0xde, 0x9a, 0xe6, 0x30, 0x30, 0xca, 0x32, 0x61, 0x14, 0x97, 0xc8, 0x27 }; uint8_t my_cmac[16]; MifareAesKeyNew(&key, key_data); CmacGenerateSubkeys(&key); memset(ivect, 0, sizeof (ivect)); Cmac(&key, ivect, message, sizeof (message), my_cmac); assert_equal_memory(expected_cmac, 16, my_cmac, 16, "AES-128 320 bit msg: Wrong CMAC"); } void test_mifare_desfire_aes_cmac_512(void) { mifare_desfire_key key; uint8_t ivect[16]; uint8_t message[] = { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a, 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51, 0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef, 0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10 }; uint8_t expected_cmac[] = { 0x51, 0xf0, 0xbe, 0xbf, 0x7e, 0x3b, 0x9d, 0x92, 0xfc, 0x49, 0x74, 0x17, 0x79, 0x36, 0x3c, 0xfe }; uint8_t my_cmac[16]; MifareAesKeyNew(&key, key_data); CmacGenerateSubkeys(&key); memset(ivect, 0, sizeof (ivect)); Cmac(&key, ivect, message, sizeof (message), my_cmac); assert_equal_memory(expected_cmac, 16, my_cmac, 16, "AES-128 512 bit msg: Wrong CMAC"); } void test_mifare_desfire_aes(void) { test_mifare_desfire_aes_generate_subkeys(); test_mifare_desfire_aes_cmac_empty(); test_mifare_desfire_aes_cmac_128(); test_mifare_desfire_aes_cmac_320(); test_mifare_desfire_aes_cmac_512(); }
C
// // LCBXXZDChapterSevenAlgorithmDesignFour.c // DataStructurePractice // // Created by ly on 2018/7/7. // Copyright © 2018年 LY. All rights reserved. // #include "LCBXXZDChapterSevenAlgorithmDesignFour.h" void deleteBomaryTreeSubtreeParivate(BinaryTree *tree) ; void deleteBinaryTreeSubtreeAnotherPrivate(BinaryTree *tree,ElemType element) ; void deleteBinaryTreeSubtree(BinaryTree *tree,ElemType element) { //存在一个bug,如果跟节点为要删除的值,则原来指向跟节点的指针无法变为NULL if (tree->data == element) { deleteBomaryTreeSubtreeParivate(tree); return ; } deleteBinaryTreeSubtreeAnotherPrivate(tree, element) ; } void deleteBinaryTreeSubtreeAnotherPrivate(BinaryTree *tree,ElemType element) { if (tree == NULL) { return ; } if (tree->left != NULL && tree->left->data == element) { deleteBomaryTreeSubtreeParivate(tree->left); tree->left = NULL ; }else if (tree -> right != NULL && tree->right->data == element) { deleteBomaryTreeSubtreeParivate(tree->right); tree->right = NULL ; }else{ deleteBinaryTreeSubtreeAnotherPrivate(tree->left,element) ; deleteBinaryTreeSubtreeAnotherPrivate(tree->right, element) ; } } void deleteBomaryTreeSubtreeParivate(BinaryTree *tree) { if (tree == NULL) { return ; } deleteBomaryTreeSubtreeParivate(tree->right); deleteBomaryTreeSubtreeParivate(tree->left) ; free(tree); }
C
#include <stdio.h> #include <stdlib.h> #include <mpi.h> #include <math.h> #include <time.h> /* Andres McNeill cpsc 4770 Fall 2019 Assignment 1 */ int main(int argc, char *argv[]) { int i, count; // Points inside the unit quarter circle double x, y; // Coordinates of points int samples; // Samples number of points to generate double pi; // Estimate of pi int rank, numtasks; int size; int totalcount; double start, stop; // Timekeeping vars start = MPI_Wtime(); samples = atoi(argv[1]); MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); numtasks = samples/size; if (rank == 0) { numtasks += samples % size; } count = 0; for (i = 0; i < numtasks; i++) { x = (double) rand() / RAND_MAX; y = (double) rand() / RAND_MAX; if (x*x + y*y <= 1) count++; } MPI_Reduce(&count, &totalcount, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); if (rank == 0) { pi = 4.0 * (double)totalcount/(double)samples; stop = MPI_Wtime(); printf("Elapsed time: %7.7f\n", stop - start); printf("Count = %d, Samples = %d, Estimate of pi = %7.5f\n", totalcount, samples, pi); } MPI_Finalize(); return 0; }
C
#include "ports.h" void halt() { asm volatile ( "hlt" ); } uint8_t inb(uint16_t port) { uint8_t ret; asm volatile ( "inb %1, %0" : "=a"(ret) : "Nd"(port) ); return ret; } void outb(uint16_t port, uint8_t val) { asm volatile ( "outb %0, %1" : : "a"(val), "Nd"(port) ); /* There's an outb %al, $imm8 encoding, for compile-time constant port numbers that fit in 8b. (N constraint). * Wider immediate constants would be truncated at assemble-time (e.g. "i" constraint). * The outb %al, %dx encoding is the only option for all other cases. * %1 expands to %dx because port is a uint16_t. %w1 could be used if we had the port number a wider C type */ } uint64_t read_stackptr() { uint64_t val; asm volatile ( "mov %%rsp, %0" : "=r"(val) ); return val; } uint64_t read_cr0() { //https://wiki.osdev.org/Inline_Assembly/Examples#READ_CRx uint64_t val; asm volatile ( "mov %%cr0, %0" : "=r"(val) ); return val; } uint64_t read_cr4() { uint64_t val; asm volatile ( "mov %%cr4, %0" : "=r"(val) ); return val; } uint64_t read_cs() { uint64_t val; asm volatile ( "mov %%cs, %0" : "=r"(val) ); return val; } uint64_t cpuid(uint64_t index) { uint64_t val; asm volatile("cpuid" : "=d"(val) : "a"(index) ); return val; } void enableInterrupts() { asm volatile("sti"); } void disableInterrupts() { asm volatile("cli"); } uint64_t read_msr(const uint32_t msr) { uint64_t result; uint32_t *lo = (uint32_t*)&result; uint32_t *hi = lo+1; asm volatile("rdmsr" : "=a"(*lo), "=d"(*hi) : "c"(msr)); return result; } void write_msr(const uint32_t msr, const uint64_t val) { uint32_t lo = val; uint32_t hi = val >> 32; asm volatile("wrmsr" : : "a"(lo), "d"(hi), "c"(msr)); } extern uint8_t* _isr_table; void setISR(uint8_t intnum, uint64_t address) { // an ISR table entry is 16 bytes in long mode uint16_t* ptr = (uint16_t*)&_isr_table; ptr += intnum*8; ptr[0] = address & 0x0FFFF; // low offset ptr[1] = 8; // code selector ptr[2] = 0x8e00; // type and attributes ptr[3] = (address >> 16) & 0x0FFFF; ptr[4] = (address >> 32) & 0x0FFFF; ptr[5] = (address >> 48) & 0x0FFFF; ptr[6] = 0; ptr[7] = 0; } void int10() { //asm volatile ("int qword 10"); }
C
#include <lib/circular_buffer.h> #include <lib/lib.h> /* * circular_buffer_init * Initialize the circular buffer and use the given backing memory. * * @param buf The circular buffer to initialize * @param data_buf A contiguous block of memory that we will use circularly. * @param max_len Maximum length of circular buffer */ void circular_buffer_init(circular_buffer_t *buf, void *data_buf, uint32_t max_len) { buf->max_len = max_len; buf->current_len = 0; buf->data_start = data_buf; buf->data_end = data_buf + max_len; buf->head = data_buf; buf->tail = data_buf; } /* * circular_buffer_clear * Clear the circular buffer. * * @param buf The circular buffer to clear */ void circular_buffer_clear(circular_buffer_t *buf) { buf->current_len = 0; // no need to actually delete the data, just set length to 0 buf->head = buf->data_start; buf->tail = buf->data_start; } /* * circular_buffer_put * Copy data from input buffer into circular buffer, up to len bytes (may be less). Circular buffer grows. * * @param buf The circular buffer to copy data to * @param input_buf The linear buffer to copy data from * @param len The number of bytes to (try to) copy * * @returns number of bytes copied (may be less than len) */ uint32_t circular_buffer_put(circular_buffer_t *buf, void *input_buf, uint32_t len) { int i; uint8_t *in = (uint8_t*) input_buf; // Cap the # of bytes to add if(buf->current_len + len > buf->max_len) { len = buf->max_len - buf->current_len; } // Add byte and then increment tail pointer len times, wrapping around when necessary for(i = 0; i < len; i++) { *(buf->tail++) = *(in++); if(buf->tail >= buf->data_end) { buf->tail = buf->data_start; } } buf->current_len += len; return len; } /* * circular_buffer_get * Copy data out of circular buffer into output buffer, up to len bytes (may be less). Circular buffer shrinks. * * @param buf The circular buffer to copy data from * @param input_buf The linear buffer to copy data to * @param len The number of bytes to (try to) copy * * @returns number of bytes copied (may be less than len) */ uint32_t circular_buffer_get(circular_buffer_t *buf, void *output_buf, uint32_t len) { int i; uint8_t *out = (uint8_t*) output_buf; // Cap the # of bytes to remove if (len > buf->current_len) { len = buf->current_len; } // Remove byte and then increment head pointer len times, wrapping around when necessary for(i = 0; i < len; i++) { *(out++) = *(buf->head++); if(buf->head >= buf->data_end) { buf->head = buf->data_start; } } buf->current_len -= len; return len; } /* * circular_buffer_peek * Copy data out of circular buffer without modifying buffer, up to len bytes (may be less) * * @param buf The circular buffer to copy data from * @param input_buf The linear buffer to copy data to * @param len The number of bytes to (try to) copy * * @returns number of bytes copied (may be less than len) */ uint32_t circular_buffer_peek(circular_buffer_t *buf, void *output_buf, uint32_t len) { int i; uint8_t *out = (uint8_t*) output_buf; uint8_t *addr = buf->head; // Cap the # of bytes to copy if (len > buf->current_len) { len = buf->current_len; } // Copy byte and then increment temporary head pointer len times, wrapping around when necessary for(i = 0; i < len; i++) { *(out++) = *(addr++); if(addr >= buf->data_end) { addr = buf->data_start; } } return len; } /* * circular_buffer_put_byte * Copy 1 byte into circular buffer (may not copy if full). * * @param buf The circular buffer to copy data to * @param b The byte to copy into circular buffer * * @returns Number of bytes we successfully "put" (either 0 or 1) */ uint32_t circular_buffer_put_byte(circular_buffer_t *buf, uint8_t b) { if(buf->current_len >= buf->max_len) return 0; // Copy byte, increment pointer, wraparound *(buf->tail) = b; buf->tail++; if(buf->tail >= buf->data_end) { buf->tail = buf->data_start; } buf->current_len++; return 1; } /* * circular_buffer_get_byte * Copy 1 byte out of circular buffer (may not copy if empty). Circular buffer shrinks by 1 byte (if successful) * * @param buf The circular buffer to get data from * @param b A pointer to copy the byte to. * * @returns Number of bytes we successfully got (either 0 or 1) */ uint32_t circular_buffer_get_byte(circular_buffer_t *buf, uint8_t *b) { if(buf->current_len == 0) return 0; // Copy byte, increment pointer, wraparound *b = *(buf->head); buf->head++; if(buf->head >= buf->data_end) { buf->head = buf->data_start; } buf->current_len--; return 1; } /* * circular_buffer_peek_end_byte * Examine last byte of circular buffer without affecting data (may fail if empty). * * @param buf The circular buffer to peek at 1 byte from * @param b A pointer to copy the byte to. * * @returns Number of bytes we successfully got (either 0 or 1) */ uint32_t circular_buffer_peek_end_byte(circular_buffer_t *buf, uint8_t *b) { if(buf->current_len == 0) return 0; uint8_t *addr = buf->tail - 1; if(addr < buf->data_start) { addr = buf->data_end - 1; } *b = *addr; return 1; } /* * circular_buffer_remove_end_byte * Remove last byte of circular buffer (may fail if empty) * * @param buf The circular buffer to remove 1 byte from. * * @returns Number of bytes we successfully removed (either 0 or 1) */ uint32_t circular_buffer_remove_end_byte(circular_buffer_t *buf) { if(buf->current_len == 0) return 0; // Remove byte, increment pointer, wraparound buf->tail--; if(buf->tail < buf->data_start) { buf->tail = buf->data_end - 1; } buf->current_len--; return 1; } /* * circular_buffer_find * Find and return the number of characters before the given value is encountered, or return -1 if not found. * * @param buf The circular buffer to search for the value. * @param val The value to search circular buffer for. * * @returns The number of characters before the given value is encountered, or -1 if not found. */ int32_t circular_buffer_find(circular_buffer_t *buf, uint8_t val) { int32_t len = 0; uint8_t *addr = buf->head; // Basically a strlen but with pointer wraparound for(; len < buf->current_len; len++) { if(*addr == val) { return len; } addr++; if(addr >= buf->data_end) { addr = buf->data_start; } } return -1; } /* * circular_buffer_len * Return current length of circular buffer. * * @param buf The circular buffer to get the size of * * @returns Size (in bytes) of circular buffer. */ inline uint32_t circular_buffer_len(circular_buffer_t *buf) { return buf->current_len; }
C
#ifndef AWE_ALG_H #define AWE_ALG_H // ===================================================================== // Serviceroutinen // (c) - 2013 A. Weidauer alex.weidauer@huckfinn.de // All rights reserved to A. Weidauer // ===================================================================== // Maschinen Null DOUBLE #define DBL_EPSILON 2.2204460492503131e-16 #define ERR_TRFM_SIZE_EQUAL 3010; #define ERR_TRFM_3_POINTS 3020; // =========================================================================== /** * Dynamischer double Vektor * array das Datenablage */ typedef struct { double * data; size_t length; size_t mem_size; } dbl_vector_t; // --------------------------------------------------------------- /** * Dynamischer int Vektor * array das Datenablage */ typedef struct { int * data; size_t length; size_t mem_size; } int_vector_t; // ================================================================= /** * Imfehlerfall verlassen * @param code Exit code * @param message Fehlernachricht Template * @param ... Parameter String */ void error_exit(int code, const char *message, ...); // --------------------------------------------------------------- /** * Dynamischer double Vektor Initialisierung * @param vec der Vektor * @param size Initiale Groesse */ void dbl_vector_init(dbl_vector_t *vec, size_t size); // --------------------------------------------------------------- /** * Dynamischer double Vektor Wert hinzufuegen * @param vec * @param element */ void dbl_vector_add(dbl_vector_t *vec, double element); // --------------------------------------------------------------- /** * Dynamischer double Vektor freigeben * @param vec Datenvektor */ void dbl_vector_free(dbl_vector_t *vec); // ------------------------------------------------------------------- /** * Dynamischer int Vektor Initialisierung * @param vec der Vektor * @param size Initiale Groesse */ void int_vector_init(int_vector_t *vec, size_t size); // --------------------------------------------------------------- /** * Dynamischer int Vektor Wert hinzufuegen * @param vec * @param element */ void int_vector_add(int_vector_t *vec, int element); // --------------------------------------------------------------- /** * Dynamischer int Vektor freigeben * @param vec Datenvektor */ void int_vector_free(int_vector_t *vec); // ------------------------------------------------------------------- /** * Transformation von Pixel auf Weltkoordianten * @param col Spalte im Bild * @param row Zeile im Bild * @param x X-Koordinate globales Koordsys. * @param y Y-Koordinate globales Koordsys. */ void trfm_pix_geo(double *trfm, double col, double row, double *x , double *y); // ------------------------------------------------------------------- /** * Transformation von Welt auf Pixelkoordianten * @param trfm Transformation * @param x X-Koordinate globales Koordsys. * @param y Y-Koordinate globales Koordsys. * @param col Spalte im Bild * @param row Zeile im Bild * @return true falls Berechnung OK */ int trfm_geo_pix(double *trfm, double x, double y, long *col , long* row); // --------------------------------------------------------------- /** Berechnet eine Transformation mit gegebenen * Quell- und Zielkoordinaten so dass der mittlere quadratische Fehler * minimal wird. * @param src_x - Der Vektor der X-Koodianten des Quellkoordinatensystems * @param src_y - Der Vektor der Y-Koodianten des Quellkoordinatensystems * @param dst_x - Der Vektor der X-Koodianten des Zielkoordinatensystems * @param dst_y - Der Vektor der Y-Koodianten des Zielkoordinatensystems * @param result - Verktor vom Typ double[6] der die Transformation haelt * @returns 1 falls erfolgreich * @exit Fehler * falls die Koodinatenvekoren nicht die gleiche Laenge besitzen oder * weniger als 3 Koordinateneintraege enthalten. */ int trfm_create(dbl_vector_t *src_x, dbl_vector_t *src_y, dbl_vector_t *dst_x, dbl_vector_t *dst_y, double *result); #endif
C
#include <stdio.h> int main(void) { char nome[50]; int x; printf("Digite seu nome: "); scanf("%49s", nome); for (x=0; x<49; x++) { if (nome[x]==0) { break; } printf("%c", nome[x]); } printf("\n"); return 0; }
C
/* * Universidade Federal do Rio de Janeiro * Escola Politecnica * Departamento de Eletronica e de Computacao * EEL270 - Computacao II - Turma 2019/2 * Prof. Marcelo Luiz Drumond Lanza * * Autor: <nome completo> * Descricao: <descricao sucinta sobre o programa> * * $Author$ * $Date$ * $Log$ */ #include "exemplo_032.h" boolean ValidarDigitoVerificadorDre (byte dre [COMPRIMENTO_DRE]) { unsigned short soma = 0; byte indice; for (indice = 0; indice < (COMPRIMENTO_DRE - 1); indice++) soma += dre [indice] * (indice + 1); if ((soma % 10) != dre [indice]) return falso; return verdadeiro; } /* $RCSfile$ */
C
/* 16 8 ǥ 꿡 ̿Ǵ ̴. */ #include <stdio.h> int main(void) { int num1=0xA7, num2=0x43; int num3=032, num4=024; printf("0xA7 10 : %d\n", num1); printf("0x43 10 : %d\n", num2); printf("032 10 : %d\n", num3); printf("024 10 : %d\n", num4); printf("%d-%d=%d\n", num1, num2, num1-num2); printf("%d+%d=%d\n", num3, num4, num3+num4); return 0; }
C
#include "headers.h" int main(int argc, char ** argv){ if(argc < 2){ printf("Not enough args\n"); exit(0); } if( !strcmp(argv[1], "-c" ) ) create_all(); else if( !strcmp(argv[1], "-v") ) view_story(); else if( !strcmp(argv[1], "-r") ) remove_all(); else printf("Invalid arg: %s\n", argv[1]); return 0; } void create_all(){ int sem = semget(sKEY, 1, IPC_EXCL | IPC_CREAT | 0600); shmget(mKEY , sizeof(int), IPC_EXCL | IPC_CREAT | 0600 ); open("story", O_CREAT | O_RDWR | O_TRUNC, 0644); semctl(sem,0,SETVAL, 1); printf("Story created!\n"); } void view_story(){ struct stat story; stat("story", &story); int size = story.st_size; char buff[size]; int fd = open("story", O_RDONLY); read(fd , buff , size ); printf("Story:\n%s\n", buff); } void remove_all(){ int sem = semget(sKEY, 1, 0); semctl(sem, 0, IPC_RMID); printf("Deleted semaphore!\n"); int shm = shmget(mKEY, sizeof(int), 0); shmctl(shm, IPC_RMID, 0); printf("Deleted shared memory!\n"); view_story(); remove("story"); }
C
// ------------------------------------------------------------------------- // github.com/souza10v // souza10vv@gmail.com // ------------------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <math.h> int main() { int conta[10000],i,totalnegativos,totalclientes; float saldo[10000],saldototal;; char nome[10000]; i=1; totalnegativos=0; printf("Insira o número da conta: "); scanf("%d",&conta[i]); totalclientes=1; printf("Insira o nome: "); scanf("%s",&nome[i]); printf("Insira o saldo: "); scanf("%f",&saldo[i]); if(saldo[i]<0){ totalnegativos=totalnegativos+1; } saldototal=saldo[i]; while (conta[i]!=-999 && conta[i]!=10000){ i=i+1; printf("Insira o número da conta: "); scanf("%d",&conta[i]); printf("Insira o nome: "); scanf("%s",&nome[i]); printf("Insira o saldo: "); scanf("%f",&saldo[i]); if(saldo[i]<0){ totalnegativos=totalnegativos+1; } saldototal=saldototal+saldo[i]; totalclientes=totalclientes+1; } printf(" O total de clientes com saldo negativo é %d.",totalnegativos); printf("\n O total de clientes da agencia é %d.",totalclientes); printf("\n O saldo total da agencia é %f.",saldototal); return 0; }
C
#include <iostream> using namespace std; bool f[1009] = {}; int main(int argc,char *argv[]) { int i = 0; int j = 0; f[1] = true; for(i = 2; i <= 1000; ++i){ if(f[i]){ continue; } j = i + i; while(j <= 1000){ f[j] = true; j += i; } } int a,ans = 0; cin >> a; for(i = 2; i*2 <= a; ++i ){ if(!f[i] && !f[a-i]){ ans++; }//end for } cout << ans << endl; return 0; }
C
#include <stdio.h> #define DIM1 2 #define DIM2 3 size_t StringLength_suboptimal(char *string) { size_t index = 0; for (; string[index] != '\0'; ++index) ; return index; } size_t StringLength(char *string) { char *current = string; for (; *current != '\0'; ++current) ; return current - string; } void main(void) { /* char s1[] = "Hello"; char s2[] = { 'H', 'e', 'l', 'l', 'o', '\0' }; size_t length = StringLength(s1); */ int arr[] = { 10, 20, 30, 40, 50 }; int *p = arr; /* <==> p = &arr */ //++p; /* <==> p += sizeof(*p) */ int *median = arr + 2; int num = median[-2]; /* access deviations */ /* Pointer arithmetic: */ char str[] = "Hello everyone how are you"; char *beginningOfSecondWord = str + 6; char *endOfSecondWord = str + 14; size_t lengthOfSecondWord = endOfSecondWord - beginningOfSecondWord; int matrix[DIM1][DIM2] = { {10, 20, 30}, {40, 50, 60} }; /* Naive iteration: */ /* for (size_t i = 0; i < DIM1; ++i) { for (size_t j = 0; j < DIM2; ++j) { printf("%d\n", matrix[i][j]); } } */ int *vector = *matrix;//matrix[0]; //&(matrix[0][0]); int *limit = vector + DIM1 * DIM2; for (; vector < limit; ++vector) { printf("%d\n", *vector); } //int m[][2] = { {1, 2}, {3, 4}, {5, 6} }; //int m[][3] = { {1, 2, 3}, 4, {5} }; void *pVoid = limit; float f; pVoid = &f; limit = pVoid; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "ArrayEmployees.h" #include "MiLibreria.h" int main() { char seguir = 's'; char confirmacion; char opcion; int flag = 0; int hayEmpleados = 0; Employee lista[TAM]; int id = 1000; initEmployees( lista, TAM); while(seguir == 's' ) { printf(" 1.Alta\n 2.Modifica\n 3.Baja\n 4.Informar\n 5.Salir\n\n"); printf("Seleccione una opcion: \n"); scanf("%c", &opcion); if(opcion != 49) { hayEmpleados = buscarEmpleadoIngresado(lista, TAM); if(hayEmpleados == 0) { while(opcion != 49) { system("cls"); printf("No hay empleados ingresados, primero debe ingresar al menos uno\n\n"); printf("Ingrese la opcion 1.Alta: "); scanf("%c", &opcion); } } } while(opcion < 49 || opcion > 53) { system("cls"); printf("Opcion invalida \n\n"); printf(" 1.Alta\n 2.Modifica\n 3.Baja\n 4.Informar\n 5.Salir\n\n"); printf("Seleccione una opcion valida: \n"); scanf("%c", &opcion); } switch(opcion) { case '1': { system("cls"); int sector; float salario; char nombre[51]; char apellido[51]; int respuestaAlta; printf("*******Alta Empleado*******\n\n"); printf("Ingrse el nombre: "); fflush(stdin); gets(nombre); system("cls"); printf("Ingrse el apellido: "); fflush(stdin); gets(apellido); system("cls"); printf("Ingrese sector: "); scanf("%d", &sector); system("cls"); printf("Ingrese salario: "); scanf("%f", &salario); system("cls"); respuestaAlta = addEmployee (lista, TAM, id, nombre, apellido , salario, sector); while(respuestaAlta == 0) { printf("No es posible registrar al empleado, intente otra vez\n\n"); } printf("El empleado se ha registrado correctamente\n\n"); id = id+1; } break; case '2': system("cls"); printf("*******Modificar empleado*******\n\n"); int idModificar; int rtaModificar; char menuModificar; char nombreDos [51]; char apellidoDos [51]; int sectorDos; int salarioDos; printf("Ingrese el Id del empleado que desea modificar: \n\n"); scanf("%d", &idModificar); system("cls"); rtaModificar = findEmployeeById(lista, TAM, idModificar); if(rtaModificar == -1) { printf("No se encontro el empleado\n\n"); } else { printf("Se enconto al empleado\n\n"); printf(" A. Nombre\n B. Apellido\n C. Salario\n D. Sector\n\n"); printf("Ingrese la opcion que desea modificar: "); fflush(stdin); scanf("%c", &menuModificar); while(menuModificar != 'a' && menuModificar != 'A' && menuModificar != 'b' && menuModificar != 'B' && menuModificar != 'c' && menuModificar != 'C' && menuModificar != 'd' && menuModificar != 'D') { system("cls"); printf(" A. Nombre\n B. Apellido\n C. Salario\n D. Sector\n\n"); printf("Ingrese una opcion valida: "); fflush(stdin); scanf("%c", &menuModificar); } switch(menuModificar) { case 'a': case 'A': system("cls"); printf("Reingrese el nombre: "); fflush(stdin); gets(nombreDos); strcpy(lista[rtaModificar].name, nombreDos); system("cls"); printf("El nombre fue modificado\n\n"); break; case 'b': case 'B': system("cls"); printf("Reingrese el apellido: "); fflush(stdin); gets(apellidoDos); strcpy(lista[rtaModificar].lastName, apellidoDos); system("cls"); printf("El apellido fue modificado\n\n"); break; case 'c': case 'C': system("cls"); printf("Reingrese el salario: "); scanf("%d", &salarioDos); lista[rtaModificar].salary = salarioDos; system("cls"); printf("El salario fue modificado\n\n"); break; case 'd': case 'D': system("cls"); printf("Reingrese el sector: "); scanf("%d", &sectorDos); lista[rtaModificar].sector = sectorDos; system("cls"); printf("El sector fue modificado\n\n"); break; } } break; case '3': system("cls"); printf("*******Baja empleado*******\n\n"); int idBaja; int rtaBaja; printf("Ingrese el Id del empleado que desea dar de baja: \n\n"); scanf("%d", &idBaja); rtaBaja = removeEmployee( lista, TAM, idBaja); if(rtaBaja==0) { system("cls"); printf("Id erroneo\n\n"); } else { system("cls"); printf("Se ha removido al empleado con exito\n\n"); } break; case '4': system("cls"); printf("*******Informes*******\n\n"); char menuInformes; printf(" A.Listar empleados por apellido y sector\n B.Salarios y promedios\n\n"); printf("Ingrese una opcion: \n\n"); fflush(stdin); scanf("%c", &menuInformes); while(menuInformes != 'a' && menuInformes != 'b' && menuInformes != 'A' && menuInformes != 'B') { printf(" A.Listar empleados por apellido y sector\n B.No seleccionar(version gamma)\n\n"); printf("Ingrese una opcion valida: \n\n"); fflush(stdin); scanf("%c", &menuInformes); } switch(menuInformes) { case 'A': case 'a': system("cls"); printf("*******Informes*******\n\n"); ordenarEmpleados (lista, TAM); break; case 'B': case 'b': system("cls"); printf("*******Informes*******\n\n"); salarios (lista, TAM); break; } break; case '5': system("cls"); printf("Confirme con 's' si siquiere salir del pograma:\n "); fflush(stdin); scanf("%c", &confirmacion); if (confirmacion == 's') { system("cls"); printf("\n******Fin del programa********\n\n"); flag = 1; break; } } if(flag == 0) { printf("Para continuar ingrese 's': "); fflush(stdin); scanf("%c", &seguir); system("cls"); } else { seguir = 'f'; } } return 0; } int initEmployees(Employee* list, int len) { for(int i=0; i<len; i++) { list[i].isEmpty = 1; } return 0; } int addEmployee(Employee* list, int len, int id, char name[],char lastName[],float salary,int sector) { int indice = buscarVacio(list, len); int flagAlta = 0; if(indice == -1) { flagAlta = 0; return flagAlta; } else { list[indice].id = id; strcpy(list[indice].name, name); strcpy(list[indice].lastName, lastName); list[indice].salary = salary; list[indice].sector = sector; list[indice].isEmpty = 0; flagAlta = 1; return flagAlta; } } int buscarVacio(Employee* list, int len) { int indice = -1; for(int i=0; i<len; i++) { if(list[i].isEmpty == 1) { indice = i; return i; break; } } return indice; } int printEmployees(Employee* list, int length) { int flagMostrar = 0; printf("Apellido Nombre ID Sector Salario\n\n\n"); for(int i=0; i<length; i++) { if(list[i].isEmpty == 0) { printf("%s %s %d %d %.2f\n\n", list[i].lastName, list[i].name, list[i].id, list[i].sector, list[i].salary); flagMostrar = 1; } } if(flagMostrar == 0) { system("cls"); printf("No hay empleados registrados\n\n"); } return 0; } int removeEmployee(Employee* list, int len, int id) { int flagBaja = 0; int flagID = 0; for( int i=0; i<len; i++) { if(list[i].id == id && list[i].isEmpty == 0) { list[i].isEmpty = 1; flagBaja = 1; } } if(flagBaja==0) { flagID = 0; return flagID; } else { flagID = 1; return flagID; } } int findEmployeeById(Employee* list, int len,int id) { int indice = -1; for(int i=0; i<len; i++) { if(list[i].id == id && list[i].isEmpty == 0) { indice = i; return indice; break; } } return indice; } int buscarEmpleadoIngresado(Employee* list, int len) { int primerEmpleado = 0; for(int i=0; i<len; i++) { if(list[i].isEmpty == 0) { primerEmpleado = 1; return primerEmpleado; break; } } return primerEmpleado; } void ordenarEmpleados (Employee* list, int len) { Employee auxiliar; int comparacion; for(int i=0; i<len-1; i++) { for(int j=i+1; j<len; j++) { comparacion = strcmp(list[i].lastName, list[j].lastName); if(comparacion == 0) { if(list[i].sector > list[j].sector) { auxiliar = list[i]; list[i]= list[j]; list[j] = auxiliar; } } if(comparacion == 1) { auxiliar = list[i]; list[i]= list[j]; list[j] = auxiliar; } } } printEmployees(list, len); } void salarios (Employee* list, int len) { int total = 0; int contador = 0; float promedio = 0; int contadorPromedio = 0; for(int i=0; i<len; i++) { total = total + list[i].salary; if(total != 0) { contador = contador + 1; } } promedio = total / contador; for(int x=0; x<len; x++) { if(promedio < list[x].salary) { contadorPromedio = contadorPromedio + 1; } } printf("Total de los salarios: %d\n", total); printf("El promedio de los salarios es: %.2f\n", promedio); printf("La cantidad de empleados que superan el promedio es: %d\n\n", contadorPromedio); }
C
#define _XOPEN_SOURCE 600 #include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <sys/select.h> #include <sys/socket.h> #include <sys/wait.h> #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <errno.h> #include "server_handler.h" #define MAXLINE 4096 #define LISTENQ 10 int main(int argc, char *argv[]) { int ret; int listenfd, connfd; char address[MAXLINE]; socklen_t clilen; pid_t childpid; struct sockaddr_in cliaddr, servaddr; if (argc != 2) { fprintf(stdout, "Usage: %s <PORT>\n", argv[0]); return -1; } listenfd = socket(AF_INET, SOCK_STREAM, 0); if (listenfd < 0) { fprintf(stderr, "Socket error"); return -1; } memset(&servaddr,'\0',sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(atoi(argv[1])); servaddr.sin_addr.s_addr = htonl(INADDR_ANY); ret = bind(listenfd,(struct sockaddr *) &servaddr, sizeof(servaddr)); if (ret < 0) { fprintf(stderr, "Bind error"); return -1; } ret = listen(listenfd,LISTENQ); if (ret < 0) { fprintf(stderr, "listen error"); return -1; } fprintf(stdout, "Server is running ... \n"); for ( ; ; ) { clilen = sizeof(cliaddr); if ((connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &clilen)) < 0 ) { if (errno == EINTR) continue; else { fprintf(stderr, "Accept error"); return 0; } } fprintf(stdout, "Connection from %s, port %d \n", inet_ntop(AF_INET,&cliaddr.sin_addr,address,sizeof(address)), ntohs(cliaddr.sin_port)); if ( 0 == (childpid = fork())) { close(listenfd); server_handler(connfd, connfd); exit(0); } close(connfd); } return 0; }
C
/* ** read_dir.c for tetris in /home/wyzlic_a ** ** Made by Dimitri Wyzlic ** Login <wyzlic_a@epitech.net> ** ** Started on Wed Jul 27 15:47:20 2016 Dimitri Wyzlic ** Last update Sun Aug 21 03:52:45 2016 wyzlic_a */ #include <dirent.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include "my.h" t_ll *add_ll(t_ll *all, t_mino **mino) { t_ll *new; new = malloc(sizeof(t_ll)); if (new == NULL) return (NULL); if (all == NULL) new->next = NULL; else new->next = all; new->tab = mino; return (new); } t_ll *pre_round_files(t_opt *opt) { DIR *dir; opt->nb_tetris = 0; dir = opendir("tetriminos"); if (dir == NULL) return (NULL); return (round_files(opt, dir, 0, "")); } t_mino **tab_norme() { t_mino **tab; if ((tab = malloc(sizeof(t_mino *) * 4)) == NULL) return (NULL); if ((tab[0] = malloc(sizeof(t_mino))) == NULL) return (NULL); tab[0]->h = -50; return (tab); } t_ll *round_files(t_opt *opt, DIR *dir, int fd, char *name) { struct dirent *ent; t_ll *ll; t_mino *temp; t_mino **tab; ll = NULL; while ((ent = readdir(dir)) != NULL && (name = ent->d_name) != NULL) { if (is_in(".tetrimino", name) == 1) { if ((name = my_conca("tetriminos/", name)) == NULL) return (NULL); if ((fd = open(name, O_RDONLY)) < 0) return (NULL); temp = parse_file(fd, 0); if ((tab = get_shape(temp)) == NULL) if ((tab = tab_norme()) == NULL) return (NULL); tab[0]->name = name; opt->nb_tetris = opt->nb_tetris + 1; if ((ll = add_ll(ll, tab)) == NULL) return (NULL); } } return (sort_alpha(ll)); }
C
// // Created by Brett Garberman // // Written for Teensy 2.0 (ATMEGA32U4) // #include <avr/interrupt.h> #include <avr/io.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include "uart.h" #include "Uroflow_AVR.h" uint16_t reading = 0; int newSample = 0; int currentVal = 0; int lastVal = 0; int difference = 0; float derivative = 0; int index_last = 0; uint16_t movingAverage(uint16_t val) { adc_window_avg -= (adc_window[(index_last+1) % WINDOW_SIZE] / (float) WINDOW_SIZE); //Removes oldest window value adc_window_avg += (val / (float) WINDOW_SIZE); //Inserts new moving average value adc_window[index_last] = val; //Inserts new value into moving average window index_last = (index_last++) % WINDOW_SIZE; //Increment index return (uint16_t) adc_window_avg; } void movingAverageInit(){ memset(adc_window, 0x00, SAMPLE_SIZE * sizeof(unsigned int)); //Initializes moving average window unsigned int adc_window[WINDOW_SIZE]; float adc_window_avg = 0; } void ADC_init(){ ADMUX &= ~0x1F; //Clears lower 5 bits to choose ADC0 ADMUX = _BV(REFS0); //Chooses reference voltage AREF & selects channel ADCSRA = _BV(ADPS0) | _BV(ADPS1) | _BV(ADPS2); //Enable prescaler of 128 ADCSRA |= _BV(ADEN); //Enable ADC ADCSRA |= _BV(ADIE) | _BV(ADATE); // ADC Interrupt enable & auto trigger enable ADCSRB = 0; //Free running mode } void Timer0_init(){ //Timer for flush int overflows = 0; TIMSK0 |= _BC(TOIE0); //Enables overflow interrupt } void Timer1_init(){ //Timer for ADC, with 50 Hz (20ms) sampling rate TCCR1A |= _BV(WGM12); //CTC Mode OCR1AL = 0b01000000; OCR1AH = 0b10011100; //Set OCR1A to 40000 ticks TCCR1B |= _BV(CS11); // Starts timer at 1/8 prescaler } void Timer3_init(){ //Input capture for flush button on IPC3 TIMSK3 |= _BV(ICIE3); //Enables input capture interrupt TCCR3B |= _BV(ICES3); //Input capture edge select(rising edge) } void openValve(){ PORTB |= _BV(1): PORTB &= _CV(2); } void closeValve(){ PORTB &= _CV(1): PORTB |= _BV(2); } ISR(ADC_VECT){ reading = ADC; newSample = 1; } ISR(TIMER0_OVERFLOW_vect){ //Times flush overflows++; if (overflows > 609){ //Waits 10 seconds closeValve(); overflows = 0; TCCR1B |= _BV(CS11); // Starts timer at 1/8 prescaler TCCR0B &= 0x00; // Stops timer 0 } } ISR(TIMER3_CAPT_vect){ //Initiates flush TCCR1B &= 0x00; //Stops timer 1 valveOpen(); TCCR0B |= _BV(CS00) | _BV(CS02); // Starts timer 0 at 1/1024 prescaler } int main(void){ DDRB |= _BV(1) | _BV(2); //Flush outputs DDRC &= _CV(7) //Button input ADC_init(0); movingAverageInit(); uart_init(); Timer0_init(); Timer1_init(); Timer3_init(); sei() ADCSRA |= _BV(ADSC) | //Start ADC Conversions if (newSample) { currentVal = movingAverage(reading); //Filter new reading currentVal = currentVal; //Convert to volume difference = (currentVal - lastVal); //Take derivative derivative = difference / .05; lastVal = currentVal; //Store current value printf(derivative); //Transmit flow rate newSample = 0; } }
C
// These functions are already defined as macros // in the MoSync API and in order not get compile // errors, we only use these declarations in the binding // definitions used by tolua, not in the actual C-code. // This file is never included in any C-code. /** * Create an object the represents a size (width and height). * @param x The width value of the extent. * @param y The width value of the extent. * @return An extent object (a 32-bit int with x and y packed as 16-bit values). */ MAExtent EXTENT(int x, int y); /** * Get the width part of an extent. * @param extent The extent object. * @return Width of the extent. */ int EXTENT_X(MAExtent extent); /** * Get the height part of an extent. * @param extent The extent object. * @return Height of the extent. */ int EXTENT_Y(MAExtent extent);
C
#include <stdio.h> #include <stdlib.h> #include <string.h> struct student { int Matrikelnr; char *VName; char *NName; }; void student_print(struct student *p){ printf("\tMatrikelnr: %d\n",p->Matrikelnr); printf("\tVorname: %s\n",p->VName); printf("\tNachname: %s\n",p->NName); } int main(){ struct student test = {1234565, "Max" , "Mustermann"}; struct student *p = &test; student_print(&test); }
C
//#define COMMENT 0 #define ZERO 48 #define NINE 57 #define REVZERO -128 #define REVNINE -119 #define VALUE 80 #include<stdio.h> #define RLELENGTH 50 void append(char* des,char* src); void numberToString(int num,char* str); int string_length(char* str); #include<stdlib.h> #include"stringManipulation.c" void isNumber(char* ch); void changeToNumber(char *ch); char* runLengthEncoding(char* str); char* runLengthDecoding(char* rle); int main() { FILE* fptr = fopen("/home/econsys4/Documents/letusc-yashwantkanetkar.pdf","r"); if(!fptr) { printf("No such file or directory\n"); return 0; } fseek(fptr,0L,SEEK_END); int strlen = ftell(fptr); rewind(fptr); printf("%d\n",strlen); char *str = (char*)malloc(strlen+1); fread(str,1,strlen,fptr); *(str+strlen) = '\0'; printf("Successfully text read from file: %s\n",str); char* rle = runLengthEncoding(str); free(str); strlen = string_length(rle); FILE* fptr1 = fopen("/home/econsys4/Reshma/Files/file2.txt","w"); fwrite(rle,1,strlen,fptr1); printf("Successfully written into the file: %s\n",rle); fclose(fptr1); str = runLengthDecoding(rle); printf("Decoded Text: %s\n",str); fptr1 = fopen("/home/econsys4/Reshma/Files/file.txt","w"); fwrite(str,1,strlen,fptr1); free(str); free(rle); str = NULL; rle = NULL; fclose(fptr); fclose(fptr1); return 0; } char* runLengthEncoding(char* str) { char *tmp,*temp,*rle; unsigned char c1,c2,ch; rle = (char*)malloc(RLELENGTH); *(rle) = '\0'; temp = (char*)malloc(RLELENGTH); *temp = '\0'; int strlen = string_length(str); int i,rleLength = RLELENGTH,count = 1; ch = *(str); isNumber(&ch); for(i=1;i<strlen;i++) { c1 = *(str+i); c2 = *(str+i-1); isNumber(&c1); isNumber(&c2); if(c1 != c2) { numberToString(count,temp); if(string_length(rle) > rleLength-2) { rleLength = rleLength + RLELENGTH; tmp = (char*)realloc(rle,rleLength); if(tmp == NULL) { printf("Realloc Error for Run Length Encoding String\n"); free(rle); return NULL; } rle = tmp; } append(rle,temp); *(temp) = ch; *(temp+1) = '\0'; append(rle,temp); ch = c1; count = 1; } else { count++; } } return rle; } char* runLengthDecoding(char* rle) { int rlelen = string_length(rle),i,j=0,strlen,strMemLength = RLELENGTH,count; char* temp = (char*)malloc(RLELENGTH); char* str = (char*)malloc(RLELENGTH); char ch,*tmp; *(str) = '\0'; *(temp) = '\0'; for(i=0;i<rlelen;i++) { if(*(rle+i) >= '0' && *(rle+i) <= '9') { *(temp+j++) = *(rle+i); *(temp+j) = '\0'; } else { ch = *(rle+i); changeToNumber(&ch); count = string_to_number(temp); strlen = string_length(str); if(strlen+count > strMemLength-2) { strMemLength += RLELENGTH; tmp = (char*)realloc(str,strMemLength); if(tmp == NULL) { printf("Realloc Memory error for Decode String\n"); free(temp); free(str); return NULL; } str = tmp; } for(j=0;j<count;j++) { *(str+j+strlen) = ch; } *(str+count+strlen) = '\0'; j = 0; } } return str; } void isNumber(char* ch) { if(*ch >= ZERO && *ch <= NINE) { *ch += VALUE; } } void changeToNumber(char *ch) { if(*ch >= REVZERO && *ch <= REVNINE) { *ch -= VALUE; } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "definition.h" #include "loadProfile.h" /** * Change the cwd of the shell * @param shell Shell state * @param path Path to change to * @return Success status */ int cd(Shell *shell, const char *path) { if(path == NULL) { path = shell->home; } if(chdir(path) == -1) { printf("Tried changing to %s\n", path); perror("Error changing dir"); return -1; }; if (getcwd(shell->cwd, sizeof(shell->cwd)) == NULL) { perror("getcwd() error"); exit(-1); } return 1; } /** * Handles the builtin command for environment variable * assignments * @param shell Shell state * @param input Full variable assignment string. E.g. $HOME=/home * @return Success status */ int set_shell_variable(Shell *shell, const char *input) { set_variable(shell, input); return 1; }
C
#include "string.h" int slen(char* str) { int count = 0; while (str[count] != '\0') { count++; } return count; } int s_tok(char* str, char delim, char* ptr[]) { char* suf = str; ptr[0] = str; int i, j = 1; while ((i = schr(suf, delim)) >= 0) { suf[i] = '\0'; suf = suf + i + 1; ptr[j] = suf; j++; } return j; } int schr(char* str, char ch) { int i, index = -1; for (i = 0; (str[i] != '\0') && (str[i] != ch); i++) ; if (str[i] == ch) index = i; return index; } int scopy(char* s1, char* s2) { int i = 0; while ((*s2++ = *s1++) != '\0'); if (slen(s2) == (slen(s1) + slen((s2)))) { i = 1; return i; } else { return i; } } int str_chr(char* str, char* ch) { int i, j; for (i = 0; i < slen(str); i++) { for (j = 0; j < slen(ch); j++) { if (str[i] == ch[j]) { return i; } } } return -1; }
C
#include "refcount.h" #include <stdio.h> #define mu_assert(message, test) do { if (!(test)) return message; } while (0) #define mu_run_test(test) do { const char *message = test(); tests_run++; \ if (message) return message; } while (0) int tests_run; static const char *test_initial_ref() { void *tentativo; tentativo = rc_malloc(1024, NULL); mu_assert("allocation successful", tentativo!=0); mu_assert("initial reference count", rc_count(tentativo)==1); rc_unref(tentativo); return 0; } static const char *test_ref() { void *tentativo; tentativo = rc_malloc(1024, NULL); mu_assert("allocation successful", tentativo!=0); mu_assert("initial reference count", rc_count(tentativo)==1); rc_ref(tentativo); mu_assert("reference count was updated after ref", rc_count(tentativo)==2); rc_unref(tentativo); mu_assert("reference count was updated after unref", rc_count(tentativo)==1); rc_unref(tentativo); return 0; } struct fiction_object { int *o; }; static void destructor_test_1(struct fiction_object *d) { *(d->o) = 0; } static const char *test_launch_destructor() { struct fiction_object *tentativo; int flag; tentativo = (struct fiction_object *) rc_malloc(sizeof(struct fiction_object), (destructor_t)destructor_test_1); tentativo->o = &flag; mu_assert("allocation successful", tentativo!=0); mu_assert("initial reference count", rc_count(tentativo)==1); flag = 1; mu_assert("initial flag", flag==1); rc_unref(tentativo); mu_assert("final flag", flag==0); return 0; } static const char *all_tests() { mu_run_test(test_initial_ref); mu_run_test(test_ref); mu_run_test(test_launch_destructor); return 0; } int main() { const char *result = all_tests(); if (result) { printf("Test errato: %s\n", result); } else { printf("OK. Ho eseguito %i tests\n", tests_run); } return 0; }
C
/*-------------------------------------------------- * 实现屏幕操作的函数 * 文本模式下VGA保留内存0xb8000-0xb8fa0 * 0xfa0 = 25 * 80 * 2 对应80 × 25 文本模式 每个字符占两个字节,低字节为字符,高字节为显示的颜色 *-------------------------------------------------- */ #include "types.h" #include "console.h" //显示缓冲区起始地址为0xb8000 static uint16_t *video_mem = (uint16_t*) 0xb8000; //光标坐标 static uint8_t cursor_x = 0; static uint8_t cursor_y = 0; /* 移动光标 *索引寄存器端口号 0x3d4,向它写入一个值来指定某个内部寄存器 * 两个光标寄存器索引值分别为 14, 15 分别提供高8位低8位 *指定寄存器后通过数据端口 0x3d5 来进行读写 */ static void move_cursor() { uint16_t cursor_location = cursor_x + cursor_y * 80; outb(0x3d4, 14); outb(0x3d5, cursor_location >> 8); outb(0x3d4, 15); outb(0x3d5, cursor_location); } //屏幕滚动 static void scroll() { //attribute_byte构造出黑底白字 uint8_t attribute_byte = 0x0f; //亮白色字,黑底 uint16_t blank = 0x20 | (attribute_byte << 8); //空格为0x20 //纵坐标大于等于25换行 if (cursor_y >= 25) { //所有行的数据移动到第一行, 第一行消失 for (uint32_t i = 0; i < 24 * 80; i++) video_mem[i] = video_mem[i + 80]; //最后一行空格填充 for (uint32_t i = 24 * 80; i < 25 * 80; i++) video_mem[i] = blank; cursor_y = 24; } } //清屏 void console_clear() { uint8_t attribute_byte = 0x0f; uint16_t blank = 0x20 | (attribute_byte << 8); for (uint32_t i = 0; i < 25 * 80; i++) video_mem[i] = blank; cursor_x = 0; cursor_y = 0; move_cursor(); } //输出一个字符 void console_putc_color(char c, screen_color_t back , screen_color_t fore) { uint8_t backcolor = (uint8_t) back; uint8_t forecolor = (uint8_t) fore; uint8_t attribute_byte = (backcolor << 4) | (forecolor); uint16_t attribute = attribute_byte << 8; //0x8退格 0x9tab if (c == 0x8 && cursor_x) cursor_x--; else if (c == 0x9) cursor_x = (cursor_x + 8) & (~7); else if (c == '\r') cursor_x = 0; else if (c == '\n') { cursor_x = 0; cursor_y++; } else { video_mem[cursor_x + cursor_y * 80] = c | attribute; cursor_x++; } //满80换行 if (cursor_x >= 80) { cursor_x = 0; cursor_y++; } scroll(); //纵坐标大于等于25换行 move_cursor(); } //屏幕打印字符串(黑底白字) void console_print(char *cstr) { while (*cstr) console_putc_color(*cstr++, sc_black, sc_white); } //屏幕打印字符串带颜色 void console_print_color(char *cstr,screen_color_t back,screen_color_t fore) { while(*cstr) console_putc_color(*cstr++,back,fore); } void console_print_hex(uint32_t n, screen_color_t back , screen_color_t fore) { console_print_color("0x",back,fore); if (n == 0) console_print_color("0",back,fore); char a[8]; uint16_t count = 0; while (n) { uint32_t temp = n % 16; if (temp < 10) a[count++] = '0' + temp; else a[count++] = 'A' + temp - 10; n >>= 4; } for (uint16_t i = count - 1; i >= 0; i--) console_putc_color(a[i],back,fore); } //屏幕输出十进制整数 void console_print_dec(uint32_t n, screen_color_t back, screen_color_t fore) { char a[32]; uint16_t count = 0; while (n) { uint32_t temp = n % 10; a[count++] = temp + '0'; n /= 10; } for (uint16_t i = count - 1; i >= 0; i--) console_putc_color(a[i], back, fore); }
C
#include<stdio.h> #include<fcntl.h> #include<unistd.h> #include<string.h> #include<arpa/inet.h> #include<sys/socket.h> int main(){ struct sockaddr_in direccionServidor; direccionServidor.sin_family= AF_INET; direccionServidor.sin_addr.s_addr=INADDR_ANY direccionServidor.sin_port=htons(9000) int servidor=socket(AF_INET,SOCK_STREAM,0); if(bind(servidor,(void*) &direccionServidor, sizeof(direccionServidor))!=0){ perror("Falló el bind"); return 1; } printf("estoy escuchando\n"); listen(servidor,5); FILE * pf = fopen("Usuarios.txt", "r"); t_usuarios *usuarios; if( !pf ) { printf("No se pudo abrir el archivo"); return 1; } char temp[50] int cont =0; while( !feof(pf) ){ fgets(temp,50,pf); cont++; } rewind(f); usuarios = (t_usuarios*)malloc(cont*sizeof(t_usuarios)); if(usuarios==NULL){ printf("no hay memoria"); } int i=0; fscanf(pf,"%[^|],%[^|],%[^|],%d\n", usuarios[i].nombre, usuarios[i].contraseña, usuarios[i].rol, &usuarios[i].cod_comision); while( !feof(pf) ) { fscanf(pf,"%[^|],%[^|],%[^|],%d\n", usuarios[i].nombre, usuarios[i].contraseña, usuarios[i].rol, &usuarios[i].cod_comision); i++; } fclose(pf); //--------------------- struct sockaddr_in direccionCliente; unsigned int tamDireccion; int cliente = accept(servidor, (void*)&direccionCliente,&tamDireccion); printf("Recibi una conexion\n",cliente); send(cliente,"Hola",5,0); //------------------------ char* buffer = malloc(100); while(1){ int bytesRecibidos = recv(Cliente, buffer,100, 0); if bytesRecibidos<=0){ perror("se desconectó"); return 1; } bytesRecibidos[bytesRecibidos]= '\0'; printf("llegaron %d bytes con %s \n",bytesRecibidos, buffer); } free(buffer); close(cliente); close(servidor); return 0; } void txt_a_parsear(FILE *txt) { t_usuarios user; char linea[TAM]; fgets(linea,TAM,txt); while(!feof(txt)) { parseo_txt_var(linea,&emp); fgets(linea,TAM,txt); } } void parseo_txt_var(char * linea,t_usuarios *user) { char *act = strchr(linea,'\n'); *act='\0'; act=strrchr(linea,'|'); strncpy(user->nombre,act+1,sizeof(user->nombre)); *act='\0'; act=strrchr(linea,'|'); strncpy(user->contraseña,act+1,sizeof(user->contraseña)); *act='\0'; act=strrchr(linea,'|'); user->rol=*(act+1); *act='\0'; sscanf(linea,"%d",&user->cod_comision); }
C
#include <stdio.h> typedef unsigned char * byte_pointer; void main(void){ int x= 97; //binary byte_pointer tmp = (byte_pointer) &x; printf("%d\n", (int) *tmp); // 97 printf("%c\n", *tmp); // a printf("%.2x\n",tmp[0]); // 61 printf("%.2x\n",tmp[1]); // 00 printf("%.2x\n",tmp[2]); // 00 printf("%.2x\n",tmp[3]); // 00 printf("%.2x\n",tmp[5]); // (random number) 99 }
C
#include <unistd.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include "distmon.h" #include "distlock.h" #include "debug.h" int main(int argc, char **argv) { pthread_t distmon_thread; int interactive = distmon_start(argc, argv, &distmon_thread); if (interactive < 0) { fprintf(stderr, "Failed to start distmon\n"); return 1; } struct { int len; int put_pos; int get_pos; int data[10]; } buffer; memset(&buffer, 0, sizeof(buffer)); distlock_cond_init(global_distenv, &buffer, sizeof(buffer)); if (interactive) { DEBUG_PRINTF("Running interactively..."); char *line = NULL; size_t size = 0; size_t length = 0; while ((length = getline(&line, &size, stdin)) > 0) { if (line[length - 1] == '\n') { line[length - 1] = '\0'; } if (strcmp(line, "lock") == 0) { distlock_lock(global_distenv); } else if (strcmp(line, "unlock") == 0) { distlock_unlock(global_distenv); } else if (strncmp(line, "put ", 4) == 0) { distlock_lock(global_distenv); while (buffer.len >= 10) { DEBUG_PRINTF("No space (%d), waiting for elements remove...", buffer.len); distlock_cond_wait(global_distenv); } int val = atoi(line + 4); buffer.data[buffer.put_pos] = val; buffer.len++; DEBUG_PRINTF("Put %d at %d. Len: %d", val, buffer.put_pos, buffer.len); buffer.put_pos = (buffer.put_pos + 1) % 10; distlock_cond_broadcast(global_distenv); distlock_unlock(global_distenv); } else if (strcmp(line, "get") == 0) { distlock_lock(global_distenv); while (buffer.len <= 0) { DEBUG_PRINTF("To few elements: %d. Waiting...", buffer.len); distlock_cond_wait(global_distenv); } int val = buffer.data[buffer.get_pos]; buffer.len--; DEBUG_PRINTF("Got %d from %d. Len: %d", val, buffer.put_pos, buffer.len); buffer.get_pos = (buffer.get_pos + 1) % 10; distlock_cond_broadcast(global_distenv); distlock_unlock(global_distenv); } } } else { DEBUG_PRINTF("Running automatically..."); while (1) { sleep(2); } } }
C
/*@ behavior a_less: assumes a<b; ensures \result == a; behavior b_less: assumes a>=b; ensures \result == b; */ int min(int a, int b){ if(a<b) return a; else return b; }
C
#include <stdio.h> #define M 14 void main() { char a[M]; int i; for(i=0;i<M;i++) { scanf("%c",&a[i]); } for(i=0;i<M;i++) { if(a[i]==',') printf("\n"); else if ((a[i]>='a'&&a[i]<='z')||(a[i]>='A'&&a[i]<='Z')) printf("%c",a[i]); else printf("룡"); } printf("\n"); }
C
/* ** add_list.c for dante in /home/angevil124/prog/CPE/dante ** ** Made by Benoit Hoffman ** Login <benoit.hoffman@epitech.eu> ** ** Started on Tue Apr 25 10:22:25 2017 Benoit Hoffman ** Last update Wed May 3 12:23:30 2017 Benoit Hoffman */ #include <stdlib.h> #include "generator.h" void free_stack(t_stack **list) { t_stack *tmp; t_stack *to_free; to_free = *list; tmp = to_free->next; free(to_free); *list = tmp; } int add_list(t_coords coords, t_stack **list) { t_stack *new; new = malloc(sizeof(*new)); if (new == NULL) { my_putstr("malloc error\n", 2, 0); return (84); } new->next = *list; new->coords.x = coords.x; new->coords.y = coords.y; *list = new; return (0); } int add_stacks(t_coords walls[3], t_stack **list) { int i; i = 0; while (i != 3) { if (walls[i].x != 0 || walls[i].y != 0) if (add_list(walls[i], list) == 84) return (84); i += 1; } return (0); }
C
#include <sys/time.h> #include <stdlib.h> #include <stdio.h> #include <sys/resource.h> #include <unistd.h> void main(int argv, char *argc[]){ struct timeval start, end; struct rusage usage; getrusage(RUSAGE_SELF, &usage); start = usage.ru_utime; //printf("Time in User Mode: %s\nTime in Kernel Mode: %s\n", usage.ru_utime.tv_sec, usage.ru_stime.tv_sec); int a = 0; while(a < 1000000){ int b = 1; int c = b; c++; a++; } getrusage(RUSAGE_SELF, &usage); end = usage.ru_utime; printf("Time in User Mode: %1dms\n", (/*start.tv_sec - */end.tv_usec)); }
C
/* * File: opt.c * Author: Ron F. <> * Last Modified: August 19, 2018 * Topic: ASSEMBLER * ---------------------------------------------------------------- */ #include "myas.h" /* CHECK OPT LINE AND RETURN HOW MUCH IC THERE */ int checkOPT(theDATA d) { int sum_ic; theDATA * d_ptr = &d; /* HOW MUCH IC IN THIS LINE */ sum_ic = d.LABEL + d.REG + d.NUM; if (sum_ic > MAX_IC_IN_LINE){ d.tab -> E_ERR += err_in_line(pERR_ID_line_IC_MAX,d_ptr,d.LINE); return 0; } else{ if (d.REG > ONE) /* TWO REGISTER IN LINE */ sum_ic = sum_ic-ONE; } return sum_ic; } int optLine (theDATA d, int r) { int ind = ZERO, x = ZERO, switch_n, temp_ic, before_temp; int sum_ic, des, sur; tnode * TEMP_T = d.tab -> T_ROOT; char * temp_l; theDATA * d_ptr = &d; switch_n = (int)d.ENCODING[ind]; if (switch_n == LABEL_N && r == R_ONE){ temp_l = d.NEW_LABEL; TEMP_T = addtree (TEMP_T, temp_l, d); } else if (switch_n == LABEL_N && r != R_ONE) switch_n = (int)d.ENCODING[ind+ONE]; else ; /* IF R1 -> SAVE HOW MUCH IC IN THIS LINE AND RETURN */ if (r==R_ONE){ d.tab -> TEMP_IC += sum_ic = checkOPT(d)+ONE; return 0; } else { sum_ic = checkOPT(d); } /* TAKE THE DES AND SUR */ des = returnAddress(d.ENCODING[d.WORDS]); sur = returnAddress(d.ENCODING [x = GIVE_ME_NUM (d,x)]); before_temp = temp_ic = d.tab -> TEMP_IC; /* THIS IS R2 SECTION SWITCH TO THE RIGHT OPT */ switch(switch_n) { case V_MOV : if ((sur == adr_0_NUM || sur == adr_1_LAB || sur == adr_3_REG) && (des == adr_1_LAB || des == adr_3_REG)) temp_ic += DES_and_SUR(d,sum_ic,des,sur); break; case V_CMP : if ((sur == adr_0_NUM || sur == adr_1_LAB || sur == adr_3_REG) && (des == adr_0_NUM || des == adr_1_LAB || des == adr_3_REG)) temp_ic += DES_and_SUR(d,sum_ic,des,sur); break; case V_ADD : if ((sur == adr_0_NUM || sur == adr_1_LAB || sur == adr_3_REG) && (des == adr_1_LAB || des == adr_3_REG)) temp_ic += DES_and_SUR(d,sum_ic,des,sur); break; case V_SUB : if ((sur == adr_0_NUM || sur == adr_1_LAB || sur == adr_3_REG) && (des == adr_1_LAB || des == adr_3_REG)) temp_ic += DES_and_SUR(d,sum_ic,des,sur); break; case V_NOT : if ((des == adr_1_LAB || des == adr_3_REG)) temp_ic += DES_only(d,sum_ic,des); break; case V_CLR : if ((des == adr_1_LAB || des == adr_3_REG)) temp_ic += DES_only(d,sum_ic,des); break; case V_LEA : if ((sur == adr_1_LAB) && (des == adr_1_LAB || des == adr_3_REG)) temp_ic += DES_and_SUR(d,sum_ic,des,sur); break; case V_INC : if ((des == adr_1_LAB || des == adr_3_REG)) temp_ic += DES_only(d,sum_ic,des); break; case V_DEC : if ((des == adr_1_LAB || des == adr_3_REG)) temp_ic += DES_only(d,sum_ic,des); break; case V_JMP : if (sum_ic == ONE && (d.NUM == ZERO)) temp_ic += DES_only(d,sum_ic,des); else if (sum_ic > ONE /* && (d.NUM == 0)*/) temp_ic += optJUMP(d,sum_ic); else ; break; case V_BNE : if (sum_ic == ONE && (d.NUM == ZERO)) temp_ic += DES_only(d,sum_ic,des); else if (sum_ic > ONE && (d.NUM == ZERO)) temp_ic += optJUMP(d,sum_ic); else ; break; case V_RED : if ((des == adr_1_LAB || des == adr_3_REG)) temp_ic += DES_only(d,sum_ic,des); break; case V_PRN : if ((des == adr_0_NUM || des == adr_1_LAB || des == adr_3_REG)) temp_ic += DES_only(d,sum_ic,des); break; case V_JSR : if (sum_ic == ONE && (des == adr_1_LAB || des == adr_3_REG)) temp_ic += DES_only(d,sum_ic,des); else if (sum_ic >= TWO /* && (d.NUM == 0)*/) temp_ic += optJUMP(d,sum_ic); else ; break; case V_RTS : temp_ic += noDES_noSUR(d,sum_ic); break; case V_STOP : temp_ic += noDES_noSUR(d,sum_ic); break; default : d.tab -> E_ERR += err_in_line(ZERO,d_ptr,d.LINE); } /* END OF SWITCH */ /* IF TEMP NOT CHANGE IS MEAN ERROR */ if (before_temp == temp_ic) d.tab -> E_ERR += err_in_line(pERR_ID_line_OPT,d_ptr,d.LINE); return 0; } int noDES_noSUR (theDATA d, int ic) { int mc = ZERO; /* RETURN IF FOUND TOO MUCH IC OR WORD IN LINE */ if (ic > ZERO || d.WORDS > ONE){ return 0; } d.MC_ARR[d.tab -> TEMP_IC++] = mc = d.OPT_DATA * bit_OPT; return ic+ONE; } int DES_only (theDATA d, int ic, int des) { int mc1 = ZERO, mc2 = ZERO, labelInd = ZERO; int temp_ic = d.tab -> TEMP_IC; tnode * TEMP_T = d.tab -> T_ROOT; char * temp_l; /* RETURN IF FOUND TOO MUCH IC OR WORD IN LINE */ if ( ic > ONE || d.WORDS > THREE ){ return 0; } temp_ic++; /* TAKE DATA FOR DES */ if (des == adr_0_NUM){ mc2 = d.NUM_ARR[ZERO] * BIT_3; } else if (des == adr_1_LAB) { /* SAVE LABEL AND FOUND THE IC */ temp_l = d.LABEL_ARR[labelInd]; mc2 = findLabel (TEMP_T,temp_l,d,temp_ic++); if (mc2 != EX_ADR) mc2 = ADD_R_LBAEL_ADR(mc2); } else if (des == adr_3_REG) { mc2 = d.REG_ARR[ZERO] * BIT_3; } else { ; } mc1 = (d.OPT_DATA * bit_OPT) + (des * bit_DES); d.MC_ARR[d.tab -> TEMP_IC++] = mc1; d.MC_ARR[d.tab -> TEMP_IC++] = mc2; return ic+ONE; } int DES_and_SUR (theDATA d, int ic, int des, int sur) { int mc1 = ZERO, mc2 = ZERO, mc3 = ZERO, labelInd = ZERO; int temp_ic = d.tab -> TEMP_IC; tnode * TEMP_T = d.tab -> T_ROOT; char * temp_l; /* RETURN IF FOUND TOO MUCH IC OR WORD IN LINE */ if ( ic < ONE || ic > TWO){ return 0; } mc1 = (d.OPT_DATA * bit_OPT) + (des * bit_DES) + (sur * bit_SUR); if (des == adr_3_REG && sur == adr_3_REG){ /* IF FOUND TWO REGISTER */ mc2 += d.REG_ARR[ZERO] * BIT_9; mc2 += d.REG_ARR[ONE] * BIT_3; } else { if (sur == adr_0_NUM) mc2 = d.NUM_ARR[ZERO] * BIT_3; else if (sur == adr_1_LAB) { /* MC2 IS LABEL ADR -> FOUND THE IC */ temp_l = d.LABEL_ARR[labelInd++]; mc2 = findLabel (TEMP_T,temp_l,d,temp_ic++); if (mc2 != EX_ADR) mc2 = ADD_R_LBAEL_ADR(mc2); } else if (sur == adr_3_REG) mc2 += d.REG_ARR[ZERO] * BIT_9; else ; if (des == adr_0_NUM) mc3 = d.NUM_ARR[ZERO] * BIT_3; else if (des == adr_1_LAB) { /* MC3 IS LABEL ADR -> FOUND THE IC */ temp_l = d.LABEL_ARR[labelInd]; mc3 = findLabel (TEMP_T,temp_l,d,temp_ic++); if (mc3 != EX_ADR) mc3 = ADD_R_LBAEL_ADR(mc3); } else if (des == adr_3_REG) mc3 += d.REG_ARR[ZERO] * BIT_3; else ; } d.MC_ARR[d.tab -> TEMP_IC++] = mc1; d.MC_ARR[d.tab -> TEMP_IC++] = mc2; if (des != adr_3_REG || sur != adr_3_REG){ d.MC_ARR[d.tab -> TEMP_IC++] = mc3; } return ic+ONE; } int optJUMP (theDATA d, int ic) { int mc1 = ZERO, mc2 = ZERO, mc3 = ZERO, mc4 = ZERO, labelInd = ZERO; int x = ZERO, p1, p2, label; int temp_ic = d.tab -> TEMP_IC; tnode * TEMP_T = d.tab -> T_ROOT; char * temp_l; /* RETURN IF FOUND TOO MUCH IC OR WORD IN LINE */ if ( ic < TWO || ic > THREE){ return 0; } if (checkIfHaveNum(d,BRECKT_N) != ONE) return 0; label = returnAddress(d.ENCODING [x += GIVE_ME_NUM (d,x)]); p1 = returnAddress(d.ENCODING [x = GIVE_ME_NUM (d,x)]); p2 = returnAddress(d.ENCODING [x = GIVE_ME_NUM (d,x)]); /* IF JUNP HAVE LABEL AS THIS SHOULD */ if (label == adr_1_LAB){ /* MC1 IS THE OPT CMD */ mc1 = d.OPT_DATA * bit_OPT; mc1 += p1 * bit_P1; mc1 += (p2 * bit_P2) + BIT_4; temp_ic++; /* MC2 IS THE LABEL ADR -> FOUND THE IC */ temp_l = d.LABEL_ARR[labelInd++]; mc2 = findLabel (TEMP_T,temp_l,d,temp_ic++); if (mc2 != EX_ADR) mc2 = ADD_R_LBAEL_ADR(mc2); if (p1 == adr_3_REG && p2 == adr_3_REG){ /* IF FOUND TWO REGISTER */ mc3 += d.REG_ARR[ZERO] * BIT_9; mc3 += d.REG_ARR[ONE] * BIT_3; temp_ic++; } else { if (p1 == adr_0_NUM) mc3 = d.NUM_ARR[ZERO] * BIT_3; else if (p1 == adr_1_LAB){ temp_l = d.LABEL_ARR[labelInd++]; mc3 = findLabel (TEMP_T,temp_l,d,temp_ic++); if (mc3 != EX_ADR) mc3 = ADD_R_LBAEL_ADR(mc3); } else if (p1 == adr_3_REG) mc3 += d.REG_ARR[ZERO] * BIT_9; else ; if (p2 == adr_0_NUM) mc4 = d.NUM_ARR[ZERO] * BIT_3; else if (p2 == adr_1_LAB){ temp_l = d.LABEL_ARR[labelInd]; mc4 = findLabel (TEMP_T,temp_l,d,temp_ic++); if (mc4 != EX_ADR) mc4 = ADD_R_LBAEL_ADR(mc4); } else if (p2 == adr_3_REG) mc4 += d.REG_ARR[ZERO] * BIT_3; else ; } } else ; /* COPY MC TO MC ARRAY */ d.MC_ARR[d.tab -> TEMP_IC++] = mc1; d.MC_ARR[d.tab -> TEMP_IC++] = mc2; d.MC_ARR[d.tab -> TEMP_IC++] = mc3; if (p1 != adr_3_REG || p2 != adr_3_REG){ d.MC_ARR[d.tab -> TEMP_IC++] = mc4; } return ic+ONE; } /* ADD ADDRESS LABEL RELOCATE */ int ADD_R_LBAEL_ADR (int adr) { adr = (adr * BIT_3)+TWO; return adr; } /* RETURN ADDRESS METHOD */ int returnAddress (int x) { int R = REGISTER_N; if (x == DIGIT_A){ x = adr_0_NUM; } else if (x == LABEL_NL) { x = adr_1_LAB; } else if (x >= R+reg_r0 && x <= R+reg_r7) { x = adr_3_REG; } else { x = EMPTY_AND_BLOCK; } return x; }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]){ int s; while((s = getopt(argc,argv,"ma:")) != -1){ int sum = 0; int mul = 1; for(int i = 2; i < argc; i++){ sum += atoi(argv[i]); } for(int i = 2; i < argc; i++){ mul *= atoi(argv[i]); } switch(s){ case 'm': printf("%d\n",mul); break; case 'a': if((strcmp(argv[1],"-a")) == 0){ printf("%d\n",sum); break; } else if((strcmp(argv[1],"-am")) == 0){ printf("%d %d\n",sum,mul); break; } default : printf("Usage : error\n"); break; } } if(atoi(argv[1]) > 0){ int sum = 0; for(int i = 1; i < argc; i++){ sum += atoi(argv[i]); } printf("%d\n",sum); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "LinkedListLib.h" #include "LinkedListLib_int.h" #include "LinkedListLib_Log.h" /****************************************************************************** * Function LinkedListLib_Init -- * This function should be invoked to initialize the LinkedListLib *****************************************************************************/ int LinkedListLib_Init() { if (MainLinkedListLibInstExists()) { // If theLinkedListLibInst is already initialized, then // logging should be up as well LOG_DEBUG("LinkedListLib is already initialized!"); return TRUE; } theLinkedListLibInst = (LinkedListLibInst *)malloc(sizeof *theLinkedListLibInst * 1); if (!theLinkedListLibInst) { printf("%s(): Memory Allocation Failed, just exiting out ... \n", __FUNCTION__); return FALSE; } theLinkedListLibInst->m_logLevel = LOG_LEVEL_DEFAULT; LOG_INFO("LinkedListLib Initializing."); LOG_DEBUG("Default Log level is: %s", LinkedListLib_LogLevel_To_Str(theLinkedListLibInst->m_logLevel)); // Init the Head node list maintained by theLinkedListLibInst if (InitHeadNodeList(theLinkedListLibInst) == FALSE) { LOG_ERROR("InitHeadNodeList() Failed !"); return FALSE; } // LOG_LEVEL_DEFAULT is DEBUG, so the below TRACE shouldn't show up in Log LOG_TRACE("theLinkedListLibInst: [0x%p]", theLinkedListLibInst); // The below INFO log should show up though LOG_INFO("LinkedListLib Initialized"); return TRUE; } /****************************************************************************** * Function LinkedListLib_Uninit -- * This Uninit func for LinkedListLib *****************************************************************************/ int LinkedListLib_Uninit() { LOG_INFO("LinkedListLib Uninitialing"); if (MainLinkedListLibInstExists()) { // Uninit the Head node list maintained by theLinkedListLibInst if (UninitHeadNodeList(theLinkedListLibInst) == FALSE) { LOG_ERROR("UninitHeadNodeList() Failed !"); } LOG_INFO("LinkedListLib Uninitialized"); free(theLinkedListLibInst); theLinkedListLibInst = NULL; } return TRUE; } /****************************************************************************** * Function LinkedListLib_InitList -- * Initializes head node for the List - return pointer to this head node. * This head node pointer can be considered as an equivalent of "handle" to * the LinkedList. * * The caller should record this headPointer/listHandle and it should be * used to make any subsequent operations on this LinkedList. *****************************************************************************/ int LinkedListLib_InitList(ListNode **listHandle) { if (!MainLinkedListLibInstExists()) { return FALSE; } LOG_DEBUG("Enter"); if (IsLinkedListLibInstFull(theLinkedListLibInst)) { LOG_INFO("Can not create a new LinkedList"); LOG_INFO("theLinkedListLibInst alreafy full"); return FALSE; } ListNode *node = (ListNode *)malloc(sizeof *node * 1); if (!node) { LOG_ERROR("Memory allocation Failed!"); return FALSE; } // Head node's m_data will keep track of number of Nodes in the list node->m_type = LIST_NODE_HEAD; node->m_data = 0; node->m_next = NULL; /* * Record the listHandle */ int index; if (!GetFirstHeadNodeEmptySlot(theLinkedListLibInst, &index)) { LOG_ERROR("Failed to get an empty slot for headNode"); return FALSE; } LOG_DEBUG("New LinkedList will be at index: %d", index); theLinkedListLibInst->m_lists[index] = node; theLinkedListLibInst->m_numLists += 1; LOG_DEBUG("Added listHandle: 0x%p", node); LOG_DEBUG("Number of Lists: %d", theLinkedListLibInst->m_numLists); /* * Return pointer to head node back to the caller * The caller is expected to record this head pointer * and it should be used to make any subsequent operations * on this LinkedList */ *listHandle = node; LOG_DEBUG("Exit"); return TRUE; } /****************************************************************************** * Function LinkedListLib_UninitList -- * Delete every Data node of the list. Delete head node. *****************************************************************************/ int LinkedListLib_UninitList(ListNode *listHandle) { if (!MainLinkedListLibInstExists()) { return FALSE; } LOG_DEBUG("Enter - listHandle: 0x%p", listHandle); int index; if (!LinkedListLib_ListExists(listHandle, &index)) { LOG_ERROR("LinkedList 0x%p does not Exist in LinkedListLib", listHandle); return FALSE; } LOG_DEBUG("LinkedList found at index: %d", index); if (!DeleteList(listHandle)) { LOG_ERROR("DeleteList() failed for listHandle: 0x%p", listHandle); return FALSE; } if (!DeleteHeadNode(theLinkedListLibInst, index)) { LOG_ERROR("DeleteHeadNode() failed for index: %d", index); return FALSE; } LOG_DEBUG("LinkedList deleted, theLinkedListLibInst->m_numLists: %d", theLinkedListLibInst->m_numLists); LOG_DEBUG("Exit"); return TRUE; } /****************************************************************************** * Function LinkedListLib_ListExists -- * Checks if the list corresponding to given listHandle exists or not *****************************************************************************/ int LinkedListLib_ListExists(ListNode *listHandle, // IN int *retIndex) // OUT { if (!MainLinkedListLibInstExists()) { return FALSE; } LOG_DEBUG("Enter - listHandle: 0x%p", listHandle); if (!retIndex) { LOG_ERROR("Invalid Parameter - *retIndex is NULL"); return FALSE; } int ok = FALSE; int i = 0; for (i=0 ; i < LINKEDLISTLIB_MAX_NUM_LISTS ; i++) { if (theLinkedListLibInst->m_lists[i] == listHandle) { LOG_DEBUG("LinkedList found in theLinkedListLib at index %d", i); *retIndex = i; ok = TRUE; break; } } LOG_DEBUG("Exit"); return ok; } /****************************************************************************** * Function LinkedListLib_IsFull -- *****************************************************************************/ int LinkedListLib_IsFull() { if (!MainLinkedListLibInstExists()) { return FALSE; } return IsLinkedListLibInstFull(theLinkedListLibInst); } /****************************************************************************** * Function LinkedListLib_IsFullList -- *****************************************************************************/ int LinkedListLib_IsFullList(ListNode *listHandle) // IN { int ok = FALSE; if (!MainLinkedListLibInstExists()) { return ok; } int retIndex = -1; if (!LinkedListLib_ListExists(listHandle, &retIndex)) { LOG_ERROR("LinkedList with Handle 0x%p does Not exist", listHandle); return ok; } LOG_DEBUG("About to check if LinkedList [0x%p] is Full or Not ...", listHandle); ok = (IsListFull(listHandle) == TRUE ? TRUE : FALSE); return ok; } /****************************************************************************** * Function LinkedListLib_IsEmptyList -- *****************************************************************************/ int LinkedListLib_IsEmptyList(ListNode *listHandle) // IN { int ok = FALSE; if (!MainLinkedListLibInstExists()) { return ok; } int retIndex = -1; if (!LinkedListLib_ListExists(listHandle, &retIndex)) { LOG_ERROR("LinkedList with Handle 0x%p does Not exist", listHandle); return ok; } LOG_DEBUG("About to check if LinkedList [0x%p] is Empty or Not ...", listHandle); ok = (IsListEmpty(listHandle) == TRUE ? TRUE : FALSE); return ok; } /****************************************************************************** * Function LinkedListLib_GetListNumElements -- *****************************************************************************/ int LinkedListLib_GetListNumElements(ListNode *listHandle, // IN int *numElements) // OUT { int ok = FALSE; int retIndex = -1; if (!numElements) { LOG_ERROR("Invalid args - NULL second parameter!"); goto exit; } if (!LinkedListLib_ListExists(listHandle, &retIndex)) { LOG_ERROR("Inavlid args - LinkedList 0x%p does Not exist", listHandle); goto exit; } if (!IsHeadNode(listHandle)) { LOG_ERROR("Invalid args - listHandle 0x%p is corrupt", listHandle); goto exit; } *numElements = listHandle->m_data; LOG_DEBUG("Number of Elements in LinkedList[%d] = %d", retIndex, *numElements); ok = TRUE; exit: LOG_DEBUG("Getting Number of elements in the List: %s", ok == TRUE ? "Succeeded" : "Failed!"); return ok; } /****************************************************************************** * Function LinkedListLib_AddIntDataNodeFromRear -- *****************************************************************************/ int LinkedListLib_AddIntDataNodeFromRear(ListNode *listHandle, // IN int nodeData) // IN { int ok = FALSE; int retIndex = -1; if (!LinkedListLib_ListExists(listHandle, &retIndex)) { goto exit; } if (LinkedListLib_IsFullList(listHandle)) { goto exit; } LOG_DEBUG("Adding element from rear to LinkedList[%d]", retIndex); ListNode *tmp = listHandle->m_next; while (tmp && tmp->m_next) { tmp = tmp->m_next; } ListNode *newNode = NULL; newNode = (ListNode *)malloc(sizeof(*newNode) * 1); if (!newNode) { LOG_ERROR("Memory allocation Failed!"); goto exit; } newNode->m_type = LIST_NODE_DATA; newNode->m_data = nodeData; newNode->m_next = NULL; if (tmp) { tmp->m_next = newNode; } else { listHandle->m_next = newNode; } listHandle->m_data += 1; ok = TRUE; exit: LOG_DEBUG("Node addition to rear of LinkedList[%d]: %s", retIndex, ok == TRUE ? "Succeeded" : "Failed!"); return ok; } /****************************************************************************** * Function LinkedListLib_DeleteIntDataNodeFromRear -- *****************************************************************************/ int LinkedListLib_DeleteIntDataNodeFromRear(ListNode *listHandle, // IN int *nodeData) // OUT { int ok = FALSE; int retIndex = -1; if (!nodeData) { goto exit; } if (!LinkedListLib_ListExists(listHandle, &retIndex)) { goto exit; } if (LinkedListLib_IsEmptyList(listHandle)) { goto exit; } LOG_DEBUG("Deleting element from rear to LinkedList[%d]", retIndex); ListNode *last, *newLast; last = listHandle->m_next; newLast = listHandle; while (last->m_next) { last = last->m_next; newLast = newLast->m_next; } *nodeData = last->m_data; free(last); newLast->m_next = NULL; listHandle->m_data -= 1; LOG_DEBUG("Node %d deleted from LinkedListLib[%d]", *nodeData, retIndex); ok = TRUE; exit: LOG_DEBUG("Node deletion from rear of LinkedList[%d]: %s", retIndex, ok == TRUE ? "Succeeded" : "Failed!"); return ok; } /****************************************************************************** * Function LinkedListLib_AddIntDataNodeFromFront -- *****************************************************************************/ int LinkedListLib_AddIntDataNodeFromFront(ListNode *listHandle, // IN int nodeData) // IN { int ok = FALSE; int retIndex = -1; if (!LinkedListLib_ListExists(listHandle, &retIndex)) { goto exit; } if (LinkedListLib_IsFullList(listHandle)) { goto exit; } LOG_DEBUG("Adding element from front to LinkedList[%d]", retIndex); ListNode *tmp = listHandle->m_next; ListNode *newNode = NULL; newNode = (ListNode *)malloc(sizeof(*newNode) * 1); if (!newNode) { LOG_ERROR("Memory allocation Failed!"); goto exit; } newNode->m_type = LIST_NODE_DATA; newNode->m_data = nodeData; newNode->m_next = tmp; listHandle->m_next = newNode; listHandle->m_data += 1; ok = TRUE; exit: LOG_DEBUG("Node addition to rear of LinkedList[%d]: %s", retIndex, ok == TRUE ? "Succeeded" : "Failed!"); return ok; } /****************************************************************************** * Function LinkedListLib_DeleteIntDataNodeFromFront -- *****************************************************************************/ int LinkedListLib_DeleteIntDataNodeFromFront(ListNode *listHandle, // IN int *nodeData) // OUT { int ok = FALSE; int retIndex = -1; if (!nodeData) { goto exit; } if (!LinkedListLib_ListExists(listHandle, &retIndex)) { goto exit; } if (LinkedListLib_IsEmptyList(listHandle)) { goto exit; } LOG_DEBUG("Deleting element from front to LinkedList[%d]", retIndex); ListNode *tmp = listHandle->m_next; if (tmp->m_next) { listHandle->m_next = tmp->m_next; } else { listHandle->m_next = NULL; } *nodeData = tmp->m_data; free(tmp); listHandle->m_data -= 1; LOG_DEBUG("Node %d deleted from LinkedListLib[%d]", *nodeData, retIndex); ok = TRUE; exit: LOG_DEBUG("Node deletion from front of LinkedList[%d]: %s", retIndex, ok == TRUE ? "Succeeded" : "Failed!"); return ok; } /****************************************************************************** * Function LinkedListLib_PrintHeadNodes -- *****************************************************************************/ int LinkedListLib_PrintHeadNodes() { int i = 0; LOG_DEBUG("Enter - theLinkedListLibInst->m_numLists: %d", theLinkedListLibInst->m_numLists); for(i = 0 ; i < theLinkedListLibInst->m_numLists ; i++) { LOG_DEBUG("theLinkedListLibInst->m_lists[i]: 0x%p", theLinkedListLibInst->m_lists[i]); } return TRUE; } /****************************************************************************** * Function LinkedListLib_PrintListToLog -- *****************************************************************************/ int LinkedListLib_PrintListToLog(ListNode *listHandle) // IN { int ok = FALSE; int retIndex = -1; if (!LinkedListLib_ListExists(listHandle, &retIndex)) { LOG_ERROR("Invalid args - List 0x%p does Not exists", listHandle); goto exit; } if (LinkedListLib_IsEmptyList(listHandle)) { LOG_DEBUG("LinkedList[%d][0x%p] is Empty ... ", retIndex, listHandle); ok = TRUE; goto exit; } ListNode *tmp = listHandle->m_next; while (tmp) { LOG_DEBUG("%d ->", tmp->m_data); tmp = tmp->m_next; } LOG_DEBUG("NULL"); ok = TRUE; exit: return ok; }
C
#include "barrier.h" void ResetBarrier(barrier_t* b, int max_count) { b->barrier_counter = 0; b->barrier_max = max_count; pthread_cond_init(&(b->barrier_active), NULL); } void IncrementBarrier(barrier_t* b) { pthread_mutex_lock(&(b->barrier_mutex)); b->barrier_counter += 1; pthread_mutex_unlock(&(b->barrier_mutex)); } int PollBarrier(barrier_t* b) { if(b->barrier_counter == b->barrier_max) { return 0; } else { return 1; } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: amadrid- <amadrid-@student.42madrid> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/07 12:02:48 by amadrid- #+# #+# */ /* Updated: 2021/09/07 12:54:22 by amadrid- ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" char *ft_clean_line(char *save, char **line, int r) { unsigned int i; char *tmp; i = 0; while (save[i]) { if (save[i] == '\n') break ; i++; } if (i < ft_strlen(save)) { *line = ft_substr(save, 0, i); tmp = ft_substr(save, i + 1, ft_strlen(save)); free(save); save = ft_strdup(tmp); free(tmp); } else if (r == 0) { *line = save; save = NULL; } return (save); } char *ft_save(char *buffer, char *save) { char *tmp; if (save) { tmp = ft_strjoin(save, buffer); free(save); save = ft_strdup(tmp); free(tmp); } else save = ft_strdup(buffer); return (save); } int get_next_line(int fd, char **line) { static char *save[4096]; char buffer[BUFFER_SIZE + 1]; int r; r = 1; while (r) { r = read(fd, buffer, BUFFER_SIZE); if (r == -1) return (-1); buffer[r] = '\0'; save[fd] = ft_save(buffer, save[fd]); if (ft_strchr(buffer, '\n')) break ; } if (r <= 0 && !save[fd]) { *line = ft_strdup(""); return (r); } save[fd] = ft_clean_line(save[fd], line, r); if (r <= 0 && !save[fd]) return (r); return (1); }
C
#include <stdio.h> extern int fak (int v); extern int tester(int i); int realfak(int v){ int sum = 1; while(v != 0){ sum *= v; v--; } return sum; } int main (void) { int i = 10; printf("Fak(%d) = %d(%d)\n",i,fak(i),realfak(i)); printf("Testprogram(%d) = %d\n",i,tester(i)); }
C
#ifndef __errors_h #define __errors_h #include <unistd.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* * Define a macro that can be used for diagnostic output from examples. * When compiled -DDEBUG, it results in calling printf with the specified * argument list. When DEBUG is not defined, it expands to nothing */ #ifdef DEBUG # define DPRINTF(arg) printf arg #else # define DPRINT(arg) #endif /* * NOTE: the "do {" ... "} while (0);" bracketing around the macros allows * the err_abort and errno_abort macros to be used as if they were function * callss, even in contexts where a trailing ";" would generate a null statement. * For example, * * if (status !=0 ) * err_abort(status, "messages"); * else * return status; * * will not compile if err_abort is a macro ending with "}", because C does * not expect a ";" to following the "}". Because C DOES expect a ";" following * the ")" in the do ... while constract, err_abort and errno_abort can be * used as if they were function calls. */ #define err_abort(code, text) do { \ fprintf(stderr, "%s at \"%s\":%d: %s\n", \ text, __FILE__, __LINE__, strerror(code)); \ abort(); \ } while (0) #define errno_abort(text) do { \ fprintf(stderr, "%s at \"%s\":%d: %s\n", \ text, __FILE__, __LINE__, strerror(errno)); \ abort(); \ } while (0) #endif
C
# include <stdio.h> # define LENGTH 10 # define WIDTH 5 # define NEWLINE '\n' void test02() { const int LENGTH1 = 10; const int WIDTH1 = 5; const char NEWLINE1 = '\n'; int area; area = LENGTH1 * WIDTH1; printf("value of area:%d\n",area); printf("看看newline的值是什么:%c\n",NEWLINE1); return; } int main() { int area; area = LENGTH * WIDTH; printf("value of area:%d\n",area); printf("看看newline的值是什么:%c\n",NEWLINE); test02(); return 0; }
C
#include <linux/kernel.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/signal.h> #include <asm/io.h> #include <linux/timekeeping.h> #include <linux/gpio.h> #define BUTTON_1 25 // switch #define LED_1 24 // LED1 #define IRQ_NAME "button_1" // define IRQ_NAME, we can type cat /proc/interrupts to see name of IRQ MODULE_LICENSE("GPL"); MODULE_AUTHOR("RTES LAB"); MODULE_DESCRIPTION("irq demo for RTES lab"); MODULE_VERSION("0.3"); static short int button_irq_id = 0; static ktime_t last_time; static char is_on = 0; static char is_press = 0; irq_handler_t isr (int irq, void *data){ ktime_t this_time = ktime_get(); //get current time if(this_time - last_time > 100000000 ){ //debounce, minimum interval time = 0.1s is_press ^= 0x01; //1 when button press, 0 when button relese if(is_press){ //if button press, change the state of LED_1 gpio_direction_output(LED_1, is_on); is_on ^= 0x01; //1 for LED_1 on, 0 for LED_1 off } } last_time = this_time; //update the last trigger time of ISR return (irq_handler_t) IRQ_HANDLED; //tell system that this ISR is handled } int init_module (){ gpio_free(BUTTON_1); //in case BUTTON_1 pin is occupy gpio_free(LED_1); //in case LED_1 pin is occupy if(gpio_request(BUTTON_1,"BUTTON_1") != 0){ //sign up for using BUTTON_1 return -1; //sign up fail, exit with -1 } if(gpio_request(LED_1,"LED") != 0){ //sign up for using LED_1 return -1; //sign up fail, exit with -1 } gpio_direction_output(LED_1, is_on); //tell system we will use LED_1 as output port is_on ^= 0x01; //initialize last_time = ktime_get(); //get current time if( (button_irq_id = gpio_to_irq(BUTTON_1)) < 0 ){ //translate gpio pin id to irq id return -1; } printk (KERN_ALERT "\nbutton_isr loaded !\n"); //debug information, check with dmesg //go google dmesg if you don't know what it is request_irq(button_irq_id, (irq_handler_t) isr, IRQF_TRIGGER_RISING|IRQF_TRIGGER_FALLING, IRQ_NAME, NULL); //sign up IRQ //let's break this up //button_irq_id : irq id of BUTTON_1, got this with gpio_to_irq() //isr : the name of your ISR, in this case, the function name is "isr" //IRQF_TRIGGER_RISING|IRQF_TRIGGER_FALLING : bit mask(google it if you don't know what is bit mask), // we are using "|" to tell system to trigger isr // when rising edge AND falling edge event happen //IRQ_NAME : the name of this IRQ, you could check this in "/proc/interrupts" //NULL : the address of varible passed to handler function return 0; } void cleanup_module(void){ //triggered when rmmod use free_irq(button_irq_id, NULL); //free IRQ gpio_free(BUTTON_1); //free BUTTON_1 gpio pin gpio_free(LED_1); //free LED_1 gpio pin printk (KERN_ALERT "\n1 button_isr unloaded !\n"); //debug information, check with dmesg }
C
#include<stdio.h> #include<conio.h> #include<stdlib.h> float calc(float raio) { return (4/3 * raio * raio * raio); } main() { float raio=0; printf ("Informe o raio\n"); scanf ("%f",&raio); printf ("O valor %.2f ",calc(raio)); getch(); }
C
#include <ncurses.h> #include <string.h> #include <unistd.h> /* only for sleep() */ #include <stdio.h> #include <stdlib.h> #include <time.h> int main(){ clock_t start, end; float time_dif; printf("starting the program\n"); start = clock(); while(1){ //check time end = clock(); time_dif = (end - start) / CLOCKS_PER_SEC; if (time_dif > 0.1){ printf("Hello \n"); start = clock(); } } return 0; }
C
/*------------------------------------------------------------------------------- * Project: KoreBot Library * $Author: pbureau $ * $Date: 2004/11/12 14:35:23 $ * $Revision: 1.3 $ * * * $Header: /home/cvs/libkorebot/src/kb_wav.c,v 1.3 2004/11/12 14:35:23 pbureau Exp $ */ /*--------------------------------------------------------------------*/ /*! * \file kb_wav.c wav files handling * * \brief * This module provides functions to read, write and playback * wav data from/to a wav file. * * \author Cdric Gaudin (K-Team SA) * \author Pierre Bureau (K-Team SA) * \note Copyright (C) 2004 K-TEAM SA */ #include "korebot.h" #define print_type(t) printf("%c%c%c%c\n" , t[0], t[1], t[2], t[3]) /*--------------------------------------------------------------------*/ /*! Play a wav file to the given sound interface. The sound interface * must be initialized first using kb_sound_init and kb_sound_open. * This function does not return until the full wav file is played. * \param snd the sound interface * \param filename the name of wav file to play * \param soundbufsize the size of the sound buffer * \return an error code or 0 if successful */ int kb_wav_play(snd_t * snd, char * filename, unsigned soundbufsize) { WAV wav; int rc; short buf[soundbufsize]; /* Init the wav struct */ kb_wav_init( &wav ); /* Open the given wav file */ if ((rc = kb_wav_open( &wav , filename, 1 )) == -1 ) { return KB_ERROR("kb_wav_play",KB_ERROR_FILEOPEN, filename); } /* Check that the format is supported */ /*! \todo change the format check to be used with different sound interfaces. So far only the KoreMedia interface is supported. */ if ( wav.fmt.bit_per_sample != 16 && wav.fmt.nb_channel != 2 ) { return KB_ERROR("kb_wav_play",KB_ERROR_BADSOUND, filename); } /* Sound playing loop */ for (;;) { rc = kb_wav_read_data( &wav , buf , soundbufsize); if ( rc <= 0 ) { if ( rc < 0 ) kb_warning(KB_WARN_SOUNDIO , filename); break; } do { rc = kb_snd_play( snd , buf , soundbufsize); if ( rc < 0 ) { if ( errno != EAGAIN ) { kb_warning(KB_WARN_SOUNDSAMPLE, errno); break; } continue; } } while (0); } /* Close the wav file */ kb_wav_close( &wav ); return 0; } /*--------------------------------------------------------------------*/ /*! This function initializes the wav struct, it must be called before * calling other wav functions. * \param wav the wav struct to initialize */ void kb_wav_init( WAV * wav ) { wav->file = NULL; wav->length = 0; wav->modified = 0; } /*--------------------------------------------------------------------*/ /*! This function opens a wav file for reading or writing * \param wav the wav struct to use with the given file * \param file the file to read or write * \param read set to 1 for reading or to 0 for writing * \return * - the data length on success * - -1 if the file cannot be opened */ int kb_wav_open( WAV * wav , const char * file , int read ) { COMMON_CHUNK_HEADER hdr; int type; if ((wav->file = fopen( file , read ? "rb" : "wb" )) == NULL) { return -1; } if ( read ) { for (;;) { type = kb_wav_read_hdr( wav , &hdr ); switch( type ) { /* RIFF */ case 1: break; /* FMT */ case 2: memcpy( &wav->fmt , &hdr.chunk.fmt , sizeof(wav->fmt)); break; /* DATA */ case 3: wav->length = hdr.length; return (int)hdr.length; } } } else { memcpy( &hdr.type , "RIFF" , 4 ); hdr.length = sizeof( RIFF_CHUNK_HEADER) + 8 + sizeof( FMT_CHUNK_HEADER) + 8 + 8 + wav->length; memcpy( &hdr.chunk.riff.chunk_content , "WAVE" , 4 ); kb_wav_write_hdr( wav , &hdr ); memcpy( &hdr.type , "fmt " , 4 ); hdr.length = sizeof( FMT_CHUNK_HEADER ) ; memcpy( &hdr.chunk.fmt , &wav->fmt , sizeof( FMT_CHUNK_HEADER )); kb_wav_write_hdr( wav , &hdr ); memcpy( &hdr.type , "data" , 4 ); hdr.length = wav->length; kb_wav_write_hdr( wav , &hdr ); wav->modified = 0; } return 0; } /*--------------------------------------------------------------------*/ /*! This function closes a wav file. * \param wav the wav struct linked to the wav file */ void kb_wav_close( WAV * wav ) { COMMON_CHUNK_HEADER hdr; if ( wav->modified ) { rewind( wav->file ); memcpy( &hdr.type , "RIFF" , 4 ); hdr.length = sizeof( RIFF_CHUNK_HEADER) + sizeof( FMT_CHUNK_HEADER) + 8 + 8 + wav->length; memcpy( &hdr.chunk.riff.chunk_content , "WAVE" , 4 ); kb_wav_write_hdr( wav , &hdr ); memcpy( &hdr.type , "fmt " , 4 ); hdr.length = sizeof( FMT_CHUNK_HEADER ) ; memcpy( &hdr.chunk.fmt , &wav->fmt , sizeof( FMT_CHUNK_HEADER )); kb_wav_write_hdr( wav , &hdr ); memcpy( &hdr.type , "data" , 4 ); hdr.length = wav->length; kb_wav_write_hdr( wav , &hdr ); wav->modified = 0; } fclose(wav->file); wav->file = NULL; } /*--------------------------------------------------------------------*/ /*! This function reads a given number of data from a file opened with * kb_wav_open. The resulting data are placed in buf and can be played * using kb_snd_play. * \param wav the wav struct * \param buf the buffer to store the data * \param size the length of data to read * \return the number of bytes read */ int kb_wav_read_data( WAV * wav , void * buf , unsigned int size ) { int n; n=fread( buf , sizeof(unsigned char) , size , wav->file ); if ( n>0 ) { #if BYTE_ORDER == BIG_ENDIAN unsigned int pos; unsigned int incr; unsigned int nsample; unsigned short *p16; unsigned long *p32; incr = wav->fmt.byte_per_sample; nsample = size / incr; p16 = (unsigned short *)buf; p32 = (unsigned long *)buf; for (pos=0; pos<nsample; pos++) { switch(incr) { case 2: p16[pos] = SWAP_WORD(p16[pos]); break; case 4: p32[pos] = SWAP_LONG(p32[pos]); break; } } #endif /* BYTE_ORDER == BIG_ENDIAN */ } return n; } /*--------------------------------------------------------------------*/ /*! This function writes some data into the file. * \param wav the wav struct * \param buf the data to be writen * \param len the amount of bytes to write * \return the number of bytes writen */ int kb_wav_write_data( WAV * wav , void * buf , unsigned int len ) { int n; #if BYTE_ORDER == BIG_ENDIAN unsigned int pos; unsigned int incr; unsigned int nsample; unsigned short * p16; unsigned long *p32; incr = wav->fmt.byte_per_sample; nsample = len / incr; p16 = (unsigned short *)buf; p32 = (unsigned long *)buf; for (pos=0; pos<nsample; pos++) { switch(incr) { case 2: p16[pos] = SWAP_WORD(p16[pos]); break; case 4: p32[pos] = SWAP_LONG(p32[pos]); break; } } #endif /* BYTE_ORDER == BIG_ENDIAN */ n=fwrite( buf , sizeof(unsigned char) , len , wav->file ); if ( n > 0 ) { wav->length += n; wav->modified = 1; } return n; } /*--------------------------------------------------------------------*/ /*! Set the format for the given wav struct. The format is usually read * from the wav file header using kb_wav_open. */ void kb_wav_set_format( WAV * wav , unsigned short format , unsigned short nb_channel , unsigned long sample_rate , unsigned short bit_per_sample ) { unsigned long byte_per_sec; unsigned short byte_per_sample; wav->fmt.format = format; wav->fmt.nb_channel = nb_channel; wav->fmt.sample_rate = sample_rate; wav->fmt.bit_per_sample = bit_per_sample; byte_per_sample = ( bit_per_sample / 8 ); byte_per_sec = ( nb_channel * byte_per_sample * sample_rate ); wav->fmt.byte_per_sample = byte_per_sample; wav->fmt.byte_per_sec = byte_per_sec; wav->modified = 1; } /*--------------------------------------------------------------------*/ /*! This function reads Wave File header. */ int kb_wav_read_hdr( WAV * wav , COMMON_CHUNK_HEADER * hdr ) { fread( (void *)hdr , 8 , 1 , wav->file ); if ( memcmp( hdr->type , "RIFF" , 4 )==0 || memcmp( hdr->type , "riff" , 4 )==0) { fread( (void *)&hdr->chunk.riff , sizeof(RIFF_CHUNK_HEADER) , 1 , wav->file ); #if BYTE_ORDER == BIG_ENDIAN hdr->length = SWAP_LONG(hdr->length); #endif /* BYTE_ORDER == BIG_ENDIAN */ return 1; } if ( memcmp( hdr->type , "FMT " , 4 )==0 || memcmp( hdr->type , "fmt " , 4 )==0) { fread( (void *)&hdr->chunk.fmt , sizeof(FMT_CHUNK_HEADER) , 1 , wav->file ); #if BYTE_ORDER == BIG_ENDIAN hdr->length = SWAP_LONG(hdr->length); hdr->chunk.fmt.format = SWAP_WORD(hdr->chunk.fmt.format); hdr->chunk.fmt.nb_channel = SWAP_WORD(hdr->chunk.fmt.nb_channel); hdr->chunk.fmt.sample_rate = SWAP_LONG(hdr->chunk.fmt.sample_rate); hdr->chunk.fmt.byte_per_sec = SWAP_LONG(hdr->chunk.fmt.byte_per_sec); hdr->chunk.fmt.byte_per_sample = SWAP_WORD(hdr->chunk.fmt.byte_per_sample); hdr->chunk.fmt.bit_per_sample = SWAP_WORD(hdr->chunk.fmt.bit_per_sample); #endif /* BYTE_ORDER == BIG_ENDIAN */ return 2; } if ( memcmp( hdr->type , "DATA" , 4 )==0 || memcmp( hdr->type , "data" , 4 )==0) { #if BYTE_ORDER == BIG_ENDIAN hdr->length = SWAP_LONG(hdr->length); #endif /* BYTE_ORDER == BIG_ENDIAN */ return 3; } return -1; } /*--------------------------------------------------------------------*/ /*! This function writes a header into a Wave File. */ int kb_wav_write_hdr( WAV * wav , COMMON_CHUNK_HEADER * hdr ) { unsigned int hdrlen=8; if ( memcmp( hdr->type , "RIFF" , 4 ) == 0 || memcmp( hdr->type , "riff" , 4 ) == 0 ) { #if BYTE_ORDER == BIG_ENDIAN hdr->length = SWAP_LONG(hdr->length); #endif /* BYTE_ORDER == BIG_ENDIAN */ hdrlen += sizeof(RIFF_CHUNK_HEADER); } else if ( memcmp( hdr->type , "FMT " , 4 ) == 0 || memcmp( hdr->type , "fmt " , 4 ) == 0 ) { #if BYTE_ORDER == BIG_ENDIAN hdr->length = SWAP_LONG( hdr->length ); hdr->chunk.fmt.format = SWAP_WORD( hdr->chunk.fmt.format ); hdr->chunk.fmt.nb_channel = SWAP_WORD( hdr->chunk.fmt.nb_channel ); hdr->chunk.fmt.sample_rate = SWAP_LONG( hdr->chunk.fmt.sample_rate ); hdr->chunk.fmt.byte_per_sec = SWAP_LONG( hdr->chunk.fmt.byte_per_sec ); hdr->chunk.fmt.byte_per_sample = SWAP_WORD( hdr->chunk.fmt.byte_per_sample ); hdr->chunk.fmt.bit_per_sample = SWAP_WORD( hdr->chunk.fmt.bit_per_sample ); #endif /* BYTE_ORDER == BIG_ENDIAN */ hdrlen += sizeof(FMT_CHUNK_HEADER); } else if ( memcmp( hdr->type , "DATA" , 4 ) == 0 || memcmp( hdr->type , "data" , 4 ) == 0 ) { #if BYTE_ORDER == BIG_ENDIAN hdr->length = SWAP_LONG( hdr->length ); #endif /* BYTE_ORDER == BIG_ENDIAN */ } return fwrite( (void *)hdr , hdrlen , 1 , wav->file ); } /*--------------------------------------------------------------------*/ /*! This function dumps the wav file header to the standard output. * \param wav the wav struct */ void kb_wav_dump_format( WAV * wav ) { printf("%s\n" , (wav->fmt.format==1) ? "mono" : "stereo" ); printf("%u channel(s)\n", wav->fmt.nb_channel); printf("%lu Hz sample rate \n" , wav->fmt.sample_rate); printf("%lu byte per second\n", wav->fmt.byte_per_sec); printf("%u byte per sample\n" , wav->fmt.byte_per_sample); printf("%u bit per sample\n", wav->fmt.bit_per_sample); }
C
/*! \file userlist.c \brief The utility file. */ /*! \fn main() \brief The main executing function. */ #include<stdio.h> //#include "userlist.c" int main() { char string[10];char nl[2];char x; x='y'; struct node *first; first=NULL; while(x!='n') { printf("Enter user name : "); gets(string); first = ord_ins(string,first); printf("\nPress d to delete Element\nDo you wish to continue ?"); scanf("%c",&x); gets(nl); if(x=='d') { printf("\nEnter username to be deleted : "); gets(string); gets(nl); first=del(string,first); } } printf("Sorted List : \n"); display(first); return 0; }
C
#include <reg51.h> sbit WAVE =P0^1; void timer0() interrupt 1 { WAVE=~WAVE; //toggle pin } void serial0() interrupt 4 { if (TI==1) { TI=0; //clear interrupt } else { P0=SBUF; //put value on pins RI=0; //clear interrupt } } void main() { unsigned char x; P1=0xFF; //make P1 an input TMOD=0x22; TH1=0xF6; //4800 baud rate SCON=0x50; TH0=0xA4; //5 kHz has T=200us IE=0x92; //enable interrupts TR1=1; //start timer 1 TR0=1; //start timer 0 while (1) { x=P1; //read value from pins SBUF=x; //put value in buffer P2=x; //write value to pins } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/mman.h> #include <sys/types.h> #include <fcntl.h> int main() { struct stat fileStat; int file = open("ex1.txt", O_RDWR); stat("ex1.txt", &fileStat); off_t size = fileStat.st_size; char * message = "This is a nice day"; char * ad = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, file, 0); memcpy(ad, message, strlen(message)); return 0; }
C
#include <stdio.h> #include <string.h> #include <math.h> #define Length 100010 #define Len 200020 #define OK 1 #define ERROR 0 typedef int Status; typedef char QElemType; typedef struct BinaryS{ char bs[13]; int front; int rear; int maxsize; }BinaryS; Status EnQueue(BinaryS *Q, QElemType e){ if((Q->rear + 1) % Q->maxsize == Q->front) return ERROR; Q->bs[Q->rear] = e; Q->rear = (Q->rear + 1) % Q->maxsize; return OK; }//EnQueue Status DeQueue(BinaryS *Q, QElemType *e){ if(Q->front == Q->rear) return ERROR; //队列为空 *e = Q->bs[Q->front]; Q->front = (Q->front + 1) % Q->maxsize; return OK; }//DeQueue void HexConversion(char s[], char e[]) { //十六进制s[]转换为八进制存放在e[]中 int len, i, j, si, ei = 0; char b; BinaryS Q; len = strlen(s); Q.front = Q.rear = 0; Q.maxsize = 13; for(i = len; i > 0; i -= 3){ for(si = 1; i - si >= 0 && si <= 3; si++){ if(s[i - si] >= '0' && s[i - si] <= '9') s[i - si] -= '0'; else if(s[i - si] >= 'A' && s[i - si] <= 'F') s[i - si] = s[i - si] - 'A' + 10; else return; j = 4; while(j--){ b = s[i - si] % 2; s[i - si] /= 2; EnQueue(&Q, b); } } //每连续三个出队并转换为8进制存放于e[]中, e[]为8进制的倒序 while(Q.front != Q.rear){ e[ei] = '0'; for(j = 0; Q.front != Q.rear && j < 3; j++){ DeQueue(&Q, &b); e[ei] += b * pow(2, j); } ei++; } } e[ei] = '\0'; }//HexConversion int main() { int n, i, len, j; char sixteen[Length], eight[Len]; scanf("%d", &n); for(i = 0; i < n; i++){ scanf("%s", sixteen); HexConversion(sixteen, eight); len = strlen(eight); for(j = len - 1; j >= 0; j--) if(eight[j] != '0') break; for(; j >= 0; j--) printf("%c", eight[j]); putchar('\n'); } return 0; }//main
C
#include "gender_id.h" const char* gender_id_to_str(int genderId) { const char* ret; switch (genderId) { case GENDER_ID_Male: ret = "Male"; break; case GENDER_ID_Female: ret = "Female"; break; default: case GENDER_ID_Neuter: ret = "Neuter"; break; } return ret; }
C
#include <stdio.h> #include <stdlib.h> int main(){ FILE *fptr; char str[81]; if((fptr = fopen("Testestr.txt", "r")) == NULL){ puts("Não foi possível abri o arquivo."); return 0; } while(fgets(str, 80, fptr) != NULL) printf("%s", str); fclose(fptr); return 0; }
C
#include<stdio.h> void fun(); void main() { int a=5; printf("the value of a=%d",a); fun(); } void fun() { int a =10; printf("value of a within fun is fx:%d",a); }
C
#include <stdio.h> #include <stdlib.h> typedef struct Node { int key; struct Node *left; struct Node *right; struct Node *parent; } Node; Node *BST_Min(Node *node) { Node *cur = node; while (cur->left) { cur = cur->left; } return cur; } Node *BST_Max(Node *node) { Node *cur = node; while (cur->right) { cur = cur->right; } return cur; } Node *create_node(int key) { Node *new = malloc(sizeof *new); new->key = key; new->left = (void *)0; new->right = (void *)0; new->parent = (void *)0; return new; } void BST_Insert(Node **node, Node *parent, int key) { if (!(*node)) { *node = create_node(key); (*node)->parent = parent; return; } key < (*node)->key ? BST_Insert(&(*node)->left, *node, key) : BST_Insert(&(*node)->right, *node, key); } void BST_Destroy(Node *node) { if (!node) return; BST_Destroy(node->left); BST_Destroy(node->right); if (node) { free(node); } node = (void *)0; } void BST_Traverse(Node *node) { if (!node) return; BST_Traverse(node->left); printf("Node(%d)\n", node->key); BST_Traverse(node->right); } Node *BST_Search(Node *node, int key) { if (!node) { return (void *)0; } if (node->key == key) { return node; } return key < node->key ? BST_Search(node->left, key) : BST_Search(node->right, key); } Node *BST_Predecessor(Node *node, int key) { if (!node) { return (void *)0; } Node *n = BST_Search(node, key); if (n && n->left) { return BST_Max(n->left); } for (Node *cur = n; cur->parent; cur = cur->parent) { if (cur->parent->key < n->key) { return cur->parent; } } return (void *)0; } Node *BST_Successor(Node *node, int key) { if (!node) { return (void *)0; } Node *n = BST_Search(node, key); if (n && n->right) { return BST_Min(n->right); } for (Node *cur = n; cur->parent; cur = cur->parent) { if (cur->parent->key > n->key) { return cur->parent; } } return (void *)0; } void BST_Delete(Node *root, int key) { Node *delete = BST_Search(root, key); if (!delete) { return; } if (!delete->left && !delete->right) { if (delete->parent) { delete->key < delete->parent->key && (delete->parent->left = (void *)0); delete->key > delete->parent->key && (delete->parent->right = (void *)0); } free(delete); delete = (void *)0; return; } if (delete->left && delete->right) { Node *pred = BST_Predecessor(root, key); // Swap(pred(k), k); int temp = pred->key; pred->key = delete->key; delete->key = temp; BST_Delete(root, key); } if (delete->left) { delete->key < delete->parent->key ? (delete->parent->left = delete->left) : (delete->parent->right = delete->left); free(delete); delete = (void *)0; return; } if (delete->right) { delete->key < delete->parent->key ? (delete->parent->left = delete->right) : (delete->parent->right = delete->right); free(delete); delete = (void *)0; return; } } int main() { Node *root = (void *)0; for (int i = 0; i < 10; i++) { BST_Insert(&root, root, rand() % 100); } printf("(Min, Max) = (%d, %d)\n", BST_Min(root)->key, BST_Max(root)->key); int query = 77; Node *pred = BST_Predecessor(root, query); Node *succ = BST_Successor(root, query); if (pred) { printf("Predecessor(%d) == %d\n", query, pred->key); } if (succ) { printf("Successor(%d) == %d\n", query, succ->key); } int delete = 49; printf("Deleting %d\n", delete); BST_Delete(root, delete); BST_Traverse(root); BST_Destroy(root); }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <math.h> int prime(int x) { if(x<=1) return 0; for(int i=2; i*i<=x; i++) { if(x%i==0) return 0; } return 1; } int main() { int fd0[2],fd1[2]; if(pipe(fd0)==-1) printf("Can't send infos\n"); if(pipe(fd1)==-1) printf("Can't send infos\n"); pid_t PID=fork(); if(PID==0) { printf("In parent process\n"); printf("Enter length of Fibonacci array : "); int n; scanf("%d",&n); int fib[n+1]; fib[0]=0; fib[1]=1; for(int i=2;i<=n;i++) fib[i]=fib[i-1]+fib[i-2]; //send the n to parent process close(fd1[0]); write(fd1[1],&n,sizeof(n)); close(fd1[1]); //send the fib array to parent process close(fd0[0]); write(fd0[1],&fib,sizeof(fib)); close(fd0[1]); } else { wait(NULL); printf("In child process\n"); //receive n from child int n; close(fd1[1]); read(fd1[0],&n,sizeof(n)); close(fd1[0]); //receive fibonacci array from child int fib[n+1]; close(fd0[1]); read(fd0[0],&fib,sizeof(fib)); close(fd0[0]); printf("Fibonacci series upto n=%d is\n",n); for(int i=0;i<=n;i++) printf("%d ",fib[i]); printf("\nThe prime numbers in this series are\n"); for(int i=0;i<=n;i++) { if(prime(fib[i])==0) continue; printf("index = %d, number= %d\n",i,fib[i]); } } return 0; }
C
#ifndef linkedList_H #define linkedList_H typedef struct _Item { struct _Item* nextItem; char* data; } Item; typedef struct LinkedList { Item* originItem; } LinkedList; LinkedList* createList(Item* originItem); void freeList(LinkedList* list); void printList(LinkedList* list); Item* createItem(char* data); Item* getFinalItem(LinkedList* list); void addItem(LinkedList* list, Item* newItem); int delItem(LinkedList* list, char* data); void printItem(Item* item); #endif
C
#define SDL_MAIN_HANDLED #include <SDL2/SDL.h> #include <stdio.h> #include <stdlib.h> #include <time.h> int rnd(int max) { return rand() % max; } void draw_rect(SDL_Surface *surf, int x, int y, int w, int h, int color) { SDL_Rect rect = {x, y, w, h}; SDL_FillRect(surf, &rect, color); } void fill_triangle(SDL_Surface *surf, int x0, int y0, int x1, int y1, int x2, int y2, int color) { int tmp; if (y0 > y1) { tmp = y0; y0 = y1; y1 = tmp; tmp = x0; x0 = x1; x1 = tmp; } if (y0 > y2) { tmp = y0; y0 = y2; y2 = tmp; tmp = x0; x0 = x2; x2 = tmp; } if (y1 > y2) { tmp = y1; y1 = y2; y2 = tmp; tmp = x1; x1 = x2; x2 = tmp; } int cross_x1; int cross_x2; int dx1 = x1 - x0; int dy1 = y1 - y0; int dx2 = x2 - x0; int dy2 = y2 - y0; int top_y = y0; while(top_y < y1) { cross_x1 = x0 + dx1 * (top_y - y0) / dy1; cross_x2 = x0 + dx2 * (top_y - y0) / dy2; if (cross_x1 > cross_x2) { draw_rect(surf, cross_x2, top_y, cross_x1 - cross_x2, 1, color); } else { draw_rect(surf, cross_x1, top_y, cross_x2 - cross_x1, 1, color); } top_y++; } dx1 = x2 - x1; dy1 = y2 - y1; while(top_y < y2) { cross_x1 = x1 + dx1 * (top_y - y1) / dy1; cross_x2 = x0 + dx2 * (top_y - y0) / dy2; if (cross_x1 > cross_x2) { draw_rect(surf, cross_x2, top_y, cross_x1 - cross_x2, 1, color); } else { draw_rect(surf, cross_x1, top_y, cross_x2 - cross_x1, 1, color); } top_y++; } } int main(int argc, char* argv[]) { SDL_Init(SDL_INIT_VIDEO); int w = 640; int h = 480; SDL_Window *window = SDL_CreateWindow( "Triangles", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, w, h, SDL_WINDOW_ALLOW_HIGHDPI ); if (window == NULL) { printf("Could not create window: %s\n", SDL_GetError()); return 1; } int colors[] = {0x0000ff, 0x00ff00, 0x00ffff, 0xff0000, 0xff00ff, 0xffff00, 0xffffff}; int color_num = 0; SDL_Surface *screenSurface = SDL_GetWindowSurface(window); srand(time(0)); SDL_Event event; while(1) { SDL_WaitEvent(&event); if (event.type == SDL_QUIT) { break; } if (event.type == SDL_KEYDOWN) { int x0 = rnd(w); int y0 = rnd(h); int x1 = rnd(w); int y1 = rnd(h); int x2 = rnd(w); int y2 = rnd(h); int color = colors[color_num]; color_num++; if (color_num > 6) { color_num = 0; } fill_triangle(screenSurface, x0, y0, x1, y1, x2, y2, color); SDL_UpdateWindowSurface(window); } } SDL_FreeSurface(screenSurface); SDL_DestroyWindow(window); SDL_Quit(); return 0; }
C
#include "controller.h" //Function that creates an empty controller controller* CtrlCreate() { controller* C = (controller*)malloc(sizeof(controller)); C->repo = RepoCreate(); C->undoStack = StackCreate(&VecCreate); C->redoStack = StackCreate(&VecCreate); C->undoStackOps = StackCreate(&OperationDestroy); C->redoStackOps = StackCreate(&OperationDestroy); return C; } //Function that destroys the controller void CtrlDestroy(controller** C) { RepoDestroy(&((*C)->repo)); StackDestroy(&((*C)->undoStack), &VecDestroy); StackDestroy(&((*C)->redoStack), &VecDestroy); StackDestroy(&((*C)->undoStackOps), &OperationDestroy); StackDestroy(&((*C)->redoStackOps), &OperationDestroy); free(*C); *C = NULL; } //Function that return all the elements from the controller vector* CtrlGetAll(controller* C) { return RepoGetAll(C->repo); } /* Function that adds an element to controller. input: C - the initial controller c - the country that is added output: C - the new controller with the c country added */ int CtrlAdd(controller* C, country* c) { vector* W = CtrlGetAll(C); vector* to_push = VecCopy(W, &CountryDestroy, &CopyCountry); Push(C->undoStack, to_push); operation* op = OperationCreate("add", 0, CopyCountry(c), CopyCountry(c)); Push(C->undoStackOps, op); int exitcode = RepoAdd(C->repo, c); if (exitcode != 0) { Pop(C->undoStack); } return exitcode; } /* Function that deletes an element from controller. input: C - the initial controller name - the name of the country which is deleted output: C - the new controller without the country with the given name */ int CtrlDelete(controller* C, char* name) { vector* W = CtrlGetAll(C); vector* to_push = VecCopy(W, &CountryDestroy, &CopyCountry); Push(C->undoStack, to_push); int pos = RepoFind(C->repo, name); if (pos == -1) { return 1; } country* c = VecGetElement(C->repo->V, pos); operation* op = OperationCreate("delete", 0, CopyCountry(c), CopyCountry(c)); Push(C->undoStackOps, op); int exitcode = RepoDelete(C->repo, name); if (exitcode != 0) { Pop(C->undoStack); } return exitcode; } /* Function that updates a country existing in the controller input: C - the initial controller name - the name of the country which is updated - string c - the new country - country* output: C - the controller with the given country updated */ int CtrlUpdate(controller* C, char* name, country* c) { vector* W = CtrlGetAll(C); vector* to_push = VecCopy(W, &CountryDestroy, &CopyCountry); Push(C->undoStack, to_push); int pos = RepoFind(C->repo, name); if (pos != -1) { country* old_c = VecGetElement(C->repo->V, pos); operation* op = OperationCreate("update", 0, CopyCountry(old_c), CopyCountry(c)); Push(C->undoStackOps, op); } int exitcode = RepoUpdate(C->repo, name, c); if (exitcode != 0) { Pop(C->undoStack); } return exitcode; } /* Function that updates the 2 countries in case of migration input: C - the initial controller number - the number of people that migrate - integer from - the name of the country from which people migrate - string to - the name of the country to which people migrate - string output: C - the updated Controller */ int CtrlMigrate(controller* C, int number, char* from, char* to) { vector* W = CtrlGetAll(C); vector* to_push = VecCopy(W, &CountryDestroy, &CopyCountry); Push(C->undoStack, to_push); int pos_from = RepoFind(C->repo, from); int pos_to = RepoFind(C->repo, to); if (pos_from != -1 && pos_to != -1) { country* c1 = VecGetElement(C->repo->V, pos_from); country* c2 = VecGetElement(C->repo->V, pos_to); operation* op = OperationCreate("migrate", number, CopyCountry(c1), CopyCountry(c2)); Push(C->undoStackOps, op); } int exitcode = RepoMigrate(C->repo, number, from, to); if (exitcode != 0) { Pop(C->undoStack); } return exitcode; } /* Function that filters the countries from the controller. input: C - the controller pattern - the argument after which whe filter - genericType cmp - the comapre function - CompareFunctionType copy - the copy function for the elements from the controller - CopyFunctionType output: RepoFilter - a filtered vector with elements of genericType */ vector* CtrlFilter(controller* C, genericType pattern, CompareFunctionType cmp, CopyFunctionType copy) { return RepoFilter(C->repo, pattern, cmp, copy); } int CtrlUndoBonus(controller* C) { if (IsEmpty(C->undoStack)) { return 1; } vector* top = GetTop(C->undoStack); Push(C->redoStack, C->repo->V); C->repo->V = top; Pop(C->undoStack); return 0; } int CtrlRedoBonus(controller* C) { if (IsEmpty(C->redoStack)) { return 1; } vector* top = GetTop(C->redoStack); Push(C->undoStack, C->repo->V); C->repo->V = top; Pop(C->redoStack); return 0; } int CtrlUndo(controller* C) { if (IsEmpty(C->undoStackOps)) { return 1; } operation* op = GetTop(C->undoStackOps); Push(C->redoStackOps, OperationCopy(op)); if (strcmp(op->operationName, "add") == 0) { char* name = malloc(sizeof(char) * 100); strcpy(name, GetName(op->c1)); RepoDelete(C->repo, name); free(name); } if (strcmp(op->operationName, "delete") == 0) { RepoAdd(C->repo, CopyCountry(op->c1)); } if (strcmp(op->operationName, "update") == 0) { char* name = malloc(sizeof(char) * 100); strcpy(name, GetName(op->c2)); RepoUpdate(C->repo, name, CopyCountry(op->c1)); free(name); } if (strcmp(op->operationName, "migrate") == 0) { char* from = malloc(sizeof(char) * 100); char* to = malloc(sizeof(char) * 100); strcpy(from, GetName(op->c2)); strcpy(to, GetName(op->c1)); RepoMigrate(C->repo, op->number, from, to); free(from); free(to); } Pop(C->undoStackOps); return 0; } int CtrlRedo(controller* C) { if (IsEmpty(C->redoStackOps)) { return 1; } operation* op = GetTop(C->redoStackOps); Push(C->undoStackOps, OperationCopy(op)); if (strcmp(op->operationName, "add") == 0) { RepoAdd(C->repo, CopyCountry(op->c1)); } if (strcmp(op->operationName, "delete") == 0) { char* name = malloc(sizeof(char) * 100); strcpy(name, GetName(op->c1)); RepoDelete(C->repo, name); free(name); } if (strcmp(op->operationName, "update") == 0) { char* name = malloc(sizeof(char) * 100); strcpy(name, GetName(op->c1)); RepoUpdate(C->repo, name, CopyCountry(op->c2)); free(name); } if (strcmp(op->operationName, "migrate") == 0) { char* from = malloc(sizeof(char) * 100); char* to = malloc(sizeof(char) * 100); strcpy(from, GetName(op->c1)); strcpy(to, GetName(op->c2)); RepoMigrate(C->repo, op->number, from, to); free(from); free(to); } Pop(C->redoStackOps); return 0; }
C
/* дһ򣬽 ÿڵҶӽڵ */ #include<stdio.h> #include<stdlib.h> #define M 100 int i=0; typedef char Datatype; typedef struct Node { Datatype data; struct Node *Lchild; struct Node *Rchild; }Bitree; Bitree *Create() { Bitree *root; char ch; scanf("%c",&ch); if(ch=='*') root=NULL; else { root=(Bitree *)malloc(sizeof(struct Node)); root->data=ch; root->Lchild=Create(); root->Rchild=Create(); } return (root); } void Preorder(Bitree *root) { if(root!=NULL) { printf("%2c",root->data); Preorder(root->Lchild); Preorder(root->Rchild); } } Bitree *change(Bitree *root) { char temp[M],str[M]; if(root!=NULL&&root->Lchild!=NULL&&root->Rchild!=NULL) { if(root->Lchild!=NULL&&root->Rchild!=NULL) { temp[i]=root->Rchild->data; str[i]=root->Lchild->data; root->Lchild->data=temp[i]; root->Rchild->data=str[i]; i++; } else if(root->Lchild!=NULL&&root->Rchild==NULL) { root->Rchild=(Bitree *)malloc(sizeof(struct Node)); temp[i]=root->Lchild->data; root->Lchild=NULL; root->Rchild->data=temp[i]; i++; } else { root->Lchild=(Bitree *)malloc(sizeof(struct Node)); str[i]=root->Rchild->data; root->Rchild=NULL; root->Lchild->data=str[i]; i++; } change(root->Lchild); change(root->Rchild); } return root; } int main() { Bitree *root; root=NULL; root=Create(); printf("öõ£\n"); Preorder(root); printf("\n"); change(root); printf("ӽڵ㽻õΪ\n"); Preorder(root); printf("\n"); }
C
// Sean Szumlanski // COP 3502, Spring 2019 // ======================= // DupeyDupe: UnitTest02.c // ======================= // This test case helps ensure that your hoursSpent() function is implemented // correctly. // // For instructions on compiling your program with this source code, please see // the assignment PDF. #include <stdio.h> #include "DupeyDupe.h" // This acts as the main() function for this test case. int unit_test(int argc, char **argv) { int success = 1; // hoursSpent() must be strictly greater than zero. if (hoursSpent() <= 0) success = 0; printf("%s\n", success ? "Success!" : "Fail whale!"); return 0; }
C
#include<stdio.h> int main() { int seive[1000*1000]; long long i,j,s,temp,count,mp; s = 0; mp = 2; for(i=2;i<1000*1000;i++) seive[i] = 0; for(i=2;i<1000;i++) if(seive[i] == 0) for(j=i*i;j<1000*1000;j=j+i) seive[j] = 1; for(i=2;i<1000*1000;i++) if (seive[i] == 0) { temp = i; count = 1; for(j=i+1;j<1000*1000;j++) { if(seive[j] == 0) { if (temp+j >= 1000*1000) { break; } else { count++; temp = temp + j; if(seive[temp] == 0) { if(count > s) { s = count; mp = temp; } } } } } } printf("%lld %lld\n",s, mp); return 0; }
C
#include <stdio.h> #include <stdlib.h> int simple(int * a, int size){ int counter = 0; for(int i = 0; i < size; i+=1){ counter += a[i]; }; return counter; } int doubl(int * c, int size){ int counter = 0; for(int i = 0; i < size - 1; i += 2){ counter += c[i]; counter += c[i + 1]; } return counter; } int foo(int * a, int * b, int size){ int counter = 0; for(int i = 0; i < size; i += 2){ counter += b[i]; counter += b[i+1]; } for(int i = 0; i < size; i += 2){ counter += a[i]; counter += a[i+1]; } return counter; } int main(){ int size = 512; int b[size]; int a[size]; int one = 0; int two = 0; for(int i = 0; i < size; i ++){ b[i] += i; } for(int i = 0; i < size - 1; i ++){ for(int j = -1; j < 2; j++){ a[i] = b[i+j]; } } return 0; }
C
#include <stdio.h> #include <stdlib.h> void trace(int a[], int N){ for (int i =0 ; i<N; i++){ if (i>0){ printf(" "); } printf("%d", a[i]); } printf("\n"); } void insertion(int a[], int N){ int i, j, tmp; for (int i=0; i<N;i++){ tmp=a[i]; j=i-1; while(j>=0 && a[j]>tmp){ a[j+1]=a[j]; j--; } a[j+1]=tmp; trace(a,N); } } int main(int argc, char const *argv[]) { int N; int* A=(int*)malloc(N*sizeof(int)); scanf("%d",&N); for(int i=0; i<N;i++){ scanf("%d", &A[i]); } printf("input result is...\n"); trace(A,N); printf("start algorithm insertion\n"); insertion(A,N); free(A); return 0; }
C
#include <cs50.h> #include <stdio.h> #include <string.h> #include <ctype.h> string get_name(){ string name; do { name = get_string(); }while(name == NULL); return name; } void make_initials(string name){ char initial[2]; for(int i = 0; i < strlen(name); i++){ if(isalpha(name[i])){ if( i > 0){ if(!isalpha(name[i-1])){ initial[0] = toupper(name[i]); printf("%s", initial); } }else{ initial[0] = toupper(name[0]); printf("%s", initial); } } } printf("\n"); } int main(void){ make_initials(get_name()); return 0; }
C
#include <stdio.h> /* 问题描述: 返回输入正整数第一个是1的比特位的位置(若输入0或负数返回-1) 样例输入: 12 0 样例输出: 2 -1 */ int indexFind(long long int num) { if(num <= 0) return -1; int index = 0; while(((num >> index) & 1) == 0) { ++index; } return index; } int main() { long long int n = 0; while(scanf("%lld", &n) != EOF) { printf("%d\n", indexFind(n)); } return 0; }
C
/* @Anugunj Naman @1801022 To run this file create object file using lpthread then $>./server */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/ipc.h> #include <mirror.h> #include <sys/msg.h> #include <signal.h> #include <pthread.h> #define _GNU_SOURCE int send_message( int qid, struct mymsgbuf *qbuf ){ int result, length; length = sizeof(struct mymsgbuf) - sizeof(long); if((result = msgsnd( qid, qbuf, length, 0)) == -1){ return(-1); } return(result); } int read_message( int qid, long type, struct mymsgbuf *qbuf ){ int result, length; length = sizeof(struct mymsgbuf) - sizeof(long); if((result = msgrcv( qid, qbuf, length, type, 0)) == -1){ return(-1); } return(result); } int main() { key_t key=1234; qid=msgget(key,IPC_CREAT|0666); if(change_queue_size(qid)==-1) { perror("Error while changing the size of Message queue"); exit(1); } int j=0; for(j=0;j<10000;j++) poid[j]=-1; printf("qid : %d\n",qid); pthread_t threads[3]; int rc; long i; i=0; rc = pthread_create(&threads[i], NULL, cpl, qid); i=1; if (rc){ printf("Error:unable to create thread, %d\n",rc); return 0; } rc = pthread_create(&threads[i], NULL, uncpl, qid); if (rc){ printf("Error:unable to create thread, %d\n",rc); return 0; } i=2; rc = pthread_create(&threads[i], NULL, rcvsend, qid); if (rc){ printf("Error:unable to create thread, %d\n",rc); return 0; } signal(SIGINT,ctrlc); pthread_exit(NULL); return 0; } void ctrlc() { msgctl(qid,IPC_RMID,NULL); exit(0); }
C
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<sys/time.h> #include<signal.h> #include<sys/types.h> void fa(int signo){ printf("random\n"); } int main(){ //设置对信号SIGALRM进行自定义处理 if(SIG_ERR==signal(SIGALRM,fa)) perror("signal"),exit(-1); struct itimerval timer; //设置间隔时间 timer.it_interval.tv_sec=2; timer.it_interval.tv_usec=300000; //设置启动时间 timer.it_value.tv_sec=5; timer.it_value.tv_usec=0; int res=setitimer(ITIMER_REAL,&timer,NULL); if(-1==res) perror("setitimer"),exit(-1); getchar(); itimer.it_value.tv_sec=0; setitimer(ITIMER_REAL,&timer,NULL); //没有错误处理 while(1); return 0; }
C
#include <stdio.h> int triangulo(int x, int y, int z) { return (x < y+z && y < x+z && z < x+y ); } int tipoTriangulo(int x, int y, int z) { if(!triangulo(x, y, z)) { return 0; } if(x == y && y == z) { return 3; } else if(x == y || x == z || y == z) { return 2; } else { return 1; } } main() { int x, y, z; printf("Forneca o primeiro lado: "); scanf("%d", &x); printf("Forneca o segundo lado: "); scanf("%d", &y); printf("Forneca o terceiro lado: "); scanf("%d", &z); printf("O triangulo e :"); switch (tipoTriangulo(x,y,z)) { case 1: printf(" Escaleno"); break; case 2: printf(" Isosceles"); break; case 3: printf(" Equilatero"); break; default: printf("Nao e triangulo"); break; } }
C
#include<stdio.h> //implement by piyal_IT_15021 void main() { int nop,nof,page[20],i,count=0; printf("\nEnter the No. of Pages: "); scanf("%d",&nop); //Store the no of pages printf("\n Enter the Reference String:\n"); for(i=0; i<nop; i++) { scanf("%d",&page[i]); //Array for Storing Reference String } printf("\n Enter the No of frames: "); scanf("%d",&nof); int frame[nof],fcount[nof]; for(i=0; i<nof; i++) { frame[i]=-1; //Frame Array fcount[i]=0; // Track the next Availability of frames } i=0; while(i<nop) { int j=0,flag=0; while(j<nof) { if(page[i]==frame[j]) // Checking Whether the Page is Already in frame or not { flag=1; } j++; } j=0; printf("\n"); printf("\t%d",page[i]); if(flag==0) { if(i>=nof) { int max=0,k=0; while(k<nof) { int dist=0,j1=i+1; while(j1<nop) { if(frame[k]!=page[j1]) //Calculating Distances of pages that are in the frame to their next occurence dist++; else { break; } j1++; } fcount[k]=dist; //Storing Distances into array k++; } k=0; while(k<nof-1) { if(fcount[max]<fcount[k+1]) //Finding out the maxximum distance max=k+1; k++; } frame[max]=page[i]; } else { frame[i%nof]=page[i]; } count++; // Increasing Page Fault. while(j<nof) { printf("\t%d",frame[j]); j++; } } i++; } char exit; printf("\n\nPage Fault is: %d\n",count); printf("\npress e for exit...... "); scanf("%c",&exit); if(exit=='e') { printf(".......Exit....."); } return 0; }
C
#include<stdio.h> #include<math.h> int main(){ int x; scanf("%d",&x); double sum=1; double t=1; double cons=0.00001; int i=1; while(t>cons){ t=power(x,i)/fact(i); sum+=t; i++; } printf("sum =%lf\n",sum); printf("exp(%d)=%lf",x,exp(x)); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h>> struct email { char title[100]; char receiver[50]; char sender[50]; char content[1000]; char date[100]; int priority; }; int main(void) { struct email e; //strcpy(e.title, "Ⱥ "); printf("title:\n"); scanf_s("%s", e.title,sizeof(e.title)); //strcpy(e.receiver, "chulsoo@hankuk.ac.kr"); printf("receiver:\n"); scanf_s("%s", e.receiver, sizeof(e.receiver)); //strcpy(e.sender, "hsh@hankuk.ac.kr"); printf("sender:\n"); scanf_s("%s", e.sender, sizeof(e.sender)); //strcpy(e.content, "ȳϽʴϱ? ?"); printf("content:\n"); scanf_s("%s", e.content, sizeof(e.content)); getchar(); getchar(); //strcpy(e.date, "2018/9/1"); printf("date:\n"); scanf_s("%s",e.date, sizeof(e.receiver)); e.priority = 1; printf("%s\n %s\n %s\n %s\n %s\n %d\n", e.title, e.receiver, e.sender, e.content, e.date, e.priority); system("pause"); getchar(); return 0; }
C
#include <stdio.h> #include <unistd.h> double t = 0.1; int y = 7; double g = 6.9; int main(void) { int k = 0; printf("Hello, world!\n"); y = y + 3; g = g + t; sleep(5); /* changed from master */ return k; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <memory.h> #define MAX_WORD_SIZE 100 #define MAX_MEANING_SIZE 200 typedef struct { char word[MAX_WORD_SIZE]; char meaning[MAX_MEANING_SIZE]; } element; typedef struct TreeNode { element key; TreeNode *left, *right; } TreeNode; int compare(element e1, element e2) { return strcmp(e1.word, e2.word); } void display(TreeNode * p) { if (p != NULL) { printf("("); display(p->left); printf("%s:%s", p->key.word, p->key.meaning); display(p->right); printf(")"); } } TreeNode * search(TreeNode * root, element key) { TreeNode * p = root; while (p != NULL) { if (compare(key, p->key) == 0) return p; else if (compare(key, p->key) < 0) p = p->left; else if (compare(key, p->key) > 0) p = p->right; } return p; } TreeNode * new_node(element item) { TreeNode * temp = (TreeNode *)malloc(sizeof(TreeNode)); temp->key = item; temp->left = temp->right = NULL; return temp; } TreeNode * insert_node(TreeNode * node, element key) { if (node == NULL) return new_node(key); if (compare(key, node->key) < 0) node->left = insert_node(node->left, key); else if (compare(key, node->key) > 0) node->right = insert_node(node->right, key); return node; } TreeNode * min_value_node(TreeNode * node) { TreeNode * current = node; while (current->left != NULL) current = current->left; return current; } TreeNode * delete_node(TreeNode * root, element key) { if (root == NULL) return root; if (compare(key, root->key) < 0) root->left = delete_node(root->left, key); if (compare(key, root->key) > 0) root->right = delete_node(root->right, key); else { if (root->left == NULL) { TreeNode * temp = root->right; free(root); return temp; } else if (root->right == NULL) { TreeNode * temp = root->left; free(root); return temp; } TreeNode * temp = min_value_node(root->right); root->key = temp->key; root->right = delete_node(root->right, temp->key); } return root; } void help() { printf("\n**** i: Է, d: , s: Ž, p: , q: ****: "); } int main() { char command; element e; TreeNode * root = NULL; TreeNode * tmp; do { help(); command = getchar(); getchar(); switch (command) { case 'i': printf("ܾ:"); gets(e.word); printf("ǹ:"); gets(e.meaning); root = insert_node(root, e); break; case 'd': printf("ܾ:"); gets(e.word); root = delete_node(root, e); break; case 'p': display(root); printf("\n"); break; case 's': printf("ܾ:"); gets(e.word); tmp = search(root, e); if (tmp != NULL) printf("ǹ:%s\n", e.meaning); break; } } while (command != 'q'); return 0; }
C
/* set_initial: stores initial values on all points of the */ /* computational grid */ /* (very simple and dumb routine) */ /* input: int grid[3] # of points in all directions */ /* double *domain Pointer to the memory */ /* output: int set_initial =0 for ok, <>0 for error */ #include "mpi.h" #include "parheat.h" int set_initial( int *grid, double *mem ) { int i, imax; imax = grid[0]*grid[1]*grid[2]; for( i=0 ; i<imax ; i++ ) { mem[i] = 0.0; } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: nthrynn <nthrynn@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/09/17 16:50:12 by nthrynn #+# #+# */ /* Updated: 2019/09/17 18:10:59 by nthrynn ### ########.fr */ /* */ /* ************************************************************************** */ #include <fcntl.h> #include <unistd.h> #include "get_next_line.h" #include <stdlib.h> #include "libft/libft.h" #include <libc.h> int ft_new_line(char **res, char **line, int fd) { char *tmp; size_t i; i = 0; while (res[fd][i] != '\n' && res[fd][i] != '\0') i++; if (res[fd][i] == '\n') { *line = ft_strsub(res[fd], 0, i); tmp = ft_strdup(res[fd] + i + 1); free(res[fd]); res[fd] = tmp; if (res[fd][0] == '\0') ft_strdel(&res[fd]); } else if (res[fd][i] == '\0') { *line = ft_strdup(res[fd]); ft_strdel(&res[fd]); } return (1); } int get_next_line(const int fd, char **line) { static char *res[15000]; char buf[BUFF_SIZE + 1]; char *tmp; int ret; if (fd < 0 || line == NULL || read(fd, buf, 0) > 0 || fd > 200) return (-1); while ((ret = read(fd, buf, BUFF_SIZE)) > 0) { buf[ret] = '\0'; if (res[fd] == NULL) res[fd] = ft_strnew(1); tmp = ft_strjoin(res[fd], buf); free(res[fd]); res[fd] = tmp; if (ft_strchr(buf, '\n')) break ; } if (ret < 0) return (-1); else if (ret == 0 && (res[fd] == NULL || res[fd] == '\0')) return (0); return (ft_new_line(res, line, fd)); }
C
#include "Polinomios.h" NoLOG* criaListaLOG(){ /* Cria lista do LOG */ return NULL; } /* Insere no inicio da lista LOG as operações e resultados do usuário */ NoLOG* InsereInicioLOG (NoLOG* l, char* info) { NoLOG* novo = (NoLOG*) malloc(sizeof(NoLOG)); if(novo == NULL){ printf("Erro."); exit(1);} novo->info = info; novo->proximo = l; return novo; } /** Funcao recebe uma lista L e insere ela no arquivo **/ void escreveLOG(FILE *log, NoLOG* lista) { NoLOG *l = lista; while(l != NULL){ /** Enquanto a lista nao chegar no fim, insere a string NoLOG por cada char* na lista no arquivo, linha a linha **/ fputs (l->info, log); l = l->proximo; } } void imprimeLOG(FILE *log){ /** Funcao que imprime o LOG **/ char s[20]; log = fopen("log.txt", "r"); if(log == NULL){ printf("Erro, nao foi possivel abrir o arquivo\n");} else{ while(fscanf(log,"%s", &s) != EOF){ /* Printa linha a linha */ printf("%s \n", s); } } fclose(log); }