language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include<iostream> using namespace std; class A { private: int x,y; public: void setdata(int x,int y) { this->x=x,this->y=y; } int modify() { x=-x,y=-y; return *this; } void print() { cout<<"x="<<this->x<<"y="<<this->y<<endl; } }; int main() { A obj1,obj2; obj1.setdata(12,33); obj2=obj1.modify(); cout<<"obj1 data:"<<endl; obj1.print(); cout<<"obj2 data:"<<endl; obj2.print(); }
C
#include "ucode.c" #define BLKSIZE 1024 int main(int argc, char *argv[ ]) { char buf[1024]; int n,i; int fd = open(argv[1], O_RDONLY); creat(argv[2]); int gd = open(argv[2], O_WRONLY); while (n = read(fd, buf, BLKSIZE)) { for (i = 0; i < n; i++) { if (buf[i] >= 'a' && buf[i] <= 'z') buf[i] = buf[i]+('A'-'a'); } write(gd, buf, n); } close(fd); close(gd); }
C
// ------------------------------------------------------------------ // exemple-sigaction-3.c // Fichier d'exemple du livre "Developpement Systeme sous Linux" // (C) 2000-2019 - Christophe BLAESS <christophe@blaess.fr> // https://www.blaess.fr/christophe/ // ------------------------------------------------------------------ #include <signal.h> #include <stdio.h> #include <stdlib.h> void signal_handler(int unused) { } int main (void) { struct sigaction action; signal(SIGUSR1, signal_handler); sigaction(SIGUSR1, NULL, &action); if (action.sa_handler == signal_handler) fprintf(stdout, "same address\n"); else fprintf(stdout, "different address\n"); return EXIT_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <conio.h> #include <string.h> #include "arrayEmployess.h" #include "validaciones.h" #define EMPTY 1 #define OCCUPIED 0 int initEmployees(Employee* employees, int lengthEmp) { int i; for(i=0; i<lengthEmp; i++) { employees[i].isEmpty=EMPTY; } return 0; } int mainMenu() { int option; char auxOption[3]; system("cls"); printf("MENU\n\n"); printf("1- Alta empleado\n"); printf("2- Modificacion empleado\n"); printf("3- Baja empleado\n"); printf("4- Informes\n"); printf("5- Salir\n\n"); printf("Ingrese option: "); scanf("%s",auxOption); if(isInt(auxOption)==0) { printf("->Solo numeros<-"); system("pause"); } else { option=atoi(auxOption); } return option; } int addEmployee(Employee* employees, int lengthEmp, int id, char name[],char lastName[],float salary,int sector) { int validation=0; int index; index=findEmptyIndex(employees,lengthEmp); employees[index].id=id; strcpy(employees[index].name,name); strcpy(employees[index].lastName,lastName); employees[index].salary=salary; employees[index].sector=sector; employees[index].isEmpty=OCCUPIED; system("cls"); printf("*** EMPLEADO A DAR DE ALTA ***\n\n"); printf("%8s %12s %12s %12s %12s\n", "Legajo", "Sector", "Nombre", "Apellido", "Sueldo"); printEmployee(employees[index]); printf("\nAlta efectuada\n\n"); return validation; } int getRandomId(Employee* employees, int lengthEmp, int* requestedRandomId) { int firstRandomId=1000; int index; int validation=-1; index=findEmptyIndex(employees,lengthEmp); if(index>=0) { *requestedRandomId=firstRandomId+index; validation=0; } return validation; } int findEmptyIndex(Employee* employees, int lengthEmp) { int index=-1; int i; for(i=0; i<lengthEmp; i++) { if(employees[i].isEmpty==1) { index=i; break; } } return index; } int findEmployeeById(Employee* employees, int lengthEmp,int id) { int index=-1; int i; for(i=0; i<lengthEmp; i++) { if(employees[i].id==id) { index=i; } } return index; } int removeEmployee(Employee* employees, int lengthEmp) { int idEmployee; int validation=0; int index; char confirm; printEmployees(employees,lengthEmp); printf("Ingrese legajo del empleado a eliminar: "); scanf("%d",&idEmployee); index=findEmployeeById(employees,lengthEmp,idEmployee); if(index==-1) { printf("No se ha encontrado al empleado\n"); system("pause"); validation=-1; } else { system("cls"); printf("*** EMPLEADO A ELIMINAR ***\n\n"); printf("%8s %12s %12s %12s %12s\n", "Legajo", "Sector", "Nombre", "Apellido", "Sueldo"); printEmployee(employees[index]); printf("Confirma eliminacion?\n"); fflush(stdin); printf("Ingrese s/n: "); scanf("%c",&confirm); if(confirm=='s') { employees[index].isEmpty=EMPTY; validation=0; printf("\nBaja efectuada\n\n"); } else { validation=-1; } } return validation; } int modifyMenu() { int option; system("cls"); printf("Que desea modificar?\n"); printf("1- Nombre\n"); printf("2- Apellido\n"); printf("3- Salario\n"); printf("4- Sector\n"); printf("Ingrese opcion: "); scanf("%d",&option); return option; } int modifyEmployee(Employee* employees, int lengthEmp) { int validation=0; int index; int option; int idEmployee; printEmployees(employees,lengthEmp); printf("Ingrese legajo del empleado a modificar: "); scanf("%d",&idEmployee); index=findEmployeeById(employees,lengthEmp,idEmployee); if(index==-1) { printf("No se ha encontrado al empleado\n"); validation=-1; } else { option=modifyMenu(); switch(option) { case 1: modifyNameEmployee(employees,lengthEmp,index); break; case 2: modifyLastNameEmployee(employees,lengthEmp,index); break; case 3: modifySalaryEmployee(employees,lengthEmp,index); break; case 4: modifySectorEmployee(employees,lengthEmp,index); break; default: printf("Opcion Invalida\n"); break; } } return validation; } int modifyNameEmployee(Employee* employees, int lengthEmp, int index) { char auxName[51]; char confirm; int validation; validation=getString(auxName,"Ingrese el NUEVO nombre del empleado","Nombre invalido, cantidad de caracteres [min 2 - max 50]",2,50); if(validation==1) { system("cls"); printf("EMPLEADO A MODIFICAR\n\n"); printf("%8s %12s %12s %12s %12s\n", "Legajo", "Sector", "Nombre", "Apellido", "Sueldo"); printEmployee(employees[index]); printf("Confirma NUEVO nombre: %s? s/n\n",auxName); fflush(stdin); scanf("%c",&confirm); if(confirm=='s') { strcpy(employees[index].name,auxName); validation=0; } else { validation=-1; } } else { validation=-1; } return validation; } int modifyLastNameEmployee(Employee* employees, int lengthEmp, int index) { char auxLastName[51]; char confirm; int validation; validation=getString(auxLastName,"Ingrese el NUEVO apellido del empleado","Apellido invalido, cantidad de caracteres [min 2 - max 50]",2,50); if(validation==1) { system("cls"); printf("EMPLEADO A MODIFICAR\n\n"); printf("6%8s %12s %12s %12s %12s\n", "Legajo", "Sector", "Nombre", "Apellido", "Sueldo"); printEmployee(employees[index]); printf("Confirma NUEVO apellido: %s? s/n\n",auxLastName); fflush(stdin); scanf("%c",&confirm); if(confirm=='s') { strcpy(employees[index].lastName,auxLastName); validation=0; } else { validation=-1; } } else { validation=-1; } return validation; } int modifySalaryEmployee(Employee* employees, int lengthEmp, int index) { float auxSalary; int validation; char confirm; validation=getFloat(&auxSalary,"Ingrese el NUEVO salario del empleado","Salario invalido, rango [min 1 - max 999999]",1,100000); if(validation==1) { system("cls"); printf("EMPLEADO A MODIFICAR\n\n"); printf("%8s %12s %12s %12s %12s\n", "Legajo", "Sector", "Nombre", "Apellido", "Sueldo"); printEmployee(employees[index]); printf("Confirma NUEVO salario: %.2f? s/n\n",auxSalary); fflush(stdin); scanf("%c",&confirm); if(confirm=='s') { employees[index].salary=auxSalary; validation=0; } else { validation=-1; } } else { validation=-1; } return validation; } int modifySectorEmployee(Employee* employees, int lengthEmp, int index) { int auxIdSector=0; int validation; char confirm; validation=getInt(&auxIdSector,"Elija el Nuevo sector del empleado","Opcion invalida, rango [0-5]",0,5); if(validation==1) { system("cls"); printf("EMPLEADO A MODIFICAR\n\n"); printf("%8s %12s %12s %12s %12s\n", "Legajo", "Sector", "Apellido", "Nombre", "Sueldo"); printEmployee(employees[index]); printf("AUXILIAR SECTORS ID(recibo): %d\n\n",auxIdSector); printf("Confirma NUEVO sector ?:s/n\n"); fflush(stdin); scanf("%c",&confirm); if(confirm=='s') { employees[index].sector=auxIdSector; validation=0; } else { validation=-1; } } else { validation=-1; } return validation; } int sortingMenu(Employee* employees, int lengthEmp) { int order; system("cls"); printf("Ordenar [A-Z] o [Z-A]\n"); printf("1- [A-Z]\n"); printf("2- [Z-A]\n"); printf("\nIngrese opcion: "); scanf("%d",&order); sortEmployeesByName(employees,lengthEmp,order); return order; } int sortEmployeesByName(Employee* employees, int lengthEmp, int order) { int sortingOk=0; int i, j; for(i=0; i<lengthEmp-1; i++) { for(j=i+1; j<lengthEmp; j++) { if(employees[i].isEmpty==OCCUPIED) { if(order==1) { if(employees[i].sector>employees[j].sector) { bubbleSorting(employees,lengthEmp,i,j); } else { if((employees[i].sector==employees[j].sector)&&(strcmp(employees[i].name,employees[j].name)>0)) { bubbleSorting(employees,lengthEmp,i,j); } } } else if(order==2) { if(employees[i].sector<employees[j].sector) { bubbleSorting(employees,lengthEmp,i,j); } else { if((employees[i].sector==employees[j].sector)&&(strcmp(employees[i].name,employees[j].name)<0)) { bubbleSorting(employees,lengthEmp,i,j); } } } } } } return sortingOk; } void bubbleSorting(Employee* employees, int length, int i, int j) { Employee auxEmp; auxEmp=employees[i]; employees[i]=employees[j]; employees[j]=auxEmp; } int printEmployees(Employee* employees, int lengthEmp) { int i; system("cls"); printf("EMPLEADOS ACTIVOS\n\n"); printf("%8s %12s %12s %12s %12s\n", "Legajo", "Sector", "Nombre", "Apellido", "Sueldo"); for(i=0; i<lengthEmp; i++) { if(employees[i].isEmpty==OCCUPIED) { printEmployee(employees[i]); } } return 0; } int printEmployee(Employee employee) { printf("%8d %12d %12s %12s %12.2f\n", employee.id,employee.sector,employee.name,employee.lastName,employee.salary); return 0; } int reportsMenu() { int option; system("cls"); printf("->MENU<- \n\n"); printf("1- Lista de empleados por orden alfabetico\n"); printf("2- Lista de total y promedio de salarios\n"); printf("\nIngrese opcion: "); scanf("%d",&option); return option; } int reports(Employee* employees, int lengthEmp) { int validation=0; switch(reportsMenu()) { case 1: sortingMenu(employees,lengthEmp); printf("EMPLEADOS ORDENADOS ALFABETICAMENTE\n\n"); printEmployees(employees,lengthEmp); break; case 2: reportsSalary(employees,lengthEmp); break; default: printf("Opcion invalida"); system("pause"); validation=-1; break; } return validation; } void reportsSalary(Employee* employees, int lengthEmp) { int i; float averageSalary=0; float accumulateSalary=0; int countAverage=0; int countEmployees=0; for(i=0; i<lengthEmp; i++) { if(employees[i].isEmpty==OCCUPIED) { accumulateSalary+=employees[i].salary; countEmployees++; } } averageSalary=accumulateSalary/countEmployees; for(i=0; i<lengthEmp; i++) { if(employees[i].isEmpty==OCCUPIED) { if(employees[i].salary>averageSalary) { countAverage++; } } } system("cls"); printf("->INFORME<-\n\n"); printf("TOTAL sueldos: %.2f\n\n",accumulateSalary); printf("PROMEDIO sueldos: %.2f\n\n",averageSalary); printf("Cant. Emp. que superan el promedio: %d\n\n",countAverage); }
C
// // firdespm_example.c // // This example demonstrates finite impulse response filter design // using the Parks-McClellan algorithm. // // SEE ALSO: firdes_kaiser_example.c #include <stdio.h> #include <stdlib.h> #include <math.h> #include "liquid.h" #define OUTPUT_FILENAME "firdespm_example.m" int main(int argc, char*argv[]) { // filter design parameters unsigned int h_len = 91; liquid_firdespm_btype btype = LIQUID_FIRDESPM_BANDPASS; unsigned int num_bands = 4; float bands[8] = {0.00f, 0.10f, 0.12f, 0.18f, 0.20f, 0.30f, 0.31f, 0.50f}; float des[4] = {1.0f, 0.0f, 0.1f, 0.0f}; float weights[4] = {1.0f, 4.0f, 8.0f, 4.0f}; liquid_firdespm_wtype wtype[4] = {LIQUID_FIRDESPM_FLATWEIGHT, LIQUID_FIRDESPM_FLATWEIGHT, LIQUID_FIRDESPM_FLATWEIGHT, LIQUID_FIRDESPM_EXPWEIGHT}; unsigned int i; float h[h_len]; firdespm_run(h_len,num_bands,bands,des,weights,wtype,btype,h); // print coefficients for (i=0; i<h_len; i++) printf("h(%4u) = %16.12f;\n", i+1, h[i]); // open output file FILE*fid = fopen(OUTPUT_FILENAME,"w"); fprintf(fid,"%% %s : auto-generated file\n", OUTPUT_FILENAME); fprintf(fid,"clear all;\n"); fprintf(fid,"close all;\n\n"); fprintf(fid,"h_len=%u;\n", h_len); for (i=0; i<h_len; i++) fprintf(fid,"h(%4u) = %20.8e;\n", i+1, h[i]); fprintf(fid,"nfft=1024;\n"); fprintf(fid,"H=20*log10(abs(fftshift(fft(h,nfft))));\n"); fprintf(fid,"f=[0:(nfft-1)]/nfft-0.5;\n"); fprintf(fid,"figure; plot(f,H,'Color',[0 0.5 0.25],'LineWidth',2);\n"); fprintf(fid,"grid on;\n"); fprintf(fid,"xlabel('normalized frequency');\n"); fprintf(fid,"ylabel('PSD [dB]');\n"); fprintf(fid,"title('Filter design (firdespm)');\n"); fprintf(fid,"axis([-0.5 0.5 -60 5]);\n"); fclose(fid); printf("results written to %s.\n", OUTPUT_FILENAME); printf("done.\n"); return 0; }
C
//cnproj.c - protocol for secured data transfer over UDP // Sends and receives the given file // //Usage: ./cnproj Sender/Recveiver filename listenport // //Authors: Syed Muazzam Ali Shah Kazmi // Muhammad Hasnain Naeem // //NOTE: this file contains code for both the sender and the receiver #include <stdio.h> #include <signal.h> #include <sys/socket.h> #include <sys/types.h> #include <netdb.h> #include <netinet/in.h> #include <unistd.h> #include <arpa/inet.h> #include <stdbool.h> #include <string.h> #include <stdlib.h> #include <time.h> enum allErrors { NO_ERRORS, ERROR_NOT_ENOUGH_ARGS, ERROR_WRONG_USAGE, ERROR_SOCKET, ERROR_BIND, ERROR_FILE_FOPEN, ERROR_FILE_WRITE }; typedef struct sockaddr_in SAin; typedef const struct sockaddr cSA; typedef struct sockaddr SA; //#define SIM_LATENCY 1000 //latency in milliseconds //#define SIM_CORRUPTION_CHECKSUM 14 //chance of error: use 0 to 14 #define SEGMENT_SIZE(s) (sizeof(s) - SEGMENT_MESSAGE_SIZE + s.length) #define SEGMENT_MESSAGE_SIZE 400 int networkWindowSize = 10; typedef struct Segment { uint16_t checksum; int length; int seqnum; char message[SEGMENT_MESSAGE_SIZE]; } Segment; int main(int argc, char *argv[]); int fileSender(unsigned short port, char* fileName); int fileRecveiver(unsigned short port, char* fileName); uint16_t checksum(Segment seg); int checkWindow(Segment *segWin, int winSize, int nextSeq, int *defectivePackets); int saveWindow(Segment *segWin, int winSize, FILE *recvFP); void getSegmentOrder(Segment *segWin, int winSize, int *orderArray); //reorders and saves int saveWindow(Segment *segWin, int winSize, FILE *recvFP) { if (winSize < 1) return NO_ERRORS; int *orderArray = (int*)malloc(winSize * sizeof(int)); getSegmentOrder(segWin, winSize, orderArray); int bytesWritten = 0; for (int i=0; i<winSize; i++) { int ordIndex = orderArray[i]; //save in that order if (segWin[ordIndex].length < 1) break; bytesWritten = fwrite(segWin[ordIndex].message, sizeof(char), segWin[ordIndex].length, recvFP); if (bytesWritten != segWin[ordIndex].length) { fclose(recvFP); return ERROR_FILE_WRITE; } } return NO_ERRORS; } //supporting function for saveWindow() //gives packet orders in descending seqnum order void getSegmentOrder(Segment *segWin, int winSize, int *orderArray) { if (winSize < 1) return; int orderArrayN = winSize-1; for (int i=0; i<winSize; i++) { int largestSeq = 0; int largestIndex = 0; for (int j=0; j<winSize; j++) { if ((segWin[j].seqnum > largestSeq) && (segWin[j].seqnum > 0)) { largestSeq = segWin[j].seqnum; largestIndex = j; } } segWin[largestIndex].seqnum = -1; orderArray[orderArrayN--] = largestIndex; } } //performs checksum, checks possible duplicates, and stores defective packets in defectivePackets array int checkWindow(Segment *segWin, int winSize, int nextSeq, int *defectivePackets) { int numDefect = 0; for (int i=0; i<winSize; i++) { if (segWin[i].checksum != checksum(segWin[i])) defectivePackets[numDefect++] = i; } return numDefect; } uint16_t checksum(Segment seg) { uint16_t *segBytes = (uint16_t*) &seg; int n = seg.length; if (n <= sizeof(seg.checksum)) return 0; uint16_t csum = 0xffff; for (int i=sizeof(seg.checksum); i < n/2; i++) { csum += ntohs(segBytes[i]); if (csum > 0xffff) csum -= 0xffff; } //last remaining bytes (if odd length) if (n & 1) { csum += ntohs(segBytes[n/2]); if (csum > 0xffff) csum -= 0xffff; } return csum; } int fileSender(unsigned short port, char* fileName) { printf("File sender started with:\n\tfileName: \t%s\n\ \tport: \t\t%d\n", fileName, port); //sender (server), receiver (client) details (IP, ports, etc.) SAin servaddr, cliaddr; Segment *segWin = (Segment*) malloc(sizeof(Segment) * networkWindowSize); Segment segRecv; memset(&servaddr, 0, sizeof(servaddr)); memset(&cliaddr, 0, sizeof(cliaddr)); int sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) return ERROR_SOCKET; servaddr.sin_family = AF_INET; servaddr.sin_port = htons(port); servaddr.sin_addr.s_addr = INADDR_ANY; if (bind(sockfd, (cSA*)&servaddr, sizeof(servaddr)) < 0) { close(sockfd); return ERROR_BIND; } int len, n, byteRead; len = sizeof(cliaddr); n = recvfrom(sockfd, (Segment *)&segRecv, sizeof(segRecv), MSG_WAITALL, (SA*) &cliaddr, &len); printf("Connection established\n"); FILE *sendFP = fopen(fileName, "r"); if (!sendFP) return ERROR_FILE_FOPEN; int pktCount = 0, glbSeqnum = 0; segWin[pktCount].seqnum = 0; len = sizeof(cliaddr); while ((byteRead = fread(segWin[pktCount].message, sizeof(char), SEGMENT_MESSAGE_SIZE, sendFP))) { segWin[pktCount].length = byteRead; segWin[pktCount].seqnum = glbSeqnum++; segWin[pktCount].checksum = checksum(segWin[pktCount]); n = sendto(sockfd, (Segment *) &segWin[pktCount], sizeof(segWin[pktCount]), MSG_CONFIRM, (cSA*) &cliaddr, len); //wait for ack if (pktCount == networkWindowSize-1) { do { n = recvfrom(sockfd, (Segment *)&segRecv, sizeof(segRecv), MSG_WAITALL, (SA*) &cliaddr, &len); if (segRecv.seqnum >= 0 && segRecv.seqnum < networkWindowSize) { //resend requested packet n = sendto(sockfd, (Segment *) &segWin[segRecv.seqnum], sizeof(segWin[segRecv.seqnum]), MSG_CONFIRM, (cSA*) &cliaddr, len); printf("Selective repeat requested.\n"); } } while (segRecv.seqnum != -1); //-1 ack = Ok to proceed printf("RECEIVING ACK.........%d\n", pktCount); pktCount = -1; } pktCount++; } //eof segWin[0].length = 0; segWin[0].seqnum = glbSeqnum; segWin[0].checksum = checksum(segWin[0]); n = sendto(sockfd, (Segment *) &segWin[0], sizeof(segWin[0]), MSG_CONFIRM, (cSA*) &cliaddr, len); fclose(sendFP); close(sockfd); return 0; } int fileRecveiver(unsigned short port, char* fileName) { printf("File receiver started with:\n\tfileName: \t%s\n\ \tport: \t\t%d\n", fileName, port); SAin servaddr; memset(&servaddr, 0, sizeof(servaddr)); Segment *segWin = (Segment*) malloc(sizeof(Segment) * networkWindowSize); Segment seg; seg.seqnum = 0; seg.length = -1; int sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) return ERROR_SOCKET; servaddr.sin_family = AF_INET; servaddr.sin_port = htons(port); servaddr.sin_addr.s_addr = INADDR_ANY; int n, len, bytesWritten; sendto(sockfd, (Segment *)&seg, sizeof(seg), MSG_CONFIRM, (cSA*) &servaddr, sizeof(servaddr)); printf("Handshake message sent.\n"); FILE *recvFP = fopen(fileName, "w"); if (!recvFP) { close(sockfd); return ERROR_FILE_FOPEN; } len = sizeof(servaddr); int pktCount = 0, glbSeqnum = 0; int *defectivePackets = (int*)malloc(sizeof(int)*networkWindowSize); while ((n = recvfrom(sockfd, (Segment *)&segWin[pktCount], sizeof(segWin[pktCount]), MSG_WAITALL, (SA*) &servaddr, &len))) { int isEOF = (segWin[pktCount].length == 0); //Simulate latency #ifdef SIM_LATENCY usleep(1000); #endif //Simulate corrupted papcket (with checksum) #ifdef SIM_CORRUPTION_CHECKSUM if (rand() % 100 < SIM_CORRUPTION_CHECKSUM) segWin[pktCount].checksum = 1234; #endif //send ack if (pktCount == networkWindowSize - 1 || isEOF) { int nDef = 0; while ( ( nDef = checkWindow(segWin, pktCount+1, seg.seqnum, defectivePackets))) { //get correct packets for corrupted/duplicate packets for (int i=0; i<nDef; i++) { seg.seqnum = defectivePackets[i]; sendto(sockfd, (Segment *)&seg, sizeof(seg), MSG_CONFIRM, (cSA*) &servaddr, sizeof(servaddr)); printf("Recovering packet: %d\n", seg.seqnum); n = recvfrom(sockfd, (Segment *)&segWin[defectivePackets[i]], sizeof(Segment), MSG_WAITALL, (SA*) &servaddr, &len); glbSeqnum++; } } //all okay, now save if (saveWindow(segWin, pktCount+1, recvFP) != NO_ERRORS) { close(sockfd); return ERROR_FILE_WRITE; } seg.seqnum = -1; //all ok, proceed sendto(sockfd, (Segment *)&seg, sizeof(seg), MSG_CONFIRM, (cSA*) &servaddr, sizeof(servaddr)); printf("SENDING ACK.........%d\n", pktCount); pktCount = -1; } if (isEOF) { printf("EOF reached.........Packets transmitted: %d\n", glbSeqnum); break; } pktCount++; glbSeqnum++; len = sizeof(servaddr); //segWin[pktCount].message[segWin[pktCount].length] = '\0'; //printf("Client: %d %d %d %s\n", segWin[pktCount].checksum, //segWin[pktCount].length, segWin[pktCount].seqnum, segWin[pktCount].message); } fclose(recvFP); close(sockfd); return 0; } int main(int argc, char *argv[]) { srand(time(0)); int status = ERROR_NOT_ENOUGH_ARGS; do { if (argc != 4) break; unsigned short port = atoi(argv[3]); signal(SIGPIPE, SIG_IGN); status = ERROR_WRONG_USAGE; if (strcmp(argv[1], "Sender") == 0) { status = fileSender(port, argv[2]); } else if (strcmp(argv[1], "Receiver") == 0) { status = fileRecveiver(port, argv[2]); } else break; } while (false); //print errors switch (status) { case 0: break; //no error case ERROR_NOT_ENOUGH_ARGS: case ERROR_WRONG_USAGE: printf("Usage: ./cnproj Sender/Recveiver filename listenport\n"); return 1; case ERROR_SOCKET: perror("Socket"); return 1; case ERROR_BIND: perror("Bind"); return 1; case ERROR_FILE_FOPEN: perror("fopen"); return 1; case ERROR_FILE_WRITE: perror("fwrite"); return 1; default: printf("Unknown error.\n"); return 1; } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_errors.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: adda-sil <adda-sil@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/01/11 17:06:22 by adda-sil #+# #+# */ /* Updated: 2020/01/20 17:35:01 by adda-sil ### ########.fr */ /* */ /* ************************************************************************** */ #include "cub3d.h" int ft_print_err(char *txt) { ft_fprintf(2, "Error\n"); ft_fprintf(2, txt); ft_fprintf(2, "\n"); return (ERROR); } int ft_print_defined_err(char *txt) { ft_fprintf(2, "Error\n"); perror(txt); return (ERROR); } int ft_generate_cos_sin_table(t_game *game) { int i; double teth; double teth0; if (!(game->win.sin = malloc(sizeof(double) * game->win.width)) || !(game->win.cos = malloc(sizeof(double) * game->win.width))) return (ft_print_defined_err("Allocating cos/sin table failed")); i = game->win.width - 1; teth = -M_PI / 3 / (game->win.width - 1); teth0 = M_PI / 6; while (i >= 0) { game->win.sin[i] = sin(teth0); game->win.cos[i] = cos(teth0); teth0 += teth; i--; } return (SUCCESS); } int ft_check_opts(char opts[8], int key) { if (opts[key] == 1) return (ft_print_err("A key has been set twice.")); opts[key] = 1; return (SUCCESS); } int ft_verify_opts(char *opts) { if (opts[0] != 1) return (ft_print_err(ERR0)); if (opts[1] != 1) return (ft_print_err(ERR1)); if (opts[2] != 1) return (ft_print_err(ERR2)); if (opts[3] != 1) return (ft_print_err(ERR3)); if (opts[4] != 1) return (ft_print_err(ERR4)); if (opts[5] != 1) return (ft_print_err(ERR5)); if (opts[6] != 1) return (ft_print_err(ERR6)); if (opts[7] != 1) return (ft_print_err(ERR7)); return (SUCCESS); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <math.h> #define CL_KERNEL_FILE "./heat_diffusion.cl" #define INPUT_FILE "./diffusion" #define MAX_KERNEL_SIZE 1048576 // 1 Kbytes #define ARRAY_MATRIX 1 #define DEBUG 0 /*open cl version 1.2*/ #ifndef CL_TARGET_OPENCL_VERSION #define CL_TARGET_OPENCL_VERSION 120 #endif #include <CL/cl.h> int main (int argc , char ** argv ) { int required_iterations=0; float diffusion_const=0; int ret; int option=0; int h,w,x,y; #ifndef ARRAY_MATRIX float ** matrix; #else float *matrix; #endif float val,avg; FILE *fp; char * opencl_program_src; long int size_cl_program=0; /*it returns the parsed char and as third arg it requires the separation char for arguments*/ while ((option = getopt(argc,argv,"n:d:"))!=-1) { switch(option){ case 'n': sscanf(optarg,"%d",&required_iterations); break; case 'd': sscanf(optarg,"%f",&diffusion_const); break; default: fprintf(stdout,"no valid arguments\n"); exit(-1); } } avg=0; fp=fopen(INPUT_FILE,"r"); if(fp==NULL) { fprintf(stderr,"error openign the file \n"); exit(-1); } /*saving input files*/ /*adding two additional rows and colums for avoididn to use control on the indexes*/ fscanf(fp,"%d %d\n",&h,&w); size_t MATRIX_SIZE_N_PAD=h*w; h+=2; w+=2; #ifndef ARRAY_MATRIX matrix=(float **) malloc ( sizeof(float *) *h); if(matrix==NULL) { fprintf(stderr,"error allocating matrix\n"); exit(-1); } for(int i=0;i<h;i++) { matrix[i]=(float *) malloc (sizeof(float) * (w)); if(matrix[i]==NULL) { fprintf(stderr,"errorr allocating row\n"); exit(-1); } /*obtaining a clean matrix and with boundaries at zero*/ for(int j=0;j<w;j++) { matrix[i][j]=0; } } /*populating matrix reading from file*/ while(fscanf(fp,"%d %d %f\n",&x,&y,&val)!=EOF) { matrix[x+1][y+1]=val; } #else /*calloc allows us to obtain a clean matrix ( zeros) also with boundaries*/ matrix=(float *) calloc(h*w*2,sizeof(float)); if(matrix==NULL) { fprintf(stderr,"eerror allocatin the matrix\n"); exit(-1); } while(fscanf(fp,"%d %d %f\n",&x,&y,&val)!=EOF) { matrix [ (x+1)*w +(y+1) ]=val; } #endif fclose(fp); if(fp==NULL) { fprintf(stderr,"error closing the file\n"); exit(-1); } #if DEBUG for(int i=0;i<h;i++) { for(int j=0;j<w;j++) { #ifndef ARRAY_MATRIX fprintf(stdout,"%.3f ",matrix[i][j]); #else fprintf(stdout,"%.3f ",matrix[ i*w +j]); #endif } fprintf(stdout,"\n"); } #endif /*loading the kernel file*/ fp=fopen(CL_KERNEL_FILE,"r"); if(fp==NULL) { fprintf(stderr,"error opening .cl file\n"); exit(-1); } opencl_program_src=(char *)calloc(MAX_KERNEL_SIZE,sizeof(char)); if(opencl_program_src==NULL) { fprintf(stderr,"error allocating string for opencl program\n"); exit(-1); } size_cl_program=fread(opencl_program_src,sizeof(char),MAX_KERNEL_SIZE,fp); fclose(fp); if(fp==NULL) { fprintf(stderr,"error closing .cl file\n"); exit(-1); } /*******************/ /*SET UP open cl*/ /****************/ /*data types of open cl declaration*/ cl_int error; cl_platform_id platform_id; cl_uint nmb_platforms; cl_program program; cl_context context; cl_command_queue command_queue; cl_kernel kernel_diffusion,kernel_matrix_abs_val; cl_device_id device_id; cl_uint nmb_devices; cl_mem buffer,buffer_out; /*platform*/ if (clGetPlatformIDs(1, &platform_id, &nmb_platforms) != CL_SUCCESS) { printf( "cannot get platform\n" ); return 1; } /*device */ if (clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, 1, &device_id, &nmb_devices) != CL_SUCCESS) { printf( "cannot get device\n" ); return 1; } /*context*/ cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties) platform_id, 0 }; context = clCreateContext(properties,1, &device_id, NULL, NULL, &error); if (error != CL_SUCCESS) { printf("cannot create context\n"); return 1; } /*command queue-> for sendig comman to the device * *The command queue takes memory writes and reads, and kernel execution * * i.e. execution is controlled by command queue * */ command_queue = clCreateCommandQueue(context, device_id, 0, &error); if (error != CL_SUCCESS) { printf("cannot create command queue\n"); return 1; } /*open cl program command stored in a string */ program = clCreateProgramWithSource(context,1, (const char **) &opencl_program_src, NULL, &error); /*error checking -> build log of the kernel*/ error = clBuildProgram(program, 0, NULL, NULL, NULL, NULL); if (error != CL_SUCCESS) { printf("cannot build program. log:\n"); size_t log_size = 0; clGetProgramBuildInfo(program, device_id, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size); char * log = calloc(log_size, sizeof(char)); if (log == NULL) { printf("could not allocate memory\n"); return 1; } clGetProgramBuildInfo(program, device_id, CL_PROGRAM_BUILD_LOG, log_size, log, NULL); printf( "%s\n", log ); free(log); exit(-1); } kernel_diffusion = clCreateKernel(program, "compute_diffusion", &error); if(error!=CL_SUCCESS) { fprintf(stderr,"cannot build kernel for diffusion calculation\n"); exit(-1); } /*memory reserved as buffers*/ const size_t MATRIX_SIZE = w*h; // plus the two additional row and column /*doubling the data structure on the device in order to prevent data blocking between work groups*/ buffer = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(float) * MATRIX_SIZE*2, NULL, &error); if(error!=CL_SUCCESS) { fprintf(stderr,"error creating buffer\n"); exit(-1); } /*three last arguments are used for synchronization ( events ) */ /*enqueuing writing buffers*/ if((error=clEnqueueWriteBuffer(command_queue, buffer, CL_TRUE, 0, MATRIX_SIZE*sizeof(float)*2 , matrix, 0, NULL, NULL))!=CL_SUCCESS) { fprintf(stderr,"%d error enqueuing the write buffer\n",error); exit(-1); } /* * ATTENTION: real index of matrix goes from 1 to n-1 */ error=clSetKernelArg(kernel_diffusion, 0, sizeof(cl_mem), &buffer); if(error!=CL_SUCCESS) { fprintf(stderr,"error setting first argument of diffusion kernel\n"); exit(-1); } error=clSetKernelArg(kernel_diffusion,1,sizeof(float),&diffusion_const); if(error!=CL_SUCCESS) { fprintf(stderr,"error setting second argument of diffusion kernel\n"); exit(-1); } error=clSetKernelArg(kernel_diffusion,2,sizeof(int),&h); if(error!=CL_SUCCESS) { fprintf(stderr,"error setting third argument of diffusion kernel\n"); exit(-1); } error=clSetKernelArg(kernel_diffusion,3,sizeof(int),&w); if(error!=CL_SUCCESS) { fprintf(stderr,"error setting fourth argument of diffusion kernel\n"); exit(-1); } #if DEBUG printf("getting local size %d\n",local_size); #endif /*executing the required iterations*/ for(size_t step=0;step<required_iterations ;step++) { error=clSetKernelArg(kernel_diffusion,4,sizeof(int), &step); if(error!=CL_SUCCESS) { fprintf(stderr,"error setting fiveth argument of diffusion kernel\n"); exit(-1); } /*enqueuing kernel */ error=clEnqueueNDRangeKernel(command_queue, kernel_diffusion, 1, NULL, &MATRIX_SIZE_N_PAD, NULL, 0, NULL, NULL); // null after matrix size will allow to choose automatically the size if(error!=CL_SUCCESS) { fprintf(stderr,"error enqueuing the diffusion kernel\n"); exit(-1); } } /*SYNCHRONIZATION POINT*/ /*it will wait until there are still some commands in the queue*/ if(clFinish(command_queue)!=CL_SUCCESS) { fprintf(stderr,"error in finishing the command queue\n"); exit(-1); } /*reading the output diffusion matrix*/ /*enqueuing reading buffer, implicit waiting thanks to CL_TRUE*/ if(clEnqueueReadBuffer(command_queue,buffer,CL_TRUE,0,MATRIX_SIZE*sizeof(float),matrix,0,NULL,NULL)!=CL_SUCCESS) { fprintf(stderr,"error enqueuing the read buffer\n"); exit(-1); } #if DEBUG printf("%d %d size\n",h,w); for(int i=1;i<h-1;i++) { for(int j=1;j<w-1;j++) { #ifndef ARRAY_MATRIX fprintf(stdout,"%.2f ",matrix[i][j]); #else fprintf(stdout,"%.2f ", matrix[ i*w + j] ); #endif } fprintf(stdout,"\n"); } #endif #if DEBUG fprintf(stdout,"calculating average\n"); #endif /*calculating the average*/ avg=0; for(int i=1;i<h-1;i++) { for(int j=1;j<w-1;j++) { avg+=matrix[i*w+j]; } } avg/=(MATRIX_SIZE_N_PAD); fprintf(stdout,"Average temperature: %.2f\n",avg); #if DEBUG avg=0; for(int i=1;i<h-1;i++) { for(int j=1;j<w-1;j++) { #ifndef ARRAY_MATRIX avg+=matrix[i][j]; #else avg+=matrix[i*w+j]; #endif } } avg/=(MATRIX_SIZE_N_PAD); fprintf(stdout,"Average temperature (debug check): %.2f\n",avg); fprintf(stdout,"calculating abs difference with previous avg kernel \n"); #endif /*print absolute difference between entries of matrix and average tmp*/ /*instantiate kernel for computing the abs matrix value ( also arguments ) */ kernel_matrix_abs_val=clCreateKernel(program,"compute_matrix_abs_val",&error); if(error!=CL_SUCCESS){ fprintf(stderr,"cannot build kernel for average calculation\n"); exit(-1); } /*setting arguments*/ error=clSetKernelArg(kernel_matrix_abs_val, 0, sizeof(cl_mem), &buffer); if(error!=CL_SUCCESS) { fprintf(stderr,"error setting first argument of abs matrix kernel\n"); exit(-1); } error=clSetKernelArg(kernel_matrix_abs_val,1,sizeof(int),&h); if(error!=CL_SUCCESS) { fprintf(stderr,"error setting second argument of abs matrix kernel\n"); exit(-1); } error=clSetKernelArg(kernel_matrix_abs_val,2,sizeof(int),&w); if(error!=CL_SUCCESS) { fprintf(stderr,"error setting third argument of abs matrix kernel\n"); exit(-1); } error=clSetKernelArg(kernel_matrix_abs_val,3,sizeof(float),&avg); if(error!=CL_SUCCESS){ fprintf(stderr,"error setting the fourth argument ofabs matrix kernel\n"); exit(-1); } /*executing kernel*/ clEnqueueNDRangeKernel(command_queue, kernel_matrix_abs_val, 1, NULL, (const size_t *)&MATRIX_SIZE_N_PAD, NULL, 0, NULL, NULL); /*it will wait until there are still some commands in the queue*/ if(clFinish(command_queue)!=CL_SUCCESS) { fprintf(stderr,"error in finishing the command queue\n"); exit(-1); } if(clEnqueueReadBuffer(command_queue,buffer,CL_TRUE,0,sizeof(float)*MATRIX_SIZE,matrix,0,NULL,NULL)!=CL_SUCCESS) { fprintf(stderr,"error enqueuing the read buffer for abs matrix\n"); exit(-1); } #if DEBUG avg=111080; for(int i=1;i<h-1;i++) { for(int j=1;j<w-1;j++) { #ifndef ARRAY_MATRIX fprintf(stdout,"%.3f ",fabs(matrix[i][j]-avg)); fprintf(stdout,"%.3f ",matrix[i][j]); #else fprintf(stdout,"(debug i.e. normal value) %.3f vs %.3f ",fabs(matrix[i*w + j]-avg),matrix[i*w+j]); #endif } fprintf(stdout,"\n"); } #endif /*computing again the average on the absolute values*/ #if DEBUG avg=111081110811; #endif avg=0; for(int i=1;i<h-1;i++) { for(int j=1;j<w-1;j++) { avg+=matrix[i*w+j]; } } avg/=MATRIX_SIZE_N_PAD; fprintf(stdout,"Average temperature of absolute values: %.2f\n",avg); #if DEBUG avg=0; for(int i=1;i<h-1;i++) { for(int j=1;j<w-1;j++) { #ifndef ARRAY_MATRIX avg+=matrix[i][j]; #else avg+=matrix[i*w+j]; #endif } } avg/=(MATRIX_SIZE_N_PAD); fprintf(stdout,"Average temperature of absolute value(debug): %.2f\n",avg); #endif /*it will wait until there are still some commands in the queue*/ if(clFlush(command_queue)!=CL_SUCCESS) { fprintf(stderr,"error in finishing the command queue\n"); exit(-1); } /*release memory*/ /*IN ORDER ACCORDING TO THE UML SCHEMATIC*/ clReleaseMemObject(buffer); clReleaseMemObject(buffer_out); clReleaseKernel(kernel_diffusion); clReleaseKernel(kernel_matrix_abs_val); clReleaseProgram(program); clReleaseCommandQueue(command_queue); clReleaseContext(context); #ifndef ARRAY_MATRIX for(int i=0;i<h;i++) { free(matrix[i]); } #endif free(matrix); return 0; }
C
#include <stdio.h> #pragma warning(disable:4996) int main() { int old; printf("̸ ԷϽÿ : "); scanf("%d", &old); if (old <= 7) printf(" Դϴ."); else if (old <= 12) printf("500 Դϴ."); else if (old <= 19) printf("700 Դϴ."); else if (old <= 64) printf("1500 Դϴ."); else if (old >= 65) printf("1000 Դϴ."); }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <sys/mman.h> #include <sys/ipc.h> #include <sys/sem.h> //shared memoryの文字列受け取って文字数を代入する側 int main(int argc, char *argv[]) { char *p, *ptr, count[4096]; int fd, ret1, semid, n, i; key_t semkey; struct sembuf buf; semkey = ftok("mmap2_r_sem", 'a'); semid = semget(semkey, 1, IPC_CREAT | IPC_EXCL | 0666); if (semid < 0) { semid = semget(semkey, 1, IPC_CREAT | 0666); } else { semctl(semid, 0, SETVAL, 1); } buf.sem_num = 0; buf.sem_flg = 0; fd = shm_open("/shared_memory", O_RDWR, 0666); //O_RDONLY->O_RDWR if (fd == -1) { fprintf(stderr, "shm_open failed\n"); exit(1); } p = mmap(0, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (p == MAP_FAILED) { perror("mmap"); return 1; } while (1) { buf.sem_op = -2; semop(semid, &buf, 1); fprintf(stderr, "-%s-\n", p); ret1 = strcmp(p, "exit"); if (ret1 == 0) break; n = strlen(p); snprintf(count, sizeof(count), "%d", n); fprintf(stderr, "%s\n", count); strncpy(p, count, 4096); /*fprintf(stderr,"+%s+\n",p); */ buf.sem_op = 1; semop(semid, &buf, 1); } if (munmap(p, sizeof(char)) == -1) { perror("munmap"); } //if(semctl(semid,0,IPC_RMID)!=0){ perror("semctl"); } close(fd); shm_unlink("/shared_memory"); return 0; } /* [sasayama@localhost Syoseki]$ ./mmap2_r_sem -Apple- 5 -Ball- 4 -exit- ipcs -s ipcrm -s 131073 ------ セマフォ配列 -------- キー semid 所有者 権限 nsems 0x6102bc13 819200 sasayama 666 1 */
C
#include <string.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <stdbool.h> #include "../include/http.h" #include "../include/log.h" static void parse_http_req_method(char** req_str, struct http_request_t* req) { if (req_str == NULL || *req_str == NULL || req == NULL) { log(ERROR, "Invalid function arguments"); return; } size_t get_len = strlen(STR_GET); if (strncmp(*req_str, STR_GET, get_len) == 0) { req->method = GET; *req_str += get_len + 1; // len of GET + single space return; } size_t head_len = strlen(STR_HEAD); if (strncmp(*req_str, STR_HEAD, head_len) == 0) { req->method = HEAD; *req_str += head_len + 1; //len of HEAD + single space return; } req->method = METHOD_UNDEFINED; } static void url_decode(char* url) { char url_repl_buf[4096 * 4]; char* url_repl = strcpy(url_repl_buf, url); if (url_repl == NULL) { log(ERROR, "Unable to copy URL to buffer"); return; } char* cursor = strchr(url_repl, '%'); while (cursor != NULL) { int hex_chr = 0; sscanf(cursor + 1, "%x", &hex_chr); char chr = (char)hex_chr; *cursor = chr; strcpy(cursor + 1, cursor + 3); cursor = strchr(cursor, '%'); } strcpy(url, url_repl); } static void parse_http_req_uri(char** req_str, struct http_request_t* req) { if (req_str == NULL || *req_str == NULL || req == NULL) { log(ERROR, "Invalid function arguments"); return; } req->URI = *req_str; *req_str = strchr(*req_str, ' '); if (*req_str == NULL) { req->URI = NULL; return; } **req_str = '\0'; *req_str += 1; url_decode(req->URI); char* query_start = strrchr(req->URI, '?'); if (query_start != NULL) { *query_start = '\0'; } } static void parse_http_req_proto_ver(char** req_str, struct http_request_t* req) { if (req_str == NULL || *req_str == NULL || req == NULL) { log(ERROR, "Invalid function arguments"); return; } size_t http_v1_0_len = strlen(STR_HTTPv1_0); if (strncmp(*req_str, STR_HTTPv1_0, http_v1_0_len) == 0) { req->http_version=HTTPv1_0; *req_str += http_v1_0_len + 2; // len of HTTP/1.0 + \r\n return; } size_t http_v1_1_len = strlen(STR_HTTPv1_0); if (strncmp(*req_str, STR_HTTPv1_1, http_v1_1_len) == 0) { req->http_version=HTTPv1_1; *req_str += http_v1_1_len + 2; // len of HTTP/1.1 + \r\n return; } req->http_version = VERSION_UNDEFINED; } static void parse_http_req_headers(char** req_str, struct http_request_t* req) { if (req_str == NULL || *req_str == NULL || req == NULL) { log(ERROR, "Invalid function arguments"); return; } const char* delim = "\r\n"; const int delim_len = 2; char** cursor = req_str; size_t header_len = 0; size_t headers_count = 0; while(1) { char* prev_cursor_val = *cursor; *cursor = strstr(*cursor, delim); header_len = *cursor - prev_cursor_val; log(DEBUG, "header_len: %d", header_len); if(header_len == 0) { *cursor += delim_len; req->headers_count = headers_count; break; } if (*cursor == NULL) { log(ERROR, "Can't parse headers: empty line does not reached"); req->headers_count = 0; return; } if (headers_count > req->headers_count) { log(ERROR, "Not enough memory allocated for headers"); req->headers_count = 0; return; } req->headers[headers_count].text = prev_cursor_val; req->headers[headers_count].len = header_len + delim_len; //CRLF is a part of a header too *cursor += delim_len; headers_count++; } } /*static void parse_http_req_body(char** req_str, struct http_request_t* req) { if (req_str == NULL || *req_str == NULL || req == NULL || req->headers == NULL) { log(ERROR, "Invalid function arguments"); return; } //TODO develop? }*/ char* request_method_t_to_string(enum request_method_t method) { switch (method) { case HEAD: { return STR_HEAD; } case GET: { return STR_GET; } default: { return "METHOD_UNDEFINED\0"; } } } char* http_version_t_to_string(enum http_version_t version) { switch (version) { case HTTPv1_0: { return STR_HTTPv1_0; } case HTTPv1_1: { return STR_HTTPv1_1; } default: { return "VERSION_UNDEFINED"; } } } char* http_state_t_to_string(enum http_state_t state) { switch (state) { case OK: { return STR_200_OK; } case BAD_REQUEST: { return STR_400_BAD_REQUEST; } case FORBIDDEN: { return STR_403_FORBIDDEN; } case NOT_FOUND: { return STR_404_NOT_FOUND; } case METHOD_NOT_ALLOWED: { return STR_405_METHOD_NOT_ALLOWED; } case INTERNAL_SERVER_ERROR: { return STR_500_INTERNAL_SERVER_ERROR; } default: { return "STATE_UNDEFINED\0"; } } } enum http_state_t parse_http_request(char* req_str, struct http_request_t* req) { if (req_str == NULL || req ==NULL) { log(ERROR, "Invalid function arguments"); return INTERNAL_SERVER_ERROR; } char* cursor = req_str; while (*cursor == '\r' || *cursor == '\n') { cursor += 1; } if (*cursor == '\0') { log(INFO, "Skipped empty req_str while parsing request"); return BAD_REQUEST; } parse_http_req_method(&cursor, req); log(DEBUG, "HTTP request method parsed: %s", request_method_t_to_string(req->method)); if (req->method == METHOD_UNDEFINED) { return METHOD_NOT_ALLOWED; } parse_http_req_uri(&cursor, req); log(DEBUG, "HTTP request URI parsed: %s", req->URI); if (req->URI == NULL) { log(DEBUG, "parse_http_request returning BAD_REQUEST, URI==NULL"); return BAD_REQUEST; } parse_http_req_proto_ver(&cursor, req); log(DEBUG, "HTTP request protocol version parsed: %s", http_version_t_to_string(req->http_version)); if (req->http_version == VERSION_UNDEFINED) { log(DEBUG, "parse_http_request returning BAD_REQUEST, HTTP_VERSION==VERSION_UNDEFINED"); return BAD_REQUEST; } if (req->headers_count > 0) { parse_http_req_headers(&cursor, req); log(DEBUG, "HTTP headers parsed:"); #ifdef DEBUG_MODE for (size_t i = 0; i < req->headers_count; i++) { log(DEBUG, "%.*s", req->headers[i].len - 2, req->headers[i].text); } #endif if (req->headers_count == 0) { log(DEBUG, "parse_http_request returning INTERNAL_SERVER_ERROR, unable to parse headers"); return INTERNAL_SERVER_ERROR; } } else { log(DEBUG, "There are no headers to parse in request"); } return OK; } int build_date_header(struct http_header_t* header) { if (header == NULL) { log(ERROR, "Invalid function arguments"); return -1; } time_t raw_time; //timestamp if (time(&raw_time) < 0) { log(ERROR, "Unable to get calendar time"); return -1; } struct tm* time_info = localtime(&raw_time); //datetime if (time_info == NULL) { log(ERROR, "Unable to parse raw_time into time_info"); return -1; } size_t header_len = strftime(header->text, HTTP_HEADER_DEFAULT_BUFFER_SIZE, "Date: %a, %d %b %Y %X %Z\r\n", time_info); if (header_len == 0) { log(ERROR, "Can not build Date header: buffer is too small"); return -1; } header->len = strlen(header->text); return 0; } static int build_content_length_header(struct http_header_t* header, int64_t content_len) { if (header == NULL || header->text == NULL) { log(ERROR, "Invalid function arguments"); return -1; } strcpy(header->text, STR_CONTENT_LENGTH_HEADER); sprintf(header->text + strlen(header->text), "%lu\r\n", content_len); header->len = strlen(header->text); return 0; } static int build_content_type_header(struct http_header_t* header, enum mime_t mime_type) { if (header == NULL || header->text == NULL) { log(ERROR, "Invalid function arguments"); return -1; } strcpy(header->text, STR_CONTENT_TYPE_HEADER); strcat(header->text, mime_type_to_str(mime_type)); strcat(header->text, "\r\n\0"); header->len = strlen(header->text); return 0; } enum http_state_t build_http_response(struct http_request_t* req, struct http_response_t* resp) { const size_t headers_count = 5; if (req == NULL || resp == NULL || resp->headers == NULL || resp->headers_count < headers_count) { log(ERROR, "Invalid function arguments"); return INTERNAL_SERVER_ERROR; } size_t header_idx = 0; if (req->http_version == HTTPv1_1) { resp->headers[header_idx] = (struct http_header_t) { STR_CONNECTION_KEEP_ALIVE_HEADER, strlen(STR_CONNECTION_KEEP_ALIVE_HEADER) }; } else { resp->headers[header_idx] = (struct http_header_t) { STR_CONNECTION_CLOSE_HEADER, strlen(STR_CONNECTION_CLOSE_HEADER) }; } header_idx++; int build_result = build_date_header(&resp->headers[header_idx]); if (build_result < 0) { log(ERROR, "Unable to build Date header"); resp->headers[header_idx] = (struct http_header_t){ STR_DEFAULT_DATE_HEADER, strlen(STR_DEFAULT_DATE_HEADER) }; } header_idx++; bool should_get_fd = req->method==GET; enum file_state_t inspect_result = inspect_file(req->URI, &resp->file_to_send, should_get_fd); switch (inspect_result) { case FILE_STATE_OK: { log(DEBUG, "File inspection successfully finished"); break; } case FILE_STATE_NOT_FOUND: { log(DEBUG, "File inspection finished: file not found"); return NOT_FOUND; } case FILE_STATE_FORBIDDEN: { log(DEBUG, "File inspection finished: access forbidden"); return FORBIDDEN; } case FILE_STATE_INTERNAL_ERROR: { log(ERROR, "File inspection finished цшер штеуктфд уккщк"); return INTERNAL_SERVER_ERROR; } default: { log(ERROR, "Unknown return code: %d", inspect_result); return INTERNAL_SERVER_ERROR; } } log(DEBUG, "File_to_send: fd: %d, len: %d, mime-type: %s", resp->file_to_send.fd, resp->file_to_send.mime_type, mime_type_to_str(resp->file_to_send.mime_type)); build_result = build_content_length_header(&resp->headers[header_idx], resp->file_to_send.len); if (build_result < 0) { log(WARNING, "Unable to build Content-Length header"); } else { header_idx++; } log(DEBUG, "Content-Length header built"); build_result = build_content_type_header(&resp->headers[header_idx], resp->file_to_send.mime_type); if (build_result) { log(WARNING, "Unable to build Content-Type header"); } else { header_idx++; } log(DEBUG, "Content-Type header built"); resp->headers[header_idx] = (struct http_header_t){ STR_SERVER_HEADER, strlen(STR_SERVER_HEADER) }; header_idx++; resp->code = OK; resp->http_version = req->http_version; resp->headers_count = headers_count; return OK; }
C
#include <string.h> #include <stdio.h> #include "PIlha_String_Header.h" //Questao -5 void inverter_string(tipo_pilha* pilha, char* dado, int tam) { tipo_pilha *a; int size; for (int i = 0; i < tam; i++) { if(empilhar(pilha, dado) == 0) { printf(" Letra nao pode ser alocada."); } } size = quantidadeElementos(pilha); for (int i = 0; i < size; i++) { printf("%c",desempilhar(pilha)); } } int main() { int tam; char* dado[20]; tipo_pilha* pilha = NULL; pilha = criaPilha(); if (pilha == NULL) { printf("Pilha nao pode ser alocada."); } printf("\n Digite uma frase: "); scanf(" %[^\n]s", dado); tam = strlen(frase); inverter_string(pilha, dado, tam); return 0; }
C
#include "./guk.h" #include <math.h> void phis_guk_sym(int *sym, int *n) { int i, j; int *map_sym; int map_sym_ident[]={0,1,2,3,4,5,6,7,8}; int map_sym4[]={0,1,3,4,2}; int map_sym8[]={0,1,8,7,2,6,3,4,5}; double *scfvectors; Type_3 *not_needed; int n2; FILE *dump_fp; if (*n < nAct) { *n = -nAct; return; } /* reading scf vectors (needed for determining symmetry from AOs) */ if ((dump_fp = guk_open_dump_file(dumpfile_name)) == NULL) { perror( "Cannot open dumpfile" ); exit( 1 ); } not_needed = guk_get_section(dump_fp,3); free(not_needed->data); free(not_needed); n2=nBas*nBas; if ((scfvectors = (double *) malloc(n2*sizeof(double))) == NULL) exit(0); if (guk_read_data(dump_fp, (char *) scfvectors, 0, n2) != n2) { printf("Something wrong reading SCF vectors.\n"); exit(1); } fclose( dump_fp ); /* do symmetry mapping from GUK to PHIS symmetries */ switch(section51->n_irrep) { case 8: map_sym=map_sym8; break; case 4: map_sym=map_sym4; break; default: map_sym=map_sym_ident; } /* read the MO symmetries */ for (i=0; i<nAct; i++) sym[i] = map_sym[section51->symlabels_mo[map_active[i]]]; /* get symmetry using the SCF vectors and the AO symmetries */ for (i=0; i<nAct; i++) { if(sym[i] == 0) { for (j=0; j<nBas; j++) { if(fabs(scfvectors[map_active[i]*nBas+j]) > 1.0e-4) { if(!sym[i]) {sym[i]=map_sym[section51->symlabels_ao[j]]; } else if (sym[i]!=map_sym[section51->symlabels_ao[j]]) { fprintf(stderr, "Inconsistency in the AO symmetry labels detected!\n" "(If you use 'HARMONIC ON', please do not use 'BYPASS HF' in the integral transformation)\n" "Aborting.\n"); exit(-2); } } } if(!sym[i]) { fprintf(stderr, "Unable to determine the symmetry of orbital %d\n",i+1); exit(-2); } } } *n = nAct; free(scfvectors); return; }
C
// Filename: qr_codes.c #include "cheats.h" #include "hid.h" /******************************** * * * QR Codes * * * ********************************/ u32 o_islandwait = 0x0043DAA8, o_qr100 = 0x3313EF33; // QR Codes menu entry void qrMenu(void) { switch(gameVer) { case 10: break; case 11: ; o_islandwait += 0x1C0D; break; } new_spoiler("QR Codes"); new_entry("Remove Island Scan Wait", removeIslandScanWait); new_entry("QR Scan Point 100", qrScan100); new_line(); exit_spoiler(); } // Remove 24 hour wait time for island scanning void removeIslandScanWait(void) { WRITEU32(o_islandwait, 0xE3A00000); } // Sets QR Scan points to 100 allowing you to Island Scan void qrScan100(void) { WRITEU8(o_qr100, 0x64); }
C
#include "config.h" int server; int client; int working; pid_t pid; pid_t child; char *name; key_t serverKey; key_t clientKey; void signalHandler(int signal); bool startsWith(char * prefix, char * text); void registerClient(); int main(int argc, char *argv[]) { if (argc != 2) { printf("Blad w linii komend\n Poprawne uruchomienie programu to: nazwa programu [nazwa uzytkownika]\n"); return 1; } name = argv[1]; working = 1; if (signal(SIGTSTP, signalHandler) == SIG_ERR) { printf("CLIENT ERROR : %s\n", strerror(errno)); exit(1); } struct mymesg message; pid = getpid(); // get server key : if ((serverKey = ftok(".", 1)) == -1) { printf("CLIENT ERROR : %s\n", strerror(errno)); exit(1); } // get server queue id : if ((server = msgget(serverKey, 0200)) < 0) { printf("CLIENT ERROR : %s\n", strerror(errno)); exit(1); } // get client key : if ((clientKey = ftok(".", pid)) == -1) { printf("CLIENT ERROR : %s\n", strerror(errno)); exit(1); } // get client queue id : if ((client = msgget(clientKey, IPC_CREAT | 0600)) < 0) { printf("CLIENT ERROR : %s\n", strerror(errno)); exit(1); } // register client : message.mtype = pid; strcpy(message.mtext, name); if (msgsnd(server, &message, MAXNAME, 0) < 0) { printf("CLIENT ERROR : %s\n", strerror(errno)); exit(1); } printf("\nCommand > "); if ((child = fork()) < 0) { printf("CLIENT ERROR : %s\n", strerror(errno)); working = 0; } else if (child > 0) { // receiving from server : while (working) { usleep(500000); if (msgrcv(client, &message, MAXMSGSIZE, 1, IPC_NOWAIT) < 0) { if (errno != EAGAIN && errno != ENOMSG) { printf("CLIENT ERROR : %s\n", strerror(errno)); working = 0; } } else { printf("FROM SERVER : %s\n", message.mtext); } } exit(0); } else if (child == 0) { // sending to server : while (working) { // get command : char *cmd = NULL; size_t len = MAXMSGSIZE; getline(&cmd, &len, stdin); for (int i = 0; i < MAXMSGSIZE; i++) message.mtext[i] = 0; for (int i = 0; i < strlen(cmd) - 1; i++) message.mtext[i] = cmd[i]; if (strcmp(message.mtext, "exit") == 0) { printf("Koniec\n"); kill(getpid(), SIGTSTP); } else if (strcmp(message.mtext, "time") == 0) { message.mtype = 2; message.mrequest = GET_TIME; if (msgsnd(client, &message, MAXMSGSIZE, 0) < 0) { printf("CLIENT ERROR : %s\n", strerror(errno)); working = 0; } } else if (startsWith("echo",message.mtext)) { // send to server message.mtype = 2; message.mrequest = ECHO; strcpy(message.mtext,message.mtext+5); if (msgsnd(client, &message, MAXMSGSIZE, 0) < 0) { printf("CLIENT ERROR : %s\n", strerror(errno)); working = 0; } } else if (startsWith("upper",message.mtext)) { // send to server message.mtype = 2; message.mrequest = TO_UPPER; strcpy(message.mtext,message.mtext+6); if (msgsnd(client, &message, MAXMSGSIZE, 0) < 0) { printf("CLIENT ERROR : %s\n", strerror(errno)); working = 0; } } } } // ? if (msgctl(client, IPC_RMID, (struct msqid_ds *) NULL) < 0) { printf("CLIENT ERROR : %s\n", strerror(errno)); exit(1); } return 0; } void signalHandler(int signal) { working = 0; kill(child, SIGTSTP); } bool startsWith(char * prefix, char * text) { size_t lenpre = strlen(prefix), lenstr = strlen(text); return lenstr < lenpre ? false : strncmp(prefix, text, lenpre) == 0; }
C
// // David Zheng // September 27, 2018 // CIS2107 Computer Systems and Low-Level Programming // Section 4 // Lab 4 Part 1 // Arrays2D.c // Objective: Design and implement functionsto process 2DArrays // // Created by David Zheng on 9/21/18. // Copyright © 2018 David Zheng. All rights reserved. // #include <stdio.h> int ROW, COL; // define ROW and COL // create prototypes void max(int arr[ROW][COL]); void displayOutputs(int arr[ROW][COL]); void rowSum(int arr[ROW][COL]); void columnSum(int arr[ROW][COL]); void isSquare(int ROW, int COL); int main(int argc, const char * argv[]) { puts("Let's make a 2D array.\nHow many rows are in your array?"); scanf("%d", &ROW); // take in value for ROW while(ROW <= 0) { // checks that there is at least 1 row puts("You need to have at least 1 row.\nHow many rows are in your array?"); scanf("%d", &ROW); } puts("How many columns are in your array?"); scanf("%d", &COL); // take in value for COL while(COL <= 0) { // checks that there is at least 1 column puts("You need to have at least 1 column.\nHow many columns are in your array?"); scanf("%d", &COL); } int arr[ROW][COL]; // creates a 2d array with ROW rows and COL columns for(size_t r = 0; r < ROW; ++r) { // for every row for(size_t c = 0; c < COL; ++c) { // for every element in every row printf("enter\t[%zu][%zu]:\t", r, c); int value; scanf("%d", &value); // take in value arr[r][c] = value; // put value in array } } printf("\n"); max(arr); rowSum(arr); columnSum(arr); isSquare(ROW, COL); displayOutputs(arr); return 0; } void max(int arr[ROW][COL]) { int max = arr[0][0]; // set the max value to first element in array for(size_t i = 0; i < ROW; ++i) { for(size_t j = 0; j < COL; ++j) { // for every element in array if(arr[i][j] > max) { // if the current element is greater than max max = arr[i][j]; // make the current element max } } } printf("Your maximum value of the 2D array is: %d\n\n", max); } void rowSum(int arr[ROW][COL]) { for(size_t i = 0; i < ROW; ++i) { // for every row int sum = 0; // sum starts at 0 for(size_t j = 0; j < COL; ++j) { // for every element in current row sum += arr[i][j]; // add current element value to sum } size_t row = i + 1; printf("The sum of row %zu = %d.\n", row, sum); } printf("\n"); } void columnSum(int arr[ROW][COL]) { for(size_t i = 0; i < COL; ++i) { // for every column int sum = 0; // sum starts at 0 for(size_t j = 0; j < ROW; j++) { // for every element in current column sum += arr[j][i]; // add current element to sum } size_t col = i + 1; printf("The sum of column %zu = %d.\n", col, sum); } printf("\n"); } void isSquare(int ROW, int COL) { if(ROW == COL) { // if there are as many rows as there are columns printf("The array is square because there are %d rows and %d columns.\n", ROW, COL); } else { printf("The array is not square because there are %d rows and %d columns.\n", ROW, COL); } printf("\n"); } void displayOutputs(int arr[ROW][COL]) { puts("Your new array is:"); for(size_t i = 0; i < ROW; ++i) { // for every row printf("["); // open bracket for(size_t j = 0; j < COL - 1; ++j) { // for every element in row excluding the last one printf("%d,\t", arr[i][j]); // print out element with a comma at the end } printf("%d", arr[i][COL - 1]); // print out last element printf("]\n"); // closing bracket } printf("\n"); }
C
#include <stdio.h> int main() { int num = 20; int a; if(num < 20) { a = (num++) - (num * num); } else if(num > 20) { a = (num--) * (num / 20); } else { a = num / (num + (3*num)); } printf("%d", a); }
C
/* This program uses red-black tree to remove multiple occurences of the same value from its paramaters. For example: a.out 6 7 3 4 1 4 1 3 5 writes: 1 3 4 5 6 7 */ #include <stdio.h> #include <stdlib.h> #include "sglib.h" typedef struct rbtree { int n; char color_field; struct rbtree *left; struct rbtree *right; } rbtree; #define CMPARATOR(x,y) ((x->n)-(y->n)) SGLIB_DEFINE_RBTREE_PROTOTYPES(rbtree, left, right, color_field, CMPARATOR) SGLIB_DEFINE_RBTREE_FUNCTIONS(rbtree, left, right, color_field, CMPARATOR) int main(int argc, char **argv) { int i,a; struct rbtree e, *t, *the_tree, *te; struct sglib_rbtree_iterator it; the_tree = NULL; for (i=1; i<argc; i++) { sscanf(argv[i],"%d", &a); e.n = a; if (sglib_rbtree_find_member(the_tree, &e)==NULL) { t = malloc(sizeof(struct rbtree)); t->n = a; sglib_rbtree_add(&the_tree, t); } } for(te=sglib_rbtree_it_init_inorder(&it,the_tree); te!=NULL; te=sglib_rbtree_it_next(&it)) { printf("%d ", te->n); } printf("\n"); for(te=sglib_rbtree_it_init(&it,the_tree); te!=NULL; te=sglib_rbtree_it_next(&it)) { free(te); } return(0); }
C
#include<stdio.h> #include<stdlib.h> int main(int argc, char const *argv[]) { int a, b, c, d, e, f, g; int sum; scanf("%d%d%d%d%d%d%d", &a, &b, &c, &d, &e,&f,&g); sum=a+b+c+d+ a*e+b*e+c*e+ c*f+d*f+ e*g +f+g; printf("%d", sum); return 0; }
C
#include "minishell.h" int find_bin(char *cmnd_name, char *path) { DIR *dir; struct dirent *dir_ptr; if ((dir = opendir(path))) { while ((dir_ptr = readdir(dir))) if (ft_strcmp(dir_ptr->d_name, cmnd_name) == 0) { closedir(dir); return (1); } closedir(dir); } return (0); } char *path(char *name, char *path) { char *full; char *tmp; if (path[ft_strlen(path) - 1] == '/') return (ft_strjoin(path, name)); else { tmp = ft_strjoin(path, "/"); full = ft_strjoin(tmp, name); ft_memdel((void **)&tmp); } return (full); } char *check_extern_command(char **cmnd) { char *env_path; char **paths; int i; int paths_quant; char *path; i = 0; paths_quant = 0; if (!(env_path = getenv_cmnd("PATH"))) return (NULL); paths = ft_strsplit(env_path, ':'); while (paths[paths_quant]) paths_quant++; while (i < paths_quant) { if ((find_bin(cmnd[0], paths[i]))) { path = ft_strdup(paths[i]); clean_env(paths); return (path); } i++; } return (NULL); } int external_launch(char **cmnd, char *paths) { char *filepath; if (!access(cmnd[0], R_OK)) // check //X_OK?? { perror_cmnd("minishell", cmnd[0], 0); return (1); } filepath = path(cmnd[0], paths); ft_strdel(&paths); return (launch(filepath, cmnd)); }
C
#define _CRT_SECURE_NO_WARNINGS #include "Hash_Table/Hash_Sep.h" #include "Link_List/link_list.h" #include <string.h> void DisplayHashTablePostion(Position pos); void DisplayLinkListPostion(ListPosition pos); void DoTask(Position pos, void* arg); void DealWithText(char* str, HashTable ht); int WordCmp(void* arg1, void* arg2); int CountCmp(void* arg1, void* arg2); void ShowTopTen(List list); void FreeListInfo(ListPosition pos); int main() { FILE* pf = fopen("essay.txt", "r"); if (!pf) { perror("open file"); exit(EXIT_FAILURE); } HashTable ht = InitializeTable(100); List list; InitList(&list); //一行一行的读取文件 //当一行太长就会出bug,但是懒得处理了 char buf[BUFSIZ]; while (!feof(pf)) { fgets(buf, BUFSIZ, pf); DealWithText(buf, ht); } //ForEach(ht, DisplayHashTablePostion); //带参遍历 ForEachWithArg(ht, DoTask, &list); //按词序排序 SortList(list, WordCmp); //打印链表 DisplayList(list, DisplayLinkListPostion); //按次数排序 SortList(list, CountCmp); //Top 10 printf("---------------------------------\n Top 10\n"); ShowTopTen(list); //释放内存 ListForEach(list, FreeListInfo); DestroyList(list); DestroyTable(ht); fclose(pf); return 0; } typedef struct Info { const char* key; int count; }Info; void DisplayHashTablePostion(Position pos) { printf("%16s : %d\n", pos->Key, Retrieve(pos)); } void DisplayLinkListPostion(ListPosition pos) { Info* pInfo = (Info*)pos->ELement; printf("%16s : %d\n", pInfo->key, pInfo->count); } Info* MakeInfo(const char* key, int count) { Info* pInfo = malloc(sizeof(Info)); if (pInfo) { pInfo->count = count; pInfo->key = key; } return pInfo; } void DoTask(Position pos, void* arg) { List* pList = (List*)arg; *pList = PushFront(MakeInfo(pos->Key, pos->ELement), *pList); } void AddOnce(HashTable ht, const char* key) { Position pos = Find(key, ht); if (pos) { pos->ELement += 1; } else { Insert(key, 1, ht); } } void AddWord(char* ptr, int n, HashTable ht) { char* p = ptr; for (int i = 0; i < n; ++i) { if (*p) { //printf("[%s]\n", p); AddOnce(ht, p); } p += strlen(p) + 1; } } int isAlpha(int ch) { if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) return 1; else return 0; } void DealWithText(char* str, HashTable ht) { char* pstr = str; int count = 0; while (*pstr) { if (!isAlpha(*pstr)) { *pstr = '\0'; ++count; } ++pstr; } AddWord(str, count + 1, ht); } int Strcmp(const char* p1, const char* p2) { int i = 0; while (p1[i] == p2[i] && p1[i] != '\0') { i++;//继续向前 } if (p1[i] == '\0' && p2[i] == '\0') { return 0; } else { int num = p1[i] - p2[i]; if (num > 0) return 1; else return -1; } } int WordCmp(void* arg1, void* arg2) { if (!arg1 || !arg2) return 1; Info* pInfo1 = (Info*)arg1; Info* pInfo2 = (Info*)arg2; //if (strcmp(pInfo1->key, pInfo2->key) == 1) return Strcmp(pInfo2->key, pInfo1->key); } int CountCmp(void* arg1, void* arg2) { if (!arg1 || !arg2) return 1; Info* pInfo1 = (Info*)arg1; Info* pInfo2 = (Info*)arg2; return pInfo1->count > pInfo2->count; } void ShowTopTen(List list) { int count = 0; for (ListPosition pos = HeadOfList(list); pos && count < 10; pos = pos->Next, ++count) { DisplayLinkListPostion(pos); } } void FreeListInfo(ListPosition pos) { free(pos->ELement); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "empleados.h" #include "ArrayList.h" empleados* empleados_new(void) { empleados* returnAux = (empleados*) malloc(sizeof(empleados)); return returnAux; } int empleados_setid(empleados* this, int id) { int retorno=-1; if(this!=NULL) { retorno=0; this->id=id; } return retorno; } int empleados_getid(empleados* this) { int retorno=-1; if(this!=NULL) { retorno=this->id; } return retorno; } int empleados_setnombre(empleados* this, char* nombre) { int retorno=-1; if(this!=NULL && nombre!=NULL) { retorno=0; strcpy(this->nombre,nombre); } return retorno; } int empleados_getnombre(empleados* this) { int retorno=-1; if(this!=NULL) { retorno=this->nombre; } return retorno; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <pthread.h> void error(char* msg) { fprintf(stderr, "%s: %s\n", msg, strerror(errno)); exit(1); } int beers = 2000000; void* drink_lots(void *a) { int i; for(i=0; i<100000; i++) { beers -= 1 ; } return NULL; } int main(int argc, char* argv[]) { pthread_t threads[20]; int t; printf("%i bottles of beer on the wall\n%i bottles of beer\n", beers, beers); for(t=0; t<20; t++) //create 20 threads that run the function { if(pthread_create(&threads[t], NULL, drink_lots, NULL) == -1) error("Error creating thread"); } void* result; for(t=0 ; t<20 ; t++) { if(pthread_join(threads[t], &result) == -1) error("Error joining thread"); } printf("There are now %i bottles of beer on the wall\n", beers ); return 0; }
C
#include <stdio.h> #include <string.h> int main (void) { if(strcmp("na", "a")) { printf("Whaaaat?"); } else { printf("NO"); } }
C
#include <stdlib.h> #include <unistd.h> #include <signal.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <time.h> #include <stdbool.h> #define BLOCK 512 #define INTERVAL 2 #define TRUE true #define FALSE false // Forward Declarations int install_handler(int sig, void (*handler)(int)); void sigint_handler(int sig); void sigtstp_handler(int sig); void sigquit_handler(int sig); int read_and_echo(); // global to keep track of time time_t seconds; bool sig_int, sig_stop, sig_quit; /* main * Install the necessary signal handlers, then call read_and_echo(). */ int main(int argc, char** argv) { sigset_t old; sigset_t full; sigfillset(&full); // Ignore signals while installing handlers sigprocmask(SIG_SETMASK, &full, &old); // Install signal handlers if(install_handler(SIGINT, &sigint_handler)) perror("Warning: could not install handler for SIGINT"); if(install_handler(SIGTSTP, &sigtstp_handler)) perror("Warning: could not install handler for SIGTSTP"); if(install_handler(SIGQUIT, &sigquit_handler)) perror("Warning: could not install handler for SIGQUIT"); // Restore signal mask to previous value sigprocmask(SIG_SETMASK, &old, NULL); read_and_echo(); return 0; } /* install_handler * Installs a signal handler for the given signal * Returns 0 on success, -1 on error */ int install_handler(int sig, void (*handler)(int)) { // TODO: Use sigaction() to install a the given function // as a handler for the given signal. struct sigaction act; // set struct's handler to be the same as *handler act.sa_handler = handler; // set masks; this is from lecture - should zero it sigemptyset(&act.sa_mask); // set flags; I think this would be something if you were using sa_sigaction instead of sa_handler act.sa_flags = 0; if(sigaction(sig, &act, NULL) < 0) return -1; else return 0; } /* sigint_handler * Respond to SIGINT signal (CTRL-C) * * Argument: int sig - the integer code representing this signal */ void sigint_handler(int sig) { // set time seconds = time(NULL); // update global variables sig_int = TRUE; sig_stop = FALSE; sig_quit = FALSE; char buffer[BLOCK]; int sz = sprintf(buffer, "%d signal received!\n", sig); // if write error if(write(STDOUT_FILENO, buffer, sz) < 0) exit(1); } /* sigtstp_handler * Respond to SIGTSTP signal (CTRL-Z) * * Argument: int sig - the integer code representing this signal */ void sigtstp_handler(int sig) { time_t stp_seconds = time(NULL); // for knocker if(stp_seconds - seconds < INTERVAL) { if(sig_int && !sig_stop && !sig_quit) { sig_stop = TRUE; } else { sig_int = FALSE; sig_stop = FALSE; sig_quit = FALSE; } } else { sig_int = FALSE; sig_stop = FALSE; sig_quit = FALSE; } char buffer[BLOCK]; int sz = sprintf(buffer, "%d signal received!\n", sig); // if write error if(write(STDOUT_FILENO, buffer, sz) < 0) exit(1); } /* sigquit_handler * Catches SIGQUIT signal (CTRL-\) * * Argument: int sig - the integer code representing this signal */ void sigquit_handler(int sig) { time_t quit_seconds = time(NULL); if(quit_seconds - seconds < INTERVAL) { if(sig_int && sig_stop) { char buffer[BLOCK]; int sz = sprintf(buffer, "\n"); if(write(STDOUT_FILENO, buffer, sz) < 0) exit(1); exit(0); } else { sig_int = FALSE; sig_stop = FALSE; sig_quit = FALSE; } } else { sig_int = FALSE; sig_stop = FALSE; sig_quit = FALSE; } char buffer[BLOCK]; int sz = sprintf(buffer, "%d signal received!\n", sig); // if write error if(write(STDOUT_FILENO, buffer, sz) < 0) exit(1); } /* read_and_echo * Read input from stdin, echo to stdout. * Return 0 on EOF, -1 on error */ int read_and_echo() { // TODO: Read from stdin and write to stdout // Use the async-signal-safe syscalls read() and write() char buffer[BLOCK]; ssize_t sz; while((sz = read(STDIN_FILENO, buffer, BLOCK)) != 0) { // write error if(sz > 0) { if(write(STDOUT_FILENO, buffer, sz) < 0) return -1; } } // end of file if(!sz) return 0; else return -1; }
C
struct Point2D{ public: Point2D(){} Point2D(int x, int y){ this->x = x; this->y = y; } int x; int y; };
C
/* ============================================================================ Name : FWOAWR7.c Author : Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> int oppnumber(); int main(void) { int k,i; i=oppnumber(k); return EXIT_SUCCESS; } int oppnumber(){ int L=0,i,j; for(i=10;i>=L;i--){ for(j=1;j<i;j++){ printf("%d",j); } printf("\n"); }return i; }
C
/* * Very simple and small shell * Copyright (C) 2008 Claudio M. Alessi * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <pwd.h> #include "geeksh.h" /* Common definitions */ extern char **environ; /* * Call exit(3) making the C compiler happy :-) If an exit status is given then * it's used instead. */ void do_exit(int argc, char *argv[]) { if( argc > 2 ) { cmdhelp(argv[0], 0); return; } /* * XXX: are there processes in background? */ exit((argv && argv[1] ? atoi(argv[1]) : EXIT_SUCCESS)); /* Make C compiler happy! */ } /* eof do_exit() */ /* * Print to the standard output the given list of arguments. */ void do_echo(int argc, char *argv[]) { int i = 0; /* Echoing the arguments */ while(argv[++i]) { printf("%s", argv[i]); if( i == argc ) break; printf(" "); } printf("\n"); } /* eof do_echo() */ /* * Add the given list of pairs variable=value to the * environment. */ void do_putenv(int argc, char *argv[]) { size_t envsz; int i; char *envstr; if( argc == 1 ) { cmdhelp(argv[0], 0); return; } for(i = 0; i < argc; i++) { envsz = strlen(argv[i]) + 1; if( (envstr = malloc(envsz)) == NULL ) return; strncpy(envstr, argv[i], envsz); if( putenv(envstr) ) free(envstr); } } /* eof do_putenv() */ /* * Add the given pair variable/value to the environment. */ void do_setenv(int argc, char *argv[]) { if( argc != 3 ) { cmdhelp(argv[0], 0); return; } setenv(argv[1], argv[2], 1); } /* eof do_setenv() */ /* * Remove the given list of variables from the environment. */ void do_unsetenv(int argc, char *argv[]) { if( argc == 1 ) { cmdhelp(argv[0], 0); return; } while( --argc && ! unsetenv(argv[argc]) ) ; } /* eof do_unsetenv() */ /* * Print the pair variable=value for any of the given * environment variables. */ void do_getenv(int argc, char *argv[]) { int i; if( argc == 1 ) { cmdhelp(argv[0], 0); return; } for(i = 1; i < argc; i++) printf("%s=%s\n", argv[i], getenv(argv[i])); } /* eof do_getenv() */ /* * Change the current working directory to the given path. If no path is * specified then the user home directory is used instead. The '-' * meta-directory goes to the directory specified by the OLDPWD environment * variable, if any. */ void do_cd(int argc, char *argv[]) { struct passwd *pwd; size_t tplen; char *tp, *path; if( argc > 2 ) { cmdhelp(argv[0], 0); return; } if( ! (path = argv[1]) ) { if( ! (path = getenv("HOME")) ) { if( (pwd = getpwuid(getuid())) != NULL ) path = pwd->pw_dir; else { /* This should never happen */ warnx("%s: cannot get the user home directory", argv[0]); return; } } } if( *path == '-' && ! path[1] ) { if( ! (path = getenv("OLDPWD")) ) return; printf("%s\n", path); /* TODO: An option should toggle this call */ } tp = path_alloc(&tplen); getcwd(tp, tplen); if( chdir(path) ) { warn("cd: %s", path); return; } setenv("OLDPWD", tp, 1); } /* eof do_cd() */ /* * Show the full list of the environment variables. The number of maximum * variables to show may be passed in order to control the listing length. */ void do_environ(int argc, char *argv[]) { int i, max; if( argc > 2 ) { cmdhelp(argv[0], 0); return; } for(i = 0, max = (argc == 2 ? atoi(argv[1]) : -1); environ[i] && max; i++, max--) printf("%s\n", environ[i]); } /* eof do_environ() */ /* * Print a full list of the builtins commands. If a command name is given, then * its passed as argument for cmdhelp() in order to show the relative help * message. */ void do_help(int argc, char *argv[]) { int i; if( argc >= 2 ) { cmdhelp(argv[1], argc == 2); return; } /* Few informations */ printf("\n%s v.%s\n\n", SH_NAME, SH_VERSION); for(i = 0; tblkeys[i].name; i++) printf(" %-9s%s\n", tblkeys[i].name, tblkeys[i].desc); printf("\n"); } /* eof do_help() */
C
/** * @file I2C.c * @brief I2C communication module * @date 11/15/2014 * @author a7med * @version 1.0 **/ #include "I2C.h" /******************************************************************************************************************************/ /** * Description: Function is used to Initialize I2C module to be ready for using **/ void TWI_Init(void) { /* setting SCL to 400KHz */ TWSR=0x00; TWBR=0x02; /* enable TWI */ TWCR=(1<<TWEN); } /******************************************************************************************************************************/ /** * Description: Function is used to Send start signal **/ void TWI_start(void) { TWCR=(1<<TWINT)|(1<<TWSTA)|(1<<TWEN); while((TWCR & (1<<TWINT)) == 0); } /******************************************************************************************************************************/ /** * Description: Function is used to Send stop signal **/ void TWI_stop(void) { TWCR=(1<<TWINT)|(1<<TWSTO)|(1<<TWEN); } /******************************************************************************************************************************/ /** * Description: Function is used to write data or address on SDA line **/ void TWI_write(uint8 data) { TWDR=data; TWCR=(1<<TWINT)|(1<<TWEN); while((TWCR & (1<<TWINT)) == 0); } /******************************************************************************************************************************/ /** * Description: Function is used to receive data and send acknowledge signal **/ uint8 TWI_read_ack(void) { TWCR=(1<<TWINT)|(1<<TWEN)|(1<<TWEA); while((TWCR & (1<<TWINT)) == 0); return TWDR; } /******************************************************************************************************************************/ /** * Description: Function is used to receive data without sending an acknowledgment **/ uint8 TWI_read_Nack(void) { TWCR=(1<<TWINT)|(1<<TWEN); while((TWCR & (1<<TWINT)) == 0); return TWDR; } /******************************************************************************************************************************/ /** * Description: Function is used to get status of TWI **/ uint8 TWI_get_status(void) { uint8 status; status = TWSR & 0xF8; return status; }
C
/*! \ingroup Logging \brief This function registers a logging callback that will be used to handle the wolfSSL log message. By default, if the system supports it fprintf() to stderr is used but by using this function anything can be done by the user. \return Success If successful this function will return 0. \return BAD_FUNC_ARG is the error that will be returned if a function pointer is not provided. \param log_function function to register as a logging callback. Function signature must follow the above prototype. _Example_ \code int ret = 0; // Logging callback prototype void MyLoggingCallback(const int logLevel, const char* const logMessage); // Register the custom logging callback with wolfSSL ret = wolfSSL_SetLoggingCb(MyLoggingCallback); if (ret != 0) { // failed to set logging callback } void MyLoggingCallback(const int logLevel, const char* const logMessage) { // custom logging function } \endcode \sa wolfSSL_Debugging_ON \sa wolfSSL_Debugging_OFF */ WOLFSSL_API int wolfSSL_SetLoggingCb(wolfSSL_Logging_cb log_function); /*! \ingroup Debug \brief If logging has been enabled at build time this function turns on logging at runtime. To enable logging at build time use --enable-debug or define DEBUG_WOLFSSL. \return 0 upon success. \return NOT_COMPILED_IN is the error that will be returned if logging isn’t enabled for this build. \param none No parameters. _Example_ \code wolfSSL_Debugging_ON(); \endcode \sa wolfSSL_Debugging_OFF \sa wolfSSL_SetLoggingCb */ WOLFSSL_API int wolfSSL_Debugging_ON(void); /*! \ingroup Debug \brief This function turns off runtime logging messages. If they’re already off, no action is taken. \return none No returns. \param none No parameters. _Example_ \code wolfSSL_Debugging_OFF(); \endcode \sa wolfSSL_Debugging_ON \sa wolfSSL_SetLoggingCb */ WOLFSSL_API void wolfSSL_Debugging_OFF(void);
C
// Programmdescription // Author: Marian Sievers // dd.mm.yyyy v0.x #include <stdio.h> int maximum(int numberA, int numberB) { if (numberA > numberB) { return numberA; } else { return numberB; } } int main() { printf("The biggest number is %i\n", maximum(12, 42)); return 0; }
C
#ifndef guardar_h #define guardar_h #include "struct.h" #include "obtenerproducto.h" char guardarReporte(){ FILE *archivo; char guardado; Producto *productos; int numeroProductos; int i; float costoTotal; float precioTotal; int cantidadTotal; productos = obtenerProductos(&numeroProductos); /* Retorna un vector din�mico de productos */ if (numeroProductos == 0) { guardado = 0; } else { /* Abre el archivo en modo texto para escritura */ archivo = fopen("reporte.txt", "w"); if (archivo == NULL) { /* Si no se pudo abrir el archivo, el valor de archivo es NULL */ guardado = 0; } else { fprintf(archivo, "\n\t\t ==> LISTADO DE LIBROS <==\n"); fprintf(archivo, " ------------------------------------------------------------------------------\n"); fprintf(archivo, "%8s\t%-20s%15s%15s%10s\n", "ISBN", "TITULO", "Editorial", "COSTO $", "PRECIO $", "CANTIDAD"); fprintf(archivo, " ------------------------------------------------------------------------------\n"); /* Se recorre el vector din�mico de productos */ costoTotal = 0; precioTotal = 0; cantidadTotal = 0; for (i = 0; i < numeroProductos; i++) { if (productos[i].codigo != VALOR_CENTINELA) { fprintf(archivo, "%7d \t%-20.20s%15.1s%15.1f%8d\n", productos[i].codigo, productos[i].nombre, productos[i].editorial, productos[i].costo, productos[i].precio, productos[i].cantidad); costoTotal += productos[i].costo; precioTotal += productos[i].precio; cantidadTotal += productos[i].cantidad; } } fprintf(archivo, " ------------------------------------------------------------------------------\n"); fprintf(archivo, "\t\t\t TOTAL: %15.1f%15.1f%8d", costoTotal, precioTotal, cantidadTotal); guardado = 1; /* Cierra el archivo */ fclose(archivo); } } return guardado; } #endif
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printf_put.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: wbraeckm <wbraeckm@student.s19.be> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/05 17:54:02 by wbraeckm #+# #+# */ /* Updated: 2018/09/14 15:58:39 by wbraeckm ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" static char g_buffer[PRINTF_BUFFER]; static int g_index = 0; void ft_printf_putchar(int c, t_flags *flags) { flags->printed++; g_buffer[g_index++] = c; if (g_index == PRINTF_BUFFER) ft_printf_flush(flags); } void ft_printf_putnchar(int c, t_flags *flags, size_t amount) { while (amount--) ft_printf_putchar(c, flags); } void ft_printf_putnstr(const char *str, size_t len, t_flags *flags) { while (len--) ft_printf_putchar(*str++, flags); } void ft_printf_putstr(const char *str, t_flags *flags) { ft_printf_putnstr(str, ft_strlen(str), flags); } void ft_printf_flush(t_flags *flags) { char *tmp; if (g_index == 0) return ; if (flags->str == NULL) flags->str = malloc(sizeof(char) * flags->printed); else { tmp = flags->str; flags->str = malloc(sizeof(char) * flags->printed); if (flags->str) ft_memcpy(flags->str, tmp, flags->printed - g_index); free(tmp); } if (!flags->str) { flags->printed = -1; return ; } ft_memcpy(flags->str + flags->printed - g_index, g_buffer, g_index); g_index = 0; }
C
#include "List.h" #include <stdio.h> #include <malloc.h> List *listNew(void *data,List*next) { List *list = malloc(sizeof(List)); list->data=data; list->next=next; return list; } void listDump(List *list,void (*dump)(void*)) { while(list!=NULL) { dump(list->data); list=list->next; } }
C
#include <stdio.h> #include <stdlib.h> int main (int argc, char* argv[]){ if (argc > 1) { for (int argIter = 1; argIter < argc; ++argIter) { char *resolved_path_buffer = NULL; char *result = realpath(argv[argIter], resolved_path_buffer); puts(result); if (result != NULL) { free(result); } } } return 0; }
C
/* pq.h Visible structs and functions for priority queues. Skeleton written by Grady Fitzpatrick for COMP20007 Assignment 1 2021 */ /* The priority queue. */ #ifndef PATH_STRUCT #define PATH_STRUCT struct path { int vertex; int *prevToCur; int cost; }; #endif #ifndef PQ_STRUCT #define PQ_STRUCT struct pq { int count; // length of pq int allocated; // to increase size of pq, no other function struct path **queue; // 2d list of overall path from start to each point int *priorities; // list of overall distance from start to each point }; #endif /* Get a new empty priority queue. */ struct pq *newPQ(); /* Add an item to the priority queue - cast pointer to (void *). */ /* struct pq *pq = priority queue int *item = a list of overall path from start to vertex int priority = overall distance from start to vertex*/ void enqueue(struct pq *pq, struct path *item, int priority); /* Take the smallest item from the priority queue - cast pointer back to original type. */ struct path *deletemin(struct pq *pq); /* Returns 1 if empty, 0 otherwise. */ int empty(struct pq *pq); /* Remove all items from priority queue (doesn't free) and free the queue. */ void freePQ(struct pq *pq);
C
#include<stdio.h> #include<time.h> int main() { int h1,h2,h3,m1,m2,m3; scanf("%d:%d",&h1,&m1); scanf("%d:%d",&h2,&m2); m3=((h1*60+m1)+(h2*60+m2))%120; m3=m3/2; h3=(h1+h2)/2; printf("%02d:%02d",h3,m3); }
C
/** * @input A : Read only ( DON'T MODIFY ) Integer array * @input n1 : Integer array's ( A ) length * */ int compare(const void *a1,const void *b1){ int a = *(int*)a1; int b = *(int*)b1; int i=0; char arr[10000]={0}; char brr[10000]={0}; sprintf(arr, "%d%d", a, b); sprintf(brr, "%d%d", b, a); int k = strlen(arr); for(i=0; i < k; i++){ if(arr[i] != brr[i]) return brr[i] - arr[i]; } return b-a; } char* largestNumber(const int* A, int n1) { char *ans = (char*) calloc(10000000,sizeof(char)); int i=0, count=0; qsort(A, n1, sizeof(int), compare); if(A[0] == 0){ ans[0] = '0'; ans[1]=0; return ans; } for(i=0; i<n1; i++){ int k = A[i]; // printf("%d ", k); count += sprintf(ans+count, "%d", k); } // printf("\n"); ans[count] = 0; return ans; }
C
/* Brandon Wu */ // UCLA CS 111 Lab 1 command reading #include "command.h" #include "command-internals.h" #include <error.h> /* TODO: 1. Proper error msg format 2. Better documentation 3. Detect single & as an ERROR FIXME: 1. Subshell commands across multiple lines only picks up last word */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "alloc.h" #define BUFFER_SIZE 1024 #define WORD_SIZE 100 typedef enum { TRUE, FALSE, } boolean; typedef enum { WORD, // A word not including whitespace or other token OPAREN, // Left paren ( CPAREN, // Right paren ) AND, // && OR, // || PIPE, // | SEMI, // ; IN, // < OUT, // > COMMENT, // # TICK, // ` INVALID, // Invalid token (e.g. <<<) } token_type; typedef struct { token_type type; char* word; } token; struct command_node { command_t cmd; struct command_node* nxt; }; struct command_stream { /* command_stream implemented by linked list of commands*/ struct command_node* list; }; /* Determine if character is white space */ inline boolean is_space(char c) { switch(c) { case ' ': case '\t': case '\n': case '\v': case '\f': return TRUE; default: return FALSE; } }; /* Determine if argument c is special character */ inline boolean is_special(char c) { switch(c) { case ';': case '|': case '&': case '<': case '>': case '(': case ')': case '#': case '`': return TRUE; default: return FALSE; } }; /* Returns the type of the token at position pos in line_buffer of length len. RETURNS INVALID if no valid token (e.g. white space) */ inline token_type get_token_type(char* line_buffer, int pos, int len) { char c = line_buffer[pos]; if (c=='(') return OPAREN; if (c==')') return CPAREN; if (c==';') return SEMI; if (c=='<') return IN; if (c=='>') return OUT; if (c=='#') { return COMMENT; } if (c=='&') { if(pos<len-1 && line_buffer[pos+1] == '&') return AND; else error(1, 0, "Single ampersand is invalid\n");; // Invalid if single & } if (c == '|') { if (pos<len-1 && line_buffer[pos+1] == '|') return OR; else return PIPE; } else if (c == '`') return TICK; return INVALID; } /* GET_TOKEN Given line buffer and current pos within buffer, get the next token in that line Return position of next char in buffer after end of token t. If no token exists, report INVALID token. RETURNS next unvisited pos in line_buffer, or len if EOL */ int get_token(char* line_buffer, int len, int pos, token* t) { char c; int word_len = 0; if (pos >= len) { t->type = INVALID; return pos; } while((pos<len) && is_space(c=line_buffer[pos])==TRUE) ++pos; if ((pos<len) && is_special(c) == FALSE) // if it is a word token { t->type = WORD; t->word = checked_malloc(WORD_SIZE); while (pos<len && is_space(c=line_buffer[pos]) == FALSE && is_special(c) == FALSE && word_len < WORD_SIZE) { t->word[word_len] = c; word_len++; pos++; } t->word[word_len] = '\0'; } else // If it is a valid special token { t->type = get_token_type(line_buffer, pos, len); if (t->type == COMMENT) return len; switch((t->type = get_token_type(line_buffer, pos, len))) { case AND: case OR: pos++; default: pos++; } } if (t->type == IN || t->type == OUT) if (line_buffer[pos-1] == line_buffer[pos]) pos++; return pos; } /* Read a single line terminated by \n or EOF from file RETURN len of line_buffer */ int get_line(int (*get_next_byte) (void *), void* fp, char* line_buffer) { char c; int len=0; c=(*get_next_byte)(fp); while((len<BUFFER_SIZE) && c != '\n' && (c>0)) { line_buffer[len] = c; len++; c=(*get_next_byte)(fp); } if (c < 0) // If c is negative, return EOF return -1; if (len >= BUFFER_SIZE) error(1,0, "Buffer Overflow"); return len; } /* Count num of words in line_buffer up to \n or special token */ int count_words(char* line_buffer, int len) { int i=0, num=0; char c; while (i < len) { while(i < len && is_space(c=line_buffer[i]) == TRUE && is_special(c) == FALSE) i++; if (i < len && is_special(c) == FALSE) num++; while(i < len && is_space(c=line_buffer[i]) == FALSE && is_special(c) == FALSE) i++; if(is_special(c) == TRUE) { break; } } return num; } /* Get I/O redirect file beginning at pos, store the word into command_t */ int get_io(char* line_buffer, int len, int pos, command_t cmd, int input, int* line_num) { /* if input = 1, the redirect is input if input = 0, the redirect is an output */ int i; char* word = checked_malloc(WORD_SIZE); token* t = checked_malloc(sizeof(token)); if (input) { if (cmd->input != NULL) error(1,0, "Multiple I/O redirect :%d", *line_num); cmd->input = word; } else { if (cmd->output != NULL) error(1,0, "Multiple I/O Redirect :%d", *line_num); cmd->output = word; } i = get_token(line_buffer,len, pos, t); if (t->type != WORD) error(1,0, "I/O redirect needs to be followed by a word :%d", *line_num); memcpy(word, t->word, WORD_SIZE); free(t->word); get_token(line_buffer,len,i,t); if (t->type == WORD) error(1,0,"I/O redirect cannot be followed by > 1 word :%d", *line_num); return i; } /* If next cmd is a simple command, create the cmd starting at pos until the end of the simple cmd (i.e newline, pipe, sequence, etc). RETURN last visited position in line_buffer */ int make_simple_cmd(int (*get_next_byte) (void*), void* fp, char* line_buffer, int len, int pos, command_t cmd, int subshell, int* line_num) { int num_words = count_words(line_buffer+pos, len-pos); int i = 0, wnum = 0; token* t = checked_malloc(sizeof(token)); if( get_next_byte == 0 && fp == 0) { } if (num_words == 0) { return -1; } if (subshell && (cmd->type == SIMPLE_COMMAND)) { // If there is another simple command, it should be treated as // ( cmd1; cmd2) char** temp = cmd->u.word; cmd->type = SEQUENCE_COMMAND; cmd->u.command[0] = checked_malloc(sizeof(struct command)); memset(cmd->u.command[0], 0, sizeof (struct command)); cmd->u.command[0]->status = -1; cmd->u.command[0]->type = SIMPLE_COMMAND; cmd->u.command[0]->u.word = temp; cmd->u.command[0]->input = cmd->input; cmd->u.command[0]->output = cmd->output; cmd->input = NULL; cmd->output = NULL; cmd->u.command[1] = checked_malloc(sizeof(struct command)); memset(cmd->u.command[1], 0, sizeof(struct command)); cmd->u.command[1]->status = -1; return make_simple_cmd(get_next_byte, fp, line_buffer, len, pos, cmd->u.command[1], subshell, line_num); } else if (subshell && cmd->type == SEQUENCE_COMMAND) { /* For nested, multi-line subshell commands Example: ( a\n b\n c) should be treated as (a; b; c) */ command_t tmp_cmd = cmd->u.command[1]; cmd->u.command[1] = checked_malloc(sizeof(struct command)); memset(cmd->u.command[1], 0, sizeof(struct command)); cmd->u.command[1]->type = SEQUENCE_COMMAND; cmd->u.command[1]->status=-1; cmd->u.command[1]->u.command[0] = tmp_cmd; cmd->u.command[1]->u.command[1] = checked_malloc(sizeof(struct command)); memset(cmd->u.command[1]->u.command[1], 0, sizeof(struct command)); cmd->u.command[1]->u.command[1]->status = -1; return make_simple_cmd(get_next_byte, fp, line_buffer, len, pos, cmd->u.command[1]->u.command[1], subshell, line_num); } else // For a new simple cmd { cmd->type = SIMPLE_COMMAND; cmd->u.word = checked_malloc(sizeof(void*)*num_words+1); } // Allocate mem for each word for (i=wnum; i<num_words; ++i) cmd->u.word[i] = checked_malloc(WORD_SIZE); i = get_token(line_buffer, len, pos, t); do { if (t->type==IN || t->type==OUT) { i = get_io(line_buffer, len, i, cmd, (t->type==IN),line_num); } else memcpy(cmd->u.word[wnum],t->word, WORD_SIZE); wnum++; i = get_token(line_buffer, len, i, t); } while ((wnum<num_words && t->type==WORD) || t->type==IN || t->type==OUT); token_type type = t->type; free(t->word); switch(type) { case AND: case OR: return i-2; case IN: case OUT: case INVALID: return i; default: return i-1; } } /* Parse the next command not yet read from the file stream and return it */ command_t make_command(int (*get_next_byte) (void*), void* fp, char* line_buffer, int len, int* line_num, int subshell) { /* subshell = 1 if current command is a SUBSHELL_COMMAND and should only terminate on a close paren line_num tracks the current line number in the filestream len stores the length of the currently active line buffer, len=0 when there is no valid line stored in line_buffer (start of read) */ boolean done = FALSE; command_t cmd = NULL; token* t = checked_malloc(sizeof(token)); int pos = 0; int temp; while(done == FALSE || subshell==1) { while(pos>=len) { len = get_line(get_next_byte, fp, line_buffer); if (len < 0) { if (subshell) error(1,0, "%d: Subshell not terminated", *line_num); else return NULL; } pos = 0; *line_num += 1; } done = TRUE; while(pos < len) { temp = get_token(line_buffer, len, pos, t); token_type type = t->type; if (type!=WORD) pos= temp; if (type==WORD) { if (cmd == NULL) { cmd = checked_malloc(sizeof(struct command)); memset(cmd, 0, sizeof(struct command)); } pos = make_simple_cmd(get_next_byte, fp, line_buffer, len, pos, cmd, subshell, line_num); } else if (type==IN || type==OUT) { error(1,0, "%d: I/O not affiliated with simple command", *line_num); } else if (type==AND || type==OR || type==PIPE || type == SEMI) { if (cmd == NULL) error(1,0, "%d: No left-hand operand", *line_num); command_t tmp_cmd; tmp_cmd = checked_malloc(sizeof(struct command)); memset(tmp_cmd, 0, sizeof(struct command)); tmp_cmd->u.command[1] = checked_malloc(sizeof(struct command)); memset(tmp_cmd->u.command[1], 0, sizeof(struct command)); tmp_cmd->status = -1; if((type==PIPE || type==SEMI)&&(cmd->type==AND_COMMAND || cmd->type == OR_COMMAND)) { tmp_cmd->u.command[0] = cmd->u.command[1]; cmd->u.command[1] = tmp_cmd; } else { tmp_cmd->u.command[0] = cmd; cmd = tmp_cmd; } while((pos = make_simple_cmd(get_next_byte, fp, line_buffer, len, pos,tmp_cmd->u.command[1], subshell, line_num)) == -1) { len = get_line(get_next_byte, fp, line_buffer); if (len == -1) error(1,0, "%d: Syntax Error", *line_num); pos = 0; *line_num += 1; } switch(type) { case AND: tmp_cmd->type = AND_COMMAND; break; case OR: tmp_cmd->type = OR_COMMAND; break; case PIPE: tmp_cmd->type = PIPE_COMMAND; break; case SEMI: tmp_cmd->type = SEQUENCE_COMMAND; break; default:; } } else if (type == OPAREN) { if (cmd != NULL) error(1,0,"%d: Non empty cmd preceding '('", *line_num); cmd = checked_malloc(sizeof(struct command)); memset(cmd, 0, sizeof(struct command)); cmd->status = -1; cmd->type = SUBSHELL_COMMAND; cmd->u.subshell_command = make_command(get_next_byte, fp, line_buffer+pos, len-pos, line_num, subshell+1); return cmd; } else if (type == CPAREN) { if (subshell >= 1) subshell--; else error(1,0,"%d: Unmatched ')'", *line_num); } else if (type == COMMENT) done = FALSE; else if (type == TICK) { error(1,0,"%d: Invalid symbol", *line_num); } } } return cmd; } /* Make a command stream given file handler */ command_stream_t make_command_stream (int (*get_next_byte) (void *), void *get_next_byte_argument) { int num_cmds = 0; int* line = checked_malloc(sizeof(int)); *line = 0; char *line_buffer = checked_malloc(BUFFER_SIZE); command_stream_t stream = checked_malloc(sizeof(struct command_stream)); stream->list = checked_malloc(sizeof(struct command_node)); struct command_node* walk = stream->list; while ((walk->cmd = make_command(get_next_byte, get_next_byte_argument, line_buffer, 0, line, 0)) != NULL) { walk->nxt = checked_malloc(sizeof(struct command_node)); walk = walk->nxt; num_cmds++; } free(line_buffer); free(line); return stream; } /* Read from a command stream, one command at a time until command stream is empty (returns NULL) */ command_t read_command_stream (command_stream_t s) { command_t cmd = s->list->cmd; struct command_node* temp = s->list; if (s->list != NULL) s->list = s->list->nxt; free(temp); return cmd; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* and_or_xor.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mmatiush <mmatiush@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/09/26 15:00:59 by gdanylov #+# #+# */ /* Updated: 2018/11/14 17:52:06 by vmorguno ### ########.fr */ /* */ /* ************************************************************************** */ #include "corewar.h" unsigned int ft_and(t_proc *proc, t_prog *g, t_arg_type *type, unsigned char *map) { t_arg *args; unsigned int ret; args = ft_memalloc(sizeof(t_arg) * 3); if ((ret = get_args(proc, args, type, map)) == 0xff) { free(args); return (ft_calc_move(type, proc)); } proc->reg[args[2].obts[0] - 1] = args[0].qbt & args[1].qbt; check_carry(proc->reg[args[2].obts[0] - 1], proc); if (g->verbose & 4) g->printed += ft_printf("P%5d | and %d %d r%d\n", proc->pid,\ args[0].qbt, args[1].qbt, args[2].obts[0]); free(args); return (ret); } unsigned int ft_or(t_proc *proc, t_prog *g, t_arg_type *type, unsigned char *map) { t_arg *args; unsigned int ret; args = ft_memalloc(sizeof(t_arg) * 3); if ((ret = get_args(proc, args, type, map)) == 0xff) { free(args); return (ft_calc_move(type, proc)); } proc->reg[args[2].obts[0] - 1] = args[0].qbt | args[1].qbt; check_carry(proc->reg[args[2].obts[0] - 1], proc); if (g->verbose & 4) g->printed += ft_printf("P%5d | or %d %d r%d\n", proc->pid, args[0].qbt, args[1].qbt, args[2].obts[0]); free(args); return (ret); } unsigned int ft_xor(t_proc *proc, t_prog *g, t_arg_type *type, unsigned char *map) { t_arg *args; unsigned int ret; args = ft_memalloc(sizeof(t_arg) * 3); if ((ret = get_args(proc, args, type, map)) == 0xff) { free(args); return (ft_calc_move(type, proc)); } proc->reg[args[2].obts[0] - 1] = args[0].qbt ^ args[1].qbt; check_carry(proc->reg[args[2].obts[0] - 1], proc); if (g->verbose & 4) g->printed += ft_printf("P%5d | xor %d %d r%d\n", proc->pid,\ args[0].qbt, args[1].qbt, args[2].obts[0]); free(args); return (ret); }
C
#include<stdio.h> #include<stdlib.h> #define N 100 int cmp(char a,char b){ if((a=='+'||a=='-')&&(b=='*'||b=='/'))return -1; else if((b=='+'||b=='-')&&(a=='*'||a=='/')) return 1; else return 0; } int main(){ int i=0,j=0; char a[N],ch; do { ch=getchar(); a[i]=ch; i++; } while(ch!='@') InitStack (S1);// InitStack(S2);// Push(S1'#'); while(a[j]!='@'){ switch(a[j]){ case'+': case'-': case'*': case'/':if(cmp(a[j],GetTop(S1))>0||GetTop(S1)=='(') Push(S1,a[j]); else {Pop(S1,e);Push(S2,e);} break; case')':while(GetTop(S1!='(')){Pop(S1,e);Push(S2,e);} Pop(S1,e);break; case'(':Push(S1,'('); default: Push(S1,a[j]); j++;} Pop(S2); return 0; } }
C
#include "data.h" #include "process.h" #include<unistd.h> void run(Node *instruction,Stack *scope,Stack *inputStack) { ////////////////////////////////////////////////// // Recursive loop that grabs the next instruction & proceses it // // Uncomment for debugging // printf("Processing %s [%s] [%s]\n", instruction->name, getInstruction(instruction->name),getArgument(instruction -> name)); //if ( scope != NULL) switchInstruction(instruction,scope, inputStack); // stack2string(scope,10); // printf("\n------------------------------------------\n"); if(instruction != NULL && instruction -> next != NULL) run(instruction -> next,scope,inputStack); } void switchInstruction(Node* thisNode,Stack *scope,Stack *inputStack) { if( thisNode != 0 && thisNode -> name != 0 && thisNode -> name != NULL && thisNode != NULL) { ////////////////////////////////////// // Ignore empty strings // The instruction type is determined // by the instruction. (the first arguemnt) char * line = thisNode -> name; char * instruction = getInstruction(line); //printf("[%s], %s\n", line,instruction); if(isLogclOprn(instruction)) doLogclOprn(instruction,scope); else if(isRelatOprn(instruction)) doRelatOprn(instruction,scope); else if(isArthmOprn(instruction)) doArthmOprn(instruction,scope); else if(isStackOprn(instruction)) doStackOprn(line,scope); else if(isSubCntrol(instruction)) doSubCntrol(line,scope,inputStack,thisNode); else if(isCntrlOprn(instruction)) { doCntrlOprn(line,scope, inputStack, thisNode); } else doOutput(line,scope); } else //////////////////////////////// // White spaces messing everything up!! if(thisNode != NULL && thisNode -> next != NULL) run(thisNode -> next,scope,inputStack); } bool isRelatOprn(char * line) { ////////////////////////////// // "<>,<=,>=,<,>,=" // return( (line[0] == '<') || (line[0] == '>') || (line[0] =='=') ); } bool isArthmOprn(char * line) { ////////////////////////////// // "*,+,-,/,div" // return( (line[0] == '*') || (line[0] == '+') || (line[0] == '-') || (line[0] == '/') || (line[0] == 'd')); } bool isLogclOprn(char * line) { ////////////////////////////// // "!,&,|" // return( (line[0] == '!') || (line[0] == '&') || (line[0] == '|') ); } bool isStackOprn(char * line) { ////////////////////////////// // "pop,push,rval" // // A little different here. Want to make sure that the FIRST // word is one of the stack calls. return( (strcmp(line,"pop") == 0) || (strcmp(line,"push") == 0) || (strcmp(line,"rvalue") == 0) || (strcmp(line,"lvalue") == 0) || (strcmp(line,":=") == 0) || (strcmp(line,"pop\r") == 0)); } bool isCntrlOprn(char * line) { ///////////////////////////////// // label, goto, gotrue, gofalse, halt // return( (strcmp(line,"label") == 0) || (strcmp(line,"goto") ==0) ||(strcmp(line,"gofalse")==0) || (strcmp(line,"gotrue")==0) ||(strcmp(line,"halt")==0) || (strcmp(line,"halt\r")==0)); } bool isSubCntrol(char* line) { /////////////////////////////////// // begin, end, return, call // return( (strcmp(line,"begin")== 0) || (strcmp(line,"end")==0) ||(strcmp(line,"return")==0) || (strcmp(line,"call")==0)); } void doLogclOprn(char *line,Stack *scope) { int oper1 = (pop(scope))->value; int oper2 = 0; if( scope -> top != NULL) oper2 = (pop(scope))->value; if( line[0] == '!' ) push(scope,makeNode(NULL,bang(oper1))); else if(line[0] == '&') push(scope,makeNode(NULL,ampr(oper1,oper2))); else if(line[0] == '|') push(scope,makeNode(NULL,pype(oper1,oper2))); } void doRelatOprn(char *line,Stack* scope) { int oper1 = scope->top -> value; int oper2 = scope->top->back -> value; if(line[0] == '=') neq(oper1,oper2); else if(line[0] == '<') { switch(line[1]) { case '>': push(scope,makeNode(NULL,equ(oper1,oper2))); break; case '=': push(scope,makeNode(NULL,leq(oper1,oper2))); break; default: push(scope,makeNode(NULL,lt(oper1,oper2))); break; } } else if(line[0] == '>') { switch(line[1]) { case '=': push(scope,makeNode(NULL,geq(oper1,oper2))); break; default: push(scope,makeNode(NULL,gt(oper1,oper2))); } } } void doArthmOprn(char *line,Stack* scope) { int oper1 = pop(scope)->value; int oper2 = pop(scope)->value; if( line[0] == '+' ) push(scope,makeNode(NULL,sum(oper1,oper2))); else if(line[0] == '-') push(scope,makeNode(NULL,sub(oper1,oper2))); else if(line[0] == '*') push(scope,makeNode(NULL,mul(oper1,oper2))); else if( line[0] == '/') push(scope,makeNode(NULL,divi(oper1,oper2))); else if(line[0] == 'd') push(scope,makeNode(NULL,mod(oper1,oper2))); } void doStackOprn(char *line,Stack *scope) { if (strstr(line,"pop") != NULL) pop(scope); else if(strstr(line,"push") != NULL) { int i = 0; while( line[i] != ' ') i++; doPush(scope,atoi(getArgument(line)),getArgument(line),getNextAddr(scope)+1); } else if(strstr(line,"rvalue") != NULL) rvalue(line, scope); else if(strstr(line,"lvalue") != NULL) lvalue(line,scope); else if(strstr(getInstruction(line),":=")!= NULL) eval(scope); } void doCntrlOprn(char * line, Stack *scope, Stack *inputStack,Node * curNode) { //////////////////////////////////// // goto, halt, gofalse, gotrue if(strcmp(getInstruction(line),"goto") == 0) run(got(line,inputStack), scope,inputStack); else if((strcmp(getInstruction(line),"halt\r") == 0 ) || strcmp(getInstruction(line),"halt") == 0) { clean(scope, inputStack); exit(-9); } else if(strcmp(getInstruction(line),"gofalse") == 0) gofalse(line,scope,inputStack); else if(strcmp(getInstruction(line),"gotrue") == 0) gotrue(line,scope,inputStack); else if(strcmp(getInstruction(line),"label") == 0) run(curNode -> next, scope,inputStack); // get the next instruction } void doSubCntrol(char *line, Stack* scope,Stack* inputStack,Node *pos) { if (strcmp(getInstruction(line),"begin")== 0) begin(inputStack,scope,pos); else if (strcmp(getInstruction(line),"end")==0) end(inputStack,pos); else if( strcmp(getInstruction(line),"return")==0) retn(inputStack, scope); else if(strcmp(getInstruction(line),"call")==0) call(pos,line,scope,inputStack ); } void doOutput(char *line1,Stack* scope) { char *line = getInstruction(line1); char *argument = (char *) malloc(sizeof(char)*strlen(line)-4); int i = 0; argument = "\n"; if( strlen(line1) > 4) argument = getArgument(line1); if( (strstr(line,"show")) != NULL) { //fprintf(FP,"@#@#@#:"); fprintf(FP,"%s\n", getArgument(line1)); } else { fprintf(FP, "%d\n", scope->top->value); //fprintf(FP, "1111111:"); } } void doPush(Stack* scope, int value, char *name, int address) { ///////////////////////////////////// // Push to the stack push(scope,makeNode(name, value)); if( scope -> top -> back != NULL) scope -> top -> address = address+1; else scope -> top -> address = 0; }
C
/** * @file * * @author jeff.daily@pnnl.gov * * Copyright (c) 2015 Battelle Memorial Institute. */ #include "config.h" #include <errno.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #if defined(_MSC_VER) #include <io.h> #define READ_FUNCTION _read #else #include <unistd.h> #define READ_FUNCTION read #endif #include <kseq.h> #if HAVE_ZLIB #include <zlib.h> KSEQ_INIT(gzFile, gzread) #else KSEQ_INIT(int, READ_FUNCTION) #endif #include "parasail.h" #include "parasail/io.h" #include "parasail/stats.h" static char* strdup_rpl(const char *str) { size_t l = strlen(str); char *s = (char*)calloc(l + 1, sizeof(char)); if(!s) { return NULL; } (void)memcpy(s, str, l); return s; } parasail_sequences_t* parasail_sequences_from_file(const char *filename) { #if HAVE_ZLIB gzFile fp; #else FILE* fp; int is_stdin = 0; #endif kseq_t *seq = NULL; int l = 0; parasail_sequences_t *retval = NULL; parasail_sequence_t *sequences = NULL; unsigned long count = 0; unsigned long capacity = 1000; size_t chars = 0; stats_t stats; stats_clear(&stats); retval = (parasail_sequences_t*)malloc(sizeof(parasail_sequences_t)); if (NULL == retval) { perror("malloc"); exit(1); } sequences = (parasail_sequence_t*)malloc(sizeof(parasail_sequence_t) * capacity); if (NULL == sequences) { perror("malloc"); exit(1); } /* check for stdin instead of a normal filename */ if (0 == strncmp("stdin", filename, 5)) { #if HAVE_ZLIB fp = gzdopen(fileno(stdin), "r"); if (fp == Z_NULL) { perror("gzdopen"); exit(1); } #else fp = stdin; is_stdin = 1; #endif } else { /* open the file */ errno = 0; #if HAVE_ZLIB fp = gzopen(filename, "r"); if (fp == Z_NULL) { perror("gzopen"); exit(1); } #else fp = fopen(filename, "r"); if (fp == NULL) { perror("fopen"); exit(1); } #endif } /* initialize kseq structures */ #if HAVE_ZLIB seq = kseq_init(fp); #else seq = kseq_init(fileno(fp)); #endif /* parse file */ while ((l = kseq_read(seq)) >= 0) { errno = 0; sequences[count].name.l = seq->name.l; sequences[count].comment.l = seq->comment.l; sequences[count].seq.l = seq->seq.l; sequences[count].qual.l = seq->qual.l; sequences[count].name.s = NULL; sequences[count].comment.s = NULL; sequences[count].seq.s = NULL; sequences[count].qual.s = NULL; stats_sample_value(&stats, seq->seq.l); chars += seq->seq.l; if (sequences[count].name.l) { sequences[count].name.s = strdup_rpl(seq->name.s); if (NULL == sequences[count].name.s) { perror("strdup name"); exit(1); } } if (sequences[count].comment.l) { sequences[count].comment.s = strdup_rpl(seq->comment.s); if (NULL == sequences[count].comment.s) { perror("strdup comment"); exit(1); } } if (sequences[count].seq.l) { sequences[count].seq.s = strdup_rpl(seq->seq.s); if (NULL == sequences[count].seq.s) { perror("strdup seq"); exit(1); } } if (sequences[count].qual.l) { sequences[count].qual.s = strdup_rpl(seq->qual.s); if (NULL == sequences[count].qual.s) { perror("strdup qual"); exit(1); } } ++count; /* allocate more space for sequences if we ran out */ if (count >= capacity) { parasail_sequence_t *new_sequences = NULL; capacity *= 2; errno = 0; new_sequences = (parasail_sequence_t*)realloc(sequences, sizeof(parasail_sequence_t) * capacity); if (NULL == new_sequences) { perror("realloc"); exit(1); } sequences = new_sequences; errno = 0; } } kseq_destroy(seq); #if HAVE_ZLIB gzclose(fp); #else if (!is_stdin) { fclose(fp); } #endif retval->seqs = sequences; retval->l = count; retval->characters = chars; retval->shortest = stats._min; retval->longest = stats._max; retval->mean = stats._mean; retval->stddev = stats_stddev(&stats); return retval; } void parasail_sequences_free(parasail_sequences_t *sequences) { size_t i; for (i=0; i<sequences->l; ++i) { if (sequences->seqs[i].name.s) free(sequences->seqs[i].name.s); if (sequences->seqs[i].comment.s) free(sequences->seqs[i].comment.s); if (sequences->seqs[i].seq.s) free(sequences->seqs[i].seq.s); if (sequences->seqs[i].qual.s) free(sequences->seqs[i].qual.s); } free(sequences->seqs); free(sequences); } char* parasail_sequences_pack(const parasail_sequences_t *sequences, size_t *size) { size_t i = 0; size_t offset = 0; char *packed = NULL; packed = (char*)malloc(sizeof(char) * (sequences->characters+sequences->l+1)); for (i=0; i<sequences->l; ++i) { memcpy(&packed[offset], sequences->seqs[i].seq.s, sequences->seqs[i].seq.l); offset += sequences->seqs[i].seq.l; packed[offset++] = '$'; } packed[offset] = '\0'; *size = offset; return packed; }
C
#include<stdio.h> double SquareMeter(int); int main() { int iValue=0; double dRet=0.0; printf("Enter a Area in Square Feet :"); scanf("%d",&iValue); dRet=SquareMeter(iValue); printf("Area : %lf",dRet); return 0; } double SquareMeter(int iValue) { double dSquareFeet=0.0; dSquareFeet = iValue * 0.0929; return dSquareFeet; }
C
//2+4+6+.....+nth #include<stdio.h> int main() { int a,s=0,ath,n; scanf("%d",&n); a=1; m:ath=2*a; s+=ath; a++; if(a<=n) goto m; printf("%d",s); return 0; }
C
/*TO COMPILE THE PROGRAM PUT BOTH FILES THAT ARE ON MY GITHUB -majo.h and binary.c then to start the program start by adding a user: add .... to delete a user: delete user + password to show the data: show...*/ #include<stdio.h> #include<ctype.h> #include<stdlib.h> #include"majo.h" #define LIM 100 int main() { node* n = NULL; node* tree = NULL; int a = 0, b = 0, count = 0; char c; char username[LIM]; char password[LIM]; char line[LIM]; char type[LIM]; while(1) { a = 0, b = 0; do{ line[a++] = c; if(isspace(c)) count++; }while((c = getchar()) != EOF && c != '\n'); line[a] = '\0'; if(count >= 2) { a = getdata(type, line); a += getdata(username, line+a); a += getdata(password, line+a); } if(strstr(type, "add") && username && password) { n = insert(username, password, tree); if (tree == NULL) tree = n; show(tree); } else if (strstr(type, "delete")) printf("the user has been deleted\n"); /*for (i=0; i<strlen(user);i++){ j[i]=user[i]; }*/ else printf("Invalid user, try again\n\n"); if(strstr(line, "show") != NULL){ alpha(tree); printf("\n\n"); } } } void show(node* position) { if (position != NULL) { printf("The user is %s and the password is %s\n", position->name, position->password); printf("\n"); return; } } node *insert(char *name, char *password, node* pos) { node* temp; if (pos == NULL) { pos = (node*)malloc(sizeof(node)); pos->name = name; pos->password = password; } else if(pos->right == NULL) { pos->right = (node*)malloc(sizeof(node)); pos->name = name; pos->password = password; } else if(pos->left == NULL) { pos->left = (node*)malloc(sizeof(node)); pos->name = name; pos->password = password; } printf("User succesfully added\n"); return pos; } int getdata(char *user, char *line) { int i = 0, j = 0; if(isspace(line[0])) while(isspace(line[++i])); while(!isspace(line[i])) user[j++] = line[i++]; user[i] = '\0'; return i; } //References: Antonio Cortes, Daniela Rodriguez, Rogelio Salinas and Dr Satu Elisa//
C
/* * Copyright (C) 2017, Saul Lawliet <october dot sunbathe at gmail dot com> * All rights reserved. * * 维持首尾两个指针, 和首尾的最大高度, 然后向中间寻找 * 如果遇到'坑', 就把'坑'的深度累加到结果中 */ #include "c/data-structures/array.h" #include "c/test.h" int trap(int *height, int heightSize) { int rtn = 0, left_max = 0, right_max = 0, left = 0, right = heightSize - 1; while (left < right) { if (height[left] < height[right]) { height[left] >= left_max ? (left_max = height[left]) : (rtn += left_max - height[left]); ++left; } else { height[right] >= right_max ? (right_max = height[right]) : (rtn += right_max - height[right]); --right; } } return rtn; } void test(int expect, const char *str) { arrayEntry *e = arrayParse1D(str, ARRAY_INT); EXPECT_EQ_INT(expect, trap(arrayValue(e), (arraySize(e)))); arrayFree(e); } int main(void) { test(6, "[0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]"); return testOutput(); }
C
// // Vector.m // Carnivores // // Created by Dmitry Nechay on 18.08.09. // Copyright 2009 Action Forms. All rights reserved. // #include "Common.h" #include "FastMath.h" #include "Vector.h" float Vector3D_DistanceToVectorSQR(Vector3D *v, Vector3D *nv, Vector3D *p) { Vector3D vc = Vector3D_Subtract(p, v); Vector3D n = Vector3D_CrossProduct(nv, &vc); return (n.x * n.x + n.y * n.y + n.z * n.z); } float Vector3D_DistanceToVector(Vector3D *v, Vector3D *nv, Vector3D *p) { Vector3D vc = Vector3D_Subtract(p, v); Vector3D n = Vector3D_CrossProduct(nv, &vc); return sqrtf(n.x * n.x + n.y * n.y + n.z * n.z); } Vector3D Vector3D_GetPointOnQuadCurve(Vector3D *v1, Vector3D *v2, Vector3D *v3, float k) { Vector3D p1 = Vector3D_GetPointOnSegment(v1, v2, k); Vector3D p2 = Vector3D_GetPointOnSegment(v2, v3, k); return Vector3D_GetPointOnSegment(&p1, &p2, k); } Vector3D Vector3D_GetPointOnQubicCurve(Vector3D *v1, Vector3D *v2, Vector3D *v3, Vector3D *v4, float k) { Vector3D p1 = Vector3D_GetPointOnSegment(v1, v2, k); Vector3D p2 = Vector3D_GetPointOnSegment(v2, v3, k); Vector3D p3 = Vector3D_GetPointOnSegment(v3, v4, k); return Vector3D_GetPointOnQuadCurve(&p1, &p2, &p3, k); } void Plane_Create(Plane *plane, const Vector3D *v1, const Vector3D *v2, const Vector3D *v3) { Vector3D _v1, _v2; _v1 = Vector3D_Subtract(v2, v1); _v2 = Vector3D_Subtract(v3, v1); plane->normal = Vector3D_CrossProduct(&_v1, &_v2); Vector3D_Normalize(&plane->normal); plane->dist = Vector3D_DotProduct(v1, &plane->normal); } float Plane_Distance(const Plane *plane, const Vector3D *point) { return Vector3D_DotProduct(point, &plane->normal) - plane->dist; } void Frustum_Calculate(Frustum *f, Vector3D v[5]) { /* +---------------------------------+ |\ 2 3 /| | \ / | | \ / | | \ / | | \ Frustum / | | \ / | | \ / | | 1 \ / 4 | + - - - -\- - - - - - - -/- - - - + \ \ / / \ \ / / \ \ / / \ \ / / \ \ 0 / / \ \ / / \ \-/ / \-/ */ Plane_Create(&f->planes[frLeft], &v[0], &v[1], &v[2]); Plane_Create(&f->planes[frRight], &v[0], &v[3], &v[4]); Plane_Create(&f->planes[frBottom], &v[0], &v[4], &v[1]); Plane_Create(&f->planes[frTop], &v[0], &v[2], &v[3]); Plane_Create(&f->planes[frFar], &v[1], &v[4], &v[3]); } int Frustum_IsPointInside(const Frustum *f, const Vector3D *point) { for (U32 i = 0; i < 5; i ++) if (Plane_Distance(&f->planes[i], point) <= -90.0f) return FALSE; return TRUE; } int Frustum_IsSphereInside(const Frustum *f, const Vector3D *sph_center, const float sph_sqr_radius) { int result = InsideFrustum; float sqr_dist; for (U32 i = 0; i < 5; i ++) { sqr_dist = Vector3D_DotProduct(sph_center, &f->planes[i].normal) - f->planes[i].dist; sqr_dist = (sqr_dist < 0) ? -SQR(sqr_dist) : SQR(sqr_dist); if (sqr_dist <= -sph_sqr_radius) return OutsideFrustum; else if (sqr_dist <= sph_sqr_radius) result = ClipsFrustum; } return result; } int Trace_CheckPlane(Vector3D *a, Vector3D *b, Vector3D *c, Vector3D *trace_a, Vector3D *trace_b, Vector3D *trace_nv) { Vector3D trace_plane_nv; Vector3D trace_hp; Vector3D trace_v1, trace_v2, trace_v3, trace_v4; float trace_ca, trace_cb; float trace_ccln, trace_ccvn; trace_v3 = Vector3D_Subtract(b, a); trace_v2 = Vector3D_Subtract(c, a); trace_plane_nv = Vector3D_CrossProduct(&trace_v3, &trace_v2); Vector3D_Normalize(&trace_plane_nv); trace_v1 = Vector3D_Subtract(trace_a, a); trace_v2 = Vector3D_Subtract(trace_b, a); trace_ca = Vector3D_DotProduct(&trace_v1, &trace_plane_nv); trace_cb = Vector3D_DotProduct(&trace_v2, &trace_plane_nv); if (trace_ca * trace_cb > -1.0f) return 0; //=================== calc hit point ===================// trace_ccln = Vector3D_DotProduct(&trace_v1, &trace_plane_nv); trace_ccvn = Vector3D_DotProduct(trace_nv, &trace_plane_nv); if (trace_ccvn == 0.0f) return 0; trace_ccln /= trace_ccvn; trace_ccln = fabsf(trace_ccln); trace_hp.x = trace_a->x + trace_nv->x * trace_ccln; trace_hp.y = trace_a->y + trace_nv->y * trace_ccln; trace_hp.z = trace_a->z + trace_nv->z * trace_ccln; trace_v2 = Vector3D_Subtract(&trace_hp, a); trace_v4 = Vector3D_CrossProduct(&trace_v3, &trace_v2); trace_ca = Vector3D_DotProduct(&trace_v4, &trace_plane_nv); if (trace_ca < 0.0f) return 0; trace_v1 = Vector3D_Subtract(c, b); trace_v2 = Vector3D_Subtract(&trace_hp, b); trace_v4 = Vector3D_CrossProduct(&trace_v1, &trace_v2); trace_ca = Vector3D_DotProduct(&trace_v4, &trace_plane_nv); if (trace_ca < 0.0f) return 0; trace_v1 = Vector3D_Subtract(a, c); trace_v2 = Vector3D_Subtract(&trace_hp, c); trace_v4 = Vector3D_CrossProduct(&trace_v1, &trace_v2); trace_ca = Vector3D_DotProduct(&trace_v4, &trace_plane_nv); if (trace_ca < 0.0f) return 0; if (Vector3D_SegmentLengthSQR(&trace_hp, trace_a) < Vector3D_SegmentLengthSQR(trace_b, trace_a)) { *trace_b = trace_hp; return 1; } return 0; } void Plane_FindClosestPointInTriangle(const Vector3D * PointA, const Vector3D * PointB, const Vector3D * PointC, const Vector3D * DistPoint, Vector3D * PointInTriangle) // TODO: not my style { Vector3D TriangleVectorA = Vector3D_Subtract(PointB, PointA); float TriangleVectorADistanceSQR = TriangleVectorA.x * TriangleVectorA.x + TriangleVectorA.y * TriangleVectorA.y + TriangleVectorA.z * TriangleVectorA.z; Vector3D TriangleVectorB = Vector3D_Subtract(PointC, PointA); float TriangleVectorBDistanceSQR = TriangleVectorB.x * TriangleVectorB.x + TriangleVectorB.y * TriangleVectorB.y + TriangleVectorB.z * TriangleVectorB.z; Vector3D TriangleVectorC = Vector3D_Subtract(DistPoint, PointA); float QA = Vector3D_DotProduct(&TriangleVectorA, &TriangleVectorC) / TriangleVectorADistanceSQR; float QB = Vector3D_DotProduct(&TriangleVectorB, &TriangleVectorC) / TriangleVectorBDistanceSQR; if ((QA >= 0.0f) && (QB >= 0.0f) && ((QA + QB) <= 1.0f)) { // projected of DistPoint in triangle PointInTriangle->x = PointA->x + TriangleVectorA.x * QA + TriangleVectorB.x * QB; PointInTriangle->y = PointA->y + TriangleVectorA.y * QA + TriangleVectorB.y * QB; PointInTriangle->z = PointA->z + TriangleVectorA.z * QA + TriangleVectorB.z * QB; } else { if (QA <= 0.0f) { if (QB <= 0.0f) { PointInTriangle->x = PointA->x; PointInTriangle->y = PointA->y; PointInTriangle->z = PointA->z; } else if (QB >= 1.0f) { PointInTriangle->x = PointC->x; PointInTriangle->y = PointC->y; PointInTriangle->z = PointC->z; } else { PointInTriangle->x = PointA->x + TriangleVectorB.x * QB; PointInTriangle->y = PointA->y + TriangleVectorB.y * QB; PointInTriangle->z = PointA->z + TriangleVectorB.z * QB; } } else if (QB <= 0.0f) { if (QA >= 1.0f) { PointInTriangle->x = PointB->x; PointInTriangle->y = PointB->y; PointInTriangle->z = PointB->z; } else { PointInTriangle->x = PointA->x + TriangleVectorA.x * QA; PointInTriangle->y = PointA->y + TriangleVectorA.y * QA; PointInTriangle->z = PointA->z + TriangleVectorA.z * QA; } } else { if (QA >= QB + 1) { PointInTriangle->x = PointB->x; PointInTriangle->y = PointB->y; PointInTriangle->z = PointB->z; } else if (QA <= QB - 1) { PointInTriangle->x = PointC->x; PointInTriangle->y = PointC->y; PointInTriangle->z = PointC->z; } else { QA = (1.0f + QA - QB) / 2.0f; QB = 1.0f - QA; PointInTriangle->x = PointA->x + TriangleVectorA.x * QA + TriangleVectorB.x * QB; PointInTriangle->y = PointA->y + TriangleVectorA.y * QA + TriangleVectorB.y * QB; PointInTriangle->z = PointA->z + TriangleVectorA.z * QA + TriangleVectorB.z * QB; } } } } float Vector2D_DistanceToSegmentSQR(const Vector2D *v1, const Vector2D *v2, const Vector2D *p) { Vector2D vd1, vd2, projection; const float lsqr = Vector2D_SegmentLengthSQR(v1, v2); if (lsqr == 0.0f) return Vector2D_SegmentLengthSQR(v1, p); vd1 = Vector2D_Subtract(p, v1); vd2 = Vector2D_Subtract(v2, v1); float plsqr = Vector2D_DotProduct(&vd1, &vd2) / lsqr; if (plsqr < 0.0f) return Vector2D_SegmentLengthSQR(v1, p); else if (plsqr > 1.0f) return Vector2D_SegmentLengthSQR(v2, p); projection.x = v1->x + plsqr * (v2->x - v1->x); projection.y = v1->y + plsqr * (v2->y - v1->y); return Vector2D_SegmentLengthSQR(p, &projection); } float Vector2D_DistanceToSegment(const Vector2D *v1, const Vector2D *v2, const Vector2D *p) { return sqrtf(Vector2D_DistanceToSegmentSQR(v1, v2, p)); }
C
#include "Sorter.h" /* prints an error message and exits the program */ void ERROR(char *error) { fprintf(stderr,"ERROR: %s\n",error); exit(1); } /* wrapper around malloc to detect out of memory errors */ void *safeMalloc(size_t size) { void *p; p=malloc(size); if(p==NULL) ERROR("Out of memory!"); return p; } /* wrapper around realloc to detect out of memory errors */ void *safeRealloc(void *ptr,size_t size) { void *p; p=realloc(ptr,size); if(p==NULL) ERROR("Out of memory!"); return p; } /* count the number of comma separated columns in the given line */ int countColumns(char *line) { char *p; int n; n=1; /* by default, line contains a field */ p=line; while(*p) { if(*p==',') /* we found a comma */ n++; /*increment number of fields*/ p++; } return n; /* return the number of fields */ } /* split a given line using the commas as delimiters, returns an array of data, expects n columns of data*/ Data *commaSplit(char *line,int n) { int start; int pos,col; Data *parts; int inquotes; parts=(Data *)safeMalloc(n*sizeof(Data)); /* allocate space for columns*/ pos=0; start=0; /*start of current column data*/ col=0; /*current column number */ inquotes=0; while(line[pos]!=0 && line[pos]!='\r' && line[pos]!='\n') { if(line[pos] == '\"') inquotes=!inquotes; if(!inquotes && line[pos]==',') /* we found a comma */ { parts[col].s=(char *)safeMalloc(pos-start+1); /* allocate space for column data*/ strncpy(parts[col].s,&line[start],pos-start); parts[col].s[pos-start]=0; /* insert string terminator */ start=pos+1; /* column data starts after the comma*/ col++; /*increment current column*/ } pos++; } parts[col].s=(char *)safeMalloc(pos-start+1); /* allocate space for last column*/ strncpy(parts[col].s,&line[start],pos-start); parts[col].s[pos-start]=0; /* insert string terminator */ return parts; } /* inserts a new row in the csv structure */ void insertRow(Data *rowdata,CSV *csv) { int col; if(csv->nrows==0) csv->rows=(Data **)safeMalloc(sizeof(Data *)); /*create single row entry */ else csv->rows=(Data **)safeRealloc(csv->rows,(csv->nrows+1)*sizeof(Data *)); /*create single row entry */ csv->rows[csv->nrows]=rowdata; csv->nrows++; } /* creates a new CSV structure */ CSV *newCSV(int nrows) { CSV *csv; csv=(CSV*)safeMalloc(sizeof(CSV)); /* create new CSV structure */ csv->ncols=0; csv->nrows=nrows; csv->header=NULL; if(nrows==0) csv->rows=NULL; else csv->rows=(Data **)safeMalloc(csv->nrows*sizeof(Data *)); /*create rows */ csv->types=NULL; return csv; } /* frees all the space used by the csv structure*/ void deleteCSV(CSV *csv) { int i,j; if(csv->header) { for(j=0; j<csv->ncols; j++) free(csv->header[j].s); free(csv->header); } for(i=0; i<csv->nrows; i++) { for(j=0; j<csv->ncols; j++) if(csv->types[j]==STRING) free(csv->rows[i][j].s); free(csv->rows[i]); } if(csv->types) free(csv->types); free(csv->rows); free(csv); } /* returns 1 if the string is an integer, 0 if it is not, -1 if an error is found */ int isInteger(char *val) { int i; if(val[0]==0) return -1; i=0; if(val[i]=='+' || val[i]=='-') /* skip sign if found */ i++; for(; i<strlen(val); i++) if(!isdigit(val[i])) return 0; return 1; } /* returns 1 if the string is a float, 0 if it is not, -1 if an error is found */ int isFloat(char *val) { int i; if(val[0]==0) return -1; i=0; if(val[i]=='+' || val[i]=='-') /* skip sign if found */ i++; for(; i<strlen(val); i++) if(!isdigit(val[i])) break; if(val[i++]!='.') return 0; for(; i<strlen(val); i++) if(!isdigit(val[i])) return 0; return 1; } /* detect the type of column in the csv */ int detectColumnType(int col,CSV *csv) { int isi,isf; int row; int type; type=UNKNOWN; for(row=0; row<csv->nrows; row++) { if((isf=isFloat(csv->rows[row][col].s))==1) { if(type!=STRING) type=FLOAT; } else if((isi=isInteger(csv->rows[row][col].s))==1) { if(type!=STRING && type!=FLOAT) type=INTEGER; } else if(!isi && !isf) type=STRING; } if(type==UNKNOWN) type=STRING; return type; } /* set the types for all columns in the CSV*/ void setTypes(CSV *csv) { int row,col; char *p; csv->types=(int*)safeMalloc(csv->ncols*sizeof(int)); for(col=0; col<csv->ncols; col++) csv->types[col]=detectColumnType(col,csv); for(col=0; col<csv->ncols; col++) { if(csv->types[col]==INTEGER) { for(row=0; row<csv->nrows; row++) { p=csv->rows[row][col].s; csv->rows[row][col].i=atoi(p); free(p); } } else if(csv->types[col]==FLOAT) { for(row=0; row<csv->nrows; row++) { p=csv->rows[row][col].s; csv->rows[row][col].f=atof(p); free(p); } } } } /* parses a CSV file given in stdin and saves it in a CSV structure */ CSV *inputCSV() { CSV *csv; char buffer[1024]; Data *rowdata; if(!fgets(buffer,1024,stdin)) /* read header */ ERROR("Empty file."); csv=newCSV(0); csv->ncols=countColumns(buffer); /* get expected number of columns */ csv->header=commaSplit(buffer,csv->ncols); /* fill column names */ while(fgets(buffer,1024,stdin)) /* read line by line*/ { rowdata=commaSplit(buffer,csv->ncols); /* get column values for current row */ insertRow(rowdata,csv); /* insert a new row in the csv structure */ } setTypes(csv); return csv; } /* send CSV structure to stdout */ void outputCSV(CSV *csv) { int i,j; for(i=0; i<csv->ncols; i++) { printf("%s",csv->header[i].s); if(i<csv->ncols-1) printf(","); } printf("\n"); for(i=0; i<csv->nrows; i++) { for(j=0; j<csv->ncols; j++) { if(csv->types[j]==STRING) printf("%s",csv->rows[i][j].s); else if(csv->types[j]==INTEGER) printf("%d",csv->rows[i][j].i); if(csv->types[j]==FLOAT) printf("%lf",csv->rows[i][j].f); if(j<csv->ncols-1) printf(","); } printf("\n"); } } /* sorts the csv using the selected column*/ void sortCSV(CSV *csv,char *column) { int col; for(col=0; col<csv->ncols; col++) if(!strcmp(csv->header[col].s,column)) break; if(col==csv->ncols) { deleteCSV(csv); ERROR("Column was not found!"); } mergeSort(csv,col); } /* compare two strings using the type to convert them to an integer or a float*/ int compare(Data a,Data b,int type) { switch(type) { case STRING: /* if they are strings */ return strcmp(a.s,b.s); break; case INTEGER: /* if they are integers, */ if(a.i>b.i) return 1; else if(a.i<b.i) return -1; else return 0; break; case FLOAT: /* if the values are floating point */ if(a.f>b.f) return 1; else if(a.f<b.f) return -1; else return 0; break; } return 0; } int main(int argc,char **argv) { char buffer[100]; CSV *csv; if(argc<2) ERROR("Missing arguments.\nUSAGE:\n ./sorter -c <column>"); else if(strcmp(argv[1],"-c")) { sprintf(buffer,"Invalid option \"%s\".",argv[1]); ERROR(buffer); } else if(argc==2) ERROR("Missing column name.\nUSAGE:\n ./sorter -c <column>"); csv=inputCSV(); sortCSV(csv,argv[2]); outputCSV(csv); deleteCSV(csv); return 0; }
C
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<math.h> int convert_deci(char *s,int b) { int q=1,d=0; int l=strlen(s); int i; for(i=l-1;i>=0;i--) { if(s[i]>='0'&&s[i]<='9') { d+=(s[i]-48)*q; } else if(s[i]>='A'&&s[i]<='F') { d+=(s[i]-55)*q; } q=q*b; } return d; } long int convert_decitobin(int n) { int a,r=1; long int b=0; while(n!=0) { a=n%2; b+=a*r; n/=2; r=r*10; } return b; } long int convert_decitoocta(int n) { int a,r=1; long int o=0; while(n!=0) { a=n%8; o+=a*r; n/=8; r=r*10; } return o; } char *convert_decitohexa(int n) { char *s=(char*)malloc(100*sizeof(char)); int i=0; int a; while(n!=0) { a=n%16; if(a<10) s[i]=a+48; else if(a>=10) s[i]=a+55; i++; n/=16; } int l=strlen(s); char temp; int j,k; for(j=l-1,k=0;k<l/2;k++,j--) { temp=s[k]; s[k]=s[j]; s[j]=temp; } return s; } int main() { int b,l,d; int t; long int x; char *s=(char*)malloc(10*sizeof(char)); char *n=(char*)malloc(10*sizeof(char)); printf("************************MENU***************************\n"); printf("Press 1 to convert decimal to binary\n"); printf("Press 2 to convert decimal to octa\n"); printf("Press 3 to convert decimal to hexa\n"); printf("Press 4 to convert binary to decimal\n"); printf("Press 5 to convert binary to octa\n"); printf("Press 6 to convert binary to hexa\n"); printf("Press 7 to convert octa to decimal\n"); printf("Press 8 to convert octa to binary\n"); printf("Press 9 to convert octa to hexa\n"); printf("Press 10 to convert hexa to decimal\n"); printf("Press 11 to convert hexa to binary\n"); printf("Press 12 to convert hexa to octa\n"); printf("*******************************************************\n"); scanf("%d",&b); switch(b) { case 1: printf("input a decimal number:"); scanf("%d",&d); x=convert_decitobin(d); printf("Binary number is:%ld\n",x); break; case 2: printf("input a decimal number:"); scanf("%d",&d); x=convert_decitoocta(d); printf("Octa number is:%ld\n",x); break; case 3: printf("input a decimal number:"); scanf("%d",&d); s=convert_decitohexa(d); printf("Hexa number is:"); printf("%s\n",s);; break; case 4: printf("input a binary number:"); scanf("%s",s); t=2; l=convert_deci(s,t); printf("Decimal number is:%d\n",l); break; case 5: printf("input a binary number:"); scanf("%s",s); t=2; l=convert_deci(s,t); x=convert_decitoocta(l); printf("Octa number is:%ld\n",x); break; case 6: printf("input a binary number:"); scanf("%s",s); t=2; l=convert_deci(s,t); n=convert_decitohexa(l); printf("Hexa number is:"); printf("%s\n",n); break; case 7: printf("input octa number:"); scanf("%s",s); t=8; l=convert_deci(s,t); printf("Decimal number is:%d\n",l); break; case 8: printf("input octa number:"); scanf("%s",s); t=8; l=convert_deci(s,t); x=convert_decitobin(l); printf("Binary number is:%ld\n",x); break; case 9: printf("input octa number:"); scanf("%s",s); t=8; l=convert_deci(s,t); n=convert_decitohexa(l); printf("Hexa number is:"); printf("%s\n",n); break; case 10: printf("input Hexa number:"); scanf("%s",s); t=16; l=convert_deci(s,t); printf("Decimal number is:%d\n",l); break; case 11: printf("input hexa number:"); scanf("%s",s); t=16; l=convert_deci(s,t); x=convert_decitobin(l); printf("Binary number is:%ld\n",x); break; case 12: printf("input hexa number:"); scanf("%s",s); t=16; l=convert_deci(s,t); x=convert_decitoocta(l); printf("Octa number is:%ld\n",x); break; default: break; } return 0; }
C
#include <jni.h> #include <stdio.h> #include "Arrays.h" JNIEXPORT jintArray JNICALL Java_Arrays_reverse(JNIEnv * env, jobject obj, jintArray array) { jint *body = (*env)->GetIntArrayElements(env,array,0); jsize len = (*env)->GetArrayLength(env,array); for (int i = 0; i <= len/2; ++i) { int temp = body[i]; body[i] = body[len-1-i]; body[len-1-i] = temp; } (*env)->ReleaseIntArrayElements(env,array,body,0); return array; }
C
//Tipos de variables #include<stdio.h> int main() { char b = 'F'; //1byte Rango: 0...255 %c short c = -15; //2bytes Rango: -128...127 %i int d = 1024; //2bytes Rango: -32768...32767 %i unsigned int e = 128; //2bytes Rango: 0...65535 %i long f = 123456; //4bytes %li float g = 15.678; //4bytes %f double h = 123123.123123; //8bytes %lf %.lf transforma a entero printf("El elemento es: %c",b); return 0; }
C
#ifndef ARRAY_HEADER #include <stdlib.h> /* array(int) my_variable; */ #define array(__data_type, __args...)\ __data_type* ## __args /* array_new(int, 10); */ #define array_new(__data_type, __size) \ (__data_type*)malloc(__size * sizeof(__data_type)) /* array_resize(int, 20); */ #define array_resize(__data_type, __size)\ (__data_type*)realloc(__size * sizeof(__data_type)) /* array_delet(my_varaiable)*/ #define array_delet(__array)\ free(__array) /* int size = array_size(my_varaiable) */ #define array_size(__var_name)\ sizeof(__var_name)/sizeof(__var_name[0]) /* int data = array_at(my_varaiable, index)*/ #define array_at(__var_name, __index)\ array_size(__var_name) <= (index+1) ? __var_name[index] : -1 /* array_push_back(int, my_varaiable, 55); */ #define array_push_back(__data_type, __var_name, __data)\ {\ long size = array_size(__var_name);\ size++;\ __var_name = array_resize(__data_type, size);\ __var_name[size-1] = __data;\ } #endif // !ARRAY_HEADER
C
#include "holberton.h" /** * _pow - calculates the value of `x` to the power of `y` * @x: the base integer * @y: the exponent integer * * Return: the result of `x` raised to the power of `y` */ int _pow(int x, int y) { if (y > 0) return (x * _pow(x, y - 1)); else if (y < 0) return (-1); else return (1); } /** * binary_to_uint - convert a binary string to an unsigned integer * @b: pointer to the binary string * * Return: the converted number of 0 if it fails */ unsigned int binary_to_uint(const char *b) { unsigned int result = 0, exp; int index = 0; if (!b) return (0); while (b[index]) index++; index--; for (exp = 0; index >= 0; index--, exp++) { if (b[index] == '1' || b[index] == '0') { result += (b[index] - '0') * _pow(2, exp); } else return (0); } return (result); }
C
/****************************************************************************** * @file Madragon main program. * * @author Linas Kaminskas and Nis Agger. * * @date 29-10-2015 * * @modified 01-11-2015 * ******************************************************************************/ #include <inttypes.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include "algorithm.h" #include "bitmatrix.h" #ifndef VERBOSE #define VERBOSE 0 #endif /* VERBOSE */ #ifndef DEBUG #define DEBUG 0 #endif /* DEBUG */ /* minu64t : Fast way of finding a minimum between two uint64_t. */ uint64_t minu64t(uint64_t a, uint64_t b); /* minu64t : Fast way of finding a maximum between two uint64_t. */ uint64_t maxu64t(uint64_t a, uint64_t b); /* initialise_madragon : Initiliase a Madragon game instance. */ uint32_t initialise_madragon(madragon_t *dest, FILE *src); /* destroy_madragon : Destroy a Madragon game instance. */ uint32_t destroy_madragon(madragon_t *src); int main(int argc, char *argv[]) { #if DEBUG == 1 auto uint64_t k = 0; #endif /* DEBUG == 1 */ auto bool decision_ans; auto madragon_t inst; #ifdef VERBOSE char *proc_name = argv[0]; #endif /* VERBOSE */ if (argc < 2) { #ifdef VERBOSE printf("%s: %s\n",proc_name,"missing input file as argument"); #endif /* VERBOSE */ return EXIT_FAILURE; } if (argc > 3) { #ifdef VERBOSE printf("%s: %s\n",proc_name,"too many arguments"); #endif /* VERBOSE */ return EXIT_FAILURE; } auto char *data_name = argv[1]; auto FILE *data_file = fopen(data_name,"r"); if (data_file == NULL) { #ifdef VERBOSE printf("%s: %s %s %s\n",proc_name,"file",data_name,"could not be opened or does not exist"); #endif /* VERBOSE */ return EXIT_FAILURE; } auto char *out_name = NULL; auto FILE *out_file = NULL; if (argc == 3) { out_name = argv[2]; out_file = fopen(out_name,"w"); if (out_file == NULL) { #ifdef VERBOSE printf("%s: %s %s %s\n",proc_name,"file",out_name,"could not be opened or does not exist"); #endif /* VERBOSE */ } } #if VERBOSE == 1 printf("%s: %s\n",proc_name,"reading data"); #endif /* VERBOSE == 1 */ if (initialise_madragon(&inst,data_file) != 0) { #ifdef VERBOSE printf("%s: %s\n",proc_name,"illegal madragon instance"); #endif /* VERBOSE */ return EXIT_FAILURE; } #if VERBOSE == 1 printf("%s: %s\n",proc_name,"read data"); #endif /* VERBOSE == 1 */ #if VERBOSE == 1 printf("%s: rows: %"PRIu64" columns: %"PRIu64" moves: %"PRIu64"\n",proc_name,inst.m,inst.n,inst.k); #endif /* VERBOSE == 1 */ #if VERBOSE == 1 printf("%s: %s\n",proc_name,"closing file"); #endif /* VERBOSE == 1 */ fclose(data_file); #if DEBUG == 1 printf("\n"); for (k = 0; k < MADRAGON_INST_COUNT; ++k) { bitmatrix_fprintf(stdout,inst.a[k]); printf("\n"); printf("\n"); } #endif /* DEBUG == 1 */ decision_ans = algorithm(&inst); if (out_file != NULL) operation_reconstruct(out_file,&inst); if (destroy_madragon(&inst) != 0) { #ifdef VERBOSE printf("%s: %s\n",proc_name,"could not destroy madragon instance"); #endif /* VERBOSE */ return EXIT_FAILURE; } #ifdef VERBOSE printf("%s: %s %s\n",proc_name,"the instance is",decision_ans? "solvable" : "unsolvable"); #endif /* VERBOSE */ return !decision_ans; } inline uint64_t minu64t(uint64_t a, uint64_t b) { return b ^ ((a ^ b) & -(a < b)); } inline uint64_t maxu64t(uint64_t a, uint64_t b) { return a ^ ((a ^ b) & -(a < b)); } uint32_t initialise_madragon(madragon_t *instance, FILE *data_file) { auto char data; auto uint32_t status; auto uint64_t i = 0, j = 0, k = 0; if (instance == NULL || data_file == NULL) return 1; status = fscanf(data_file,"%"SCNu64"",&(instance->m)); if (status == EOF) return 1; status = fscanf(data_file,"%"SCNu64"",&(instance->n)); if (status == EOF) return 1; status = fscanf(data_file,"%"SCNu64"",&(instance->k)); if (status == EOF) return 1; if (instance->m == 0 || instance->n == 0 || instance->k == 0) return 1; status = 0; for (k = 0; k < MADRAGON_INST_COUNT; ++k) { instance->a[k] = bitmatrix_malloc(instance->m,instance->n); status |= (instance->a[k] == NULL); } instance->o = operation_malloc(k); status |= (instance->o == NULL); if (status) return destroy_madragon(instance); k = 0; while(status != EOF) { status = fscanf(data_file,"%c",&data); #if DEBUG == 1 printf("%c",data); #endif /* DEBUG */ if (data == 'b' || data == 'w') { bitmatrix_set(instance->a[k],(data == 'w'),i,j); j = (uint64_t) (j + 1) % instance->n; i = (uint64_t) (i + (j == 0)) % instance->m; k = (uint64_t) (k + (i == 0 && j == 0)) % MADRAGON_INST_COUNT; } } return 0; } uint32_t destroy_madragon(madragon_t *instance) { auto uint64_t i; if (instance == NULL) return 1; for (i = 0; i < MADRAGON_INST_COUNT; ++i) bitmatrix_free(instance->a[i]); operation_free(instance->o); return 0; }
C
#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ main() { int count = 0; while (count < 100) { printf("This goes on forever, HELP!!!\n"); count +=10; printf("\t%d", count); count -= 10; printf("\t%d", count); printf("Ctrl - c will help"); } }
C
#include <stdio.h> #include <alloc.h> #include <conio.h> #include "matrixop.h" float *aloca( int dim1, int dim2 ) { float *rez; rez = (float*) malloc( dim1*dim2*sizeof(float) ); return rez; } void atribuie_val( float *mat, int dim1, int dim2 ) { float i,j; for(i=0;i<dim1;i++) for(j=0;j<dim2;j++) mat[i*dim2+j] = (i+1)*(j+1); } void afiseaza( float *mat, int dim1, int dim2 ) { int i,j; for(i=0;i<dim1;i++) { printf("\n"); for(j=0;j<dim2;j++) printf("%8.2f",mat[i*dim2+j]); } printf("\n"); } float *inmulteste( float *mat1, int dim1, int dim2, float *mat2, int dim3, int dim4 ) { int i,j,k; float *mat3; mat3 = aloca( dim1,dim4 ); for(i=0;i<dim1;i++) for(j=0;j<dim4;j++) { mat3[i*dim4+j] = 0; for(k=0;k<dim2;k++) mat3[i*dim4+j] = mat3[i*dim4+j] + mat1[i*dim2+k]*mat2[k*dim4+j]; } return mat3; } 
C
/* Minimal TCP client example. The client connects to port 8080 on the local machine and prints up to 255 received characters to the console, then exits. To test it, try running a minimal server like this on your local machine: echo "Here is a message" | nc -l -6 8080 */ #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include <errno.h> #define BUFSZ 255 int main(int argc, char** argv) { /* inpsired heavily by man 3 getaddrinfo */ char host[BUFSZ], resource[BUFSZ], protocol[BUFSZ], filename[BUFSZ]; struct addrinfo hints; struct addrinfo * result, * rp; int sock_fd, s; memset(&host, 0, BUFSZ); memset(&protocol, 0, BUFSZ); memset(&resource, 0, BUFSZ); memset(&filename, 0, BUFSZ); memset(&hints,0,sizeof(struct addrinfo)); hints.ai_socktype = SOCK_STREAM; // Retrieve command line args if( argc < 2 ) { fprintf(stderr, "usage: hw1 link\n"); exit(1); } char *host_start; if((host_start = strstr(argv[1], "//")) == NULL) { // TODO: Not a very robust test for invalid host... fprintf(stderr, "Invalid hostname\n"); exit(1); } // Get protocol int protocol_len = strlen(argv[1]) - strlen(host_start) - 1; // remove colon strncpy(protocol, argv[1], protocol_len); // Get host + resource strcpy(host, host_start+2); char *resource_start = strstr(host, "/"); // Default to root if no resource requested if(resource_start == NULL || strcmp(resource, "/") == 0) { strcpy(resource, "/"); strcpy(filename, "index.html"); } else { strcpy(resource, resource_start); int host_length = strlen(host) - strlen(resource); host[host_length] = '\0'; strcpy(filename, (char*) strrchr(resource, '/') + 1); if(filename[0] == '\0') strcpy(filename, "index.html"); } printf("Connecting to: %s %s\n", host, resource); // Resolve address info if ((s = getaddrinfo(host, protocol, &hints, &result)) != 0){ fprintf(stderr, "ERROR: %s\n", gai_strerror(s)); exit(1); } // Connect for (rp = result; rp != NULL; rp = rp->ai_next) { sock_fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (sock_fd == -1) continue; if (connect(sock_fd, rp->ai_addr, rp->ai_addrlen) != -1) break; /* Success */ close(sock_fd); } if (rp == NULL) { fprintf(stderr, "could not connect\n"); exit(1); } freeaddrinfo(result); char query[BUFSZ]; memset(query, 0, sizeof(query)); sprintf(query, "GET %s HTTP/1.0\r\nHost: %s\r\n\r\n", resource, host); // Send query write(sock_fd, query, strlen(query)); // Create buffer and file for response char *buf = (char *) calloc(BUFSZ+1, sizeof(char)); char *buf2 = (char *) calloc(BUFSZ+1, sizeof(char)); // Process response int recv_count = recv(sock_fd, buf, BUFSZ, 0); if(recv_count == -1) { fprintf(stderr, "Error: receive failed\n"); exit(1); } if(strstr(buf, "200 OK") == NULL) { fprintf(stderr, "Error: response is not 200\n"); exit(1); } FILE *output = fopen(filename, "w"); int output_fd = fileno(output); char *response = NULL; char *curr = buf; char *prev = buf2; int response_len = 0; do { // Found "...\r\n\r\n..." if((response = strstr(curr, "\r\n\r\n")) != NULL) { response += 4; response_len = BUFSZ - (response - curr); break; } // First time around if(prev == NULL) continue; else { prev = curr; if((recv_count = recv(sock_fd, curr, BUFSZ, 0)) < 1) { fprintf(stderr, "Error: end of transmission reached without EOH\n"); exit(1); } // Found "...\r\n\r" + "\n..." if(curr[0] == '\n' && prev[BUFSZ-3] == '\r' && prev[BUFSZ-2] == '\n' && prev[BUFSZ-1] == '\r') { response = curr + 1; response_len = BUFSZ - 1; break; } // Found "...\r\n" + "\r\n..." if(curr[0] == '\r' && curr[1] == '\n' && prev[BUFSZ-2] == '\r' && prev[BUFSZ-1] == '\n') { response = curr + 2; response_len = BUFSZ - 2; break; } // Found "...\r" + "\n\r\n..." if(curr[0] == '\n' && curr[1] == '\r' && curr[2] == '\n' && prev[BUFSZ-1] == '\r') { response = curr + 3; response_len = BUFSZ - 3; break; } } } while(response == NULL); write(output_fd, response, response_len); while((recv_count = recv(sock_fd, buf, BUFSZ, 0)) > 0) write(output_fd, buf, recv_count); if(recv_count == -1) { fprintf(stderr, "Receive failed\n"); exit(1); } close(output_fd); printf("Downloaded %s\n", filename); shutdown(sock_fd,SHUT_RDWR); exit(0); }
C
#ifndef CONV_H #define CONV_H #include <stdlib.h> #include <math.h> #include <assert.h> #include "uwnet.h" #include "image.h" // Add bias terms to a matrix // matrix m: partially computed output of layer // matrix b: bias to add in (should only be one row!) void forward_convolutional_bias(matrix m, matrix b); // Calculate bias updates from a delta matrix // matrix delta: error made by the layer // matrix db: delta for the biases void backward_convolutional_bias(matrix delta, matrix db); // Make a column matrix out of an image // image im: image to process // int size: kernel size for convolution operation // int stride: stride for convolution // returns: column matrix matrix im2col(image im, int size, int stride); // The reverse of im2col, add elements back into image // matrix col: column matrix to put back into image // int size: kernel size // int stride: convolution stride // image im: image to add elements back into void col2im(matrix col, int size, int stride, image im); // Run a convolutional layer on input // layer l: pointer to layer to run // matrix in: input to layer // returns: the result of running the layer matrix forward_convolutional_layer(layer l, matrix in); // Run a convolutional layer backward // layer l: layer to run // matrix prev_delta: error term for the previous layer void backward_convolutional_layer(layer l, matrix prev_delta); // Update convolutional layer // layer l: layer to update // float rate: learning rate // float momentum: momentum term // float decay: l2 regularization term void update_convolutional_layer(layer l, float rate, float momentum, float decay); // Make a new convolutional layer // int w: width of input image // int h: height of input image // int c: number of channels // int size: size of convolutional filter to apply // int stride: stride of operation layer make_convolutional_layer(int w, int h, int c, int filters, int size, int stride, ACTIVATION activation); #endif
C
/*Write a program that reads three floating values and check if it is possible to make a triangle with them */ #include<stdio.h> int main(){ int s1,s2,s3; printf("Enter length of first side\n"); scanf("%d",&s1); printf("Enter length of second side\n"); scanf("%d",&s2); printf("Enter length of third side\n"); scanf("%d",&s3); if(s1<(s2+s3) && s2<(s1+s3) && s3<(s1+s2)){ printf("Triangle can be formed\n"); }else printf("Triangle can not be formed try again\n"); return 0; }
C
//Programa 9: desenvolver um programa que utilize a função concat(char *str1, char *str2) para concatenar duas strings. A função deve fazer a alocação dinâmica de memória para acomodar a nova string concatenada na memória. Lembre-se de verificar o tamanho do espaço de memória disponível e caso não haja espaço suficiente o programa deve retornar uma mensagem de erro para o usuário. #include <stdio.h> #include <string.h> char *concat(char *str1, char *str2){ char *str3 = (char *) malloc(1 + (strlen(str1) + strlen(str2))); int index = 0; if (str3 == NULL){ return "STRIGS MUITO GRANDE. ESPAÇO EM MEMÓRIA INSUFICIENTE."; } while (*str1 != '\0'){ str3[index] = *str1; index++; str1++; } while (*str2 != '\0'){ str3[index] = *str2; index++; str2++; } str3[index] = '\0'; return str3; } int main(void) { char str1[] = "Teste", str2[] = " 123"; printf("%s", concat(str1, str2)); }
C
#include<stdio.h> #include<signal.h> #include<stdlib.h> #include<unistd.h> void ouch(int sig){ printf("Oh, I got signal %d\n", sig); (void) signal(SIGINT, SIG_DFL); } int main(){ (void) signal(SIGINT, ouch); while(1){ printf("hello world!\n"); sleep(1); } }
C
#include "hash_tables.h" /** * key_index - return the index which the key should be save * @key: The key of the disctionary * @size: The size of the array * Return: The index. This index is the value of the size % hash of key. */ unsigned long int key_index(const unsigned char *key, unsigned long int size) { unsigned long int hash = 0; hash = hash_djb2(key); return (hash % size); }
C
//аналог ls -l и ls-lR (а так же ls файлового) //Компиляция: gcc art-ls.c -o art_ls //Пример запуска: ./art_ls -lR /home/user/Desktop/ #include <string.h> #include <stdio.h> #include <sys/stat.h> #include <grp.h> #include <stdlib.h> #include <dirent.h> #include <time.h> #include <pwd.h> inline void abort_prg(const char* str); inline char print_type(int m); inline void set_mode(int m); inline void file_ls(const char* filename); //для файлов inline void ls_l(const char* dirname); //-l void ls_R(const char *dirname); //-lR int main(int argc, const char* argv[]) { const char* dirname; struct stat st; if (argc < 2) //Работаем с текущей директорией(при этом применяем аналог ls -l) { dirname = "."; ls_l(dirname); return 0; } else { if (argc == 2) //работаем с текущей директорией (взависимости от argv[1] решаем , что делать) { if (!strcmp(argv[1], "-l")) //если пользователь просит -l { dirname = "."; ls_l(dirname); return 0; } if (!strcmp(argv[1], "-lR")) //пользователь просит -lR { dirname = "."; ls_R(dirname); return 0; } dirname = argv[1]; if (0 == stat(dirname, &st) && '-' == print_type(st.st_mode)) //Если файл { file_ls(dirname); return 0; } ls_R(dirname); // если директория - рекурсивный ls (аналог ls -R) return 0; } if (argc>2) //с переданной директорией решаем, что делать { dirname = argv[2]; if (!strcmp(argv[1], "-l")) { ls_l(dirname); return 0; } else { if (!strcmp(argv[1], "-lR")) { ls_R(dirname); return 0; } } } } return 0; } inline void abort_prg(const char* str) { fprintf(stderr, "%s\n", str); exit(1); } inline char print_type(int m) { if(m & S_IFDIR) return 'd'; else if(m & S_IFBLK) return 'b'; else if(m & S_IFCHR) return 'c'; else if(m & S_IFIFO) return 'p'; else return '-'; } inline void set_mode(int m) { if (m & S_IRUSR) printf("r"); else printf("-"); if (m & S_IWUSR) printf("w"); else printf("-"); if (m & S_IXUSR) printf("x"); else printf("-"); if (m & S_IRGRP) printf("r"); else printf("-"); if (m & S_IWGRP) printf("w"); else printf("-"); if (m & S_IXGRP) printf("x"); else printf("-"); if (m & S_IROTH) printf("r"); else printf("-"); if (m & S_IWOTH) printf("w"); else printf("-"); if (m & S_IXOTH) printf("x"); else printf("-"); } inline void file_ls(const char* filename) { struct stat st; struct passwd* user; struct group* group; if (0 == stat(filename, &st)) { int mode = st.st_mode; struct tm* time; char time_str[80]; printf("%c", print_type(mode)); set_mode(mode); printf(" %d ", (int)st.st_nlink); user = getpwuid(st.st_uid); if (NULL == user) abort_prg("st_uid не найден"); printf("%s ", user->pw_name); group = getgrgid(st.st_gid); if (NULL == group) abort_prg("st.gid не найден"); printf("%s ", group->gr_name); printf("%d ", (int)st.st_size); time = localtime((const time_t*)&(st.st_mtime)); strftime(time_str, 80, "%b %e %H:%M", time); printf("%s ", time_str); printf("%s\n", filename); } } inline void ls_l(const char* dirname) { DIR* dir; struct dirent* d; char* dname; int mode; struct stat st; struct passwd *user; struct group *group; struct tm *time; char time_str[80]; int dirsize; dirsize = 0; printf("%s:\n", dirname); dir = opendir(dirname); while((d = readdir(dir)) != NULL) { dname = (char*) malloc((strlen(dirname) + strlen(d->d_name) + 2)*sizeof(char)); if (NULL == dname) abort_prg("Недостаточно памяти"); strcpy(dname, dirname); strcat(dname, "/"); strcat(dname, d -> d_name); if (stat(dname, &st) || d -> d_name[0] == '.') continue; mode = st.st_mode; if (!(mode & S_IRUSR)) continue; dirsize=dirsize + st.st_size/512; free(dname); } closedir(dir); printf("Итого: %d\n", dirsize); dir = opendir(dirname); while((d = readdir(dir)) != NULL) { dname = (char*) malloc((strlen(dirname) + strlen(d->d_name) + 2)*sizeof(char)); if (NULL == dname) abort_prg("Недостаточно памяти"); strcpy(dname, dirname); strcat(dname, "/"); strcat(dname, d -> d_name); if (stat(dname, &st) || d -> d_name[0] == '.') continue; mode = st.st_mode; if (!(mode & S_IRUSR)) continue; printf("%c", print_type(mode)); set_mode(mode); printf(" %d ", (int)st.st_nlink); user = getpwuid(st.st_uid); printf("%s ", user -> pw_name); group = getgrgid(st.st_gid); printf("%s ", group -> gr_name); printf("%d ", (int)st.st_size); time = localtime((const time_t*)&(st.st_mtime)); strftime(time_str, 80, "%b %e %H:%M", time); printf("%s ", time_str); printf(" %s\n", d -> d_name); free(dname); } printf("\n"); } void ls_R(const char *dirname) { DIR* dir; struct dirent* d; dir = opendir(dirname); ls_l(dirname); while((d = readdir(dir)) != NULL) { DIR* theD; char* theDirname; theDirname = (char*) malloc((strlen(dirname) + strlen(d -> d_name) + 2)*sizeof(char)); if (NULL == theDirname) abort_prg("Недостаточно памяти"); strcpy(theDirname, dirname); strcat(theDirname, "/"); strcat(theDirname, d -> d_name); theD = opendir(theDirname); if(theD != NULL && d -> d_name[0] != '.') { closedir(theD); ls_R(theDirname); } free(theDirname); } }
C
# include <stdio.h> int main(){ int a[] = {2,3,7,8,8,12}, aL = sizeof(a)/sizeof(int); int b[] = {7,8}, bL = sizeof(b)/sizeof(int); int i, j, k; int c[20]; for(i=0, j=0, k=0 ; ; ++k){ if((i >= aL-1)&&(j >= bL-1)) break; else if(j >= bL-1){ c[k] = a[i]; i++; continue; } else if(i >= aL-1){ c[k] = b[j]; j++; continue; } if(a[i]<b[j]){ c[k] = a[i]; i++; } else if(a[i] > b[j]){ c[k] = b[j]; j++; } else{ c[k] = b[j]; c[++k] = b[j]; j++;i++; } } for(i=0; i<=k; i++){ printf("%d ",c[i]); } }
C
#include <stdio.h> int main() { int marks; printf("Enter marks: "); scanf("%d", &marks); if (marks>=85 && marks<=100) printf("The kid's grade is A!"); else if (marks>=70 && marks<85) printf("The kid's grade is B!"); else if (marks>=55 && marks<70) printf("The kid's grade is C!"); else if (marks>=40 && marks<55) printf("The kid's grade is D!"); else if (marks<40) printf("The kid's grade is F!"); else printf("Please enter valid mark."); return 0; }
C
/* barrier_nocheck.c Sets up a barrier blocking n threads. If more than n arrive, the rest can go through. Doesn't check for errors. */ #include <pthread.h> #include <stdio.h> static pthread_cond_t bcond = PTHREAD_COND_INITIALIZER; static pthread_mutex_t bmutex = PTHREAD_MUTEX_INITIALIZER; static int count = 0; // How many to go // Initialize the barrier to be size n void init_barrier(int n) { pthread_mutex_lock(&bmutex); count = n; fprintf(stderr, "count initialized to: %d\n", count); pthread_mutex_unlock(&bmutex); } // Wait at the barrier until all threads arrive void wait_barrier(void) { pthread_mutex_lock(&bmutex); // Safely, access the barrier value --count; // We're in! fprintf(stderr, "count decremented to: %d\n", count); // Anyone left? Then release lock and wait. while (count) pthread_cond_wait(&bcond, &bmutex); pthread_cond_broadcast(&bcond); // We're good! Wake up! pthread_mutex_unlock(&bmutex); // And we're done with the lock. }
C
/* Description: This file checks the if there is missing files from jan-may missing txt files Compile Instructions: * gcc -o check_jan-may_missing_txt check_jan-may_missing_txt.c -std=c99 * ./check_jan-may_missing_txt */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <time.h> int main() { char date[9]; time_t t = time(NULL); struct tm * ptm = gmtime(&t); char year[4]; char month[2]; char Test_exist[200]; FILE *fptr; fptr = fopen("jan_may_missing_files.txt", "w"); if (fptr == NULL) { printf("Error!\n"); exit(1); } int cmd; ptm->tm_year = 115; ptm->tm_mon = 0; ptm->tm_mday = 1; mktime(ptm); strftime(date, 9, "%Y%m%d", ptm); printf("date: %s\n", date); memcpy(&year, &date[0], 4); year[4] = '\0'; memcpy(&month, &date[4], 2); month[2] = '\0'; for (int i = 1; i <= 151; i++) { for (int j = 0; j <= 23; j++) { if (j <= 9) { snprintf(Test_exist, 200, "hdfs dfs -test -e ./Wiki/%s-%s/pagecounts-%s-0%d0000.txt", year, month, date, j); cmd = system(Test_exist); } else { snprintf(Test_exist, 200, "hdfs dfs -test -e ./Wiki/%s-%s/pagecounts-%s-%d0000.txt", year, month, date, j); cmd = system(Test_exist); } if (cmd != 0) { printf("Missing date: %s-%d\n", date, j); fprintf(fptr, "Missing date: %s-%d\n", date, j); } } ptm->tm_mday += 1; mktime(ptm); strftime(date, 9, "%Y%m%d", ptm); memcpy(&year, &date[0], 4); year[4] = '\0'; memcpy(&month, &date[4], 2); month[2] = '\0'; } fclose(fptr); return 0; }
C
#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int c,f; //nhap do c printf("nhap do c ="); scanf("%f", &c); printf("nhap do f ="); scanf("%f", &f); c =((f-32)/9)*5; }
C
/** * @file * VuoMesh C type definition. * * @copyright Copyright © 2012–2016 Kosada Incorporated. * This code may be modified and distributed under the terms of the MIT License. * For more information, see http://vuo.org/license. */ #ifndef VUOMESH_H #define VUOMESH_H #include "VuoPoint2d.h" #include "VuoPoint3d.h" #include "VuoPoint4d.h" #include "VuoList_VuoPoint2d.h" #include "VuoList_VuoPoint3d.h" /** * @ingroup VuoTypes * @defgroup VuoMesh VuoMesh * Vertices representing a 3D object. * * @{ */ /** * The way in which an @c elements array should be interpreted during rasterization. */ typedef enum { VuoMesh_IndividualTriangles, ///< GL_TRIANGLES, requires `elementCount % 3 == 0`. VuoMesh_TriangleStrip, ///< GL_TRIANGLE_STRIP, requires `elementCount >= 3`. VuoMesh_TriangleFan, ///< GL_TRIANGLE_FAN, requires `elementCount >= 3`. VuoMesh_IndividualLines, ///< GL_LINES, requires `elementCount % 2 == 0`. VuoMesh_LineStrip, ///< GL_LINE_STRIP, requires `elementCount >= 2`. VuoMesh_Points ///< GL_POINTS } VuoMesh_ElementAssemblyMethod; /** * One set of vertices, with associated normals and other per-vertex data, within a mesh. */ typedef struct { unsigned int vertexCount; ///< Number of vertices in @c positions, @c normals, @c tangents, @c bitangents, and @c textureCoordinates. /// @todo Change to `VuoDictionary_VuoPoint4D vertexAttributes;` once dictionaries exist: a string-keyed list of equal-size arrays of points (vertex attributes). Typically contains at least 'positions', 'normals', and 'textureCoordinates'. VuoPoint4d * positions; ///< XYZW vertex positions VuoPoint4d * normals; ///< Vertex normals. May be @c NULL. VuoPoint4d * tangents; ///< Vertex tangents. May be @c NULL. VuoPoint4d * bitangents; ///< Vertex bitangents. May be @c NULL. VuoPoint4d * textureCoordinates; ///< STRQ texture coordinates. May be @c NULL. unsigned int elementCount; ///< Number of elements in @c elements. /** * An array of size elementCount of integer elements (triangle indices) which are indexes into @c positions. * (Requires conversion to i16 for OpenGL ES unless GL_OES_element_index_uint.) */ unsigned int * elements; /// The way in which the @c elements array should be interpreted during rasterization. VuoMesh_ElementAssemblyMethod elementAssemblyMethod; /** * For lines, the width (in scene units). * For points, the width and height (in scene units). */ VuoReal primitiveSize; /// GL_BACK (default), GL_NONE, or GL_FRONT unsigned int faceCullingMode; /** * References to mesh data uploaded to the GPU. */ struct { unsigned int combinedBuffer; unsigned int combinedBufferSize; void *normalOffset; void *tangentOffset; void *bitangentOffset; void *textureCoordinateOffset; unsigned int elementBuffer; unsigned int elementBufferSize; } glUpload; } VuoSubmesh; /** * A 3D mesh that contains one or more submeshes (allowing each submesh to have a different element assembly method). */ typedef struct _VuoMesh { unsigned int submeshCount; ///< Number of items in @c submeshes. VuoSubmesh *submeshes; ///< The submeshes that together define the shape of the mesh. All VuoSubmeshes are assumed to have the same primitive type (points, lines, triangles), but the assembly can vary (e.g., a single mesh can contain submeshes with VuoMesh_IndividualLines and VuoMesh_LineStrip). } *VuoMesh; VuoSubmesh VuoSubmesh_make(unsigned int vertexCount, unsigned int elementCount); VuoSubmesh VuoSubmesh_makeGl(unsigned int vertexCount, unsigned int combinedBuffer, unsigned int combinedBufferSize, void *normalOffset, void *tangentOffset, void *bitangentOffset, void *textureCoordinateOffset, unsigned int elementCount, unsigned int elementBuffer, unsigned int elementBufferSize, VuoMesh_ElementAssemblyMethod elementAssemblyMethod); unsigned long VuoSubmesh_getGlMode(VuoSubmesh submesh); unsigned long VuoSubmesh_getSplitPrimitiveCount(VuoSubmesh submesh); unsigned long VuoSubmesh_getSplitVertexCount(VuoSubmesh submesh); unsigned long VuoSubmesh_getCompleteElementCount(const VuoSubmesh submesh); VuoMesh VuoMesh_make(unsigned int itemCount); void VuoMesh_upload(VuoMesh mesh); VuoMesh VuoMesh_makeFromSingleSubmesh(VuoSubmesh submesh); VuoMesh VuoMesh_makeQuad(void); VuoMesh VuoMesh_makeQuadWithoutNormals(void); VuoMesh VuoMesh_makeEquilateralTriangle(void); VuoMesh VuoMesh_make_VuoPoint2d(VuoList_VuoPoint2d positions, VuoMesh_ElementAssemblyMethod elementAssemblyMethod, VuoReal primitiveSize); VuoMesh VuoMesh_make_VuoPoint3d(VuoList_VuoPoint3d positions, VuoMesh_ElementAssemblyMethod elementAssemblyMethod, VuoReal primitiveSize); VuoMesh VuoMesh_copy(const VuoMesh mesh); const char *VuoMesh_cStringForElementAssemblyMethod(VuoMesh_ElementAssemblyMethod elementAssemblyMethod); VuoBox VuoMesh_bounds(const VuoMesh mesh, float matrix[16]); bool VuoMesh_isPopulated(const VuoMesh mesh); VuoMesh VuoMesh_makeFromJson(struct json_object * js); struct json_object * VuoMesh_getJson(const VuoMesh value); char * VuoMesh_getSummary(const VuoMesh value); /** * For a given element assembly method, returns the equivalent assembly method for individual elements (i.e., after they've been expanded from strips/fans). */ static inline VuoMesh_ElementAssemblyMethod VuoMesh_getExpandedPrimitiveMode(const VuoMesh_ElementAssemblyMethod inputMode) { if (inputMode == VuoMesh_IndividualTriangles || inputMode == VuoMesh_TriangleFan || inputMode == VuoMesh_TriangleStrip) return VuoMesh_IndividualTriangles; else if (inputMode == VuoMesh_IndividualLines || inputMode == VuoMesh_LineStrip) return VuoMesh_IndividualLines; else return VuoMesh_Points; } ///@{ /** * Automatically generated function. */ VuoMesh VuoMesh_makeFromString(const char *str); char * VuoMesh_getString(const VuoMesh value); void VuoMesh_retain(const VuoMesh v); void VuoMesh_release(const VuoMesh v); ///@} /** * @} */ #endif
C
#include "human.h" struct teacher { human thehuman; // "human" int WorkExp; // char Degree[40]; // char FacultyName[30]; // }; // void SetDegree(teacher* edit_teacher, char new_degree[]); // void SetFacultyName(teacher* edit_teacher, char new_facultyname[]); // teacher CreateTeacher(human buf_human, int buf_WorkExp, char buf_Degree[], char buf_FacultyName[]); // void PrintTeacher(teacher buf_teacher); // teacher ConsoleCreateTeacher();
C
#include <stdio.h> #include <stdlib.h> int main() { int a = 7; int b = a & ; printf("%d\n", b); }
C
#include <stdio.h> #include <time.h> #include <stdlib.h> #include <stdbool.h> void main(){ int mat[8][8],i,j; bool sim = true; loop: srand(time(NULL)); for(i = 0;i < 8;i++){ for(j = 0;j < 8;j++){ mat[i][j] = rand()%2; } } for(i = 0;i<8;i++){ for(j = 0;j < 8;j++){ if(mat[i][j] != mat[j][i]){ sim = false; } } } if(!sim){ printf("A matriz nao e simetrica\n"); }else{ printf("A matriz e simetrica\n"); } getch(); goto loop; }
C
#ifndef STRUCTSERVIDOR_H_ #define STRUCTSERVIDOR_H_ #include <stddef.h> /* Este es el Struct que manda el Servidor, y recibe el Cliente */ typedef struct structServidor structServidor_t; structServidor_t* structServidor_crear(unsigned int id, int x, int y, int estado, unsigned int tipo); unsigned int structServidor_obtener_id(structServidor_t*); void structServidor_obtener_posicion(structServidor_t*, int*, int*); int structServidor_obtener_estado(structServidor_t*); void structServidor_destruir(structServidor_t*); size_t structServidor_obtener_tamanio(); unsigned int structServidor_obtener_tipo(structServidor_t*); #endif /* STRUCTSERVIDOR_H_ */
C
/*һά. ÿдǵģÿдϵǵ. вһǷڡ ʱ临ӶСO(N) 飺 1 2 3 2 3 4 3 4 5 1 3 4 2 4 5 4 5 6 1 2 3 4 5 6 7 8 9*/ #include<stdio.h> #include<Windows.h> #define N 3 #pragma warning(disable:4996) int Find(int a[N][N], int row, int col) { int key; printf("Ҫҵ\n"); scanf("%d", &key); int row1 = row - 1; int col1 = 0; while (row1 < row&&col1 < col) { if (a[row1][col1] == key) { return 1; break; } else { if (a[row1][col1]>key) { row1--; } else { col1++; } } } return -1; } int main() { int a[N][N] = { { 1, 2, 3 }, { 2, 3, 4 }, { 3, 4, 5 } }; printf("1ʾҵˣ-1ʾûҵ\n%d\n", Find(a, N, N)); system("pause"); return 0; }
C
// gcc -Wall -g `pkg-config --libs --cflags gtk+-3.0` label.c -o label #include <gtk/gtk.h> static void on_window_closed (GtkWidget *widget, gpointer data) { gtk_main_quit (); } int main (int argc, char *argv[]) { GtkWidget *window, *label; /* Initialization */ gtk_init (&argc, &argv); /* Create a new top-level window */ window = gtk_window_new (GTK_WINDOW_TOPLEVEL); /* Connect callback for the destroy event */ g_signal_connect (window, "destroy", G_CALLBACK(on_window_closed), NULL); /* Create a label */ label = gtk_label_new (NULL); /* Set the text of the label with a markup language */ gtk_label_set_markup (GTK_LABEL(label), "<small>Small</small>\n" "<big>Big</big>\n" "<b>Bold</b>\n" "<span foreground=\"#ff0000\">Foreground Color</span>"); /* Add the label to the window */ gtk_container_add (GTK_CONTAINER(window), label); /* Set the title of the window */ gtk_window_set_title (GTK_WINDOW(window), "Dibujar 1.0"); /* Set the default size of the window (dependsd on window manager) */ gtk_window_set_default_size (GTK_WINDOW(window), 640, 480); /* Show the label and the window */ gtk_widget_show_all (window); /* Got to the main loop */ gtk_main (); return 0; }
C
#include <stdio.h> // int aloca(int numero){ // int contador, *numeros; // numeros = (int *)malloc(num*sizeof(int)); // for(contador = 0; contador < numero; contador++){ // printf("Numero [%d]: ", contador + 1); // scanf("%d", &numeros[contador]); // } // return numeros; // } // float media(int numeros, int numero){ // float media = 0.0; // int contador; // for(contador = 0; contador < numero; contador++){ // media += numeros[contador]; // } // return media/numero; // } // void exibe(int *numeros, int numero){ // int contador; // for(contador = 0; contador < numero; contador++){ // printf("%3d", numeros[contador]); // } // } // int main(void){ // int numero = 1, *numeros; // while(numero){ // printf("Media de quantos numeros (0 para sair): "); // scanf("%d", &numero); // if(numero > 0){ // numeros = aloca(numero); // exibe(numeros, numero); // printf("A media dos numeros eh: %.2f\n", media(numeros, numero)); // free(numeros); // } // } // } void soma(int a, int b){ int soma; soma = 2*a + b; printf("%d\n",soma); return; } int main(){ int a, b; scanf("%d %d",&a,&b); soma(a,b); return 0; }
C
/* ************************************************************************** */ /* LE - / */ /* / */ /* ft_strtol.c .:: .:/ . .:: */ /* +:+:+ +: +: +:+:+ */ /* By: rcepre <rcepre@student.42.fr> +:+ +: +: +:+ */ /* #+# #+ #+ #+# */ /* Created: 2018/07/09 16:41:48 by rcepre #+# ## ## #+# */ /* Updated: 2018/12/12 09:32:56 by rcepre ### #+. /#+ ###.fr */ /* / */ /* / */ /* ************************************************************************** */ #include "libft.h" static char convert(char c) { if (c >= 'a' && c <= 'z') return (c - 'a' + 10); if (c >= 'A' && c <= 'Z') return (c - 'A' + 10); return (c - '0'); } static int is_valid(char c, int base) { if ((c >= '0' && c <= base - 1 + '0') \ || (c >= 'A' && c <= base - 11 + 'A') || (c >= 'a' && c <= base - 11 + 'a')) return (1); return (0); } static int check_base(char **s, int base) { if (**s == '0' && *(*s + 1) == 'x' && base == 0) { *s += 2; return (16); } if (**s == '0' && base == 0) return (8); return (base == 0 ? 10 : base); } static long extract(char **s, int base, int *len) { int res; res = 0; *len = 0; while (**s == '0') *s += 1; while (is_valid(**s, base)) { res = res * base + convert(**s); *s += 1; *len += 1; } return (res); } long ft_strtol(char *s, char **endptr, int base) { long res; char neg; char *tmp; int len; char *bidule; tmp = s; res = 0; if (endptr == NULL) endptr = &bidule; *endptr = ""; if (base < 0 || base > 32 || base == 1) return (0); while (ft_iswhitespace(*s)) s++; neg = *s == '-' ? 1 : 0; if (*s == '-' || *s == '+') s++; base = check_base(&s, base); res = extract(&s, base, &len); if (!is_valid(*s, base) && *s != '\0') *endptr = s - 1 == tmp ? tmp : s; if ((len == 19 && (*(s - 1) > '6' + neg || *(s - 2) > '0')) || len > 19) return (neg == 1 ? -9223372036854775807 : FT_LONG_MAX); return (neg == 1 ? -res : res); }
C
/********************************************************************* genmapcon.c written by IL edited by CAS EDIT: change zoom from *2.0 to +0.5 ********************************************************************/ #include "fpp.h" void highlightmarker(BOOL high); #define ZINC 0.25 /*************************************************************** DEF: fpwhole Whole button on fingerprint display *************************************************************/ void fpwhole() /* This routine resets the zoom and shiftfor the fp map to the original */ /* values and redisplays the graph */ { if(FPZOOM != 1.0){ FPZOOM = 1.0; FPYSHIFT = 0; drawfpdata(0); } FPYSHIFT = 0; } /*************************************************************** DEF: fpzoomin zoomin button on fingerprint display *************************************************************/ void fpzoomin() /* This routine double the zoom for the fp map and redisplays it*/ { FPZOOM = FPZOOM + ZINC; drawfpdata(0); } /*************************************************************** DEF: fpzoomout zoomout button on fingerprint display *************************************************************/ void fpzoomout() { if(FPZOOM > 1.0){ FPZOOM = FPZOOM- ZINC; drawfpdata(0); } } /*************************************************************** DEF: setupshift *************************************************************/ BOOL setypshift(float *y) /* fingerprint scale bar has changed by shift therefore up date it */ /* always returns TRUE */ { *y = *y - FPBUTTONHEIGHT; /* shift = shift - the top bit of the graph */ FPYSHIFT = (*y); /* set global shift to this */ return(TRUE); } /*************************************************************** DEF: banddrag fingerprint display *************************************************************/ void banddrag(float *x, float *y, BOOL isUP) /* This routine enables the scroll bar to be moved. Shift routine is called */ /* when the drag has finished. x is fixed and the graph is redrawn if needed */ { *x = 0.5; if(isUP) { if(setypshift(y)) /* if the scroll bar has been moved */ drawfpdata(0); /* then redraw fp map */ } } /*************************************************************** DEF: movebotscroll *************************************************************/ static BOOL movebotscroll(float *x) /* fingerprint scale bar has changed by shift therefore up date it */ /* always returns TRUE */ { *x = (*x - FPSCALEWIDTH); /* shift = shift - the top bit of the graph */ fpcolstart = (int)((*x/sizepercol)+0.5); /* set global shift to this */ return(TRUE); } /*************************************************************** DEF: botscrolldrag fingerprint display *************************************************************/ void botscrolldrag(float *x, float *y, BOOL isUP) { *y = fpheight; if(isUP) { if(movebotscroll(x)) /* if the scroll bar has been moved */ drawfpdata(0); /* then redraw fp map */ } }
C
/*Scrieți un program care afișează numerele pare cuprinse între 1 și x, unde x este un număr întreg citit de la tastatură.*/ #include <stdio.h> void main() { int n, i; printf("Introdu un numar:\n"); scanf("%d", &n); printf("Numerele pare in ordine crescatoare de la 1 la %d sunt: 1 \n", n); for (i = 1; i <= n; i++) { if (i % 2 == 0) { printf("%d \t", i); } } printf("\n"); }
C
/* ** my_framebuffer_create.c for my_framebuffer_create in /home/lyliya/rendu/G_Graphical_prog ** ** Made by Guillaume ** Login <lyliya@epitech.net> ** ** Started on Mon Nov 14 07:50:48 2016 Guillaume ** Last update Wed Jan 4 15:30:01 2017 Guillaume */ #include <unistd.h> #include <stdlib.h> #include "my.h" t_my_framebuffer* my_framebuffer_create(int width, int height) { int i; t_my_framebuffer *framebuffer; i = 0; if ((framebuffer = malloc(sizeof(*framebuffer))) == NULL) return (NULL); framebuffer->width = width; framebuffer->height = height; if ((framebuffer->pixels = malloc(width * height * 4 * sizeof(*framebuffer))) == NULL) return (NULL); while (i < width * height * 4) { framebuffer->pixels[i] = 0; i += 1; } return (framebuffer); }
C
#include <stdio.h> #include <string.h> int wcount(char *s) { int words, space, c; char carray[128]; memset(carray, 0, 128); words = c = 0; space = 1; if (gets(carray) && strlen(carray) > 0) { for (c = 0; c < strlen(carray); c++) { if (isspace(carray[c])) { if (!space) { words++; } space = 1; } else space = 0; } if (!space) words++; } return words; } int main() { wcount("1 2 3"); }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> //关于结构体的使用 /*情景: 图书馆里的书 有四个属性 1, Title 2, Author 3, Subject 4, Book ID*/ //结构体的定义 /* struct tag{ member-list member-list member-list ... }variable-list; tag 是结构体的标签 member-list是标准的变量定义, 比如 int/float 或者其他有效的变量定义 variable-list 结构变量,定义在结构体的末尾,最后一个分号之前,可以指定一个或多个结构变量 一般来说,tag/member-list/variable-list这三部分至少要出现两个。 */ typedef struct { char title[50]; char author[50]; char subject[100]; int book_id; int data[10]; int length; }books; void printBook(books *book) { printf("Book Titile:%s\n",book->title); printf("Book author :%s\n", book->author); printf("Book Subject :%s\n", book->subject); printf("Book ID:%d\n", book->book_id); } int main() { books book1; //strcpy(book1.title,"C语言"); //strcpy(book1.author,"谭"); //strcpy(book1.subject,"编程基础"); //book1.book_id = 1; //printBook(&book1); int i; for (i = 0; i < 10;i++) { book1.data[i]=i+1; } book1.length=i; for(i=0;i<book1.length;i++) { printf("%d ",book1.data[i]); } printf("\n"); return 0; }
C
//environment.h: scanning for walls, holes, and victims const double coordToGPS = 0.06; //the gps measurement that corresponds to one tile pair<int, int> getCoords() { //use GPS coordinates to get integer coordinates of the robot pair<double, double> diff; pair<int, int> newCoords = startingCoord; diff.first = gps->getValues()[0] - startingGPS.first; diff.second = gps->getValues()[2] - startingGPS.second; newCoords.first += round(diff.first / coordToGPS); newCoords.second -= round(diff.second / coordToGPS); //cout << "At coords: " << newCoords.first << " " << newCoords.second << ", direction: " << direction << endl; return newCoords; } void orient(int timeStep){ setMotors(1, 1); for (int i = 0; i < 5; i++) robot->step(timeStep); double xValue= fabs(gps->getValues()[0] - startingGPS.first); double yValue = fabs(gps->getValues()[2] - startingGPS.second); if (xValue > yValue){ if (gps->getValues()[0] > startingGPS.first) direction = 1; else direction = 3; } else{ if (gps->getValues()[2] > startingGPS.second) direction = 2; else direction = 0; } angle = 1.5708 * direction; setMotors(-1, -1); for (int i = 0; i < 5; i++) robot->step(timeStep); setMotors(0, 0); } double getDeltaTarget(pair<int, int> targetCoordinates) { //find the maximum GPS distance in a cardinal direction from current location to a certain coordinate //for example, if the function is called from (0,0) with target (-100, 1), it'll return 100 converted into GPS distance pair<double, double> targetGPS; targetGPS.first = startingGPS.first + (targetCoordinates.first - startingCoord.first) * coordToGPS; targetGPS.second = startingGPS.second - (targetCoordinates.second - startingCoord.second) * coordToGPS; return max(fabs(targetGPS.first - gps->getValues()[0]), fabs(targetGPS.second - gps->getValues()[2])); } pair<double, double> moveStart; //where the move started - updated in main() double getDelta() { //distance moved in a cardinal direction from where the move began return max(fabs(moveStart.first - gps->getValues()[0]), fabs(moveStart.second - gps->getValues()[2])); } double wallThreshold = 0.2; double paraThreshold = 0.15; //0.1 int scanningMax = 20; int getTileType(const unsigned char* img); void wallScan(int timeStep){ if(loc.first%2==0 && loc.second%2==0) { int tileType=getTileType(colorCam->getImage()); switch(tileType) { case 1: fullSpecialTileSet(loc,'4'); break; case 3: fullSpecialTileSet(loc,'8'); break; case 4: fullSpecialTileSet(loc,'6'); break; case 5: fullSpecialTileSet(loc,'7'); break; case 6: fullSpecialTileSet(loc,'3'); break; } } double startScan = getAngle(); boardLoc(loc).visited = true; boardLoc(loc).open[0] = boardLoc(loc).open[1] = boardLoc(topLeft(loc)).open[1] = boardLoc(topLeft(loc)).open[2] = true; boardLoc(topRight(loc)).open[2] = boardLoc(topRight(loc)).open[3] = boardLoc(bottomRight(loc)).open[3] = boardLoc(bottomRight(loc)).open[0] = true; vector<pair<int, int>> psDirections {loc, topLeft(loc), topRight(loc), bottomRight(loc)}; rotate(psDirections.begin(), psDirections.begin() + direction, psDirections.end()); cout << "Direction: " << direction << endl; cout << infrared[0]->getValue() << ' ' << infrared[1]->getValue() << ' ' << infrared[2]->getValue() << ' ' << infrared[4]->getValue() << ' ' << infrared[5]->getValue() << ' ' << infrared[6]->getValue() << endl; int ctr = 0; int doRight = 0, doLeft = 0, doCenter = 0; if (infrared[0]->getValue() > wallThreshold) { boardLoc(psDirections[0]).open[(direction + 3) % 4] = true; pair<int, int> neighbor = neighborTile(psDirections[0], (direction + 3) % 4); board[neighbor.first][neighbor.second].open[(direction + 1) % 4] = true; doLeft++; } if (infrared[1]->getValue() > wallThreshold) { boardLoc(psDirections[1]).open[(direction + 3) % 4] = true; pair<int, int> neighbor = neighborTile(psDirections[1], (direction + 3) % 4); board[neighbor.first][neighbor.second].open[(direction + 1) % 4] = true; doLeft++; } if (infrared[2]->getValue() > wallThreshold) { boardLoc(psDirections[1]).open[direction % 4] = true; pair<int, int> neighbor = neighborTile(psDirections[1], direction % 4); board[neighbor.first][neighbor.second].open[(direction + 2) % 4] = true; doCenter++; } if (infrared[4]->getValue() > wallThreshold) { boardLoc(psDirections[2]).open[direction % 4] = true; pair<int, int> neighbor = neighborTile(psDirections[2], direction % 4); board[neighbor.first][neighbor.second].open[(direction + 2) % 4] = true; doCenter++; } if (infrared[5]->getValue() > wallThreshold) { boardLoc(psDirections[2]).open[(direction + 1) % 4] = true; pair<int, int> neighbor = neighborTile(psDirections[2], (direction + 1) % 4); board[neighbor.first][neighbor.second].open[(direction + 3) % 4] = true; doRight++; } if (infrared[6]->getValue() > wallThreshold) { boardLoc(psDirections[3]).open[(direction + 1) % 4] = true; pair<int, int> neighbor = neighborTile(psDirections[3], (direction + 1) % 4); board[neighbor.first][neighbor.second].open[(direction + 3) % 4] = true; doRight++; } if (doLeft < 2 && doCenter < 2 && doRight < 2){ return; } bool leftSide = false, frontSide = false, rightSide = false; setMotors(-3, 3); while (doTimeStep() != -1 && ctr < scanningMax) { if (infrared[1]->getValue() < paraThreshold) leftSide = true; if (infrared[6]->getValue() < paraThreshold) rightSide = true; if (infrared[4]->getValue() < paraThreshold) frontSide = true; //cout << "Left:" << infrared[1]->getValue() << "Right:" << infrared[6]->getValue() << "Front:" << infrared[4]->getValue() << endl; ctr++; } setMotors(3, -3); //change 1.5 to 3 to fix spin issue while (doTimeStep() != -1 && (fabs(getAngle() - startScan) > 3 )) {;} setMotors(0, 0); if (!leftSide && doLeft == 2){ cout << "Left!" << endl; pair<int, int> neighbor = neighborTile(psDirections[0], (direction + 3) % 4); board[neighbor.first][neighbor.second].open[direction] = true; pair<int, int> nNeighbor = neighborTile(neighbor, direction); board[nNeighbor.first][nNeighbor.second].open[(direction+2) % 4] = true; } if (!rightSide && doRight == 2){ cout << "Right!" << endl; pair<int, int> neighbor = neighborTile(psDirections[3], (direction + 1) % 4); board[neighbor.first][neighbor.second].open[direction] = true; pair<int, int> nNeighbor = neighborTile(neighbor, direction); board[nNeighbor.first][nNeighbor.second].open[(direction+2) % 4] = true; }if (!frontSide && doCenter == 2){ cout << "Center!" << endl; pair<int, int> neighbor = neighborTile(psDirections[1], (direction) % 4); board[neighbor.first][neighbor.second].open[(direction + 1) % 4] = true; pair<int, int> nNeighbor = neighborTile(neighbor, (direction + 1) % 4); board[nNeighbor.first][nNeighbor.second].open[(direction+3) % 4] = true; } } double motorMax(){ return min(leftMotor->getMaxVelocity(), rightMotor->getMaxVelocity()); } const int max_value_H = 360/2; const int max_value = 255; const String window_capture_name = "Video Capture"; const String window_detection_name = "Object Detection"; int low_H = 150, low_S = 60, low_V = 60; int high_H = max_value_H, high_S = max_value, high_V = max_value; int low_Hy = 0; int high_Hy = 40; int PosX; int PosZ; int thresh = 192; const int max_thresh = 255; //blur int DELAY_CAPTION = 1500; int DELAY_BLUR = 100; int MAX_KERNEL_LENGTH = 31; char window_name[] = "Smoothing Demo"; int display_caption( const char* caption ); int display_dst( int delay ); char getLetter(double Values[3]) { //{top, mid, bottom} double Data[7][3] = {{0.159763, 0.230769, 0.191321}, //Hdata top: 0.159763, mid: 0.230769, bot: 0.191321 {0.230769, 0.333333, 0.349112}, //Udata top: 0.177515, mid: 0.252465, bot: 0.094675 {0.177515, 0.252465, 0.094675}, //Udata2 top: 0.177515, mid: 0.252465, bot: 0.094675 {0.112426, 0.106509, 0.161736}, //Sdata top: 0.112426, mid: 0.106509, bot: 0.161736 {0.595661, 0.439625, 0.651854}, //C top: 0.595661, mid: 0.169625, bot: 0.581854 {0.429980, 0.532544, 0.641026}, //C2 top: 0.429980, mid: 0.532544, bot: 0.641026 {0.558974, 0.208521, 0.558560}}; //P top: 0.408974, mid: 0.248521, bot: 0.408560 //{mid-top, mid-bottom, bottom-top} double diffs[7][3]; for(int n = 0; n < 7; n++) { diffs[n][0] = 10*(Data[n][1] - Data[n][0]); diffs[n][1] = 10*(Data[n][1] - Data[n][2]); diffs[n][2] = 10*(Data[n][2] - Data[n][0]); } double valDiffs[3] = {10*(Values[1] - Values[0]), 10*(Values[1] - Values[2]), 10*(Values[2] - Values[0])}; // printf("valDiffs %f, %f, %f\n", valDiffs[0], valDiffs[1], valDiffs[2]); double dist[7] = { 0 }; for(int n = 0; n < 7; n++) { for(int i = 0; i < 3; i++) { dist[n] += (Values[i]-Data[n][i])*(Values[i]-Data[n][i]); } // dist[n] = sqrt(dist[n]); } for(int n = 0; n < 7; n++) { for(int i = 0; i < 3; i++) { dist[n] += 2*(valDiffs[i]-diffs[n][i])*(valDiffs[i]-diffs[n][i]); } dist[n] = sqrt(dist[n]); } int letter = 0; if(dist[1] < dist[letter]) letter = 1; if(dist[2] < dist[letter]) letter = 2; if(dist[3] < dist[letter]) letter = 3; if(dist[4] < dist[letter]) letter = 4; if(dist[5] < dist[letter]) letter = 5; if(dist[6] < dist[letter]) letter = 6; if(letter == 0){//Closest to H printf("H victim\n"); return 'H'; } else if(letter == 1 || letter == 2){//Closest to U printf("U victim\n"); return 'U'; } else if(letter == 3){//Closest to S printf("S victim\n"); return 'S'; } else if(letter == 4 || letter == 5){//Closest to C printf("C victim\n"); return 'C'; } else{//Closest to P printf("P victim\n"); return 'P'; } } bool checkVisualVictim(Camera* cam) { namedWindow(window_capture_name); namedWindow(window_detection_name); Mat frame_HSV, frame_red, frame_yellow; Mat frame(cam->getHeight(), cam->getWidth(), CV_8UC4, (void*)cam->getImage());; if( frame.empty() ) { cout << "Could not open or find the image!\n" << endl; return false; } Mat clone = frame.clone(); Mat drawing = frame.clone(); // Convert from BGR to HSV colorspace cvtColor(frame, frame_HSV, COLOR_BGR2HSV); // Detect the object based on HSV Range Values inRange(frame_HSV, Scalar(low_H, low_S, low_V), Scalar(high_H, high_S, high_V), frame_red); inRange(frame_HSV, Scalar(low_Hy, low_S, low_V), Scalar(high_Hy, high_S, high_V), frame_yellow); // Show the frames imshow(window_capture_name, frame); imshow("red", frame_red); imshow("yellow", frame_yellow); waitKey(1); Mat canny_output; vector<vector<Point> > contours; vector<Vec4i> hierarchy; findContours( frame_red, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE ); if(contours.size() == 0) // if see no red { cvtColor(frame,clone,COLOR_BGR2GRAY); //grayscale //blur( clone, clone, Size(3,3) ); // Mat inverted; bitwise_not ( clone, clone ); GaussianBlur(clone, clone, cv::Size(0, 0), 0.5); addWeighted(clone, 1.5, clone, -0.5, 0, clone); imshow("blured", clone); bitwise_not ( clone, clone ); threshold(clone,clone,thresh,max_thresh,THRESH_BINARY); //threshold imshow("thresh", clone); Mat canny_output; vector<vector<Point>> contours; vector<vector<Point>> invContours; vector<Vec4i> hierarchy; findContours( clone, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE ); for( size_t i = 0; i < contours.size(); i++ ) { Scalar color = Scalar( 0, 255, 255); drawContours( clone, contours, (int)i, color, 2, LINE_8, hierarchy, 0 ); Rect roi = boundingRect(contours[i]); imshow("conts", clone); double width = (double)roi.width; double height = (double)roi.height; if(width < 120 && width > 40 && height < 120 && height > 40 && width/height < 1.2 && width/height > 0.66) { printf("width: %f, height: %f\n", width, height); printf("width/height: %f\n", width/height); double area = 39*13; rectangle(frame, roi, color,1); Mat crop = frame(roi); Mat reCrop; resize(crop, reCrop, Size(), 45.0*3/width, 45.0/height); reCrop = reCrop(Rect(9, 3, 39*3, 39)); imshow("reCrop", reCrop); Rect slicet(0, 0, 39*3, 13); Mat slice1 = reCrop(slicet); imshow("slice1", slice1); Rect slicemh(0, 13, 39*3, 13); Mat slice2 = reCrop(slicemh); imshow("slice2", slice2); Rect sliceb(0, 26, 39*3, 13); Mat slice3 = reCrop(sliceb); imshow("slice3", slice3); Vec3b t; Vec3b m; Vec3b b; double top = 0; double mid = 0; double bottom = 0; int valThresh = 140; for(int y = 0; y < 39; y++)//get horizontal slices { if(y<13){ for(int x = 0; x < 39; x++) { t = reCrop.at<Vec3b>(Point(x, y)); if(t.val[0] < valThresh){ top+=(1/area); } } } else if(y<26){ for(int x = 0; x < 39; x++) { m = reCrop.at<Vec3b>(Point(x, y)); if(m.val[0] < valThresh){ mid+=(1/area); } } } else if(y<39){ for(int x = 0; x < 39; x++) { b = reCrop.at<Vec3b>(Point(x, y)); if(b.val[0] < valThresh){ bottom+=(1/area); } } } } printf("top: %f, mid: %f, bot: %f\n", top, mid, bottom); PosX = gps->getValues()[0]*100; PosZ = gps->getValues()[2]*100; if(top > 0.04 && top < 0.9 && mid > 0.05 && mid < 0.8 && bottom > 0.04 && bottom < 0.9)//exclude noisy info { double img[3] = {top, mid, bottom}; changeMessage(PosX, PosZ, getLetter(img)); return true; } } } } else{// yes red for( size_t i = 0; i < contours.size(); i++ ) { Scalar color = Scalar( 0, 0, 255); drawContours( drawing, contours, (int)i, color, 2, LINE_8, hierarchy, 0 ); Rect roi = boundingRect(contours[i]); double width = (double)roi.width; double height = (double)roi.height; if(width > 30 && width < 100 && height > 15 && height < 100 && (width/height > 0.9 && width/height < 2.1)) { PosX = gps->getValues()[0]*100; PosZ = gps->getValues()[2]*100; findContours( frame_yellow, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE ); if(contours.size() == 0){ //if no yellow changeMessage(PosX, PosZ, 'F'); } else{ changeMessage(PosX, PosZ, 'O'); } return true; } } } return false; } bool checkAllVictims(){return false;} string tileTypeStr; int getTileType(const unsigned char* img) { //0normal 1checkpoint 2pit 3red 4blue 5purple 6swamp int r=Camera::imageGetRed(img,1,0,0); int g=Camera::imageGetGreen(img,1,0,0); int b=Camera::imageGetBlue(img,1,0,0); const char* str; int ret; if(r>230 && g>230 && b>230) { str="checkpoint"; ret=1; } else if(r<100 && g<100 && b<100) { str="pit"; cout << "Found a hole!" << endl; ret=2; } else if(r>190 && g<100 && b<100) { str="red"; ret=3; } else if(r<100 && g<100 && b>190) { str="blue"; ret=4; } else if(r>80 && g<90 && b>130) { str="purple"; ret=5; } else if(r>170&&r<178 && g>136&&g<144 && b>74&&b<82) //+-4 from 174 140 78 { str="swamp"; ret=6; } else { str="normal"; ret=0; } //(void)str;//this silences the unused variable warning tileTypeStr=to_string(r)+" "+to_string(g)+" "+to_string(b)+" "+str; //cout<<r<<" "<<g<<" "<<b<<" "<<str<<endl; return ret; } bool checkHole(){ return getTileType(colorCam->getImage()) == 2; }
C
#include <Stdio.h> int main () { long n,a,d,i; a=0; d=0; char s[100000]; scanf("%li",&n); for(i=0;i<=n;i++) { s[i]=getchar(); if(s[i]=='A') a++; if(s[i]=='D') d++; } if(a>d) printf("Anton"); if(d>a) printf("Danik"); if (d==a) printf("Friendship"); return 0; }
C
// RUN: %clang_builtins %s %librt -o %t && %run %t // REQUIRES: librt_has_fixunssfsivfp #include <stdio.h> #include <stdlib.h> #include <math.h> extern unsigned int __fixunssfsivfp(float a); #if defined(__arm__) && defined(__ARM_FP) && (__ARM_FP & 0x4) int test__fixunssfsivfp(float a) { unsigned int actual = __fixunssfsivfp(a); unsigned int expected = a; if (actual != expected) printf("error in test__fixunssfsivfp(%f) = %u, expected %u\n", a, actual, expected); return actual != expected; } #endif int main() { #if defined(__arm__) && defined(__ARM_FP) && (__ARM_FP & 0x4) if (test__fixunssfsivfp(0.0)) return 1; if (test__fixunssfsivfp(1.0)) return 1; if (test__fixunssfsivfp(-1.0)) return 1; if (test__fixunssfsivfp(4294967295.0)) return 1; if (test__fixunssfsivfp(65536.0)) return 1; #else printf("skipped\n"); #endif return 0; }
C
#include<stdio.h> #include<string.h> void main() { char s[100]; int count = 0; char c; printf("Enter a sentence: "); gets(s); printf("Enter a character to know it's repetance in sentence: "); scanf("%c", &c); for(int i = 0; i < strlen(s); i++) { if(s[i] == c) { count++; } } printf("Letter %c is repeated %d times in sentence", c, count); }
C
#include<stdio.h> int main() { char str[100]; int i,j; printf("Enter the String: "); fgets(str,sizeof(str),stdin); for(i=0;str[i]!='\0';i++) while(!(str[i]>='a'&&str[i]<='z')&&!(str[i]>='A'&&str[i]<='Z')&&!(str[i]=='\0')) { for(j=i;str[j]!='\0';j++) { str[j] = str[j+1]; } str[j]='\0'; } printf("String: "); puts(str); return 0; }
C
#include "stdio.h" int main(){ int A,B,C; int A_temp,B_temp,C_temp; scanf("%d %d %d",&A,&B,&C); int roomcounter=0; while (1) { if ((A%2==1)||(B%2==1)||(C%2==1)) { break; } if (A==B) { if (A==C) { if (B==C) { roomcounter=-1; break; }}} A_temp=A; B_temp=B; C_temp=C; A=0; B=0; C=0; A+=B_temp/2+C_temp/2; B+=A_temp/2+C_temp/2; C+=A_temp/2+B_temp/2; roomcounter++; } printf("%d\n",roomcounter); return 0; } ./Main.c: In function main: ./Main.c:10:5: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%d %d %d",&A,&B,&C); ^
C
/* ppa.c a) Escreva um programa que processe os argumentos da linha de comando, inicialize a estrutura de tipo "vector_t" a usar e, finalmente, mostre o estado do vector partilhado por via da invocação da função "print_vector()" (incluída em util.c) Exemplo de invocação: ./ppa 6000 4000 */ #include "util.h" #include <stdio.h> #include <stdlib.h> #include <pthread.h> vector_t vector; // estrutura de dados a partilhar pelos threads int main(int argc, char *argv[]) { setbuf(stdout, NULL); if(argc < 3) { print_usage(argv[0]); exit(1); } int Thread0Count; if(!parse_int(argv[1], &Thread0Count, 1)) { exit(2); } int Thread1Count; if(!parse_int(argv[2], &Thread1Count, 2)) { exit(2); } vector.len = 1000*(Thread0Count + Thread1Count); vector.array = malloc(sizeof(*vector.array)*vector.len); vector.next = 0; vector.cnt[0] = 0; vector.cnt[1] = 0; pthread_mutex_init(&vector.lock, 0); print_vector(&vector); return 0; }
C
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2010, 2013 Oracle and/or its affiliates. All rights reserved. * * $Id$ */ /* * A simple main function that gives a command line to the CuTest suite. * It lets users run the entire suites (default), or choose individual * suite(s), or individual tests. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "CuTest.h" #include "db.h" #ifdef _WIN32 extern int getopt(int, char * const *, const char *); #endif int append_case(char **cases, int *num_cases, const char *this_case); int usage(); void CuTestAssertForDb(const char *msg, const char *file, int line); const char *progname; int main(int argc, char **argv) { #define MAX_CASES 1000 extern char *optarg; extern int optind; char *suites[MAX_CASES], *tests[MAX_CASES]; int ch, failed, i, num_suites, num_tests, verbose; char *test; progname = argv[0]; num_suites = num_tests = verbose = 0; while ((ch = getopt(argc, argv, "s:t:v")) != EOF) switch (ch) { case 's': append_case(suites, &num_suites, optarg); break; case 't': append_case(tests, &num_tests, optarg); break; case 'v': verbose = 1; break; case '?': default: return (usage()); } argc -= optind; argv += optind; if (argc != 0) return (usage()); /* Setup the assert to override the default DB one. */ db_env_set_func_assert(CuTestAssertForDb); failed = 0; if (num_tests == 0 && num_suites == 0) failed = RunAllSuites(); else { for(i = 0; i < num_suites; i++) failed += RunSuite(suites[i]); for(i = 0; i < num_tests; i++) { test = strchr(tests[i], ':'); if (test == NULL) { fprintf(stderr, "Invalid test case: %s\n", tests[i]); continue; } /* * Replace the ':' with NULL, to split the current * value into two strings. */ *test = '\0'; ++test; failed += RunTest(tests[i], test); } } while(num_suites != 0) free(suites[num_suites--]); while(num_tests != 0) free(tests[num_tests--]); if (failed > 0) return (1); else return (0); } int append_case(char **cases, int *pnum_cases, const char *this_case) { int num_cases; num_cases = *pnum_cases; if (num_cases >= MAX_CASES) return (1); cases[num_cases] = strdup(this_case); if (cases[num_cases] == NULL) return (1); ++(*pnum_cases); return (0); } void CuTestAssertForDb(const char *msg, const char *file, int line) { CuFail_Line(NULL, file, line, NULL, msg); } int usage() { (void)fprintf(stderr, "usage: %s %s\n", progname, "[-s suite] [-t test] -v. Multiple test and suite args allowed."); return (EXIT_FAILURE); }
C
/** * WipEout Pure DLC Region Converter * Copyright 2021 Thomas Perl <m@thp.io> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. **/ #define _XOPEN_SOURCE 500 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> /** * This is simply 8-round XTEA encryption. * * See also: * https://en.wikipedia.org/wiki/XTEA * https://cryptography.fandom.com/wiki/XTEA **/ static void xtea8(uint32_t *genkey, const uint32_t *key) { uint32_t v0 = genkey[0]; uint32_t v1 = genkey[1]; const uint32_t k = 0x9e3779b9; const uint32_t num_rounds = 8; uint32_t sum = 0; for (uint32_t i=0; i<num_rounds; ++i) { v0 += (((v1 << 4 ^ v1 >> 5) + v1) ^ (key[sum&3] + sum)); sum += k; v1 += (((v0 << 4 ^ v0 >> 5) + v0) ^ (key[(sum>>11)&3] + sum)); } genkey[0] = v0; genkey[1] = v1; } /** * This is a simple XOR encryption where the keystream is generated by * "encrypting" the constant 0x12345678 and the file offset (divided by * 8 bytes) with XTEA and the per-DLC 128-bit key (from keys.txt). This * allows starting decryption at any 8-byte offset within the file, but * we only support full-file (en|de)cryption here for simplicity. **/ static void crypt_with_key(uint8_t *buffer, uint32_t buffer_length, const uint32_t *key) { union { uint32_t u32[2]; uint8_t u8[8]; } genkey; for (uint32_t i=0; i<buffer_length; ++i) { if (i % 8 == 0) { genkey.u32[0] = 0x12345678; genkey.u32[1] = i / 8; xtea8(genkey.u32, key); } buffer[i] ^= genkey.u8[i % 8]; } } struct WoPureDlcKey { char *name; uint8_t key[16]; struct WoPureDlcKey *next; } *keys = NULL; struct PiWadReadCtx { const char *filename; uint8_t *buf; size_t len; const struct WoPureDlcKey *key; }; #define KEY_REGION_CHAR(key) ((key)->name[2]) #define KEY_BASE_NAME(key) ((key)->name + 10) static struct PiWadReadCtx read_file(const char *filename) { struct PiWadReadCtx result = { filename, NULL, 0, NULL }; FILE *fp = fopen(filename, "rb"); if (fp) { fseek(fp, 0, SEEK_END); result.len = ftell(fp); result.buf = malloc(result.len); fseek(fp, 0, SEEK_SET); if (fread(result.buf, result.len, 1, fp) != 1) { free(result.buf); result.buf = NULL; result.len = 0; } fclose(fp); } if (!result.buf) { printf("Could not open or read '%s'\n", filename); } return result; } int main(int argc, char *argv[]) { printf(" __ ___ ___ _\n" " \\ \\ / (_)_ __| __|___ _ _| |_\n" " \\ \\/\\/ /| | '_ \\ _|/ _ \\ || | _|\n" " \\_/\\_/ |_| .__/___\\___/\\_,_|\\__|\n" " |_| | _ \\_ _ _ _ ___\n" " DLC | _/ || | '_/ -_)\n" " Region |_| \\_,_|_| \\___|\n" " Converter 2021-01-02 <m@thp.io>\n" "\n"); FILE *kfp = fopen("keys.txt", "r"); char line[512]; while (!feof(kfp)) { char *tmp = fgets(line, sizeof(line), kfp); if (tmp == NULL || *tmp == '\0' || *tmp == '#') { continue; } char *end = strchr(tmp, ' '); if (end == NULL) { continue; } *end = '\0'; end++; while (*end == ' ') { ++end; } struct WoPureDlcKey *key = malloc(sizeof(struct WoPureDlcKey)); key->next = keys; keys = key; key->name = strdup(tmp); for (size_t j=0; j<sizeof(key->key); ++j) { char *cur = end; end = strchr(cur, ' '); if (!end) { end = strchr(cur, '\n'); } if (end == NULL) { printf("Could not parse keys.txt\n"); return 1; } *end = '\0'; key->key[j] = strtol(cur, NULL, 16); ++end; } } fclose(kfp); if (argc != 4) { printf("Usage: %s [PI.WAD] [DONOR.WAD] [OUT.WAD]\n" "\n" " PI.WAD ........ The DLC pack you want to convert\n" " DONOR.WAD ..... Any target region DLC from which we 'borrow' the signature\n" " OUT.WAD ....... The region-converted, fake-signed output PI.WAD file\n" "\n" "This tool will convert downloadable content from one region\n" "to another, making it possible to use e.g. JPN- and USA-\n" "exclusive content with an EUR release of the game.\n" "\n", argv[0] ); return 1; } char *source_filename = argv[1]; char *target_filename = argv[2]; char *out_filename = argv[3]; enum { SOURCE = 0, DONOR, COUNT }; struct PiWadReadCtx bufs[COUNT]; bufs[SOURCE] = read_file(source_filename); bufs[DONOR] = read_file(target_filename); if (!bufs[SOURCE].buf || !bufs[DONOR].buf) { return 1; } struct WoPureDlcKey *key = keys; while (key != NULL) { for (int j=0; j<COUNT; ++j) { struct PiWadReadCtx *buf = &bufs[j]; union { uint8_t u8[8]; uint32_t version; } try_bytes; memcpy(try_bytes.u8, buf->buf, sizeof(try_bytes)); crypt_with_key(try_bytes.u8, sizeof(try_bytes), (const uint32_t *)key->key); if (try_bytes.version == 1) { buf->key = key; } } key = key->next; } for (int j=0; j<COUNT; ++j) { struct PiWadReadCtx *buf = &bufs[j]; if (!buf->key) { printf("Could not identify %s\n", buf->filename); return 1; } printf("Detected %-6s pack: %-12s (Region: %c)\n", (j==SOURCE)?"source":"donor", KEY_BASE_NAME(buf->key), KEY_REGION_CHAR(buf->key)); } if (KEY_REGION_CHAR(bufs[SOURCE].key) == KEY_REGION_CHAR(bufs[DONOR].key)) { printf("%s is already in region %c.\n", bufs[SOURCE].filename, KEY_REGION_CHAR(bufs[DONOR].key)); return 1; } if (KEY_REGION_CHAR(bufs[SOURCE].key) == 'E') { printf("Cannot convert EUR content to USA/JAP, because it uses zlib compression.\n"); return 1; } const size_t SIG_SIZE = 256; printf("Decrypting WAD... (%zu bytes)\n", bufs[SOURCE].len - SIG_SIZE); crypt_with_key(bufs[SOURCE].buf, bufs[SOURCE].len - SIG_SIZE, (const uint32_t *)bufs[SOURCE].key->key); struct WadHeader { uint32_t version; uint32_t nitems; } *wad_header = (struct WadHeader *)bufs[SOURCE].buf; if (wad_header->version == 1) { printf("WAD contents: %u entries\n", wad_header->nitems); } else { printf("Decrypting failed\n"); return 1; } printf("Borrowing fake signature... (%zu bytes)\n", SIG_SIZE); memcpy(bufs[SOURCE].buf + bufs[SOURCE].len - SIG_SIZE, bufs[DONOR].buf + bufs[DONOR].len - SIG_SIZE, SIG_SIZE); printf("Encryping WAD... (%zu bytes)\n", bufs[SOURCE].len - SIG_SIZE); crypt_with_key(bufs[SOURCE].buf, bufs[SOURCE].len - SIG_SIZE, (const uint32_t *)bufs[DONOR].key->key); printf("Writing to %s... (%zu bytes)\n", out_filename, bufs[SOURCE].len); FILE *fp = fopen(out_filename, "wb"); if (!fp) { printf("Could not open '%s' for writing\n", out_filename); return 1; } if (fwrite(bufs[SOURCE].buf, bufs[SOURCE].len, 1, fp) != 1) { printf("Could not write converted DLC to '%s'\n", out_filename); } fclose(fp); char region_prefix[10]; memcpy(region_prefix, bufs[DONOR].key->name, 9); region_prefix[9] = '\0'; printf("\n" "Success! Copy the output file to\n" " PSP/SAVEDATA/%s%s/PI.WAD\n" "on your memory stick.\n" "Do not forget to disable DLC signature checks via cheats!\n", region_prefix, bufs[SOURCE].key->name + 9); for (int j=0; j<COUNT; ++j) { free(bufs[j].buf); } return 0; }
C
#include "headers.h" int delay(int sec) { int mili = 1000 * sec; clock_t timestart = clock(); while (clock() < timestart + mili) { fd_set fds; struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 0; int ret_val; FD_ZERO(&fds); FD_SET(0, &fds); ret_val = select(1, &fds, NULL, NULL, &tv); if (ret_val == -1) { perror("select()"); } else if (ret_val) { ret_val = select(1, &fds, NULL, NULL, &tv); char c = fgetc(stdin); char d = fgetc(stdin); if (c == 'q') return -1; } } return 1; } int nightwatch(char *command) { error_code=0; int newborn = 0, interrupt = 0; char com[1024][1024]; int word_count = 0; int char_count = 0; for (int i = 0; i < strlen(command); i++) { if (command[i] != ' ' && command[i]!='\t' && command[i] != '\0') { while (command[i] != ' ' && command[i]!='\t' && command[i] != '\0') { com[word_count][char_count] = command[i]; i++; char_count++; } com[word_count][char_count] = '\0'; word_count++; char_count = 0; } } if (word_count != 4) { error_code=1; fprintf(stderr, "Incorrect command format\n"); return -1; } else if (strcmp("-n", com[1]) != 0) { error_code=1; fprintf(stderr, "Incorrect flag\n"); return -1; } else if (chint(com[2]) < 0) { error_code=1; fprintf(stderr, "Invalid number\n"); return -1; } else if (strcmp("interrupt", com[3]) == 0) { interrupt = 1; } else if (strcmp("newborn", com[3]) == 0) { newborn = 1; } else { error_code=1; fprintf(stderr, "Incorrect command format\n"); return -1; } int der_sec = atoi(com[2]); if (interrupt == 1) { int cpu_first = 0; while (1) { int cpu_no = 0; char watch[100000]; FILE *fd; fd = fopen("/proc/interrupts", "r"); if (fd == NULL) { error_code=1; fprintf(stderr, "Permission denied\n"); return -1; } else { fscanf(fd, "%[^\n]s", watch); } for (int i = 0; i < strlen(watch); i++) { if (watch[i] != ' ' && watch[i] != '\0') { cpu_no++; while (watch[i] != ' ' && watch[i] != '\0') { i++; } } } int flag = 0; int bflag = 0; char line[1024]; while (fgets(line, sizeof(line), fd)) { for (int i = 0; i < strlen(line); i++) { if (line[i] != ' ') { if (line[i] == '1') { bflag = 1; flag = 1; break; } } } if (bflag == 1) { break; } } if (flag == 0) { error_code=1; fprintf(stderr, "No keyboard found\n"); } else { if (cpu_first == 0) { printf("%s\n", watch); } int no_spaces = 2; int f_time = 0; for (int i = 0; i < strlen(line); i++) { if (f_time == 0) { f_time = 1; while (line[i] == ' ') { printf(" "); i++; } while (line[i] != ' ') { printf(" "); i++; } } printf("%c", line[i]); if (line[i] == ' ') { no_spaces++; while (line[i] == ' ') { i++; printf("%c", line[i]); } } if (no_spaces > cpu_no + 1) { printf("\n"); break; } } } fclose(fd); cpu_first = 1; int exit = delay(der_sec * 1000); if (exit == -1) { break; } } } else if (newborn == 1) { while (1) { char line[100]; int w_c = 0; int c_c = 0; char storepid[10][100]; FILE *handle = fopen("/proc/loadavg", "r"); if(handle==NULL) { error_code=1; fprintf(stderr, "Could not open /proc/loadavg\n"); return -1; } fscanf(handle, "%[^\n]s", line); for (int i = 0; i < strlen(line); i++) { if (line[i] != ' ' && line[i] != '\0') { while (line[i] != ' ' && line[i] != '\0') { storepid[w_c][c_c] = line[i]; i++; c_c++; } storepid[w_c][c_c] = '\0'; c_c = 0; w_c++; } } printf("%s\n", storepid[4]); fclose(handle); int exit = delay(der_sec * 1000); if (exit == -1) { break; } } } return 0; }
C
#include <stdio.h> int main(void){ int i,j,k; for(i=0;i<6;i++){ for(j=0;j<6-i;j++){ printf(" "); } for(k=0;k<=i;k++){ printf("* "); } printf("\n"); } }
C
/* ** EPITECH PROJECT, 2018 ** init_3.c ** File description: ** initialisation */ #include <stdlib.h> #include <fcntl.h> #include "map.h" #include "my.h" int get_next_nd(char *str) { for (; *str != ','; str++); str++; return (my_getnbr(str)); } int get_option(char *str) { for (; *str != ','; str++); str++; for (; *str != ','; str++); str++; return (my_getnbr(str)); } int get_pos_y(tab_map_t *tab_map, int i, int j) { return (get_next_nd(tab_map->tab[i][j])); } void init_sprite(map_t ***map, int i, int j, tab_map_t *tab_map) { map[i][j]->rect.height = 100; map[i][j]->rect.width = 100; map[i][j]->rect.left = get_pos_x(tab_map, i, j); map[i][j]->rect.top = get_pos_y(tab_map, i, j); map[i][j]->option = get_option(tab_map->tab[i][j]); map[i][j]->sprite = sfSprite_create(); map[i][j]->position.x = j * 100 + tab_map->decal_x - 100; map[i][j]->position.y = i * 100 + tab_map->decal_y - 100; }
C
#include <zjunix/vfs/vfs.h> #include <zjunix/vfs/err.h> #include <zjunix/vfs/errno.h> #include <driver/vga.h> #include <zjunix/debug/debug.h> /****************************** 外部变量 *******************************/ extern struct dentry * pwd_dentry; /* 当前工作目录 */ extern struct vfsmount * pwd_mnt; const char* __my_strcat(const u8* dest,const u8* src) { char* res = (char *) dest; while(*res) res++;// *res != '\0' while((*res++ = *src++)); return dest; } // cat:连接文件并打印到标准输出设备上 u32 vfs_cat(const u8 *path) { debug_start("[usr.c: vfs_cat:24]\n"); u8 *buf; u32 err; u32 base; u32 file_size; struct file *file; // 打开文件 file = vfs_open(path, O_RDONLY); // 处理打开文件的错误 if (IS_ERR_OR_NULL(file)){ if ( PTR_ERR(file) == -ENOENT ) kernel_printf("No such file.\n"); debug_err("[usr.c: vfs_cat:37]\n"); return PTR_ERR(file); } // 读取文件内容到缓存区 base = 0; file_size = file->f_dentry->d_inode->i_size; kernel_printf("usr.c: 44 cat: %d", file_size); buf = (u8*) kmalloc ((unsigned int) (file_size + 1)); if ( vfs_read(file, buf, file_size, &base) != file_size ) { debug_err("[usr.c: vfs_cat:47]read file size error\n"); return 1; } // 打印buf里面的内容 buf[file_size] = 0; kernel_printf("%s\n", buf); // 关闭文件并释放内存 err = vfs_close(file); if (err) return err; kfree(buf); debug_end("[usr.c: vfs_cat:61]\n"); return 0; } // touch: 新建文件 u32 vfs_touch(const u8 * path) { debug_start("[usr.c: vfs_touch:67]\n"); u32 err=0; struct dentry *dentry; struct nameidata nd; // 找到path对应的nd信息 extern struct dentry* root_dentry; err = path_lookup(path,LOOKUP_PARENT,&nd); if (err) return err; // 若是没有则创建dentry dentry = lookup_create(&nd, 1); // err = PTR_ERR(dentry); if (!IS_ERR_OR_NULL(dentry)) { struct inode * dir = nd.dentry->d_inode; if (!dir->i_op || !dir->i_op->mkdir) { debug_err("[usr.c: vfs_mkdir:82] operation not permitted\n"); return -EPERM; } // 调用文件系统对应的touch kernel_printf("777777777777777777777777777 %d %d\n",container_of(&(nd.dentry->d_inode),struct dentry,d_inode),root_dentry); err = dir->i_op->touch(nd.dentry->d_inode, dentry, 0); dput(dentry); } dput(nd.dentry); debug_end("[usr.c: vfs_touch:91]\n"); return err; } // mkdir:新建目录 u32 vfs_mkdir(const u8 * path) { debug_start("[usr.c: vfs_mkdir:67]\n"); u32 err=0; struct dentry *dentry; struct nameidata nd; // 找到path对应的nd信息 extern struct dentry* root_dentry; err = path_lookup(path,LOOKUP_PARENT,&nd); if (err) return err; // 若是没有则创建dentry dentry = lookup_create(&nd, 1); // err = PTR_ERR(dentry); if (!IS_ERR_OR_NULL(dentry)) { struct inode * dir = nd.dentry->d_inode; if (!dir->i_op || !dir->i_op->mkdir) { debug_err("[usr.c: vfs_mkdir:82] operation not permitted\n"); return -EPERM; } // 调用文件系统对应的mkdir kernel_printf("777777777777777777777777777 %d %d\n",container_of(&(nd.dentry->d_inode),struct dentry,d_inode),root_dentry); err = dir->i_op->mkdir(nd.dentry->d_inode, dentry, 0); dput(dentry); } dput(nd.dentry); debug_end("[usr.c: vfs_mkdir:91]\n"); return err; } // rm:删除文件 u32 vfs_rm(const u8 * path) { debug_start("[usr.c: vfs_rm:97]\n"); u32 err; struct nameidata nd; /* 查找目的文件 */ err = path_lookup(path, 0, &nd); if (err == -ENOENT) { // 返回No such file or directory的错误信息 kernel_printf("No such file.\n"); return err; } else if (IS_ERR_VALUE(err)) { // 如果有其他错误 kernel_printf("Other error: %d\n", err); return err; } /* 删除对应文件在外存上的相关信息 */ // 由dentry去找inode去找super_block去调用相关的删除文件的操作 err = nd.dentry->d_inode->i_sb->s_op->delete_dentry_inode(nd.dentry); if (err) { debug_err("[usr.c: vfs_rm:115]\n"); return err; } /* 删除缓存中的inode */ nd.dentry->d_inode = 0; debug_end("[usr.c: vfs_rm:121]\n"); return 0; } // rm -r:递归删除目录 //u32 vfs_rm_r(const u8 * path) { // u32 err; // struct file *file; // struct getdent getdent; // struct nameidata nd; // // // 打开目录 // if (path[0] == 0) { // kernel_printf("No parameter.\n"); // return -ENOENT; // } // else // file = vfs_open(path, LOOKUP_DIRECTORY); // if (file->f_dentry->d_inode->i_type!=FTYPE_DIR) // vfs_rm(path); // if (IS_ERR_OR_NULL(file)) { // if (PTR_ERR(file) == -ENOENT) // kernel_printf("Directory not found!\n"); // else // kernel_printf("Other error: %d\n", -PTR_ERR(file)); // return PTR_ERR(file); // } // err = file->f_op->readdir(file, &getdent); // if (err) // return err; // // 遍历目录下每一项,若是文件直接调用rm,否则递归调用vfs_rm_r // for (int i = 0; i < getdent.count; ++i) { // if (getdent.dirent[i].type == FTYPE_DIR) { // const u8* tmp_path = __my_strcat(path, "/"); // const u8* new_path = __my_strcat(tmp_path, getdent.dirent[i].name); // vfs_rm_r(new_path); // } else if (getdent.dirent[i].type == FTYPE_NORM) { // const u8* tmp_path = __my_strcat(path, "/"); // const u8* new_path = __my_strcat(tmp_path, getdent.dirent[i].name); // vfs_rm(new_path); // } else if (getdent.dirent[i].type == FTYPE_LINK) { // } else { // return -ENOENT; // } // } // // 删除目录本身的dentry和inode // err = path_lookup(path, 0, &nd); // if (err == -ENOENT) { // 返回No such file or directory的错误信息 // kernel_printf("No such directory.\n"); // return err; // } else if (IS_ERR_VALUE(err)) { // 如果有其他错误 // kernel_printf("Other error: %d\n", err); // return err; // } // nd.dentry->d_inode->i_op->rmdir(nd.dentry->d_inode,nd.dentry); // nd.dentry->d_op->d_delete(nd.dentry); // return 0; //} // rm -r:递归删除目录 u32 vfs_rm_r(const u8 * path) { debug_start("[usr.c: vfs_rm_r:183]\n"); u32 err = 0; struct dentry * dentry; struct nameidata nd; err = path_lookup(path, LOOKUP_PARENT, &nd); if (err) return err; switch (nd.last_type) { case LAST_DOTDOT: err = -ENOTEMPTY; dput(nd.dentry); debug_info("[usr.c: vfs_rm_r:196] dotdot\n"); return err; case LAST_DOT: err = -EINVAL; dput(nd.dentry); debug_info("[usr.c: vfs_rm_r:201] dot\n"); return err; case LAST_ROOT: err = -EBUSY; dput(nd.dentry); debug_info("[usr.c: vfs_rm_r:206] root\n"); return err; default:break; } dentry = __lookup_hash(&nd.last, nd.dentry, 0); err = PTR_ERR(dentry); if (!IS_ERR(dentry)) { struct inode * dir = nd.dentry->d_inode; if (!dir->i_op || !dir->i_op->rmdir) return -EPERM; if (dentry->d_mounted) { dput(nd.dentry); return -EBUSY; } err = dir->i_op->rmdir(dir,dentry); if (!err) { dentry->d_inode->i_flags |= S_DEAD; dentry_iput(dentry); } dput(dentry); } dput(nd.dentry); debug_end("[usr.c: vfs_rm_r:228]\n"); return err; } // ls:列出目录项下的文件信息 u32 vfs_ls(const u8 * path) { debug_start("[usr.c: vfs_ls:234]\n"); u32 err; struct file *file; struct getdent getdent; // 打开目录 if (path[0] == 0) file = vfs_open(".", LOOKUP_DIRECTORY); else file = vfs_open(path, LOOKUP_DIRECTORY); if (IS_ERR_OR_NULL(file)) { if (PTR_ERR(file) == -ENOENT) kernel_printf("Directory not found!\n"); else kernel_printf("Other error: %d\n", -PTR_ERR(file)); debug_err("[usr.c: vfs_ls:249] vfs open err\n"); return PTR_ERR(file); } // 读取目录到gedent中 err = file->f_op->readdir(file, &getdent); // kernel_printf("usr.c: vfs_ls: 255 err: %d\n", err); if (err) return err; // kernel_printf("usr.c vfs_ls: 259 count: %d\n", getdent.count); // 遍历gedent,向屏幕打印结果 for (int i = 0; i < getdent.count; ++i) { if (getdent.dirent[i].type == FTYPE_DIR) kernel_puts(getdent.dirent[i].name, VGA_GREEN,VGA_BLACK); else if (getdent.dirent[i].type == FTYPE_NORM) kernel_puts(getdent.dirent[i].name, VGA_WHITE,VGA_BLACK); else if (getdent.dirent[i].type == FTYPE_LINK) kernel_puts(getdent.dirent[i].name, VGA_BLUE,VGA_BLACK); else if (getdent.dirent[i].type == FTYPE_UNKOWN) kernel_puts(getdent.dirent[i].name, VGA_RED, VGA_BLACK); kernel_printf(" "); } kernel_printf("\n"); debug_end("[usr.c: vfs_ls:271]\n"); return 0; } // cd:切换当前工作目录 u32 vfs_cd(const u8 * path) { debug_start("[usr.c: vfs_cd:277]\n"); u32 err; struct nameidata nd; /* 查找目的目录 */ err = path_lookup(path, LOOKUP_DIRECTORY, &nd); if (err == -ENOENT) { // 返回No such file or directory的错误信息 kernel_printf("No such directory.\n"); return err; } else if (IS_ERR_VALUE(err)) { // 如果有其他错误 kernel_printf("Other error: %d\n", err); return err; } /* 一切顺利,更改dentry和mnt */ pwd_dentry = nd.dentry; pwd_mnt = nd.mnt; debug_end("[usr.c: vfs_cd:294]\n"); return 0; } // mv:移动文件(同目录下移动则为重命名) u32 vfs_mv(const u8 * path) { } // 新建一个文件 u32 vfs_create(const u8 * path) { debug_start("[usr.c: vfs_create:305]\n"); u32 err = 0; struct dentry *dentry; struct nameidata nd; // 找到path对应的nd信息 err = path_lookup(path,LOOKUP_PARENT,&nd); if (err) return err; // 若是没有则创建dentry dentry = lookup_create(&nd, 1); err = PTR_ERR(dentry); if (!IS_ERR(dentry)) { struct inode * dir = nd.dentry->d_inode; debug_info("[usr.c: vfs_create:319] dentry error\n"); if (!dir->i_op || !dir->i_op->mkdir) return -ENOSYS; // 调用文件系统对应的create err = dir->i_op->create(dir, dentry, &nd); dput(dentry); } dput(nd.dentry); debug_end("[usr.c: vfs_create:327]\n"); return err; } //void vfs_pwd() { // kernel_puts() //}
C
/******************************************************************** * Nombre : ALEAT01.H * * Funcin : Variables aleatorias. * * Parmetros : -- * * Compilador : Turbo C++ v1. * * Hecho por : Jos Rafael Sosa Briceo. * * Fecha : Junio de 1994. * * Notas : Implementa varias generadoras de numeros aleatorios * ********************************************************************/ #include <math.h> #include <stdlib.h> #include <time.h> #define MBIG 1000000000 #define MSEED 161803398 #define MZ 0 #define FAC (1.0/MBIG) static long idum3; int bernoulli( float ); int uniformei( int, int ); float uniformef( float, float ); long int exponencial( float ); int triangular( int, int, int ); float unif01(); int bernoulli( float p ) { if( unif01() < p ) return 1; else return 0; } int uniformei( int a, int b ) { int x = (int)( floor(unif01()*(b-a+1) + a) ); if( x > b ) return b; else return x; } float uniformef( float a, float b ) { return ( unif01()*(b-a) + a ); } long int exponencial(float k) { float x; x = uniformef(0.0,10000.0); x = x * 0.0001; if (x < 0.9999) return (long)(-(log(1-x)/k)); else return 10000; }; int triangular(int min, int mod, int max) { float x,a,b,c; a = (float)min; b = (float)max; c = (float)mod; x = uniformef(0.0,10000.0); x = x * 0.0001; if (x <= (c-a)/(b-a)) return (int)(a+sqrt(x*(b-a)*(c-a))); else return (int)(b-sqrt(pow(c-b,2)+(c-b)*(x*(b-a)-(c-a)))); }; void inirandom(long cemilla) { cemilla=1234; idum3 = cemilla; //randomize(); } float unif01() { return ((float)rand()/RAND_MAX); } float rand3() { static int inext,inextp; static long ma[56]; static int iff=0; long mj,mk; int i,ii,k; if (idum3 < 0 || iff == 0) { iff=1; mj=MSEED-(idum3 < 0 ? -idum3 : idum3); mj %= MBIG; ma[55]=mj; mk=1; for (i=1;i<=54;i++) { ii=(21*i) % 55; ma[ii]=mk; mk=mj-mk; if (mk < MZ) mk += MBIG; mj=ma[ii]; } for (k=1;k<=4;k++) for (i=1;i<=55;i++) { ma[i] -= ma[1+(i+30) % 55]; if (ma[i] < MZ) ma[i] += MBIG; } inext=0; inextp=31; idum3=1; } if (++inext == 56) inext=1; if (++inextp == 56) inextp=1; mj=ma[inext]-ma[inextp]; if (mj < MZ) mj += MBIG; ma[inext]=mj; return mj*FAC; } #undef MBIG #undef MSEED #undef MZ #undef FAC
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_atoi_base.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: akovalyo <al.kovalyov@gmail.com> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/17 03:18:50 by akovalyo #+# #+# */ /* Updated: 2020/03/02 14:16:50 by akovalyo ### ########.fr */ /* */ /* ************************************************************************** */ int ft_value(char c, int str_base) { int digit; if (c >= '0' && c <= '9') digit = c - '0'; else if (c >= 'A' && c <= 'F') digit = c - 'A' + 10; else if (c >= 'a' && c <= 'f') digit = c - 'a' + 10; else return (-1); if (digit < str_base) return (digit); return (-1); } int base_str_len(const char *str, int i, int str_base) { while (str[i] && ft_value(str[i], str_base) != -1) i++; return (i - 1); } int ft_atoi_base(const char *str, int str_base) { int sign; int result; int i; int end; int power; sign = 1; result = 0; i = 0; power = 1; if (str[i] == '-') { sign = -1; i++; } end = base_str_len(str, i, str_base); while (end >= i) { result += ft_value(str[end], str_base) * power; power *= str_base; end--; } return (result * sign); }
C
// // //// //// ////#include <stdio.h> //////1~4 ////#if 0 //////1 ////int odd_cnt(int n){ //// int i,cnt = 0; //// for (i = 1; i <= n; i++){//i=0;i<n안됨 //// if ((i % 2) != 0) cnt++; //// } //// return cnt; ////} //////2 ////int odd_sum(int n){ //// int i, sum = 0; //// for (i = 1; i <= n; i++){ //// if ((i % 2) != 0) sum = sum + i; //// } //// return sum; ////} //////3 ////void odd_print(int n){ //// int i; //// for (i = n; i > 0; i--){ //// if ((i % 2) != 0) printf("%d ", i); //// } //// printf("\n"); ////} //////4 ////void cnt3_5(int n){ //// int i, cnt = 0; //// for (i = 1; i <= n; i++){ //// if (((i % 15) == 0)) { //// printf("%d ", i); //// cnt++; //// } //// } //// printf("\n%d\n", cnt); //// ////} ////int main(void){ //// int n; //// scanf("%d", &n); //// //printf("%d\n", odd_cnt(n)); //// //printf("%d\n", odd_sum(n)); //// //odd_print(n); //// cnt3_5(n); ////} ////#endif //////5 ////#if 0 ////int main(void){ //// int i, cnt=0; //// for (i = 1; i < 100; i = i + 2){ //// printf("%2d ", i); //// cnt++; //// if (cnt%15==0){ printf("\n"); } //// } //// printf("\n"); ////} ////#endif //////6~8 ////#if 0 //////6 ////void left(int n){ //// int i,j; //// for(i = 0; i < n; i++){ //// for (j = 1; j < i+2; j++) //// {printf("%d", j);} //// printf("\n"); //// } //// printf("\n"); ////} //////7 ////void right(int n){ //// int i, j; //// for (i = 0; i < n; i++){ //// for (j = 1; j < n - i; j++) //// { //// printf(" "); //// } //// for (j = 1; j < i + 2; j++) //// { //// printf("%d", j); //// } //// printf("\n"); //// } //// printf("\n"); ////} //////8 ////void left_alpha(char x){ //// char i, j; //// for (i = 'A'; i < x; i++){ //// for (j = 'A'; j < i + 2; j++) //// { //// printf("%c", j); //// } //// printf("\n"); //// } //// printf("\n"); ////} //// ////int main(void){ //// int n; //// char x; //// scanf("%d %c", &n,&x); //// left(n); //// right(n); //// left_alpha(x); ////} ////#endif //////9 //10 ////#if 0 ////int main(void){ //// int i, j; //// for (i = 1; i < 10; i++){ //// for (j = 2; j < 10; j++){ //// printf(" %d* %d=%2d",j,i,i*j); //// } //// printf("\n"); //// } //// printf("\n"); //// int a, b; //// for (a = 1; a < 7; a++){ //// for (b = 1; b < 7; b++){ //// printf("%d %d\n",a,b); //// } //// } //// printf("\n"); ////} ////#endif //////11 ////#if 0 ////int last_int(int n){ //// int i=0,sum=0; //// while (sum < n ){ //// sum = sum + i; //// i++; //// } //// return i-1; ////} ////int main(void){ //// int n; //// scanf("%d", &n); //// printf("%d\n",last_int(n)); ////} ////#endif //////12 ////#if 0 ////void Num_Reverse(int num) ////{ //// int i = 0; //// while (num) //// { //// printf("%d", num % 10); //// num /= 10; //// } ////} ////void main(void) ////{ //// int n; //// scanf("%d", &n); //// Num_Reverse(n); ////} ////#endif //// //////주말 workshop 1 ////#if 0 ////int main(void){ //// int a, b,i,sum=0; //// scanf("%d %d", &a, &b); //// for ( i = a; i < b+1; i++) //// { //// if (i % 2 == 0){ sum = sum + i; } //// } //// printf("%d\n", sum); ////} ////#endif //////2 ////#if 0 ////int main(void){ //// int i; //// for (i = 1; i < 101; i++){ //// printf(" %3d", i); //// if (i % 10 == 0){ printf("\n"); } //// } ////} ////#endif //////3 ////#if 0 ////int main(void){ //// int i; //// char x; //// for (i = 0; i < 26; i++){ //// for (x = 'A'+i; x < 'Z'+1; x++){ //// printf("%c", x); //// } //// for (x = 'A' ; x < 'A' + i; x++){ //// printf("%c", x); //// } //// printf("\n"); //// } ////} ////#endif //////4 ////#if 0 ////int main(void){ //// int i,j,k; //// for (i = 1; i < 7; i++){ //// for (j = 1; j < 7; j++){ //// for (k = 1; k < 7; k++) //// { //// printf("%d %d %d\n",i,j,k); //// } //// } //// } ////} ////#endif //////5 ////#if 0 ////int main(void){ //// int n,sum=0; //// scanf("%d", &n); //// while(n!=0){ //// sum = sum + n % 10; //// n = n / 10; //// } //// printf("%d\n", sum); ////} ////#endif //////6 ////#if 1 ////void left(int a){ //// int i, j; //// for (i = 0; i < a; i++){ //// for (j = 0; j < i+1; j++){ //// printf("*"); //// } //// printf("\n"); //// } //// printf("\n"); ////} ////void right(int a){ //// int i, j; //// for (i = 0; i < a; i++){ //// for (j = 1; j < a-i; j++){ //// printf(" "); //// } //// for (j = 0; j < i + 1; j++){ //// printf("*"); //// } //// printf("\n"); //// } //// printf("\n"); ////} ////void right_dowm(int a){ //// int i, j; //// for (i = 0; i < a; i++){ //// for (j = 1; j < i + 1; j++){ //// printf(" "); //// } //// for (j = 0; j < a - i; j++){ //// printf("*"); //// } //// printf("\n"); //// } ////} //// ////int main(void){ //// int a = 5; //// //// left(5); //// right(5); //// right_dowm(5); ////} ////#endif //////7 ////#if 0 ////int main(void){ //// int i=0,sum=0; //// while(sum<1000) { //// i += 3; //// sum = sum + i; //// } //// printf("%d\n", i-3); ////} ////#endif //////8 ////#if 0 ////int main(void){ //// int n,i,j,sum=0,sub_sum=1; //// scanf("%d", &n); //// for (i = 1; i < n + 1; i++){ //// sub_sum = sub_sum*i; //// sum = sum+sub_sum; //// } //// printf("%d\n", sum); ////} ////#endif //////9 ////#if 0 ////int main(void){ //// int a; //// scanf("%d", &a); //// rand()%1000000 +1 ////} ////#endif //////10 ////#if 0 ////#include <stdio.h> ////int main(void){ //// int n,i,j; //// scanf("%d", &n); //// for (i = 2; i < n + 1;i++){ //// for (j = 1; j < i+1; j++){ //// if (i%j == 0){ printf("%d ", j); } //// } //// printf("\n"); //// } ////} ////#endif //////11 ////#if 0 ////int jin(int n, int m) ////{ //// int i, j, cnt = 0; //// for (i = n; i < m + 1; i++){ //// for (j = 1; j < i/2 + 1; j++){ //// if (i%j == 0){ //// cnt += j; //// } //// } //// } ////} ////int main(void){ //// int n,m,i,j,sum=0; //// scanf("%d %d", &n, &m); //// for (i = n; i < m + 1; i++){ //// sum = 0; //// for (j = 1; j < i; j++){ //// if (i%j == 0){ //// sum = sum + j; //// } //// } //// //// if (i == sum){ printf("%d\n", i);} //// } ////} ////#endif //////12 ////#if 0 //int calender(int year,int mon,int d){ // int m,day,sum_day=0; // if ((year % 4 != 0) || (year % 100 == 0)){ // for (m = 1; m < mon; m++){ // switch (m){ // case 1: // case 3: // case 5: // case 7: // case 8: // case 10: // case 12: day = 31; break; // case 4: // case 6: // case 9: // case 11: day = 30; break; // case 2: day = 28; break; // } // sum_day = sum_day + day; // } // } // else{ // for (m = 1; m < mon; m++){ // switch (m){ // case 1: // case 3: // case 5: // case 7: // case 8: // case 10: // case 12: day = 31; break; // case 4: // case 6: // case 9: // case 11: day = 30; break; // case 2: day = 29; break; // } // sum_day = sum_day + day; // } // } // return sum_day+d; //} //int main(void){ // int year, mon, d; // scanf("%d %d %d", &year, &mon, &d); // printf("%d\n", calender(year, mon, d)); //} ////#endif
C
/********************************************** * * * ļ: 05_array_lists\01 SequenceArray * * * * ļ: SequenceArray.h * * * * : زб * * * **********************************************/ #ifndef SEQUENCEARRAY_H #define SEQUENCEARRAY_H #include <stdio.h> #include <stdlib.h> //ṩmallocreallocfreeexitԭ #include <stdarg.h> //ṩva_startva_argva_end #include "../../01_abstract/Status.h" //**01_abstract**// /* 궨 */ #define MAX_ARRAY_DIM 8 //άΪ8 /* Ͷ */ typedef int AElemType_Sq; typedef struct { //˳洢ʾ AElemType_Sq *base; //ԪػַԪأ int dim; //ά int *bounds; //άַСϢ int *constants; //ӳFuncַ洢ԽijάʱҪԽԪظ } Array; /* Funcб */ Status InitArray(Array *A, int dim, ...); /* (01)InitialάΪdim顣 */ Status DestroyArray(Array *A); /* (02)顣 */ Status LocateArray(Array A, va_list ap, int *off); /* (03)apָʾֵAеλá */ Status ValueArray(Array A, AElemType_Sq *e, ...); /* (04)ȡֵɱdim±ֵ */ Status AssignArray(Array *A, AElemType_Sq e, ...); /* (05)ֵɱdim±ֵ */ void ArrayPrint(Array A); /* (06)ݡ */ #endif