language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> int main(){ int a = 10; int b = 2; printf("%d += %d = ", a, b); a += b; //a = a + b printf("%d\n", a); a = 10; b = 2; printf("%d -= %d = ", a, b); a -= b; printf("%d\n", a); a = 10; b = 2; printf("%d /= %d = ", a, b); a /= b; printf("%d\n", a); a = 10; b = 2; printf("%d *= %d = ", a, b); a *= b; printf("%d\n", a); a = 21; b = 2; printf("%d %%= %d = ", a, b); a %= b; printf("%d\n", a); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ants.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jmeier <jmeier@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/03/28 13:56:31 by jmeier #+# #+# */ /* Updated: 2018/04/07 22:25:54 by jmeier ### ########.fr */ /* */ /* ************************************************************************** */ #include <lemin.h> /* ** So it looks as if the ants work on a sort of queue? I run through the things ** in what looks to be a while loop. So while */ void one_small_step_for_an_ant(int finished, t_node *second, t_lemin *lem) { second->path->ant_in_node = second->ant_in_node + 1; second->path->ant_in_node - 1 != finished ? write(1, " ", 1) : 0; ft_printf("L%i-%s", second->path->ant_in_node, second->path->name); --lem->remain; } void the_ants_go_marching(t_lemin *lem, int finished) { t_node *tmp; while (finished < lem->ants) { tmp = lem->end; while (tmp->path) { if (tmp->end && tmp->ant_in_node) ++finished; tmp->ant_in_node = tmp->path->ant_in_node; if (tmp->ant_in_node) { tmp->ant_in_node - 1 != finished ? write(1, " ", 1) : 0; ft_printf("L%i-%s", tmp->ant_in_node, tmp->name); } if (tmp->path->start) !lem->remain ? (tmp->path->ant_in_node = 0) : \ one_small_step_for_an_ant(finished, tmp, lem); tmp = tmp->path; } if (finished == lem->ants) break ; write(1, "\n", 1); } }
C
/** page 410 program 12.6 Write a program to append additional items to the file INVENTORY created in program 12.3 and print the total content of the file. */ ///program begin #include<stdio.h> #include<conio.h> //main() function begin struct invent_record { char name[10]; int number; float price; int quantity; }; int main() { struct invent_record item; char filename[10]; int response; FILE *fp; long n; void append(struct invent_record *x, FILE *y); printf("Type Filename:\n"); scanf("%s",filename); getchar(); fp = fopen(filename, "a+"); do { append(&item, fp); printf("\nItem %s appended.\n",item.name); printf("\nDo you want to add another item\n(1 for YES 0 for NO)?"); scanf("%d",&response); }while(response == 1); n = ftell(fp); fclose(fp); fp = fopen(filename , "r"); while(ftell(fp) < n) { fscanf(fp, "%s %d %f %d", item.name, &item.number, &item.price, &item.quantity); fprintf(stdout,"%-8s %7d %8.2f %8d\n", item.name, item.number, item.price, item.quantity); } fclose(fp); getch(); return 0; } ///main() end void append(struct invent_record *product, FILE *ptr) { printf("Item name\n"); scanf("%s",product->name); printf("Item number\n"); scanf("%d",&product->number); printf("Item price\n"); scanf("%f",&product->price); printf("Quantity\n"); scanf("%d",&product->quantity); fprintf(ptr ,"%s %d %.2f %d", product->name, product->number, product->price, product->quantity); } ///program end /** output Type Filename: INVENTORY Item name xxx Item number 444 Item price 40.50 Quantity 34 Item xxx appended. Do you want to add another item (1 for YES 0 for NO)?1 Item name YYY Item number 555 Item price 50.50 Quantity 45 Item YYY appended. Do you want to add another item (1 for YES 0 for NO)?0 AAA-1 111 17.50 115 BBB-2 125 36.00 75 C-3 247 31.75 104 xxx 444 40.50 34 YYY 555 50.50 45 Process returned 0 (0x0) execution time : 58.762 s Press any key to continue. */
C
/* Задача 11. Направете обединение с елементи тип int, int, char. Дайте стойност на елементите един по един -7, 10 и 'c' и изведете тези стойности на конзолата. */ /* Не разбрах идеята */ #include <stdio.h> union wabadabadubdub { int waba; int daba; char dub; }; int main() { union wabadabadubdub wbd; wbd.waba = -7; printf("%d\n", wbd.waba); wbd.daba = 10; printf("%d\n", wbd.daba); wbd.dub = 'c'; printf("%c\n", wbd.dub); wbd.waba = -7; wbd.daba = 10; wbd.dub = 'c'; printf("%d\n", wbd.waba); printf("%d\n", wbd.daba); printf("%c\n", wbd.dub); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include "osc_types.h" extern osc_node *osc_root; static osc_node *init_working_set(osc_node *root) { osc_node *working_set = NULL; while (root != NULL) { root->next = working_set; working_set = root; root = root->sibling; } return working_set; } static osc_node *add_children(osc_node *set, osc_node *p) { p = p->child; while (p != NULL) { p->next = set; set = p; p = p->sibling; } return set; } static osc_node *add_to_set(osc_node *set, osc_node *p) { p->next = set; set = p; return set; } #if 0 static void print_set(osc_node *p) { printf("{"); while (p != NULL) { printf("%d (%s), ",p->id,p->name); p = p->next; } printf("}\n"); } #endif static int match(osc_node *p, char *query) { int match = 1; char *name = p->name; char *saved_name = NULL; char *saved_query = NULL; int finished = 0; int hash_matched = 0; while (!finished) { // printf(": %s : %s :\n",query, name); switch (*query) { case 0: case '/': if (*name == 0 || (OSC_IS_HASH_NODE(p) && hash_matched)) { finished = 1; } else if (saved_query && saved_name != name-1) { query = saved_query; saved_name++; name = saved_name; } else { finished = 1; match = 0; } break; case '*': saved_query = query; saved_name = name; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (OSC_IS_HASH_NODE(p)) { p->val = *query-'0'; hash_matched = 1; break; } default: if (*query == *name || *query == '?') { name++; } else if (saved_query && *name != 0) { query = saved_query; saved_name++; name = saved_name; } else { finished = 1; match = 0; } break; } query++; } return (match); } osc_node *osc_match(char *query) { osc_node *working_set = NULL; char *next_query; osc_node *p; osc_node *child_set = NULL; osc_node *matched_set = NULL; working_set = init_working_set(osc_root); // printf("init_set:");print_set(working_set); while (*query) { child_set = NULL; matched_set = NULL; // printf("query: %s\n", query); next_query=query; while (*next_query != 0 && *next_query != '/') next_query++; if (*next_query) next_query++; matched_set = NULL; child_set = NULL; p = working_set; while (p != NULL) { osc_node *next = p->next; if (match(p, query)) { matched_set = add_to_set(matched_set, p); child_set = add_children(child_set, p); } p = next; } // printf("child:");print_set(child_set); working_set = child_set; // print_set(working_set); query = next_query; } // printf("matched:");print_set(matched_set); return matched_set; }
C
/* Thomas BERNARD */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "hfscommon.h" enum command { INVALID = 0, SHOW = 1, DISABLE, SETROOT, SETID }; void writeu32(unsigned char * p, uint32_t i) { p[0] = (i >> 24) & 0xff; p[1] = (i >> 16) & 0xff; p[2] = (i >> 8) & 0xff; p[3] = i & 0xff; } #define AUTO_OPEN_DIR_ID_OFFSET (80 + 2 * 4) void set_auto_folder(FILE * f, uint32_t folderid) { unsigned char buffer[512]; unsigned char a_buffer[512]; uint32_t dir_id; int write_alternate = 0; if(fseek(f, hfs_part_sector * SECTOR_SIZE + HFS_VOLUME_HEADER_OFFSET, SEEK_SET) != 0) { perror("fseek"); return; } if(fread(buffer, 1, sizeof(buffer), f) != sizeof(buffer)) { fprintf(stderr, "reading error\n"); return; } printf("SIGNATURE %c%c\n", buffer[0], buffer[1]); if(buffer[0] != 'H' || buffer[1] != '+') { printf("Not HFS+\n"); return; } if(fseek(f, (hfs_part_sector + hfs_part_sector_count) * SECTOR_SIZE - HFS_VOLUME_HEADER_OFFSET, SEEK_SET) != 0) { perror("fseek"); return; } if(fread(a_buffer, 1, sizeof(a_buffer), f) != sizeof(a_buffer)) { fprintf(stderr, "reading error\n"); return; } if(memcmp(buffer, a_buffer, sizeof(buffer)) == 0) { write_alternate = 1; } dir_id = readu32(buffer + AUTO_OPEN_DIR_ID_OFFSET); printf("Former value = %u\n", dir_id); if(dir_id == folderid) { printf("No need to patch\n"); return; } writeu32(buffer + AUTO_OPEN_DIR_ID_OFFSET, folderid); dir_id = readu32(buffer + AUTO_OPEN_DIR_ID_OFFSET); printf("New value = %u\n", dir_id); /* Main Volume Header */ if(fseek(f, hfs_part_sector * SECTOR_SIZE + HFS_VOLUME_HEADER_OFFSET, SEEK_SET) != 0) { perror("fseek"); return; } if(fwrite(buffer, 1, sizeof(buffer), f) != sizeof(buffer)) { fprintf(stderr, "write error\n"); return; } /* Alternate Volume Header */ if(write_alternate) { if(fseek(f, (hfs_part_sector + hfs_part_sector_count) * SECTOR_SIZE - HFS_VOLUME_HEADER_OFFSET, SEEK_SET) != 0) { perror("fseek"); return; } if(fwrite(buffer, 1, sizeof(buffer), f) != sizeof(buffer)) { fprintf(stderr, "write error\n"); return; } } printf("successfully patched !\n"); } void usage(const char * progname) { fprintf(stderr, "usage: %s <command> <file.iso>\n", progname); fprintf(stderr, "commands :\n"); fprintf(stderr, " show : only display informations\n"); fprintf(stderr, " disable : disable autofolder\n"); fprintf(stderr, " setroot : set autofolder to root\n"); fprintf(stderr, " setfolderid <id> : set autofolder to id * USE WITH CARE *\n"); } int main(int argc, char * * argv) { FILE * f; int ok = 0; const char * filename = NULL; enum command cmd = INVALID; uint32_t folderid = 0; if(argc < 3 || 0 == strcmp(argv[1], "help")) { usage(argv[0]); return 1; } filename = argv[2]; if(strcmp(argv[1], "show") == 0) { cmd = SHOW; } else if(strcmp(argv[1], "disable") == 0) { cmd = DISABLE; folderid = 0; } else if(strcmp(argv[1], "setroot") == 0) { cmd = SETROOT; folderid = 2; /* ROOT folder */ } else if(strcmp(argv[1], "setfolderid") == 0) { folderid = strtoul(argv[2], NULL, 0); if(argc < 4) { usage(argv[0]); return 1; } filename = argv[3]; } else { fprintf(stderr, "unknown command '%s'\n\n", argv[1]); usage(argv[0]); return 1; } f = fopen(filename, "rb"); if(!f) { fprintf(stderr, "Failed to open file %s\n", filename); return 2; } read_partition_map(f); if(hfs_part_sector == 0 && hfs_part_sector_count == 0) { printf("HFS/HFS+ partition not found\n"); } else { ok = read_hfs_volume_header(f); } fclose(f); if(ok) { switch(cmd) { case DISABLE: case SETROOT: case SETID: f = fopen(filename, "r+b"); if(!f) { fprintf(stderr, "Failed to open file %s for Writing\n", filename); return 4; } set_auto_folder(f, folderid); fclose(f); break; case SHOW: (void)0; break; default: fprintf(stderr, "*** INVALID COMMAND ***\n"); return 5; } } else { fprintf(stderr, "Errors reading HFS+ volume from %s\n", filename); return 3; } return 0; }
C
/** * This file contains all of the data used to configure the robot * * @author Thomas Batchelder * @date 1/19/2021 - Created configuration file */ #pragma once #include <Arduino.h> #define BAUDRATE 250000 // Serial monitor baud rate #define STARTUP_DELAY 7500 // Delay at beginning of program to let Serial monitor initialize #define UNLIMITED_ROTATIONS -1 // Used to indicate that a motor is not limited #define CLOCKWISE false // Used to set the direction of the motor to reverse #define COUNTERCLOCKWISE true // Used to set the direction of the motor to forward #define MAX_VELOCITY 1e-2 // Maximum velocity the arm can travel at #define MAX_STEPPER_ENCODER_DIFFERENCE 500 // number of steps that the encoder and stepper can differ #define ENCODER_CPR 4000.0 // Number of counts per revolution of the encoder #define DOF 6 // Degrees of freedom in the arm #define DOF_ACTIVE 6 // Degrees of freedom in the arm that are active #define MINUTES_TO_SECONDS 60.0 // Number of seconds in a minute #define SECONDS_TO_MICROSECONDS 1000000.0f // Converstion from seconds to microseconds #define DEGREES_PER_ROTATION 360.0 // Number of degrees in one rotation // Homing configuration #define HOMING_VELOCITY 0.04e-3 #define HOMING_ACCELERATION 0.03e-9 // Axis Pins: 1 2 3 4 5 6 #define STEP_PINS { 3, 9, 1, 6, 24, 32} #define DIR_PINS { 5, 11, 0, 8, 26, 31} #define LIMIT_SWITCH_PINS {38, 37, 36, 35, 34, 33} #define ENCODER_THRESHOLD {100, 100, 100, 100, 100, 100} #define MICROSTEPING {1000, 1000, 1000, 1600, 1000, 1000} #define GEAR_REDUCTION {40.0, 50.0, 50.0, 14.0 * (28.0 / 10), 10.0, 19.0} #define MAX_POSITION {-1, -1, -1, -1, -1, -1} #define INVERT_DIR {1, 1, 1, 1, 1, 1} #define CRASH_DETECTION {1, 0, 1, 0, 1, 1} #define ENCODER_1_PINS 39, 7 #define ENCODER_2_PINS 40, 25 #define ENCODER_3_PINS 2, 41 #define ENCODER_4_PINS 21, 10 #define ENCODER_5_PINS 23, 28 #define ENCODER_6_PINS 22, 29
C
#include <stdio.h> typedef struct pnode { float coef; int exp; struct pnode *next; }p; p *getnode(); void main() { p *p1,*p2,*p3; p *getpoly(),*add(p*,p*); void display(p*); printf(“enter first polynomial”); p1=getpoly(); printf(“\n enter second polynomial”); p2=getpoly(); printf(“\nthe first polynomial is”); display(p1); printf(“\nthe second polynomial is”); display(p2); p3=add(p1,p2); printf(“\naddition of two polynomial is :\n”); display(p3); } p *getpoly() { p *temp,*New,*last; int flag,exp; char ans; float coef; temp=NULL; flag=1; printf(“\nenter the polynomial in descending order of exponent”); do { printf(“\nenter the coef & exponent of a term”); scanf(“%f%d”,&coef,&exp); New=getnode(); if(New==NULL) printf(“\nmemory cannot be allocated”); New->coef=coef; New->exp=exp; if(flag==1) { temp=New; last=temp; flag=0; } else { last->next=New; last=New; } printf(“\ndou want to more terms”); ans=getch(); } while(ans==’y'); return(temp); } p *getnode() { p *temp; temp=(p*) malloc (sizeof(p)); temp->next=NULL; return(temp); } void display(p*head) { p*temp; temp=head; if(temp==NULL) printf(“\npolynomial empty”); while(temp->next!=NULL) { printf(“%0.1fx^%d+”,temp->coef,temp->exp); temp=temp->next; } printf(“\n%0.1fx^%d”,temp->coef,temp->exp); getch(); } p*add(p*first,p*second) { p *p1,*p2,*temp,*dummy; char ch; float coef; p *append(int,float,p*); p1=first; p2=second; temp=(p*)malloc(sizeof(p)); if(temp==NULL) printf(“\nmemory cannot be allocated”); dummy=temp; while(p1!=NULL&&p2!=NULL) { if(p1->exp==p2->exp) { coef=p1->coef+p2->coef; temp=append(p1->exp,coef,temp); p1=p1->next; p2=p2->next; } else if(p1->expexp) { coef=p2->coef; temp=append(p2->exp,coef,temp); p2=p2->next; } else if(p1->exp>p2->exp) { coef=p1->coef; temp=append(p1->exp,coef,temp); p1=p1->next; } } while(p1!=NULL) { temp=append(p1->exp,p1->coef,temp); p1=p1->next; } while(p2!=NULL) { temp=append(p2->exp,p2->coef,temp); p2=p2->next; } temp->next=NULL; temp=dummy->next; free(dummy); return(temp); } p*append(int Exp,float Coef,p*temp) { p*New,*dum; New=(p*)malloc(sizeof(p)); if(New==NULL) printf(“\ncannot be allocated”); New->exp=Exp; New->coef=Coef; New->next=NULL; dum=temp; dum->next=New; dum=New; return(dum); }
C
#include<stdio.h> /** * main - if q or e , dont print if a - z putchar * * Return: 0 */ int main(void) { char ch = 97; while (ch >= 97 && ch <= 122) { if (ch != 101 && ch != 113) putchar(ch); ch++; } putchar('\n'); return (0); }
C
// // Function.h // Lab2 // // Created by Sorokin Dmytro on 4/7/16. // Copyright (C) 2016 Sorokin Dmytro. All rights reserved. // #ifndef FUNCTION_H_INCLUDED #define FUNCTION_H_INCLUDED typedef struct __IntNode IntNode; struct __IntNode { int value; IntNode *nextNode; }; IntNode *CreateN(int perevod); void FreeIntNode(IntNode *aNode); void selectionSort(IntNode *theList,int IndexMin,int IndexMax); int doFindIndexMax(IntNode *theList); int doFindIndexMin(IntNode *theList); void insertionSort(IntNode *theList, int count); #endif // FUNCTION_H_INCLUDED
C
#include"myheader25.h" struct node *root=NULL; void Search(int item, struct node **par, struct node **loc) { struct node *ptr,*ptrsave;//save parent of ptr *loc=NULL; if(NULL==root) /*tree empty*/ { *loc=NULL; *par=NULL; return ; } if(item==(root)->info) /*item is at root*/ { *loc=root; *par=NULL; return ; } /*Initialize ptr and ptrsave*/ if(item<(root->info)) { ptr=root->lchild; } else { ptr=root->rchild; } ptrsave=root; while(NULL!=ptr) { if(item==(ptr->info)) { *loc=ptr; *par=ptrsave; return ; } ptrsave=ptr; if(item<ptr->info) { ptr=ptr->lchild; } else { ptr=ptr->rchild; } } *loc=NULL; /*item not found*/ *par=ptrsave; } void insert(int item) { struct node *new, *parent, *location; Search(item,&parent,&location); if(NULL != location) { printf("Item already present"); return; } new = (struct node *)malloc(sizeof(struct node)); if(NULL==new) { printf("memory allocation failure!!"); return; } new->info = item; new->lchild = NULL; new->rchild = NULL; if(NULL == parent) { root=new; } else { if(item<parent->info) { parent->lchild=new; } else { parent->rchild=new; } } } //Deleting a node that has no children... void case_a(struct node *par, struct node *loc) { if(par==NULL) /*item to be deleted is root node*/ { root=NULL; } else if(loc==par->lchild) { par->lchild=NULL; } else { par->rchild=NULL; } } //Deleting a node with one child... void case_b(struct node *par, struct node *loc) { struct node *child=NULL; /*Initialize child*/ if(NULL!=(loc->lchild)) /*item to be deleted has lchild */ { child=loc->lchild; } else /*item to be deleted has rchild */ { child=loc->rchild; } if(NULL==par) /*Item to be deleted is root node*/ { root=child; } else { if(par->lchild==loc) /*item is lchild of its parent*/ { par->lchild=child; } else/*item is rchild of its parent*/ { par->rchild=child; } } } //Deleting a node with two child... void case_c(struct node *par, struct node *loc) { struct node *ptr,*suc,*parsuc,*ptrsave; /*Find inorder successor and its parent*/ ptrsave=loc; ptr=loc->rchild; while(NULL!=ptr->lchild) { ptrsave=ptr; ptr=ptr->lchild; } suc=ptr; parsuc=ptrsave; if(suc->lchild==NULL && suc->rchild==NULL) { case_a(parsuc,suc); } else { case_b(parsuc,suc); } if(NULL==par) /*if item to be deleted is root node */ { root=suc; } else if(loc==(par->lchild)) { par->lchild=suc; } else { par->rchild=suc; } suc->lchild=loc->lchild; suc->rchild=loc->rchild; } int del(int item) { struct node *parent,*location; if(root==NULL) { printf("Tree empty"); return 0; } Search(item,&parent,&location); if(NULL==location) { printf("Item not present in tree"); return 0; } if(NULL==(location->lchild) && NULL==(location->rchild)) { case_a(parent,location); } if(NULL!=(location->lchild) && NULL==(location->rchild)) { case_b(parent,location); } if(NULL==(location->lchild) && NULL!=(location->rchild)) { case_b(parent,location); } if(NULL!=(location->lchild) && NULL!=(location->rchild)) { case_c(parent,location); } free(location); } int preorder(struct node *ptr) { if(root==NULL) { printf("Tree is empty"); return 0; } if(ptr!=NULL) { printf("%d ",ptr->info); preorder(ptr->lchild); preorder(ptr->rchild); } } void inorder(struct node *ptr) { if(root==NULL) { printf("Tree is empty"); return; } if(ptr!=NULL) { inorder(ptr->lchild); printf("%d ",ptr->info); inorder(ptr->rchild); } } void postorder(struct node *ptr) { if(root==NULL) { printf("Tree is empty"); return; } if(ptr!=NULL) { postorder(ptr->lchild); postorder(ptr->rchild); printf("%d ",ptr->info); } } void display(struct node *ptr, int level) { int i; if ( ptr!=NULL ) { display(ptr->rchild, level+1); printf("\n"); for (i = 0; i < level; i++) printf(" "); printf("%d", ptr->info); display(ptr->lchild, level+1); } }
C
#include<stdio.h> #include<string.h> int main() { char name[3] = {'R','J', '\0'}; char str1[65], str2[98], str3[32]; strcpy(str1, "Kedar"); strcpy(str2, "Raj"); printf("%s\n",name); printf("%s\n",str1); printf("%s\n",str2); strcat(str1, str2); printf("%s\n", str1); // CASE-1 for strcmp strcpy(str1, "A"); strcpy(str2, "A"); printf("%s\n",str1); printf("%s\n",str2); printf("%d\n", strcmp(str1, str2)); // CASE-2 for strcmp strcpy(str1, "A"); strcpy(str2, "Z"); printf("%s\n",str1); printf("%s\n",str2); printf("%d\n", strcmp(str1, str2)); // CASE-3 for strcmp strcpy(str1, "Z"); strcpy(str2, "A"); printf("%s\n",str1); printf("%s\n",str2); printf("%d", strcmp(str1, str2)); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> int find(int n) { int sum = 0; int i = 0; int j = 0; int k = 0; int arr[200]; for (i = 0; i < 999; i++) { for (j = 2; j < i; j++) { if (i%j == 0) { break; } if (j == i - 1) { printf("%d ", i); arr[k] = i; k++; } } } printf("\n"); for (i = 0; i < n; i++) { sum += arr[i]; } return sum; } int main() { printf("%d", find(8));//0999ǰ߸ĺ system("pause"); return 0; }
C
#include <pty.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <errno.h> #include <math.h> #include <signal.h> #include <string.h> static void color(int depth, FILE *out1, FILE *out2) { static char *colors[] = { "\x1b[31m", "\x1b[32m", "\x1b[33m", "\x1b[34;1m", "\x1b[35m", "\x1b[36m", }; if (depth == 0) { fprintf(out1, "\x1b[39m"); fprintf(out2, "\x1b[39m"); } else { char *color = colors[depth % (sizeof(colors) / sizeof(*colors))]; fprintf(out1, "%s", color); fprintf(out2, "%s", color); } } static void process(char c, FILE *out1, FILE *out2) { static int depth = 0; static int prev_was_cr = 0; if (c == '\n') { color(depth = 0, out1, out2); putc(c, out1); // If the previous character was a cr, we already gave less // a newline. Don't give it another one. if (!prev_was_cr) putc(c, out2); } else if (c == '<') { color(++depth, out1, out2); putc(c, out1); putc(c, out2); } else if (c == '>' && depth > 0) { putc(c, out1); putc(c, out2); color(--depth, out1, out2); } else if (c == '\r') { putc(c, out1); // Less doesn't really handle carriage return well putc('\n', out2); } else { putc(c, out1); putc(c, out2); } if (c == '\r') prev_was_cr = 1; else prev_was_cr = 0; } int main(int argc, char *argv[]) { char *argv0 = argv[0]; int do_always_pager = 0; int do_color = 1; argc -= 1; argv += 1; while (argc > 0) { if (strcmp(*argv, "-y") == 0 || strcmp(*argv, "--always") == 0) { do_always_pager = 1; } else if (strcmp(*argv, "-n") == 0 || strcmp(*argv, "--no-color") == 0) { do_color = 0; } else if (strcmp(*argv, "--") == 0) { argv += 1; argc -= 1; break; } else if ((*argv)[0] != '-') { break; } argv += 1; argc -= 1; } if (argc == 0) { printf("Usage: %s [options] [--] <command...>\n", argv0); printf("Options:\n"); printf(" -y|--always: Always show the pager, even if the command didn't error\n"); printf(" -n|--no-color: Don't color code nesting\n"); return EXIT_FAILURE; } const char *pager = getenv("MSOAK_PAGER"); if (pager == NULL) pager = "less --RAW-CONTROL-CHARS"; FILE *output = stderr; FILE *outfile = tmpfile(); if (outfile == NULL) { perror("tmpfile()"); return EXIT_FAILURE; } int amaster; pid_t child = forkpty(&amaster, NULL, NULL, NULL); if (child < 0) { perror("forkpty()"); return EXIT_FAILURE; } if (child == 0) { // Child if (execvp(argv[0], argv) < 0) { perror("exec()"); return EXIT_FAILURE; } } char buf[1024]; while (1) { ssize_t len = read(amaster, buf, sizeof(buf)); if (len < 0) { if (errno == EIO) break; kill(child, SIGKILL); perror("read"); goto cleanup; } if (do_color) { for (ssize_t i = 0; i < len; ++i) process(buf[i], output, outfile); } else { fwrite(buf, 1, len, output); fwrite(buf, 1, len, outfile); } fflush(output); } int stat; cleanup: wait(&stat); int errored = (WIFEXITED(stat) && WEXITSTATUS(stat) != EXIT_SUCCESS) || WIFSIGNALED(stat); // Only show pager if we errored (or if --always was passed) if (errored || do_always_pager) { fflush(outfile); rewind(outfile); FILE *proc = popen(pager, "w"); while (1) { ssize_t len = fread(buf, 1, sizeof(buf), outfile); if (len < 0) { perror("read"); return EXIT_FAILURE; } else if (len == 0) { break; } fwrite(buf, 1, len, proc); } pclose(proc); wait(NULL); } if (WIFEXITED(stat)) return WEXITSTATUS(stat); else if (WIFSIGNALED(stat)) return WTERMSIG(stat) + 128; else return EXIT_FAILURE; }
C
#include <stdio.h> #include <stdlib.h> /* * */ //el el cuadrado, cubo, elevado a la cuarta y quinta. int main(int argc, char** argv) { int a; scanf("%d",&a); int b=2; while(b <= 5){ a = a * a; printf("%d \n",a); b=b+1; } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include "cJSON.h" #include "seniverse_weather.h" #include "seniverse_cJson_utils.h" #include "test_weather_location.h" /* API: https://api.seniverse.com/v3/weather/now.json?key=your_api_key&location=beijing&language=zh-Hans&unit=c 参数名 类型 默认值 必须 备注 key String 无 是 你的 API 密钥 location Location 无 是 所查询的位置 language Language zh-Hans 否 语言 unit Unit c 否 单位 返回结果: { "results": [ { "location": { "id": "C23NB62W20TF", "name": "西雅图", "country": "US", "path": "西雅图,华盛顿州,美国", "timezone": "America/Los_Angeles", "timezone_offset": "-07:00" }, "now": { "text": "多云", //天气现象文字 "code": "4", //天气现象代码 "temperature": "14", //温度,单位为c摄氏度或f华氏度 "feels_like": "14", //体感温度,单位为c摄氏度或f华氏度 "pressure": "1018", //气压,单位为mb百帕或in英寸 "humidity": "76", //相对湿度,0~100,单位为百分比 "visibility": "16.09", //能见度,单位为km公里或mi英里 "wind_direction": "西北", //风向文字 "wind_direction_degree": "340", //风向角度,范围0~360,0为正北,90为正东,180为正南,270为正西 "wind_speed": "8.05", //风速,单位为km/h公里每小时或mph英里每小时 "wind_scale": "2", //风力等级,请参考:http://baike.baidu.com/view/465076.htm "clouds": "90", //云量,单位%,范围0~100,天空被云覆盖的百分比 #目前不支持中国城市# "dew_point": "-12" //露点温度,请参考:http://baike.baidu.com/view/118348.htm #目前不支持中国城市# }, "last_update": "2015-09-25T22:45:00-07:00" //数据更新时间(该城市的本地时间) } ] } */ static const char *weather_now_example = "\ \r\n\r\n\ {\ \"results\": [\ {\ \"location\": {\ \"id\": \"C23NB62W20TF\",\ \"name\": \"西雅图\",\ \"country\": \"US\",\ \"path\": \"西雅图,华盛顿州,美国\",\ \"timezone\": \"America/Los_Angeles\",\ \"timezone_offset\": \"-07:00\"\ },\ \"now\": {\ \"text\": \"多云\",\ \"code\": \"4\",\ \"temperature\": \"14\",\ \"feels_like\": \"14\",\ \"pressure\": \"1018\",\ \"humidity\": \"76\",\ \"visibility\": \"16.09\",\ \"wind_direction\": \"西北\",\ \"wind_direction_degree\": \"340\",\ \"wind_speed\": \"8.05\",\ \"wind_scale\": \"2\",\ \"clouds\": \"90\",\ \"dew_point\": \"-12\"\ },\ \"last_update\": \"2015-09-25T22:45:00-07:00\"\ }\ ]\ }\ "; static const char *example_real = "\n\n{\"results\":[{\"location\":{\"id\":\"WX4FBXXFKE4F\",\"name\":\"北京\",\"country\":\"CN\",\"path\":\"北京,北京,中国\",\"timezone\":\"Asia/Shanghai\",\"timezone_offset\":\"+08:00\"},\"now\":{\"text\":\"多云\",\"code\":\"4\",\"temperature\":\"27\"},\"last_update\":\"2020-06-28T21:00:00+08:00\"}]}"; #define KEY "S-nc7Ea36Sthm8mGn" #define LOCATION "beijing" int test_weather_now() { struct seniverse_weather_obj *now = creat_weather_data(SENIVERSE_WEATHER_NOW, 1); int count = 0; char url[1024]; count = seniverse_get_url_api(SENIVERSE_WEATHER_NOW, url, 1024, KEY, LOCATION, SENIVERSE_LANGUAGE_CHINESE_SIMP, SENIVERSE_UNIT_METRIC, 0, 0); /* print the version */ printf("Version: %s\n", cJSON_Version()); printf("\n\n\n>>>>>>>weather now test.>>>>>>>>>>\n"); printf("get url %s, %d\n", url, count); seniverse_parse_resp(SENIVERSE_WEATHER_NOW, weather_now_example, now, &count); printf("weather now data has %d items.\n", count); dump_weather_now(&now->now); destroy_weather_data(now); now = NULL; return 0; }
C
char *ft_strcat(char *dest, char *src); #include <stdio.h> #include <string.h> int main() { char dest[20]= "coucou"; char src[50]= "les loulous"; printf("%s", ft_strcat(dest, src)); printf("\n"); char dest1[20]= "coucou"; char src1[50]= "les loulous"; printf("%s", strcat(dest1, src1)); return (0); }
C
// Author: Johnnie Alan #include "testStruct.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <time.h> int testFunc1(void); int testFunc2(void); int testFunc3(void); bool flag = false; void child_handler(int sig, siginfo_t *siginfo, void *context) { if(sig == SIGUSR1) { printf("Timeout, Cleaning up...\n"); flag = true; } } struct user_test_case aTestCase1[] = {/*"TESTCASE_1", 10000, "testFunc1", "TESTCASE_2",10000, "testFunc2", "TESTCASE_3", 5000, "testFunc3",*/ /*"TESTCASE_1", 10000, "testFunc1", "TESTCASE_2",10000, "testFunc2", "TESTCASE_3", 5000, "testFunc3", "TESTCASE_1", 10000, "testFunc1", "TESTCASE_2",10000, "testFunc2", "TESTCASE_3", 5000, "testFunc3", "TESTCASE_1", 10000, "testFunc1", "TESTCASE_2",10000, "testFunc2", "TESTCASE_3", 5000, "testFunc3",*/ TEST_CASE_END}; struct user_test_case aTestCase2[] = {"TESTCASE_1", 10000, "testFunc1", "TESTCASE_2",10000, "testFunc2", "TESTCASE_3", 5000, "testFunc3", /*"TESTCASE_1", 10000, "testFunc1", "TESTCASE_2",10000, "testFunc2", "TESTCASE_3", 5000, "testFunc3", "TESTCASE_1", 10000, "testFunc1", "TESTCASE_2",10000, "testFunc2", "TESTCASE_3", 5000, "testFunc3", "TESTCASE_1", 10000, "testFunc1", "TESTCASE_2",10000, "testFunc2", "TESTCASE_3", 5000, "testFunc3",*/ TEST_CASE_END}; struct user_test_suite aTestSuite[] = {"TESTSUIT_1", "cleanup", aTestCase1, "TESTSUIT_2", "cleanup", aTestCase2, TEST_SUITE_END}; int testFunc1(void) { printf("In test case 1\n"); sleep(5); return 1; } int testFunc2(void) { printf("In test case 20\n"); return 2; } int testFunc3(void) { struct sigaction act; memset(&act, '\0', sizeof(act)); act.sa_sigaction = child_handler; act.sa_flags = SA_SIGINFO; if (sigaction(SIGUSR1, &act, NULL) < 0) { perror("sigaction"); exit(1); } printf("In test case 3\n"); while(1){ if(flag == true) break; sleep(1); } flag = false; return 3; }
C
#include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <signal.h> #include "global.h" int crianovapos(struct artigo art){ char buffer[1024]; char BUFFER[1024]; int codigo; int fd1=open("strings.txt",O_CREAT|O_RDWR,0666); lseek(fd1,art.codigo-1,SEEK_SET); read(fd1,buffer,1024); int i=0; int fd2=open("strings2.txt",O_CREAT|O_RDWR,0666); read(fd1,buffer,sizeof(char)); while(buffer[i++]!='/') read(fd1,buffer,1); codigo=lseek(fd2,0,SEEK_END)+1 ;//atualiza o codigo do produto write(fd2,buffer,i*sizeof(char));//escreve o novo nome no strings lseek(fd2,0,SEEK_SET); close(fd2); close(fd1); return codigo; } //função para detetar se o "lixo" é 20% do ficheiro strings int vinteporcento(){ struct lixo lixo; int fd3=open("lixo.txt",O_CREAT|O_RDWR,0666); lseek(fd3,0,SEEK_SET); read(fd3,&lixo,sizeof(struct lixo)); if (lixo.total*0.2==lixo.lixo) return 1; close(fd3); return 0; } int main(){ if (vinteporcento()){ struct artigo art; int n; int count=0; int fd1=open("artigos.txt",O_CREAT|O_RDWR,0666); while((n=read(fd1,&art,sizeof(struct artigo)))>0){ //procura onde se encontra o codigo no artigos count+=n; art.codigo=crianovapos(art); lseek(fd1,count-sizeof(struct artigo),SEEK_SET); write(fd1,&art,sizeof(struct artigo)); } } unlink("strings.txt"); rename("strings2.txt","strings.txt"); return 0; }
C
#include "mem.h" void memory_copy(uint8_t *source, uint8_t *dest, int nbytes) { // this is good old memcpy int i; for (i = 0; i < nbytes; i++) { *(dest + i) = *(source + i); } }
C
#include <stdio.h> int fahr=0; float celcius; #define INFERIOR 0 #define SUPERIOR 300 #define PASSO 20 int main() { while (fahr <= SUPERIOR) { celcius= (5.0 / 9.0) * (fahr - 32 ); printf("%3d\t%6.2f\n",fahr,celcius); fahr=fahr + PASSO; } return 0; }
C
/* ** EPITECH PROJECT, 2020 ** my_printf ** File description: ** recreation of _printf_function */ #include <stdarg.h> #include <unistd.h> #include "my.h" void switch_casep1(char flag, va_list args) { switch (flag) { case 'd': my_put_nbr(va_arg(args, int)); break; case 's': my_putstr(va_arg(args, char *)); break; case 'S': my_showstr(va_arg(args, char *)); break; case 'c': my_putchar(va_arg(args, int)); break; case 'u': my_put_uint(va_arg(args, unsigned int)); break; case 'i': my_put_nbr(va_arg(args, int)); break; } } void switch_casep2(char flag, va_list args) { switch (flag) { case 'b': my_put_binary(va_arg(args, int)); break; case 'o': my_put_octal(va_arg(args, int)); break; case 'x': my_put_hexa(va_arg(args, int)); break; case 'X': my_put_uphexa(va_arg(args, int)); break; case 'p': my_put_ptr(va_arg(args, int)); break; case 'r': my_putrev(va_arg(args, char *)); break; } } void my_printf(char *s, ...) { va_list args; char *order = s; int n = my_strlen(s); va_start(args, s); for (int c = 0; c < n ; c++) { if (order[c] == '%') { c++; if (order[c] == '%') my_putchar('%'); switch_casep1(order[c], args); switch_casep2(order[c], args); } else my_putchar(order[c]); } va_end(args); return; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/wait.h> #include <sys/mman.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <semaphore.h> #define NUM_PROC 5 #define NUM_ELEM 200 int main(){ FILE *fp; pid_t p[NUM_PROC]; int i, j, c, estado; sem_t *sem[NUM_PROC]; //Semaphore & File Management fp = fopen("file.txt", "w+"); sem[0] = sem_open("semaforo", O_CREAT | O_EXCL, 0644, 1); sem[1] = sem_open("semaforo1", O_CREAT | O_EXCL, 0644, 0); sem[2] = sem_open("semaforo2", O_CREAT | O_EXCL, 0644, 0); sem[3] = sem_open("semaforo3", O_CREAT | O_EXCL, 0644, 0); sem[4] = sem_open("semaforo4", O_CREAT | O_EXCL, 0644, 0); for(i = 0; i < NUM_PROC; i++){ p[i] = fork(); if(p[i] == 0){ sem_wait(sem[i]); for( j = NUM_ELEM*i; j<NUM_ELEM*(i+1); j++){ fprintf(fp, "%d ", j); } fprintf(fp, "----\n"); if(i<4) sem_post(sem[i+1]); exit(0); } } for(i = 0; i < NUM_PROC; i++) waitpid(p[i], &estado, 0); fclose(fp); //Leitura do ficheiro fp = fopen("file.txt", "r"); while(1){ c = fgetc(fp); if(feof(fp)) break; //Sai do ciclo quando EOF printf("%c", c); } fclose(fp); //Semaphore Management if(sem_unlink("semaforo") != 0) printf("Error! >> sem_unlink \n"); if(sem_unlink("semaforo1") != 0) printf("Error! >> sem_unlink \n"); if(sem_unlink("semaforo2") != 0) printf("Error! >> sem_unlink \n"); if(sem_unlink("semaforo3") != 0) printf("Error! >> sem_unlink \n"); if(sem_unlink("semaforo4") != 0) printf("Error! >> sem_unlink \n"); return 0; }
C
#include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> static int ask(); extern void exit(); extern char *malloc(); extern void perror(); char first_on_queue[] = "-> first message on queue", full_buf[] = "Message buffer overflow. Extra message text\ discarded."; main() { register int c; /* message text input */ int choice; /* user's selected operation code */ register int i; /* loop control for mtext */ int msgflg; /* message flags for the operation */ struct msgbuf *msgp; /* pointer to the message buffer */ int msgsz; /* message size */ long msgtyp; /* desired message type */ int msqid, /* message queue ID to be used */ maxmsgsz, /* size of allocated message buffer */ rtrn; /* return value from msgrcv or msgsnd */ fprintf(stderr, "All numeric input is expected to follow C conventions:\n"); fprintf(stderr, "\t0x... is interpreted as hexadecimal,\n"); fprintf(stderr, "\t0... is interpreted as octal,\n"); fprintf(stderr, "\totherwise, decimal.\n"); /* Get the message queue ID and set up the message buffer. */ fprintf(stderr, "Enter msqid: "); scanf("%i", &msqid); /* * Note that <sys/msg.h> includes a definition of struct msgbuf * with the mtext field defined as: * char mtext[1]; * therefore, this definition is only a template, not a structure * definition that you can use directly, unless you want only to * send and receive messages of 0 or 1 byte. To handle this, * malloc an area big enough to contain the template - the size * of the mtext template field + the size of the mtext field * wanted. Then you can use the pointer returned by malloc as a * struct msgbuf with an mtext field of the size you want. Note * also that sizeof msgp->mtext is valid even though msgp isn't * pointing to anything yet. Sizeof doesn't dereference msgp, but * uses its type to figure out what you are asking about. */ fprintf(stderr, "Enter the message buffer size you want:"); scanf("%i", &maxmsgsz); if (maxmsgsz < 0) { fprintf(stderr, "msgop: %s\n", "The message buffer size must be >= 0."); exit(1); } msgp = (struct msgbuf *)malloc((unsigned)(sizeof(struct msgbuf)- sizeof msgp->mtext + maxmsgsz)); if (msgp == NULL) { fprintf(stderr, "msgop: %s %d byte messages.\n", "could not allocate message buffer for", maxmsgsz); exit(1); } /* Loop through message operations until the user is ready to quit. */ while (choice = ask()) { switch (choice) { case 1: /* msgsnd() requested: Get the arguments, make the call, and report the results. */ fprintf(stderr, "Valid msgsnd message %s\n", "types are positive integers."); fprintf(stderr, "Enter msgp->mtype: "); scanf("%li", &msgp->mtype); if (maxmsgsz) { /* Since you've been using scanf, you need the loop below to throw away the rest of the input on the line after the entered mtype before you start reading the mtext. */ while ((c = getchar()) != '\n' && c != EOF); fprintf(stderr, "Enter a %s:\n", "one line message"); for (i = 0; ((c = getchar()) != '\n'); i++) { if (i >= maxmsgsz) { fprintf(stderr, "\n%s\n", full_buf); while ((c = getchar()) != '\n'); break; } msgp->mtext[i] = c; } msgsz = i; } else msgsz = 0; fprintf(stderr,"\nMeaningful msgsnd flag is:\n"); fprintf(stderr, "\tIPC_NOWAIT =\t%#8.8o\n", IPC_NOWAIT); fprintf(stderr, "Enter msgflg: "); scanf("%i", &msgflg); fprintf(stderr, "%s(%d, msgp, %d, %#o)\n", "msgop: Calling msgsnd", msqid, msgsz, msgflg); fprintf(stderr, "msgp->mtype = %ld\n", msgp->mtype); fprintf(stderr, "msgp->mtext = \""); for (i = 0; i < msgsz; i++) fputc(msgp->mtext[i], stderr); fprintf(stderr, "\"\n"); rtrn = msgsnd(msqid, msgp, msgsz, msgflg); if (rtrn == -1) perror("msgop: msgsnd failed"); else fprintf(stderr, "msgop: msgsnd returned %d\n", rtrn); break; case 2: /* msgrcv() requested: Get the arguments, make the call, and report the results. */ for (msgsz = -1; msgsz < 0 || msgsz > maxmsgsz; scanf("%i", &msgsz)) fprintf(stderr, "%s (0 <= msgsz <= %d): ", "Enter msgsz", maxmsgsz); fprintf(stderr, "msgtyp meanings:\n"); fprintf(stderr, "\t 0 %s\n", first_on_queue); fprintf(stderr, "\t>0 %s of given type\n", first_on_queue); fprintf(stderr, "\t<0 %s with type <= |msgtyp|\n", first_on_queue); fprintf(stderr, "Enter msgtyp: "); scanf("%li", &msgtyp); fprintf(stderr, "Meaningful msgrcv flags are:\n"); fprintf(stderr, "\tMSG_NOERROR =\t%#8.8o\n", MSG_NOERROR); fprintf(stderr, "\tIPC_NOWAIT =\t%#8.8o\n", IPC_NOWAIT); fprintf(stderr, "Enter msgflg: "); scanf("%i", &msgflg); fprintf(stderr, "%s(%d, msgp, %d, %ld, %#o);\n", "msgop: Calling msgrcv", msqid, msgsz, msgtyp, msgflg); rtrn = msgrcv(msqid, msgp, msgsz, msgtyp, msgflg); if (rtrn == -1) perror("msgop: msgrcv failed"); else { fprintf(stderr, "msgop: %s %d\n", "msgrcv returned", rtrn); fprintf(stderr, "msgp->mtype = %ld\n", msgp->mtype); fprintf(stderr, "msgp->mtext is: \""); for (i = 0; i < rtrn; i++) fputc(msgp->mtext[i], stderr); fprintf(stderr, "\"\n"); } break; default: fprintf(stderr, "msgop: operation unknown\n"); break; } } exit(0); } static ask() { int response; /* User's response. */ do { fprintf(stderr, "Your options are:\n"); fprintf(stderr, "\tExit =\t0 or Control-D\n"); fprintf(stderr, "\tmsgsnd =\t1\n"); fprintf(stderr, "\tmsgrcv =\t2\n"); fprintf(stderr, "Enter your choice: "); /* Preset response so "^D" will be interpreted as exit. */ response = 0; scanf("%i", &response); } while (response < 0 || response > 2); return(response); }
C
/* * tests.c * * Created on: 20 oct. 2019 * Author: Manu Cabello */ #include "ejercicios/ejercicio1.h" #include "ejercicios/ejercicio2.h" #include "ejercicios/ejercicio3.h" #include "ejercicios/ejercicio4.h" #include "ejercicios/ejercicio5.h" int main(void) { // ejercicio1((char*) "ficheros/PI1Ej1DatosEntrada.txt"); ejercicio2((char*) "ficheros/PI1Ej2DatosEntrada.txt"); // TODO - Falta mostrar el resultado. // ejercicio3((char*) "ficheros/PI1Ej3DatosEntrada.txt"); // ejercicio4((char*) "ficheros/PI1Ej4DatosEntrada.txt"); // TODO - Falta completo // ejercicio5((char*) "ficheros/PI1Ej5DatosEntrada.txt"); }
C
/* * Démonstration 1: * Nous allons créer un programme qui crée deux processus fils. */ #include <sys/wait.h> #include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { printf("Hello from root process\n"); pid_t child1PID = fork(); if (child1PID == 0) { // Je suis le fils 1 printf("Hello from child 1\n"); exit(0); } pid_t child2PID = fork(); if (child2PID == 0) { // Je suis le fils 2 printf("Hello from child 2\n"); exit(0); } while (wait(NULL) > 0); return 0; }
C
#include <stdio.h> int main(void) { int x, first, second, third, fourth, fifth; printf("Enter value of x: "); scanf("%d", &x); first = 3 * x * x * x * x * x; second = 2 * x * x * x * x; third = 5 * x * x * x; fourth = x * x; fifth = 7 * x; printf("Polynomial resut: %d\n", first + second - third - fourth + fifth - 6); return 0; }
C
/** * comnpilar con: gcc p2.c -lproj */ #include <stdio.h> #include <proj.h> int main (void) { PJ_CONTEXT *C; PJ *P; PJ* P_for_GIS; PJ_COORD a, b; /* or you may set C=PJ_DEFAULT_CTX if you are sure you will */ /* use PJ objects from only one thread */ C = proj_context_create(); P = proj_create_crs_to_crs (C, "EPSG:6372", "EPSG:4326", NULL); if (0==P) { fprintf(stderr, "Oops\n"); return 1; } /* This will ensure that the order of coordinates for the input CRS */ /* will be longitude, latitude, whereas EPSG:4326 mandates latitude, */ /* longitude */ P_for_GIS = proj_normalize_for_visualization(C, P); if( 0 == P_for_GIS ) { fprintf(stderr, "Oops\n"); return 1; } proj_destroy(P); P = P_for_GIS; /*2470517.824300,1155028.588300*/ a = proj_coord (2470517.824300, 1155028.588300, 0, 0); /* transform to UTM zone 32, then back to geographical */ b = proj_trans (P, PJ_FWD, a); printf ("longitud: %.6f, latitud: %.6f\n", b.lp.lam, b.lp.phi); b = proj_trans (P, PJ_INV, b); printf ("Este: %.6f, Norte: %.6f\n", b.enu.e, b.enu.n); /* Clean up */ proj_destroy (P); proj_context_destroy (C); /* may be omitted in the single threaded case */ return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "hash_table.h" #define HASH_OFFSET 0 #define HASH_A 1 #define HASH_B 2 ///HASH table node typedef struct hashtable { unsigned int hash_val_a; unsigned int hash_val_b; int exists; int key_len; void *value; } hashtable_t; ///HASH table static hashtable_t *hashtable = NULL; ///Hash Seeds static unsigned int refer_table[0x500] = { 0 }; ///the current length of the HASH table static unsigned int hashtable_cur_len = 0; ///the increased length of the HASH table static unsigned int hashtable_inc_len = 0; void init_refer_table(void) { unsigned int seed = 1, index1 = 0, index2 = 0, i; unsigned int temp1, temp2; for( index1 = 0; index1 < 0x100; index1++ ) { for( index2 = index1, i = 0; i < 5; i++, index2 += 0x100 ) { seed = (seed * 125 + 3) % 0xAAAB; temp1 = (seed & 0xFF) << 0x04; seed = (seed * 125 + 3) % 0xAAAB; temp2 = (seed & 0xFF); refer_table[index2] = ( temp1 + temp2 ); } } } int hash_alloc() { unsigned int index = 0; hashtable_t * new_hashtable = NULL; new_hashtable = (hashtable_t *)realloc(hashtable, sizeof(hashtable_t) * (hashtable_cur_len + hashtable_inc_len)); if (new_hashtable == NULL) return -1; hashtable = new_hashtable; for (index=hashtable_cur_len; index<hashtable_cur_len+hashtable_inc_len; index++) { hashtable[index].hash_val_a = -1; hashtable[index].hash_val_b = -1; hashtable[index].exists = 0; hashtable[index].key_len =0; hashtable[index].value = NULL; } hashtable_cur_len += hashtable_inc_len; return 0; } int hash_create( unsigned int table_len ) { int ret = 0; hashtable = NULL; hashtable_cur_len = 0; hashtable_inc_len = table_len; ret = hash_alloc(); if(ret != 0) return -1; init_refer_table(); return 0; } unsigned int hash_charset(unsigned char *charset, int charset_len, int hash_type) { unsigned char *key = charset; unsigned int seed1 = 0x7FED, seed2 = 0xEEEE; unsigned int ch; while(charset_len) { ch = (*key++); seed1 = refer_table[(hash_type << 4) + ch] ^ (seed1 + seed2); seed2 = ch + seed1 + seed2 + (seed2 << 2) + 3; charset_len--; } return seed1; } int get_add_hash_pos(unsigned int hash_start, unsigned int hash_val_a,unsigned int hash_val_b) { unsigned int hash_pos = hash_start; while (hashtable[hash_pos].exists) { if (hashtable[hash_pos].hash_val_a == hash_val_a && hashtable[hash_pos].hash_val_b == hash_val_b) break; hash_pos = (hash_pos + 1) % hashtable_cur_len; if(hash_pos == hash_start) return -1; } return hash_pos; } int hash_add( unsigned char *key, int key_len, void *value ) { unsigned int hash_val, hash_val_a, hash_val_b; unsigned int hash_start; unsigned int hash_pos; hash_val = hash_charset(key, key_len, HASH_OFFSET); hash_val_a = hash_charset(key, key_len, HASH_A); hash_val_b = hash_charset(key, key_len, HASH_B); hash_start = hash_val % hashtable_cur_len; //if the buf is full, realloc hash_pos = get_add_hash_pos(hash_start,hash_val_a,hash_val_b); if(hash_pos == -1) { if(hash_alloc() == 0) hash_pos = get_add_hash_pos(hash_start,hash_val_a,hash_val_b); if (hash_pos == -1) return -1; } hashtable[hash_pos].hash_val_a = hash_val_a; hashtable[hash_pos].hash_val_b = hash_val_b; hashtable[hash_pos].exists = 1; hashtable[hash_pos].key_len = key_len; hashtable[hash_pos].value = value; return 0; } int hash_get_charset_pos( unsigned char *charset, int charset_len ) { unsigned int hash_val, hash_val_a, hash_val_b; unsigned int hash_start; unsigned int hash_pos; hash_val = hash_charset(charset, charset_len, HASH_OFFSET); hash_val_a = hash_charset(charset, charset_len, HASH_A); hash_val_b = hash_charset(charset, charset_len, HASH_B); hash_start = hash_val % hashtable_cur_len; hash_pos = hash_start; while ( hashtable[hash_pos].exists) { if (hashtable[hash_pos].hash_val_a == hash_val_a && hashtable[hash_pos].hash_val_b == hash_val_b) return hash_pos; else hash_pos = (hash_pos + 1) % hashtable_cur_len; if (hash_pos == hash_start) break; } return -1; } void * hash_search( unsigned char *key, int key_len ) { unsigned int hash_pos; hash_pos = hash_get_charset_pos( key, key_len ); if ( hash_pos == -1 ) return NULL; return hashtable[hash_pos].value; } int hash_del( unsigned char *key, int key_len ) { unsigned int hash_pos; hash_pos = hash_get_charset_pos(key, key_len); if(hash_pos == -1) return -1; hashtable[hash_pos].hash_val_a = -1; hashtable[hash_pos].hash_val_a = -1; hashtable[hash_pos].exists = 0; hashtable[hash_pos].key_len = 0; hashtable[hash_pos].value = NULL; return 0; } void hash_destroy( hash_ex_func free_data ) { unsigned int i = 0; if(hashtable != NULL) { for( i=0; i< hashtable_cur_len; i++ ) { if( NULL != hashtable[i].value ) { if( (NULL!=free_data)&&(NULL!=hashtable[i].value) ) free_data( hashtable[i].value ); hashtable[i].value = NULL; } } free(hashtable); hashtable = NULL; } } int hash_visit( hash_ex_func_ex set_flags, void *pflags ) { unsigned int i = 0; if( NULL == hashtable ) return -1; for( i=0; i< hashtable_cur_len; i++ ) { if( (NULL!=hashtable[i].value)&&(NULL!=pflags) ) { set_flags( hashtable[i].value, pflags ); } } return 0; }
C
#include<stdio.h> #include <math.h> main(){ double A,raio, pi; pi = 3.14159; //printf("digite o raio\n"); scanf("%lf", &raio); A= pow(raio,2)*pi; printf("A=%2.lf\n", A); }
C
#include "rtv1.h" void ft_pvect(char *str, t_vect v) { printf("%s %f %f %f\n", str, v.x, v.y, v.z); } t_vect ft_rot_x(t_vect v, double a) { t_vect v1; v1.x = v.x; v1.y = cos(a) * v.y - sin(a) * v.z; v1.z = sin(a) * v.y + cos(a) * v.z; return v1; } t_vect ft_rot_y(t_vect v, double a) { t_vect v1; v1.x = v.x * cos(a) + sin(a) * v.z; v1.y = v.y; v1.z = -sin(a) * v.x + cos(a) * v.z; return v1; } t_vect ft_rot_z(t_vect v, double a) { t_vect v1; v1.x = v.x * cos(a) - sin(a) * v.y; v1.y = sin(a) * v.x + cos(a) * v.y; v1.z = v.z; return v1; } double ft_rad(double a) { return (a * M_PI / 180); } t_vect ft_rot(t_vect v, t_vect rot) { t_vect v1; //ft_pvect("v: ", v); v1 = ft_rot_x(v, ft_rad(rot.x)); v1 = ft_rot_y(v1, ft_rad(rot.y)); v1 = ft_rot_z(v1, ft_rad(rot.z)); return v1; } t_ray ft_rot_obj(t_obj obj, t_ray ray) { t_vect dir; t_vect pos; pos = ft_vec_sub(ray.pos, obj.pos); pos = ft_rot(pos, ft_vec_multr(obj.rot, -1)); pos = ft_vec_sum(pos, obj.pos); dir = ft_rot(ray.dir, ft_vec_multr(obj.rot, -1)); ray.pos = pos; ray.dir = dir; return ray; }
C
//======================================================================== // merge-sort.c //======================================================================== // Implementation of the merge sort function // //--------------------!!! IMPORTANT NOTE !!!------------------------------ // // You need to use ece2400_malloc and ece2400_free in your implementation // in order to get memory usage for eval! // //------------------------------------------------------------------------ // #include <stdio.h> #include "merge-sort.h" #include "ece2400-stdlib.h" //------------------------------------------------------------------------ // merge //------------------------------------------------------------------------ // Helper function that merges two sorted arrays. void merge( int* dst, int* src0, size_t begin0, size_t end0, int* src1, size_t begin1, size_t end1 ) { unsigned int size = (end0 - begin0) + (end1 - begin1); unsigned int idx0 = begin0; unsigned int idx1 = begin1; for ( unsigned int i = 0; i < size; i++ ) { // src0 is done if ( idx0 == end0 ) { dst[i] = src1[idx1]; idx1 += 1; } // src1 is done else if ( idx1 == end1 ) { dst[i] = src0[idx0]; idx0 += 1; } // scr0 < src1 else if ( src0[idx0] < src1[idx1] ) { dst[i] = src0[idx0]; idx0 += 1; } // src1 < src0 else { dst[i] = src1[idx1]; idx1 += 1; } } } //------------------------------------------------------------------------ // merge_sort //------------------------------------------------------------------------ // Sorts the array with merge sort. void merge_sort( int* arr, size_t size ) { // base case if ( size <= 1 ) { return; } size_t size_h1 = size / 2; size_t size_h2 = size - size_h1; int* arr1 = ece2400_malloc( size_h1 * sizeof(int) ); int* arr2 = ece2400_malloc( size_h2 * sizeof(int) ); // split the array into two arrays for ( unsigned int i = 0; i < size_h1; i++ ) { arr1[i] = arr[i]; } for ( unsigned int i = 0; i < size_h2; i++ ) { arr2[i] = arr[i + size_h1]; } // partitions the arrays merge_sort( arr1, size_h1 ); merge_sort( arr2, size_h2 ); // merges the individual partitions int* temp = ece2400_malloc( size * sizeof(int)); merge( temp, arr1, 0, size_h1, arr2, 0, size_h2 ); // copy temp array to input array unsigned int j = 0; for ( unsigned int i = 0; i < size; i++ ) { arr[i] = temp[j]; j += 1; } ece2400_free(arr1); ece2400_free(arr2); ece2400_free(temp); }
C
//Author:- Amit Kumar #include<stdio.h> struct test { char a; char b; int i; char c; char d; }__attribute__((packed)) test1; int main() { printf("%lu",sizeof(test1)); }
C
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> //main() //{ // int i, j, n, m; // int a[16] = { 0 }; // int clrscr(); // printf("֣0~32767\n"); // scanf("%d\n", &n); // for (m = 0; m < 15; m++) // { // i = n % 2; // j = n / 2; // n = j; // a[m] = i; // break; // } // // for (m = 15; m >= 0; m--) // { // printf("%d", a[m]); // if (m % 4 == 0) // printf(""); // } //} //int main() //{ // int a = 0; // int b = ~a; // printf("%d\n", b); // return 0; //} int main() { int a = 3; int b = 5; int max = 0; max = (a >b ? a : b); printf("%d\n", max); return 0; }
C
#include<stdio.h> #include "common.h" void test_delete_link_node(); int main() { test_delete_link_node(); } typedef struct LNode LNode; struct LNode{ int value; LNode* next; LNode(int val,LNode* next):value(val),next(next){} }; void print_lnode(const LNode* head) { while(NULL != head){ printf("%d \n",head->value); head = head->next; } } bool compare(int m){ return m == 2; } typedef bool (*PCompare)(int m); void delete_link_node_old(LNode* head, PCompare pfun) { //assert(head) LNode* prev = head; LNode* cur = head->next; if (pfun(prev->value)){ //not *pfun(prev->value) if (NULL == cur) head = NULL; else head = cur; return; } while(NULL != cur){ printf("in: %d \n",cur->value); if (pfun(cur->value)){ prev->next = cur->next; printf("hit: %d prev value:%d next:%d\n",cur->value,prev->value,prev->next->value); } prev = prev->next; cur = cur->next; } } void delete_link_node_new(LNode** head, PCompare pfun) {//change the *pt LNode** cur = head; while(*cur != NULL){ if (pfun( (*cur)->value )){ //delete *cur *cur = (*cur)->next; } cur = &((*cur)->next); } } /* * refer to http://coolshell.cn/articles/8990.html */ void delete_link_node_by_LinusTorvalds(LNode** head, PCompare pfun) {//change the *pt for (LNode **curr=head; *curr; ){ LNode *entry = *curr; if (pfun(entry->value)){ *curr = entry->next; //free entry } else curr = &entry->next; } } void test_delete_link_node() { ENTER_TEST(); //prepare LNode n3(3,NULL); LNode n2(2,&n3); LNode n1(1,&n2); LNode head(0,&n1); print_lnode(&head); delete_link_node_old(&head, compare); print_lnode(&head); printf("Ready for LinusTorvalds's method... ...\n"); LNode n30(3,NULL); LNode n20(2,&n30); LNode n10(1,&n20); LNode head0(0,&n10); print_lnode(&head0); LNode *ht = &head0; LNode **pt = &ht; printf("try LinusTorvalds's method... ...\n"); delete_link_node_by_LinusTorvalds(pt, compare); //delete_link_node_new(&(&head0), compare);//error: lvalue required as unary & operand print_lnode(&head0); }
C
/************************************************************************* > File Name: GetNumOfKey.c > Author: cyf > Mail: 1097189275@qq.com > Created Time: 2016年03月24日 星期四 09时23分12秒 ************************************************************************/ #include "GetNumOfKey.h" /* * 得到数组中第一个查找的数字的下标 * */ int GetFirstKey(int *data, int length, int k, int start, int end) { if(start > end) return -1; int middle = (start+end)>>1; int middledata = data[middle]; if(middledata == k) { if((middle>0 && (data[middle-1]!=k)) || (middle == 0)) return middle; else end = middle-1; } else if(middledata < k) start = middle+1; else end = middle-1; return GetFirstKey(data, length, k, start, end); } /* * 得到数组中最后一个查找的数字的下标 * */ int GetLastKey(int *data, int length, int k, int start, int end) { if(start > end) return -1; int middle = (start + end)>>1; int middledata = data[middle]; if(middledata == k) { if(((middle < length-1)&&(data[middle+1]!=k))||(middle == length-1)) return middle; else start = middle+1; } else if(middledata < k) start = middle+1; else end = middle-1; return GetLastKey(data, length, k, start, end); } /* * 得到数组中要查找数字的个数 * */ int GetNumOfKey(int *data, int length, int k) { int number = 0; if(data!=NULL && length >0) { int first = GetFirstKey(data, length, k, 0, length-1); int last = GetLastKey(data, length, k, 0, length-1); if(first > -1 && last > -1) number = last-first+1; } return number; }
C
/* ** main.c for emacs in /home/jules/CPE/CPE_2016_BSQ ** ** Made by Jules Spender ** Login <jules.spender@epitech.eu@epitech.net> ** ** Started on Thu Dec 8 15:04:25 2016 Jules Spender ** Last update Sun Dec 18 19:45:56 2016 Jules Spender */ #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include "include/my.h" int my_error(int argc, char **argv) { int i; i = 0; if (argc < 2 || argc > 2) { write(2, "Error in Number of Argument.", 28); return (84); } i = open(argv[1], O_RDONLY); if (i == -1) { write(2, "Error, wrong arguments", 22); return (84); } close (i); return (0); } int my_atoi(char *str) { int i; int negative; int number; i = 0; negative = 0; number = 0; if (str[i] == 45) negative = 1; if ((str[i] == 45) || (str[i] == 43)) i++; while (str[i] >= 48 && str[i] <= 57) { number *= 10; number += ((int)str[i] - 48); i++; } if (negative == 1) return (-number); else return (number); } int my_square(char *str, int column_number, int place_number) { int square_side; int map_vertical_size; int map_horizontal_size; square_side = 1; map_vertical_size = 0; map_horizontal_size = 0; map_vertical_size = vertical_size(str); map_horizontal_size = horizontal_size(only_map(str)); str_to_array(only_map(str), map_vertical_size, map_horizontal_size); return (0); } int my_strlen(char *str) { int i; i = 0; while (str[i] != '\0') i = i + 1; return (i); } int main(int argc, char **argv) { int i; int a; struct stat s; if (stat(argv[1], &s) != 0) { write(2, "Error", 5); return (84); } a = s.st_size; i = my_error(argc, argv); if (i == 84) return (84); my_map_to_str(argv, 0, a); return (0); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "mainVersionFinale.h" #define MAX_PERSONNE 200 #define MAX_ID 200 #define GRAND_TAB 100 //seulement 2 donc on s'arrete à 6 #define GENERATION 6 int main(){ person Test[MAX_PERSONNE+1]; //Affectaction et ouverture du fichier FILE *fic= fopen("200.csv","r"); signed char texte[256]; signed char tmp[256]; int i,k; //Si la lecture du fichier echoue, le programme quit automatiquement. if(fic == NULL) exit(1); //variables de passage int a,b,c; char name[20]; char lname[20]; char birth[20]; char birthzip[20]; signed char stockage[255]; int tab_ancetre[GENERATION]; i=0; // variable de la fonction bortherhood : int id; //Boucle pour parcourir le fichier csv while(fgets(texte,255, fic) != NULL){ strcpy(stockage, texte); //printf("%s\n", stockage); // Passage sur des variables pour la lisibilité a=atoi(strtok(stockage,",")); b=atoi(strtok(NULL, ",")); c=atoi(strtok(NULL,",")); strcpy(name, strtok(NULL,",")); strcpy(lname, strtok(NULL,"," )); strcpy(birth, strtok(NULL,",")); strcpy(birthzip, strtok(NULL," ")); //printf("%d,%d,%d,%s %s,%s,%s\n", a, b,c, name, lname, birth, birthzip); //Affectaction des variables précèdentes sur le tableau de struct. Test[i].id=a; Test[i].father_id=b; Test[i].mother_id=c; strcpy(Test[i].firstname, name); strcpy(Test[i].lastname, lname); strcpy(Test[i].birthzipcode, birthzip); strcpy(Test[i].birthdate, birth); //suivre le parcour de la boucle //verification si les Affectaction ont bien eu lieu. /*printf("%d,%d,%d,%s,%s,%s,%s\n", Test[i].id, Test[i].father_id,Test[i].mother_id, Test[i].firstname, Test[i].lastname, Test[i].birthdate, Test[i].birthzipcode);*/ i++; } int Tab_Longueur = i; //lier la populations link_populations(Test, Tab_Longueur); int Id_Person_choix; int Id_Pere, Id_Mere; int choix; printf("\nBonjour, choissisez une action.\n\n"); printf(" 1:Parcourir la liste \n 2:afficher les informations de la personne. \n 3:Connaitre les freres de la personne.\n 4:Connaitre les parents de la personne.\n 5:Afficher tout l arbre généalogique de la personne.\n 6:Voir le rendu sur un site internet. \n 0:Qutter le programme.\n"); //verification scanf("%d",&choix); /*printf("%d",choix);*/ if(choix < 0 || choix > 6){ printf("Choix indisponible\n"); return 1; } switch(choix){ case(0): return 0; case(1): //parcours du tableau de structure for(k =0; k <=MAX_PERSONNE; k++){ printf("%d,%d,%d,%s,%s,%s,%s\n", Test[k].id, Test[k].father_id,Test[k].mother_id, Test[k].firstname, Test[k].lastname, Test[k].birthdate, Test[k].birthzipcode); } break; case(2): printf("\nEntrez l'id de la personne :\n"); scanf("%d", &Id_Person_choix); //conditions cas d'erreur if(Id_Person_choix < -1 || Id_Person_choix >MAX_PERSONNE-1 || Id_Person_choix==0){ printf("Données limitées de 1 à %d\n", MAX_PERSONNE-1); return 1; } printf("\n"); print_ID(Test, Id_Person_choix); break; case(3): printf("\nChoisissez l'id de l'individu :\n"); scanf("%d", &id); if(id < -1 || id > MAX_PERSONNE || id == 0){ printf("\nDonnées limitées de 1 à %d\n", MAX_PERSONNE); return 1; } brotherhood(Test, id); break; case(4): printf("\nEntrez l'id de la personne\n"); scanf("%d", &Id_Person_choix); //conditions cas d'erreur if(Id_Person_choix < -1 || Id_Person_choix >MAX_PERSONNE || Id_Person_choix==0){ printf("Données limitées de 1 à %d\n", MAX_PERSONNE); return 1; } Id_Pere = Test[Id_Person_choix].father_id; Id_Mere = Test[Id_Person_choix].mother_id; printf("\ninformations sur le père :\n"); print_ID(Test, Id_Pere); printf("informations sur la mère :\n"); print_ID(Test, Id_Mere); break; case(5): printf("\nEntrez l'id de la personne\n"); scanf("%d", &Id_Person_choix); //conditions cas d'erreur if(Id_Person_choix < -1 || Id_Person_choix >MAX_PERSONNE || Id_Person_choix==0){ printf("Données limitées de 1 à %d\n", MAX_PERSONNE); return 1; } printf("\n\n=======Individu=======\n\n"); printf("Nom de la personne : %s %s\nid : %d\t", Test[Id_Person_choix].firstname, Test[Id_Person_choix].lastname, Test[Id_Person_choix].id); ancetre(Test, tab_ancetre, Test[Id_Person_choix].id); printf("\n\n=======Parents========\n\n"); print_court(Test, tab_ancetre[2]); printf("\n"); print_court(Test, tab_ancetre[1]); printf("\n====Grand-parents=====\n\n"); printf("Paternels :\n\n"); // grand-parents paternelle print_court(Test,tab_ancetre[3]); print_court(Test,tab_ancetre[4]); printf("Maternels :\n\n"); // grand-parents maternelle print_court(Test,tab_ancetre[5]); print_court(Test,tab_ancetre[6]); break; case(6): break; } fclose(fic); return 0; } //fonctions pour lier les parents. void link_populations(struct Person *Tab, int Longueur){ int j; int idP; int idM; //Boucle for pour parcourir le tableau, conditions if, else if et else pour chaque cas. for(int j = 1; j < Longueur; j++){ // tab[0] est le prototype de la structure des données. On commence à 1. if( Tab[j].mother_id > Longueur || Tab[j].father_id > Longueur){// Tab[j].p_father = &(Tab[j]); Tab[j].p_mother = &(Tab[j]); }else if( Tab[j].mother_id == 0){ Tab[j].p_mother = &(Tab[j]); }else if( Tab[j].father_id == 0){ Tab[j].p_father = &(Tab[j]); }else{ idM=Tab[j].mother_id; idP=Tab[j].father_id; Tab[j].p_mother = &(Tab[idM]); Tab[j].p_father = &(Tab[idP]); } } } void ancetre(struct Person *Tab_Struct, int *Tab_Anc, int Id_Person){ int i =0; int indicePere = 2*i +1; int indiceMere = 2*i +2; Tab_Anc[i] = Tab_Struct[Id_Person].id; //pere Tab_Anc[indicePere] =Tab_Struct[Id_Person].father_id; //mere Tab_Anc[indiceMere]= Tab_Struct[Id_Person].mother_id; //Grand-Parents Maternels //grand mere Tab_Anc[2*indiceMere +2] = Tab_Struct[Tab_Anc[indiceMere]].mother_id; //grand pere Tab_Anc[2*indiceMere +1] = Tab_Struct[Tab_Anc[indicePere]].father_id; //Grand-Parents Paternels //grande mere Tab_Anc[2*indiceMere +2] = Tab_Struct[Tab_Anc[indicePere]].mother_id; //grand pere Tab_Anc[2*indicePere +1]= Tab_Struct[Tab_Anc[indicePere]].father_id; } //fonction qui permet d'afficher les informations d'une personne void print_ID(struct Person *Tab, int Id_Person){ if(Tab[Id_Person].id == 0 || Tab[Id_Person].id == MAX_PERSONNE || Tab[Id_Person].id < 0){ printf("Individu inconnu\n\n"); }else{ printf(" Id: %d \n Id du Père : %d \n id de la mère : %d \n Prenom : %s\n Nom : %s\n Jour de Naissance : %s\n Ville de Naissance : %s\n", Tab[Id_Person].id, Tab[Id_Person].father_id, Tab[Id_Person].mother_id, Tab[Id_Person].firstname, Tab[Id_Person].lastname, Tab[Id_Person].birthdate, Tab[Id_Person].birthzipcode); } } person ** brotherhood(struct Person *Tab, int id){ int nb_freres = 0; int i; int tab_provisoire[GRAND_TAB]; // parcours liste for(i = 0; i <= MAX_ID; i++){ //si aucun parent n'est inconnu if(Tab[i].father_id != 0 || Tab[i].mother_id != 0){ // si le père et la mère sont les mêmes, et que la personne n'est pas comparée à elle-même alors ... if(Tab[id].father_id == Tab[i].father_id && Tab[id].mother_id == Tab[i].mother_id && id != Tab[i].id){ //on place les id dans un tableau provisoire en attendant de connaitre le nombre de frères tab_provisoire[nb_freres] = Tab[i].id; nb_freres++; // compte le nombre de frères } } } printf("\nL'individu a %d frère(s)/soeur(s)\n\n", nb_freres); // création du tableau de la taille du nombre de frères int *tab; tab = malloc(nb_freres * sizeof(int)); for(int j=0; j < nb_freres; j++){ // on remplace le tableau provisoire par un plus petit tab[j] = tab_provisoire[j]; printf("id du frère/soeur numéro %d : %d\n", j+1, tab[j]); } return tab; } // version court de print_ID seulement id et le nom entier void print_court(struct Person *Tab, int Id_Person){ if(Tab[Id_Person].id == 0 || Tab[Id_Person].id == MAX_PERSONNE || Tab[Id_Person].id < 0){ printf("Individu inconnu\n\n"); }else{ printf("Prenom : %s\nNom : %s\nId : %d\n", Tab[Id_Person].firstname, Tab[Id_Person].lastname, Tab[Id_Person].id); } }
C
#include <stdio.h> int main() { int num1, num2, num3; float d; printf("\nDigite o primeiro numero: "); scanf("%d", &num1); printf("\nDigite o segundo numero: "); scanf("%d", &num2); printf("\nDigite o terceiro numero: "); scanf("%d", &num3); d = ((num1 * num1 + num2 * num2) + (num2 * num2 + num3 * num3))/ 2; printf("\n O resultado da expressao e: %.2f", d); return 0; }
C
#include <stdio.h> #include <stdlib.h> // プロトタイプ宣言 void swap(int *x, int *y); int main(int argc, char *argv[]) { int a,b; // 引数の数を検査 if(argc != 3) { printf("Usage : %s <number1> <number2>¥n", argv[0]); return 0; } a = atoi(argv[1]); b = atoi(argv[2]); // 値ではなく、値のあるアドレスを渡す swap(&a, &b); printf("%d %d¥n", a, b); return 0; } /** * x, yの値を入れ替える。 * 呼び出し元の変数の値を直接書き換えたい場合、ポインタを利用することで、呼び出し元の情報を直接書き換えられる * @param *x 数字のポインタ * @param *y 数字のポインタ */ void swap(int *x, int *y) { int tmp; tmp = *x; *x = *y; *y = tmp; }
C
/* Small C program that uses a function in another file. Intended as part of an example of how to use Makefiles. Jim Teresco, Williams College, The College of Saint Rose, Siena College */ #include <stdio.h> /* for printf */ #include <stdlib.h> /* for atoi */ #include "sub.h" /* for our function */ int main(int argc, char *argv[]) { int value, newvalue; value=atoi(argv[1]); newvalue=sub(value); printf("sub(%d)=%d\n",value,newvalue); return 0; }
C
#include <stdio.h> int main() { int x = 2, y, z; x *= 3 + 2; printf("\nx = %d", x); x *= y = z = 4; printf("\nx = %d", x); x = y == z; printf("\nx = %d", x); x == (y = z); printf("\nx = %d", x); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <time.h> /* * Implementace jednoduche hadaci hry. * Author: Jakub Kulik */ /* Definovane konstanty pro nabarveni textu terminalu. */ #define RED "\x1b[31m" #define GREEN "\x1b[32m" #define YELLOW "\x1b[33m" #define BLUE "\x1b[34m" #define MAGENTA "\x1b[35m" #define CYAN "\x1b[36m" #define RESET "\x1b[0m" /* * Hadaci hra, ve ktere se nahodne vygeneruje cislo v intervalu <1,100> a hrac * ho pote musi najit hadanim. Program je navic obohacen o barvy, takze to pekne vypada ^^. */ void guessing_game() { int target, guess; srand(time(NULL)); target = rand() % 100 + 1; printf(GREEN "Nahodne cislo je v intervalu <1,100> \n" RESET); while (1) { printf(GREEN "Zadejte hadane cislo: " RESET); if (scanf("%d", &guess) != 1) { printf("Spatny vstup - learn your numbers\n"); return; } if (guess > target) { printf(CYAN "Hledane cislo je mensi.\n" RESET); } else if (guess < target) { printf(CYAN "Hledane cislo je vetsi.\n" RESET); } else { printf(GREEN "Toto je hledane cislo. Gratuluji.\n" RESET); break; } } } /* main function */ int main(int argc, char **argv) { while (1) guessing_game(); return EXIT_SUCCESS; }
C
//preprocessor directive #pragma once //this is a macro that replaces ITERATE_NODES with code inside for loop //this is also a variadic function - a function that takes variable arguments //required arguments are START, NAME, END. Elipses (...) indicate variable args #define ITERATE_NODES(START, NAME, END, ...) \ { \ for (int64_t NAME = START; NAME < END; NAME++) { \ __VA_ARGS__; \ } \ } //this is a macro that replaces ITERATE_NEIGHBORS with code inside for loop #define ITERATE_NEIGHBORS(NODE, NAME, ROW, COL, ...) \ { \ for (int64_t NAME##_i = ROW[NODE]; NAME##_i < ROW[NODE + 1]; NAME##_i++) { \ auto NAME = COL[NAME##_i]; \ __VA_ARGS__; \ } \ }
C
/* Alloc测试程序 1. Alloc申请测试 2. Free空洞测试 3. 首次适应算法测试 */ #include"types.h" #include"stat.h" #include"user.h" #define KB (1024) #define ALLOC_NUM 6 char buf[100]; void Block(const char* msg){ printf(0, (char*)msg); gets(buf, 100); } int main(){ void* addr[ALLOC_NUM]; Block("Before Alloc 6\n"); int i; for( i = 0; i < ALLOC_NUM; i++ ){ addr[i] = Alloc(8 * KB); } Block("Before free\n"); printf(0, "Free: %d\n", Free(addr[1])); addr[1] = 0; printf(0, "Free: %d\n", Free(addr[2])); addr[2] = 0; printf(0, "Free: %d\n", Free(addr[4])); addr[4] = 0; Block("Before Alloc again\n"); addr[1] = Alloc(4 * KB); addr[2] = Alloc(4 * KB); addr[4] = Alloc(4 * KB); Block("After Alloc again\n"); for( i = 0; i < ALLOC_NUM; i++ ){ if( addr[i] != 0 ) Free(addr[i]); } exit(); }
C
#include<stdio.h> int main() { int test_cases; scanf("%d",&test_cases); while(test_cases--) { int t,b,num1,num2,ans=0,y=1,d1,d2,x; scanf("%d%d%d%d",&t,&b,&num1,&num2); while((num1)||(num2)) { d1 = num1%b; d2 = num2%b; num1 /=b; num2 /=b; x = (d1+d2)%b; ans += x*y; y *=b; } printf("%d %d\n",t,ans); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "../include/main.h" int tt = 0, tot_tt = 0, wt = 0, tot_wt = 0; void initialize_vars() { tt = 0, wt = 0, tot_wt = 0, tot_tt = 0; } void first_process(ProcessStruct process) { printf("******************\n"); printf("Process %d\n", process.id); printf("Waiting time: 0\n"); printf("Turnaround time: %d\n", process.burstTime); tt = process.burstTime; tot_tt += tt; } void times(ProcessStruct process, int nproc) { int id = process.id; int bt = process.burstTime; printf("******************\n"); printf("Process: %d\n", id); printf("Waiting time: %d\n", tt); printf("Turnaround time: %d\n", tt + bt); wt = tt; tot_wt += wt; tt += bt; tot_tt += tt; } void exec_processes(ProcessStruct processes[], int nproc) { // rest of processes for (int i = 1; i < nproc; i++) { times(processes[i], nproc); } } void avg_times(int nproc) { // find average printf("******************\n"); float avg_tt = (float)tot_tt / (float)nproc; float avg_wt = (float)tot_wt / (float)nproc; printf("Average waiting time = %.3f, Average turnaround time = %.3f\n", avg_wt, avg_tt); printf("******************\n"); printf("\n\n\n"); } void fcfs_cpu(ProcessStruct processes[], int nproc) { initialize_vars(); printf("\nFIRST COME, FIRST SERVED ALGORITHM\n"); // sort according to arrival time for (int i = 0; i < nproc; i++) { for (int j = i + 1; j < nproc; j++) { if (processes[i].arrivalTime > processes[j].arrivalTime) { ProcessStruct tmp = processes[i]; processes[i] = processes[j]; processes[j] = tmp; } } } // Waiting and turnaround time per process and average // Turnaround time = Burst time + Waiting time // Waiting time = Turnaround time - Burst time // Info for the first process first_process(processes[0]); // Rest processes exec_processes(processes, nproc); // Obtain averages avg_times(nproc); } void sjf(ProcessStruct processes[], int nproc) { initialize_vars(); printf("\nSHORTEST JOB FIRST ALGORITHM\n"); // sort according to burst time for (int i = 0; i < nproc; i++) { for (int j = i + 1; j < nproc; j++) { if (processes[i].burstTime > processes[j].burstTime) { ProcessStruct tmp = processes[i]; processes[i] = processes[j]; processes[j] = tmp; } } } // Info for the first process first_process(processes[0]); // Rest processes exec_processes(processes, nproc); // Obtain averages avg_times(nproc); } void priorityNP(ProcessStruct processes[], int nproc) { initialize_vars(); printf("\nPRIORITY NON PREEMPTIVE ALGORITHM\n"); // sort according to priority for (int i = 0; i < nproc; i++) { for (int j = i + 1; j < nproc; j++) { if (processes[i].priority > processes[j].priority) { ProcessStruct tmp = processes[i]; processes[i] = processes[j]; processes[j] = tmp; } } } // Info for the first process first_process(processes[0]); // Rest processes exec_processes(processes, nproc); // Obtain averages avg_times(nproc); } void rr(ProcessStruct processes[], int nproc, int q) { initialize_vars(); int curr_time = 0; printf("\nROUND ROBIN ALGORITHM\n"); // sort according to arrival time for (int i = 0; i < nproc; i++) { for (int j = i + 1; j < nproc; j++) { if (processes[i].arrivalTime > processes[j].arrivalTime) { ProcessStruct tmp = processes[i]; processes[i] = processes[j]; processes[j] = tmp; } } } while (1) { // Check if we can exit cicle int done = 1; for (int i = 0; i < nproc; i++) { if (processes[i].burstTime > 0) { // There are processes in queue, we're not done done = 0; // Check if we need to preempt again the process if (processes[i].burstTime > q) { printf("******************\n"); printf("Process %d\n", processes[i].id); printf("from %d to %d\n", curr_time, curr_time + q); curr_time += q; processes[i].burstTime -= q; } // Process can end in the quantum time else { printf("******************\n"); printf("Process %d finished\n", processes[i].id); printf("from %d to %d\n", curr_time, curr_time + processes[i].burstTime); wt = curr_time - processes[i].arrivalTime; printf("Wating time %d \n", wt); tt = wt + processes[i].burstTime; printf("Turnaround time %d \n", tt); tot_wt += wt; tot_tt += tt; curr_time += processes[i].burstTime; processes[i].burstTime = 0; } } } // If all processes are done if (done) break; } // Obtain averages avg_times(nproc); } /*int main() { int nproc = 3; ProcessStruct processes[nproc]; // proceso 0 processes[0].id = 0; processes[0].arrivalTime = 0; processes[0].burstTime = 3; processes[0].priority = 0; // proceso 1 processes[1].id = 1; processes[1].arrivalTime = 2; processes[1].burstTime = 2; processes[1].priority = 1; // proceso 2 processes[2].id = 2; processes[2].arrivalTime = 1; processes[2].burstTime = 6; processes[2].priority = 3; fcfs_cpu(processes, nproc); //sjf(processes, nproc); //priorityNP(processes, nproc); rr(processes, nproc, 2); }*/
C
/********************************************************************/ /* Author : Mahmoud Alaa Elwelily */ /* Date : 29 Jan 2019 */ /* Version : V01 */ /* Description: This header file is dedicated for defining fixed */ /* size data types which are required to be used */ /* Embedded System development. */ /********************************************************************/ /* This header file is dedicated for defining fixed size data types which are realable to be used Embedded System development. */ #ifndef STD_TYPES #define STD_TYPES /* unsigned 8 bit type */ typedef unsigned char u8 ; /* signed 8 bit type */ typedef signed char s8 ; /* unsigned 16 bit type */ typedef unsigned short int u16 ; /* signed 16 bit type */ typedef signed short int s16 ; /* unsigned 32 bit type */ typedef unsigned long int u32 ; /* signed 32 bit type */ typedef signed long int s32 ; /* floating type 32 bit */ typedef float f32 ; /* floating type 64 bit */ typedef double f64 ; /* Register 32 bits */ typedef union { struct { u8 Bit0 : 1; u8 Bit1 : 1; u8 Bit2 : 1; u8 Bit3 : 1; u8 Bit4 : 1; u8 Bit5 : 1; u8 Bit6 : 1; u8 Bit7 : 1; u8 Bit8 : 1; u8 Bit9 : 1; u8 Bit10 : 1; u8 Bit11 : 1; u8 Bit12 : 1; u8 Bit13 : 1; u8 Bit14 : 1; u8 Bit15 : 1; u8 Bit16 : 1; u8 Bit17 : 1; u8 Bit18 : 1; u8 Bit19 : 1; u8 Bit20 : 1; u8 Bit21 : 1; u8 Bit22 : 1; u8 Bit23 : 1; u8 Bit24 : 1; u8 Bit25 : 1; u8 Bit26 : 1; u8 Bit27 : 1; u8 Bit28 : 1; u8 Bit29 : 1; u8 Bit30 : 1; u8 Bit31 : 1; }BitAccess; u32 WordAccess; } Register_32Bit; /* Error status */ #define ERROR_NOK (u8)1 #define ERROR_OK (u8)0 #define UNSIGNED_MIN 0 /* Macro for NULL */ #define NULL ((void*)0) #endif
C
#include<stdio.h> #include<stdlib.h> void merge(int *arr, int low, int mid, int high){ int n1 = mid-low+1, n2 = high-mid, i=0, j=0, k = low; int left[n1], right[n2]; for(i=0;i<n1;i++) left[i] = arr[low+i]; for(i=0;i<n2;i++) right[i] = arr[mid+i+1]; i=0; while(i<n1 && j<n2){ if(left[i]<=right[j]) arr[k++] = left[i++]; else arr[k++] = right[j++]; } while(i<n1) arr[k++] = left[i++]; while(j<n2) arr[k++] = right[j++]; } void merge_sort(int *arr, int low, int high){ if(low<high){ int mid = (low+high)/2; merge_sort(arr, low, mid); merge_sort(arr, mid+1, high); merge(arr, low, mid, high); } } int main(void){ int *arr, n, i; printf("enter the size of array - "); scanf("%d", &n); arr = (int *)malloc(n*sizeof(int)); printf("enter the array elements - "); for(i=0;i<n;i++) scanf("%d",&arr[i]); merge_sort(arr, 0, n-1); printf("the sorted array is "); for(i=0;i<n;i++) printf("%d ",arr[i]); return 0; }
C
// Minimal C11 linked list // #ifndef __MINLLIST__ #define __MINLLIST__ #include <stdbool.h> struct dlnode{ void* data; struct dlnode* prev; struct dlnode* next; }; // Operations on list nodes. Use with caution. Not as safe as below. struct dlnode *dlnode_new(void*); void dlnode_free(struct dlnode*); void dlnode_link(struct dlnode*, struct dlnode*); void dlnode_unlink(struct dlnode*); struct dlnode *dlnode_seek(struct dlnode*, int); typedef struct dllist { struct dlnode* head; struct dlnode* tail; }dllist; struct dllist* dllist_new(void); void dllist_init(dllist*); int dllist_free(dllist*); // Adds to the back of a list. int dllist_append(dllist*, void*); // Gets an item from the back of the list. void* dllist_retrieve(dllist*); // Adds to the front of the list. int dllist_push(dllist*, void*); // Removes the first element from the list. void* dllist_pop(dllist*); dllist* dllist_map(dllist* list, void* (*function)(void*)); dllist* dllist_filter(dllist* list, bool (*fun)(void*)); int dllist_do(dllist*, void (*)(void*)); // Merge sorts the list with the given comparison function. struct dllist* dllist_sort(dllist*, int (*)(void*, void*)); #endif//LLIST
C
#include <stdio.h> struct Cliente{ int idade, matricula; float apolice; char nome[20]; char estadocivil; }; float mediapolice(struct Cliente *a, int n){ float soma = 0; int i; for(i = 0; i < n; i++){ soma += a[i].apolice; } return soma/n; } int maior_apolice(struct Cliente *a, int n){ float max = a[0].apolice; char max_nome[20]; strcpy(a[0].nome, max_nome); char max_estadocivil = a[0].estadocivil; int i; for(i = 1; i < n; i++){ if (a[i].apolice > max){ max = a[i].apolice; strcpy(max_nome, a[i].nome); max_estadocivil = a[i].estadocivil; } } printf("Maior apolice: %f\n", max); printf("Estado civil: "); if(max_estadocivil == 's' || max_estadocivil == 'S') printf("Solteiro\n"); if(max_estadocivil == 'd' || max_estadocivil == 'D') printf("Divorciado\n"); if(max_estadocivil == 'c' || max_estadocivil == 'C') printf("Casado\n"); printf("nome: %s\n", max_nome); return 0; } float idadeporcent(struct Cliente *a, int n){ int count = 0, i; for(i = 0; i < n; i++){ if(a[i].idade < 40){ count++; } } return count*100/n; } int main() { int i, n; struct Cliente *vector; printf("Número de clientes: "); scanf("%d",&n); vector = (struct Cliente*)malloc(n * sizeof(struct Cliente)); for(i = 0; i < n; i++){ printf("Cliente %d nome = ", i+1); scanf(" %c", &vector[i].nome); printf("Cliente %d idade = ", i+1); scanf("%d", &vector[i].idade); printf("Cliente %d estado civil \n (S solteiro, C para casado, D para divorciado) = ", i+1); scanf(" %c", &vector[i].estadocivil); printf("Cliente %d matricula = ", i+1); scanf("%d", &vector[i].matricula); printf("Cliente %d valor da apolice = ", i+1); scanf("%f", &vector[i].apolice); } printf("Media de apolice de casados : %f\n", mediapolice(vector, n)); maior_apolice(vector, n); printf("Porcentagem de clientes com menos de 40 anos: %f\n", idadeporcent(vector, n)); }
C
#ifndef __FIGHTER_H #define __FIGHTER_H #include "constants.h" #include "devices.h" #include "sprites.h" /** @defgroup fighter fighter /* @{ * * Classe que representa um personagem do jogo */ /** @name stance_t */ /**@{*/ typedef enum { stand1, stand2, walk1, walk2, walk3, walk4, LA1, LA2, MA1, MA2, HA1, HA2, LD, MD, HD, Win, Die1, Die2, Hit } stance_t; /**@}*/ /** @name fighter_t */ /**@{*/ typedef struct { int not_verified; int pos_x; /**< @brief posicao no eixo dos x */ int victories; /**< @brief numero de vitorias */ int pos_y; /**< @brief posicao no eixo dos y */ int life; /**< @brief vida */ int player_number; /**< @brief numero do jogador - pode ser 1 ou 2 */ sprite_t waiting_stance[2]; /**< @brief sprites de 'espera' */ sprite_t low_attack_stance[2]; /**< @brief sprites de ataque baixo */ sprite_t medium_attack_stance[2]; /**< @brief sprites de ataque medio */ sprite_t high_attack_stance[2]; /**< @brief sprites de ataque alto */ sprite_t low_defense_stance [1]; /**< @brief sprites de defesa baixa */ sprite_t medium_defense_stance [1]; /**< @brief sprites de defesa media */ sprite_t high_defense_stance [1]; /**< @brief sprites de defesa alta */ sprite_t walking_stance[4]; /**< @brief sprites de movimento */ sprite_t die_stance[2]; /**< @brief sprites de morte */ sprite_t win_stance [1]; /**< @brief sprites de vencer a ronda*/ sprite_t hit_stance [1]; /**< @brief sprites de sofrer dano */ unsigned long long time_begin_action; /**< @brief tempo em que comecou a ultima acao */ float power; /**< @brief numero entre 0 e 1 que determina a forca */ float defense; /**< @brief numero entre 0 e 1 que determina a defesa */ stance_t stance; /**< @brief estado em que se encontra atualmente */ int movement; /**< @brief -1 se esta a mover para tras, 0 se nao esta a mover, 1 se esta a mover para a frente */ } fighter; /**@}*/ /* * @brief Inicia os fighters nas posicoes iniciais com os estados e vida iniciais para comecar uma nova ronda. * * @param f1 fighter1 * @param f2 fighter2 */ void init_fighter(fighter* f1, fighter* f2); /* * @brief Cria os fighters nas posicoes iniciais. Caso seja o jogador 1, cria numa posicao. se for o 2, cria noutra. (As posicoes podem ser alteradas em constants.h) * * @param number numbero do fighter (pode ser 1 ou 2) * @param power valor entre 0 e 1 que indica a 'forca' do fighter * @param defense valor entre 0 e 1 que indica a 'defesa' do fighter * * @return fighter que foi criado */ fighter* create_fighter(int number, float power, float defense); /* * @brief Movimenta o jogador para a frente. Verifica se ha colisao com o adversario. Se houver, vai decrementando a distancia que percorre ate nao existir colisao. * * @param f_move fighter que se pretende mover * @param f adversario (preciso passar como parametro para usar no check_colision) * * @return 0 */ int move_front(fighter* f_move, fighter* f); // atualizar o time_begin_action e next_action. se houver colisao, da os passos sem se mexer /* * @brief Movimenta o jogador para tras. Verifica se ultrapassa os limites do ecra. Se sim, atualiza os valores do sprite com o minimo/maximo valor que o fighter pode estar. * * @param f_move fighter que se pretende mover * * @return 0 */ int move_back(fighter* f_move); /* * @brief Atualiza a vida do fighter * * @param f fighter que se pretende atualizar a vida * @param lost_hp vida perdida resultante de um ataque do adversario */ void update_life(fighter* f, int lost_hp); /* * @brief Atualiza o estado seguinte do jogador e a variavel time_begin_action para o tempo em que a acao comecou. Verifica se ha colisoes nos ataques e defesas do adversario, calculando assim a vida perdida. * *@param f1 fighter que se pretende atualizar *@param f2 fighter adversario (preciso passar como parametro para usar no check_colision) */ void update_fighter(fighter* f1, fighter* f2); //f1 e o player que se deseja atualizar /* * @brief Atualiza a posicao dos sprites carregados inicialmente com a posicao atual do fighter * * @param f fighter que se pretende atualizar a posicao dos sprites */ void update_sprite_pos(fighter* f); /* * @brief Retorna o sprite do estado atual em que o fighter se encontra * * @param f fighter que se pretende obter o sprite * * @return sprite correspondente ao estado atual do fighter */ sprite_t* get_curr_sprite(fighter* f); /* * @brief Executa as acoes quando um fighter vence uma ronda. Incremente o numero de vitorias e atualiza o estado para 'Win' * * @param f fighter vencedor da ronda */ void win_round(fighter* f); /* * @brief Executa as acoes de um ataque alto. Atualiza a variavel time_begin_action para o tempo inicial da acao e atualiza o estado do fighter * * @param f fighter que se executa o ataque alto */ void high_attack(fighter *f); /* * @brief Executa as acoes de um ataque medio. Atualiza a variavel time_begin_action para o tempo inicial da acao e atualiza o estado do fighter * * @param f fighter que se executa o ataque medio */ void medium_attack(fighter *f); /* * @brief Executa as acoes de um ataque baixo. Atualiza a variavel time_begin_action para o tempo inicial da acao e atualiza o estado do fighter * * @param f fighter que se executa o ataque baixo */ void low_attack(fighter *f); /* * @brief Executa as acoes de uma defesa alta. Atualiza a variavel time_begin_action para o tempo inicial da acao e atualiza o estado do fighter * * @param f fighter que se executa a defesa alta */ void high_defence(fighter *f); /* * @brief Executa as acoes de uma defesa media. Atualiza a variavel time_begin_action para o tempo inicial da acao e atualiza o estado do fighter * * @param f fighter que se executa a defesa media */ void medium_defence(fighter *f); /* * @brief Executa as acoes de uma defesa baixa. Atualiza a variavel time_begin_action para o tempo inicial da acao e atualiza o estado do fighter * * @param f fighter que se executa a defesa baixa */ void low_defence(fighter *f); /**@}*/ #endif
C
#include "rogue.h" void render(Game* game) { clear(); print_gamehub(game->levels[game->current_level - 1]); draw_level(game->levels[game->current_level - 1]); } int game_loop(Game* game) { int ch = '\0'; Position* new_position; Level* level; if (game->current_level == 0) { game->levels[game->current_level] = create_level(1); game->current_level++; } level = game->levels[game->current_level - 1]; print_gamehub(level); while (ch != 'q') { print_gamehub(level); new_position = handle_input(ch, level->user); check_pos(new_position, level); move_monsters(level); render(game); clear(); print_gamehub(level); draw_level(level); move(level->user->position->y, level->user->position->x); if (level->user->health <= 0) { game->current_level = 0; return -1; } ch = getch(); } }
C
/** * time_julian_day.c * * Created on: Feb 20, 2017 * Author: */ #include <stdio.h> #include <time.h> #include <string.h> #include <math.h> #include "time_julian_day.h" #include "time_calendar.h" /** * error occurs here. * time_julian_day.o:time_julian_day.c:(.rdata+0x0): multiple definition of `SECS_OF_DAY' * time_gregorian_calendar.o:time_gregorian_calendar.c:(.rdata+0x4): first defined here * */ //const int SECS_OF_DAY = 86400; //const time_t SECS_OF_JD_BEFORE_1970 = (4713 * 365 + 4713 / 4 + 1 + 719163) * 86400ll - 43200; //static SJULIAN_DAY RESULT_JULIAN_DAY; /** * timeptr used to be declared as a time_t* point. * */ double getJulianDayBySecond(time_t timePoint) { time_t lltime = timePoint; time_t llinteger; time_t lldecimal = 0.0; time_t llJDsecs = lltime + SECS_OF_JD_BEFORE_1970; double ddecimal; llinteger = llJDsecs / SECS_OF_DAY; lldecimal = llJDsecs - llinteger * SECS_OF_DAY; if(lldecimal > 0) { ddecimal = lldecimal / (double)SECS_OF_DAY; } double dJulianDay = llinteger + ddecimal; return dJulianDay; } /** * @param jd Julian day. * */ time_t getSecondByJulianDay(double jd) { time_t llJDsecs = 0; time_t integer; double decimal; integer = (time_t)ceil(jd); decimal = jd - ceil(jd); llJDsecs += integer * SECS_OF_DAY; llJDsecs += decimal * SECS_OF_DAY; llJDsecs -= SECS_OF_JD_BEFORE_1970; return llJDsecs; } double getJulianCenturyByJulianDay(double jd) { double dJulianDaySince2000 = jd - 2451545.0; return dJulianDaySince2000 / 36525.0; } double getJulianCenturyBySecond(time_t timePoint) { double jd = getJulianDayBySecond(timePoint); return getJulianCenturyByJulianDay(jd); } double getJulianMillenniumByJulianDay(double jd) { double dJulianDaySince2000 = jd - 2451545.0; return dJulianDaySince2000 / 365250.0; } double getJulianMillenniumBySecond(time_t timePoint) { double jd = getJulianDayBySecond(timePoint); return getJulianMillenniumByJulianDay(jd); }
C
#include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include "command.h" /* Get the full path of a command */ void get_command_path(char* command_name, char* path) { FILE *fp; // Exec the command char command[MAX_STRING_LENGTH]; strcpy(command, "which "); strcat(command, command_name); fp = popen(command, "r"); // Check if everything works if (fp == NULL) { printf("Failed to execute command \"%s\".\n", command); exit(1); } char output_t[MAX_STRING_LENGTH]; // Get the command result fgets(output_t, sizeof(output_t) - 1, fp); // Remove the "\n" dues to fgets behavior size_t size = strlen(output_t); if (output_t[size - 1] == '\n') output_t[size - 1] = '\0'; // Copy the string to the output strcpy(path, output_t); }
C
// // main.c // Quesiti // // Created by Rocco Carpi on 05/02/21. // #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, const char * argv[]) { FILE *f; f = fopen("quesiti.txt", "r"); char c = 0; int input; int stampa = 0; if (!f) { printf("errore apertura file quesiti.txt \n"); exit(0); } printf("inserire un numero "); scanf("%d", &input); while (fscanf(f,"%c",&c) == 1) { if (c == '@') { fscanf(f,"%c",&c); if ((int)(c - '0') == input) { stampa = 1; }else { stampa = 0; } continue; } if (stampa == 1) { printf("%c",c); } } fclose(f); return 0; }
C
/** * * MQTT/UDP project * * https://github.com/dzavalishin/mqtt_udp * Copyright (C) 2017-2018 Dmitry Zavalishin, dz@dz.ru * * * Packet send * **/ #include <sys/types.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include "mqtt_udp.h" #define BUFLEN PKT_BUF_SIZE // 512 static int pack_len( char *buf, int *blen, int *used, int data_len ) { *used = 0; while( 1 ) { if( *blen <= 0 ) return ENOMEM; int byte = data_len % 128; data_len /= 128; if( data_len > 0 ) byte |= 0x80; *buf++ = byte; (*blen)--; (*used)++; if( data_len == 0 ) return 0; } } // ---------------------------------------------------- // Make and send PUBLISH packet // ---------------------------------------------------- int mqtt_udp_send( int fd, char *topic, char *data ) { return mqtt_udp_send_publish( fd, topic, data ); } #if 1 int mqtt_udp_send_publish( int fd, char *topic, char *data ) { struct mqtt_udp_pkt p; unsigned char buf[BUFLEN]; int rc; size_t out_size; mqtt_udp_clear_pkt( &p ); p.ptype = PTYPE_PUBLISH; p.topic = topic; p.value = data; p.topic_len = strlen( topic ); p.value_len = strlen( data ); mqtt_udp_dump_any_pkt( &p ); rc = mqtt_udp_build_any_pkt( buf, BUFLEN, &p, &out_size ); if( rc ) return rc; mqtt_udp_dump( buf, out_size ); return mqtt_udp_send_pkt( fd, buf, out_size ); } #else int mqtt_udp_send_publish( int fd, char *topic, char *data ) { unsigned char buf[BUFLEN]; int tlen = strlen(topic); int dlen = strlen(data); int blen = sizeof(buf); unsigned char *bp = buf; *bp++ = PTYPE_PUBLISH; blen--; int total = tlen + dlen + 2; // packet size if( total > blen ) return ENOMEM; //int size = total+1; int used = 0; int rc = pack_len( bp, &blen, &used, total ); if( rc ) return rc; bp += used; *bp++ = (tlen >>8) & 0xFF; *bp++ = tlen & 0xFF; blen -= 2; //NB! Must be UTF-8 while( tlen-- > 0 ) { if( blen <= 0 ) return ENOMEM; *bp++ = *topic++; blen--; } while( dlen-- > 0 ) { if( blen <= 0 ) return ENOMEM; *bp++ = *data++; blen--; } return mqtt_udp_send_pkt( fd, buf, bp-buf ); } #endif // ---------------------------------------------------- // Packet with no payload, just type and zero length // ---------------------------------------------------- static int mqtt_udp_send_empty_pkt( int fd, char ptype ) { #if 1 unsigned char buf[2]; buf[0] = ptype; buf[1] = 0; return mqtt_udp_send_pkt( fd, buf, sizeof(buf) ); #else unsigned char buf[BUFLEN]; int blen = sizeof(buf); unsigned char *bp = buf; *bp++ = ptype; blen--; int used = 0; int rc = pack_len( bp, &blen, &used, 0 ); if( rc ) return rc; bp += used; return mqtt_udp_send_pkt( fd, buf, bp-buf ); #endif } // ---------------------------------------------------- // Ping // ---------------------------------------------------- int mqtt_udp_send_ping_request( int fd ) { #if 1 return mqtt_udp_send_empty_pkt( fd, PTYPE_PINGREQ ); #else unsigned char buf[BUFLEN]; int blen = sizeof(buf); unsigned char *bp = buf; *bp++ = PTYPE_PINGREQ; blen--; int used = 0; int rc = pack_len( bp, &blen, &used, 0 ); if( rc ) return rc; bp += used; return mqtt_udp_send_pkt( fd, buf, bp-buf ); #endif } int mqtt_udp_send_ping_responce( int fd, int ip_addr ) { return mqtt_udp_send_empty_pkt( fd, PTYPE_PINGRESP ); }
C
#include "cp1headers.h" /*=================momentum.c================= *Marches u and v for diffusion and convection (not PG), applies BCs, and evaluates source terms for PPE */ void momentum(int nx, int ny, float* u, float* v, float* uh, float* vh, float* s, float amu, float dx, float dy, float dt){ float conv_x, conv_y, diff_x, diff_y; int i,j,ij,ijw,ije,ijn,ijs; for ( i = 1; i < nx + 1; i++){ for (j = 1; j < ny + 1; j++){ ij = i +j*(nx+2); ije = (i+1)+ j*(nx+2); ijw = (i-1)+ j*(nx+2); ijs = i + (j-1)*(nx+2); ijn = i + (j+1)*(nx+2); //Solve for x-momentum conv_x = u[ij] * (u[ije] - u[ijw])/ (2.0 * dx); conv_y = v[ij] * (u[ijn] - u[ijs])/ (2.0 * dy); diff_x = amu * (u[ije] - 2.0*u[ij] + u[ijw])/(dx * dx); diff_y = amu * (u[ijn] - 2.0*u[ij] + u[ijs])/(dy * dy); uh[ij] = u[ij] + dt * (-conv_x -conv_y + diff_x + diff_y); //Solve for y-momentum conv_x = u[ij] * (v[ije] - v[ijw])/ (2.0 * dx); conv_y = v[ij] * (v[ijn] - v[ijs])/ (2.0 * dy); diff_x = amu * (v[ije] - 2.0*v[ij] + v[ijw])/(dx * dx); diff_y = amu * (v[ijn] - 2.0*v[ij] + v[ijs])/(dy * dy); vh[ij] = v[ij] + dt * (-conv_x -conv_y + diff_x + diff_y); } } }
C
#include <stdio.h> int main() { int arr1[10][10],arr2[10][10],arr3[10][10],sum=0; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { scanf("%d",&arr1[i][j]); } } for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { scanf("%d",&arr2[i][j]); } } for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { for(int k=0;k<3;k++) { sum=sum+arr1[i][k]*arr2[k][j]; } arr3[i][j]=sum; } } for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { printf("%d ",arr3[i][j]); } printf("\n"); } return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef int /*<<< orphan*/ * HANDLE ; /* Variables and functions */ int CloseHandle (int /*<<< orphan*/ *) ; int /*<<< orphan*/ * CreateFileMappingA (int /*<<< orphan*/ *,int /*<<< orphan*/ *,int /*<<< orphan*/ ,int,int,char*) ; int DeleteFileA (int /*<<< orphan*/ ) ; scalar_t__ ERROR_FILE_INVALID ; scalar_t__ GetLastError () ; int /*<<< orphan*/ PAGE_READWRITE ; scalar_t__ broken (int /*<<< orphan*/ ) ; int /*<<< orphan*/ filename ; int /*<<< orphan*/ ok (int,char*) ; int test_Mapfile_createtemp (int /*<<< orphan*/ **) ; __attribute__((used)) static void test_MapFile(void) { HANDLE handle; HANDLE hmap; ok(test_Mapfile_createtemp(&handle), "Couldn't create test file.\n"); hmap = CreateFileMappingA( handle, NULL, PAGE_READWRITE, 0, 0x1000, "named_file_map" ); ok( hmap != NULL, "mapping should work, I named it!\n" ); ok( CloseHandle( hmap ), "can't close mapping handle\n"); /* We have to close file before we try new stuff with mapping again. Else we would always succeed on XP or block descriptors on 95. */ hmap = CreateFileMappingA( handle, NULL, PAGE_READWRITE, 0, 0, NULL ); ok( hmap != NULL, "We should still be able to map!\n" ); ok( CloseHandle( hmap ), "can't close mapping handle\n"); ok( CloseHandle( handle ), "can't close file handle\n"); handle = NULL; ok(test_Mapfile_createtemp(&handle), "Couldn't create test file.\n"); hmap = CreateFileMappingA( handle, NULL, PAGE_READWRITE, 0, 0, NULL ); ok( hmap == NULL, "mapped zero size file\n"); ok( GetLastError() == ERROR_FILE_INVALID, "not ERROR_FILE_INVALID\n"); hmap = CreateFileMappingA( handle, NULL, PAGE_READWRITE, 0x80000000, 0, NULL ); ok( hmap == NULL || broken(hmap != NULL) /* NT4 */, "mapping should fail\n"); /* GetLastError() varies between win9x and WinNT and also depends on the filesystem */ if ( hmap ) CloseHandle( hmap ); hmap = CreateFileMappingA( handle, NULL, PAGE_READWRITE, 0x80000000, 0x10000, NULL ); ok( hmap == NULL || broken(hmap != NULL) /* NT4 */, "mapping should fail\n"); /* GetLastError() varies between win9x and WinNT and also depends on the filesystem */ if ( hmap ) CloseHandle( hmap ); /* On XP you can now map again, on Win 95 you cannot. */ ok( CloseHandle( handle ), "can't close file handle\n"); ok( DeleteFileA( filename ), "DeleteFile failed after map\n" ); }
C
/* * Starter image: * Load and place an image using various options for scaling and positioning * * Place the image it its original size. * Place the image with scaling and orientation to the west. * Fit the image into a box with clipping. * Fit the image into a box with proportional resizing. * Fit the image into a box entirely. * * Required software: PDFlib/PDFlib+PDI/PPS 9 * Required data: image file */ #include <stdio.h> #include <stdlib.h> #include "pdflib.h" int main(void) { /* This is where the data files are. Adjust as necessary. */ const char* searchpath = "../data"; const char* outfile = "starter_image.pdf"; #define BUFLEN 1024 char buf[BUFLEN]; PDF * p; const char* imagefile = "lionel.jpg"; int font, image; int bw = 400, bh = 200; int x = 20, y = 580, yoffset = 260; /* create a new PDFlib object */ if ((p = PDF_new()) == (PDF *) 0) { printf("Couldn't create PDFlib object (out of memory)!\n"); return(2); } PDF_TRY(p) { char optlist[256]; sprintf(optlist, "SearchPath={{%s}}", searchpath); PDF_set_option(p, optlist); /* This means we must check return values of load_font() etc. */ PDF_set_option(p, "errorpolicy=return"); if (PDF_begin_document(p, outfile, 0, "") == -1) { printf("Error: %s\n", PDF_get_errmsg(p)); PDF_delete(p); return(2); } PDF_set_info(p, "Creator", "PDFlib starter sample"); PDF_set_info(p, "Title", "starter_image"); font = PDF_load_font(p, "Helvetica", 0, "winansi", ""); if (font == -1) { printf("Error: %s\n", PDF_get_errmsg(p)); PDF_delete(p); return(2); } /* Load the image */ image = PDF_load_image(p, "auto", imagefile, 0, ""); if (image == -1) { printf("Error: %s\n", PDF_get_errmsg(p)); PDF_delete(p); return(2); } /* Start page 1 */ PDF_begin_page_ext(p, 0, 0, "width=a4.width height=a4.height"); PDF_setfont(p, font, 12); /* ------------------------------------ * Place the image in its original size * ------------------------------------ */ /* Position the image in its original size with its lower left corner * at the reference point (20, 380) */ PDF_fit_image(p, image, 20, 380, ""); /* Output some descriptive text */ PDF_fit_textline(p, "The image is placed with the lower left corner in its original " "size at reference point (20, 380):", 0, 20, 820, ""); PDF_fit_textline(p, "fit_image(image, 20, 380, \"\");", 0, 20, 800, ""); /* -------------------------------------------------------- * Place the image with scaling and orientation to the west * -------------------------------------------------------- */ /* Position the image with its lower right corner at the reference * point (580, 20). * "scale=0.5" scales the image by 0.5. * "orientate=west" orientates the image to the west. */ PDF_fit_image(p, image, 580, 20, "scale=0.5 position={right bottom} orientate=west"); /* Output some descriptive text */ PDF_fit_textline(p, "The image is placed with a scaling of 0.5 and an orientation to " "the west with the lower right corner", 0, 580, 320, "position={right bottom}"); PDF_fit_textline(p, " at reference point (580, 20): fit_image(image, 580, 20, " "\"scale=0.5 orientate=west position={right bottom}\");", 0, 580, 300, "position={right bottom}"); PDF_end_page_ext(p, ""); /* Start page 2 */ PDF_begin_page_ext(p, 0, 0, "width=a4.width height=a4.height"); PDF_setfont(p, font, 12); /* -------------------------------------- * Fit the image into a box with clipping * -------------------------------------- */ /* The "boxsize" option defines a box with a given width and height and * its lower left corner located at the reference point. * "position={right top}" positions the image on the top right of the * box. * "fitmethod=clip" clips the image to fit it into the box. */ sprintf(buf, "boxsize={%d %d} position={right top} fitmethod=clip", bw, bh); PDF_fit_image(p, image, x, y, buf); /* Output some descriptive text */ PDF_fit_textline(p, "fit_image(image, x, y, \"boxsize={400 200} position={right top} " "fitmethod=clip\");", 0, 20, y+bh+10, ""); /* --------------------------------------------------- * Fit the image into a box with proportional resizing * --------------------------------------------------- */ /* The "boxsize" option defines a box with a given width and height and * its lower left corner located at the reference point. * "position={center}" positions the image in the center of the * box. * "fitmethod=meet" resizes the image proportionally until its height * or width completely fits into the box. * The "showborder" option is used to illustrate the borders of the box. */ sprintf(buf, "boxsize={%d %d} position={center} fitmethod=meet showborder", bw, bh); PDF_fit_image(p, image, x, y-=yoffset, buf); /* Output some descriptive text */ PDF_fit_textline(p, "fit_image(image, x, y, \"boxsize={400 200} position={center} " "fitmethod=meet showborder\");", 0, 20, y+bh+10, ""); /* --------------------------------- * Fit the image into a box entirely * --------------------------------- */ /* The "boxsize" option defines a box with a given width and height and * its lower left corner located at the reference point. * By default, the image is positioned in the lower left corner of the * box. * "fitmethod=entire" resizes the image proportionally until its height * or width completely fits into the box. */ sprintf(buf, "boxsize={%d %d} fitmethod=entire", bw, bh); PDF_fit_image(p, image, x, y-=yoffset, buf); /* Output some descriptive text */ PDF_fit_textline(p, "fit_image(image, x, y, \"boxsize={400 200} fitmethod=entire\");", 0, 20, y+bh+10, ""); PDF_end_page_ext(p, ""); PDF_close_image(p, image); PDF_end_document(p, ""); } PDF_CATCH(p) { printf("PDFlib exception occurred:\n"); printf("[%d] %s: %s\n", PDF_get_errnum(p), PDF_get_apiname(p), PDF_get_errmsg(p)); PDF_delete(p); return(2); } PDF_delete(p); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printf.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: prolling <prolling@student.42wolfsburg. +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/12 10:54:50 by prolling #+# #+# */ /* Updated: 2021/10/11 21:02:52 by prolling ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" /* * Interpolates (convert and print) the variable given va_arg and fpos * Returns the *t_format */ static char *interpolate_var(int *fpos, const char *fstr, va_list args) { t_format format; char *str; init_format(&format); build_conv(&format, fpos, fstr, args); build_flags(&format, fpos, fstr); ft_convert_variable(&format); ft_apply_flags_to_variable(&format); str = ft_strdup(format.str); free_format(&format); return (str); } /* * processes the character pos and stores beginning & end of the formatter in * fpos[1&2]. * Sets the fpos[3] status flag: 0-default/none, 1-cpy normal, 2-interpolate, * Returns fpos[3]. * //if FORMAT_FLAG then strchr until CONVERSIONS+FORMAT_FLAG and set c,s,e,f=2 * //else then strchr until FORMAT_FLAG and set c,s,e,f=1 * fpos[4] = counter, start, end, flag */ static size_t process_pos(const char *fstr, int *fpos) { const char *pos; const char *pend; pos = &fstr[fpos[0]]; if (*pos == FORMAT_FLAG) { pend = ft_strset(pos + 1, CONVERSIONS); fpos[1] = fpos[0]; fpos[2] = (int)(pend - fstr); fpos[3] = 2; fpos[0] = fpos[2]; } else { pend = ft_strchr(pos, FORMAT_FLAG); fpos[1] = fpos[0]; if (pend) fpos[2] = (int)(pend - fstr - 1); else fpos[2] = (int)(ft_strend(fstr) - fstr - 1); fpos[3] = 1; fpos[0] = fpos[2]; } return (fpos[3]); } /* * Write formatted fstr to *str interpolating the args. * Worker Function for ft_sprintf and ft_printf * Return bytes written or zero on error/empty. * * fpos[5] = counter, start, end, flag, invisible character counter * flag can be -1 exit, 1 normal append, 2 var interpolation */ char *ft_vprintf(const char *fstr, va_list args, int *nbytes) { int fpos[5]; char *temp; char *str; str = (char *)ft_calloc(sizeof(char), 1); if (!str || !*fstr) return (NULL); reset_fpos(fpos, 0); while (fstr[fpos[0]] != '\0' && fpos[3] != -1) { process_pos(fstr, fpos); if (fpos[3] == 1) temp = ft_substr((char const *)fstr, \ fpos[1], fpos[2] - fpos[1] + 1); else if (fpos[3] == 2) temp = interpolate_var(fpos, fstr, args); *nbytes += ft_strlen(temp); str = ft_strfjoin(str, temp); fpos[0]++; } return (str); } /* * Write formatted <fstr> to <str>. Return bytes written. * str is defined outside and it is not freed for later reuse. */ int ft_sprintf(char *str, const char *fstr, ...) { va_list args; int nbytes; if (!fstr || !str) return (-1); nbytes = 0; va_start(args, fstr); str = ft_vprintf(fstr, args, &nbytes); va_end(args); return (nbytes); } /* * Write formatted fstr to stdout. Return bytes written. * Creates str itself for printing to stdout and frees it before returning. */ int ft_printf(const char *fstr, ...) { char *str; va_list args; int nbytes; if (!fstr) return (-1); nbytes = 0; va_start(args, fstr); str = ft_vprintf(fstr, args, &nbytes); va_end(args); nbytes = ft_printstring(str, 1); free(str); return (nbytes); }
C
#pragma once //һеk㡣 struct ListNode { int val; struct ListNode *next; ListNode(int x) :val(x) , next(NULL) {} }; ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) { assert(pListHead != NULL); //ָ룬֮IJֵΪk ListNode* first = pListHead; ListNode* second = pListHead; unsigned int i = k; int count = 0; while (first) { ++count; first = first->next; if (i < 1 || i > k) { second = second->next; } --i; } if (count < k) { return NULL; } return second; } void Push(ListNode*& head, int val) { if (head == NULL) { head = new ListNode(val); } else { ListNode* cur = head; while (cur->next) { cur = cur->next; } cur->next = new ListNode(val); } } void TestFindKthToTail() { ListNode* list = NULL; Push(list, 1); Push(list, 2); Push(list, 3); Push(list, 4); Push(list, 5); int k = 0; cout << "ҪҵĵKڵ: "; cin >> k; ListNode* node = FindKthToTail(list, k); assert(node != NULL); cout << node->val << endl; }
C
#include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/un.h> #include <netdb.h> #include <stdio.h> #include <string.h> #include <unistd.h> char path[] = {"/tmp/socket3.3.6"}; /* socket name */ main(void) /* ** Listing3.6.c - UDP communication with a forked subtask */ { struct sockaddr_un sock; int len=sizeof(sock); int pid; /* child task’s process id */ int fd; /* socket file descriptor */ char buffer[80]; /* establish and initialize UDP socket struct */ fd = socket(AF_UNIX, SOCK_DGRAM, 0); memset((char *) &sock, 0, sizeof(sock)); strcpy(sock.sun_path, path); sock.sun_family = AF_UNIX; /* create child subtask */ if((pid = fork()) == 0) { /* publish the port number we are listening to */ bind(fd, (struct sockaddr *) &sock, len); /* echo messages received from parent back to user */ while(1) { recvfrom(fd, buffer, sizeof(buffer), 0, (struct sockaddr *) &sock, &len); printf("Child: %s", buffer); if(strncmp(buffer, "EXIT", 4) == 0) /* exit request */ { unlink(path); puts("Bye!"); close(fd); break; } } /* Child exit */ exit(0); } /* send a message typed from interactive user to child subtask */ while(1) { sleep(1); /* response time */ printf("\nEnter a message: "); fflush(stdout); fgets(buffer, sizeof(buffer), stdin); sendto(fd, buffer, strlen(buffer)+1, 0, (struct sockaddr *) &sock, sizeof(sock)); if(strncmp(buffer, "EXIT", 4) == 0) { close(fd); break; } /* exit request */ } /* await Child exit */ waitpid(pid); return; }
C
/* * src/parser.c -- shell parser * * David Vargas * CSCI 4334-01 Operating Systems * Professor David Egle * University of Texas Rio Grande Valley * * Programming Project One * Due 09/30/16 * */ /* standard c header files */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* GNU readline specific header files */ #include <readline/readline.h> #include <readline/history.h> /* shell specific header files */ #include <sh/main.h> #include <sh/console.h> #include <sh/parser.h> #include <sh/exec.h> void parser_free(struct parser_t **parser) { struct token_t *tp; int i; /* free parser */ if ((*parser) != NULL) { /* free parser->path */ if ((*parser)->path != NULL) { /* free parser->path->argv[i] */ for (i = 0; i < (*parser)->path->argc; i++) { if ((*parser)->path->argv[i] != NULL) { free((*parser)->path->argv[i]); } } /* free parser->path->argv */ if ((*parser)->path->argv != NULL) { free((*parser)->path->argv); } free((*parser)->path); } /* free parser->paths */ if ((*parser)->paths != NULL) { /* free parser->paths->next */ while ((*parser)->paths->token != NULL) { tp = (*parser)->paths; (*parser)->paths = (*parser)->paths->next; if (tp != NULL) { free(tp); } } free((*parser)->paths); } /* free parser->command */ if ((*parser)->command != NULL) { /* free parser->command->argv[i] */ for (i = 0; i < (*parser)->command->argc; i++) { if ((*parser)->command->argv[i] != NULL) { free((*parser)->command->argv[i]); } } /* free parser->command->argv */ if ((*parser)->command->argv != NULL) { free((*parser)->command->argv); } free((*parser)->command); } /* free parser->tokens */ if ((*parser)->tokens != NULL) { /* free parser->tokens->next */ while ((*parser)->tokens->token != NULL) { tp = (*parser)->tokens; (*parser)->tokens = (*parser)->tokens->next; if (tp != NULL) { free(tp); } } free((*parser)->tokens); } free((*parser)); } } void parse_path_argv(struct shell_t **shell) { struct token_t *tp; size_t size; int i; tp = (*shell)->parser->paths; /* path->argv */ size = ((*shell)->parser->path->argc * sizeof(char *)) + sizeof(char *); (*shell)->parser->path->argv = (char **) malloc(size); if ((*shell)->parser->path->argv == NULL) { fprintf(stderr, "sh: error: malloc() failed\n"); abort(); } memset((*shell)->parser->path->argv, 0, size); /* path->argv[i] */ for (i = 0; i < (*shell)->parser->path->argc; i++) { size = (strlen(tp->token) * sizeof(char)) + sizeof(char); (*shell)->parser->path->argv[i] = (char *) malloc(size); if ((*shell)->parser->path->argv[i] == NULL) { fprintf(stderr, "sh: error: malloc() failed\n"); abort(); } memset((*shell)->parser->path->argv[i], 0, size); size = size - sizeof(char); strncpy((*shell)->parser->path->argv[i], tp->token, size); tp = tp->next; } } void parse_path_list(struct shell_t **shell) { size_t size; struct token_t *tp; /* exec->orig_path */ (*shell)->exec->orig_path = getenv("PATH"); /* exec->shell_path */ size = (strlen((*shell)->exec->orig_path) * sizeof(char)) + sizeof(char); (*shell)->exec->shell_path = (char *) malloc(size); if ((*shell)->exec->shell_path == NULL) { fprintf(stderr, "sh: error: malloc() failed\n"); abort(); } memset((*shell)->exec->shell_path, 0, size); size = size - sizeof(char); strncpy((*shell)->exec->shell_path, (*shell)->exec->orig_path, size); /* parser->paths */ tp = (*shell)->parser->paths; tp->token = strtok((*shell)->exec->shell_path, PATH_DELIM); while (tp->token != NULL) { (*shell)->parser->path->argc++; tp->next = (struct token_t *) malloc(sizeof(struct token_t)); if (tp->next == NULL) { fprintf(stderr, "sh: error: malloc() failed\n"); abort(); } tp = tp->next; tp->token = strtok(NULL, PATH_DELIM); } } void parse_command_argv(struct shell_t **shell) { struct token_t *tp; size_t size; int i; tp = (*shell)->parser->tokens; /* command->argc == 0 -- empty line */ if ((*shell)->parser->command->argc == 0) { return; } /* command->argv */ size = ((*shell)->parser->command->argc * sizeof(char *)) + sizeof(char *); (*shell)->parser->command->argv = (char **) malloc(size); if ((*shell)->parser->command->argv == NULL) { fprintf(stderr, "sh: error: malloc() failed\n"); abort(); } memset((*shell)->parser->command->argv, 0, size); /* command->argv[i] */ for (i = 0; i < (*shell)->parser->command->argc; i++) { size = (strlen(tp->token) * sizeof(char)) + sizeof(char); (*shell)->parser->command->argv[i] = (char *) malloc(size); if ((*shell)->parser->command->argv[i] == NULL) { fprintf(stderr, "sh: error: malloc() failed\n"); abort(); } memset((*shell)->parser->command->argv[i], 0, size); size = size - sizeof(char); strncpy((*shell)->parser->command->argv[i], tp->token, size); tp = tp->next; } } void parse_command_list(struct shell_t **shell) { struct token_t *tp; tp = (*shell)->parser->tokens; /* parser->tokens */ tp->token = strtok((*shell)->console->line, WHITESPACE); while (tp->token != NULL) { (*shell)->parser->command->argc++; tp->next = (struct token_t *) malloc(sizeof(struct token_t)); if (tp->next == NULL) { fprintf(stderr, "sh: error: malloc() failed\n"); abort(); } tp = tp->next; tp->token = strtok(NULL, WHITESPACE); } } void parse_setup(struct shell_t **shell) { struct token_t *tp; int i; /* parser->tokens */ while ((*shell)->parser->tokens->token != NULL) { tp = (*shell)->parser->tokens; (*shell)->parser->tokens = (*shell)->parser->tokens->next; if (tp != NULL) { free(tp); } } (*shell)->parser->tokens->token = NULL; (*shell)->parser->tokens->next = NULL; /* parser->command */ for (i = 0; i < (*shell)->parser->command->argc; i++) { if ((*shell)->parser->command->argv[i] != NULL) { free((*shell)->parser->command->argv[i]); } } if ((*shell)->parser->command->argv != NULL) { free((*shell)->parser->command->argv); } (*shell)->parser->command->argc = 0; (*shell)->parser->command->argv = NULL; /* parser->paths */ while ((*shell)->parser->paths->token != NULL) { tp = (*shell)->parser->paths; (*shell)->parser->paths = (*shell)->parser->paths->next; if (tp != NULL) { free(tp); } } (*shell)->parser->paths->token = NULL; (*shell)->parser->paths->next = NULL; /* parser->path */ for (i = 0; i < (*shell)->parser->path->argc; i++) { if ((*shell)->parser->path->argv[i] != NULL) { free((*shell)->parser->path->argv[i]); } } if ((*shell)->parser->path->argv != NULL) { free((*shell)->parser->path->argv); } (*shell)->parser->path->argc = 0; (*shell)->parser->path->argv = NULL; /* exec->shell_path */ if ((*shell)->exec->shell_path != NULL) { free((*shell)->exec->shell_path); } (*shell)->exec->shell_path = NULL; } void parse(struct shell_t **shell) { /* setup parser */ parse_setup(&(*shell)); /* create command list from line */ parse_command_list(&(*shell)); /* create command argv from command list */ parse_command_argv(&(*shell)); /* create path list from $PATH */ parse_path_list(&(*shell)); /* create path argv from path list */ parse_path_argv(&(*shell)); } void parser_alloc(struct parser_t **parser) { (*parser) = (struct parser_t *) malloc(sizeof(struct parser_t)); if ((*parser) == NULL) { fprintf(stderr, "sh: error: malloc() failed\n"); abort(); } /* parser->tokens setup */ (*parser)->tokens = (struct token_t *) malloc(sizeof(struct token_t)); if ((*parser)->tokens == NULL) { fprintf(stderr, "sh: error: malloc() failed\n"); abort(); } (*parser)->tokens->token = NULL; (*parser)->tokens->next = NULL; /* parser->command setup */ (*parser)->command = (struct command_t *) malloc(sizeof(struct command_t)); if ((*parser)->command == NULL) { fprintf(stderr, "sh: error: malloc() failed\n"); abort(); } (*parser)->command->argc = 0; (*parser)->command->argv = NULL; /* parser->paths setup */ (*parser)->paths = (struct token_t *) malloc(sizeof(struct token_t)); if ((*parser)->paths == NULL) { fprintf(stderr, "sh: error: malloc() failed\n"); abort(); } (*parser)->paths->token = NULL; (*parser)->paths->next = NULL; /* parser->path setup */ (*parser)->path = (struct command_t *) malloc(sizeof(struct command_t)); if ((*parser)->path == NULL) { fprintf(stderr, "sh: error: malloc() failed\n"); abort(); } (*parser)->path->argc = 0; (*parser)->path->argv = NULL; }
C
#include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <fcntl.h> #include <signal.h> #include <unistd.h> #define MAX_LEN 100 void input_handler(int num) { printf("globalfifo: Receive a signal form globalfifo, signalnum: %d\n", num); } int main(void) { int oflages; int fd; fd = open("/dev/globalfifo_0", O_RDWR, S_IRUSR | S_IWUSR); if (fd != -1) { signal(SIGIO, input_handler); fcntl(fd, F_SETOWN, getpid()); oflages = fcntl(fd, F_GETFL); fcntl(fd, F_SETFL, oflages | FASYNC); while (1) { sleep(100); } } else { printf("device open failure\n"); } return 0; }
C
#include <stdio.h> #include <string.h> #define TEST(x) test(x, #x) #include "myfilesystem.h" /* You are free to modify any part of this file. The only requirement is that when it is run, all your tests are automatically executed */ /* Some example unit test functions */ int success() { return 0; } int failure() { return 1; } /* Test init_fs*/ int no_operation() { void * helper = init_fs("test_data.txt", "test_dir.txt", "test_hash.txt", 1); // Remember you need to provide your own test files and also check their contents as part of testing char * filename = ((file *)helper)->filename; char * directory = ((file *)helper)->directory; char * hash = ((file *)helper)->hash; int core = ((file *)helper)->core; if(strcmp(filename,"test_data.txt")!=0 || strcmp(directory,"test_dir.txt")!=0 || strcmp(hash,"test_hash.txt")!=0 || core != 1) return 1; close_fs(helper); return 0; } /*Test create_file simple case*/ int create_file_test() { void * helper = init_fs("test_data.txt", "test_dir.txt", "test_hash.txt", 1); create_file("1.doc",100,helper); ssize_t size = file_size("1.doc",helper); if(size == 100) { close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test create an existsed file*/ int create_existsfile_test() { void * helper = init_fs("test_data.txt", "test_dir.txt", "test_hash.txt", 1); int result = create_file("1.doc",100,helper); if(result == 1) { close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test create_file but insufficient space*/ int create_file_insufficient_test(){ void * helper = init_fs("test_data.txt", "test_dir.txt", "test_hash.txt", 1); int result = create_file("2.txt",1000000000000000,helper); if(result == 2) { close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test create_file reapck case*/ int create_file_repack_test(){ void * helper = init_fs("test_data.txt", "test_dir.txt", "test_hash.txt", 1); create_file("14.txt",2000,helper); create_file("12.txt",2000,helper); create_file("13.txt",10,helper); delete_file("12.txt", helper); int result = create_file("3.txt",2010,helper); if(result==0){ close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test decress resize*/ int resize_file_test(){ void * helper = init_fs("test_data_resize.txt", "test_dir_resize.txt", "test_hash_resize.txt", 1); create_file("1.doc",1000,helper); resize_file("1.doc",500,helper); int size = file_size("1.doc",helper); if(size == 500){ close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test resize a not exists file*/ int resize_nofile_test(){ void * helper = init_fs("test_data_resize.txt", "test_dir_resize.txt", "test_hash_resize.txt", 1); int result = resize_file("77.txt",5,helper); if(result == 1) { close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test resize a file which cause insufficient space*/ int resize_insufficient_test(){ void * helper = init_fs("test_data_resize.txt", "test_dir_resize.txt", "test_hash_resize.txt", 1); create_file("11.doc",1000,helper); int result = resize_file("11.doc",4000000000,helper); if(result == 2 ) { close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test simple increase size repack*/ int resize_repack1_test(){ void * helper = init_fs("test_data_resize.txt", "test_dir_resize.txt", "test_hash_resize.txt", 1); create_file("44.doc",50,helper); resize_file("44.doc",1000,helper); size_t size = file_size("44.doc",helper); if(size == 1000) { close_fs(helper); return 0; } close_fs(helper); return 1; } /* Test increase size that affect next file offset*/ int resize_repack2_test(){ void * helper = init_fs("test_data_resize.txt", "test_dir_resize.txt", "test_hash_resize.txt", 1); resize_file("11.doc",1010,helper); size_t size = file_size("11.doc",helper); if(size == 1010) { close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test decrease size that doesn't affect next file offset*/ int resize_repack3_test(){ void * helper = init_fs("test_data_resize.txt", "test_dir_resize.txt", "test_hash_resize.txt", 1); resize_file("11.doc",10,helper); size_t size = file_size("11.doc",helper); if(size == 10) { close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test delete file simple case*/ int delete_test(){ void * helper = init_fs("test_data_resize.txt", "test_dir_resize.txt", "test_hash_resize.txt", 1); delete_file("11.doc",helper); ssize_t size = file_size("11.doc",helper); if(size < 0) { close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test delete a file twice*/ int delete_filetwice_test(){ void * helper = init_fs("test_data_resize.txt", "test_dir_resize.txt", "test_hash_resize.txt", 1); delete_file("11.doc",helper); ssize_t size = file_size("11.doc",helper); if(size < 0) { close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test delete a not existsed file*/ int delete_nofile_test(){ void * helper = init_fs("test_data_resize.txt", "test_dir_resize.txt", "test_hash_resize.txt", 1); int result = delete_file("111.doc",helper); if(result == 1) { close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test rename a not existsed file*/ int rename_nofile_test(){ void * helper = init_fs("test_data.txt", "test_dir.txt", "test_hash.txt", 1); int result = rename_file("123.txt","456.txt",helper); if(result == 1) { close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test rename a file but its new name existsed*/ int rename_new_exists_test(){ void * helper = init_fs("test_data.txt", "test_dir.txt", "test_hash.txt", 1); int result = rename_file("14.txt","3.txt",helper); if(result == 1) { close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test rename file simple case*/ int rename_test(){ void * helper = init_fs("test_data.txt", "test_dir.txt", "test_hash.txt", 1); int result = rename_file("1.doc","31.txt",helper); if(result == 0) { close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test read_file file simple case*/ int read_file_test(){ void * helper = init_fs("test_data_read.txt", "test_dir_read.txt", "test_hash_read.txt", 1); create_file("00.doc",50,helper); char input[50]; memset(input,'0',50); write_file("00.doc",0,50,input,helper); char buf[50]; int result = read_file("00.doc",0,50,buf,helper); if(result == 3) { close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test read a not exists file*/ int read_file_nofile_test(){ void * helper = init_fs("test_data_read.txt", "test_dir_read.txt", "test_hash_read.txt", 1); char buf[1]; int result =read_file("2.doc",0,1,buf,helper); if(result == 1){ close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test read a file from an impossible offset*/ int read_file_offsetover_test(){ void * helper = init_fs("test_data_read.txt", "test_dir_read.txt", "test_hash_read.txt", 1); char buf[1]; create_file("1.doc",100,helper); int result = read_file("1.doc",1000,1,buf,helper); if(result == 2){ close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test read a file for an impossible length*/ int read_file_lenover_test(){ void * helper = init_fs("test_data_read.txt", "test_dir_read.txt", "test_hash_read.txt", 1); char buf[1]; int result =read_file("1.doc",1,1000,buf,helper); if(result == 2){ close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test write a not exists file*/ int write_nofile_test(){ void * helper = init_fs("test_data_write.txt", "test_dir_write.txt", "test_hash_write.txt", 1); char input[10]; memset(input,'0',10); int result = write_file("p.bin",2,12,input,helper); if(result == 1) { close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test write a file which cause insufficient space*/ int write_file_insufficient_test(){ void * helper = init_fs("test_data.txt", "test_dir.txt", "test_hash.txt", 1); char input[100000]; memset(input,'0',100000); create_file("19.doc",100,helper); int result = write_file("19.doc",1,100000,input,helper); if(result == 3) { close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test write a file simple case*/ int write_file_test(){ void * helper = init_fs("test_data.txt", "test_dir.txt", "test_hash.txt", 1); char* input = "helloC"; int result = write_file("19.doc",1,strlen(input),input,helper); if(result == 0) { close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test write and increase size of file but no need repack*/ int write_file_increase1_test(){ void * helper = init_fs("test_data_.txt", "test_dir.txt", "test_hash.txt", 1); char * input = "world123"; int result = write_file("19.doc",6,strlen(input),input,helper); if(result == 0) { close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test write and increase size of file need to repack*/ int write_file_test_increase2_test(){ void * helper = init_fs("test_data_write.txt", "test_dir_write.txt", "test_hash_write.txt", 1); char input[150]; memset(input,'0',150); create_file("1.doc",1000,helper); create_file("2.doc",1000,helper); create_file("3.doc",2000,helper); create_file("4.doc",50,helper); int result = write_file("1.doc",1000,10,input,helper); if(result == 0) { close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test get a file size simple case*/ int file_size_test(){ void * helper = init_fs("test_data.txt", "test_dir.txt", "test_hash.txt", 1); create_file("size.txt",5,helper); ssize_t size = file_size("size.txt",helper); if(size == 5) { close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test hash_bock*/ int hash_block_test(){ void * helper = init_fs("test_data_h.txt", "test_dir_h.txt", "test_hash_h.txt", 1); create_file("ppx.doc",1000,helper); char buf [496]; FILE* fpt = fopen("test_hash_h.txt","rb+"); fread(buf,1,496,fpt); fclose(fpt); compute_hash_tree(helper); char b [496]; fpt = fopen("test_hash_h.txt","rb+"); fread(b,1,496,fpt); fclose(fpt); if(strcmp(buf,b) == 0){ close_fs(helper); return 0; } close_fs(helper); return 1; } /*Test get the size of a not exists file*/ int file_size_nofile_test(){ void * helper = init_fs("test_data.txt", "test_dir.txt", "test_hash.txt", 1); ssize_t size = file_size("999.txt",helper); if(size < 0) { close_fs(helper); return 0; } close_fs(helper); return 1; } /****************************/ /* Helper function */ void test(int (*test_function) (), char * function_name) { int ret = test_function(); if (ret == 0) { printf("Passed %s\n", function_name); } else { printf("Failed %s returned %d\n", function_name, ret); } } /************************/ int main(int argc, char * argv[]) { // You can use the TEST macro as TEST(x) to run a test function named "x" TEST(no_operation); TEST(success); TEST(failure); printf("Test cases\n"); TEST(create_file_test); TEST(create_existsfile_test); TEST(create_file_insufficient_test); TEST(create_file_repack_test); TEST(resize_file_test); TEST(resize_nofile_test); TEST(resize_insufficient_test); TEST(resize_repack1_test); TEST(resize_repack2_test); TEST(resize_repack3_test); TEST(delete_test); TEST(delete_filetwice_test); TEST(delete_nofile_test); TEST(rename_nofile_test); TEST(rename_new_exists_test); TEST(rename_test); TEST(read_file_test); TEST(read_file_nofile_test); TEST(read_file_offsetover_test); TEST(read_file_lenover_test); TEST(write_nofile_test); TEST(write_file_insufficient_test); TEST(write_file_test); TEST(write_file_test_increase2_test); TEST(file_size_test); TEST(file_size_nofile_test); TEST(hash_block_test); // Add more tests here return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* p_operand.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hhuhtane <hhuhtane@student.hive.fi> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/21 21:50:26 by hhuhtane #+# #+# */ /* Updated: 2021/07/22 17:36:36 by hhuhtane ### ########.fr */ /* */ /* ************************************************************************** */ #include "builtins.h" /* ** -p pathname ** True if pathname resolves to a file that exists and is a FIFO. False ** if pathname cannot be resolved, or if pathname resolves to a file that ** exists but is not a FIFO. */ void p_operand(void *proc) { t_process *p; t_stat buf; p = proc; p->status = 2; if (p->argc > 4) return ((void)err_builtin(E_TOO_MANY_ARGS, "test", NULL)); if (p->argc > 3) return ((void)err_builtin(E_BIN_OP_EXP, "test", p->argv[3])); p->status = 1; if (access(p->argv[2], F_OK)) return ; if (stat(p->argv[2], &buf) == -1) return ; if ((buf.st_mode & S_IFMT) != S_IFIFO) return ; p->status = 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <assert.h> #include <unistd.h> const int BUFF_SIZE = 512; const char* _EOF_ = "$EOF"; const char* _FIN_ = "$FIN"; int main(int argc, char* argv[] ){ //CLI int port_num; if (argc == 1){ port_num = 49217; printf("\nport number: %d\n", port_num); } else if (argc==2){ // for (int i=0; i<argc; i++) printf("%s\n", argv[i]); port_num = atoi(argv[1]); printf("\nport number: %d\n", port_num); } else{ printf("\nWrong input!\n"); return -1; } const int PORT = port_num; //create a socket int sd; if ((sd = socket(PF_INET, SOCK_STREAM,0)) < 0){ // return socket descriptor fprintf(stderr,"socket creating err!\n"); exit(1); } //binding struct sockaddr_in serv_addr, clnt_addr; memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(sd, (struct sockaddr*)&serv_addr, sizeof(serv_addr))==-1 ){ fprintf(stderr,"bind err\n"); exit(1); } printf("bind complete!\n"); printf("listening....\n"); // For unknown IP addr /* gethostbyname("DOMAIN") struct sockaddr_in, my_addr; memset(&my_addr, 0, sizeof(my_addr)); my_addr.sin_family = AF_INET'; my_addr.sin.port = htonl(MYPORT); printf("%s", inet_ntoa(my_addr.sin_addr)); */ //listen if(listen(sd, 5) == -1){ fprintf(stderr,"listen() err\n"); exit(1); } printf("listend!!\n"); // char* buf = (char*)malloc(sizeof(char)* BUFF_SIZE); // assert(buf != NULL); char buf[BUFF_SIZE]; unsigned int flag = 0; int msg_len; FILE *fp =NULL; // Iterative server int pkt_num = 0; while (1) { int filesize; int bufsize; int recvbyte; int filename = 0; char fdata[100]; memset(fdata, 0, sizeof(fdata)); memset(buf, 0, sizeof(buf)); printf("\n\nwaiting connection...\n\n"); // accept - return new socket descriptor(>0) //printf("wait accepting clnt_sock...\n"); unsigned int sin_size; int new_sd; sin_size = sizeof(clnt_addr); new_sd = accept(sd, (struct sockaddr *)&clnt_addr, &sin_size); if(new_sd == -1) { fprintf(stderr, "accept() err\n"); close(new_sd); exit(1); } printf("connection esatablished!\n"); //printf("file?\n"); //get file name if (filename == 0) { bufsize = 1; filename = recv(new_sd, buf, bufsize, flag); int i = 0; while(i < 3){ if(buf[0]=='\\') i++; // printf("%c\n", buf[0]); filename = recv(new_sd, buf, bufsize, flag); strcat(fdata, buf); } // printf("first packet: %s\n",fdata); char *ptr = strtok(fdata, "\\"); // printf("filename: %s\n", fdata); fp = fopen(ptr, "wb"); ptr = strtok(NULL, "\\"); filesize = atoi(ptr); // printf("filesize:%d\n", filesize); ptr = strtok(NULL, "\\"); filename = 100; printf("Filename: %s, Filesize: %d\n", fdata, filesize); } // printf("recieved... "); //receive file bufsize = BUFF_SIZE; recvbyte = 0; while (filesize != recvbyte) { if (filesize < BUFF_SIZE) bufsize = filesize; recvbyte = recv(new_sd, buf, bufsize, 0); filesize = filesize - recvbyte; // printf("%d\n", filesize); fwrite(buf, 1, recvbyte, fp); pkt_num++; } printf("finish to write!\n"); fclose(fp); filename = 0; close(new_sd); } return 0; }
C
/* 1、front and end is where? */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define Error -1 typedef struct Node { int data; struct Node *next; }Qnode; typedef struct { Qnode *front; Qnode *end; }Queue; Queue *CreatQueue(); void add(int x,Queue *que); int delete(Queue *que); int main(void) { return 0; } Queue *CreatQueue() { Queue *que; que->front=NULL; que->end=NULL; return que; } void add(int x,Queue *que) { Qnode *NewNode; NewNode=(Qnode *)malloc(sizeof(Qnode)); NewNode->data=x; NewNode->next=NULL; // Empty if(que->front==NULL){que->front=que->end=NewNode;return;}; // not empty que->front->next=NewNode; que->front=NewNode;//be careful: do not forget this step } int delete(Queue *que) { int FirstNodeData; Qnode *SecondNode; //empty if(que->front==NULL){printf("the queue is empty!\n");return Error;} //count=1 if(que->front==que->end) { FirstNodeData=que->front->data; free(que->front); que->front=que->end=NULL; return FirstNodeData; } // count>=2 FirstNodeData=que->front->data; SecondNode=que->front->next; free(que->front); que->front=SecondNode; return FirstNodeData; }
C
#include "header.h" #include "util.h" #include "svpng.inc" #include <math.h> #include <stdio.h> extern double xpos, ypos; extern double deltaX, deltaY; extern double lastX, lastY; extern int button_press_state; extern double totalOffX, totalOffY; extern double ratio; // if get ESC // then exit void key_press_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { // putchar(key); switch (key) { case 'Q': case GLFW_KEY_ESCAPE: glfwSetWindowShouldClose(window, 1); break; case 'S': printf("%s\n", "Saving Frame..."); FILE* fp = fopen("out.png", "wb"); unsigned char pixels[WIDTH * HEIGHT * 3]; glReadPixels(0,0, WIDTH, HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, pixels); svpng(fp, WIDTH, HEIGHT, pixels, 0); fclose(fp); break; default: break; } } // if mouse press then // ones the press_state // update lastX and lastY // else // zeros the press_state void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) { if (button == GLFW_MOUSE_BUTTON_LEFT) { if (action == GLFW_PRESS) { button_press_state = 1; lastX = xpos; lastY = ypos; } else if (action == GLFW_RELEASE) { button_press_state = 0; } } } // if scroll then // update ratio by yoffset // note: if yoffset == -1 the graph bllo up void scroll_callback(GLFWwindow * window, double xoffset, double yoffset) { ratio = (pow(0.9, yoffset)) * ratio; // printf("r: %f\n", ratio); } // if press_state then void cursor_position_state(void) { if (button_press_state) { totalOffX -= deltaX / ratio; totalOffY -= deltaY / ratio; deltaX = xpos - lastX; deltaY = ypos - lastY; totalOffX += deltaX / ratio; totalOffY += deltaY / ratio; } else { deltaX = 0.0; deltaY = 0.0; } }
C
/* Copyright (c) 2011 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include "cryptolib.h" #include "file_keys.h" #include "host_common.h" #include "timer_utils.h" #define FILE_NAME_SIZE 128 #define NUM_OPERATIONS 100 /* Number of signature operations to time. */ int SpeedTestAlgorithm(int algorithm) { int i, key_size; int error_code = 0; double speed, msecs; char file_name[FILE_NAME_SIZE]; uint8_t* digest = NULL; uint8_t* signature = NULL; uint64_t digest_len, sig_len; RSAPublicKey* key = NULL; ClockTimerState ct; char* sha_strings[] = { /* Maps algorithm->SHA algorithm. */ "sha1", "sha256", "sha512", /* RSA-1024 */ "sha1", "sha256", "sha512", /* RSA-2048 */ "sha1", "sha256", "sha512", /* RSA-4096 */ "sha1", "sha256", "sha512", /* RSA-8192 */ }; key_size = siglen_map[algorithm] * 8; /* in bits. */ /* Get key. */ snprintf(file_name, FILE_NAME_SIZE, "testkeys/key_rsa%d.keyb", key_size); key = RSAPublicKeyFromFile(file_name); if (!key) { VBDEBUG(("Couldn't read RSA Public key from file: %s\n", file_name)); error_code = 1; goto failure; } /* Get expected digest. */ snprintf(file_name, FILE_NAME_SIZE, "testcases/test_file.%s.digest", sha_strings[algorithm]); digest = BufferFromFile(file_name, &digest_len); if (!digest) { VBDEBUG(("Couldn't read digest file.\n")); error_code = 1; goto failure; } /* Get signature to verify against. */ snprintf(file_name, FILE_NAME_SIZE, "testcases/test_file.rsa%d_%s.sig", key_size, sha_strings[algorithm]); signature = BufferFromFile(file_name, &sig_len); if (!signature) { VBDEBUG(("Couldn't read signature file.\n")); error_code = 1; goto failure; } StartTimer(&ct); for (i = 0; i < NUM_OPERATIONS; i++) { if (!RSAVerify(key, signature, sig_len, algorithm, digest)) VBDEBUG(("Warning: Signature Check Failed.\n")); } StopTimer(&ct); msecs = (float) GetDurationMsecs(&ct) / NUM_OPERATIONS; speed = 1000.0 / msecs ; fprintf(stderr, "# rsa%d/%s:\tTime taken per verification = %.02f ms," " Speed = %.02f verifications/s\n", key_size, sha_strings[algorithm], msecs, speed); fprintf(stdout, "ms_rsa%d_%s:%.02f\n", key_size, sha_strings[algorithm], msecs); failure: free(signature); free(digest); RSAPublicKeyFree(key); return error_code; } int main(int argc, char* argv[]) { int i; int error_code = 0; for (i = 0; i < kNumAlgorithms; ++i) { if(SpeedTestAlgorithm(i)) error_code = 1; } return error_code; }
C
#include <stdio.h> #include "match.h" int check(int expected, const char pattern[], const char text[]) { int result = best_match_index(pattern, text); if(result != expected) { printf("--- TEST FAILED WITH pattern: \"%s\", text: \"%s\" ---- returned %d instead of %d\n", pattern, text, result, expected); return 1; } return 0; } main() { int failedTests = 0; failedTests += check (0, "a", "aaa"); failedTests += check (0, "a", "bbb"); failedTests += check (0, "a", "b"); failedTests += check (0, "a", "a"); failedTests += check (0, "abc", "abcde"); failedTests += check (0, "abc", "abcabc"); failedTests += check (0, "abc", "abdacb"); failedTests += check (2, "abc", "bcabbc"); failedTests += check (0, "abc", "addfs"); failedTests += check (0, "abc", "bbc"); failedTests += check (1, "abc", "bcacb"); failedTests += check (1, "abc", "babc"); failedTests += check (1, "abc", "cabcabc"); failedTests += check (1, "abc", "fangfh"); failedTests += check (0, "abc", "fbngfh"); failedTests += check (2, "abc", "asabc"); failedTests += check (2, "abc", "ababc"); failedTests += check (2, "abc", "bcabc"); failedTests += check (2, "abc", "dcabg"); failedTests += check (12, "abcd", "gffdhgcdhbcdabcd"); if(failedTests == 0) printf("ALL TESTS PASSED!\n"); }
C
#include <stdio.h> #include "testlib.h" #include "testlib2.h" int do_test(int num) { int num_squared = square(num); int i; for (i = 0; i < num_squared; i++) { printf("%d Hello\n", i+1); } return num; }
C
#include <windows.h> #include <stdio.h> #include <pthread.h> #include "parm.h" #include "function.h" // float **MakeMatrix(int N) { srand((unsigned int)time(0)); float **Matrix; Matrix=(float**)malloc(N*sizeof(float*)); for(int i=0; i<N; i++) { Matrix[i] = (float*)malloc(N*sizeof(float)); } for(int i=0; i<N; i++) { for(int j=0; j<N; j++) { Matrix[i][j] = (float)((rand()%(100)))+(float)(rand()%101)/101; } } return Matrix; } //㷨 float **LUAlgorithm(float **Matrix, int N) { float **Matrix1; Matrix1=(float**)malloc(N*sizeof(float*)); for(int i=0; i<N; i++) { Matrix1[i] = (float*)malloc(N*sizeof(float)); } //LU for(int k=0; k<N; k++) { for(int j=k+1; j<N; j++) { Matrix1[k][j] = Matrix[k][j]/Matrix[k][k]; } Matrix1[k][k] = 1; for(int i=k+1; i<N; i++) { for(int j=k+1; j<N; j++) { Matrix1[i][j] = Matrix[i][j] - Matrix[i][k]*Matrix[k][j]; } Matrix1[i][k] = 0; } } return Matrix1; } //SSE float ** LUAlgorithmSSE(float **Matrix, int N) { float **Matrix1; Matrix1=(float**)malloc(N*sizeof(float*)); for(int i=0; i<N; i++) { Matrix1[i] = (float*)malloc(N*sizeof(float)); } //use SSE //LU __m128 a,a1,a2; __m128 x; for(int k=0;k<N;k++){ int quotient = (N-k-1)/4; int remainder = (N-k-1)%4; float tmp1[4] = {Matrix[k][k], Matrix[k][k], Matrix[k][k], Matrix[k][k]}; x = _mm_loadu_ps(tmp1); for(int j=k+1;j<N-remainder;j=j+4){ a = _mm_loadu_ps(Matrix[k]+j); a1 = _mm_div_ps(a,x); _mm_storeu_ps(Matrix1[k]+j,a1); } for(int j=k+1+4*quotient;j<N;j++){ Matrix1[k][j] = Matrix[k][j]/tmp1[0]; } Matrix1[k][k] = 1; for(int i=k+1;i<N;i++){ float tmp2[4] = {Matrix[i][k], Matrix[i][k], Matrix[i][k], Matrix[i][k]}; x = _mm_loadu_ps(tmp2); for(int j=k+1;j<N-remainder;j=j+4){ a = _mm_loadu_ps(Matrix[i]+j); a1 = _mm_loadu_ps(Matrix[k]+j); a2 = _mm_sub_ps(a, _mm_mul_ps(x, a1)); _mm_storeu_ps(Matrix1[i]+j, a2); } for(int j=k+1+4*quotient;j<N;j++){ Matrix1[i][j] = Matrix[i][j] - tmp2[0]*Matrix[k][j]; } Matrix1[i][k] = 0; } } return Matrix1; } //ݻ̷ֵ߳ void *calculate(void *parm) { threadParm_t *p = (threadParm_t *)parm; int k = p->k; int N = p->N; int quotient = p->quotient; int remainder = p->remainder; int thread = p->thread; float **Matrix = p->Matrix; float **Matrix1 = p->Matrix1; int i = k+1+thread; __m128 a,a1,a2; __m128 x; float tmp2[4] = {Matrix[i][k], Matrix[i][k], Matrix[i][k], Matrix[i][k]}; x = _mm_loadu_ps(tmp2); for(int j=k+1; j<N-remainder; j=j+4) { a = _mm_loadu_ps(Matrix[i]+j); a1 = _mm_loadu_ps(Matrix[k]+j); a2 = _mm_sub_ps(a, _mm_mul_ps(x, a1)); _mm_storeu_ps(Matrix1[i]+j, a2); } for(int j=k+1+4*quotient; j<N; j++) { Matrix1[i][j] = Matrix[i][j] - tmp2[0]*Matrix[k][j]; } Matrix1[i][k] = 0; } //ݻPthreadLU㷨 float ** LUAlgorithmSSEandPthread(float **Matrix, int N) { float **Matrix1; Matrix1=(float**)malloc(N*sizeof(float*)); for(int i=0; i<N; i++) { Matrix1[i] = (float*)malloc(N*sizeof(float)); } //use SSE //LU __m128 a,a1,a2; __m128 x; for(int k=0; k<N; k++) { int quotient = (N-k-1)/4; int remainder = (N-k-1)%4; float tmp1[4] = {Matrix[k][k], Matrix[k][k], Matrix[k][k], Matrix[k][k]}; x = _mm_loadu_ps(tmp1); for(int j=k+1; j<N-remainder; j=j+4) { a = _mm_loadu_ps(Matrix[k]+j); a1 = _mm_div_ps(a,x); _mm_storeu_ps(Matrix1[k]+j,a1); } for(int j=k+1+4*quotient; j<N; j++) { Matrix1[k][j] = Matrix[k][j]/tmp1[0]; } Matrix1[k][k] = 1; int thread; pthread_t* thread_handles; int thread_count = N-k-1; thread_handles = malloc(thread_count*sizeof(pthread_t)); threadParm_t threadParm[thread_count]; for(int i=0; i<thread_count; i++) { threadParm[i].k = k; threadParm[i].N = N; threadParm[i].quotient = quotient; threadParm[i].remainder = remainder; threadParm[i].Matrix = Matrix; threadParm[i].Matrix1 = Matrix1; } for (thread = 0; thread < thread_count; thread++) { threadParm[thread].thread = thread; pthread_create(&thread_handles[thread], NULL, calculate, (void *)&threadParm[thread]); } for (thread = 0; thread < thread_count; thread++) { pthread_join(thread_handles[thread], NULL); } free(thread_handles); } return Matrix1; } //ѭ̷ֵ߳ void *calculate2(void *parm) { threadParm_t2 *p = (threadParm_t2 *)parm; int k = p->k; int N = p->N; int remainder = p->remainder; int quotient = p->quotient; int thread = p->thread; int thread_count = p->thread_count; float **Matrix = p->Matrix; float **Matrix1 = p->Matrix1; int seg = (N-k-1)/thread_count+1; __m128 a,a1,a2; __m128 x; for(int i=k+1; i<N; i++) { if((i-k-1)%seg == thread) { float tmp2[4] = {Matrix[i][k], Matrix[i][k], Matrix[i][k], Matrix[i][k]}; x = _mm_loadu_ps(tmp2); for(int j=k+1; j<N-remainder; j=j+4) { a = _mm_loadu_ps(Matrix[i]+j); a1 = _mm_loadu_ps(Matrix[k]+j); a2 = _mm_sub_ps(a, _mm_mul_ps(x, a1)); _mm_storeu_ps(Matrix1[i]+j, a2); } for(int j=k+1+4*quotient; j<N; j++) { Matrix1[i][j] = Matrix[i][j] - tmp2[0]*Matrix[k][j]; } Matrix1[i][k] = 0; } } } //ѭPthreadLU㷨 float ** LUAlgorithmSSEandPthread2(float **Matrix, int N, int thread_count) { float **Matrix1; Matrix1=(float**)malloc(N*sizeof(float*)); for(int i=0; i<N; i++) { Matrix1[i] = (float*)malloc(N*sizeof(float)); } //use SSE //LU __m128 a,a1,a2; __m128 x; //̶Ŀ߳ int thread; pthread_t* thread_handles; pthread_barrier_t barrier;//ȥ thread_handles = malloc(thread_count*sizeof(pthread_t)); for(int k=0; k<N; k++) { int quotient = (N-k-1)/4; int remainder = (N-k-1)%4; float tmp1[4] = {Matrix[k][k], Matrix[k][k], Matrix[k][k], Matrix[k][k]}; x = _mm_loadu_ps(tmp1); for(int j=k+1; j<N-remainder; j=j+4) { a = _mm_loadu_ps(Matrix[k]+j); a1 = _mm_div_ps(a,x); _mm_storeu_ps(Matrix1[k]+j,a1); } for(int j=k+1+4*quotient; j<N; j++) { Matrix1[k][j] = Matrix[k][j]/tmp1[0]; } Matrix1[k][k] = 1; threadParm_t2 threadParm[thread_count]; pthread_barrier_init(&barrier, NULL, thread_count);//ȥ for(int i=0; i<thread_count; i++) { threadParm[i].k = k; threadParm[i].N = N; threadParm[i].quotient = quotient; threadParm[i].remainder = remainder; threadParm[i].Matrix = Matrix; threadParm[i].Matrix1 = Matrix1; threadParm[i].thread_count = thread_count; } for (thread = 0; thread < thread_count; thread++) { threadParm[thread].thread = thread; pthread_create(&thread_handles[thread], NULL, calculate2, (void *)&threadParm[thread]); } for (thread = 0; thread < thread_count; thread++) { pthread_join(thread_handles[thread], NULL); } pthread_barrier_destroy(&barrier);//ȥ } free(thread_handles); return Matrix1; }
C
/* * fd_seri.c * Written by SW. YOON */ #include<stdio.h> #include<fcntl.h> #include<sys/socket.h> int main(void) { int fdes1, fdes2, fdes3; fdes1 = socket(PF_INET, SOCK_STREAM, 0); //소켓 생성 fdes2 = open("test.dat",O_CREAT); fdes3 = socket(PF_INET, SOCK_DGRAM, 0); printf("첫번째 파일 디스크립터 : %d\n", fdes1); printf("두번째 파일 디스크립터 : %d\n", fdes2); printf("세번째 파일 디스크립터 : %d\n", fdes3); close(fdes1); close(fdes2); close(fdes3); return 0; }
C
#include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <stdint.h> #include "forksrv.h" int main(int argc, char *argv[]) { int ctl[2], st[2]; pipe(ctl); pipe(st); pid_t chld = fork(); if (!chld) { /* Child process */ dup2(ctl[0], FD_CTL_READ_END); dup2(st[1], FD_ST_WRITE_END); close(ctl[0]); close(ctl[1]); close(st[0]); close(st[1]); char *execve_arg[] = { "./hello", NULL }; execve(execve_arg[0], execve_arg, NULL); } /* Parent process */ close(ctl[0]); close(st[1]); int32_t status; if ((read(st[0], &status, 4)) != 4) { fprintf(stderr, "[-] The wrong length of read of sanity check message!\n"); _exit(1); } for (int i = 0; i < 10; i++) { /* Tell child to fork */ int32_t prev_timed_out = 0; if ((write(ctl[1], &prev_timed_out, 4)) != 4) { fprintf(stderr, "[-] Failed to write fork order message!\n"); _exit(1); } printf("[+] Wrote fork order message #%d\n", i); if ((read(st[0], &chld, 4)) != 4) { fprintf(stderr, "[-] Failed to read grdchld PID!\n"); _exit(1); } if ((read(st[0], &status, 4)) != 4) { fprintf(stderr, "[-] Failed to read grdchld process status!\n"); _exit(1); } if (WIFEXITED(status)) printf("[+] Grdchld process exited with status %d\n", WEXITSTATUS(status)); } }
C
#include <stdio.h> #include <stdlib.h> #include <locale.h> #include "fila.c" int main (){ setlocale (LC_ALL,"Portuguese"); Fila *filaptr; int nome,aux,aux2,i; filaptr = Criafila(); if (filaptr == NULL){ printf("\nOcorreu um erro"); return 0; } else { printf("\nO endereo da fila criada : %p\n", filaptr); } system("pause"); system("cls"); printf("Digite quantos elementos deseja inserir: "); scanf("%d",&aux); system("cls"); while (aux > 10){ printf("NMERO MXIMO PERMITIDO: 10\n"); printf("Digite quantos elementos deseja inserir: "); scanf("%d",&aux); system("cls"); } for (aux2 = 0; aux2 < aux; aux2++){ printf("Digite o valor a ser inserido: "); scanf("%d",&nome); insereValor(filaptr,nome); } imprimeFila(filaptr); system("cls"); printf("\nO endereo da fila criada : %p\n", filaptr); for (i = filaptr->frente; i < filaptr->tras; i++) printf("\nO endereo : %p\n", filaptr); system("pause"); return 0; }
C
#include "/players/pavlik/guild/defs.h"; #define NOTES "players/pavlik/guild/log/bboard_notes" string messages; string new_hd; string new_body; int num_messages; object who; id(str) { return str == "bboard" || str == "board"; } short() { return "The Message Board ["+num_messages+"]"; } long() { write( "A small message board is present here for members of the guild to\n"+ "write notes. The messages are tacked neatly onto the board with\n"+ "little tacks. If you would like to post a note on this board, use\n"+ "'note <subject>'. Please be considerate with the contents of your\n"+ "messages. Only wizards can remove notes from this board.\n"); if (num_messages == 0) { write("There are no notes at this time.\n"); return; } if(num_messages == 1) write("There is 1 message.\n"); else write("There are "+num_messages+" notes at this time.\n"); headers(); } get() { return 0; } init() { add_action("new"); add_verb("note"); add_action("read"); add_verb("read"); add_action("remove"); add_verb("remove"); } reset(arg) { if(arg) return; restore_object(NOTES); } headers() { string hd, body, rest; int i, tmp; if(this_player()->query_guild_name() != "meijin") { write("You cannot make any sense of it.\n"); return 1; } i = 1; rest = messages; while(rest != 0 && rest != "") { tmp = sscanf(rest, "%s:\n**\n%s\n**\n%s", hd, body, rest); if (tmp != 2 && tmp != 3) { write("Corrupt.\n"); return; } write("["+i+"] "+hd+"\n"); i += 1; } } new(hd) { if(!hd) return 0; if(who && environment(who) == environment(this_object())) { write(call_other(who, "query_name") + " is busy writing.\n"); return 1; } if (strlen(hd) > 50) { write("Too long header to fit the paper.\n"); return 1; } new_hd = hd; input_to("get_body"); write("Sciribing new note. End note with '**'.\n"); write("]"); new_body = ""; return 1; } get_body(str) { if(str == "**") { string wday,surplus,month,day; int number; sscanf(ctime(time()),"%s %s %s %d:%s",wday,month,day,number,surplus); new_hd = wday+" "+month+" "+day+"\t | "+new_hd+ " ("+capitalize(this_player()->query_real_name()) +")"; messages = messages + new_hd + ":\n**\n" + new_body + "\n**\n"; num_messages += 1; new_body = 0; new_hd = 0; save_object(NOTES); write("Ok.\n"); who = 0; return; } new_body = new_body + str + "\n"; write("]"); input_to("get_body"); } read(str) { string hd, body, rest; int i, tmp; if(str == 0 || (sscanf(str, "%d", i) != 1 && sscanf(str, "note %d", i) != 1)) return 0; if(i > num_messages) { write("There are not that many messages on the board.\n"); return 1; } rest = messages; while(rest != 0 && rest != "") { i -= 1; tmp = sscanf(rest, "%s:\n**\n%s\n**\n%s", hd, body, rest); if (tmp != 2 && tmp != 3) { write("Corrupt.\n"); return; } if (i == 0) { say(call_other(this_player(), "query_name") + " reads an entry titled '" + hd + "'.\n"); write("The entry is titled '" + hd + "':\n\n"); write(body); return 1; } } write("Hm. This should not happen.\n"); } remove(str) { string hd, body, rest,contname; int i, tmp; contname=this_player()->query_real_name(); if(this_player()->query_level() < 21) { write("You cannot remove a notice from this board.\n"); return 1; } if (str == 0 || (sscanf(str, "%d", i) != 1 && sscanf(str, "note %d", i) != 1)) return 0; if (i > num_messages) { write("Not that number of messages.\n"); return 1; } rest = messages; messages = ""; while(rest != 0 && rest != "") { i -= 1; tmp = sscanf(rest, "%s:\n**\n%s\n**\n%s", hd, body, rest); if (tmp != 2 && tmp != 3) { write("Corrupt.\n"); return; } if (i == 0) { say(call_other(this_player(), "query_name") + " removed a note titled '" + hd + "'.\n"); write("Ok.\n"); messages = messages + rest; num_messages -= 1; save_object(NOTES); return 1; } messages = messages + hd + ":\n**\n" + body + "\n**\n"; } write("Hm. This should not happen.\n"); }
C
#include <event2/event.h> #include <stdio.h> #include <stdlib.h> #include <signal.h> void sigint_event_function(evutil_socket_t fd, short sig_num, void *arg) { struct event_base *base = (struct event_base *)arg; printf("Caught signal %d\n", sig_num); event_base_loopexit(base, NULL); } int main(int argc, char **argv) { struct event *sigint_event; struct event_base *base = event_base_new(); sigint_event = evsignal_new(base, SIGINT, sigint_event_function, base); event_add(sigint_event, NULL); event_base_dispatch(base); }
C
int min(int A[],int k,int N) { int LOC,j; int MIN=A[k]; LOC=k; for(j=k+1;j<=N-1;j++) { if(MIN>A[j]) { MIN=A[j]; LOC=j; } } return LOC; } void main() { int A[]={33,11,66,88,98,77,44,56,22,1}; int LOC,i,k,temp; for(k=0;k<=8;k++) { LOC=min(A,k,10); temp=A[k]; A[k]=A[LOC]; A[LOC]=temp; } //display the value of array for(k=0;k<=9;k++) { printf("%d,",A[k]); } }
C
#include "headers.h" int builtin_history(char **args, int arg_count) { if (arg_count > 2) { fprintf(stderr, "Too many arguments\n"); return EXIT_FAILURE; } FILE *fp = fopen(PATH_TO_HISTORY_FILE, "r"); if (fp == NULL) { perror("fopen() error"); return EXIT_FAILURE; } char *content = (char *)malloc(sizeof(char) * MAX_HISTORY_FILE_LEN); if (content == NULL) { fprintf(stderr, "Error allocating memory"); fclose(fp); return EXIT_FAILURE; } fseek(fp, 0, SEEK_END); unsigned long len = (unsigned long)ftell(fp); rewind(fp); fread(content, len, 1, fp); content[len] = '\0'; char *token = strtok(content, "\n"); long num = 0; char *end = NULL; num = strtol(token, &end, 10); if (end == token) { fprintf(stderr, "Not an integer argument\n"); return EXIT_FAILURE; } if ((num > INT_MAX) || (num < 0)) { fprintf(stderr, "Number out of range\n"); return EXIT_FAILURE; } int cnt = (int)num; int iter = cnt; if (arg_count == 2) { int temp = 0; num = strtol(args[1], &end, 10); if (end == args[1]) { fprintf(stderr, "Not an integer argument\n"); return EXIT_FAILURE; } if ((num > INT_MAX) || (num < 0)) { fprintf(stderr, "Number out of range\n"); return EXIT_FAILURE; } temp = (int)num; if (cnt > temp) { cnt = temp; } } token = strtok(NULL, "\n"); while (token != NULL && iter != 0) { if (iter <= cnt) { printf("%s\n", token); } token = strtok(NULL, "\n"); --iter; } free(content); fclose(fp); return EXIT_SUCCESS; } int add_to_history(char *cmd) { FILE *fp = fopen(PATH_TO_HISTORY_FILE, "r"); if (fp == NULL) { perror("fopen() error"); return EXIT_FAILURE; } char *content = (char *)malloc(sizeof(char) * MAX_HISTORY_FILE_LEN); if (content == NULL) { fprintf(stderr, "Error allocating memory"); fclose(fp); return EXIT_FAILURE; } char *num = (char *)malloc(sizeof(char) * 5); if (num == NULL) { fprintf(stderr, "Error allocating memory"); fclose(fp); return EXIT_FAILURE; } char *first_cmd = (char *)malloc(sizeof(char) * BUFFER_SIZE); if (first_cmd == NULL) { fprintf(stderr, "Error allocating memory"); fclose(fp); return EXIT_FAILURE; } char *rest_cmds = (char *)malloc(sizeof(char) * MAX_HISTORY_FILE_LEN); if (rest_cmds == NULL) { fprintf(stderr, "Error allocating memory"); fclose(fp); return EXIT_FAILURE; } fseek(fp, 0, SEEK_END); unsigned long len = (unsigned long)ftell(fp); rewind(fp); if (len > 0) { fread(content, len, 1, fp); content[len] = '\0'; } else { strcpy(content, "0\n"); } char *token = strtok(content, "\n"); strcpy(num, token); token = strtok(NULL, "\n"); if (token != NULL) { strcpy(first_cmd, token); token = strtok(NULL, "\0"); if (token != NULL) { strcpy(rest_cmds, token); token = strtok(NULL, "\0"); } } fp = freopen(NULL, "w", fp); long n = 0; char *end = NULL; n = strtol(num, &end, 10); if (end == num) { fprintf(stderr, "Not an integer argument\n"); return EXIT_FAILURE; } if ((n > INT_MAX) || (n < 0)) { fprintf(stderr, "Number out of range\n"); return EXIT_FAILURE; } int no = (int)n; if (no == MAX_COMMANDS_STORED) { fprintf(fp, "%s\n%s\n%s", num, rest_cmds, cmd); } else { no++; if (no == 1) { fprintf(fp, "%d\n%s", no, cmd); } else if (no == 2) { fprintf(fp, "%d\n%s\n%s", no, first_cmd, cmd); } else { printf("%s\n", cmd); fprintf(fp, "%d\n%s\n%s\n%s", no, first_cmd, rest_cmds, cmd); } } free(num); free(first_cmd); free(rest_cmds); fclose(fp); return EXIT_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> /*Write the program tail, which prints the last n lines of its input. By default, n is 10, lets us say, but it can be changed by an optional argument, so that tail -n prints the last n lines. Write the program so it makes the best use of available storage. */ #define DEFAULTN 10 //default n #define MAXLEN 100 //max len of line #define LINEMAX 100 //max # of lines to print int get_line(char *line, int maxline); void error(char *error_line); void tail_n(char *line, int N); int main(int argc, char *argv[]){ int N; char line[MAXLEN]; // i want to know if a have a argument command or if i need to use my default if (argc <= 1){ N = DEFAULTN; } else if (argc == 2 && (*++argv)[1] == '-'){ //N = atoi(*++argv); N = atoi(argv[0]+1); } else{ error("Usage: tail [-n]"); } tail_n(line, N); return 0; } void error(char *error_line){ printf("%s\n", error_line); } int get_line(char *line, int maxline){ int input, i; for (i = 0; i < maxline - 1 && (input = getchar()) != EOF && input != '\n'; ++i){ line[i] = input; } if (input == '\n'){ line[i] = input; } line[i] = '\0'; return i; } /* print n lines of its input */ void tail_n(char *line, int N){ //Initialize variables int i, count_lines, len; int first_line, last_line; char *p; // pointer to keep track of size needded char *ptrarray[LINEMAX]; // array pointer to each string char *buffer; // size buffer char *buff_end; //boundaries: is a valid N? if (N < 1 || N > LINEMAX){ N = LINEMAX; } //Initialize array ptr to NULL for (i = 0; i < LINEMAX; ++i){ ptrarray[i] = NULL; } //boundaries: Is the buffer big enough? if ((p = buffer = malloc(LINEMAX * MAXLEN)) == NULL){ error("tail: cannot allocate buffer"); } buff_end = buffer + LINEMAX * MAXLEN; last_line = 0; count_lines = 0; //Start walking through the lines while ((len = get_line(line, MAXLEN)) > 0){ // for each read line allocate space in the buffer // check if len of line is not greater than buffer if ((p + len + 1) >= buff_end){ p = buffer; // reset pointer to the start of buffer } //put size to line ptr ptrarray[last_line] = p; //copy from line to ptr array strcpy(ptrarray[last_line], line); ++last_line; //check if the last line doesn't pass over the MAX LINE if (last_line > LINEMAX){ last_line = 0; // reset last_line } p += len + 1; // last line size //count lines ++count_lines; } // check if the N given is greater than number of lines input if (N > count_lines){ N = count_lines; } // where should start printing first_line = last_line - N; // check if you wrap around the list if (first_line < 0){ first_line += LINEMAX; } // printf n last lines // the modulus operator mantain i between first_line and LINEMAX for (i = first_line; N-- > 0; i = (i + 1) % LINEMAX){ printf("%s\n", ptrarray[i]); } }
C
#include<stdio.h> #include<string.h> int main() { int i,n,j; char str1[50]; printf("Enter the string\n"); gets(str1); puts(str1); n=strlen(str1); for(i=0;i<n;i++) { if(str1[i]==' ') { for(j=i;j<n;j++) { str1[j]=str1[j+1]; } n--; } } printf("String after removal of spaces is %s\n",str1); return(0); }
C
/** \file constants.h * Файл определяет константы, необходимые для работы программы */ #ifndef SATELLITE_PROPAGATION_CONSTANTS_H #define SATELLITE_PROPAGATION_CONSTANTS_H #include <math.h> #define SEC_IN_DAY 86400.000000000000000000000 ///< Число секунд в дне #define JULIAN_C 36525.00000000000000000000000 ///< Дней в юлианском столетии #define DIFF_EPOCH 2400000.5000000000000000000 #define MJD2000 51544.500000000000000000000000 ///< Эпоха J2000 в модифицированных юлианских днях #define PI2 6.2831853071795862319959269370883703 ///< 2π #define GRAD_IN_RAD 0.017453292519943295088124656649908317 ///< Кол-во радиан в одном градусе #define SEC_IN_RAD 4.8481368110953597467454098131995829e-06 ///< Кол-во радиан в одной секунде #define AU 149597870.69100000000000000000000000 ///< 1 а.е. /* Параметры Земли */ extern long double FM; ///< Геоцентрическая гравитационная постоянная [км^3 / с^2] extern long double R0; ///< Экваториальный радиус Земли [км] extern long double A0; ///< Полярное сжатие Земли /** * Устанавливает значение геоцентрической гравитационной постоянной [км^3 / с^2] * * @param[in] fm Значение геоцентрической гравитационной постоянной [км^3 / с^2] * */ void set_FM(long double fm); /** * Устанавливает значение экваториального радиуса Земли [км] * * @param[in] r0 Значение экваториального радиуса Земли [км] * */ void set_R0(long double r0); /** * Устанавливает значение полярного сжатия Земли * @param[in] a0 Значение полярного сжатия Земли * */ void set_A0(long double a0); /* Гравитационные постоянные */ extern long double FM_M; ///< Гравитационная постоянная на массу Луны [км^3 / с^2] extern long double FM_S; ///< Гравитационная постоянная на массу Солнца [км^3 / с^2] extern long double P0; ///< Давление солнечного света на среднем расстоянии Земли от Солнца [н / м^2] /** * Устанавливает значение Гравитационной постоянной на массу Луны [км^3 / с^2] * * @param[in] fm_m Значение Гравитационной постоянной на массу Луны [км^3 / с^2] * */ void set_FM_M(long double fm_m); /** * Устанавливает значение Гравитационной постоянной на массу Солнца [км^3 / с^2] * * @param[in] fm_s Значение Гравитационной постоянной на массу Солнца [км^3 / с^2] * */ void set_FM_S(long double fm_s); /** * Устанавливает значение давления солнечного света на среднем расстоянии Земли от Солнца [н / м^2] * * @param[in] p0 Значение давления солнечного света на среднем расстоянии Земли от Солнца [н / м^2] * */ void set_P0(long double p0); /* Параметры КА */ extern long double AS; ///< Площадь поперечного сечения [м] extern long double MS; ///< Масса [кг] extern long double SB; ///< Баллистический коэффициент extern long double KR; ///< Эмпирический коэффициент отражения extern long double CREFL; ///< Коэффициент эффективного отражения [км/с^2] /** * Устанавливает значение площади поперечного сечения КА [м] * * @param[in] as Значение площади поперечного сечения КА [м] * */ void set_AS(long double as); /** * Устанавливает значение массы КА [кг] * * @param[in] ms Значение массы КА [кг] * */ void set_MS(long double ms); /** * Устанавливает значение эмпирического коэффициента отражения [1..2] * * @param[in] kr Значение эмпирического коэффициента отражения [1..2] * */ void set_KR(long double kr); /* Признаки задействования сил возмущения */ extern int USE_EARTH_FORCE; ///< Признак задействования ускорений, обусловленных Геопотенциалом Земли extern int USE_MOON_FORCE; ///< Признак задействования ускорений, обусловленных действием Луны extern int USE_SUN_FORCE; ///< Признак задействования ускорений, обусловленных действием Солнца extern int USE_SOLAR_FORCE; ///< Признак задействования ускорений, обусловленных действием Солнечного давления extern int USE_ATMOSPHERE_FORCE; ///< Признак задействования ускорений, обусловленных торможением атмосферы /** * Устанавливает признак задействования ускорений, обусловленных Геопотенциалом Земли * * @param[in] use Признак задействования. 0 - не задействовано, 1 - задействовано * */ void set_USE_EARTH_FORCE(int use); /** * Устанавливает признак задействования ускорений, обусловленных действием Луны * * @param[in] use Признак задействования. 0 - не задействовано, 1 - задействовано * */ void set_USE_MOON_FORCE(int use); /** * Устанавливает признак задействования ускорений, обусловленных действием Солнца * * @param[in] use Признак задействования. 0 - не задействовано, 1 - задействовано * */ void set_USE_SUN_FORCE(int use); /** * Устанавливает признак задействования ускорений, обусловленных действием Солнечного давления * * @param[in] use Признак задействования. 0 - не задействовано, 1 - задействовано * */ void set_USE_SOLAR_FORCE(int use); /** * Устанавливает признак задействования ускорений, обусловленных торможением атмосферы * * @param[in] use Признак задействования. 0 - не задействовано, 1 - задействовано * */ void set_USE_ATMOSPHERE_FORCE(int use); #endif //SATELLITE_PROPAGATION_CONSTANTS_H
C
// // main.c // Exercise 8 // // Created by Changheng Chen on 11/4/16. // Copyright © 2016 Changheng Chen. All rights reserved. // #include <stdio.h> int main() { int x=2; int y; int z; x*=3+2; printf("x=%d\n", x); // x = x*(3+2) = 2*(3+2) = 10 x*=y=z=4; printf("x=%d\n", x); // z = 4; y = z = 4; x = x*y = 10*4 = 40 x=y==z; printf("x=%d\n", x); // y==z (4==4) evaluates as 1; x = 1 }
C
#include "all_tests.h" #include "kernel.h" #include "syscall.h" #include "test_helpers.h" #include "priorities.h" static int flag; static int did_run; static int parent_tid; static int child_1_tid; static int child_2_tid; static void user_task3() { child_2_tid = MyTid(); int p_tid = MyParentTid(); assert_int_equals(parent_tid, p_tid, "Basic Test: Child_2 Check Parent Tid"); Exit(); } static void user_task2() { int tid = MyTid(); assert_int_equals(child_1_tid, tid, "Basic Test: Child Check Tid"); int p_tid = MyParentTid(); assert_int_equals(parent_tid, p_tid, "Basic Test: Child Check Parent Tid"); flag = 1; Exit(); } static void user_task() { did_run = 1; parent_tid = MyTid(); child_1_tid = Create(MED_PRI, &user_task2); int p_tid = MyParentTid(); assert_int_equals(-1, p_tid, "Basic Test: Parent Check Parent Tid"); Pass(); assert_int_equals(1, flag, "Basic Test: Parent Check Pass"); // Let child run first to test that the right return value is returned. int tid = Create(HI_PRI, &user_task3); assert_int_equals(child_2_tid, tid, "Basic Test: Parent Check Child_2 Tid"); Exit(); } void run_basic_test() { char* name = "Basic Test"; start_test(name); flag = 0; did_run = 0; kernel_add_task(MED_PRI, &user_task); kernel_run(); assert_int_equals(1, did_run, "Basic Test: User Program Never Ran"); end_test(name); }
C
#include "tree.h" #include <stdio.h> #include <stdlib.h> SearchTree InitTree(); int main(int argc, char *argv[]) { SearchTree tree = InitTree(); printf("High:%d\n", High(tree)); PrintTree(tree); printf("find 3 element position is %p \n", Find(6, tree)); printf("make empty tree\n"); tree = MakeEmpty(tree); PrintTree(tree); system("pause"); return 0; } SearchTree InitTree() { Position p1 = (Position)malloc(sizeof(struct TreeNode)); Position p2 = (Position)malloc(sizeof(struct TreeNode)); Position p3 = (Position)malloc(sizeof(struct TreeNode)); Position p4 = (Position)malloc(sizeof(struct TreeNode)); Position p5 = (Position)malloc(sizeof(struct TreeNode)); Position p6 = (Position)malloc(sizeof(struct TreeNode)); Position p7 = (Position)malloc(sizeof(struct TreeNode)); p1->Element = 1; p2->Element = 2; p3->Element = 3; p4->Element = 4; p5->Element = 5; p6->Element = 6; p7->Element = 7; p1->Left = p2; p1->Right = p3; p2->Left = p4; p2->Right = p5; p3->Left = p6; p3->Right = p7; p4->Left = NULL; p4->Right = NULL; p5->Left = NULL; p5->Right = NULL; p6->Left = NULL; p6->Right = NULL; p7->Left = NULL; p7->Right = NULL; return p1; }
C
#include<stdio.h> #include<conio.h> void main() { char s1[20],s2[20]; int i; clrscr(); printf("\n enter the two string\t"); scanf("%s%s",s1,s2); printf("\n %s%s",s1,s2); getch(); }
C
#include <stdio.h> #include <fcntl.h> #include <unistd.h> #include "dir_mutex.h" int readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) { int rc; if(pthread_mutex_lock(&dir_mutex) < 0) { perror("pthread_mutex_lock"); return -1; } if(fchdir(dirfd) < 0) { perror("fchdir"); goto err_unlock; } rc = readlink(pathname, buf, bufsiz); pthread_mutex_unlock(&dir_mutex); return rc; err_unlock: pthread_mutex_unlock(&dir_mutex); return -1; }
C
#include <stdio.h> /*Adding break statements to ex10*/ int main(int argc, char *argv[]) { int i = 0; //a string array! char *states[] = { "California", "Oregon", //NULL, it just prints (null) "Washington", "Texas" }; /* NULL is a value. It is the default value assigned to a pointer of a specific type. For example (int *) or (char *) have different NULL values assigned to them. Conceptually, NULLs signify pointers that don't point anywhere. They are used as markers, such as to mark the end of a linked list. */ argv[1] = states[2]; states[2] = argv[3]; //go through the string array argv, skipping script name for(i = 0; i < argc; i++) { printf("arg %d: %s\n", i, argv[i]); if(i > 2) { break; }; } //note this loop is skipped if no args are supplied /*if pushed past length of states, it shows (null) garbage (null) garbage, etc until a segfault*/ int num_states = 6; for(i = 0; i < num_states; i++) { printf("state %d: %s\n", i, states[i]); } int j = 0, k = 0, n = 9; for( /* int j = 0, int n = 9, k = 0; //initial declarations only allowed in c99 mode */ ; (j*j< n ) && k <= 5; printf ("k is now %d\n", k), k++, j++ ); return 0; }
C
#include<stdio.h> #include<time.h> int bin(int a[],int start ,int end,int key ) { int mid; mid =start +(end- start)/2; if (key==a[mid]) { printf("Emement found at %d",mid); } else if (a[mid] > key) { return bin (a,start,mid-1,key); } else { return bin(a,mid+1,end,key); } return -1; } void main() { int a[100]; int key,size,result; int startt,endt,tim; printf("Enter the size of array"); scanf("%d",&size); printf("Enter the elements"); for (int i=0;i<size;i++) { scanf("%d",&a[i]); } printf("KEY :"); scanf("%d",&key); startt=clock(); result=bin(a,0,size-1,key); endt=clock(); tim=endt-startt; if (result==-1) { printf("Element not found\n"); } else { printf("element found at %d\n",result); } printf("the time required is %d",tim); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <limits.h> /* Part A: Time Difference - STARTS */ /* Structure to input the time */ struct time{ int hours; int minutes; int seconds; }; /* function to convert the time in seconds */ int numSeconds(int hours, int minutes, int seconds){ int conversion_seconds; conversion_seconds = hours*60*60 + minutes*60 + seconds; return conversion_seconds; } /* function to convert the time in 24 hour format */ struct time conversion_24_hour_format(int seconds){ struct time time_difference_conversion; int rem_scds; time_difference_conversion.hours = seconds/3600; rem_scds = seconds%3600; time_difference_conversion.minutes = rem_scds/60; time_difference_conversion.seconds = rem_scds%60; return time_difference_conversion; } /* function to print the difference in two times */ struct time time_difference(struct time time1, struct time time2){ struct time difference_in_time; int difference_seconds; difference_seconds = numSeconds(time2.hours, time2.minutes, time2.seconds) - numSeconds(time1.hours, time1.minutes, time1.seconds); difference_in_time = conversion_24_hour_format(difference_seconds); return difference_in_time; } /* function to print the time in HH:MM:SS format */ void print_time(struct time input1, struct time input2){ struct time difference; difference = time_difference(input1,input2); printf("Difference between %02d:%02d:%02d ", input1.hours, input1.minutes, input1.seconds); printf("and %02d:%02d:%02d ", input2.hours, input2.minutes, input2.seconds); printf(" = %02d:%02d:%02d \n", difference.hours, difference.minutes, difference.seconds); } /* Part A: Time Difference - ENDS */ /* Part B: Time Difference - STARTS */ enum Months{ JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER }; char *month_array[12] = { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" }; struct dateTime{ enum Months month; int day; int year; /* Using the time struct */ struct time struct1; }; /* function to print the date and time */ void print_date_time(struct dateTime input_dttime){ printf("%s %02d %04d %02d:%02d \n", month_array[input_dttime.month], input_dttime.day, input_dttime.year, input_dttime.struct1.hours, input_dttime.struct1.minutes); } /* Part B: Time Difference - ENDS */ /* -------------- Part 2 -- Tournament STARTS ------------- */ struct Team{ char *team_name; int scores; int handicap; }; /* Function to generate ramdom number */ int random_number_generator(int range){ range = rand() %range + 1; return range; } /* Function to decide winner between two opponents */ struct Team* game(struct Team* team1, struct Team* team2){ printf(" %s v/s %s", team1->team_name, team2->team_name); team1->scores = random_number_generator(80); team2->scores = random_number_generator(80); // printf("Contender 1 : %s and Contender 2 : %s\n",team1->team_name,team2->team_name); // printf("Score - Team 1 = %d and Team 2 = %d\n",team1->scores,team2->scores); team1->handicap = random_number_generator(20); team2->handicap = random_number_generator(20); // printf("Handicap Contribution - Team 1 = %d and Team 2 = %d\n",team1->handicap,team2->handicap); team1->scores+=team1->handicap; team2->scores+=team2->handicap; // printf("Total Score - Team 1 = %d and Team 2 = %d\n",team1->scores,team2->scores); if(team1->scores > team2->scores){ printf(" \t%s\n",team1->team_name); return team1; }else{ printf(" \t%s\n",team2->team_name); return team2; } } /* Function for the tournament */ struct Team* tournament(struct Team* league[8]){ struct Team *contender1; struct Team *contender2; struct Team *winner; char* round2[4]; char* round3[2]; winner = (struct Team*)malloc(sizeof(struct Team)); contender1 = (struct Team*)malloc(sizeof(struct Team)); contender2 = (struct Team*)malloc(sizeof(struct Team)); int i,j,game_count; j=0; game_count=0; srand(time(0)); printf("Round 1 \n"); printf("Game\tParticipants\tWinner \n"); for(i=0;i<4;i++){ printf(" %d\t",++game_count); contender1->team_name = league[j]->team_name; contender2->team_name = league[++j]->team_name; winner = game(contender1,contender2); round2[i]=winner->team_name; j++; } printf("\nRound 2\n"); printf("Game\tParticipants\tWinner \n"); j=0,game_count=0; for(i=0;i<2;i++){ printf(" %d\t",++game_count); contender1->team_name = round2[j]; contender2->team_name = round2[++j]; winner = game(contender1,contender2); round3[i]=winner->team_name; j++; } printf("\nRound 3\n"); printf("Game\tParticipants\tWinner \n"); printf("Finale\t"); contender1->team_name = round3[0]; contender2->team_name = round3[1]; winner = game(contender1,contender2); return winner; } /* -------------- Part 2 -- Tournament ENDS ------------- */ int main(){ /* Part A: Time Difference - STARTS */ struct time time_input[10] = { {3,45,15}, {9,44,03}, {1,30,45}, {16,30,45}, {1,23,01}, {12,11,12}, {00,01,01}, {23,59,59}, {12,00,00}, {12,00,00} }; print_time(time_input[0], time_input[1]); print_time(time_input[2], time_input[3]); print_time(time_input[4], time_input[5]); print_time(time_input[6], time_input[7]); print_time(time_input[8], time_input[9]); /* Part A: Time Difference - ENDS */ /* Part B: Time Difference - STARTS */ struct dateTime datetime[3] = { {JANUARY,19,1809,{12,01,00}}, {NOVEMBER,11,1922,{6,00,00}}, {JANUARY,6,2000,{8,22,00}} }; printf("\n"); print_date_time(datetime[0]); print_date_time(datetime[1]); print_date_time(datetime[2]); /* Part B: Time Difference - ENDS */ /* Part 2 -- Tournament (Extra Credit) - START */ printf("\nTournament\n"); struct Team AA = {"AA"}; struct Team BB = {"BB"}; struct Team CC = {"CC"}; struct Team DD = {"DD"}; struct Team EE = {"EE"}; struct Team FF = {"FF"}; struct Team GG = {"GG"}; struct Team HH = {"HH"}; struct Team* league [8] = {&AA, &BB, &CC, &DD, &EE, &FF, &GG, &HH}; struct Team *winner; winner=tournament(league); printf("\nChampion\tScore\n"); printf("%8s\t", winner->team_name); printf("%2d\n", winner->scores); /* Part 2 -- Tournament (Extra Credit) - END */ return 0; }
C
#include <stdio.h> #include <string.h> char a[55]; int d[55]; int main(){ fgets(a, 55, stdin); a[strlen(a)-1]=0; for (int i=0; i<strlen(a); i++){ d[i]=1; for (int j=0; j<i; j++){ if(a[j]<a[i]) d[i]=d[i]>d[j]+1?d[i]:d[j]+1; } } int ans=0; for (int i=0; i<55; i++) ans=ans>d[i]?ans:d[i]; printf("%d\n", 26-ans); }
C
/* Colaberated with James Romerro Made for CPSC 380 By Cameron Wang Refernces: Class notes and examples */ #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <sys/ipc.h> int main(int argc, char * argv[]) { pid_t pid; FILE *input_file, *output_file; char file_buffer[255]; int smem_id; key_t smem_key = KEY_CODE; void *temp_ptr = (void *)0; struct shared_mem_struct *shared_mem; if(argc == 1)//basic error checking { printf("Error: Please provide input file name\n"); return 1; } if(argc != 2)//checks number of args { printf("Error: Incorrect number of arguments passed\n"); return 1; } initializeWait(); if ((pid = fork()) < 0)//check if fork worked { perror("fork"); return 1; } else if (pid != 0)//parent process starts here { if((input_file = fopen(argv[1],"r")) == NULL) { perror("fopen"); return 1; } if((smem_id = shmget(smem_key, sizeof(struct shared_mem_struct), IPC_CREAT | 0666))<0)//create shared memory { perror("shmget"); return 1; } if((temp_ptr = shmat(smem_id, (void *)0, 0)) == (void *)-1)//attempts to attatch shared memory and error checks { perror("shmat"); return 1; } shared_mem = (struct shared_mem_struct *) temp_ptr; shared_mem->count = 0; // Set the counter to 0 while(fgets(file_buffer, (MAX_BUF_SIZE-1), input_file) != NULL) { while(shared_mem->count != 0)//waits for child to consume all data out of shared memory { waitChild(); } strcpy(shared_mem->buffer,file_buffer); shared_mem->count = strlen(shared_mem->buffer); } initializeWait(); while(shared_mem->count != 0) { waitChild(); } shared_mem->count = -1; signalChild(pid); waitpid(pid, NULL, 0); fclose(input_file); if(shmdt(shared_mem) == -1) { perror("shmdt"); return 1; } if(shmctl(smem_id, IPC_RMID, 0) == -1) { perror("shmctl"); return 1; } printf("\nSuccess: The input file provided by you has been successfully copied via shared memory to output file named \"ouput.txt\" in the current working directory.\n\n"); } else//child process starts here { if((output_file = fopen("output.txt","w")) == NULL) { perror("fopen"); return 1; } if((smem_id = shmget(smem_key, sizeof(struct shared_mem_struct), IPC_CREAT | 0666))<0) { perror("shmget"); return 1; } if((temp_ptr = shmat(smem_id, (void *)0, 0)) == (void *)-1)//attempting to attatch shared memory and error checks { perror("shmat"); return 1; } shared_mem = (struct shared_mem_struct *) temp_ptr; while(shared_mem->count != -1) { while(shared_mem->count == 0) { waitParent(); } if(shared_mem->count != -1) { fputs(shared_mem->buffer, output_file);//takes everything read from shared memory to output file shared_mem->count = 0; signalParent(getppid()); } } fclose(output_file); if(shmdt(shared_mem) == -1) { perror("shmdt"); exit(EXIT_FAILURE) kill(getpid(), SIGTERM); } return 0; }
C
#include <stdlib.h> #include <stdio.h> struct node { int info; struct node *lchild; struct node *rchild; }; typedef struct node* NODE; NODE getNode() { NODE x; x=(NODE)malloc(sizeof(struct node)); return x; } NODE create_BT() { NODE temp; int ele; printf("Enter element(-1 for no data):\n"); scanf("%d",&ele); if(ele==-1) return NULL; temp=getNode(); temp->info=ele; printf("Enter left child of %d\n",ele); temp->lchild=create_BT(); printf("Enter right child of %d\n",ele); temp->rchild=create_BT(); return temp; } int max(int a, int b){ return (a>b)?a:b; } int getHeight(NODE t){ if(t == NULL) return 0; return 1 + max(getHeight(t->lchild), getHeight(t->rchild)); } int getDiam(NODE t){ if(t == NULL) return 0; int l_h = getHeight(t->lchild); int r_h = getHeight(t->rchild); int l_d = getDiam(t->lchild); int r_d = getDiam(t->rchild); return max(l_h + r_h + 1, max(l_d, r_d)); } void main() { NODE root; root=create_BT(); printf("Diam = %d\n", getDiam(root)); }
C
#include <stdio.h> #include <unistd.h> // i *= 2 means i = i*2, we are squaring i int main(){ for(int i = 1; ; i*=2){ printf("%i\n", i); sleep(1); } } // can stop a loop with control-C
C
#ifndef LISTA_H #define LISTA_H typedef struct node { char peca; int indice; struct node *proximo; struct node *anterior; } node_t; typedef struct { int num_elementos; node_t *inicio; node_t *fim; } lista_t; lista_t *cria_lista(); void insere_final(lista_t *lista, char letra); void insere_meio(lista_t *lista, char letra, int i); void destroi_lista(lista_t *lista); void imprime_lista(lista_t *lista); char remover_elemento(lista_t *lista, int i); char remover_inicio(lista_t *lista); #endif
C
#include "cs165_api.h" #include "hashjoin.h" #define HASH_TABLE_SIZE 128000 ht_node *hash_table[HASH_TABLE_SIZE]; int hash(data n) { return n % HASH_TABLE_SIZE; } void add_to_ht(int pos, data val) { int bucket = hash(val); ht_node *new = malloc(sizeof(ht_node)); new->pos = pos; new->val = val; new->next = hash_table[bucket]; hash_table[bucket] = new; } void free_bucket(ht_node *n) { if (n == NULL) return; free_bucket(n->next); free(n); } void destroy_ht(void) { for (int i = 0; i < HASH_TABLE_SIZE; i++) { free_bucket(hash_table[i]); hash_table[i] = NULL; } } void hashjoin(vector **r1, vector **r2, vector *pos1, vector *val1, vector *pos2, vector *val2) { *r1 = create_vector(0); *r2 = create_vector(0); // Assumes pos1->length < pos2->length for (size_t i = 0; i < pos1->length; i++) add_to_ht(pos1->buf[i], val1->buf[i]); for (size_t i = 0; i < pos2->length; i++) { int bucket = hash(val2->buf[i]); for (ht_node *cur = hash_table[bucket]; cur != NULL; cur = cur->next) { vector_insert(cur->pos, *r1); vector_insert(pos2->buf[i], *r2); } } destroy_ht(); }
C
/*Guillermo Ortega Romo 14/10/17*/ #include<stdio.h> #include<stdlib.h> #include<time.h> #include<unistd.h> int dado(); int main() { srand(time(0)); int p1=0, p2=0; int q1=0, q2=0; int j1, j2; printf("Tiros de dado\n\n"); printf("| Tiro |Jugador 1|Jugador 2|\n"); for(int i=0;i<20;i++) { j1=dado(); j2=dado(); printf("| %2d | %2d | %2d |\n",i,j1,j2); switch (j1) { case 5: p1++; break; case 6: q1++; break; default: break; } switch (j2) { case 5: p2++; break; case 6: q2++; break; default: break; } usleep(100000); } if(p1>p2 && q1<p1) { printf("El jugador 1 gana\n"); printf("Puntaje: p1 %d veces 5, %d veces 6; p2 %d veces 5, %d veces 6\n", p1, q1, p2, q2); } else if(p1<p2 && q2<p2) { printf("El jugador 2 gana\n"); printf("Puntaje: p1 %d veces 5, %d veces 6; p2 %d veces 5, %d veces 6\n", p1, q1, p2, q2); } else { printf("Empate\n"); printf("Puntaje: p1 %d veces 5, %d veces 6; p2 %d veces 5, %d veces 6\n", p1, q1, p2, q2); } } int dado() { return(rand() % 6) + 1; }