language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/**\file parser.c * \brief Definição de métodos para parser de linha de comando no UdpTester. * * \author Alberto Carvalho * \date June 26, 2013 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <defines.h> #include <tools/parser.h> #include <tools/debug.h> #include <netinet/in.h> #include <arpa/inet.h> /* TODO: * - Implementar métodos corretos para parser da linha de comando. * - Suporte a parâmetros por extenso. * * const option long_options[] = { {"bandwidth", REQ_ARGUMENT, NULL, 'b'}, {"help", NO_ARGUMENT, NULL, 'h'}, {"train_interval", REQ_ARGUMENT, NULL, 'i'}, {"loop_test_interval", REQ_ARGUMENT, NULL, 'l'}, {"train_num", REQ_ARGUMENT, NULL, 'n'}, {"port", REQ_ARGUMENT, NULL, 'p'}, {"report_interval", REQ_ARGUMENT, NULL, 'r'}, {"packet_size", REQ_ARGUMENT, NULL, 's'}, {"train_size", REQ_ARGUMENT, NULL, 't'}, {"version", NO_ARGUMENT, NULL, 'v'}, {"soc_buffer", REQ_ARGUMENT, NULL, 'B'}, {"test_interval", REQ_ARGUMENT, NULL, 'I'}, {"burst_size", REQ_ARGUMENT, NULL, 'L'}, {"receiver", NO_ARGUMENT, NULL, 'R'}, {"sender", REQ_ARGUMENT, NULL, 'S'}, {0, 0, 0, 0}}; const char short_options[] = "b:i:h:l:n:p:r:s:t:v:B:I:L:R:S:"; * * */ /**\fn int read_config_file (char *argv, settings *conf_settings) * \brief Realiza o parser do arquivo de configurações de teste. * * O arquivo de configuração de testes permite especificar uma lista de * testes sequencias com diferentes perfis. * O arquivo deve seguir o seguinte template: * TIPO RATE <configs> * Tipos de testes aceitos: * 0 - UDP continuo, com as seguintes configurações: SIZE(MB) TIME(ms) REPORT(ms) * 1 - UDP trem de pacotes, com as seguintes configurações: #TRAIN(int) SIZE(int) INTERVAL(ms) * * \param fname Path para o arquivo de configurações. * \param conf_settings Estrutura de dados com configurações de teste. * \return 0 em caso de sucesso, ~0 caso contrário. */ int read_config_file (char *fname, settings *conf_settings); void usage(void) { printf("\nUsage: ./UdpTester [-S, --sender |-R, --receiver server_addr] [options]" "\nTry `./UdpTester --help' for more information.\n\n"); } void help(void) { printf("\nUsage: ./UdpTester [-S, --sender |-R, --receiver server_addr] [options]" "\n ./UdpTester [-h, --help |-v, --version]\n"); printf("\nSender/Receiver:" "\n -B, --soc_buffer <size> Socket Buffer Size (min %d, max %d, default %d Kbytes)" "\n -r, --report_interval <time> Report interval time (min %d, max %d, default %d seconds)" "\n -d, --device <if_name> Iface Name to Monitoring (default %s)" "\n -p, --port <port> Data Port number (default %d)\n", MIN_SOC_BUFFER, MAX_SOC_BUFFER, DEFAULT_SOC_BUFFER, MIN_REPORT_INTERVAL, MAX_REPORT_INTERVAL, DEFAULT_REPORT_INTERVAL, DEFAULT_INTERFACE_NAME, DEFAULT_DATA_PORT); printf("\nSender:" "\n -s, --packet_size <size> Packet size (min %d, max %d, default %d bytes)" "\n -t, --train_size <size> Train size by probe (min %d, max %d, default %d packets)" "\n -n, --train_num <size> Number of train probes (min %d, max %d, default %d probes)" "\n -i, --train_interval <time> Interval time between probes trains of packets (min %d, max %d, default %d miliseconds)" "\n -I, --test_interval <time> Interval to continuo test (min %d, max %d, default %d miliseconds)" "\n -L, --length_test <size> Burst size to test (min %d, max %d, default %d MB)" "\n -l, --loop_test_interval <time> Interval between tests (min %d, max %d, default %d minutes)" "\n -b, --rate <value> Bandwidth (min %d, max %d, default %d Mbps)\n\n" "\n -f, --file <path> Test file configuration\n\n", MIN_PACKET_SIZE, MAX_PACKET_SIZE, DEFAULT_PACKET_SIZE, MIN_TRAIN_SIZE, MAX_TRAIN_SIZE, DEFAULT_TRAIN_SIZE, MIN_TRAIN_NUM, MAX_TRAIN_NUM, DEFAULT_TRAIN_NUM, MIN_TRAIN_INTERVAL, MAX_TRAIN_INTERVAL, DEFAULT_TRAIN_INTERVAL, MIN_TEST_INTERVAL, MAX_TEST_INTERVAL, DEFAULT_TEST_INTERVAL, MIN_BURST_SIZE, MAX_BURST_SIZE, DEFAULT_BURST_SIZE, MIN_LOOP_TEST_INTERVAL, MAX_LOOP_TEST_INTERVAL, DEFAULT_LOOP_TEST_INTERVAL, MIN_SEND_RATE, MAX_SEND_RATE, DEFAULT_SEND_RATE); } void init_settings (settings *conf_settings) { int i = 0; list_test *ag_test = &(conf_settings->ag_test); memset(conf_settings, 0, sizeof (settings)); conf_settings->mode = RECEIVER; conf_settings->t_type = UDP_CONTINUO; conf_settings->udp_rate = DEFAULT_SEND_RATE; conf_settings->packet_size = DEFAULT_PACKET_SIZE; conf_settings->test.cont.size = DEFAULT_BURST_SIZE; conf_settings->test.cont.pkt_num = DEFAULT_TRAIN_SIZE; conf_settings->test.cont.interval = DEFAULT_TRAIN_INTERVAL; conf_settings->test.cont.report_interval = DEFAULT_REPORT_INTERVAL; conf_settings->loop_interval = DEFAULT_LOOP_TEST_INTERVAL; conf_settings->recvsock_buffer = DEFAULT_SOC_BUFFER; conf_settings->sendsock_buffer = DEFAULT_SOC_BUFFER; conf_settings->udp_port = DEFAULT_DATA_PORT; ag_test->size = 0; ag_test->next = 0; memset (ag_test->cfg_test, 0, (sizeof (config_test) * MAX_CONFIG_TEST)); for (i = 0; i < MAX_CONFIG_TEST; i++) ag_test->cfg_test[i].t_type = UDP_INVALID; memset (conf_settings->iface, 0, STR_SIZE); memcpy (conf_settings->iface, DEFAULT_INTERFACE_NAME, strlen(DEFAULT_INTERFACE_NAME)); } int parse_command_line (int argc, char **argv, settings *conf_settings) { int ret = 0; int i = 0; int config = 0; init_settings (conf_settings); if (argc > 1) { for (i = 1; i < argc; i++) { if (argv[i][0] != '-') { usage (); exit (1); } switch (argv[i][1]) { case 'b': i++; config = atoi(argv[i]); if ((config < MIN_SEND_RATE) || (config > MAX_SEND_RATE)) { return -1; } conf_settings->udp_rate = config; break; case 'd': i++; if (strlen(argv[i]) <= 0) { return -1; } memset (conf_settings->iface, 0, STR_SIZE); memcpy (conf_settings->iface, argv[i], strlen(argv[i])); break; case 'f': i++; if (strlen(argv[i]) <= 0) { return -1; } else { read_config_file (argv[i], conf_settings); } break; case 'i': i++; config = atoi(argv[i]); if ((config < MIN_TRAIN_INTERVAL) || (config > MAX_TRAIN_INTERVAL)) { return -1; } conf_settings->test.train.interval = config; break; case 'h': help(); ret = 1; break; case 'l': i++; config = atoi(argv[i]); if ((config < MIN_LOOP_TEST_INTERVAL) || (config > MAX_LOOP_TEST_INTERVAL)) { return -1; } conf_settings->loop_interval = config; break; case 'n': i++; config = atoi(argv[i]); if ((config < MIN_TRAIN_NUM) || (config > MAX_TRAIN_NUM)) { return -1; } conf_settings->test.train.num = config; break; case 'p': i++; config = atoi(argv[i]); if ((config < 0) || (config > 65535)) { return -1; } conf_settings->udp_port = config; break; case 'r': i++; config = atoi(argv[i]); if ((config < MIN_REPORT_INTERVAL) || (config > MAX_REPORT_INTERVAL)) { return -1; } conf_settings->test.cont.report_interval = config; break; case 's': i++; config = atoi(argv[i]); if ((config < MIN_PACKET_SIZE) || (config > MAX_PACKET_SIZE)) { return -1; } conf_settings->packet_size = config; break; case 't': i++; config = atoi(argv[i]); if ((config < MIN_TRAIN_SIZE) || (config > MAX_TRAIN_SIZE)) { return -1; } conf_settings->test.train.size = config; break; case 'v': printf("\n%s %d.%d\n", STR_VERSION, VERSION_CODE_MAJOR, VERSION_CODE_MINOR); ret = 1; break; case 'I': i++; config = atoi(argv[i]); if ((config < MIN_TEST_INTERVAL) || (config > MAX_TEST_INTERVAL)) { return -1; } conf_settings->test.cont.interval = config; break; case 'L': i++; config = atoi(argv[i]); if ((config < MIN_BURST_SIZE) || (config > MAX_BURST_SIZE)) { return -1; } conf_settings->test.cont.size = config; break; case 'B': i++; config = atoi(argv[i]); if ((config < MIN_SOC_BUFFER) || (config > MAX_SOC_BUFFER)) { return -1; } if (conf_settings->mode == SENDER) conf_settings->recvsock_buffer = config; else conf_settings->sendsock_buffer = config; break; case 'S': conf_settings->mode = SENDER; break; case 'R': i++; struct sockaddr_in *server_addr_in = (struct sockaddr_in *)&(conf_settings->address); server_addr_in->sin_family = AF_INET; server_addr_in->sin_addr.s_addr = inet_addr(argv[i]); conf_settings->mode = RECEIVER; break; default: ret = -1; break; } } } else { ret = -1; } return ret; } int read_config_file (char *argv, settings *conf_settings) { int ret = 0, count = 0; int config[5]; list_test *ag_test = &(conf_settings->ag_test); config_test *cfg_test = ag_test->cfg_test; FILE *fp; if ((argv == NULL) || (strlen (argv) <= 0)) return -1; memset (&config, 0, (sizeof (int) * 5)); fp = fopen (argv, "r"); if (fp != NULL) { while (((fscanf (fp, "%d\t%d\t%d\t%d\t%d\n", &config[0], &config[1], &config[2], &config[3], &config[4])) == 5) && (count < MAX_CONFIG_TEST)) { switch (config[0]) { case UDP_CONTINUO: cfg_test[count].test.cont.size = config[2]; cfg_test[count].test.cont.interval = config[3]; cfg_test[count].test.cont.report_interval = config[4]; break; case UDP_PACKET_TRAIN: cfg_test[count].test.train.num = config[2]; cfg_test[count].test.train.size = config[3]; cfg_test[count].test.train.interval = config[4]; break; default: DEBUG_LEVEL_MSG (DEBUG_LEVEL_LOW, "Invalid test type %d\n", config[0]); return -1; } cfg_test[count].t_type = config[0]; cfg_test[count].udp_rate = config[1]; ag_test->size++; count++; } fclose (fp); } return ret; }
C
#include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/un.h> #include <unistd.h> #include <pthread.h> #define MASTER 100 #define SLAVE 200 int gsockfd; // global sock fd. int REG_FLAG = 0; // flag used for user registration validation. char g_name[40]; // global name. char g_addr[40]; // global address. void closeSockets(void) // close socket function called atexit() { close(gsockfd); } void* test(void* arg) ////////////////////////////////////// CHANGE NAME { char* x = g_addr; char* pch = x; char* addr; char* stat; const char address[20]; const char status[15]; pch = strtok (x,",-"); addr = strtok (NULL, ",-"); stat = strtok (NULL, ",-"); strcpy(address, addr); strcpy(status, stat); char buffer[BUFSIZ + 1]; pid_t fork_result; memset(buffer, '\0', sizeof(buffer)); fork_result = fork(); if (fork_result == -1) { fprintf(stderr, "Fork failure"); } if (fork_result == 0) { printf("Forking"); execl("/usr/bin/xterm", "/usr/bin/xterm", "-e", "./chat", address, status, (void*)NULL); } pthread_exit(NULL); } void* threadedRead(void *arg) { int client_sockfd = (int) arg; char msg[40]; pthread_t init_conn; int result; while(1) { sleep(2); result = read(client_sockfd, &msg, sizeof(msg)); if(result == 0) { // Close socket and exit atexit(closeSockets); exit(-1); } if(strncmp(msg, "xyzinit", 7) == 0) { // MSG for client-client comm initiation. strcpy(g_addr, msg); pthread_create(&init_conn, NULL, test, NULL); } else if(strncmp(msg, "xyzu", 4) == 0) { // MSG for new user registration. if(strncmp(msg, "xyzunew", 7) == 0) { // MSG from server notifying user has been registered. REG_FLAG = 2; } else if(strncmp(msg, "xyzuexist", 9) == 0) { // MSG from server notifying user name unavailable; REG_FLAG = 1; printf("[SERVER]: User already exists\n"); } } else printf("[MSG]: %s\n", msg); fflush(stdout); memset(msg, '\0', sizeof(msg)); } pthread_exit(NULL); } void* threadedWrite(void *arg) { int client_sockfd = (int) arg; char msg[30]; while(1) { if(write(client_sockfd, &msg, strlen(msg)) != -1) { memset(msg, '\0', sizeof(msg)); } } pthread_exit(NULL); } int reg_user(int sockfd) // User Registration { while(REG_FLAG != 2) { // Waits for FLAG Authorization from server. char my_name[30], r_pass[10], data[50] = "xyzreg,"; printf("\nEnter Name: "); scanf("%s", my_name); printf("Enter Password: "); scanf("%s", r_pass); strcat(data, my_name); strcat(data, "."); strcat(data, r_pass); write(sockfd, &data, strlen(data)); printf("\nPlease Wait. Attempting to Register"); strcpy(g_name, my_name); sleep(5); } return 1; } int main() { int len; struct sockaddr_in address; int result; gsockfd = socket(AF_INET, SOCK_STREAM, 0); address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr("192.168.56.1"); address.sin_port = htons(9734); len = sizeof(address); result = connect(gsockfd, (struct sockaddr *) &address, len); pthread_t read_t, write_t; if(result == -1) { perror("client error"); exit(1); } pthread_create(&read_t, NULL, threadedRead, (void*)gsockfd); pthread_create(&write_t, NULL, threadedWrite, (void*)gsockfd); /* User Registration Validation */ int reg_check = 0; while(reg_check != 1) { reg_check = reg_user(gsockfd); if(reg_check == 1) { printf("\nRegistered Successfully"); } sleep(1); } int opt = 5; printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); printf("\t\t\tWelcome to the chatroom\n"); printf("\t\t\tConnected as: %s\n", g_name); printf("\t\n"); printf("\t1. Connect\n"); printf("\t2. List\n"); printf("\t3. Quit\n"); printf("\tEnter (1-3): \n"); scanf("%d", &opt); while(opt != 3) { if(opt == 1) { fflush(stdin); char other_name[30], con_data[50] = "xyzser,"; printf("\nEnter User Name: "); scanf("%s", other_name); if(strcmp(g_name, other_name) != 0){ // Checking if user attempting to connect to SELF. strcat(con_data, g_name); strcat(con_data, "-"); strcat(con_data, other_name); write(gsockfd, &con_data, strlen(con_data)); } } else if(opt == 2) { write(gsockfd, "list", 4); } else if(opt == 3) { } printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); printf("\t\t\tWelcome to the chatroom\n"); printf("\t\t\tConnected as: %s\n", g_name); printf("\t\n"); printf("\t1. Connect\n"); printf("\t2. List\n"); printf("\t3. Quit\n"); printf("\tEnter (1-3): \n"); scanf("%d", &opt); } pthread_exit(NULL); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> int n, c; int C[100], l = 0; // put huffman code. typedef struct node{ int data; int weight; struct node *father; struct node *left; struct node *right; }node; void select2(int *a, char *A, int Flag) //select already has. { int flag1 = 0, flag2 =0;//record the min,then let it be 10000 int min1 = 10000,min2 = 10000; for(int i = 0; i < n; i++){ if(a[i] < min1){ // can't use a[i] <= min,because the printf in turn... min1 =a[i]; flag1 = i; } } if(A[flag1] == c){ Flag = flag1; } a[flag1] = 10000; for(int i = 0;i < n;i++){ if((a[i] < min2) && a[i] >= min1){ min2 = a[i]; flag2 = i; } } if(A[flag2] == c){ Flag = flag2; } a[flag2] = 10000; if(Flag >= 0){ if(Flag == flag2){ if(min1 > min2){ C[l++] = 0; } else{ C[l++] = 1; } a[flag2] = min1 + min2; Flag = -1; } else{ if(min1 > min2){ C[l++] = 1; } else{ C[l++] = 0; } a[flag1] = min1 + min2; Flag = -1; } } else a[flag2] = min1 + min2; } int main(void) { n = 6; char A[7] = {'A','B','C','D','E','F'}; int a[6] = {10, 35, 40, 50, 60, 200}; scanf("%c", &c); //for(int i = 0;i < n;i++){ // scanf("%d", a+i); //} for(int j = 0;j < n;j++){ C[j] = 0; } int Flag = -1; // judge if find c.. for(int j = 0;j < n;j++){ select2(a, A, Flag); } for(int i = l-2; i >= 0 ; i--){ printf("%d ", C[i]); } return 0; }
C
#include <msp430.h> #include "LCD_I2C.H" /** * main.c */ int main(void) { WDTCTL = WDTPW | WDTHOLD; // stop watchdog timer lcd_init(0x27);//Initialize the LCD as slave with I2C Slave address as 0x27 set_backlight();//Turn on the backlight lcd_setcursor(0,2);//Set the position of the Cursor lcd_print("Sanjeeve R");//Print the String Sanjeeve R. The String must be enclosed within double brackets. return 0; }
C
#include <stdio.h> #include <math.h> void main() { float a, b, c, d, r1, r2; printf("enter parameters of the first circle\n"); scanf("%f %f %f", &a, &b, &r1); printf("enter parameters of the second circle\n"); scanf("%f %f %f", &c, &d, &r2); if((r1<=0)||(r2<=0)) {printf("error"); return;} else if((sqrt(pow((c-a),2)+pow((d-b),2)) == abs(r1-r2))&&(r1!=r2))// окружности касаются внутренним образом printf("one circle touches another inside of it"); else if (sqrt(pow((c-a),2)+pow((d-b),2)) == (r1+r2))// окружности касаются внешним образом printf("one circle touches another outside of it"); else if (sqrt(pow((c-a),2)+pow((d-b),2)) > (r1+r2))// окружности не касаются printf("circles don't touch each other"); else if ((sqrt(pow((c-a),2)+pow((d-b),2)) == 0)&&(r1==r2))// окружности совпадают printf("they are the same circles"); else if ((sqrt(pow((c-a),2)+pow((d-b),2)) > abs(r1-r2))&&(sqrt(pow((c-a),2)+pow((d-b),2)) <(r1+r2))) printf("circles touch each other twice");//окружности пересекаются else if (sqrt(pow((c-a),2)+pow((d-b),2)) < abs(r1-r2)) printf("one circle inside of another");// одна окружность внутри другой }
C
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdio.h> #include <fcntl.h> int main(int argc,char** argv) { char * arg[]={"ls","-l","monfic",NULL}; /* printf("avant exec \n"); execv("/bin/ls",arg); printf("après exec \n"); chmod("monfic",S_IRWXU); chmod("monfic",S_IROTH); chmod("monfic",S_IRGRP); execv("/bin/ls",arg); */ printf("%d %d %d\n",S_IRWXU,S_IRWXO,S_IRWXG); int fichier =open("monfic",O_RDONLY); fchmod(fichier,S_IRWXU); fchmod(fichier,S_IRWXO); fchmod(fichier,S_IRWXG); execv("/bin/ls",arg); return 0; // utilisez stat !!!!!!!!!!!! }
C
#include "fuseLib.h" #include "myFS.h" #include <stdlib.h> #include <string.h> MiSistemaDeFicheros miSistemaDeFicheros; #define USO "Uso: %s -t tamDisco -a nombreArchivo -f 'opciones fuse'\n" #define EJEMPLO "Ejemplo:\n%s -t 2097152 -a disco-virtual -f '-d -s punto-montaje'\n" int main(int argc, char **argv) { miSistemaDeFicheros.numNodosLibres = MAX_NODOSI; int ret; // Código de retorno de las llamadas a funciones int opt, tamDisco=-1; char * nombreArchivo=NULL; char *argsFUSE=NULL; char *argvNew[MAX_FUSE_NARGS]; char *pTmp; while((opt = getopt(argc, argv, "t:a:f:")) != -1) { switch(opt) { case 't': tamDisco=atoi(optarg); break; case 'a': nombreArchivo=optarg; break; case 'f': argsFUSE=optarg; break; default: /* '?' */ fprintf(stderr, USO, argv[0]); fprintf(stderr, EJEMPLO, argv[0]); exit(-1); } } //Falta algún parámetro? if(tamDisco==-1 || nombreArchivo==NULL || argsFUSE==NULL){ fprintf(stderr, USO, argv[0]); fprintf(stderr, EJEMPLO, argv[0]); exit(-1); } // Formateamos el fichero según nuestro formato ret = myMkfs(&miSistemaDeFicheros, tamDisco, nombreArchivo); if(ret) { fprintf(stderr, "Incapaz de formatear, código de error: %d\n", ret); exit(-1); } fprintf(stderr, "Sistema de ficheros disponible\n"); //Parseamos los arugumentos para FUSE argc=1; argvNew[0]=argv[0]; pTmp = strtok(argsFUSE, " "); while (pTmp && argc < MAX_FUSE_NARGS){ argvNew[argc++] = pTmp; pTmp = strtok(0, " "); } //Montamos el SF, saldremos con Control-C if( (ret=fuse_main(argc, argvNew, &myFS_operations, NULL)) ){ fprintf(stderr, "Error al montar sistema de ficheros fuse\n"); return(ret); } myFree(&miSistemaDeFicheros); return(0); }
C
#include<stdio.h> int main(){ int m,k,day=0; scanf("%d%d",&m,&k); while (m>0) { m--; day++; if (day%k==0) { m++; } } printf("%d",day); }
C
#include<stdio.h> void main() { int num; printf("enter the integer"); scanf("%d",&num); if(number%2==0) { printf("%d" is even",num); } else { printf("%d is odd",num); } return 0; }
C
#include<stdio.h> #include<math.h> int main() { int i,j,k,t,s,sg,fg,d; float m,n; scanf("%d",&t); for(i=0;i<t;i++) { scanf("%d%d%d%d%d",&s,&sg,&fg,&d,&k); n=(d*180)/k; m=s+n; if((fabs(m-sg))<(fabs(m-fg))) { printf("SEBI\n"); } else if((fabs(m-sg))>(fabs(m-fg))) { printf("FATHER\n"); } else if((fabs(m-sg))==(fabs(m-fg))) { printf("DRAW\n"); } } return 0; }
C
/* Solve x^3-3x+1=0 correct to 3 significant digits using the Regular Falsi Method. */ #include<stdio.h> #include<math.h> float fun(float x) { return(x*x*x-3*x+1); //return (x*pow(2.718,-x)-3*x+7); } main() { float x,x1,x2,f,f1,f2,e=0.0001; printf("Enter two guess values\n"); scanf("%f %f",&x1,&x2); x=(x1+x2)/2; f=fun(x); f1=fun(x1); f2=fun(x2); if(f1*f2<0) { while(fabs(f)>e) { if(f<0) x2=x; else x1=x; f1=fun(x1); f2=fun(x2); x=((x1*f2)-(x2*f1))/(f2-f1); f=fun(x); } printf("The required solution is %f",x); } else printf("Re enter guess values"); }
C
#include "biblioH.h" #include "entreeSortieH.h" #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* retourne un entier (clef) à partir du nom de l'auteur */ int fonctionClef(char* auteur){ int somme = 0; for(int i = 0; auteur[i]!='\0'; i++){ somme += (int)auteur[i]; } return somme; } /* retourne un entier (index de la clé calculée à partir de la clé et de la taille) pour la table de hachage */ int fonctionHachage(int cle, int m){ return (int)(m * ((double)cle * A - (int)(cle * A))); } /* création d'un livre dont les données sont passées en paramètre */ LivreH* creer_livreH(int num,char* titre,char* auteur){ LivreH* livre = (LivreH*)malloc(sizeof(LivreH)); if (livre==NULL) return NULL; livre -> titre = strdup(titre); if (livre->titre==NULL){ free(livre); return NULL; } livre -> auteur = strdup(auteur); if (livre->auteur==NULL){ free(livre->titre); free(livre); return NULL; } livre -> num = num; livre -> clef = fonctionClef(auteur); livre -> suivant = NULL; return livre; } /* libère le contenu du livre passé en paramètre */ void liberer_livreH(LivreH** lh){ LivreH* curr = *lh; while ((curr = *lh) != NULL) { lh = &curr->suivant; free(curr->auteur); free(curr->titre); free(curr); } } /* créer une bibliothèque dont la taille est passée en paramètre */ BiblioH* creer_biblioH(int m){ BiblioH *bh = malloc(sizeof(BiblioH)); if (bh==NULL) return NULL; bh -> nE = 0; bh -> m = m; bh -> T = (LivreH**)malloc(sizeof(LivreH*) * bh->m); if (bh->T==NULL){ free(bh); return NULL; } /* Initialisation des tableaux */ memset(bh->T, 0, sizeof(LivreH*) * bh->m); return bh; } /* libère le contenu de la bibliothèque passée en paramètre */ void liberer_biblioH(BiblioH* bh){ LivreH** tab = bh -> T; for(int i = 0; i < (bh->m); i++) liberer_livreH(&tab[i]); free(bh->T); free(bh); } /* insère un livre (dont les données ont été passé en paramètre) dans la bibliothèque */ void inserer(BiblioH* bh,int num,char* titre,char* auteur){ LivreH* lh; if ((lh=creer_livreH(num,titre,auteur)) == NULL) return; int clefH = fonctionHachage(lh->clef,bh->m); lh -> suivant = bh -> T[clefH]; bh -> T[clefH] = lh; bh -> nE++; } /* affiche les données du livre passé en paramètre */ void afficher_livreH(LivreH* lh){ if (lh==NULL) return; printf("num : %d, titre : %s, auteur : %s\n",lh -> num, lh -> titre, lh -> auteur); } /* affiche le contenu de la bibliotèque passée en paramètre */ void afficher_biblioH(BiblioH* bh){ if (bh==NULL) return; if (bh->nE == 0) return; LivreH* lh; int i = 0; while(lh = bh -> T[i++], i <= bh->m){ for(; lh; lh = lh -> suivant) afficher_livreH(lh); } /*for (int i = 0; i < bh->m; i++) afficher_livreH(bh->T[i]);*/ } /* recherche et retourne le livre portant le numéro 'num' */ LivreH *recherche_ouvrage_num(BiblioH *bh, int num){ if (bh==NULL) return NULL; if (bh->nE == 0) return NULL; LivreH* lh; int i = 0; while(lh = bh -> T[i++], i <= bh->m){ for(; lh; lh = lh -> suivant){ if (lh->num == num){ return lh; } } } return NULL; } /* recherche et retourne le livre portant le titre 'titre' */ LivreH *recherche_ouvrage_titre(BiblioH *bh, char *titre){ if (bh==NULL) return NULL; if (bh->nE == 0) return NULL; LivreH* lh; int i = 0; while(lh = bh -> T[i++], i <= bh->m){ for(; lh; lh = lh -> suivant){ if (strcmp(lh->titre,titre)==0){ return lh; } } } return NULL; } /* recherche et retourne une bibliothèque de tout les livres de l'auteur 'auteur' */ BiblioH *recherche_meme_auteur(BiblioH *bh, char *auteur){ if (bh==NULL) return NULL; if (bh->nE == 0) return NULL; BiblioH* b; if ((b=creer_biblioH(bh->m))==NULL) return NULL; int clefH = fonctionHachage(fonctionClef(auteur),bh->m); LivreH* lh; if((lh=bh->T[clefH])==NULL){ printf("Cet auteur n'est pas répertorié dans la bibliothèque !\n"); return NULL; } for(; lh; lh = lh -> suivant){ if (strcmp(lh->auteur,auteur)==0){ inserer(b,lh->num,lh->titre,lh->auteur); } } return b; } /* supprime le livre (dont les données ont été passé en paramètre) de la bibliothèque */ int supprimer_livreH(BiblioH* bh, int num, char* titre, char* auteur) { LivreH* curr; int clefH = fonctionHachage(fonctionClef(auteur),bh->m); LivreH** suivp = &(bh->T[clefH]); for(; (curr = *suivp) != NULL && (curr->num != num || strcmp(titre, curr->titre) != 0 || strcmp(auteur, curr->auteur) != 0); suivp = &curr->suivant); if (curr == NULL) return 0; *suivp = curr->suivant; curr->suivant = NULL; liberer_livreH(&curr); bh->nE--; return 1; } /* ajoute la deuxième bibliothèque à la première */ void fusion(BiblioH* b1, BiblioH* b2){ for(int i = 0; i < b2 -> m; i++){ LivreH** lp = &(b2->T[i]); LivreH* curr; for(; (curr = *lp); lp = &curr->suivant); *lp = b1->T[i]; b1->T[i] = b2->T[i]; b2->T[i] = NULL; } b1 -> nE += b2 -> nE; liberer_biblioH(b2); } /* recherche et retourne une bibliothèque dans laquelle on y retrouve plusieurs exemplaires d'ouvrages (même titre et même auteur) */ BiblioH *recherche_exemplaires(BiblioH *bh){ if (bh==NULL) return NULL; if (bh->nE == 0) return NULL; BiblioH* b = creer_biblioH(bh -> m); for(int i = 0; i < bh -> m; i++){ for(LivreH* lh1 = bh -> T[i]; lh1; lh1 = lh1 -> suivant){ for(LivreH* lh2 = bh -> T[i]; lh2; lh2 = lh2 -> suivant){ if (lh1 != lh2 && strcmp(lh1->titre,lh2->titre)==0 && strcmp(lh1->auteur,lh2->auteur)==0){ inserer(b,lh2->num,lh2->titre,lh2->auteur); } } } } return b; }
C
// c program to find largest element in the array #include <stdio.h> int main() { int n, i, a[100], max; printf("enter the size of array\n"); scanf("%d", &n); printf("enter the elemrent of the array\n"); for (i = 0; i <= n; i++) { scanf("%d", &a[i]); } max = a[0]; //initialise the first element is the largest element for (i = 0; i <= n; i++) { if (max < a[i + 1]) { max = a[i + 1]; } } if (i > n) { printf("the largest elemrent is %d", max); } }
C
/* Copyright 2015 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "libpdb/pdbp.h" #include <ctype.h> #include <errno.h> #include <stdio.h> /* Treat any Unicode characters as word characters. */ #define ISWORD(x) ((unsigned char)(x) >= 0x80 || isalnum(x)) #define ISDIGIT(x) ((unsigned char)(x) < 0x80 && isdigit(x)) #define ISPUNCT(a) (isascii(a) && ispunct(a)) #define ISSPACE(a) (isascii(a) && isspace(a)) #define ISBREAK(a) (ISSPACE(a) || (ISPUNCT(a) && (a) != '-' && (a) != '+')) #define ISSIGN(a) ((a) == '-' || (a) == '+') #define ISSIGNPTR(s, s0) \ ((*(s) == '-' || *(s) == '+') && (s == s0 || ISBREAK(s[-1]))) #define ISPOINT(a) ((a) == '.') static const unsigned char ascii_to_hash[128] = { ['\0'] = 0, ['a'] = 3, ['b'] = 4, ['c'] = 5, ['d'] = 6, ['e'] = 7, ['f'] = 8, ['g'] = 9, ['h'] = 10, ['i'] = 11, ['j'] = 12, ['k'] = 13, ['l'] = 14, ['m'] = 15, ['n'] = 16, ['o'] = 17, ['p'] = 18, ['q'] = 19, ['r'] = 20, ['s'] = 21, ['t'] = 22, ['u'] = 23, ['v'] = 24, ['w'] = 25, ['x'] = 26, ['y'] = 27, ['z'] = 28, ['A'] = 3, ['B'] = 4, ['C'] = 5, ['D'] = 6, ['E'] = 7, ['F'] = 8, ['G'] = 9, ['H'] = 10, ['I'] = 11, ['J'] = 12, ['K'] = 13, ['L'] = 14, ['M'] = 15, ['N'] = 16, ['O'] = 17, ['P'] = 18, ['Q'] = 19, ['R'] = 20, ['S'] = 21, ['T'] = 22, ['U'] = 23, ['V'] = 24, ['W'] = 25, ['X'] = 26, ['Y'] = 27, ['Z'] = 28, /* Projecting the numbers into little-used letter slots to * get more distribution, smaller sets. 0 and 1 get their * own full slots - they're expected to be the most popular * numbers. */ ['0'] = 1, ['1'] = 2, ['2'] = 17, ['3'] = 19, ['4'] = 24, ['5'] = 26, ['6'] = 27, ['7'] = 28, ['8'] = 29, ['9'] = 30, /* Alphabetical; keeping braces, single quotes, * and spaces together. */ [' '] = 1, /* various spaces */ ['\t'] = 1, ['\n'] = 1, ['\r'] = 1, ['&'] = 2, /* ampersand */ ['*'] = 3, /* asterisk */ ['@'] = 4, /* at-sign */ ['^'] = 5, /* circumflex */ ['}'] = 6, /* close brace */ [')'] = 6, /* close paren */ [']'] = 6, /* close square bracket */ [':'] = 7, /* colon */ [','] = 8, /* comma */ ['-'] = 9, /* dash */ ['$'] = 10, /* dollar */ ['"'] = 11, /* double quote */ ['='] = 12, /* equal sign */ ['!'] = 13, /* exclamation mark */ ['>'] = 14, /* greater than */ ['<'] = 15, /* less than */ ['#'] = 16, /* octothorpe */ ['{'] = 17, /* open brace */ ['('] = 17, /* open paren */ ['['] = 17, /* open square bracket */ ['%'] = 18, /* percent sign */ ['+'] = 19, /* plus */ ['.'] = 20, /* point */ ['?'] = 22, /* question mark */ ['\''] = 23, /* quote */ ['`'] = 23, /* quote (back ~) */ [';'] = 24, /* semicolon */ ['/'] = 25, /* slash */ ['\\'] = 25, /* slash (back ~) */ ['~'] = 27, /* tilde */ ['_'] = 28, /* underscore */ ['|'] = 29 /* vertical bar */ }; /* Render a hash code as a 4-byte key. */ void pdb_word_key(unsigned long code, char *buf) { ((unsigned char *)buf)[3] = code & 0xFF; code >>= 8; ((unsigned char *)buf)[2] = code & 0xFF; code >>= 8; ((unsigned char *)buf)[1] = code & 0xFF; code >>= 8; ((unsigned char *)buf)[0] = code & 0xFF; } /** * @brief Return the 5-bit hash value for a Unicode character * * Hash values within one hash family are in lexical order. * Note that 0x1F is mapped to 0x1E to avoid having the stop value, * 0x1F (31), naturally occur in the input. * * @param uc the Unicode character * @return a 5-bit hash value */ #define hash_value(uc) \ (((uc) <= 0x7F) ? ascii_to_hash[uc] \ : ((0x1F & (uc)) == 0x1F ? 0x1E : (0x1F & (uc)))) static char const *render_chars(char const *s, char const *e, char *buf, size_t bufsize) { char *w = buf; char *buf_end = buf + bufsize; while (s < e && buf_end - w >= 5) { if (isascii(*s) && isprint(*s)) *w++ = *s++; else { if (*s == '\0') { *w++ = '\\'; *w++ = '0'; } else if (*s == '\t') { *w++ = '\\'; *w++ = 't'; } else if (*s == '\n') { *w++ = '\\'; *w++ = 'n'; } else if (*s == '\r') { *w++ = '\\'; *w++ = 'r'; } else { snprintf(w, (size_t)(buf_end - w), "\\%3.3o", (unsigned char)*s); w += strlen(w); } s++; } } if (w < buf_end) *w = '\0'; return buf; } /** * @brief Return an ordered hash value for a word. * * We hash up to 5 first Unicode characters. If there are * fewer than 5, the hash mask is left-justified. * * @param pdb request context * @param s beginning of the word's spelling * @param e end of the word's spelling */ unsigned long pdb_word_hash(pdb_handle *pdb, char const *s, char const *e) { char const *s0 = s; unsigned long h = 0; unsigned long uc = 0; size_t n_chars = 5; if (s >= e) return 0; for (; s < e && n_chars > 0; s++, n_chars--) { /* At the end of this if..else if .. else block, * <uc> is either the next UCS-4 unicode character, or a * (0x80000000 | garbage) encoding of a coding error * (in the latter case, a message is logged as well.) */ if ((*(unsigned char const *)s & 0x80) == 0) uc = *s; else if ((*(unsigned char const *)s & 0x40) == 0) { char rbuf[200]; cl_log(pdb->pdb_cl, CL_LEVEL_FAIL, "pdb_word_hash: coding error: " "continuation character %#.2x without prefix: " "uc=%lx (bytes: %s)", (unsigned int)*(unsigned char const *)s, uc, render_chars(s0, e, rbuf, sizeof rbuf)); uc = 0x80000000 | *(unsigned char const *)s; cl_cover(pdb->pdb_cl); } else { unsigned char const *r; int nc; unsigned char m; /* Start of a new character. */ for (m = 0x20, nc = 1; m != 0; m >>= 1, nc++) if ((*(unsigned char const *)s & m) == 0) break; uc = *(unsigned char const *)s & ((1 << (6 - nc)) - 1); /* Continuation bytes. */ for (r = (unsigned char const *)s + 1; nc > 0; nc--, r++) { if (r >= (unsigned char const *)e) { char rbuf[200]; cl_log(pdb->pdb_cl, CL_LEVEL_FAIL, "pdb_word_hash: coding " "error: end-of-word in " "multibyte character: " "uc=%lx, *s=%x (nc=%d) " "(bytes: %s)", uc, (unsigned int)*r, nc, render_chars(s0, e, rbuf, sizeof rbuf)); /* Go back to *s and encode it as * garbage; don't interpret it as * a Unicode character, since it * obviously isn't. */ r = (unsigned char const *)s; uc = 0x80000000 | *r; break; } else if ((*r & 0xC0) != 0x80) { char rbuf[200]; cl_log(pdb->pdb_cl, CL_LEVEL_FAIL, "pdb_word_hash: coding " "error: expected continuation " "character, got %#2.2x " "(uc=%lx, nc=%d) (bytes: %s)", (unsigned int)*r, uc, nc, render_chars(s0, e, rbuf, sizeof rbuf)); r = (unsigned char const *)s; uc = 0x80000000 | *r; break; } else uc = (uc << 6) | (0x3F & *r); } /* S is incremented between iterations. R is the * first character we're having trouble with. */ s = (char const *)r - 1; cl_cover(pdb->pdb_cl); } /* <uc> holds the next Unicode character in our input word. * Translate it into a hash 5-bit piece, and add it to the * hash code. * * Trust that hash_value will always return something * < 31 -- no need to explicitly mask it. */ cl_assert(pdb->pdb_cl, hash_value(uc) < 31); h = (h << 5) | hash_value(uc); } /* cl_log(pdb->pdb_cl, CL_LEVEL_DEBUG, "pdb_word_hash \"%.*s\" is %lx", (int)(e - s0), s0, (unsigned long)(h << (n_chars * 5))); */ return h << (n_chars * 5); } /* How many UTF-8 characters are in s...e? (Stop counting at 5.) */ int pdb_word_utf8len(pdb_handle *pdb, char const *s, char const *e) { size_t n_chars = 0; if (s >= e) return 0; for (; s < e && n_chars < 5; s++, n_chars++) { if ((*(unsigned char const *)s & 0xC0) == 0xC0) { unsigned char const *r; int nc; unsigned char m; /* Start of a new character. */ for (m = 0x20, nc = 1; m != 0; m >>= 1, nc++) if ((*(unsigned char const *)s & m) == 0) break; /* Continuation bytes. */ for (r = (unsigned char const *)s + 1; nc > 0; nc--, r++) { if (r >= (unsigned char const *)e) { /* Go back to *s and encode it as * garbage; don't interpret it as * a Unicode character, since it * obviously isn't. */ r = (unsigned char const *)s; break; } else if ((*r & 0xC0) != 0x80) { r = (unsigned char const *)s; break; } } /* Incremented between iterations. */ s = (char const *)r - 1; cl_cover(pdb->pdb_cl); } } return n_chars; } int pdb_word_chop(void *data, pdb_handle *pdb, pdb_id id, char const *s, char const *e, pdb_word_chop_callback *callback) { cl_handle *cl = pdb->pdb_cl; cm_handle *cm = pdb->pdb_cm; char const *s0 = s; /* save original start */ char const *word_s, *word_e; int word_type; int err; cl_log(cl, CL_LEVEL_SPEW, "pdb_word_chop(%llx, \"%.*s\")", (unsigned long long)id, (int)(e - s), s); while (pdb_word_fragment_next(s0, &s, e, &word_s, &word_e, &word_type)) { char const *norm_s, *norm_e; char *norm_buf = NULL; char const *orig_int, *orig_point, *orig_frac; if (word_type == PDB_WORD_PUNCTUATION || word_type == PDB_WORD_SPACE) continue; cl_cover(cl); if (word_type != PDB_WORD_NUMBER) { /* Insert the word into the list as is. */ err = (*callback)(data, pdb, id, word_s, word_e); if (err != 0) return err; continue; } err = pdb_word_number_split(word_s, word_e, &orig_int, &orig_point, &orig_frac); cl_assert(cl, err == 0); if (err != 0) return err; /* Insert the integral part and the fraction, * if they're non-empty. */ if (orig_int != orig_point) { /* Insert the word into the list as is. */ err = (*callback)(data, pdb, id, orig_int, orig_point); if (err != 0) return err; } if (orig_frac != word_e) { /* Insert the fraction digits */ err = (*callback)(data, pdb, id, orig_frac, word_e); if (err != 0) return err; } /* Normalize the number. */ err = pdb_word_number_normalize(cm, word_s, word_e, &norm_buf, &norm_s, &norm_e); if (err != 0) return err; /* If the normalized version isn't identical * to the original's integral part... */ if (norm_s != orig_int || norm_e != orig_point) { char const *norm_int, *norm_point, *norm_frac; /* The whole normalized version. */ err = (*callback)(data, pdb, id, norm_s, norm_e); if (err != 0) { if (norm_buf != NULL) cm_free(cm, norm_buf); return err; } /* Split the normalization into * integral part and fraction. */ err = pdb_word_number_split(norm_s, norm_e, &norm_int, &norm_point, &norm_frac); cl_assert(cl, err == 0); if (err != 0) { if (norm_buf != NULL) cm_free(cm, norm_buf); return err; } cl_assert(cl, norm_int < norm_point); /* Just the integer part, with sign - if * that's different from the full value. */ if (norm_point != norm_e) { /* Hash in the pre-. word alone, since * it's different from the normalized word. */ err = (*callback)(data, pdb, id, norm_s, norm_point); if (err != 0) { if (norm_buf != NULL) cm_free(cm, norm_buf); return err; } } } if (norm_buf != NULL) cm_free(cm, norm_buf); } return 0; } static int pdb_word_has_prefix_callback(void *data, pdb_handle *pdb, pdb_id id, char const *s, char const *e) { char const *prefix = data; for (; *prefix != '\0'; s++, prefix++) { if (s >= e) return 0; if (isascii(*prefix) ? tolower(*prefix) != tolower(*s) : *prefix != *s) return 0; } return PDB_ERR_ALREADY; } bool pdb_word_has_prefix(pdb_handle *pdb, char const *prefix, char const *s, char const *e) { return pdb_word_chop((void *)prefix, pdb, 0, s, e, pdb_word_has_prefix_callback) == PDB_ERR_ALREADY; } static int pdb_word_has_prefix_hash_callback(void *data, pdb_handle *pdb, pdb_id id, char const *s, char const *e) { unsigned long long const *prefix = data; unsigned long long word_hash = pdb_word_hash(pdb, s, e); return (word_hash & prefix[0]) == prefix[1] ? PDB_ERR_ALREADY : 0; } bool pdb_word_has_prefix_hash(pdb_handle *pdb, unsigned long long const *prefix, char const *s, char const *e) { return pdb_word_chop((void *)prefix, pdb, 0, s, e, pdb_word_has_prefix_hash_callback) == PDB_ERR_ALREADY; } /* Compile a prefix string s..e into a two-element prefix * code. prefix[0] is the mask, prefix[1] the hash code * of the bytes set in the mask. */ void pdb_word_has_prefix_hash_compile(pdb_handle *pdb, unsigned long long *prefix, char const *s, char const *e) { int n = pdb_word_utf8len(pdb, s, e); cl_assert(pdb->pdb_cl, n <= 5); prefix[0] = ~0 << (5 * (5 - n)); prefix[1] = pdb_word_hash(pdb, s, e); } /* Use two bytes of the hash as "key" thereby dumping * all hashes having the same upper 3 bytes into the * same bucket. */ static int pdb_word_hmap_add(pdb_handle *pdb, addb_hmap *hm, unsigned long h, pdb_id id, int map) { char key[4]; pdb->pdb_runtime_statistics.rts_index_elements_written++; pdb_word_key(h, key); return addb_hmap_add(hm, h, key, sizeof key, map, id); } static int pdb_word_add_callback(void *data, pdb_handle *pdb, pdb_id id, char const *s, char const *e) { unsigned long m; unsigned long word_hash = pdb_word_hash(pdb, s, e); int err; bool bit; /* Tell the prefix cache that its statistics may be * changing, and may need recalculating. */ pdb_prefix_statistics_drift(pdb, s, e); /* Add the word entry to the index. */ err = pdb_word_hmap_add(pdb, pdb->pdb_hmap, word_hash, id, addb_hmt_word); if (err == PDB_ERR_EXISTS) return 0; if (err) { cl_log(pdb->pdb_cl, CL_LEVEL_FAIL, "pdb_word_add_callback(%.*s): error %s", (int)(e - s), s, strerror(err)); return err; } /* Update the prefix index. */ err = addb_bmap_check_and_set(pdb->pdb_prefix, word_hash, &bit); if (err) { cl_log(pdb->pdb_cl, CL_LEVEL_FAIL, "pdb_word_add_callback(%.*s): error %s", (int)(e - s), s, strerror(err)); return err; } if (bit) { cl_log(pdb->pdb_cl, CL_LEVEL_VERBOSE, "pdb_word_add_callback(%.*s, id=%llx): " "hash %llx already in the database", (int)(e - s), s, (unsigned long long)id, (unsigned long long)word_hash); return 0; } cl_log(pdb->pdb_cl, CL_LEVEL_VERBOSE, "pdb_word_add_callback(%.*s, id=%llx): " "add hash %llx", (int)(e - s), s, (unsigned long long)id, (unsigned long long)word_hash); /* That covered the full word. * * 1 2 3 4 5 * * Now mark the four prefixes: * * 1 2 3 4 # * 1 2 3 # # * 1 2 # # # * 1 # # # # * * Stop as soon as you hit a prefix that is already marked. * (It doesn't matter how many markers there are, or what * their value is.) */ for (m = 0x1F; m < (1 << (5 * 4)); m |= (m << 5)) { unsigned long wh = word_hash | m; cl_assert(pdb->pdb_cl, (word_hash & m) != wh); err = addb_bmap_check_and_set(pdb->pdb_prefix, wh, &bit); if (err < 0) return err; if (bit > 0) { cl_log(pdb->pdb_cl, CL_LEVEL_VERBOSE, "pdb_word_add_callback(%.*s): " "prefix %lx already in the database", (int)(e - s), s, (unsigned long)wh); return 0; } } return 0; } /** * @brief Add a value to the word index database. */ int pdb_word_add(pdb_handle *pdb, pdb_id id, char const *s, char const *e) { cl_cover(pdb->pdb_cl); return pdb_word_chop(NULL, pdb, id, s, e, pdb_word_add_callback); } /** * @brief Add a primitive to the word index. * * @param pdb module handle * @param id local ID of the primitive * @param pr primitive data * * @return 0 on success, a nonzero error code on unexpected error. */ int pdb_word_synchronize(pdb_handle *pdb, pdb_id id, pdb_primitive const *pr) { size_t sz; if ((sz = pdb_primitive_value_get_size(pr)) > 0) { char const *mem; mem = pdb_primitive_value_get_memory(pr); cl_cover(pdb->pdb_cl); return pdb_word_chop(NULL, pdb, id, mem, mem + sz - 1, pdb_word_add_callback); } cl_cover(pdb->pdb_cl); return 0; } /** * @brief initialize an iterator over everything that might contain * a given word. * * The indices on the map are guaranteed to be a superset of the * word's actual occurrences - the caller still needs to rescan the * value contents. * * @param pdb module handle * @param s first byte of the word in question * @param e last byte of the word in question * @param low lower boundary, or PDB_ITERATOR_LOW_ANY * @param high upper boundary, or PDB_ITERATOR_HIGH_ANY * @param forward if we should turn into a single * iteration, which direction should it have? * @param it_out the iterator to initialize * * @return 0 on success, a nonzero error code on error. */ int pdb_iterator_word_create(pdb_handle *pdb, char const *s, char const *e, pdb_id low, pdb_id high, bool forward, bool error_if_null, pdb_iterator **it_out) { unsigned long word_hash = pdb_word_hash(pdb, s, e); char key[4]; pdb_word_key(word_hash, key); return pdb_iterator_hmap_create(pdb, pdb->pdb_hmap, word_hash, key, sizeof key, addb_hmt_word, low, high, forward, error_if_null, it_out); } /** * @brief Return the next fragment from a text value. * * @param s0 the begin of the entire text * @param s in/out: the beginning of the text to parse * @param e end of the text to parse * @param word_s_out out: beginning of a fragment * @param word_e_out out: end of a fragment * @param word_type_out out: type of word * * @return true if a fragment has been extracted * @return false if we're out of words. */ bool pdb_word_fragment_next(char const *s0, char const **s, char const *e, char const **word_s_out, char const **word_e_out, int *word_type_out) { char const *r; char const *pre_s, *pre_e; char const *post_s, *post_e; if ((r = *s) == NULL) r = *s = s0; if (r >= e) return false; *word_s_out = r; /* What's the longest number that we can pull out of this? */ if (ISSIGNPTR(r, s0)) r++; pre_s = r; while (r < e && ISDIGIT(*r)) r++; pre_e = r; if ((pre_s == s0 || !ISPOINT(pre_s[-1])) && (pre_s < pre_e || r == s0 || !ISDIGIT(r[-1])) && r < e && ISPOINT(*r)) { r++; post_s = r; while (r < e && ISDIGIT(*r)) r++; post_e = r; if ((r >= e || !ISWORD(*r)) && ((post_e > post_s) || (pre_e > pre_s))) { /* 5. * +1. * -.01 */ /* There isn't another dot after this * number, right? */ if (r >= e || !ISPOINT(*r)) { /* Regular floating point number. */ *word_e_out = *s = r; *word_type_out = PDB_WORD_NUMBER; return true; } /* IP addresses and dot-separated hierarchial * names are not floating point numbers - * take them one segment at a time. */ if (pre_s < pre_e) { *word_e_out = *s = pre_e; *word_type_out = PDB_WORD_NUMBER; return true; } /* Weirdness of the form [+-].34. -- skip * punctuation, let the next iteration * take care of the number. */ *word_e_out = *s = post_s; *word_type_out = PDB_WORD_PUNCTUATION; return true; } } if (pre_s < pre_e && (pre_e == e || !ISWORD(*pre_e))) { *word_e_out = *s = pre_e; *word_type_out = PDB_WORD_NUMBER; return true; } /* OK, that didn't work. Whatever this is, we're * not standing on a number. Just pull out a normal * word or nonword. */ r = *s; if (ISWORD(*r)) { do r++; while (r < e && ISWORD(*r)); *word_type_out = PDB_WORD_ATOM; } else if (ISSPACE(*r)) { do r++; while (r < e && ISSPACE(*r)); *word_type_out = PDB_WORD_SPACE; } else { do r++; while (r < e && ISPUNCT(*r) && !ISSIGNPTR(r, s0)); *word_type_out = PDB_WORD_PUNCTUATION; } *word_e_out = *s = r; return true; } /** * @brief Split a number into its pieces * * @param s the beginning of the number * @param e end of the number * @param pre_s end of sign, pre-point start * @param point_s end of pre-point, dot start * @param post_s end of dot, post-point start * ** @return PDB_ERR_NO if the input is not a number. */ int pdb_word_number_split(char const *s, char const *e, char const **pre_s, char const **point_s, char const **post_s) { if (s >= e) return PDB_ERR_NO; s += ISSIGN(*s); *pre_s = s; if (s >= e) return PDB_ERR_NO; for (; s < e; s++) if (ISPOINT(*s)) { *point_s = s; *post_s = s + 1; return 0; } *point_s = *post_s = e; return 0; } /** * @brief Normalize a number * * - Remove "+", * - Remove "-" from 0 * - Remove leading 0 (except a lone 0) from pre-. or , values. * - Turn , into . * - Remove trailing 0 from post-. or , values. * - Remove trailing . if post-. or , values were 0 only. * - Turn .323 into 0.323 * * Numbers grow at most by one digit on normalization. If you * want to avoid overflow errors, allocate (e - s) + 2 positions * for the buffer. * * @param cm allocate normalization buffer here * @param s the beginning of the number * @param e end of the number * @param *buf_out buffer if allocated * @param norm_s_out normalized string, start * @param norm_e_out normalized string, end * * @return 0 on success, PDB_ERR_NO on syntax error. */ int pdb_word_number_normalize(cm_handle *cm, char const *s, char const *e, char **buf_out, char const **norm_s_out, char const **norm_e_out) { char const *int_s, *int_e, *frac_s, *frac_e; char const *sig_s, *sig_e; char *buf; size_t need; bool need_reconstruction = false; *buf_out = NULL; if (s >= e) return PDB_ERR_NO; sig_s = sig_e = s; if (*sig_s == '+') sig_e = ++sig_s; else if (*sig_s == '-') sig_e = sig_s + 1; frac_s = frac_e = e; int_s = sig_e; for (int_e = int_s; int_e < e; int_e++) /* Fraction starts here? */ if (ISPOINT(*int_e)) { frac_s = int_e + 1; /* Strip trailing zeros. */ while (frac_e > frac_s && frac_e[-1] == '0') frac_e--; break; } /* Add/Remove leading zeros. */ if (int_e == int_s) { /* .150 -> 0.150 */ int_s = "0"; int_e = int_s + 1; if (frac_s < frac_e || sig_s < sig_e) need_reconstruction = true; } else { /* 01 -> 1, 0000 -> 0 */ while (int_s + 1 < int_e && *int_s == '0') { int_s++; if (sig_s < sig_e) need_reconstruction = true; } } /* If the integral part is "0", and there is * no fraction, remove the leading sign. */ if (int_e == int_s + 1 && *int_s == '0' && frac_s == frac_e) sig_s = sig_e = int_s; /* Regroup empty sign and fraction value * around the int value. */ if (sig_s == sig_e) sig_s = sig_e = int_s; if (frac_s == frac_e) frac_s = frac_e = int_e; if (!need_reconstruction) { /* The normalized value is fully contained * in the pre-normalized value. */ *norm_s_out = sig_s; *norm_e_out = frac_e; return 0; } need = (sig_e - sig_s) /* sign */ + (int_e - int_s) /* integer part */ + (frac_s < frac_e) /* 1 for . if there's a fraction*/ + (frac_e - frac_s) /* fraction */ + 1; /* terminating \0 */ buf = cm_malloc(cm, need); if (buf == NULL) return errno ? errno : ENOMEM; if (frac_s < frac_e) snprintf(buf, need, "%.*s%.*s.%.*s", (int)(sig_e - sig_s), sig_s, (int)(int_e - int_s), int_s, (int)(frac_e - frac_s), frac_s); else snprintf(buf, need, "%.*s%.*s", (int)(sig_e - sig_s), sig_s, (int)(int_e - int_s), int_s); *norm_s_out = *buf_out = buf; *norm_e_out = buf + strlen(buf); return 0; } static char *shrink_spaces(const char *in_s, const char *in_e, char *out) { char c; // char * last_nonspace = out; while (in_s < in_e) { c = *out = *in_s; if (ISSPACE(c)) { *out = ' '; out++; while (ISSPACE(*in_s) && (in_s < in_e)) in_s++; } else { in_s++; out++; // last_nonspace = out; } } return out; } /* * Render a number to a string in graphd normalized form. * A normalized number looks like: * (-)[0-9]+e(-)[0-9]+ * with the resitrctions that zero is always "0" and * no other instances of leading zeroes are allowed in both * the mantissa and exponent. Except in the case of "0", the * exponent must always be present. There is an implicit decimal point * after the first digit. This is exactly strict scientific notation * with an implicit dot. */ char *pdb_number_to_string(cm_handle *cm, const graph_number *n) { char *out; if (n->num_zero) out = cm_strmalcpy(cm, "0"); else if (n->num_infinity && n->num_positive) out = cm_strmalcpy(cm, "+Inf"); else if (n->num_infinity && !n->num_positive) out = cm_strmalcpy(cm, "-Inf"); else if (n->num_dot) { out = cm_sprintf(cm, "%s%.*s%.*se%i", n->num_positive ? "" : "-", (int)(n->num_dot - n->num_fnz), n->num_fnz, (int)(n->num_lnz - n->num_dot) - 1, n->num_dot + 1, n->num_exponent); } else { out = cm_sprintf(cm, "%s%.*se%i", n->num_positive ? "" : "-", (int)(n->num_lnz - n->num_fnz), n->num_fnz, n->num_exponent); } return out; } static int pdb_number_normalize(pdb_handle *pdb, cm_handle *cm, const char *s, const char *e, const char **out_s, const char **out_e, char **buf) { graph_number n; int err; err = graph_decode_number(s, e, &n, true); if (err) { cl_log(pdb->pdb_cl, CL_LEVEL_SPEW, "pdb_normalize_number: '%.*s' is not a number", (int)(e - s), s); return PDB_ERR_SYNTAX; } *buf = NULL; if (n.num_zero) *out_s = "0"; else if (n.num_infinity && n.num_positive) *out_s = "+Inf"; else if (n.num_infinity && !n.num_positive) *out_s = "-Inf"; else if (n.num_dot) { *out_s = *buf = cm_sprintf(cm, "%s%.*s%.*se%i", n.num_positive ? "" : "-", (int)(n.num_dot - n.num_fnz), n.num_fnz, (int)(n.num_lnz - n.num_dot) - 1, n.num_dot + 1, n.num_exponent); } else { *out_s = *buf = cm_sprintf(cm, "%s%.*se%i", n.num_positive ? "" : "-", (int)(n.num_lnz - n.num_fnz), n.num_fnz, n.num_exponent); } if (!(*out_s)) { cl_log(pdb->pdb_cl, CL_LEVEL_FAIL, "normalize_number: out of memory"); return ENOMEM; } *out_e = *out_s + strlen(*out_s); return 0; } static int pdb_word_normalize(pdb_handle *pdb, char const *s, char const *e, char const **norm_s_out, char const **norm_e_out, char **buf_out) { char const *r, *word_s, *word_e; char *buf_w, *buf_e = NULL; char const *word_r; size_t point = 0, digit = 0; int word_type; int space = 0; cl_handle *cl = pdb->pdb_cl; cm_handle *cm = pdb->pdb_cm; *buf_out = NULL; for (r = s; r < e; r++) { if (ISPOINT(*r)) point++; else if (ISDIGIT(*r)) digit++; else if (ISSPACE(*r)) space++; } if (!point && !digit && !space) { *norm_s_out = s; *norm_e_out = e; *buf_out = NULL; return 0; } while (isspace(*s) && s < e) s++; r = word_r = s; buf_w = NULL; while (pdb_word_fragment_next(s, &r, e, &word_s, &word_e, &word_type)) { int err; char *norm_buf = NULL; char const *norm_s; char const *norm_e; if (word_type != PDB_WORD_NUMBER) continue; err = pdb_word_number_normalize(cm, word_s, word_e, &norm_buf, &norm_s, &norm_e); if (err != 0) return err; if (norm_s == word_s && norm_e == word_e) { cl_assert(cl, norm_buf == NULL); continue; } /* OK, we need to normalize. */ if (*buf_out == NULL) { *buf_out = cm_malloc(cm, point + 1 + (e - s)); if (*buf_out == NULL) { if (norm_buf != NULL) cm_free(cm, norm_buf); return ENOMEM; } buf_w = *buf_out; buf_e = buf_w + point + 1 + (e - s); cl_assert(cl, buf_w < buf_e); } /* Catch up to here. * * word_r is how far we're caught up. * * word_s is the beginning of the area * that may change with normalization. */ if (word_s > word_r) { /* copy norm here */ buf_w = shrink_spaces(word_r, word_s, buf_w); cl_assert(cl, buf_w < buf_e); } /* Append the normalized word */ memcpy(buf_w, norm_s, norm_e - norm_s); buf_w += norm_e - norm_s; cl_assert(cl, buf_w < buf_e); /* Advance the base of the next non-normalized * text to behind the number. */ word_r = r; if (norm_buf != NULL) cm_free(cm, norm_buf); } /* Catch up to the end. */ if (*buf_out == NULL) { /* We never normalized anything. */ if (e == s) { /* nothing to do... */ *buf_out = NULL; *norm_s_out = *norm_e_out = s; return 0; } *norm_s_out = *buf_out = cm_malloc(cm, e - s); if (!*norm_s_out) return ENOMEM; *norm_e_out = shrink_spaces(s, e, *buf_out); while ((*norm_e_out > *norm_s_out) && isspace((*norm_e_out)[-1])) (*norm_e_out)--; return 0; } /* Catch up to here. */ if (word_r < e) { buf_w = shrink_spaces(word_r, e, buf_w); } while ((buf_w > *buf_out) && isspace(buf_w[-1])) buf_w--; cl_assert(cl, buf_w < buf_e); *buf_w = '\0'; *norm_s_out = *buf_out; *norm_e_out = buf_w; return 0; } int pdb_hmap_value_normalize(pdb_handle *pdb, const char *s, const char *e, const char **out_s, const char **out_e, char **buf) { int err; err = pdb_number_normalize(pdb, pdb->pdb_cm, s, e, out_s, out_e, buf); if (!err) { cl_log(pdb->pdb_cl, CL_LEVEL_SPEW, "pdb_hmap_value_normalize: number '%.*s' to '%.*s'", (int)(e - s), s, (int)(*out_e - *out_s), *out_s); return 0; } if (err != PDB_ERR_SYNTAX) return err; err = pdb_word_normalize(pdb, s, e, out_s, out_e, buf); cl_log(pdb->pdb_cl, CL_LEVEL_SPEW, "pdb_hmap_value_normalize: string '%.*s' to '%.*s'", (int)(e - s), s, (int)(*out_e - *out_s), *out_s); return err; }
C
#ifndef VARIABLE_H_ #define VARIABLE_H_ #include "str.h" #include "error.h" #include "tabSym.h" #include <stdbool.h> /* * Funkce pro ziskani hodnoty promenne * @param tVariablePtr[in] promenna pro prevedeni * @return (int|double|bool) */ #define getVarVal(var) \ ((var->type == VAR_TYPE_INT) ? (var->data.intVal) : (var->type == VAR_TYPE_BOOL) ? (var->data.boolVal) : (var->data.doubleVal)) typedef enum { VAR_TYPE_INT, VAR_TYPE_BOOL, VAR_TYPE_DOUBLE, VAR_TYPE_STRING } tVariableType; typedef union { int intVal; double doubleVal; string stringVal; bool boolVal; }tVariableData; typedef struct tVariableStr{ tVariableType type; tVariableData data; bool init; bool deklared; } *tVariablePtr; /* * Utvori strukturu promenne, inicializuje string. * @param tVariable[out] struktura promenne * @param tVariableType[in] urcuje typ */ void variableCreate(tVariablePtr*, tVariableType); /* * Spravne smaze promennou. Preda se ukazatelem pri mazani stromu * @param tVariable[in] struktura promenne */ void variableDelete(void*); /* * Prevede notaci dat. typu tabulky symbolu do notace promenne * @param tTabSymVarDataType[in] notace v tabulce symbolu * @return tVariableType[out] notece ve variable */ tVariableType tTabSymToVarNotatation(tTabSymVarDataType); #endif //VARIABLE_H_
C
// COMP1521 18s2 mysh ... command history // Implements an abstract data object #include <stdio.h> #include <stdlib.h> #include <string.h> #include "history.h" // This is defined in string.h // BUT ONLY if you use -std=gnu99 //extern char *strdup(const char *s); // Command History // array of command lines // each is associated with a sequence number #define MAXHIST 20 #define MAXSTR 200 #define HISTFILE ".mymysh_history" typedef struct _history_entry { int seqNumber; char *commandLine; } HistoryEntry; typedef struct _history_list { int nEntries; HistoryEntry commands[MAXHIST]; } HistoryList; HistoryList CommandHistory; // initCommandHistory() // - initialise the data structure // - read from .history if it exists int initCommandHistory() { // TODO int i = 0; // open the history file FILE *file = fopen(HISTFILE, "r"); if (file != NULL) { char buffer[MAXSTR]; int seqNum; // goes through each line of the file and stores it into buffer while (fgets(buffer, sizeof(buffer), file) != NULL) { // null terminate each buffer buffer[strlen(buffer)-1] = '\0'; char *s = malloc(MAXSTR); // scans in sequence number and string from buffer sscanf(buffer, " %3d %s\n", &seqNum, s); // updates how many entries in history CommandHistory.nEntries++; // initialising the sequence number of each command CommandHistory.commands[i].seqNumber = seqNum; // copying the string into each command in history CommandHistory.commands[i].commandLine = strdup(s); free(s); i++; } seqNum++; fclose(file); return seqNum; } else { // otherwise if file is empty for (int i = 0; i < MAXHIST; i++) { CommandHistory.commands[i].commandLine = NULL; } } return 1; } // addToCommandHistory() // - add a command line to the history list // - overwrite oldest entry if buffer is full void addToCommandHistory(char *cmdLine, int seqNo) { // TODO // if the sequence number is exceeding to show the last 20 if (seqNo-1 >= MAXHIST) { // shift the history down by 1 for (int i = 0; i < MAXHIST; i++) { CommandHistory.commands[i].seqNumber = CommandHistory.commands[i+1].seqNumber; CommandHistory.commands[i].commandLine = CommandHistory.commands[i+1].commandLine; } // adds latest entry CommandHistory.commands[MAXHIST-1].seqNumber = seqNo; CommandHistory.commands[MAXHIST-1].commandLine = strdup(cmdLine); } else { // otherwise sequence number keeps increasing while adding last entry CommandHistory.commands[seqNo-1].seqNumber = seqNo; CommandHistory.commands[seqNo-1].commandLine = strdup(cmdLine); CommandHistory.nEntries++; } } // showCommandHistory() // - display the list of entries void showCommandHistory(FILE *outf) { // TODO for (int i = 0; i < CommandHistory.nEntries; i++) { printf (" %3d %s\n", CommandHistory.commands[i].seqNumber, CommandHistory.commands[i].commandLine); } } // getCommandFromHistory() // - get the command line for specified command // - returns NULL if no command with this number char *getCommandFromHistory(int cmdNo) { // TODO for (int i = 0; i < CommandHistory.nEntries; i++) { if (cmdNo == CommandHistory.commands[i].seqNumber) { return CommandHistory.commands[i].commandLine; } } return NULL; } // saveCommandHistory() // - write history to $HOME/.mymysh_history void saveCommandHistory() { // TODO FILE *f = fopen(HISTFILE, "w"); if (f != NULL) { for (int i = 0; i < CommandHistory.nEntries; i++) { fprintf (f, " %3d %s\n", CommandHistory.commands[i].seqNumber, CommandHistory.commands[i].commandLine); } fclose(f); } } // cleanCommandHistory // - release all data allocated to command history void cleanCommandHistory() { // TODO for (int i = 0; i < CommandHistory.nEntries; i++) { CommandHistory.commands[i].seqNumber = 0; free(CommandHistory.commands[i].commandLine); CommandHistory.commands[i].commandLine = NULL; } }
C
/* * event.c * * Author: kayekss * Target: unspecified */ #include <stdbool.h> #include <stdint.h> #include "ctime.h" #include "event.h" // Clear event entry inline void event_clear(event_t* ev) { ev->on.h = 0; ev->on.m = 0; ev->off.h = 0; ev->off.m = 0; ev->mask = ~0; } // Fix problems in event entry inline void event_fix_problems(event_t* ev) { uint16_t on_mins, off_mins; // Void the entire entry if any value is out of range if (ev->on.h > 23 || ev->on.m > 59 || ev->off.h > 24 || ev->off.m > 59) { event_clear(ev); } // Set off-event time to 24:00 // ... if it is 24:>00 or time order is reversed on_mins = ev->on.h * 60 + ev->on.m; off_mins = ev->off.h * 60 + ev->off.m; if (off_mins > 24 * 60 || on_mins > off_mins) { ev->off.h = 24; ev->off.m = 0; } // Set the reserved bit ev->mask |= 0x01; } // Get the output state from specified clock time and day-of-week inline bool event_output_state(event_t* ev, uint8_t h, uint8_t m, dow_t dow) { uint16_t on_mins, off_mins, mins; on_mins = ev->on.h * 60 + ev->on.m; off_mins = ev->off.h * 60 + ev->off.m; mins = h * 60 + m; return (ev->mask & (1 << dow)) && (mins >= on_mins) && (mins < off_mins); }
C
// Dang Lam San 20170111 #include <stdio.h> #include <math.h> int main() { float a, b, c; printf("Nhap vao 3 he so\n"); scanf("%f%f%f", &a, &b, &c); if (a == 0) { if (b == 0) { if (c == 0) { printf("Phuong trinh co vo so nghiem"); return 0; } else { printf("Phuong trinh vo nghiem"); return 0; } } printf("Phuong trinh co nghiem x = %f", -c / b); } else { float delta = b * b - 4 * a * c; if (delta > 0) { printf("Nghiem x1 = %f", (-b + sqrt(delta)) / (2 * a)); printf("\nNghiem x2 = %f", (-b - sqrt(delta)) / (2 * a)); return 0; } if (delta == 0) { printf("Nghiem kep x = %f", -b / (2 * a)); return 0; } printf("Nghiem x1 = %f + %fi", -b / (2 * a), sqrt(-delta) / (2 * a)); printf("Nghiem x1 = %f - %fi", -b / (2 * a), sqrt(-delta) / (2 * a)); } printf("\nDang Lam San 20170111"); }
C
#include<stdio.h> int main (void) { int v1[10], v2[10], v3[10], cnt, num; printf(" ************************************************ \n"); printf(" **Esse programa calcula multiplicao de vetores** \n"); printf(" ************************************************ \n\n"); printf("Digite os valores a guardar no vetor 1: "); for(cnt = 0; cnt < 10; cnt++) { scanf("%i", &num); v1[cnt] = num; } printf("\n"); printf("Digite os valores a guardar no vetor 2: "); for(cnt = 0; cnt < 10; cnt++) { scanf("%i", &num); v2[cnt] = num; } printf("\n"); printf("Os valores resultantes da multiplicacao sao: "); for(cnt = 0; cnt < 10; cnt++) { v3[cnt] = v1[cnt] * v2[cnt]; printf("%i ", v3[cnt]); } printf("\n"); return 0; }
C
#pragma once #include <GL/glut.h> typedef unsigned char ubyte; struct RGB { ubyte r; ubyte g; ubyte b; ubyte gray() { return 0.299 * r + 0.587 * g + 0.114 * b; } bool isGray() { return r == g && g == b; } }; extern RGB BLACK; extern RGB WHITE; bool operator == (const RGB& a, const RGB& b); bool operator != (const RGB& a, const RGB& b);
C
#include <stdio.h> #define tonum(c)(c >= 'A' && c <= 'Z' ? c - 'A' : c - 'a' + 26) int main(){ char c; c = 'B'; printf("%d\n", tonum(c)); return 0; }
C
#include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <time.h> #include <errno.h> #include <stdint.h> #include <string.h> #include <assert.h> #include "slist.h" #include "directory.h" void storage_init(const char* path) { pages_init(path); directory_init(); } int storage_stat(const char* path, struct stat* st) { int inum = tree_lookup(path); if (inum < 0) { return inum; } inode* inode = get_inode(inum); if (st) { st->st_mode = inode->mode; st->st_size = inode->size; st->st_uid = getuid(); } return 0; } int storage_read(const char* path, char* buf, size_t size, off_t offset) { int inum = tree_lookup(path); inode* inode = get_inode(inum); void* data = pages_get_page(inode->pnums[0]); memcpy(buf, (void*)((uintptr_t)data + offset), size); return size; } int storage_write(const char* path, const char* buf, size_t size, off_t offset) { int inum = tree_lookup(path); inode* inode = get_inode(inum); void* data = pages_get_page(inode->pnums[0]); memcpy((void*)((uintptr_t)data + inode->size), (void*)((uintptr_t)buf + offset), size); inode->size += size; return size; } int storage_truncate(const char *path, off_t size) { int inum = tree_lookup(path); inode* inode = get_inode(inum); inode->size = size; return size; } int storage_mknod(const char* path, int mode) { int inum = alloc_inode(); int pnum = alloc_page(); inode* inode = get_inode(inum); inode->refs = 1; inode->mode = mode; inode->size = 0; inode->pnums[0] = pnum; inode->iptr = 0; return directory_put(get_inode(0), path, inum); } int storage_unlink(const char* path) { return directory_delete(get_inode(0), path); } int storage_link(const char *from, const char *to) { return -ENOSYS; } int storage_rename(const char *from, const char *to) { int inum = tree_lookup(from); int rv = directory_delete(get_inode(0), from); assert(rv == 0); return directory_put(get_inode(0), to, inum); } int storage_set_time(const char* path, const struct timespec ts[2]) { return -ENOSYS; } slist* storage_list(const char* path) { printf(path); return directory_list(path); }
C
///============================================================================ // // PROJET : PORTABLES 2014 // MODULE : Board.c // DESCRIPTION : Configuration de la carte // //============================================================================= //============================================================================= //--- DECLARATIONS //============================================================================= //----------------------------------------------------------------------------- // Fichiers Inclus //----------------------------------------------------------------------------- #include "gpio.h" #include "clock.h" //----------------------------------------------------------------------------- // Constantes : defines et enums //----------------------------------------------------------------------------- /** @addtogroup GPIO_Private_Constants GPIO Private Constants * @{ */ #define GPIO_MODE ((uint32_t)0x00000003) #define EXTI_MODE ((uint32_t)0x10000000) #define GPIO_MODE_IT ((uint32_t)0x00010000) #define GPIO_MODE_EVT ((uint32_t)0x00020000) #define RISING_EDGE ((uint32_t)0x00100000) #define FALLING_EDGE ((uint32_t)0x00200000) #define GPIO_OUTPUT_TYPE ((uint32_t)0x00000010) #define GPIO_NUMBER ((uint32_t)16) //----------------------------------------------------------------------------- // Variables et Fonctions Privees //----------------------------------------------------------------------------- //============================================================================= //--- DEFINITIONS //============================================================================= //----------------------------------------------------------------------------- // FONCTION : HAL_Get_Nb_GPIO // // DESCRIPTION : //----------------------------------------------------------------------------- void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init) { uint32_t position; uint32_t ioposition = 0x00; uint32_t iocurrent = 0x00; uint32_t temp = 0x00; __HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); __HAL_RCC_GPIOC_CLK_ENABLE(); __HAL_RCC_GPIOD_CLK_ENABLE(); __HAL_RCC_GPIOE_CLK_ENABLE(); __HAL_RCC_GPIOF_CLK_ENABLE(); __HAL_RCC_GPIOG_CLK_ENABLE(); __HAL_RCC_GPIOH_CLK_ENABLE(); __HAL_RCC_GPIOI_CLK_ENABLE(); /* Configure the port pins */ for(position = 0; position < GPIO_NUMBER; position++) { /* Get the IO position */ ioposition = ((uint32_t)0x01) << position; /* Get the current IO position */ iocurrent = (uint32_t)(GPIO_Init->Pin) & ioposition; if(iocurrent == ioposition) { /*--------------------- GPIO Mode Configuration ------------------------*/ /* In case of Alternate function mode selection */ if((GPIO_Init->Mode == GPIO_MODE_AF_PP) || (GPIO_Init->Mode == GPIO_MODE_AF_OD)) { /* Configure Alternate function mapped with the current IO */ temp = GPIOx->AFR[position >> 3]; temp &= ~((uint32_t)0xF << ((uint32_t)(position & (uint32_t)0x07) * 4)) ; temp |= ((uint32_t)(GPIO_Init->Alternate) << (((uint32_t)position & (uint32_t)0x07) * 4)); GPIOx->AFR[position >> 3] = temp; } /* Configure IO Direction mode (Input, Output, Alternate or Analog) */ temp = GPIOx->MODER; temp &= ~(GPIO_MODER_MODER0 << (position * 2)); temp |= ((GPIO_Init->Mode & GPIO_MODE) << (position * 2)); GPIOx->MODER = temp; /* In case of Output or Alternate function mode selection */ if((GPIO_Init->Mode == GPIO_MODE_OUTPUT_PP) || (GPIO_Init->Mode == GPIO_MODE_AF_PP) || (GPIO_Init->Mode == GPIO_MODE_OUTPUT_OD) || (GPIO_Init->Mode == GPIO_MODE_AF_OD)) { /* Configure the IO Speed */ temp = GPIOx->OSPEEDR; temp &= ~(GPIO_OSPEEDER_OSPEEDR0 << (position * 2)); temp |= (2 << (position * 2)); //-- GPIO_SPEED_FREQ_HIGH GPIOx->OSPEEDR = temp; /* Configure the IO Output Type */ temp = GPIOx->OTYPER; temp &= ~(GPIO_OTYPER_OT_0 << position) ; temp |= (((GPIO_Init->Mode & GPIO_OUTPUT_TYPE) >> 4) << position); GPIOx->OTYPER = temp; } /* Activate the Pull-up or Pull down resistor for the current IO */ temp = GPIOx->PUPDR; temp &= ~(GPIO_PUPDR_PUPDR0 << (position * 2)); temp |= ((GPIO_Init->Pull) << (position * 2)); GPIOx->PUPDR = temp; /*--------------------- EXTI Mode Configuration ------------------------*/ /* Configure the External Interrupt or event for the current IO */ if((GPIO_Init->Mode & EXTI_MODE) == EXTI_MODE) { /* Enable SYSCFG Clock */ Peripheral_Descriptor_t rcc; rcc = DRIVER_open("RCC",0); DRIVER_ioctl(rcc,SYSCFG_CLK,true); // __HAL_RCC_SYSCFG_CLK_ENABLE(); temp = SYSCFG->EXTICR[position >> 2]; temp &= ~(((uint32_t)0x0F) << (4 * (position & 0x03))); temp |= ((uint32_t)(GPIO_GET_INDEX(GPIOx)) << (4 * (position & 0x03))); SYSCFG->EXTICR[position >> 2] = temp; /* Clear EXTI line configuration */ temp = EXTI->IMR; temp &= ~((uint32_t)iocurrent); if((GPIO_Init->Mode & GPIO_MODE_IT) == GPIO_MODE_IT) { temp |= iocurrent; } EXTI->IMR = temp; temp = EXTI->EMR; temp &= ~((uint32_t)iocurrent); if((GPIO_Init->Mode & GPIO_MODE_EVT) == GPIO_MODE_EVT) { temp |= iocurrent; } EXTI->EMR = temp; /* Clear Rising Falling edge configuration */ temp = EXTI->RTSR; temp &= ~((uint32_t)iocurrent); if((GPIO_Init->Mode & RISING_EDGE) == RISING_EDGE) { temp |= iocurrent; } EXTI->RTSR = temp; temp = EXTI->FTSR; temp &= ~((uint32_t)iocurrent); if((GPIO_Init->Mode & FALLING_EDGE) == FALLING_EDGE) { temp |= iocurrent; } EXTI->FTSR = temp; } } } } void HAL_GPIO_WritePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, bool PinState) { if(PinState) { GPIOx->BSRR = GPIO_Pin; } else { GPIOx->BSRR = (uint32_t)GPIO_Pin << 16; } }
C
/* ** my_printf.c for libmy in /home/kevin/Documents/prog/C/libmy ** ** Made by kevin ** Login <[email protected]> ** ** Started on Wed Nov 12 11:30:07 2014 kevin ** Last update Wed Nov 12 11:30:07 2014 kevin */ #include "my.h" int my_printf(char *str, ...) { char *ret; va_list ap; int len; va_start(ap, str); ret = parse_str(str, ap); ret = (ret == NULL ? "(null\n)" : ret); write(1, ret, (len = my_strlen(ret))); va_end(ap); free(ret); return (len); }
C
#include "common.h" /** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */ int* majorityElement(int* nums, int numsSize, int* returnSize) { int*res = malloc(2 * sizeof(int)); *returnSize = 0; int i, n1 = 0, n2 = 1, cnt1 = 0, cnt2 = 0; for (i = 0; i < numsSize; ++i) { if (nums[i] == n1) { ++cnt1; } else if (nums[i] == n2) { ++cnt2; } else if (cnt1 == 0) { n1 = nums[i]; cnt1 = 1; } else if (cnt2 == 0) { n2 = nums[i]; cnt2 = 1; } else { --cnt1; --cnt2; } } cnt1 = cnt2 = 0; for (i = 0; i < numsSize; ++i) { if (nums[i] == n1) { ++cnt1; } else if (nums[i] == n2) { ++cnt2; } } if (cnt1 > numsSize / 3) { res[*returnSize] = n1; ++(*returnSize); } if (cnt2 > numsSize / 3) { res[*returnSize] = n2; ++(*returnSize); } return res; } void Test() { int a[] = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4}; int returnSize = 0; int *res = majorityElement(a, sizeof(a) / sizeof(int), &returnSize); int i; for (i = 0; i < returnSize; ++i) { printf("%d ", res[i]); } printf("\n"); free(res); }
C
#include<stdio.h> #include<stdlib.h> #include"matrixOp.h" #include"ArrayOp.h" int checkDiagonalmatrix(int *mt, int size); //checks is matrix is diagonal int *createEffArr(int *mt, int n); //creates array parsed from matrix void printMatrixArray(int *mt,int n); //prints the optimized array in matrix form int setVal(int *mt, int i, int j, int val); //set value in matrix int getVal(int *mt, int i, int j); //gives the value int main(){ int matrix[4][4] = {{1,0,0,0},{0,6,0,0},{0,0,2,0},{0,0,0,7}}; int i,j,val; int size = 4; printf("\nOriginal Matrix: (less efficient one!)\n"); printMatrix((int *)matrix,size); int check = checkDiagonalmatrix((int*)matrix,size); if(check == 1){ printf("Its not a diagonal matrix\n"); return 1; } int *p = createEffArr((int *)matrix, size); if(p == NULL){ printf("Error in creating array\n"); return 1; } printf("\nAfter creating efficient array:\n"); printArray(p,size); int choice = 1,f; while(choice){ printf("\nEnter:\n0 => exit;\n1 => set value;\n2 => get value\n"); scanf("%d",&choice); // printf("%d", choice); switch (choice) { case 0: break; case 1: printf("\nEnter position in the matrix i,j and the value you want to insert:\n"); scanf("%d%d%d",&i,&j,&val); if(i < size && j<size) { f = setVal(p,i,j,val); if(f == 1){ printf("Cannot insert the value\nIs not a diagonal element.\n"); break; } printf("The altered matrix is:\n"); //printArray(p,size); printMatrixArray(p,size); } else { printf("Cannot access out-of-bound indexes!\n"); } break; case 2: printf("\nEnter position in the matrix i,j for the value you want:\n"); scanf("%d%d",&i,&j); if(i < size && j<size) { val = getVal(p,i,j); printf("The value at matrix[%d][%d] is: %d\n",i,j,val); } else { printf("Cannot access out-of-bound indexes!\n"); } break; default: break; } } return 0; } int checkDiagonalmatrix(int *mt, int size){ int flag = 0; for(int i =0; i< size; i++){ for (int j = 0; j < size; j++) { if(*((mt+i*size) + j) != 0 && j != i ){ flag = 1; return flag; } } } return flag; } int *createEffArr(int *mt, int n){ int *p = (int*)malloc(sizeof(int)*n); if(p == NULL){ printf("Dynamic Array memory cannot be allocated\n"); return NULL; } for(int i = 0, j = 0; i<n,j<n; i++,j++){ p[i] = *((mt+i*n) + j); } return p; } int setVal(int *mt, int i, int j, int val){ if( i == j){ mt[i] = val; return 0; } return 1; } void printMatrixArray(int* mt, int n){ int i,j; printf("\n[\n"); for(i =0; i< n; i++){ printf(" [ "); for (j = 0; j < n-1; j++) { if(i != j){ // printf("Inside i not equal j\n"); printf("0, "); } else{ // printf("Inside i equal j\n"); printf("%d, ", mt[i]); } } if(i != j){ printf("0 "); } else{ printf("%d ", mt[i]); } printf("]\n"); } printf("]\n"); } int getVal(int *mt, int i, int j){ if(i == j){ return mt[i]; } return 0; }
C
#include "tower.h" /*unsigned char tower2[] = {0x00, 0x30, 0x4E, 0x42, 0x22, 0x22, 0x3C, 0x00}; unsigned char tower3[] = {0x00, 0x3C, 0x24, 0x42, 0x42, 0x42, 0x3C, 0x00}; unsigned char tower1[] = {0x00, 0x58, 0x18, 0x66, 0x66, 0x18, 0x1A, 0x00};*/ unsigned char mortar_bmp[] = {0x00, 0x30, 0x5E, 0x6A, 0x32, 0x22, 0x3C, 0x00}; unsigned char lazer_bmp[] = {0x00, 0x18, 0x18, 0x18, 0x24, 0x18, 0x00, 0x00}; unsigned char mine_bmp[] = {0x00, 0x00, 0x18, 0x34, 0x2C, 0x18, 0x00, 0x00}; unsigned char cannon_bmp[] = {0x00, 0x18, 0x18, 0x18, 0x18, 0x24, 0x42, 0x00}; //void ll_template() //{ //tower *tmp = towers; //if(tmp == NULL)return; //if(tmp->next == NULL){ //action(); //return; //} //do{ //action(); //tmp = tmp->next; //}while(tmp != NULL); //return; //} int getNbTowerSlots(char *grid)//useless - returns the maximum number of towers { int i = 0, nbTowers = 0;; for(i = 0; i < GRID_LENGTH * GRID_WIDTH; i++) { if(grid[i] == 0) nbTowers++; } return nbTowers; } tower* addTower(int gridX, int gridY, int id, tower* towers) //adds a tower to the linked list { char mortar[] = {"Mortar"}; char lazer[] = {"Lazer"}; char mine[] = {"Mine"}; char cannon[] = {"Cannon"}; tower *new = malloc(sizeof(tower)); tower *tmp = towers; tower *tmp_prev; new->tick = 0; new->gridX = gridX; new->gridY = gridY; new->range = 20; new->id = id; new->level = 1; new->next = NULL; new->prev = NULL; new->fireRate = 5; //5: tire tout le temps, 4: extremement vite, 3: vite, 2: moyen, 1: lent, 0: tres lent new->target = NULL; /********************************LOADING TOWERS CARACTERISTICS**********************************/ if(new->id == 1)//mortar { new->name = malloc(sizeof(char)*7); memcpy(new->name, mortar, sizeof(char)*7); new->damage = 5; new->bmp = mortar_bmp; } if(new->id == 2)//lazer { new->name = malloc(sizeof(char)*6); memcpy(new->name, lazer, sizeof(char)*6); new->bmp = lazer_bmp; new->damage = 20; } if(new->id == 3)//mine { new->name = malloc(sizeof(char)*5); memcpy(new->name, mine, sizeof(char)*5); new->bmp = mine_bmp; new->damage = 30; } if(new->id == 4)//cannon { new->name = malloc(sizeof(char)*7); memcpy(new->name, cannon, sizeof(char)*7); new->bmp = cannon_bmp; new->damage = 60; } if(tmp == NULL) { new->prev = NULL; return new; } if(tmp->next == NULL) { new->prev = towers; } else { do{ tmp = tmp->next; }while(tmp->next != NULL); } if(tmp->next == NULL)//mieux vaut plus de vérifications que pas du tout ^^... { new->prev = tmp; } tmp->next = new; return towers; } tower *removeTower(tower *t, tower *towers) //removes (and frees) one tower from the linked list { tower *temp = NULL; if(t->prev == NULL && t->next == NULL)//if there is only 1 tower { free(t); return NULL; } if(t->prev == NULL)//if it is the first of the list { temp = t->next; temp->prev = NULL; free(t); return temp; } if(t->next == NULL)//if it is the last of the list { temp = t->prev; temp->next = NULL; free(t); return towers; } //sinon temp = t->prev; temp->next = t->next; t->next->prev = temp; free(t); return towers; } void cleanTargets(tower *towers, mob *mobs) //makes sure that the towers won't shoot a mob that has already been set free - it avoids system errors { tower *tmp = towers; if(tmp == NULL)return; if(tmp->next == NULL){ if(!mob_comp(tmp->target, mobs)) //if the target does no more exist in the linked list of mobs { tmp->target == NULL; } return; } do{ if(!mob_comp(tmp->target, mobs)) //same here { tmp->target == NULL; } tmp = tmp->next; }while(tmp != NULL); return; } void freeTargets(tower *towers, mob *target, mob *mobs) //first verification: removes a mob from the targets. Is called when a mob dies. { tower *tmp = towers; if(tmp == NULL)return; if(tmp->next == NULL){ if(tmp->target == target) { tmp->target = NULL; tmp->target = search_ennemy(tmp, mobs); } return; } do{ if(tmp->target == target) { tmp->target = NULL; tmp->target = search_ennemy(tmp, mobs); } tmp = tmp->next; }while(tmp != NULL); return; } void showTowers(camera cam, tower *towers) //draws the towers in the vram { tower *tmp = towers; if(tmp == NULL)return; do{ ML_bmp_8_or_cl(tmp->bmp, tmp->gridX*9 - cam.x, tmp->gridY*9 - cam.y); tmp = tmp->next; }while(tmp != NULL); return; } void towers_action(tower *towers, mob *m, camera *cam) //it is the action that will do a tower in every iteration of the main loo { tower *tmp = towers; //cleanTargets(towers, m); //protect from buffer overflows //POUR DES RAISONS DE VITESSE, JE DOIS RECODER CETTE FONCTION if(tmp == NULL) //linked lists manipulation { return; } if(tmp->next == NULL) { if(tmp->target == NULL) { tmp->target = search_ennemy(tmp, m); } if((!(tmp->tick % (7-tmp->fireRate))) && tmp->target != NULL){ //if the tower can shoot. buggy line, i will need to redo it. tmp->target = shoot(tmp, tmp->target, cam); //shooting the target } shoot(tmp, m, cam); //shooting the target tmp->tick++; return; } do{ if(tmp->target == NULL) { tmp->target = search_ennemy(tmp, m); } if((!(tmp->tick % (7-tmp->fireRate))) && tmp->target != NULL){ //if the tower can shoot. buggy line, i will need to redo it. tmp->target = shoot(tmp, tmp->target, cam); //shooting the target } shoot(tmp, m, cam); //shooting the target tmp->tick++; tmp = tmp->next; }while(tmp != NULL); } mob *search_ennemy(tower *t, mob *mobs) //if the target is NULL, the tower will search the closest target possible. { //POUR DES RAISONS DE VITESSE, JE DOIS RECODER CETTE FONCTION ! mob *tmp = mobs; if(mobs == NULL)return NULL; if(tmp->next == NULL && v_abs((tmp->realX - t->gridX*9)*(tmp->realX - t->gridX*9) + (tmp->realY - t->gridY*9)*(tmp->realY - t->gridY*9)) < pow(t->range + 9, 2)|| (t->gridX*9 - tmp->realX)*(t->gridX*9 - tmp->realX) + (t->gridY*9 - tmp->realY)*(t->gridY*9 - tmp->realY) < pow(t->range + 9, 2)) return tmp; if(tmp->next == NULL)return NULL; do{ if(v_abs( (tmp->realX - t->gridX*9)*(tmp->realX - t->gridX*9) + (tmp->realY - t->gridY*9)*(tmp->realY - t->gridY*9)) < (t->range + 9)*(t->range + 9)|| (t->gridX*9 - tmp->realX)*(t->gridX*9 - tmp->realX) + (t->gridY*9 - tmp->realY)*(t->gridY*9 - tmp->realY) < (t->range + 9)*(t->range + 9)) return tmp; tmp = tmp->next; }while(tmp != NULL); return NULL; } mob *shoot(tower *towers, mob *m, camera *cam) //shoots m with towers { if(m == NULL) return NULL; if(v_abs( (m->realX - towers->gridX*9)*(m->realX - towers->gridX*9) + (m->realY - towers->gridY*9)*(m->realY - towers->gridY*9)) < pow((towers->range + 9), 2)|| ((towers->gridX*9 - m->realX)*(towers->gridX*9 - m->realX) + (towers->gridY*9 - m->realY)*(towers->gridY*9 - m->realY) < pow(towers->range + 9, 2))) { ML_circle(m->realX - cam->x, m->realY - cam->y, 3, BLACK); ML_line(towers->gridX*9 + 4 - cam->x, (towers->gridY) * 9 + 4 - cam->y, m->realX - cam->x, m->realY - cam->y,BLACK); m->life -=towers->damage; return m; } return NULL; } tower *findTowerXY(int x, int y, tower *towers) //returns the tower that is located in (x, y), and NULL if there is no tower { tower *tmp = towers; if(tmp == NULL) { return NULL; } if(tmp->next == NULL) { if(tmp->gridX == x && tmp->gridY == y) return tmp; else return NULL; } do{ if(tmp->gridX == x && tmp->gridY == y) return tmp; tmp = tmp->next; }while(tmp != NULL); }
C
#include <stdio.h> #include <limits.h> #include <string.h> int main() { int number_array[8] = {48, 59, 2, -8, 55, 56, 78, 12}; for (int i = 2; i < 8; i++ ){ if (number_array[i-1] > number_array[i]){ number_array[i] = number_array[i] + number_array[i - 1]; number_array[i - 1] = number_array[i] - number_array[i - 1]; number_array[i] = number_array[i] - number_array[i - 1]; } if (number_array[i - 2] > number_array[i - 1]){ number_array[i - 1] = number_array[i - 1] + number_array[i - 2]; number_array[i - 2] = number_array[i - 1] - number_array[i - 2]; number_array[i - 1] = number_array[i - 1] - number_array[i - 2]; } } printf("The two biggest number are: %d and %d.", number_array[6], number_array[7]); //TODO: // Write a C program to find the two largest element in an array using only 1 for loop // From <limits.h> use INT_MIN: this is the least integer return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* pile.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: yhebbat <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/16 16:03:47 by yhebbat #+# #+# */ /* Updated: 2021/07/17 18:37:29 by yhebbat ### ########.fr */ /* */ /* ************************************************************************** */ #include "prj.h" void ft_depiler(t_list *head) { t_stack *to_delete; t_stack *a; if (head != NULL && head->header != NULL) { to_delete = head->header; if (!to_delete->suivant) { free(to_delete); head->header = NULL; head->footer = NULL; to_delete = NULL; } else { a = to_delete->suivant; head->header = a; a->preced = NULL; free(to_delete); to_delete = NULL; } } } void ft_remplir(t_list *head, int val, int index) { t_stack *a; t_stack *to_add; to_add = malloc(sizeof(t_stack)); if (!to_add) ft_exit(); if (head->header == NULL) { to_add->index = index; to_add->value = val; to_add->suivant = NULL; to_add->preced = NULL; head->footer = to_add; head->header = to_add; } else { a = head->header; to_add->index = index; to_add->value = val; to_add->suivant = a; to_add->preced = NULL; a->preced = to_add; head->header = to_add; } }
C
#include "timer.h" static struct timeval _current_time; static struct timeval _temp_time; void timer_set(struct timeval* timeout, int msec) { _temp_time.tv_sec = msec / 1000; _temp_time.tv_usec = (msec % 1000) * 1000; gettimeofday(&_current_time, 0); timeradd(&_current_time, &_temp_time, timeout); } int timer_timeout(struct timeval* timeout) { gettimeofday(&_current_time, 0); return timercmp(&_current_time, timeout, >); }
C
#include "holberton.h" /** * append_text_to_file - appends text to a file * @filename: name of the file * @text_content: content of the text * Return: 1 on success, -1 on failure */ int append_text_to_file(const char *filename, char *text_content) { int file_d, len; ssize_t size_write; if (filename == NULL) return (-1); file_d = open(filename, O_APPEND | O_WRONLY); if (file_d == -1) return (-1); if (text_content == NULL) { if (file_d == -1) return (-1); else return (1); } for (len = 0; text_content[len] != '\0'; len++) ; size_write = write(file_d, text_content, len); if (size_write == -1) return (-1); close(file_d); return (1); }
C
/* * Copyright (c) 2017, NVIDIA CORPORATION. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* * Four routines to be able to lock access to a file in the Linux * approved manner. This seems to be the only method that works * over NFS: * * __pg_make_lock_file( char* dir ) * Creates a uniquely-named file in the given directory. * To work, this must be created on the same filesystem * as the file which we are attempting to lock. * If there are multiple processes running each competing for the * same lock, each gets a unique file here. * return -1 if it can't get a unique file in 50 tries * __pg_get_lock( char* lname ) * The argument is the name of the lock. * Each process tries to create a hard link with this name * to its own uniquely-named file from __pg_make_lock_file(). * The one that succeeds is the new lock owner. The others * fail and try again. There is a fail-over to handle the case * where the process with the lock dies, which is inherently unsafe, * but we haven't come up with a better solution. * __pg_release_lock( char* lname ) * The argument is the same name for the lock. * The lock is released by deleting (calling unlink) for the * hard link we had just created. * __pg_delete_lock_file() * Clean up by deleting the uniquely named file we had created earlier. */ #ifndef _WIN32 #include <unistd.h> #else #include <Winsock2.h> #include <process.h> #endif #include <fcntl.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <string.h> #include "lockfile.h" /* * The name of the uniquely-named file and directory in which it is created */ static char *uname = NULL; static char *udir = NULL; /* * Some counts for debugging */ static long uwaiting; #ifdef _WIN32 #define pid_t int #endif int __pg_make_lock_file(char *dir) { pid_t pid; char hostname[999]; int r; FILE *F; udir = (char *)malloc(strlen(dir) + 1); strcpy(udir, dir); pid = getpid(); r = gethostname(hostname, 998); if (r != 0) { fprintf(stderr, "gethostname fails\n"); exit(1); } uname = (char *)malloc(strlen(hostname) + strlen(udir) + 25); r = 0; do { ++r; /* create a unique file */ sprintf(uname, "%s/lock.%s.%ld%d", udir, hostname, (long)pid, r); F = fopen(uname, "w"); } while (F == NULL && r < 51); if (F == NULL) { return -1; } fprintf(F, "%s\n", uname); fclose(F); uwaiting = 0; return 0; } /* __pg_make_lock_file */ void __pg_get_lock(char *lname) { int r; struct stat ss, ss1; int count; char *fullname; if (udir == NULL || uname == NULL) return; fullname = (char *)malloc(strlen(lname) + strlen(udir) + 2); /* +1 for / +1 for null terminator */ strcpy(fullname, udir); strcat(fullname, "/"); strcat(fullname, lname); memset(&ss1, 0, sizeof(ss1)); count = 0; do { r = link(uname, fullname); if (r != 0) { /* link had some problem, see if the number of links * to the new file is now two */ r = stat(uname, &ss); if (r == 0) { if (ss.st_nlink != 2) { if (ss.st_nlink != 1) { fprintf(stderr, "get_lock: %d links to %s\n", (int)ss.st_nlink, uname); exit(1); } /* see if we should forcefully TAKE the lock */ r = lstat(fullname, &ss); if (count == 0) { memcpy(&ss1, &ss, sizeof(ss)); count = 1; } else if (ss1.st_dev != ss.st_dev || ss1.st_ino != ss.st_ino || ss1.st_mode != ss.st_mode || ss1.st_uid != ss.st_uid || ss1.st_gid != ss.st_gid || ss1.st_size != ss.st_size || ss1.st_mtime != ss.st_mtime) { /* some else got there first */ memcpy(&ss1, &ss, sizeof(ss)); count = 1; } else { ++count; if (count > 20) { /* we've waited long enough. */ r = unlink(fullname); /* ignore errors on the unlink */ } } sleep(1); r = 1; } } if (r) ++uwaiting; } } while (r != 0); free(fullname); } /* __pg_get_lock */ void __pg_release_lock(char *lname) { int r; char *fullname; if (udir == NULL || uname == NULL) return; fullname = (char *)malloc(strlen(lname) + strlen(udir) + 2); strcpy(fullname, udir); strcat(fullname, "/"); strcat(fullname, lname); /* release the lock by deleting the link */ r = unlink(fullname); if (r != 0) { fprintf(stderr, "release_lock: unlink %s fails\n", lname); exit(1); } free(fullname); } /* __pg_release_lock */ void __pg_delete_lock_file() { int r; /* delete the unique file */ r = unlink(uname); if (r != 0) { fprintf(stderr, "delete_lock_file: unlink %s fails\n", uname); exit(1); } free(uname); free(udir); uname = NULL; udir = NULL; } /* __pg_delete_lock_file */
C
#include "common.h" #include "parsenum.h" #define parse_signed(type, unsigned_type, value_type_min, value_type_max) \ ParseNumError strnto## type(const char *nptr, const char * const end, char **endptr, type *ret) { \ char c; \ char ***spp; \ int negative; \ int any, cutlim; \ ParseNumError err; \ unsigned_type cutoff, acc; \ \ acc = any = 0; \ negative = FALSE; \ err = PARSE_NUM_NO_ERR; \ if (NULL == endptr) { \ char **sp; \ \ sp = (char **) &nptr; \ spp = &sp; \ } else { \ spp = &endptr; \ *endptr = (char *) nptr; \ } \ if (**spp < end) { \ if ('-' == ***spp) { \ ++**spp; \ negative = TRUE; \ } else { \ negative = FALSE; \ if ('+' == ***spp) { \ ++**spp; \ } \ } \ cutoff = negative ? (unsigned_type) - (value_type_min + value_type_max) + value_type_max : value_type_max; \ cutlim = cutoff % 10; \ cutoff /= 10; \ while (**spp < end) { \ if (***spp >= '0' && ***spp <= '9') { \ c = ***spp - '0'; \ } else { \ err = PARSE_NUM_ERR_NON_DIGIT_FOUND; \ break; \ } \ if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) { \ any = -1; \ } else { \ any = 1; \ acc *= 10; \ acc += c; \ } \ ++**spp; \ } \ } \ if (any < 0) { \ if (negative) { \ *ret = value_type_min; \ return PARSE_NUM_ERR_TOO_SMALL; \ } else { \ *ret = value_type_max; \ return PARSE_NUM_ERR_TOO_LARGE; \ } \ } else if (!any && PARSE_NUM_NO_ERR == err) { \ err = PARSE_NUM_ERR_NO_DIGIT_FOUND; \ } else if (negative) { \ *ret = -acc; \ } else { \ *ret = acc; \ } \ \ return err; \ } // parse_signed(int8_t, uint8_t, INT8_MIN, INT8_MAX); // parse_signed(int16_t, uint16_t, INT16_MIN, INT16_MAX); // parse_signed(int32_t, uint32_t, INT32_MIN, INT32_MAX); // parse_signed(int64_t, uint64_t, INT64_MIN, INT64_MAX); #undef parse_signed #define parse_unsigned(type, value_type_max) \ ParseNumError strnto## type(const char *nptr, const char * const end, char **endptr, type *ret) { \ char c; \ char ***spp; \ int negative; \ int any, cutlim; \ type cutoff, acc; \ ParseNumError err; \ \ acc = any = 0; \ negative = FALSE; \ err = PARSE_NUM_NO_ERR; \ if (NULL == endptr) { \ char **sp; \ \ sp = (char **) &nptr; \ spp = &sp; \ } else { \ spp = &endptr; \ *endptr = (char *) nptr; \ } \ if (**spp < end) { \ if ('-' == ***spp) { \ ++**spp; \ negative = TRUE; \ } else { \ negative = FALSE; \ if ('+' == ***spp) { \ ++**spp; \ } \ } \ cutoff = value_type_max / 10; \ cutlim = value_type_max % 10; \ while (**spp < end) { \ if (***spp >= '0' && ***spp <= '9') { \ c = ***spp - '0'; \ } else { \ err = PARSE_NUM_ERR_NON_DIGIT_FOUND; \ break; \ } \ if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) { \ any = -1; \ } else { \ any = 1; \ acc *= 10; \ acc += c; \ } \ ++**spp; \ } \ } \ if (any < 0) { \ *ret = value_type_max; \ return PARSE_NUM_ERR_TOO_LARGE; \ } else if (!any && PARSE_NUM_NO_ERR == err) { \ err = PARSE_NUM_ERR_NO_DIGIT_FOUND; \ } else if (negative) { \ *ret = -acc; \ } else { \ *ret = acc; \ } \ \ return err; \ } // parse_unsigned(uint8_t, UINT8_MAX); // parse_unsigned(uint16_t, UINT16_MAX); parse_unsigned(uint32_t, UINT32_MAX); // parse_unsigned(uint64_t, UINT64_MAX); #undef parse_unsigned
C
#include "BST.h" #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> BST* bst_create(CmpFunc cmp_func) { BST* tree = (BSTNode*)malloc(sizeof(BSTNode)); if (tree == NULL) return NULL; tree->cmp_func = cmp_func; tree->root = NULL; return tree; } static BSTNode* bst_add_in_tree(Pointer data) { BSTNode* leaf = (BSTNode*)malloc(sizeof(BSTNode)); if (leaf == NULL) return NULL; leaf->data = data; leaf->left = NULL; leaf->right = NULL; return leaf; } static BSTNode* destructor(BSTNode* node) { if (node == NULL) return NULL; if (node->left != NULL) destructor(node->left); if (node->right != NULL) destructor(node->right); free(node); return NULL; } void bst_clear(BST* tree) { if (tree == NULL) return; tree->root = destructor(tree->root); } void bst_destroy(BST* tree) { if (tree == NULL) return; bst_clear(tree); free(tree); } static int counter(BSTNode* node) { if (node == NULL) return 0; int count = 1; count += counter(node->left) + counter(node->right); return count; } size_t bst_size(BST* tree) { if (tree == NULL) return 0; if (tree->root == NULL) return 0; return counter(tree->root); } static BSTNode* find_node_by_data(BST* tree, Pointer data) { int is_left = 0; int cmpRes = 0; BSTNode* temp = tree->root; BSTNode* prev = tree->root; while (temp != NULL) { cmpRes = tree->cmp_func(data, temp->data); if (tree->cmp_func(prev->data, data) == NULL) break; prev = temp; if (cmpRes < 0) { is_left = 1; temp = temp->left; } else if (cmpRes > 0) { is_left = 0; temp = temp->right; } } return prev; } Pointer bst_find(BST* tree, Pointer data) { BSTNode* prev = find_node_by_data(tree, data); if (prev == NULL) return NULL; if (tree->cmp_func(prev->data, data) == NULL) return prev->data; return NULL; } Pointer bst_insert(BST* tree, Pointer data) { if (tree->root == NULL) { tree->root = bst_add_in_tree(data); return NULL; } else { int is_left = 0; int cmpRes = 0; BSTNode* temp = tree->root; BSTNode* prev = NULL; while (temp != NULL) { cmpRes = tree->cmp_func(data, temp->data); prev = temp; if (cmpRes < 0) { is_left = 1; temp = temp->left; } else if (cmpRes > 0) { is_left = 0; temp = temp->right; } else if (cmpRes == 0) { Pointer old_data = prev->data; prev->data = data; return old_data; } } if (is_left) { prev->left = bst_add_in_tree(data); return prev->left->data; } else { prev->right = bst_add_in_tree(data); return prev->right->data; } } return NULL;//bad return } Pointer bst_delete(BST* tree, Pointer data) { int is_left = 0; int cmpRes = 0; BSTNode* temp = tree->root; BSTNode* prev = tree->root; BSTNode* prev2 = prev; int prev_pos = 0;//0 - left, 1 - right while (temp != NULL) { cmpRes = tree->cmp_func(data, temp->data); if (tree->cmp_func(prev->data, data) == NULL) break; prev2 = prev; prev = temp; if (cmpRes < 0) { is_left = 1; temp = temp->left; } else if (cmpRes > 0) { is_left = 0; temp = temp->right; } } if (prev == NULL) return NULL; if (tree->cmp_func(prev->data, data) != NULL) return NULL; if (prev2->left == prev) prev_pos = 0; if (prev2->right == prev) prev_pos = 1; BSTNode* to_delete = prev; Pointer to_return = prev->data; if (prev->left == NULL && prev->right == NULL) { if (tree->cmp_func(prev->data, tree->root->data) == NULL) { tree->root = NULL; free(to_delete); return to_return; } if (prev_pos) prev2->right = NULL; else prev2->left = NULL; } else if (prev->right == NULL) { //Right branch is empty if (prev_pos) prev2->right = prev->left; else prev2->left = prev->left; } else if (prev->left == NULL) { //Right branch is empty if (prev_pos) prev2->right = prev->right; else prev2->left = prev->right; } else { // Two branches aren't empty BSTNode* next_prev = prev->right->right; temp = prev->right; BSTNode* temp_prev = temp; while (temp->left != NULL) { temp_prev = temp; temp = temp->left; } if (temp->right != NULL) temp_prev->left = temp->right; if (prev->right == temp) temp->right = NULL; else temp->right = prev->right; temp->left = prev->left; if (prev2 == tree->root && prev == tree->root) { BSTNode* temp2=tree->root; while (temp2!=NULL) { cmpRes = tree->cmp_func(temp->data, temp2->data); if (tree->cmp_func(prev->data, temp->data) == NULL) break; prev2 = prev; prev = temp2; if (cmpRes < 0) { is_left = 1; temp2 = temp2->left; } else if (cmpRes > 0) { is_left = 0; temp2 = temp2->right; } } if (!is_left) prev2->right = NULL; else prev2->left = NULL; tree->root->data = temp->data; free(temp); return to_return; } if (prev_pos) prev2->right = temp; else prev2->left = temp; } free(to_delete); return to_return; } static void summon_beast(BSTNode* node, void(*foreach_func)(Pointer data, Pointer extra_data), Pointer extra_data) { if (node == NULL) return; if (node->left != NULL) summon_beast(node->left, foreach_func, extra_data); if (node->right != NULL) summon_beast(node->right, foreach_func, extra_data); foreach_func(node->data, extra_data); } void bst_foreach(BST* tree, void(*foreach_func)(Pointer data, Pointer extra_data), Pointer extra_data) { if (tree == NULL) return; summon_beast(tree->root, foreach_func, extra_data); } // //static void deleter(BSTNode* preroot, BSTNode* root) //{ // if ((root->left == NULL) && (root->right == NULL)) { // if (preroot->left == root) // preroot->left = NULL; // if (preroot->right == root) // preroot->right = NULL; // free(root); // root = NULL; // return(0); // } // if ((root->left == NULL)) { // if (preroot->left == root) // preroot->left = root->right; // if (preroot->right == root) // preroot->right = root->right; // free(root); // root = NULL; // return(0); // } // if ((root->right == NULL)) { // if (preroot->left == root) // preroot->left = root->left; // if (preroot->right == root) // preroot->right = root->left; // free(root); // root = NULL; // return(0); // } // // BSTNode* pretemp = root; // BSTNode* temp = root->right; // while (1) { // if (temp->left == NULL) { // root->data = temp->data; // deleter(pretemp, temp); // break; // } // pretemp = temp; // temp = temp->left; // } //} // //Pointer bst_delete(BST* tree, Pointer data) //{ // if (tree->root == NULL) { // return(0); // } // BSTNode* temp; // BSTNode* pretemp = memalloc(); // BSTNode* memory_flag = pretemp; // // temp = tree->root; // pretemp->right = temp; // pretemp->left = temp; // while (1) { // if (tree->cmp_func(temp->data, data) == 1) { // if (temp->left == NULL) { // free(memory_flag); // return(NULL); // } // pretemp = temp; // temp = temp->left; // } // if (tree->cmp_func(temp->data, data) == -1) { // if (temp->right == NULL) { // free(memory_flag); // return(NULL); // } // pretemp = temp; // temp = temp->right; // } // if (tree->cmp_func(temp->data, data) == 0) // break; // } // // Pointer buffer = temp->data; // deleter(pretemp, temp); // tree->root = memory_flag->right; // free(memory_flag); // return(buffer); //}
C
#include <stdio.h> #include <unistd.h> #include <semaphore.h> #include <string.h> #include <pthread.h> char buf[64]; sem_t sem; void *fun(void *args) { while(1) { sem_wait(&sem); printf("\nbuf size:%ld character\n",strlen(buf)); } } int main() { int tid; pthread_t pth; if(sem_init(&sem,0,0) < 0) { perror("sem init failed"); return -1; } if((tid=pthread_create(&pth,NULL,fun,NULL)) < 0) { perror("pthread create failed"); return -1; } do{ printf("input:"); fgets(buf,64,stdin); sem_post(&sem); }while(strncmp(buf,"quit",4) != 0); return 0; }
C
//-*-c-*- //#include "linalg.h" //extern "C" //{ __kernel void float3add(__global float3 *a, __global float3 *b, __global float3 *dest) { int idx = get_global_id(0); dest[idx] = a[idx] + b[idx]; } __kernel void float3addequal(__global float3 *a, __global float3 *b) { int idx = get_global_id(0); a[idx] += b[idx]; } __kernel void float3sub(__global float3 *a, __global float3 *b, __global float3 *dest) { int idx = get_global_id(0); dest[idx] = a[idx] - b[idx]; } __kernel void float3subequal(__global float3 *a, __global float3 *b) { int idx = get_global_id(0); a[idx] -= b[idx]; } __kernel void float3addfloat(__global float3 *a, float c, __global float3 *dest) { int idx = get_global_id(0); dest[idx] = a[idx] + c; } __kernel void float3addfloatequal(__global float3 *a, float c) { int idx = get_global_id(0); a[idx] += c; } __kernel void floataddfloat3(__global float3 *a, float c, __global float3 *dest) { int idx = get_global_id(0); dest[idx] = c + a[idx]; } __kernel void float3subfloat(__global float3 *a, float c, __global float3 *dest) { int idx = get_global_id(0); dest[idx] = a[idx] - c; } __kernel void float3subfloatequal(__global float3 *a, float c) { int idx = get_global_id(0); a[idx] -= c; } __kernel void floatsubfloat3(__global float3 *a, float c, __global float3 *dest) { int idx = get_global_id(0); dest[idx] = c - a[idx]; } __kernel void float3mulfloat(__global float3 *a, float c, __global float3 *dest) { int idx = get_global_id(0); dest[idx] = a[idx]*c; } __kernel void float3mulfloatequal(__global float3 *a, float c) { int idx = get_global_id(0); a[idx] *= c; } __kernel void floatmulfloat3(__global float3 *a, float c, __global float3 *dest) { int idx = get_global_id(0); dest[idx] = c*a[idx]; } __kernel void float3divfloat(__global float3 *a, float c, __global float3 *dest) { int idx = get_global_id(0); dest[idx] = a[idx]/c; } __kernel void float3divfloatequal(__global float3 *a, float c) { int idx = get_global_id(0); a[idx] /= c; } __kernel void floatdivfloat3(__global float3 *a, float c, __global float3 *dest) { int idx = get_global_id(0); dest[idx] = c/a[idx]; } __kernel void minusfloat3(__global float3 *a, __global float3 *dest) { int idx = get_global_id(0); dest[idx] = -a[idx]; } //} // extern "c"
C
/* ** EPITECH PROJECT, 2020 ** NWP_myteams_2019 ** File description: ** sublistteam_cmd */ #include <stdio.h> #include "my_team.h" #include "commands.h" void send_sub_users(int socket, team_t *team) { linked_list_t *cursor = team->sub_users; user_t *user; char user_id[37]; while (cursor) { user = cursor->obj; uuid_unparse(user->uuid, user_id); dprintf(socket, "USER %s\n\"%s\"\n%d\n", user_id, user->username, user->is_logged); cursor = cursor->next; } dprintf(socket, "\r\n"); } int sublistteam_cmd(tcp_client_t *client, server_t *server, char **message) { team_t *team; user_t *user; if (message_args_nbr(message) != 2) { return (ERR_CMD); } user = get_user_from_socket(client->sock, server->users); if (user == NULL) { return (ERR_LOGIN); } team = get_team_from_id(message[1], server->teams); if (!is_in_team(user, team)) { return (ERR_NOTSUB); } if (team == NULL) { send_response_with_str(ERR_UKN_TEAM, client->sock, message[1]); return (NO_RESPONSE); } send_sub_users(client->sock, team); return (NO_RESPONSE); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <assert.h> #include "symbols.h" #ifndef _IR_BUFFER_H_ #define _IR_BUFFER_H_ /* args_count=2: * GOTO x * RETURN x * ARG x * PARAM x * READ x * WRITE x * args_count=3: * LABEL x : * FUNCTION f : * x := y * x := &y * x := *y * *x := y * DEC x [size] * args_count=4: * x := CALL f * args_count=5: * x := y + z * x := y - z * x := y * z * x := y / z * args_count=6: * IF x [relop] y GOTO z */ //双向循环链表,存储代码在内存中的表示 typedef struct code_node { struct code_node* prev; //前一个 struct code_node* next; //后一个 int args_count; //有多少个词。具体见上面注释内的分类。 char args[6][32]; //每个词都是什么 }code_node; #endif //生成新的label,名称放在提供好的name里面。 void new_label(char* name); //生成新的临时变量,名称放在提供好的name里面。 void new_temp(char* name); //添加一条代码,指明这条代码的词数,然后传入各个词语,各个词语都是char*,即传入多个字符串 void add_code(int args_count,...); //将内存中的代码打印到文件中,传入新文件路径,并顺便清理内存中的代码存储 void print_code(char* name); //关闭优化 void close_opt();
C
#ifndef PROJECT_H #define PROJECT_H #endif // PROJECT_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <conio.h> #include "project.h" /**function to display inter-active menu **/ void Load_menu() { int choice; do { printf("\n\n\t\t\t*** Main Menu ***\n\n"); printf("\t\t\t|1| ADD \n"); printf("\t\t\t|2| SORT \n"); printf("\t\t\t|3| MODIFY \n"); printf("\t\t\t|4| DELETE \n"); printf("\t\t\t|5| Print \n"); printf("\t\t\t|6| SEARCH \n"); printf("\t\t\t|7| SAVE \n"); printf("\t\t\t|8| QUIT \n\n\n"); scanf("%d",&choice); switch(choice) { case 1 : ADD(); break; case 6 : SEARCH(); break; case 4 : DELETE(); break; case 5 : PRINT(); break; case 3 : MODIFY(); break; case 2 : SORT(); break; case 7 : SAVE(); break; case 8: Exit(); default: printf("\n \tInvalid choice!\n"); break; } system("cls"); } while (1); }
C
/** * dictionary.c * * Computer Science 50 * Problem Set 5 * * Implements a dictionary's functionality. */ #include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include <memory.h> #include <ctype.h> #include "dictionary.h" /** * trie to load the dictionary in. */ typedef struct _dictionary { bool is_word; struct _dictionary *nodes[27]; } TrieNode; TrieNode *root; /** * to hold the size of the Trie/Dictionary */ unsigned int trieSize = 0; /** * returns the order of the letter in alphabetical order. * returns 26 for apostrophe. * @param letter * @return alphabetical order (0 to 26) */ unsigned int getIndex(char letter) { return isalpha(letter) ? ((unsigned int) (tolower(letter) - 'a')) : APOSTROPHE; } /** * to build the word's path inside the trie. * @param node the root node of the Trie. * @param index the zero index to iterate over the word. * @param word word to be built its path inside the Trie. */ bool buildTrie(TrieNode *node, int index, char *const word) { int nodeIndex = getIndex(word[index]); // memory allocation for corresponding letter if it's NULL. if (node->nodes[nodeIndex] == NULL) node->nodes[nodeIndex] = malloc(sizeof(TrieNode)); node = node->nodes[nodeIndex]; // If it's the word's last letter, mark it as word. if (index == strlen(word) - 1) { node->is_word = true; return true; } return buildTrie(node, index + 1, word); } /** * follows the word's path in the Trie, if it exists in the Trie */ bool checkWord(TrieNode* const root, int index, const char* word) { TrieNode* node = root; int nodeIndex = getIndex(word[index]); // sanity check if (node->nodes[nodeIndex] == NULL || index > LENGTH) return false; if (index == strlen(word) - 1) return node->nodes[nodeIndex]->is_word; return checkWord(node->nodes[nodeIndex], index + 1, word); } /** * Returns true if word is in dictionary else false. */ bool check(const char* word) { return checkWord(root, 0, word); } /** * Loads dictionary into memory. Returns true if successful else false. */ bool load(const char* dictionary) { // hold every word from dictionary to save into the trie. char word[LENGTH + 1]; // open the dictionary text file. FILE *dict = fopen(dictionary, "r"); if (dict == NULL) { printf("Failed to open the dictionary file!\n"); return false; } // initialize the root node. root = malloc(sizeof(TrieNode)); // read words from the dictionary text file. while (fscanf(dict, "%s", word) != EOF) { trieSize++; // concatenate newline to the word strcat(word, "\0"); if (!buildTrie(root, 0, word)) return false; } return true; } /** * Returns number of words in dictionary if loaded else 0 if not yet loaded. */ unsigned int size(void) { return trieSize; } /** * Unloads dictionary from memory. * by freeing all children nodes, then freeing the current node. */ void unloadNodes(TrieNode *root) { // free every node from the current node. for (int i = 0; i <= APOSTROPHE; i++) if (root->nodes[i] != NULL) unloadNodes(root->nodes[i]); // free the current passed node. free(root); } /** * Unloads dictionary from memory. Returns true if successful else false. */ bool unload(void) { unloadNodes(root); return true; }
C
//=============================================== #include "GKeyboard.h" //=============================================== static GKeyboardO* m_GKeyboardO = 0; //=============================================== GKeyboardO* GKeyboard_New() { GKeyboardO* lObj = (GKeyboardO*)malloc(sizeof(GKeyboardO)); lObj->Delete = GKeyboard_Delete; lObj->Input = scanf; lObj->Line = fgets; lObj->Clear = fflush; return lObj; } //=============================================== void GKeyboard_Delete() { GKeyboardO* lObj = GKeyboard(); if(lObj != 0) { free(lObj); } m_GKeyboardO = 0; } //=============================================== GKeyboardO* GKeyboard() { if(m_GKeyboardO == 0) { m_GKeyboardO = GKeyboard_New(); } return m_GKeyboardO; } //===============================================
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* append_cmd.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: riblanc <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/04/23 19:27:42 by riblanc #+# #+# */ /* Updated: 2021/05/13 01:18:27 by riblanc ### ########.fr */ /* */ /* ************************************************************************** */ #include "line_edit.h" void append_multi_cmd_2(t_line *line, char *s[4]) { if (line->complete.pos != -1 && line->complete.str && *line->complete.str) { s[0] = ft_substr(s[3], 0, line->complete.pos - 1); s[1] = ft_substr(s[3], line->complete.pos - 1, ft_strlen(s[3]) - line->complete.pos + 1); append(&line->buf, s[0]); ft_memdel((void **)s); append(&line->buf, "\x1b[33m"); append(&line->buf, line->complete.str); append(&line->buf, "\x1b[0m"); append(&line->buf, s[1]); ft_memdel((void **)(s + 1)); } else { append(&line->buf, s[3]); ft_memdel((void **)(s + 3)); } } static void append_multi_cmd_core(t_line *line, int sel[2], char *s[4], int max) { int sens; sens = line->sel[0] > line->sel[1]; s[0] = ft_substr(s[3], 0, sel[0] - !sens); s[1] = ft_substr(s[3], sel[0] - !sens, sel[1] - sel[0] - 1); s[2] = ft_substr(s[3], sel[1] - 1 - !sens, max - sel[1] + 1 + !sens); append(&line->buf, s[0]); append(&line->buf, "\x1b[7m"); append(&line->buf, s[1]); append(&line->buf, "\x1b[0m"); append(&line->buf, s[2]); ft_memdel((void **)s); ft_memdel((void **)s + 1); ft_memdel((void **)s + 2); } void append_multi_cmd(t_line *line, int max) { int sel[2]; char *s[4]; sel[0] = line->sel[0]; sel[1] = line->sel[1]; if (sel[0] > sel[1] && (++sel[0] || 1)) ft_swap(&sel[0], &sel[1]); s[3] = convert_to_str(line->lst_input, 0); if (sel[0] != sel[1]) append_multi_cmd_core(line, sel, s, max); else append_multi_cmd_2(line, s); append(&line->buf, "\x1b[0K"); ft_memdel((void **)s + 3); } void append_single_cmd_2(t_line *line, int *max, int i[5]) { append(&line->buf, line->seq); if (++i[3] == line->complete.pos) { append(&line->buf, "\x1b[33m"); i[4] = -1; while (line->complete.str[++i[4]]) { line->seq[0] = line->complete.str[i[4]]; line->seq[1] = 0; append(&line->buf, line->seq); *max -= 1; } append(&line->buf, "\x1b[0m"); } } void append_single_cmd(t_line *line, t_data *lst, int offset, int max) { t_lst_in *tmp; int i[5]; int sens; *i = line->sel[0]; i[1] = line->sel[1]; sens = (*i > i[1]); if (*i > i[1] && (++i[0] || 1)) ft_swap(i, i + 1); tmp = lst->head; i[2] = -1; while (++i[2] < offset && tmp) tmp = tmp->next; i[3] = 0; while (--max >= 0 && tmp != NULL) { if (i[2] >= *i + sens && *i != i[1]) append(&line->buf, "\x1b[7m"); if (i[2]++ >= i[1] - !sens && *i != i[1]) append(&line->buf, "\x1b[0m"); line->seq[0] = tmp->c; line->seq[1] = 0; append_single_cmd_2(line, &max, i); tmp = tmp->next; } }
C
/* * minmax.c * Determine the minimum and maximum values of a group of pixels. * This demonstrates use of the glMinmax() call. */ #include <GL/glut.h> #include <stdlib.h> extern GLubyte* readImage(const char*, GLsizei*, GLsizei*); GLubyte *pixels; GLsizei width, height; void init(void) { glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glClearColor(0.0, 0.0, 0.0, 0.0); glMinmax(GL_MINMAX, GL_RGB, GL_FALSE); glEnable(GL_MINMAX); } void display(void) { GLubyte values[6]; glClear(GL_COLOR_BUFFER_BIT); glRasterPos2i(1, 1); glDrawPixels(width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels); glFlush(); glGetMinmax(GL_MINMAX, GL_TRUE, GL_RGB, GL_UNSIGNED_BYTE, values); printf(" Red : min = %d max = %d\n", values[0], values[3]); printf(" Green : min = %d max = %d\n", values[1], values[4]); printf(" Blue : min = %d max = %d\n", values[2], values[5]); } void reshape(int w, int h) { glViewport(0, 0, (GLsizei) w, (GLsizei) h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, w, 0, h, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); } void keyboard(unsigned char key, int x, int y) { switch (key) { case 27: exit(0); } } /* Main Loop * Open window with initial window size, title bar, * RGBA display mode, and handle input events. */ int main(int argc, char** argv) { pixels = readImage("Data/leeds.bin", &width, &height); glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(width, height); glutInitWindowPosition(100, 100); glutCreateWindow(argv[0]); init(); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard); glutDisplayFunc(display); glutMainLoop(); return 0; } 
C
#include<stdio.h> #include<conio.h> #include<math.h> #define pi 3.14 void main() { int a,c; clrscr(); printf("Enter The Value of Radius of The Circle : "); scanf("%d",&a); c=pi*a*a; printf("\n\nThe Area of Circle is : %d Units",c); getch(); }
C
#include <stdio.h> void drawLinesWithRowCol(int rows, int cols, char character); int main(void) { int rows, cols; char character; printf("Enter rows: "); scanf("%d", &rows); printf("Enter columns: "); scanf("%d", &cols); printf("Enter character: "); scanf(" %c", &character); drawLinesWithRowCol(rows, cols, character); return 0; } void drawLinesWithRowCol(int rows, int cols, char character) { int i, j; for (i = 1; i <= rows; i++) { for (j = 1; j <= cols; j++) { printf("%c", character); } printf("\n"); } }
C
//C program merge to merge two sorted arrays // It is assumed that user will enter arrays in ascending order #include <stdio.h> void merge(int [], int, int [], int, int []); int main() { int a[100], b[100], m, n, c, sorted[200]; printf("Input number of elements in first array\n"); scanf("%d", &m); printf("Input %d integers\n", m); for (c = 0; c < m; c++) { scanf("%d", &a[c]); } printf("Input number of elements in second array\n"); scanf("%d", &n); printf("Input %d integers\n", n); for (c = 0; c < n; c++) { scanf("%d", &b[c]); } merge(a, m, b, n, sorted); printf("Sorted array:\n"); for (c = 0; c < m + n; c++) { printf("%d\n", sorted[c]); } return 0; } void merge(int a[], int m, int b[], int n, int sorted[]) { int i, j, k; j = k = 0; for (i = 0; i < m + n;) { if (j < m && k < n) { if (a[j] < b[k]) { sorted[i] = a[j]; j++; } else { sorted[i] = b[k]; k++; } i++; } else if (j == m) { for (; i < m + n;) { sorted[i] = b[k]; k++; i++; } } else { for (; i < m + n;) { sorted[i] = a[j]; j++; i++; } } } }
C
//290207 //lista 3 //zadanie 1 #include <stdio.h> #include <stdlib.h> int main(void) { int no_ones=0, longest_ones=0, longest_zeros=0; int len1=0, len0=0; unsigned int n = 0; scanf("%ud", &n); int i=0; unsigned int m=n/2; for (i=0; i<32; i++){ if (n%2 != m%2){ if (n%2==0){ len0++; if (longest_zeros<len0){ longest_zeros=len0; } len0=0; } else { no_ones++; len1++; if (longest_ones<len1){ longest_ones=len1; } len1=0; } } else if (n%2==1){ no_ones++; len1++; } else len0++; n=m; m=m/2; } if (longest_zeros<len0){ longest_zeros=len0; } else if (longest_ones<len1){ longest_ones=len1; } printf("ilosc jedynek: %d\n", no_ones); printf("dlugosc najdluzszego ciagu zer: %d\n", longest_zeros); printf("dlugosc najdluzszego ciagu jedynek: %d\n", longest_ones); return 0; }
C
#include<poll.h> #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<sys/types.h> #include<sys/socket.h> #include<string.h> #include<errno.h> #include<netinet/in.h> #include<arpa/inet.h> #define _BACKLOG_ 5 #define _SIZE_ 64 static void usage (const char *proc) { printf("%s [ip][prot]\n",proc); } static int start(char *ip,int port) { int sock = socket(AF_INET,SOCK_STREAM,0); if(sock < 0) { perror("socket"); exit(1); } int opt = 1; if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt)) < 0) { perror("setsockopt"); exit(3); } struct sockaddr_in local; local.sin_family = AF_INET; local.sin_port = htons(port); local.sin_addr.s_addr = inet_addr(ip); if(bind(sock,(struct sockaddr*)&local,sizeof(local))<0) { perror("bind"); exit(2); } if(listen(sock,_BACKLOG_) < 0) { perror("listen"); exit(2); } return sock; } int main(int argc,char* argv[]) { if(argc != 3) { usage(argv[0]); return 1; } int port = atoi(argv[2]); char *ip = argv[1]; int listen_sock = start(ip,port); //pollfd arrays struct pollfd polls[_SIZE_]; int index = 0; int timeout = 5000; //check question time int i = 0; polls[0].fd = listen_sock; polls[0].events = POLLIN; polls[0].revents = 0; ++index; //init polls.fd for(i = 1;i < _SIZE_;++i) { polls[i].fd = -1; } char buf [1024]; ssize_t s = 0; struct sockaddr_in client; socklen_t len = sizeof(client); int done = 0; int max_fd = 1; while(!done) { switch(poll(polls,max_fd,timeout)) { case -1: perror("poll"); break; case 0: printf("timeout\n"); break; default: { size_t i = 0; for(;i<_SIZE_;++i) { if((polls[i].fd == listen_sock) && (polls[i].revents == POLLIN)) { int accept_sock = accept(listen_sock,(struct sockaddr*)&client,&len); if(accept_sock < 0) { perror("accept"); continue; } printf("connet success\n"); for(;i < _SIZE_;++i) { if(polls[i].fd == -1) { polls[i].fd = accept_sock; polls[i].events = POLLIN; ++max_fd; break; } } if(i == _SIZE_) { close(accept_sock); } } else if((polls[i].fd > 0) &&(polls[i].revents == POLLIN) ) { ssize_t size = read(polls[i].fd,buf,sizeof(buf)-1); if(size < 0) { perror("read"); continue; } else if(size == 0) { printf("client close \n"); struct pollfd tmp = polls[i]; polls[i] = polls[max_fd -1]; polls[max_fd -1] = tmp; close(polls[max_fd - 1].fd); polls[max_fd - 1].fd = -1; } else { buf[size] = '\0'; printf("client # %s",buf); polls[i].events = POLLOUT; } } else if(polls[i].fd > 0&& \ polls[i].revents == POLLOUT) { write(polls[i].fd,buf,sizeof(buf)); polls[i].events = POLLIN; } } } break; } } return 0; }
C
# define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include"game.h" #include<string.h> #include<Windows.h> #include<stdlib.h> #include<time.h> void menu() { printf("**********************************\n"); printf("*************ɨСϷ***********\n"); printf("***************1.PLAY*************\n"); printf("***************0.EXIT*************\n"); printf("**********************************\n"); printf("**********************************\n"); } void game() { char arrg1[ROWS + 2][COLS + 2] = { 0 }; char arrg2[ROWS + 2][COLS + 2] = { 0 }; memset(arrg1, '*', sizeof(char)*(ROWS + 2)*(COLS + 2)); memset(arrg2, '0', sizeof(char)*(ROWS + 2)*(COLS + 2)); display(arrg1, ROWS, COLS); make_mine(arrg2, ROWS, COLS); display(arrg2, ROWS, COLS); int i = 0; while (i < ROWS*COLS - MINE) { int x = 0; int y = 0; int count = 0; //if (MINE == i) //{ // void win_mine(arrg2); //} printf(" 1 3\n"); scanf("%d %d", &x, &y); fflush(stdin); system("cls"); printf("ȥǰ̽̽·\n"); Sleep(2000); system("cls"); if (i == 0) { hide_mine(arrg2, x, y); } if (arrg2[x][y] == '1') { printf("㱻ը\n"); display(arrg1, ROWS, COLS); break; } else { i++; statistics_mines(arrg2, arrg1, x, y); display(arrg1, ROWS, COLS); } } if (i >= ROWS*COLS - MINE) { printf("!!!ʤ\n"); display(arrg2, ROWS, COLS); } } enum Option { EXIT, PLAY }; int main() { int input = 0; srand((int unsigned)time(NULL)); do { menu(); printf("ǷҪʼϷ\n"); scanf("%d", &input); fflush(stdin); switch (input) { case PLAY: while (1) { game(); //Sleep(3000); //system("cls"); break; } case EXIT: break; default: printf("ѡ \n"); break; } } while (input); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <string.h> #include <errno.h> #include <pthread.h> /* limits.h defines "PATH_MAX". */ #include <limits.h> #include "mutexleveldb.h" #include "perf.h" #undef PROFILE #define GETENTRY_THREADS 32 #define GETENTRY_COMMAND "cat output.%d | beegfs-ctl --getentryinfo --nomappings --unmounted -" //#define GETENTRY_COMMAND "cat output.%d | while read line ;do echo 'Path: '$line; echo $line| beegfs-ctl --getentryinfo --nomappings --unmounted -; done" #define PATH_IDENTIFIER "Path: " #define ENTRYID_IDENTIFIER "EntryID: " #define LINE_BUFSIZE PATH_MAX // Global values shared between threads struct mutexleveldb * db; struct arg_struct { int thread_id; int thread_count; }; /* Worker thread for fetching entries */ void * getentry_worker (void * x) { char line[LINE_BUFSIZE]; char linebuf[LINE_BUFSIZE]; long linenr; FILE *pipe; FILE *getline_pipe; char cmd[PATH_MAX]; struct arg_struct *args = (struct arg_struct *) x; char filename[PATH_MAX]; #ifdef PROFILE perf_entry_t * perf_getentry, * perf_leveldb, * perf_strcmp; #endif size_t path_identifier_len = strlen(PATH_IDENTIFIER); size_t entryid_identifier_len = strlen(ENTRYID_IDENTIFIER); char path_line[PATH_MAX]; char entryid_line[64]; #ifdef PROFILE perf_getentry = perf_create("thread", args->thread_id*3+1, 0); perf_leveldb = perf_create("leveldb", args->thread_id*3+2, args->thread_id*3+1); perf_strcmp = perf_create("strcmp", args->thread_id*3+3, args->thread_id*3+1); perf_update_start(perf_getentry); #endif /* Create cmd */ sprintf(cmd, GETENTRY_COMMAND, args->thread_id); /* Get a pipe where the output from the scripts comes in */ pipe = popen(cmd, "r"); if (pipe == NULL) { /* check for errors */ fprintf (stderr, "Failed to run: %s\n", cmd); /* report error message */ exit (EXIT_FAILURE); /* return with exit code indicating error */ } sprintf(filename, "output.%d", args->thread_id); getline_pipe = fopen(filename, "r"); /* Read script output from the pipe line by line */ while (fgets(line, LINE_BUFSIZE, pipe) != NULL) { #ifdef PROFILE perf_update_start(perf_strcmp); #endif if (strncmp(line, PATH_IDENTIFIER, path_identifier_len) == 0) { strcpy(path_line, line + (int) path_identifier_len); // Remove newline path_line[(int)strlen(path_line)-1] = '\0'; } else if (strncmp(line, ENTRYID_IDENTIFIER, entryid_identifier_len) == 0) { strcpy(entryid_line, line + (int) entryid_identifier_len); // Remove newline entryid_line[(int)strlen(entryid_line)-1] = '\0'; fgets(linebuf, LINE_BUFSIZE, getline_pipe); strcpy(path_line, linebuf); path_line[(int)strlen(path_line)-1] = '\0'; #ifdef PROFILE perf_update_tick(perf_strcmp); perf_update_start(perf_leveldb); #endif // Write to db mutexleveldb_write2(10000, db, entryid_line, strlen(entryid_line), path_line, strlen(path_line)); #ifdef PROFILE perf_update_tick(perf_leveldb); perf_update_start(perf_strcmp); #endif } #ifdef PROFILE perf_update_tick(perf_strcmp); #endif } /* Once here, out of the loop, the script has ended. */ pclose(pipe); /* Close the pipe */ fclose(getline_pipe); #ifdef PROFILE perf_update_tick(perf_getentry); perf_submit(perf_getentry); perf_submit(perf_leveldb); perf_submit(perf_strcmp); #endif pthread_exit(NULL); } int main(int argc, char *argv[]) { pthread_t threads[GETENTRY_THREADS]; pthread_attr_t attr; struct arg_struct thread_args[GETENTRY_THREADS]; int i; #ifdef PROFILE perf_entry_t * perf_main; #endif /* Get args */ if(argc == 3) { /* Init db */ db = mutexleveldb_create2(atol(argv[1]), argv[2]); } else { printf("Usage: bp-cm-getentry <filecount> <leveldb filename>\n"); exit(1); } #ifdef PROFILE perf_global_init(); perf_main = perf_create("Main", 0, -1); perf_update_start(perf_main); #endif /* For portability, explicitly create threads in a joinable state */ pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i = 0; i < GETENTRY_THREADS; i++) { thread_args[i].thread_id = i; thread_args[i].thread_count = GETENTRY_THREADS; pthread_create(&threads[i], &attr, getentry_worker, (void *) &thread_args[i]); } /* Wait for all threads to complete */ for (i=0; i<GETENTRY_THREADS; i++) { pthread_join(threads[i], NULL); } #ifdef PROFILE perf_update_tick(perf_main); perf_submit(perf_main); perf_output_report(0); perf_global_free(); #endif /* Clean up and exit */ pthread_attr_destroy(&attr); mutexleveldb_close_and_destroy(db); return 0; }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <signal.h> int main(void) { int id; int status; pid_t pid; printf("Hello world\n"); id = fork(); if (id < 0) { printf("Impossible de fork le processus\n"); return (EXIT_FAILURE); } while (1) { if (id == 0) { /* On rajoute -- avant les messages du fils afin de les distinguer de ceux du père. Les deux processus sont tués avec CTRL+C. On utilise kill pour tuer uniquement le fils : - cela semble arrêter le programme fils mais la ligne suivante reste visible avec ps a : 12644 s000 Z+ 0:00.00 (main) - cette ligne disparait lorsqu’on tue le père. */ printf("-- Je suis le fils\n"); printf("-- Mon PID est : %d\n-- Celui de mon père est : %d\n", getpid(), getppid()); printf("-- Voici un nombre aléatoire : %d\n", rand() % 100); sleep(1); } else { pid = wait(&status); if (pid >= 0) printf("Le fils vient de se terminer, avec le code retour : %d\n", WEXITSTATUS(status)); printf("Je suis le père !\n"); printf("Mon PID est : %d\nCelui de mon père est : %d\n", getpid(), getppid()); printf("Voici un nombre aléatoire : %d\n", rand() % 100); sleep(1); } } printf("Fin de la boucle while\n"); return (EXIT_SUCCESS); }
C
#include <stdio.h> #include <stdlib.h> struct stack { int size; int top; int *st; }; void create(struct stack *S) { S->top=-1; printf("Enter the size "); scanf("%d",&S->size); S->st=(int *)malloc(S->size*(sizeof (int))); } void insert (struct stack *S){ scanf("%d",&S->st[++S->top]); } void display(struct stack S) { while(S.top!=-1) { printf("%d",S.st[S.top--]); } } void isfull(struct stack S) { if(S.top==S.size-1) { printf("Stack is full"); } else if(S.top >S.size) { printf("Stack is overflow"); } else{ printf(" Stack is not full"); } } int main() { struct stack S; create(&S); insert(&S); insert(&S); display(S); isfull(S); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* parsing_colors.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ericard <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/29 15:48:02 by ericard #+# #+# */ /* Updated: 2021/04/06 11:58:42 by ericard ### ########.fr */ /* */ /* ************************************************************************** */ #include "cub3d.h" int colors_comma(char *str, int *i, t_infos *infos) { while (str[*i] == ' ' || (str[*i] >= 9 && str[*i] <= 13)) *i += 1; if (str[*i] == ',') { *i += 1; return (1); } else { free(str); errors("Couleurs incorrectes", infos); } return (0); } int atoi_colors(char *str, int *i, t_infos *infos) { int ret; ret = 0; while (str[*i] == ' ' || (str[*i] >= 9 && str[*i] <= 13)) *i += 1; if (str[*i] == '-' || str[*i] == '+' || str[*i] == '\0') { free(str); errors("Couleurs incorrectes", infos); } while (str[*i] >= '0' && str[*i] <= '9') { ret = 10 * ret + (str[*i] - '0'); *i += 1; } if (ret > 255 || ret < 0) { free(str); errors("Couleurs incorrectes", infos); } return (ret); } void colors_f(t_infos *infos, char *str) { int i; i = 1; if (infos->f.value != -1) { free(str); errors("Parametre 'F' en double", infos); } infos->f.r = atoi_colors(str, &i, infos); colors_comma(str, &i, infos); infos->f.g = atoi_colors(str, &i, infos); colors_comma(str, &i, infos); infos->f.b = atoi_colors(str, &i, infos); if (str[i] != '\0') { free(str); errors("Couleurs du sol incorrectes", infos); } infos->f.value = infos->f.r * 65536 + infos->f.g * 256 + infos->f.b; } void colors_c(t_infos *infos, char *str) { int i; i = 1; if (infos->c.value != -1) { free(str); errors("Parametre 'C' en double", infos); } infos->c.r = atoi_colors(str, &i, infos); colors_comma(str, &i, infos); infos->c.g = atoi_colors(str, &i, infos); colors_comma(str, &i, infos); infos->c.b = atoi_colors(str, &i, infos); if (str[i] != '\0') { free(str); errors("Couleurs du plafond incorrectes", infos); } infos->c.value = infos->c.r * 65536 + infos->c.g * 256 + infos->c.b; } void colors(t_infos *infos, char *str) { int i; i = 0; if (str[i] == 'F') colors_f(infos, str); if (str[i] == 'C') colors_c(infos, str); }
C
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> //Complete the following function. void calculate_the_maximum(int n, int k) { int i,j; int max1=0,max2=0,max3=0; for(i=1;i<=n-1;i++) { for(j=i+1;j<=n;j++) { int a=i&j; int b=i|j; int c=i^j; if(a<k && a>max1) { max1=a; } if(b<k && b>max2) { max2=b; }if(c<k && c>max3) { max3=c; } } } printf("%d\n%d\n%d\n",max1,max2,max3); //Write your code here. } int main() { int n, k; scanf("%d %d", &n, &k); calculate_the_maximum(n, k); return 0; }
C
/* Probem statement: * You have a ladder n-steps in height. You can either take one step * or two steps up the ladder at a time. How can you find out all the * different combinations up the ladder? Then figure out an algorithm that * will actually print out all the different ways up the ladder * Approach: * For any N, and binary value 0/1, we can have 2 power N possible combinations * So, generate all those possible combinations and count the step count * if all the step count adds up to N - then its a valid combination for our problem */ typedef unsigned int UINT; void StepProblem(UINT numOfSteps) { UINT bitCount = 0; UINT stepCount = 0; UINT count = 0; UINT possibleCombinations = pow(2, numOfSteps); /* For each such possible ways, see whether its a valid combination */ for(;count<possibleCombinations; count++) { /* this can be done by counting: * no_of_bits which has 0 ==> taking one step at a time * no_of_bits which has 1 ==> taking 2 step at a time * if its equals N, then its a valid way. * so display the sequence accordingly [by printing "1" for bits with 0 and "2" for bits with 1 */ DisplayCombination(numOfSteps, count); } } void DisplayCombination(UINT numOfSteps, UINT num) { UINT count = 0; UINT lsb = 0; UINT totalSteps = 0; UINT index = 0; char* combination = malloc(sizeof(char) * (numOfSteps + 1)); for(;index < numOfSteps; index++) { /* Get the LSB */ lsb = num & 0x01; if(lsb == 0x01) { /* taking 2 steps at a time */ totalSteps += 2; combination[index] = '2'; } else { /* taking 1 step at a time */ totalSteps += 1; combination[index] = '1'; } if(totalSteps == numOfSteps) { /* We are done with one possible combination, so display it and break*/ combination[index+1] = '\0'; printf("%s\n", combination); break; } /* shift the number a bit so that we get the next bit */ num = num >> 0x01; } free(combination); }
C
#include <stdio.h> #include <rpm/rpmlib.h> #include <rpm/rpmts.h> #include <rpm/header.h> void printtagdata(const rpmtd atagdata ) { char* datastr = NULL; if( !atagdata ) { printf("NULL POINTER\n"); return; } const char* tagname = (atagdata->tag) ? rpmTagGetName(atagdata->tag) : "!NULLTAG!"; if (atagdata->data) { datastr = rpmtdFormat(atagdata, RPMTD_FORMAT_STRING, "SOME_ERROR"); } else { datastr = strdup("!NULLDATA!"); } printf("%s : ", tagname); if( atagdata->count > 1 ) { printf("ARRAY_OF_SIZE_%u\n", atagdata->count); } else { printf("%s\n", datastr); } free(datastr); datastr = 0; return; } int main(int argc, char** argv) { int result = 0; if( argc < 2 ) { printf("Usage:\n\trpmquery [ignored-options] <file.rpm>\n"); exit(1); } const char* fnamein = argv[argc-1]; FD_t fdin = Fopen(fnamein, "r.ufdio"); if ((!fdin) || Ferror(fdin)) { fprintf(stderr, "Failed to open \"%s\": %s\n", fnamein, Fstrerror(fdin)); if (fdin) { Fclose(fdin); } exit(1); } rpmts ts = rpmtsCreate(); rpmVSFlags vsflags = 0; vsflags |= _RPMVSF_NODIGESTS; vsflags |= _RPMVSF_NOSIGNATURES; vsflags |= RPMVSF_NOHDRCHK; (void) rpmtsSetVSFlags(ts, vsflags); rpmRC rc = 0; Header rpmhdr = {0}; rc = rpmReadPackageFile(ts, fdin, fnamein, &rpmhdr); if (rc != RPMRC_OK) { fprintf(stderr, "Could not read package header for %s\n", fnamein); Fclose(fdin); exit(1); } HeaderIterator hi = headerInitIterator(rpmhdr); struct rpmtd_s curdata = {0}; rpmtd cptr = &curdata; // iterate over header entries printing each one while (headerNext(hi, cptr)) { printtagdata(cptr); rpmtdFreeData(cptr); } // Clean up headerFreeIterator(hi); headerFree(rpmhdr); rpmtsFree(ts); Fclose(fdin); return result; }
C
#include "all.h" #define Max(a,b) (a>b?a:b) #define Min(a,b) (a<b?a:b) int32_t Int32Abs(int32_t Data) { if(Data<0) return -Data; else return Data; } int64_t Int64Abs(int64_t Data) { if(Data<0) return -Data; else return Data; } float F_Abs(float Data) { if(Data<0) return -Data; else return Data; } double MaxFour(double a,double b,double c,double d) { double maxtemp1,maxtemp2; maxtemp1=Max(a,b); maxtemp2=Max(c,d); return Max(maxtemp1,maxtemp2); } /* * : GetLength * : ֮ľ * : -a -b * : ֮ľ * : ⲿ */ float GetLength(Pointfp64 a,Pointfp64 b) { float length; float dx,dy; dx = ((float)a.x-(float)b.x)*((float)a.x-(float)b.x); dy = ((float)a.y-(float)b.y)*((float)a.y-(float)b.y); length = sqrt(dx+dy); return length; } /* * : GetDis_P2L * : 㵽ֱߵľ(֪һʽ: ax+by+c=0) * : -p * -a -b -c ֱ߷̵ϵ * : 㵽ֱߵľ * : ⲿ */ float GetDis_P2L(Pointfp64 p,float a,float b,float c) { return (a*p.x+b*p.y+c)/(sqrt(a*a+b*b)); } /* * : GetDis_P2L_PK * : 㵽ֱߵľ(֪бʽ: y-y0=k(x-x0)) * : -p * -p0 ֱһ -k ֱ߷̵б * : 㵽ֱߵľ * : ⲿ */ float GetDis_P2L_PK( Pointfp64 p, Pointfp64 p0,double k) { float a,b,c; a=k; b=-1; c=-k*p0.x+p0.y; return GetDis_P2L(p,a,b,c); } int circle_circle_intersection(double x0, double y0, double r0, double x1, double y1, double r1, double *xi, double *yi, double *xi_prime, double *yi_prime) { double a, dx, dy, d, h, rx, ry; double x2, y2; /* dx and dy are the vertical and horizontal distances between * the circle centers. */ dx = x1 - x0; dy = y1 - y0; /* Determine the straight-line distance between the centers. */ //d = sqrt((dy*dy) + (dx*dx)); d = hypot(dx,dy); // Suggested by Keith Briggs /* Check for solvability. */ if (d > (r0 + r1)) { /* no solution. circles do not intersect. */ return 0; } if (d < fabs(r0 - r1)) { /* no solution. one circle is contained in the other */ return 0; } /* 'point 2' is the point where the line through the circle * intersection points crosses the line between the circle * centers. */ /* Determine the distance from point 0 to point 2. */ a = ((r0*r0) - (r1*r1) + (d*d)) / (2.0 * d) ; /* Determine the coordinates of point 2. */ x2 = x0 + (dx * a/d); y2 = y0 + (dy * a/d); /* Determine the distance from point 2 to either of the * intersection points. */ h = sqrt((r0*r0) - (a*a)); /* Now determine the offsets of the intersection points from * point 2. */ rx = -dy * (h/d); ry = dx * (h/d); /* Determine the absolute intersection points. */ *xi = x2 + rx; *xi_prime = x2 - rx; *yi = y2 + ry; *yi_prime = y2 - ry; return 1; }
C
/* * GccApplication1.c * * Created: 12/14/2017 12:20:05 PM * Author: Student */ #include <avr/io.h> #include <util/delay.h> #include "lcd_lib.h" void cycle_1() { int c; char b[2]; for(int i =20;i>0;i--) { LCDGotoXY(0,0); sprintf(b,"%d",i); LCDstring(b,2); _delay_ms(500); PORTD|=((1<<0) | (1 << 7)); PORTC|=((1<<2)|(1<<3)); if(i<=10) { PORTD|=((1<<6)|(1<<2)); PORTC |=((1<<1)|(1<<5)); PORTD&= ~((1<<0) | (1 << 7)); PORTC&= ~((1<<2)|(1<<3)); } } } void cycle_2() { char b[2]; for(int i =20;i>0;i--) { LCDGotoXY(0,0); sprintf(b,"%d",i); LCDstring(b,2); _delay_ms(500); PORTD|=((1<<2)|(1<<5)); PORTC|=((1<<0)|(1<<5)); if(i<=10) { PORTD|=((1<<1)|(1<<7)); PORTC |=((1<<2)|(1<<4)); PORTD &= ~((1<<2)|(1<<5)); PORTC &= ~((1<<0)|(1<<5)); } } } void cycle_3() { char b[2]; for(int i =20;i>0;i--) { LCDGotoXY(0,0); sprintf(b,"%d",i); LCDstring(b,2); _delay_ms(500); PORTD|=((1<<0)|(1<<6)); PORTC|=((1<<1)|(1<<3)); if(i<=10) { PORTD|=((1<<2)|(1<<5)); PORTC |=((1<<0)|(1<<5)); PORTD&=~((1<<0)|(1<<6)); PORTC&=~((1<<1)|(1<<3)); } } } int main(void){ int a[2]; char b[2]; DDRD |=((1<<0)|(1<<1)|(1<<2)|(1<<5)|(1<<6)|(1<<7)); DDRC |=((1<<0)|(1<<1)|(1<<2)|(1<<3)|(1<<4)|(1<<5)); LCDinit(); while(1) { cycle_1(); PORTD&=~((1<<6)|(1<<2)); PORTC &=~((1<<1)|(1<<5)); cycle_2(); PORTD&=~((1<<1)|(1<<7)); PORTC &=~((1<<2)|(1<<4)); cycle_3(); PORTD&=~((1<<2)|(1<<5)); PORTC &=~((1<<0)|(1<<5)); } }
C
/* Write a program which displays ASCII table. Table contains symbol, Decimal, Hexadecimal and Octal representation of every member from 0 to 255. */ #include<stdio.h> void DisplayASCII() { int i =0; printf("___________________________________________\n"); printf("Decimal\t|Octal\t|Hexadicimal\t|ASCII\t|\n"); printf("___________________________________________\n"); for(i = 0;i<=255;i++) { printf("%d \t| %o \t| %x \t\t| %c\t|",i,i,i,i); printf("\n"); } } int main() { DisplayASCII(); return 0; }
C
/* You need to implement a versioned stack, i.e. version of stack will increment after each push/pop. Apart from push/pop, implement a method print(n) which would print stack state corresponding to version 'n'. For example: -> initially stack is empty. -> Version 1: 11 is pushed -> Version 2: 8 is pushed -> version 3: pop. only 11 left -> Version 4: 15 is pushed .... And so on. Print(n) should print state at version 'n'. Here 1 should print 11, 2 should print 8, 11... All methods should be as efficient as possible. */ #include<stdio.h> #include<stdlib.h> struct node{ int data; struct node *next; }; struct node *version_array[10] = {0}; int version = 0; void push(int ele) { struct node *new_node =(struct node *)malloc(sizeof(struct node)); new_node->data = ele; new_node->next = version_array[version]; version_array[++version] = new_node; } int pop(void) { struct node *temp = version_array[version]; if(temp){ int v = temp->data; temp = temp->next; version_array[++version]= temp; return v; }else{ puts("UnderFlow"); exit(1); } } void print(int n) { if(n > version || n < 0) puts("Version Not Exist"); else{ struct node *top = version_array[n]; while(top){ printf("%d\t",top->data); top = top->next; } } } int main() { int v; push(11); push(8); v = pop(); printf("%d ",v); push(5); v = pop(); printf("%d ",v); v = pop(); printf("%d ",v); puts(""); print(3); puts(""); print(2); puts(""); print(5); return 0; }
C
/*-------------------------------------------------------------------*/ /* ITS60304 Assignment #1 */ /* C Programming */ /* Student Name: <Balreen Kaur Badesha> <Lakshana Bunghoo> */ /* Student ID: <0319848> <0323400> */ /*-------------------------------------------------------------------*/ #include<stdio.h> #include<stdlib.h> #include<string.h> int menu(void); void purchase_items(void); void edit_items(void); void delete_items(void); void show_inventory(void); void show_dailytransactions(void); int count; float s_gst,s_ngst,t_gst; unsigned int u_quantity; char useritem_code[100]; FILE *fp1, *fp2, *myfile1, *temp1;// myfile is for receipt purposes struct read_calculate{ char item_code[100];//array declared for the barcode of items char item_name[100];//array declared for the name of items float price;//price of item unsigned int quantity;// quantity of the item dealt with } reference ; int main(void){ menu(); } int menu(void){ int i; char selection; printf("\n"); for (i=0;i<80;i++){ printf("-"); } printf("Grocery Retail\n"); for (i=0;i<80;i++){ printf("-"); } printf("1. Purchase items\n"); printf("2. Edit items\n"); printf("3. Delete items\n"); printf("4. Show inventory\n"); printf("5. Show daily transaction\n"); printf("6. Exit\n"); printf("Please enter your selection:"); scanf(" %c",&selection); switch(selection){ case '1': purchase_items(); // Requirement 2 break; case '2': edit_items();// Requirement 3 break; case '3': delete_items(); // Requirement 5 break; case '4': show_inventory(); // Requirement 6 break; case '5': show_dailytransactions(); // Requirement 7 break; case '6': printf("Program has been exited\n"); fclose(fopen("purchase.txt", "w")); // clear contents of file for the next transaction / run exit(0); // exit the program break; default: printf("Your selection is not an option!\n"); menu(); } } void purchase_items(void){ int check; // To avoid the item for being checked repeatedly int i; unsigned int remainder; char copy; float total_gst,total_ngst; float gst; float sum_gst; float sum_both; float purchase_sum; do{ printf("Please enter item code <-1 to end>:"); scanf("%s",useritem_code); if(strcmp(useritem_code,"-1")!=0){ printf("Please enter quantity:"); scanf("%d",&u_quantity); if ((fp1 = fopen("gst.txt","r"))==NULL){ puts("File could not be opened!"); }//end if else{ while (!feof(fp1)) { fscanf(fp1," %[^;];%[^;];%f;%u\n",reference.item_code, reference.item_name, &reference.price, &reference.quantity); if (strcmp(reference.item_code,useritem_code)==0){ while(u_quantity > reference.quantity){ printf("Not enough items in inventory.\n"); printf("Quantity of items only left: %d\n",reference.quantity); printf("Please enter new quantity:"); scanf("%d",&u_quantity); } remainder = reference.quantity - u_quantity; total_gst = u_quantity * reference.price; gst = total_gst * 0.06; sum_gst = gst + total_gst; check = 1; count = count + u_quantity; s_gst = s_gst + sum_gst; t_gst = t_gst + gst; purchase_sum = sum_gst; printf("\n %s %15s %14s %12s %15s\n","Item Code","Item Name","Price(RM)","Quantity","Total(RM)"); printf(" %7s %18s %10.2f %12u %16.2f\n",reference.item_code, reference.item_name,reference.price,u_quantity,purchase_sum); myfile1 = fopen("purchase.txt", "a"); fprintf(myfile1, "%s;%s;%.2f;%u;%.2f\n",reference.item_code, reference.item_name,reference.price,u_quantity,purchase_sum); fclose(myfile1); temp1 = fopen("temp.txt","a"); fprintf(temp1,"%s;%s;%.2f;%u\n",reference.item_code, reference.item_name,reference.price,remainder); fclose(temp1); }//end if else{ temp1 = fopen("temp.txt","a"); fprintf(temp1,"%s;%s;%.2f;%u\n",reference.item_code, reference.item_name,reference.price,reference.quantity); fclose(temp1); } }//end while fclose(fp1); }//end else remove("gst.txt"); rename("temp.txt","gst.txt"); if(check!= 1){ if ((fp2 = fopen("ngst.txt","r"))==NULL){ puts("File could not be opened!"); }//end if else{ while (!feof(fp2)) { fscanf(fp2," %[^;];%[^;];%f;%u\n",reference.item_code, reference.item_name, &reference.price, &reference.quantity); if (strcmp(reference.item_code,useritem_code)==0){ while(u_quantity > reference.quantity){ printf("Not enough items in inventory.\n"); printf("Quantity of items only left: %d\n",reference.quantity); printf("Please enter new quantity:"); scanf("%d",&u_quantity); } total_ngst = u_quantity * reference.price; check = 1; count = count + u_quantity; s_ngst = s_ngst + total_ngst; purchase_sum = total_ngst; printf("\n %s %15s %14s %12s %13s\n","Item Code","Item Name","Price(RM)","Quantity","Total(RM)"); printf(" %7s %15s %14.2f %12u %13.2f\n",reference.item_code, reference.item_name, reference.price,u_quantity,purchase_sum); myfile1 = fopen("purchase.txt", "a");/*Write to a file without overwriting to the file*/ fprintf(myfile1, "%s;%s;%.2f;%u;%.2f\n",reference.item_code, reference.item_name, reference.price,u_quantity,purchase_sum); fclose(myfile1); temp1 = fopen("temp.txt","a"); fprintf(temp1,"%s;%s;%.2f;%u\n",reference.item_code,reference.item_name,reference.price,remainder); fclose(temp1); }//end if else{ temp1 = fopen("temp.txt","a"); fprintf(temp1,"%s;%s;%.2f;%u\n",reference.item_code,reference.item_name,reference.price,reference.quantity); fclose(temp1); } }//end while fclose(fp2); remove("ngst.txt"); rename("temp.txt","ngst.txt"); if (check != 1){ printf("-------Item not found! Please try again-------\n"); }// end if }//end else }// end if }//end if check = 0;// Initalizing back the value to ensure the program is able to repeatedly check the item code for errors or matches. }while(strcmp(useritem_code,"-1")!=0);// end do-while loop sum_both = s_gst + s_ngst; /* To calculate the sum of the gst and ngst purchases and to avoid the receipt to be printed if nothing is purchased*/ if (sum_both != 0){ for (i=0;i<80;i++){ printf("~"); } printf("%40s\n","RECEIPT"); printf("\n %s %15s %14s %12s %14s\n","Item Code","Item Name","Price(RM)","Quantity","Total(RM)"); // header for (i=0;i<80;i++){ printf("~"); } if ((myfile1 = fopen("purchase.txt","r"))==NULL){ puts("File could not be opened!"); }// end if else{ while(!feof(myfile1)){ fscanf(myfile1," %[^;] ; %[^;] ;%f ;%u;%f " ,reference.item_code, reference.item_name, &reference.price,&u_quantity,&purchase_sum); printf("%8s %20s %9.2f %11u %15.2f\n",reference.item_code, reference.item_name, reference.price,u_quantity,purchase_sum); }// end while fclose(myfile1); }// end else printf("\nTotal of gst items : RM %.2f\n",s_gst); printf("Total of ngst items : RM %.2f\n",s_ngst); printf("Total of gst and ngst items : RM %.2f\n",sum_both); for (i=0;i<80;i++){ printf("~"); } } menu(); } void edit_items(void){ int check,verify; float price; char decision; char newname[100]; int i; for (i=0;i<80;i++){ printf("~"); } printf("%45s\n","EDITING ITEMS"); for (i=0;i<80;i++){ printf("~"); } do{ printf("Please enter item code <-1 to end>:"); scanf("%s",useritem_code); if(strcmp(useritem_code,"-1")!=0){ if ((fp1 = fopen("gst.txt","r"))==NULL){ puts("File could not be opened!"); }//end if else{ while (!feof(fp1)) { fscanf(fp1," %[^;];%[^;];%f;%u\n",reference.item_code, reference.item_name, &reference.price, &reference.quantity); if (strcmp(reference.item_code,useritem_code)==0){ check = 1; printf("Please enter new name:"); scanf("%s",newname); printf("Please enter new quantity:"); scanf("%u",&u_quantity); printf("Please enter new price:"); scanf("%f",&price); printf("Enter Y to continue or any other character to retype values:"); scanf(" %c",&decision); if (decision == 'Y'){ temp1 = fopen("temp.txt","a"); fprintf(temp1,"%s;%s;%.2f;%u\n",reference.item_code, newname,price,u_quantity); fclose(temp1); verify =1; printf("--------Edits were done-------\n"); } }//end if else{ temp1 = fopen("temp.txt","a"); fprintf(temp1,"%s;%s;%.2f;%u\n",reference.item_code, reference.item_name,reference.price,reference.quantity); fclose(temp1); }// end else }//end while fclose(fp1); if(verify == 1){ remove("gst.txt"); rename("temp.txt","gst.txt"); }// only done when changes are made verify = 0; // for further checking it is initilize to 0 }//end else fclose(fopen("temp.txt", "w"));// clear content if any if(check!= 1){ if ((fp2 = fopen("ngst.txt","r"))==NULL){ puts("File could not be opened!"); }//end if else{ while (!feof(fp2)) { fscanf(fp2," %[^;];%[^;];%f;%u\n",reference.item_code, reference.item_name, &reference.price, &reference.quantity); if (strcmp(reference.item_code,useritem_code)==0){ check = 1; printf("Please enter new name:"); scanf("%s",newname); printf("Please enter new quantity:"); scanf("%u",&u_quantity); printf("Please enter new price:"); scanf("%f",&price); printf("Enter Y to continue or any other character to retype values:"); scanf(" %c",&decision); if (decision == 'Y'){ temp1 = fopen("temp.txt","a"); fprintf(temp1,"%s;%s;%.2f;%u\n",reference.item_code, newname,price,u_quantity); fclose(temp1); verify = 1; printf("--------Edits were done-------\n"); }// end if }//end if else{ temp1 = fopen("temp.txt","a"); fprintf(temp1,"%s;%s;%.2f;%u\n",reference.item_code, reference.item_name,reference.price,reference.quantity); fclose(temp1); }// end else }//end while fclose(fp2); if(verify == 1){ remove("ngst.txt"); rename("temp.txt","ngst.txt"); }// only done when changes are made verify = 0; if (check != 1){ printf("-------Item not found! Please try again-------\n"); }// end if }//end else }// end if }//end if fclose(fopen("temp.txt", "w"));// clear content if any check = 0;// Initalizing back the value to ensure the program is able to repeatedly check the item code for errors or matches. }while(strcmp(useritem_code,"-1")!=0);// end do-while loop menu(); } void delete_items(void){ int check,verify; float price; char decision; char newname[100]; int i; for (i=0;i<80;i++){ printf("~"); } printf("%45s\n","DELETE ITEMS"); for (i=0;i<80;i++){ printf("~"); } do{ printf("Please enter item code <-1 to end>:"); scanf(" %s",useritem_code); if(strcmp(useritem_code,"-1")!=0){ if ((fp1 = fopen("gst.txt","r"))==NULL){ puts("File could not be opened!"); }//end if else{ while (!feof(fp1)) { fscanf(fp1," %[^;];%[^;];%f;%u\n",reference.item_code, reference.item_name, &reference.price, &reference.quantity); if (strcmp(reference.item_code,useritem_code)==0){ check = 1; if (reference.quantity == 0){ printf("Item was successfully delected.\n"); verify =1; } else{ printf("Item cannot be deleted.\n"); } }//end if else{ temp1 = fopen("temp.txt","a"); fprintf(temp1,"%s;%s;%.2f;%u\n",reference.item_code, reference.item_name,reference.price,reference.quantity); fclose(temp1); }// end else }//end while fclose(fp1); if(verify == 1){ remove("gst.txt"); rename("temp.txt","gst.txt"); }// only done when changes are made verify = 0; // for further checking it is initilize to 0 }//end else fclose(fopen("temp.txt", "w"));// clear content if any if(check!= 1){ if ((fp2 = fopen("ngst.txt","r"))==NULL){ puts("File could not be opened!"); }//end if else{ while (!feof(fp2)) { fscanf(fp1," %[^;];%[^;];%f;%u\n",reference.item_code, reference.item_name, &reference.price, &reference.quantity); if (strcmp(reference.item_code,useritem_code)==0){ check = 1; if (reference.quantity == 0){ printf("Item was successfully delected.\n"); verify =1; } else{ printf("Item cannot be deleted.\n"); } }//end if else{ temp1 = fopen("temp.txt","a"); fprintf(temp1,"%s;%s;%.2f;%u\n",reference.item_code, reference.item_name,reference.price,reference.quantity); fclose(temp1); }// end else }//end while fclose(fp2); if(verify == 1){ remove("ngst.txt"); rename("temp.txt","ngst.txt"); }// only done when changes are made verify = 0; if (check != 1){ printf("-------Item not found! Please try again-------\n"); }// end if }//end else }// end if }//end if fclose(fopen("temp.txt", "w"));// clear content if any check = 0;// Initalizing back the value to ensure the program is able to repeatedly check the item code for errors or matches. }while(strcmp(useritem_code,"-1")!=0);// end do-while loop menu(); } void show_inventory(void){ int i; FILE *fp1, *fp2; if ((fp1 = fopen("gst.txt","r"))==NULL){ puts("File could not be opened!"); }// end if else{ for (i=0;i<80;i++){ printf("-"); } printf("Taxable items\n"); for (i=0;i<80;i++){ printf("-"); } printf("\n %s %15s %14s %12s\n","Item Code","Item Name","Price(RM)","Quantity"); for (i=0;i<54;i++){ printf("="); } while(!feof(fp1)){ fscanf(fp1,"%[^;] ; %[^;] ;%f ;%d " ,reference.item_code, reference.item_name, &reference.price, &reference.quantity); printf("\n %6s %20s %10.2f %11d",reference.item_code,reference.item_name,reference.price,reference.quantity); }// end while fclose(fp1); }//end else if ((fp2 = fopen("ngst.txt","r"))==NULL){ puts("File could not be opened!"); }// end if else{ printf("\n"); for (i=0;i<80;i++){ printf("-"); } printf("Nontaxable items\n"); for (i=0;i<80;i++){ printf("-"); } printf("\n %s %15s %14s %12s\n","Item Code","Item Name","Price(RM)","Quantity"); for (i=0;i<54;i++){ printf("="); } while(!feof(fp2)){ fscanf(fp2,"%[^;] ; %[^;] ;%f ;%d " ,reference.item_code, reference.item_name, &reference.price, &reference.quantity); printf("\n %6s %20s %10.2f %11d",reference.item_code,reference.item_name,reference.price,reference.quantity); }// end while fclose(fp2); }// end else menu(); } void show_dailytransactions(void){ int i; unsigned int u_quantity; float purchase_sum; if (count!=0){ for (i=0;i<80;i++){ printf("~"); } printf("%50s\n","Purchased items\n"); printf("\n %s %15s %14s %12s %14s\n","Item Code","Item Name","Price(RM)","Quantity","Total(RM)"); // header for (i=0;i<80;i++){ printf("~"); } if ((myfile1 = fopen("purchase.txt","r"))==NULL){ puts("File could not be opened!"); }// end if else{ while(!feof(myfile1)){ fscanf(myfile1," %[^;] ; %[^;] ;%f ;%u;%f " ,reference.item_code, reference.item_name, &reference.price,&u_quantity,&purchase_sum); printf("%8s %20s %9.2f %11u %15.2f\n",reference.item_code, reference.item_name, reference.price,u_quantity,purchase_sum); }// end while fclose(myfile1); }// end else printf("Total Transactions : %d\n",count); // The total number of transaction in one run printf("Sales with GST : RM %.2f\n",s_gst); // The sum of GST purchases printf("Sales with NGST : RM %.2f\n",s_ngst);// The sum of NGST purchases printf("GST collected : RM %.2f\n",t_gst); // The sum of GST appplied } else{ for (i=0;i<80;i++){ printf("~"); } printf("No items were purchased\n"); for (i=0;i<80;i++){ printf("~"); } } menu(); }
C
#include<stdio.h> #include<windows.h> //baraye taghyire makane makannoma void gotoxy(int x, int y) { COORD coord = {x, y}; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); } #include <time.h> //estefade az tabe delay void delay(unsigned int mseconds) { clock_t goal = mseconds + clock(); while (goal > clock()); } void hanoi(int n,char a,char b,char c); void move(int n,char a,char b); void Print(); void Printpanel(int n); int a1=0,a2=0,a3=0; int main() { int n; char a='A',b='B',c='C'; //baraye namayesh satri dar khat aval printf("Please Enter number of loops :(0~9):"); scanf("%d",&n); a1=n;//bekhater inke nemitunim az aval meghdar dehi konim darune tabe maine inkaro mikonim Print(); gotoxy(0,11-n); Printpanel(n); delay(500); gotoxy(25,0); hanoi(n,a,b,c); return 0; } void hanoi(int n,char a,char b,char c) { if(n==1) //halate tavaghof tabe bazghashti move(n,a,b); else { hanoi(n-1,a,c,b); move(n,a,b); hanoi(n-1,c,b,a); } } void move(int n,char a,char b) { int j; switch(a) //pak kardan yek disk { case 'A'://Yani dar sotun A in kararo anjam bede a1--;//mizan kardane Y gotoxy(21+n,10-a1);//ye Y balatar vaymise pointer for(j=0;j<n*2;j++) printf(" \b\b");//hazf disk gotoxy(22,10-a1);//ba'd az hazf , pointer be makani aghabtar miravad ke in gotoxy aan ra dorost mikond printf("|");//printe | bejaye disk break; case 'B': a2--; gotoxy(38+n,10-a2); for(j=0;j<n*2;j++) printf(" \b\b"); gotoxy(39,10-a2); printf("|"); break; case 'C':a3--; gotoxy(55+n,10-a3); for(j=0;j<n*2;j++) printf(" \b\b"); gotoxy(56,10-a3); printf("|"); break; } gotoxy(40,0); //namayesh dar khat aval printf("Move %d, %c-->%c\n",n,a,b); switch(b) //baraye keshidan makane jadide halghe { case 'A': gotoxy(23-n,10-a1); a1++; for(j=0;j<n*2-1;j++) printf("="); gotoxy(0,22); delay(800); break; case 'B': gotoxy(40-n,10-a2); a2++; for(j=0;j<n*2-1;j++) printf("="); gotoxy(0,22); delay(800); break; case 'C': gotoxy(57-n,10-a3); a3++; for(j=0;j<n*2-1;j++) printf("="); gotoxy(0,22); delay(800); break; } } void Print() { printf("\n\n"); printf("\t\t | | | \n"); printf("\t\t | | | \n"); printf("\t\t | | | \n"); printf("\t\t | | | \n"); printf("\t\t | | | \n"); printf("\t\t | | | \n"); printf("\t\t | | | \n"); printf("\t\t | | | \n"); printf("\t\t _____A________________B________________C_____\n"); } void Printpanel(int n) { int i,j; for(i=1;i<=n;i++) { for(j=1;j<=23-i;j++) //fasele dadan ta sotun printf(" "); for(j=1;j<=i*2-1;j++)//*2-1: baraye in ke '='ha tedadeshan fard bashad- 1,3,5,... printf("="); printf("\n"); //paridan be khat ba'di baraye shurue dobareye halghe va rasme halghe jadid } }
C
#include <stdbool.h> #include <stdio.h> #define NREGS 16 #define STACK_SIZE 1024 #define SP 13 #define LR 14 #define PC 15 int add(int a, int b); struct arm_state { unsigned int regs[NREGS]; unsigned int cpsr; unsigned char stack[STACK_SIZE]; }; void init_arm_state(struct arm_state *as, unsigned int *func, unsigned int arg0, unsigned int arg1, unsigned int arg2, unsigned int arg3) { int i; /* zero out all arm state */ for (i = 0; i < NREGS; i++) { as->regs[i] = 0; } as->cpsr = 0; for (i = 0; i < STACK_SIZE; i++) { as->stack[i] = 0; } as->regs[PC] = (unsigned int) func; as->regs[SP] = (unsigned int) &as->stack[STACK_SIZE]; as->regs[LR] = 0; as->regs[0] = arg0; as->regs[1] = arg1; as->regs[2] = arg2; as->regs[3] = arg3; } bool is_add_inst(unsigned int iw) { unsigned int op; unsigned int opcode; op = (iw >> 26) & 0b11; opcode = (iw >> 21) & 0b1111; return (op == 0) && (opcode == 0b0100); } void armemu_add(struct arm_state *state) { unsigned int iw; unsigned int rd, rn, rm; iw = *((unsigned int *) state->regs[PC]); rd = (iw >> 12) & 0xF; rn = (iw >> 16) & 0xF; rm = iw & 0xF; state->regs[rd] = state->regs[rn] + state->regs[rm]; if (rd != PC) { state->regs[PC] = state->regs[PC] + 4; } } bool is_bx_inst(unsigned int iw) { unsigned int bx_code; bx_code = (iw >> 4) & 0x00FFFFFF; return (bx_code == 0b000100101111111111110001); } void armemu_bx(struct arm_state *state) { unsigned int iw; unsigned int rn; iw = *((unsigned int *) state->regs[PC]); rn = iw & 0b1111; state->regs[PC] = state->regs[rn]; } void armemu_one(struct arm_state *state) { unsigned int iw; iw = *((unsigned int *) state->regs[PC]); if (is_bx_inst(iw)) { armemu_bx(state); } else if (is_add_inst(iw)) { armemu_add(state); } } unsigned int armemu(struct arm_state *state) { while (state->regs[PC] != 0) { armemu_one(state); } return state->regs[0]; } int main(int argc, char **argv) { struct arm_state state; unsigned int r; init_arm_state(&state, (unsigned int *) add, 1, 2, 0, 0); r = armemu(&state); printf("r = %d\n", r); return 0; }
C
/* * Copyright (c) 2009-2015 Michael P. Touloumtzis. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "utf8.h" /* * Mark placed in the leading byte of a UTF-8 sequence to indicate length. */ static const uint8_t leading_mark [7] = { 0x00 /* unused */, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC, }; /* * Error included in adding up raw UTF-8 byte values. Rather than mask * out the value part on a byte-per-byte basis, we add raw values and * subtract the accumulated junk at the end. */ static const uint32_t cumulative_error [6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL, 0x03C82080UL, 0xFA082080UL, 0x82082080UL }; /* * Lookup table mapping leading byte values to # of remaining bytes. */ static const uint8_t trailing_bytes [256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, }; static inline uint_fast8_t encoded_size(uint32_t n) { if (n < 0x00000080) return 1; if (n < 0x00000800) return 2; if (n < 0x00010000) return 3; if (n < 0x00200000) return 4; if (n < 0x04000000) return 5; return 6; } uint_fast8_t utf8_encoded_size(uint32_t n) { return encoded_size(n); } const uint8_t * utf8_decode(const uint8_t *src, uint32_t *n) { uint_fast8_t rest = trailing_bytes[*src]; uint32_t m = 0; switch (rest) { case 5: m += *src++; m <<= 6; /* fall through... */ case 4: m += *src++; m <<= 6; /* fall through... */ case 3: m += *src++; m <<= 6; /* fall through... */ case 2: m += *src++; m <<= 6; /* fall through... */ case 1: m += *src++; m <<= 6; /* fall through... */ case 0: m += *src++; } *n = m - cumulative_error[rest]; return src; } uint8_t * utf8_encode(uint8_t *dst, uint32_t n) { static const uint32_t mask = 0xBF; static const uint32_t mark = 0x80; uint_fast8_t size = encoded_size(n); dst += size; switch (size) { case 6: *--dst = (n | mark) & mask; n >>= 6; /* fall through... */ case 5: *--dst = (n | mark) & mask; n >>= 6; /* fall through... */ case 4: *--dst = (n | mark) & mask; n >>= 6; /* fall through... */ case 3: *--dst = (n | mark) & mask; n >>= 6; /* fall through... */ case 2: *--dst = (n | mark) & mask; n >>= 6; /* fall through... */ case 1: *--dst = (n | leading_mark[size]); } return dst + size; /* Need to re-increment after backing up */ }
C
#include <stdio.h> #include <cs50.h> #include <string.h> #include <ctype.h> int main(int argc, string argv[]){ // if no command line args passed if (argc == 1){ printf("No command line arguments passed\n"); return 1; } if (argc > 2){ printf("Too many command line arguments passed\n"); return 1; } // convert argv[1] from string to int int key = atoi(argv[1]); // returns 0 if not convertable printf("plaintext:"); string s = get_string(); printf("ciphertext:"); // make sure got a string if (s != NULL){ //go through the input string one char at a time for(int i = 0, n = strlen(s); i < n; i++){ if (isalpha(s[i])){ // check if character is upper case if (isupper(s[i])){ // A is 65, to convert to alphabetical index, subtract 65 char cipherchar = s[i] - 65; // then add key and mod by 26 cipherchar = (cipherchar + key)%26; // convert back from alpha index to ascii cipherchar = cipherchar + 65; printf("%c", cipherchar); } else { // dealing with lower case character // a is 97, to convert to alphabetical index, subtract 97 char cipherchar = s[i] - 97; // then add key and mod by 26 cipherchar = (cipherchar + key)%26; // convert back from alpha index to ascii cipherchar = cipherchar + 97; printf("%c", cipherchar); } } else { // not an alphabetical character // so print it without ciphering it printf("%c", s[i]); } } } //print the final newline printf("\n"); return 0; }
C
//--------------------------------------------------------------------------------------- // Smile Programming Language Interpreter (Unit Tests) // Copyright 2004-2019 Sean Werkema // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //--------------------------------------------------------------------------------------- #include "../stdafx.h" TEST_SUITE(StringUnicodeTests) //------------------------------------------------------------------------------------------------- // Case-Insensitive Comparison Tests START_TEST(CompareIShouldMatchEmptyAndIdenticalAsciiStrings) { ASSERT(String_CompareI(String_Empty, String_Empty) == 0); ASSERT(String_CompareI(String_FromC("This is a test."), String_FromC("This is a test.")) == 0); ASSERT(String_CompareI(String_Create("This\ris\0a\ntest.", 15), String_Create("This\ris\0a\ntest.", 15)) == 0); } END_TEST START_TEST(CompareIShouldLexicallyOrderAsciiStrings) { ASSERT(String_CompareI(String_FromC("Soup"), String_FromC("Nuts")) > 0); ASSERT(String_CompareI(String_FromC("Aardvark"), String_FromC("Zoetrope")) < 0); } END_TEST START_TEST(CompareIShouldMatchAsciiStringsThatDifferByCase) { ASSERT(String_CompareI(String_FromC("SOUP"), String_FromC("soup")) == 0); ASSERT(String_CompareI(String_FromC("nuts"), String_FromC("NUTS")) == 0); } END_TEST START_TEST(CompareIShouldLexicallyOrderAsciiStringsThatDifferByCase) { ASSERT(String_CompareI(String_FromC("SOUP"), String_FromC("nuts")) > 0); ASSERT(String_CompareI(String_FromC("aardvark"), String_FromC("ZOETROPE")) < 0); } END_TEST START_TEST(CompareIShouldLexicallyOrderNonAsciiStringsThatDifferByCase) { ASSERT(String_CompareI(String_FromC("\xC3\xA9tudier"), String_FromC("\xC3\x89TUDIER")) == 0); ASSERT(String_CompareI(String_FromC("apres"), String_FromC("APR\xC3\x88S")) < 0); ASSERT(String_CompareI(String_FromC("APR\xC3\x88S"), String_FromC("apres")) > 0); } END_TEST START_TEST(CompareIUsesTrueCaseFolding) { ASSERT(String_CompareI(String_FromC("Wasserschlo\xC3\x9F"), String_FromC("WASSERSCHLOSS")) == 0); ASSERT(String_CompareI(String_FromC("Wasserschlo\xC3\x9F"), String_FromC("wasserschloss")) == 0); } END_TEST //------------------------------------------------------------------------------------------------- // Case-Insensitive Index-of Tests START_TEST(IndexOfIShouldFindNothingInEmptyStrings) { ASSERT(String_IndexOfI(String_Empty, String_FromC("This is a test."), 0) == -1); } END_TEST START_TEST(IndexOfIShouldFindEmptyStringsInsideEmptyStrings) { ASSERT(String_IndexOfI(String_Empty, String_Empty, -1) == 0); ASSERT(String_IndexOfI(String_Empty, String_Empty, 0) == 0); ASSERT(String_IndexOfI(String_Empty, String_Empty, 1) == -1); } END_TEST START_TEST(IndexOfIShouldFindEmptyStringsBeforeAndAfterEveryCharacter) { ASSERT(String_IndexOfI(String_FromC("This is a test."), String_Empty, -1) == 0); ASSERT(String_IndexOfI(String_FromC("This is a test."), String_Empty, 0) == 0); ASSERT(String_IndexOfI(String_FromC("This is a test."), String_Empty, 10) == 10); ASSERT(String_IndexOfI(String_FromC("This is a test."), String_Empty, 15) == 15); ASSERT(String_IndexOfI(String_FromC("This is a test."), String_Empty, 16) == -1); } END_TEST START_TEST(IndexOfIFindsContentWhenItExists) { String str1 = String_FromC("This is a test of the emergency broadcasting system."); String str2 = String_FromC("TEST"); String str3 = String_FromC("EmErGeNcY"); String str4 = String_FromC(" sysTEM."); ASSERT(String_IndexOfI(str1, str2, 0) == 10); ASSERT(String_IndexOfI(str1, str3, 0) == 22); ASSERT(String_IndexOfI(str1, str4, 0) == 44); } END_TEST START_TEST(IndexOfIFindsUnicodeContentWhenItExists) { String str1 = String_FromC("This is a tesst of the emerg\xC3\x89ncy broadcasting syst\xC3\xA9m."); String str2 = String_FromC("TE\xC3\x9FT"); String str3 = String_FromC("EmErG\xC3\xA9NcY"); String str4 = String_FromC(" sysT\xC3\x89M."); ASSERT(String_IndexOfI(str1, str2, 0) == 10); ASSERT(String_IndexOfI(str1, str3, 0) == 23); ASSERT(String_IndexOfI(str1, str4, 0) == 46); } END_TEST START_TEST(IndexOfIDoesNotFindContentWhenItDoesNotExist) { String str1 = String_FromC("This is a test of the emergency broadcasting system."); String str2 = String_FromC("emergnecy"); // Misspelled String str3 = String_FromC("broadcastink"); // Also misspelled String str4 = String_FromC("xyzzy"); // Not even a word String str5 = String_FromC("emerg\xC3\xA9ncy"); // E-with-accent is not E ASSERT(String_IndexOfI(str1, str2, 0) == -1); ASSERT(String_IndexOfI(str1, str3, 0) == -1); ASSERT(String_IndexOfI(str1, str4, 0) == -1); ASSERT(String_IndexOfI(str1, str5, 0) == -1); } END_TEST START_TEST(IndexOfIStartsWhereYouTellItToStart) { String str1 = String_FromC("This is a test of the emergency broadcasting system."); String str2 = String_FromC("TeSt"); String str3 = String_FromC("EmErGeNcY"); ASSERT(String_IndexOfI(str1, str2, 5) == 10); ASSERT(String_IndexOfI(str1, str2, 10) == 10); ASSERT(String_IndexOfI(str1, str2, 20) == -1); ASSERT(String_IndexOfI(str1, str3, 0) == 22); ASSERT(String_IndexOfI(str1, str3, 21) == 22); ASSERT(String_IndexOfI(str1, str3, 22) == 22); ASSERT(String_IndexOfI(str1, str3, 23) == -1); } END_TEST START_TEST(IndexOfIClipsStartIndexesToTheString) { String str1 = String_FromC("This is a test of the emergency broadcasting system."); String str2 = String_FromC("TEST"); String str3 = String_FromC("EMERGENCY"); ASSERT(String_IndexOfI(str1, str2, -100) == 10); ASSERT(String_IndexOfI(str1, str2, 10) == 10); ASSERT(String_IndexOfI(str1, str2, 200) == -1); ASSERT(String_IndexOfI(str1, str3, -100) == 22); ASSERT(String_IndexOfI(str1, str3, 10) == 22); ASSERT(String_IndexOfI(str1, str3, 100) == -1); } END_TEST START_TEST(IndexOfIFindsSubsequentMatches) { String str1 = String_FromC("This is a TEST is a tEsT is a TeSt is a test."); String str2 = String_FromC("test"); ASSERT(String_IndexOfI(str1, str2, 5) == 10); ASSERT(String_IndexOfI(str1, str2, 10) == 10); ASSERT(String_IndexOfI(str1, str2, 15) == 20); ASSERT(String_IndexOfI(str1, str2, 20) == 20); ASSERT(String_IndexOfI(str1, str2, 25) == 30); ASSERT(String_IndexOfI(str1, str2, 30) == 30); ASSERT(String_IndexOfI(str1, str2, 35) == 40); ASSERT(String_IndexOfI(str1, str2, 40) == 40); ASSERT(String_IndexOfI(str1, str2, 45) == -1); } END_TEST //------------------------------------------------------------------------------------------------- // Case-Insensitive Last-Index-of Tests START_TEST(LastIndexOfIShouldFindNothingInEmptyStrings) { ASSERT(String_LastIndexOfI(String_Empty, String_FromC("This is a test."), 0) == -1); } END_TEST START_TEST(LastIndexOfIShouldFindEmptyStringsInsideEmptyStrings) { ASSERT(String_LastIndexOfI(String_Empty, String_Empty, -1) == -1); ASSERT(String_LastIndexOfI(String_Empty, String_Empty, 0) == 0); ASSERT(String_LastIndexOfI(String_Empty, String_Empty, 1) == 0); } END_TEST START_TEST(LastIndexOfIShouldFindEmptyStringsBeforeAndAfterEveryCharacter) { ASSERT(String_LastIndexOfI(String_FromC("This is a test."), String_Empty, -1) == -1); ASSERT(String_LastIndexOfI(String_FromC("This is a test."), String_Empty, 0) == 0); ASSERT(String_LastIndexOfI(String_FromC("This is a test."), String_Empty, 10) == 10); ASSERT(String_LastIndexOfI(String_FromC("This is a test."), String_Empty, 15) == 15); ASSERT(String_LastIndexOfI(String_FromC("This is a test."), String_Empty, 16) == 15); } END_TEST START_TEST(LastIndexOfIFindsContentWhenItExists) { String str1 = String_FromC("This is a test of the emergency broadcasting system."); String str2 = String_FromC("TEST"); String str3 = String_FromC("EmErGeNcY"); String str4 = String_FromC(" sysTEM."); ASSERT(String_LastIndexOfI(str1, str2, 52) == 10); ASSERT(String_LastIndexOfI(str1, str3, 52) == 22); ASSERT(String_LastIndexOfI(str1, str4, 52) == 44); } END_TEST START_TEST(LastIndexOfIFindsUnicodeContentWhenItExists) { String str1 = String_FromC("This is a tesst of the emerg\xC3\x89ncy broadcasting syst\xC3\xA9m."); String str2 = String_FromC("TE\xC3\x9FT"); String str3 = String_FromC("EmErG\xC3\xA9NcY"); String str4 = String_FromC(" sysT\xC3\x89M."); ASSERT(String_LastIndexOfI(str1, str2, 55) == 10); ASSERT(String_LastIndexOfI(str1, str3, 55) == 23); ASSERT(String_LastIndexOfI(str1, str4, 55) == 46); } END_TEST START_TEST(LastIndexOfIDoesNotFindContentWhenItDoesNotExist) { String str1 = String_FromC("This is a test of the emergency broadcasting system."); String str2 = String_FromC("emergnecy"); // Misspelled String str3 = String_FromC("broadcastink"); // Also misspelled String str4 = String_FromC("xyzzy"); // Not even a word String str5 = String_FromC("emerg\xC3\xA9ncy"); // E-with-accent is not E ASSERT(String_LastIndexOfI(str1, str2, 52) == -1); ASSERT(String_LastIndexOfI(str1, str3, 52) == -1); ASSERT(String_LastIndexOfI(str1, str4, 52) == -1); ASSERT(String_LastIndexOfI(str1, str5, 52) == -1); } END_TEST START_TEST(LastIndexOfIStartsWhereYouTellItToStart) { String str1 = String_FromC("This is a test of the emergency broadcasting system."); String str2 = String_FromC("TeSt"); String str3 = String_FromC("EmErGeNcY"); ASSERT(String_LastIndexOfI(str1, str2, 52) == 10); ASSERT(String_LastIndexOfI(str1, str2, 14) == 10); ASSERT(String_LastIndexOfI(str1, str2, 13) == -1); ASSERT(String_LastIndexOfI(str1, str2, 5) == -1); ASSERT(String_LastIndexOfI(str1, str3, 52) == 22); ASSERT(String_LastIndexOfI(str1, str3, 30) == -1); ASSERT(String_LastIndexOfI(str1, str3, 31) == 22); ASSERT(String_LastIndexOfI(str1, str3, 32) == 22); } END_TEST START_TEST(LastIndexOfIClipsStartIndexesToTheString) { String str1 = String_FromC("This is a test of the emergency broadcasting system."); String str2 = String_FromC("TEST"); String str3 = String_FromC("EMERGENCY"); ASSERT(String_LastIndexOfI(str1, str2, -100) == -1); ASSERT(String_LastIndexOfI(str1, str2, 13) == -1); ASSERT(String_LastIndexOfI(str1, str2, 14) == 10); ASSERT(String_LastIndexOfI(str1, str2, 15) == 10); ASSERT(String_LastIndexOfI(str1, str2, 200) == 10); ASSERT(String_LastIndexOfI(str1, str3, -100) == -1); ASSERT(String_LastIndexOfI(str1, str3, 30) == -1); ASSERT(String_LastIndexOfI(str1, str3, 31) == 22); ASSERT(String_LastIndexOfI(str1, str3, 32) == 22); ASSERT(String_LastIndexOfI(str1, str3, 100) == 22); } END_TEST START_TEST(LastIndexOfIFindsSubsequentMatches) { String str1 = String_FromC("This is a TEST is a tEsT is a TeSt is a test."); String str2 = String_FromC("test"); ASSERT(String_LastIndexOfI(str1, str2, 5) == -1); ASSERT(String_LastIndexOfI(str1, str2, 10) == -1); ASSERT(String_LastIndexOfI(str1, str2, 15) == 10); ASSERT(String_LastIndexOfI(str1, str2, 20) == 10); ASSERT(String_LastIndexOfI(str1, str2, 25) == 20); ASSERT(String_LastIndexOfI(str1, str2, 30) == 20); ASSERT(String_LastIndexOfI(str1, str2, 35) == 30); ASSERT(String_LastIndexOfI(str1, str2, 40) == 30); ASSERT(String_LastIndexOfI(str1, str2, 45) == 40); ASSERT(String_LastIndexOfI(str1, str2, 50) == 40); ASSERT(String_LastIndexOfI(str1, str2, 55) == 40); } END_TEST //------------------------------------------------------------------------------------------------- // Case-Insensitive Contains Tests START_TEST(ContainsIShouldFindNothingInEmptyStrings) { ASSERT(!String_ContainsI(String_Empty, String_FromC("This is a test."))); } END_TEST START_TEST(ContainsIShouldFindEmptyStringsInsideEmptyStrings) { ASSERT(String_ContainsI(String_Empty, String_Empty)); } END_TEST START_TEST(ContainsIShouldFindEmptyStringsInEveryOtherString) { ASSERT(String_ContainsI(String_FromC("This is a test."), String_Empty)); } END_TEST START_TEST(ContainsIFindsContentWhenItExists) { String str1 = String_FromC("This is a test of the emergency broadcasting system."); String str2 = String_FromC("TEST"); String str3 = String_FromC("EmErGeNcY"); String str4 = String_FromC(" sysTEM."); ASSERT(String_ContainsI(str1, str2)); ASSERT(String_ContainsI(str1, str3)); ASSERT(String_ContainsI(str1, str4)); } END_TEST START_TEST(ContainsIFindsUnicodeContentWhenItExists) { String str1 = String_FromC("This is a tesst of the emerg\xC3\x89ncy broadcasting syst\xC3\xA9m."); String str2 = String_FromC("TE\xC3\x9FT"); String str3 = String_FromC("EmErG\xC3\xA9NcY"); String str4 = String_FromC(" sysT\xC3\x89M."); ASSERT(String_ContainsI(str1, str2)); ASSERT(String_ContainsI(str1, str3)); ASSERT(String_ContainsI(str1, str4)); } END_TEST START_TEST(ContainsIDoesNotFindContentWhenItDoesNotExist) { String str1 = String_FromC("This is a test of the emergency broadcasting system."); String str2 = String_FromC("emergnecy"); // Misspelled String str3 = String_FromC("broadcastink"); // Also misspelled String str4 = String_FromC("xyzzy"); // Not even a word String str5 = String_FromC("emerg\xC3\xA9ncy"); // E-with-accent is not E ASSERT(!String_ContainsI(str1, str2)); ASSERT(!String_ContainsI(str1, str3)); ASSERT(!String_ContainsI(str1, str4)); ASSERT(!String_ContainsI(str1, str5)); } END_TEST //------------------------------------------------------------------------------------------------- // Case-Insensitive Starts-With Tests START_TEST(StartsWithIMatchesContentWhenItExists) { String str1 = String_FromC("This is a test of the emergency broadcasting system."); String str2 = String_FromC("THIS IS"); String str3 = String_FromC("This is A TEST"); String str4 = String_FromC("This is a test OF THE"); ASSERT(String_StartsWithI(str1, str1)); ASSERT(String_StartsWithI(str1, str2)); ASSERT(String_StartsWithI(str1, str3)); ASSERT(String_StartsWithI(str1, str4)); } END_TEST START_TEST(StartsWithIDoesNotFindContentWhenItDoesNotExist) { String str1 = String_FromC("This is a test of the emergency broadcasting system."); String str2 = String_FromC("Thsi is a test"); // Misspelled String str3 = String_FromC("xyzzy"); // Not even a word ASSERT(!String_StartsWithI(str1, str2)); ASSERT(!String_StartsWithI(str1, str3)); } END_TEST START_TEST(StartsWithIAlwaysMatchesTheEmptyString) { String str = String_FromC("This is a test of the emergency broadcasting system."); ASSERT(String_StartsWithI(str, String_Empty)); ASSERT(String_StartsWithI(String_Empty, String_Empty)); } END_TEST START_TEST(StartsWithIFindsUnicodeContentWhenItExists) { String str1 = String_FromC("This is a tesst of the emerg\xC3\x89ncy broadcasting syst\xC3\xA9m."); String str2 = String_FromC("This is a TE\xC3\x9FT"); String str3 = String_FromC("EmErG\xC3\xA9NcY"); ASSERT(String_StartsWithI(str1, str2)); ASSERT(!String_StartsWithI(str2, str1)); ASSERT(!String_StartsWithI(str1, str3)); } END_TEST //------------------------------------------------------------------------------------------------- // Case-Insensitive Ends-With Tests START_TEST(EndsWithIMatchesContentWhenItExists) { String str1 = String_FromC("This is a test of the emergency broadcasting system."); String str2 = String_FromC("SYSTEM."); String str3 = String_FromC("BROADCASTING system."); String str4 = String_FromC("EMERGENCY broadcasting system."); ASSERT(String_EndsWithI(str1, str1)); ASSERT(String_EndsWithI(str1, str2)); ASSERT(String_EndsWithI(str1, str3)); ASSERT(String_EndsWithI(str1, str4)); } END_TEST START_TEST(EndsWithIDoesNotFindContentWhenItDoesNotExist) { String str1 = String_FromC("This is a test of the emergency broadcasting system."); String str2 = String_FromC("braodcasting ssytem"); // Misspelled String str3 = String_FromC("xyzzy"); // Not even a word ASSERT(!String_EndsWithI(str1, str2)); ASSERT(!String_EndsWithI(str1, str3)); } END_TEST START_TEST(EndsWithIAlwaysMatchesTheEmptyString) { String str = String_FromC("This is a test of the emergency broadcasting system."); ASSERT(String_EndsWithI(str, String_Empty)); ASSERT(String_EndsWithI(String_Empty, String_Empty)); } END_TEST START_TEST(EndsWithIFindsUnicodeContentWhenItExists) { String str1 = String_FromC("This is a tesst of the emerg\xC3\x89ncy broadcasting syst\xC3\xA9m."); String str2 = String_FromC("a TE\xC3\x9FT of THE eMeRg\xC3\xA9nCy broadcasting SYST\xC3\x89M."); String str3 = String_FromC("broadcasting SYST\xC3\x89m."); ASSERT(String_EndsWithI(str1, str2)); ASSERT(!String_EndsWithI(str2, str1)); ASSERT(String_EndsWithI(str1, str3)); } END_TEST //------------------------------------------------------------------------------------------------- // ToLower Tests START_TEST(ToLowerDoesNothingToEmptyAndWhitespaceStrings) { ASSERT_STRING(String_ToLower(String_Empty), "", 0); ASSERT_STRING(String_ToLower(String_FromC(" \t\r\n ")), " \t\r\n ", 7); } END_TEST START_TEST(ToLowerConvertsAsciiToLowercase) { ASSERT_STRING(String_ToLower(String_FromC("This IS A tEsT.")), "this is a test.", 15); ASSERT_STRING(String_ToLower(String_FromC("PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS.")), "pack my box with five dozen liquor jugs.", 40); } END_TEST START_TEST(ToLowerConvertsUnicodeToLowercase) { ASSERT_STRING(String_ToLower(String_FromC("PACK MY BOX WITH FIVE DOZ\xC3\x89N LIQUOR JUGS.")), "pack my box with five doz\xC3\xA9n liquor jugs.", 41); } END_TEST //------------------------------------------------------------------------------------------------- // ToUpper Tests START_TEST(ToUpperDoesNothingToEmptyAndWhitespaceStrings) { ASSERT_STRING(String_ToUpper(String_Empty), "", 0); ASSERT_STRING(String_ToUpper(String_FromC(" \t\r\n ")), " \t\r\n ", 7); } END_TEST START_TEST(ToUpperConvertsAsciiToUppercase) { ASSERT_STRING(String_ToUpper(String_FromC("This IS A tEsT.")), "THIS IS A TEST.", 15); ASSERT_STRING(String_ToUpper(String_FromC("pack my box with five dozen liquor jugs.")), "PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS.", 40); } END_TEST START_TEST(ToUpperConvertsUnicodeToUppercase) { ASSERT_STRING(String_ToUpper(String_FromC("pack my box with five doz\xC3\xA9n liquor jugs.")), "PACK MY BOX WITH FIVE DOZ\xC3\x89N LIQUOR JUGS.", 41); ASSERT_STRING(String_ToUpper(String_FromC("pack my box with five dozen liquor jug\xC3\x9F.")), "PACK MY BOX WITH FIVE DOZEN LIQUOR JUGSS.", 41); } END_TEST //------------------------------------------------------------------------------------------------- // ToTitle Tests START_TEST(ToTitleDoesNothingToEmptyAndWhitespaceStrings) { ASSERT_STRING(String_ToTitle(String_Empty), "", 0); ASSERT_STRING(String_ToTitle(String_FromC(" \t\r\n ")), " \t\r\n ", 7); } END_TEST START_TEST(ToTitleConvertsAsciiToUppercase) { ASSERT_STRING(String_ToTitle(String_FromC("This IS A tEsT.")), "THIS IS A TEST.", 15); ASSERT_STRING(String_ToTitle(String_FromC("pack my box with five dozen liquor jugs.")), "PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS.", 40); } END_TEST START_TEST(ToTitleConvertsUnicodeToUppercase) { ASSERT_STRING(String_ToTitle(String_FromC("pack my box with five doz\xC3\xA9n liquor jugs.")), "PACK MY BOX WITH FIVE DOZ\xC3\x89N LIQUOR JUGS.", 41); } END_TEST START_TEST(ToTitleConvertsCertainCompoundUnicodeCodePointsToTitlecase) { ASSERT_STRING(String_ToTitle(String_FromC("pack my box with five dozen liquor jug\xC3\x9F.")), "PACK MY BOX WITH FIVE DOZEN LIQUOR JUGSs.", 41); ASSERT_STRING(String_ToTitle(String_FromC("This is a DZ: \xC7\x84.")), "THIS IS A DZ: \xC7\x85.", 17); ASSERT_STRING(String_ToTitle(String_FromC("This is a Dz: \xC7\x85.")), "THIS IS A DZ: \xC7\x85.", 17); ASSERT_STRING(String_ToTitle(String_FromC("This is a dz: \xC7\x86.")), "THIS IS A DZ: \xC7\x85.", 17); ASSERT_STRING(String_ToTitle(String_FromC("This is a LJ: \xC7\x87.")), "THIS IS A LJ: \xC7\x88.", 17); ASSERT_STRING(String_ToTitle(String_FromC("This is a Lj: \xC7\x88.")), "THIS IS A LJ: \xC7\x88.", 17); ASSERT_STRING(String_ToTitle(String_FromC("This is a lj: \xC7\x89.")), "THIS IS A LJ: \xC7\x88.", 17); } END_TEST //------------------------------------------------------------------------------------------------- // CaseFold Tests START_TEST(CaseFoldDoesNothingToEmptyAndWhitespaceStrings) { ASSERT_STRING(String_CaseFold(String_Empty), "", 0); ASSERT_STRING(String_CaseFold(String_FromC(" \t\r\n ")), " \t\r\n ", 7); } END_TEST START_TEST(CaseFoldConvertsAsciiToLowercase) { ASSERT_STRING(String_CaseFold(String_FromC("This IS A tEsT.")), "this is a test.", 15); ASSERT_STRING(String_CaseFold(String_FromC("PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS.")), "pack my box with five dozen liquor jugs.", 40); } END_TEST START_TEST(CaseFoldConvertsUnicodeToComparableForm) { ASSERT_STRING(String_CaseFold(String_FromC("PACK MY BOX WITH FIVE DOZ\xC3\x89N LIQUOR JUGS.")), "pack my box with five doz\xC3\xA9n liquor jugs.", 41); ASSERT_STRING(String_CaseFold(String_FromC("pack my box with five dozen liquor jug\xC3\x9F.")), "pack my box with five dozen liquor jugss.", 41); } END_TEST //------------------------------------------------------------------------------------------------- // Unicode Decomposition Tests START_TEST(DecomposeDoesNothingToEmptyAndWhitespaceAndAsciiStrings) { ASSERT_STRING(String_Decompose(String_Empty), "", 0); ASSERT_STRING(String_Decompose(String_FromC(" \t\r\n ")), " \t\r\n ", 7); ASSERT_STRING(String_Decompose(String_FromC("This is a test.")), "This is a test.", 15); ASSERT_STRING(String_Decompose(String_FromC("Pack my box with five dozen liquor jugs.")), "Pack my box with five dozen liquor jugs.", 40); } END_TEST START_TEST(DecomposeDisassemblesCompoundAccentedCharacters) { ASSERT_STRING(String_Decompose(String_FromC("trouv\xC3\xA9.")), "trouve\xCC\x81.", 9); ASSERT_STRING(String_Decompose(String_FromC("\xC3\xA0 bient\xC3\xB4t.")), "a\xCC\x80 biento\xCC\x82t.", 14); } END_TEST START_TEST(DecomposeIgnoresNonAccentedUnicodeCharacters) { ASSERT_STRING(String_Decompose(String_FromC("tr\xC3\x97uv\xC3\xB0.")), "tr\xC3\x97uv\xC3\xB0.", 9); } END_TEST //------------------------------------------------------------------------------------------------- // Unicode Composition Tests START_TEST(ComposeDoesNothingToEmptyAndWhitespaceAndAsciiStrings) { ASSERT_STRING(String_Compose(String_Empty), "", 0); ASSERT_STRING(String_Compose(String_FromC(" \t\r\n ")), " \t\r\n ", 7); ASSERT_STRING(String_Compose(String_FromC("This is a test.")), "This is a test.", 15); ASSERT_STRING(String_Compose(String_FromC("Pack my box with five dozen liquor jugs.")), "Pack my box with five dozen liquor jugs.", 40); } END_TEST START_TEST(ComposeAssemblesCompoundAccentedCharacters) { ASSERT_STRING(String_Compose(String_FromC("trouve\xCC\x81.")), "trouv\xC3\xA9.", 8); ASSERT_STRING(String_Compose(String_FromC("a\xCC\x80 biento\xCC\x82t.")), "\xC3\xA0 bient\xC3\xB4t.", 12); } END_TEST START_TEST(ComposeIgnoresNonAccentedUnicodeCharacters) { ASSERT_STRING(String_Compose(String_FromC("tr\xC3\x97uv\xC3\xB0.")), "tr\xC3\x97uv\xC3\xB0.", 9); } END_TEST //------------------------------------------------------------------------------------------------- // Unicode Combining-Character Normalization Tests START_TEST(NormalizeDoesNothingToEmptyAndWhitespaceAndAsciiStrings) { ASSERT_STRING(String_Normalize(String_Empty), "", 0); ASSERT_STRING(String_Normalize(String_FromC(" \t\r\n ")), " \t\r\n ", 7); ASSERT_STRING(String_Normalize(String_FromC("This is a test.")), "This is a test.", 15); ASSERT_STRING(String_Normalize(String_FromC("Pack my box with five dozen liquor jugs.")), "Pack my box with five dozen liquor jugs.", 40); } END_TEST START_TEST(NormalizeIgnoresCompoundCharactersWithoutSeparatedDiacritics) { ASSERT_STRING(String_Normalize(String_FromC("trouv\xC3\xA9.")), "trouv\xC3\xA9.", 8); ASSERT_STRING(String_Normalize(String_FromC("\xC3\xA0 bient\xC3\xB4t.")), "\xC3\xA0 bient\xC3\xB4t.", 12); } END_TEST START_TEST(NormalizeIgnoresSingleAccents) { ASSERT_STRING(String_Normalize(String_FromC("trouve\xCC\x81.")), "trouve\xCC\x81.", 9); ASSERT_STRING(String_Normalize(String_FromC("a\xCC\x80 biento\xCC\x82t.")), "a\xCC\x80 biento\xCC\x82t.", 14); } END_TEST START_TEST(NormalizeIgnoresNonAccentedUnicodeCharacters) { ASSERT_STRING(String_Normalize(String_FromC("tr\xC3\x97uv\xC3\xB0.")), "tr\xC3\x97uv\xC3\xB0.", 9); } END_TEST START_TEST(NormalizeSortsPairsOfDiacriticsCorrectly) { // 'x' with dot below followed by dot above can be left alone. ASSERT_STRING(String_Normalize(String_FromC("x\xCC\xA3\xCC\x87.")), "x\xCC\xA3\xCC\x87.", 6); // 'x' with dot above followed by dot below must be transformed. ASSERT_STRING(String_Normalize(String_FromC("x\xCC\x87\xCC\xA3.")), "x\xCC\xA3\xCC\x87.", 6); } END_TEST START_TEST(NormalizeSortsManyDiacriticsCorrectly) { // The test below uses the diacritics in this table; the code points (and UTF-8 "magic numbers") // are provided here for reference. // // Tilde overlay U+0334: \xCC\xB4: class 1 // Palatalized hook below U+0321: \xCC\xA1: class 202 // Horn U+031B: \xCC\x9B: class 216 // Ring below U+0325: \xCC\xA5: class 220 // Ring above U+030A: \xCC\x8A: class 230 // Grave U+0300: \xCC\x80: class 230 // Acute U+0301: \xCC\x81: class 230 // Left angle above U+031A: \xCC\x9A: class 232 // Double inverted breve U+0361: \xCD\xA1: class 234 // Try all of the diacritics in forward (sorted) order. Should be unchanged. ASSERT_STRING(String_Normalize(String_FromC("x\xCC\xB4\xCC\xA1\xCC\x9B\xCC\xA5\xCC\x8A\xCC\x80\xCC\x81\xCC\x9A\xCD\xA1.")), "x\xCC\xB4\xCC\xA1\xCC\x9B\xCC\xA5\xCC\x8A\xCC\x80\xCC\x81\xCC\x9A\xCD\xA1.", 20); // Try all of the diacritics in reverse order. Should come out reversed, with the class-230 diacritics // still in reverse order (i.e., a stable sort was used). ASSERT_STRING(String_Normalize(String_FromC("x\xCD\xA1\xCC\x9A\xCC\x8A\xCC\x80\xCC\x81\xCC\xA5\xCC\x9B\xCC\xA1\xCC\xB4.")), "x\xCC\xB4\xCC\xA1\xCC\x9B\xCC\xA5\xCC\x8A\xCC\x80\xCC\x81\xCC\x9A\xCD\xA1.", 20); // Try all of the diacritics in a random shuffly order. The class-230 diacritics should stay in order. ASSERT_STRING(String_Normalize(String_FromC("x\xCC\xA5\xCC\xA1\xCC\x80\xCC\x9A\xCC\x8A\xCC\xB4\xCD\xA1\xCC\x81\xCC\x9B.")), "x\xCC\xB4\xCC\xA1\xCC\x9B\xCC\xA5\xCC\x80\xCC\x8A\xCC\x81\xCC\x9A\xCD\xA1.", 20); } END_TEST //------------------------------------------------------------------------------------------------- // Unicode Character-Extraction Tests. START_TEST(ExtractUnicodeCharacterCorrectlyRecognizesUtf8Sequences) { String str = String_FromC("a\xCC\x80 biento\xCC\x82t. \xC3\xA0 bient\xC3\xB4t."); const Int32 expectedResult[] = { 'a', 0x0300, ' ', 'b', 'i', 'e', 'n', 't', 'o', 0x0302, 't', '.', ' ', 0x00E0, ' ', 'b', 'i', 'e', 'n', 't', 0x00F4, 't', '.', }; Int i, src; Int32 ch; for (i = 0, src = 0; i < sizeof(expectedResult) / sizeof(Int32); i++) { ch = String_ExtractUnicodeCharacter(str, &src); ASSERT(ch == expectedResult[i]); } } END_TEST START_TEST(ExtractUnicodeCharacterInternalCorrectlyRecognizesUtf8Sequences) { String str = String_FromC("a\xCC\x80 biento\xCC\x82t. \xC3\xA0 bient\xC3\xB4t."); const Int32 expectedResult[] = { 'a', 0x0300, ' ', 'b', 'i', 'e', 'n', 't', 'o', 0x0302, 't', '.', ' ', 0x00E0, ' ', 'b', 'i', 'e', 'n', 't', 0x00F4, 't', '.', }; Int i; Int32 ch; const Byte *src, *end; src = String_GetBytes(str); end = src + String_Length(str); for (i = 0; i < sizeof(expectedResult) / sizeof(Int32); i++) { ch = String_ExtractUnicodeCharacterInternal(&src, end); ASSERT(ch == expectedResult[i]); } } END_TEST //------------------------------------------------------------------------------------------------- // Unicode Code-Page Conversion Tests START_TEST(ConvertingFromUtf8ToLatin1ConvertsLatin1CodePoints) { String str = String_FromC("\xC3\xA0 bient\xC3\xB4t."); ASSERT_STRING(String_ConvertUtf8ToKnownCodePage(str, LEGACY_CODE_PAGE_ISO_8859_1), "\xE0 bient\xF4t.", 10); } END_TEST START_TEST(ConvertingFromUtf8ToLatin1ConvertsNonLatin1CodePointsToQuestionMarks) { String str = String_FromC("a\xCC\x80 biento\xCC\x82t."); ASSERT_STRING(String_ConvertUtf8ToKnownCodePage(str, LEGACY_CODE_PAGE_ISO_8859_1), "a? biento?t.", 12); } END_TEST START_TEST(ConvertingFromLatin1ToUtf8ConvertsLatin1CodePointsToCombinedForms) { String str = String_FromC("\xE0 bient\xF4t."); ASSERT_STRING(String_ConvertKnownCodePageToUtf8(str, LEGACY_CODE_PAGE_ISO_8859_1), "\xC3\xA0 bient\xC3\xB4t.", 12); } END_TEST START_TEST(ConvertingToWindows1252IsNotTheSameAsLatin1) { String str = String_FromC("\x8A\xE0 \x93\x62ient\xF4t.\x94"); ASSERT_STRING(String_ConvertKnownCodePageToUtf8(str, LEGACY_CODE_PAGE_ISO_8859_1), "\xC2\x8A\xC3\xA0 \xC2\x93\x62ient\xC3\xB4t.\xC2\x94", 18); str = String_FromC("\x8A\xE0 \x93\x62ient\xF4t.\x94"); ASSERT_STRING(String_ConvertKnownCodePageToUtf8(str, LEGACY_CODE_PAGE_WIN1252), "\xC5\xA0\xC3\xA0 \xE2\x80\x9C\x62ient\xC3\xB4t.\xE2\x80\x9D", 20); } END_TEST START_TEST(ConvertingFromWindows1252IsNotTheSameAsLatin1) { String str = String_FromC("\xC2\x8A\xC3\xA0 \xC2\x93\x62ient\xC3\xB4t.\xC2\x94"); ASSERT_STRING(String_ConvertUtf8ToKnownCodePage(str, LEGACY_CODE_PAGE_ISO_8859_1), "\x8A\xE0 \x93\x62ient\xF4t.\x94", 13); str = String_FromC("\xC5\xA0\xC3\xA0 \xE2\x80\x9C\x62ient\xC3\xB4t.\xE2\x80\x9D"); ASSERT_STRING(String_ConvertUtf8ToKnownCodePage(str, LEGACY_CODE_PAGE_WIN1252), "\x8A\xE0 \x93\x62ient\xF4t.\x94", 13); } END_TEST START_TEST(ConvertingToAnUnknownCodePageResultsInEmptyString) { String str = String_FromC("\xE0 bient\xF4t."); ASSERT_STRING(String_ConvertKnownCodePageToUtf8(str, 12), "", 0); ASSERT_STRING(String_ConvertUtf8ToKnownCodePage(str, 12), "", 0); } END_TEST #include "stringunicode_tests.generated.inc"
C
#include <stdio.h> #include "stack.h" #include "List.h" //#include "stack.c" //#include "List.c" #include <string.h> int main(int* argc, char* argv[]){ void pass_through(char s[], int size); int check_op(char*s, int size, int idx); //checks if character from idx till next space is encountered is a number int return_char(char *s, int size, int idx, char *s2); //returns the number at idx to next space int ICPprior(char ch); //returns precedence value of an operation int ISPprior(char ch); // void tester(); char s[100]; while(fgets(s,100,stdin)!=NULL){ int len=strlen(s); s[len-1]='\0'; pass_through(s,len-1); printf("\n"); } } int check_op(char* s, int size, int idx) //checks if character from idx till next space is encountered is a number { int k=idx; switch(s[k]){ case '+': case '-': case '/': case '*': case '^': case '&': case '|': case '%': case '(': case ')': return 1; default: return 0; } } int return_char(char *s, int size, int idx, char *s2) //returns the number at idx to next space { int k=0; while((s[idx]!=' ')&&(idx!=size)){ s2[k++]=s[(idx)++]; } if(s[idx]==' ') (idx)++; s2[k]='\0'; return idx; } int ICPprior(char ch){ switch(ch){ case '+': return 1+2; case '-': return 1+2; case '/': return 3+2; case '*': return 3+2; case '&': return 0+2; case '%': return 5; case '^': return 1; case '|': return 0; case '(': return -1; case ')': return -1; } } int ISPprior(char ch){ switch(ch){ case '+': return 1+2; case '-': return 1+2; case '/': return 3+2; case '*': return 3+2; case '&': return 0+2; case '%': return 3+2; case '^': return -1+2; case '|': return -2+2; case '(': return -1; case ')': return -1; } } void print(int x){ char ch=x; char s[2]; s[0]=ch; s[1]='\0'; printf("%s ", s); } void pass_through(char s[], int size){ int i=0; int flag; int j; stack *ops=stack_new(); while(i<size){ char temp[10]; j=i; i=return_char(s,size,i,temp); flag=check_op(temp, i-j-1, 0); if(!flag){ printf("%s ",temp); } if (flag) { //printf("%c ",temp[0]); if(stack_is_empty(ops)) stack_push(ops, temp[0]); else if (temp[0]=='(') { stack_push(ops, temp[0]); } else if (temp[0]==')') { int top=stack_pop(ops); char ch=top; while(top!='('){ print(top); top=stack_pop(ops); ch=top; } //top=stack_pop(ops); } else{ int top=stack_pop(ops); char* ch=top; if(top=='('){ stack_push(ops, top); stack_push(ops, temp[0]); } else if(ICPprior(temp[0])>ISPprior(top)){ stack_push(ops, top); stack_push(ops, temp[0]); } else if (ICPprior(temp[0])<=ISPprior(top)) { while(ICPprior(temp[0])<=ISPprior(top)){ print(top); top=stack_pop(ops); ch=top; //printf("x"); } stack_push(ops, top); stack_push(ops, temp[0]); } } } } while(!stack_is_empty(ops)){ print(stack_pop(ops)); } }
C
#include "rc.h" #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <math.h> #include <float.h> void read_objs(OBJ_T **list){ double x,y,z,rad,r,g,b; *list=NULL; OBJ_T *obj; while(scanf("%lf%lf%lf%lf%lf%lf%lf",&x,&y,&z,&rad,&r,&g,&b)==7){ //printf("scanned in:\n%lf %lf %lf\n%lf\n%lf %lf %lf\n",x,y,z,rad,r,g,b); //Allocate memory for a new object obj=(OBJ_T *)malloc(sizeof(OBJ_T)); //Initialize object with parameters from scanf obj->sphere.center.x=x; obj->sphere.center.y=y; obj->sphere.center.z=z; obj->sphere.radius=rad; obj->color.r=r; obj->color.g=g; obj->color.b=b; obj->next=*list;//Append list to obj *list=obj; //Set obj to head of list } } int intersect_sphere(RAY_T ray, SPHERE_T sphere, double *t){ //quadratic formula double a,b,c; a=1; b=2 * ((ray.direction.x * (ray.origin.x - sphere.center.x)) + (ray.direction.y * (ray.origin.y - sphere.center.y)) + (ray.direction.z * (ray.origin.z - sphere.center.z))); c=( (ray.origin.x - sphere.center.x) * (ray.origin.x - sphere.center.x) + (ray.origin.y - sphere.center.y) * (ray.origin.y - sphere.center.y) + (ray.origin.z - sphere.center.z) * (ray.origin.z - sphere.center.z)) - (sphere.radius * sphere.radius); //calculate discriminant, b^2 - 4ac double disc = b * b - 4 * a * c; //negative discriminant means no real solution, which means no intersection exists if(disc < 0){ return 0; } double t0,t1; //if the ray intersects the sphere, it will intersect it at 2 locations. these can store those 2 //t0 is the closer intersection. t1 is the further t0 = (-b + sqrt (disc)) / (2*a); t1 = (-b - sqrt (disc)) / (2*a); //printf("%lf,%lf\n",t0,t1); if(t0 < 0){ if(t1 < 0){//if they're both negative there's no intersect. return 0; } t0 = t1; //if t0 is negative but t1 isn't, we can use t1 instead } *t = t0; return 1; } COLOR_T cast (RAY_T ray, OBJ_T *list){ COLOR_T result; result.r=1; result.g=1; result.b=1; double dist,closest_so_far; closest_so_far=DBL_MAX; OBJ_T *current; for(current=list;current!=NULL;current=current->next){ if(intersect_sphere(ray,current->sphere,&dist)){ if(dist<closest_so_far){ closest_so_far=dist; result=current->color; } } } //if(result.r!=1 && result.g!=1 && result.b!=1) printf("r: %lf g: %lf b: %lf\n",result.r,result.g,result.b); return result; } int main(){ OBJ_T *list = NULL; read_objs(&list); // Read in the object parameters from stdin and append them to list //printf("object radius: %lf\n",list->sphere.radius); printf("P6 1000 1000 255\n"); //PPM header RAY_T current_px; current_px.direction.z=1; current_px.origin.x=0; current_px.origin.y=0; current_px.origin.z=0; COLOR_T px_color; int row,col; for(row=0;row<1000;row++){//iterate through every row, then every col for(col=0;col<1000;col++){ //set up ray pointing from origin to here current_px.direction.x = -.5 + col / 1000.0; current_px.direction.y = .5 - row / 1000.0; current_px.direction=normalize(current_px.direction); //printf("%d,%d\n",row,col); //cast the ray, get its color px_color=cast(current_px,list); unsigned char r,g,b; r=(int)(255*px_color.r); g=(int)(255*px_color.g); b=(int)(255*px_color.b); printf("%c%c%c",r,g,b); } } //free all members of list OBJ_T *current; for(current=list;current!=NULL;current=current->next){ //printf("freeing\n"); free(current); //current=current->next; } return 0; }
C
#include <stdio.h> int main() { int a,b,i,j; int num[100]; printf("Enter a number you want the loop of: "); scanf("%d", &a); for (i = 0; i < a; i++) { printf("Enter a number: "); scanf("%d", &num[i]); } for (i = 0; i <= a; i++) { for (j = i + 1; j <= a; j++) { if (num[i] < num[j]) { b = num[i]; num[i] = num[j]; num[j] = b; } } } printf("The Sorted Elements are : \n "); for (i = 0; i < a; i++) { printf("%d ", num[i]); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <locale.h> #include <string.h> /*Cabealho Instituio: Faculdade dos Guararapes Professor: Guibson Santana Aluno: ngelo Gonalo da Silva Turma: CCO 2-MA PIE Data de Entrega: 22/08/2018 Data de Resoluo: 05/09/2018 Criar um algoritmo em C que receba um Estado brasileiro por extenso e o programa deve imprimir sua respectiva Sigla. Exemplo: Digite um estado: Pernambuco. Sigla: PE.*/ int main() { setlocale(LC_ALL, "Portuguese"); char nome[20]; int tamanho; do { printf ("\nNome digitado pode ter no mximo 20 caracteres para poder ser adicionado.\nNome: "); gets (nome); tamanho = strlen(nome); if(tamanho<=20) { printf("\nNOME CADASTRADO!\n\n"); } else { printf("\nQuantidade de caracteres maior que 20 caracteres.\n\n"); } }while(tamanho>20); return(0); }
C
//*************************************************** /** ファイルの開き方・閉じ方【fopenとfcloseの使い方】 * https://monozukuri-c.com/langc-file-open-close/ * 11/26 */ //*************************************************** // #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int main(void) { //FILE構造体をポインタ変数で用意 FILE *fp1 = NULL; FILE *fp2 = NULL; //fopen()の戻り値(ファイルハンドル)をFILEポインタ型変数に代入 fp1 = fopen("memo1.txt", "w"); fp2 = fopen("memo2.txt", "w"); fclose(fp1); fclose(fp2); //***************************************************** //fopen_s()関数の場合 return 0; } /** * 「fopen()」 * ・ファイル制御のための標準ライブラリ関数 *関数仕様:FILE * fopen(const char * filename, const char * mode); *引数1:ファイル名 *引数2:開くモード *戻り値:ファイルハンドル(ファイルディスクリプタ) *異常:NULLポインタが返却 * * 「fclose()」 * ・fopen()で開いたファイルを閉じる * 関数仕様:int fclose(FILE * fp); * 引数1:閉じるファイルハンドルを指定 * 戻り値:正常時0、異常時EOF * 特記事項:引数には必ずfopen()を呼び出した時のファイルハンドルを渡す * * 「FILE構造体」 *・ファイルを管理するための情報が詰め込まれたデータ *・fopen()を呼び出す→FILE構造体のメモリ確保→メモリ番地が戻り値で返却 *・上記のハンドルのメモリ領域は「ヒープメモリ」に確保 */
C
#include <stdio.h> #include <stdlib.h> #define TElemType int typedef struct BiTNode{ TElemType data;//数据域 struct BiTNode *lchild,*rchild;//左右孩子指针 }BiTNode,*BiTree; void CreateBiTree(BiTree *T){ *T=(BiTNode*)malloc(sizeof(BiTNode)); (*T)->data=1; (*T)->lchild=(BiTNode*)malloc(sizeof(BiTNode)); (*T)->lchild->data=2; (*T)->rchild=(BiTNode*)malloc(sizeof(BiTNode)); (*T)->rchild->data=3; (*T)->rchild->lchild=NULL; (*T)->rchild->rchild=NULL; (*T)->lchild->lchild=(BiTNode*)malloc(sizeof(BiTNode)); (*T)->lchild->lchild->data=4; (*T)->lchild->rchild=NULL; (*T)->lchild->lchild->lchild=NULL; (*T)->lchild->lchild->rchild=NULL; } int main() { BiTree Tree; CreateBiTree(&Tree); printf("%d",Tree->lchild->lchild->data); return 0; }
C
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <limits.h> #include <ctype.h> #include <dirent.h> // For colors #define KNRM "\x1B[0m" #define KRED "\x1B[31m" #define KGRN "\x1B[32m" #define KYEL "\x1B[33m" #define KBLU "\x1B[34m" #define KMAG "\x1B[35m" #define KCYN "\x1B[36m" #define KWHT "\x1B[37m" int *a, ef = 0, vcount = 0, normal_c = 0, count_option = 0, nofile = 0; struct Trie* head; char word[2][20]; int num = INT_MAX; int search(int *a, int s){ int i; for(i = 0; i < count_option; i++){ if(a[i] == s){ return 1; } } return 0; } int isnumber(char str[]){ int i = 0; if(str[i] == '0') { printf("\n bad number \n"); exit(0); } while(i < strlen(str)){ if(str[i] < '0' || str[i] > '9') return 0; i++; } num = atoi(str); return 1; } int isword(char str[]){ if(str[0] == '-') return 0; if(isnumber(str)){ return 0; } int i = 0; while(i < strlen(str)){ if(str[i] == '.') return 0; i++; } return 1; } int isoption(char str[]){ if(strlen(str) == 2 && str[0] == '-') return 1; return 0; } int isfile(char str[]){ int i = 0; while(i < strlen(str)){ if(str[i] == '.') return 1; i++; } return 0; } int isreg(char str[]) { int l = strlen(str); int i; for(i = 0; i < l; i++) { if(str[i] == '$' || str[i] == '^' || str[i] == '.' || str[i] =='[' || str[i] == ':') return 1; } return 0; } int* decide_priority(char options[10][3], int count_option) { int *a; a = (int*)malloc(14 * sizeof(int)); int i; for(i = 0; i < count_option; i++) a[i] = -1; for(i = 0; i < count_option; i++) { if(options[i][1] == 'r') a[i] = 0; if(options[i][1] == 'i') a[i] = 1; if(options[i][1] == 'w') a[i] = 2; if(options[i][1] == 'm') a[i] = 3; if(options[i][1] == 'c') a[i] = 4; if(options[i][1] == 'b') a[i] = 5; if(options[i][1] == 'v') a[i] = 6; if(options[i][1] == 'h') a[i] = 7; if(options[i][1] == 'H') a[i] = 8; if(options[i][1] == 'm') a[i] = 9; if(options[i][1] == 'q') a[i] = 10; if(options[i][1] == 'f') a[i] = 11; if(options[i][1] == 'e') { a[i] = 12; } if(a[i] == -1) { printf("\n%d Bad arguements", i); exit(0); } } int j; for(i = 0; i < count_option; i++){ for(j = 0; j < count_option - 1; j++) { if(a[j] > a[j + 1]){ int t = a[j]; a[j] = a[j + 1]; a[j + 1] =t; } } } return a; } #define C_SIZE 10000 struct Trie { int leaf; struct Trie* character[C_SIZE]; }; struct Trie* getNewTrieNode(){ struct Trie* node = (struct Trie*)malloc(sizeof(struct Trie)); node -> leaf = 0; int i; for (i = 0; i < C_SIZE; i++) node -> character[i] = NULL; return node; } void insert(struct Trie* *head, char* word) { struct Trie* curr = *head; while (*word) { if (curr->character[*word - 'a'] == NULL) curr->character[*word - 'a'] = getNewTrieNode(); curr = curr->character[*word - 'a']; word++; } curr->leaf = 1; } int searchtrie(struct Trie* head, char* word) { if (head == NULL) return 0; struct Trie* curr = head; while (*word) { curr = curr->character[*word - 'a']; if (curr == NULL) return 0; word++; } return curr->leaf; } int Children(struct Trie* curr) { int i; for (i = 0; i < C_SIZE; i++) { if (curr->character[i]) { return 1; } } return 0; } int efcount = 0; int efvcount = 0; void readeachline(char path[]){ int fd = open(path, O_RDONLY); int l = lseek(fd, 0, SEEK_END); lseek(fd, 0, 0); close(fd); char *str, *str1; str = (char*)malloc((l + 1) * sizeof(char)); FILE *fp = fopen(path, "r"); int i = 0, j = 0, found, numcount = 0, lastn = 0; char line[1000], line1[1000]; while(1) { str[i] = fgetc(fp); if(str[i] >= 'A' && str[i] <= 'Z' && search(a, 1)) line[j] = str[i] + 32; else line[j] = str[i]; line1[j] = str[i]; if(str[i] == EOF) { line[j] = '\0'; line1[j] = '\0'; found = searchtrie(head, line); if(found && !search(a, 6)) { if(!search(a, 4)) { if(search(a, 8)) { //printf("\n%s ", path); printf("%s%s:%s ", KMAG, path, KNRM); } if(search(a, 5)) { printf("%s%d: %s", KGRN, lastn, KWHT); } puts(line1); printf("\n"); } efcount++; numcount++; } else if(!found && search(a, 6)) { if(!search(a, 4)) { if(search(a, 8) && str[i + 1] != '\0') { printf("%s%s:%s ", KMAG, path, KNRM); } if(search(a, 5) && str[i + 1] != '\0') { printf("%s%d: %s", KGRN, lastn, KWHT); } puts(line1); } efvcount++; numcount++; } break; } if(line[j] == '\n') { line[j] = '\0'; line1[j] = '\0'; found = searchtrie(head, line); if(found && !search(a, 6)) { if(!search(a, 4)) { if(search(a, 8)) { printf("%s%s:%s ", KMAG, path, KNRM); } if(search(a, 5)) { printf("%s%d: %s", KGRN, lastn, KWHT); } puts(line1); } efcount++; numcount++; } else if(!found && search(a, 6)) { if(!search(a, 4)) { if(search(a, 8)) { printf("%s%s:%s ", KMAG, path, KNRM); } if(search(a, 5)) { printf("%s%d: %s", KGRN, lastn, KWHT); } puts(line1); } efvcount++; numcount++; } lastn = i + 1; j = -1; } if(numcount == num) break; j++; i++; } if(search(a, 4) ) { if(search(a, 8)) printf("%s%s:%s ", KMAG, path, KNRM); if(search(a, 6)) printf("%d \n", efvcount - 1); else printf("%d \n", efcount); } } void makeitline(char str[], int index){ int l = strlen(str), i, j; i = index; char line[1000]; while(str[i] != '\n' && i != 0){ i--; } if(i != 0){ i++; } j = 0; while(i < l && str[i] != '\n') { line[j] = str[i]; i++; j++; } line[j] = '\0'; if(!searchtrie(head, line)) insert(&head, line); } void printlinereg(char*, int); int find(char str[], char pat[], char firstchar, int firstcharindex) { int i, j, k, l = strlen(str), lpat= strlen(pat); for(i = 0; i < l; i++) { if(str[i] == firstchar) { k = i; for(j = 0; j < firstcharindex; j++) k--; for(j = 0; j < lpat; j++) { if(pat[j] != '.') { if(pat[j] != str[k]) { break; } } k++; } if(j == lpat) { if((str[i + lpat] < 'A' || (str[i + lpat] > 'Z' && str[i + lpat] < 'a') || str[i + lpat] > 'z') && search(a, 2) && (str[i - 1] == ' ' || str[i - 1] == '\n')) { makeitline(str, i); } else if(!search(a, 2)) makeitline(str, i); while(str[i] != '\n') i++; } } } return 0; } int dot(char str[], char pat[], int lpat){ char firstchar; int i, j, firstcharindex; for(i = 0; i < lpat; i++) { if((pat[i] >= 'A' && pat[i] <= 'Z') || (pat[i] >= 'a' && pat[i] <= 'z' )) { firstchar = pat[i]; firstcharindex = i; break; } } find(str, pat, firstchar, firstcharindex); return 0; } int searchinc(int j, char ch, char c[][26]) { int i; for(i = 0; i < 26; i++) { if(c[j][i] == ch) return 1; } return 0; } int findb(char str[], char pat[], char firstchar, int firstcharindex, char c[][26]) { int i, j, k, l = strlen(str), lpat= strlen(pat); for(i = 0; i < l; i++) { if(str[i] == firstchar || firstchar == '@') { k = i; for(j = 0; j < firstcharindex; j++) k--; for(j = 0; j < lpat; j++) { if(pat[j] != '.') { if(pat[j] != str[k]) { break; } } else if(pat[j] == '.') { if(!searchinc(j, str[k], c)) break; } k++; } if(j == lpat) { if((str[i + lpat] < 'A' || (str[i + lpat] > 'Z' && str[i + lpat] < 'a') || str[i + lpat] > 'z') && search(a, 2) && (str[i - 1] == ' ' || str[i - 1] == '\n')) { makeitline(str, i); } else if(!search(a, 2)) makeitline(str, i); while(str[i] != '\n') i++; } } } return 0; } int dotb(char str[], char pat[], int lpat, char c[][26]){ char firstchar = '@'; int i, j, firstcharindex = 0; lpat = strlen(pat); for(i = 0; i < lpat; i++) { if((pat[i] >= 'A' && pat[i] <= 'Z') || (pat[i] >= 'a' && pat[i] <= 'z' )) { firstchar = pat[i]; firstcharindex = i; break; } } findb(str, pat, firstchar, firstcharindex, c); return 0; } int aftern = 0, beforen = 0; //aftern (^) beforen ($) int afterncount = 0; int beforencount = 0; void LPSArrayreg(char* pat, int M, int* lps); char *strlwrreg(char *str) { unsigned char *p = (unsigned char *)str; while (*p) { *p = tolower((unsigned char)*p); p++; } return str; } void printlinereg(char* str, int i){ char str1[1000]; int j = i; int l = strlen(str); for(j = i - 1; j >= 0; j--){ if(str[j] == '\n') break; } int start = j + 1; if(i == 0) start = 0; for(j = i + 1; j < l; j++){ if(str[j] == '\n' || str[j] == '\0'){ break; } } str[j] = '\n'; int end = j - 1; for(j = start; j <= end; j++) printf("%c", str[j]); } void KMPSreg(char* pat, char* txt, char path[]) { int M = strlen(pat); int N = strlen(txt); int lps[M]; LPSArrayreg(pat, M, lps); int i = 0; int j = 0; while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { if(aftern) { if(txt[i - j - 1] == '\n' || i - j == 0) { if(search(a, 2)) { if((txt[i - j + M] < 'A' || (txt[i - j + M] > 'Z' && txt[i - j + M] < 'a') || txt[i - j + M] > 'z') && search(a, 2)) { if(search(a, 10)) { exit(0); } makeitline(txt, i - j); } } else if(!search(a, 2)) { if(search(a, 10)) { exit(0); } makeitline(txt, i - j); } } } if(beforen) { if(txt[i - j + strlen(pat) + 1] == '\n' || i - j + strlen(pat) == N) { if(search(a, 2) && (txt[i - j - 1] == '\n' || txt[i - j - 1]== ' ')) { if(search(a, 10)) { exit(0); } makeitline(txt, i - j); } else if(!search(a, 2)) { if(search(a, 10)) { exit(0); } makeitline(txt, i - j); } } } j = lps[j - 1]; } else if (i < N && pat[j] != txt[i]) { if (j != 0) j = lps[j - 1]; else i = i + 1; } } } void LPSArrayreg(char* pat, int M, int* lps) { int len = 0, i; lps[0] = 0; i = 1; while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else { if (len != 0) { len = lps[len - 1]; } else { lps[i] = 0; i++; } } } } int kmpreg(char pat[], char path[]) { int fd = open(path, O_RDONLY); if(fd == -1) exit(0); int l = lseek(fd, 0, SEEK_END); lseek(fd, 0, 0); char *str, *str1; str = (char*)malloc((l + 1) * sizeof(char)); //read(fd, str, l); close(fd); FILE *fp = fopen(path, "r"); if(fp == NULL) exit(0); int i = 0; while(1) { str[i] = fgetc(fp); if(str[i] == EOF) break; i++; } str[i] = '\0'; if(search(a, 1)) { strcpy(str, strlwrreg(str)); strcpy(pat, strlwrreg(pat)); } KMPSreg(pat, str, path); return 0; } int isdot(char str[]) { int i, l = strlen(str); for(i = 0; i < l; i++) { if(str[i] == '.') return 1; } return 0; } void reg(char str[], char path[]) { int lstr = strlen(str), l, i = 0; if(str[0] == '^' && str[1] != '[') { aftern = 1; for(i = 0; i < lstr - 1; i++) { str[i] = str[i + 1]; } str[lstr - 1] = '\0'; kmpreg(str, path); readeachline(path); exit(0); } if(str[lstr - 1] == '$') { beforen = 1; str[lstr - 1] = '\0'; kmpreg(str, path); readeachline(path); exit(0); } if(isdot(str)) { int fd = open(path, O_RDONLY); if(fd == -1) { exit(0); } int l = lseek(fd, 0, SEEK_END); lseek(fd, 0, 0); char *str1; str1 = (char*)malloc((l + 1) * sizeof(char)); close(fd); FILE *fp = fopen(path, "r"); if(fp == NULL) exit(0); int i = 0; while(1) { str1[i] = fgetc(fp); if(str1[i] == EOF) break; i++; } str1[i] = '\0'; fclose(fp); if(search(a, 1)) { strcpy(str1, strlwrreg(str1)); strcpy(str, strlwrreg(str)); } printf("\n"); dot(str1, str, strlen(str)); readeachline(path); exit(0); } int j = 0, k; char c[lstr][26], str1[lstr]; for(i = 0; i < lstr; i++) for(j = 0; j < 26; j++) c[i][j] = '$'; j = 0; for(i = 0; i < lstr; i++) { if(str[i] == '[') { k = 0; i++; while(str[i] != ']' && i < lstr) { c[j][k] = str[i]; i++; k++; } str1[j] = '.'; j++; continue; } str1[j] = str[i]; j++; } str1[j] = '\0'; int fd = open(path, O_RDONLY); if(fd == -1) exit(0); l = lseek(fd, 0, SEEK_END); lseek(fd, 0, 0); str = (char*)malloc((l + 1) * sizeof(char)); close(fd); FILE *fp = fopen(path, "r"); if(fp == NULL) exit(0); i = 0; while(1) { str[i] = fgetc(fp); if(str[i] == EOF) break; i++; } str[i] = '\0'; fclose(fp); if(search(a, 1)) { strcpy(str1, strlwrreg(str1)); strcpy(str, strlwrreg(str)); } printf("\n"); dotb(str, str1, strlen(str), c); readeachline(path); exit(0); } //#include <ctype.h> void LPSArray(char* pat, int M, int* lps); int c; int resize(int *index, int size) { size = size * 2; index = (int*)realloc(index, sizeof(int) * size); return size; } char *strlwrr(char *str) { unsigned char *p = (unsigned char *)str; while (*p) { *p = tolower((unsigned char)*p); p++; } return str; } int* KMPS(char* pat, char* txt, int count, int size) { char str[strlen(txt)]; strcpy(str, txt); if(search(a, 1)) { strcpy(str, strlwrr(str)); strcpy(pat, strlwrr(pat)); } int *index; index = (int*)malloc(sizeof(int) * size); int M = strlen(pat), N = strlen(txt); int lps[M]; LPSArray(pat, M, lps); int i = 0, j = 0; while (i < N) { if (pat[j] == str[i]) { j++; i++; } if (j == M) { if(count == size){ size = resize(index, size); } if( (str[i - j - 1] < 'A' || (str[i - j - 1] > 'Z' && str[i - j - 1] < 'a') || str[i - j - 1] > 'z') && search(a, 2) ) { if((str[i - j + M] < 'A' || (str[i - j + M] > 'Z' && str[i - j + M] < 'a') || str[i - j + M] > 'z') && search(a, 2)) { if(search(a, 10)) exit(0); index[count++] = i - j; if(search(a, 12) || search(a, 11)) { makeitline(str, i - j); } } } else if(!search(a, 2)) { if(search(a, 10)) exit(0); index[count++] = i - j; if(search(a, 12) || search(a, 11)) { makeitline(str, i - j); } } j = lps[j - 1]; } else if (i < N && pat[j] != str[i]) { if (j != 0) j = lps[j - 1]; else i = i + 1; } } index[0] = count; return index; } void LPSArray(char* pat, int M, int* lps) { int len = 0, i; lps[0] = 0; i = 1; while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else { if (len != 0) { len = lps[len - 1]; } else { lps[i] = 0; i++; } } } } int searchv(int index[], int v) { int i; for(i = 1; i < index[0]; i++){ if(index[i] == v) return 1; } return 0; } void printline(char* str, int i, int index[], char path[]){ int j = i; for(j = i - 1; j >= 0; j--){ if(str[j] == '\n') break; if(searchv(index, j)) { c--; return; } } int start = j + 1; for(j = i + 1; j < strlen(str) && str[j] != '\0'; j++){ if(str[j] == '\n'){ break; } } str[j] = '\n'; int end = j - 1; if(!search(a, 4)){ if(search(a, 8) || (search(a, 0) && !search(a, 7))) printf("%s%s%s: ", KMAG, path, KNRM); if(!search(a, 11) && !search(a, 12)) { for(j = start; j <= end; j++){ printf("%c", str[j]); } printf("\n"); } } } void printvline(char* str, int index[], int j, int ii, int n, char path[]){ int i = j - 1; if(j == 0) return; i = j - 1; while(i > 0 && str[i] != '\n'){ if(searchv(index, i)) return; i--; } int end = i; if(i == 0) return; i--; while(i > 0 ){ if(searchv(index, i)) break; i--; } if(i != 0) while(str[i] != '\n' && str[i] != '\0'){ i++; } if(i == 0 && searchv(index, i)) { while(str[i] != '\n'){ i++; } } int start = i; if(!search(a, 4)) { if(start != 0) { start++; } if((search(a, 8) || (search(a, 0) && !search(a, 7)) ) && start < end ) printf("\n%s%s%s ", KMAG, path, KNRM); if(search(a, 5) && ii == 1){ if(!i) printf("\n%s0:%s", KGRN, KWHT); else printf("\n%s%d:%s", KGRN, start + 1, KWHT); } for(i = start; i < end; i++){ if(str[i - 1] == '\n' && (search(a, 8) || (search(a, 0) && !search(a, 7))) && i != start) printf("%s%s%s ", KMAG, path, KNRM); if(str[i - 1] == '\n' && search(a, 5) ) { printf("\n%s%d:%s", KGRN, i, KWHT); } printf("%c", str[i]); } } else { for(i = start + 1; i < end; i++) { if(str[i] == '\n') vcount++; } } if(ii == n - 1 ){ i = j; while(1) { if(str[i] == '\n' || str[i] == '\0') break; i++; } if(str[i + 1] == '\0' || str[i] == '\0') return; else { i++; printf("\n"); if(search(a, 8) || (search(a, 0) && !search(a, 7))) printf("%s%s%s ", KMAG, path, KNRM); while(1){ if(str[i] == '\0') break; if(str[i] == '\n') vcount++; if(str[i] == '\n' && (search(a, 8) || (search(a, 0) && !search(a, 7)) )&& str[i + 1] != '\0') { printf("\n%s%s%s ", KMAG, path, KNRM); } else if(str[i] == '\n') { printf("\n"); } if(str[i] == '\n' && str[i + 1] == '\n') break; if(!search(a, 4)) { if(str[i - 1] == '\n' && search(a, 5)) { printf("\n%s%d%s:", KGRN, i, KWHT); } if(str[i] != '\n') printf("%c", str[i]); } i++; } printf("\n"); vcount++; vcount++; } return; } } int byteoffset(char str[], int i, int index){ while(str[i] != '\n' && i > 0) { i--; } if(i + 1 == 1) return 0; return i + 1; } int totallines(char str[]) { int l = strlen(str); int i, countc = 0; for(i = 0; i < l; i++) { if(str[i] == '\n') { countc++; } } return countc + 1; } int kmp(char *pat, char *path) { int fd = open(path, O_RDONLY); if(fd == -1) { nofile = 1; return 0; } int l = lseek(fd, 0, SEEK_END); char *str, *str1; str = (char*)malloc((l + 1) * sizeof(char)); lseek(fd, 0, 0); close(fd); FILE *fp = fopen(path, "r"); if(fp == NULL){ printf("\n No such file or directory \n"); exit(2); } int i = 0; while(1) { str[i] = fgetc(fp); if(str[i] == EOF) break; i++; } str[i] = '\0'; int numcount = 0; i = 0; int *index = KMPS(pat, str, 1, 20); c = index[0]; //printf("\n%d$$$ \n", c); i = 0; if(!search(a, 11) && !search(a, 12)) { if(search(a, 6) && !search(a, 11) && !search(a, 12)) { /* if(c == 1){ printf("sad"); readeachline(path); } */ if(search(a, 8)) { if(index[0] == 1) { // puts(str); readeachline(path); exit(0); } for(i = 1; i < index[0]; i++) { if(i + 1 == num) { exit(0); } printvline(str, index, index[i], i, index[0], path); } } else { if(index[0] == 1) { // puts(str); readeachline(path); exit(0); } for(i = 1; i < index[0]; i++) { if(i + 1 == num) { exit(0); } printvline(str, index, index[i], i, index[0], path); if(!search(a, 4)) printf("\n"); } } } else { if(search(a, 8)) { for(i = 1; i < index[0]; i++) { if(i + 1 == num) { exit(0); } if(search(a, 5) && !ef) printf("\n%s%d:%s ", KGRN, byteoffset(str, index[i], i), KWHT); printline(str, index[i], index, path); } } else { for(i = 1; i < index[0]; i++) { if(i == num + 1) { exit(0); } if(search(a, 5) && !ef) printf("\n%s%d:%s ", KGRN, byteoffset(str, index[i], i), KWHT); printline(str, index[i], index, path); } } } } if(search(a, 4) && !ef) { if(search(a, 8) || (search(a, 0) && !search(a, 7))) printf("\n %s%s%s:%s", KMAG, path, KGRN, KWHT); if(search(a, 6)) { vcount = totallines(str); if(strlen(pat) == 1){ vcount = vcount - c; vcount = vcount - 2; printf("\n%d\n", vcount + 2); } else{ vcount = vcount - c; vcount = vcount - 1; printf("\n%d\n", vcount + 1); } } else if(strlen(pat) == 1){ printf("%d\n", c - 2); } else{ printf("%d\n", c - 1); } } normal_c = normal_c + c - 1; return 0; } void listFilesRecursively(char *path); void rec(char path[]) { listFilesRecursively(path); } void listFilesRecursively(char *basePath) { char path[1000]; struct dirent *dp; DIR *dir = opendir(basePath); if (!dir) return; while ((dp = readdir(dir)) != NULL) { if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0) { strcpy(path, basePath); strcat(path, "/"); strcat(path, dp->d_name); if(isfile(path)) { kmp(word[0], path); } listFilesRecursively(path); } } closedir(dir); } void showhelp(){ printf("%s", KRED); printf(" Usage: grep [OPTION]... PATTERN [FILE]... \n Search for PATTERN in each FILE.\n Example: grep -i 'hello world' main.c \n"); printf("%s", KGRN); printf(" -r traverse through directories nd grep\n"); printf(" -w force PATTERN to match only whole words\n"); printf(" -m[NUM] stop after NUM matches\n"); printf(" -q returns a value so that grep can be used by other programs\n"); printf(" -i ignore case distinctions\n"); printf(" -v select non-matching lines\n"); printf(" -n print line number with output lines\n"); printf(" -c print only a count of matching lines per FILE\n"); printf(" -b print the byte offset with output lines\n"); printf(" -f search pattern from file\n"); printf(" -e to match word starting with non-alphabet character or for searching multiple patterns\n"); printf(" -h suppress the file name prefix on output\n"); printf(" -H print the file name for each match\n"); printf("%s", KYEL); printf(" for regular expressions\n"); printf(" ^word grep only those lines whose starting word is word\n"); printf(" word$ grep only those lines whose ending word is word\n"); printf(" w.r. . can hold any values\n"); printf(" [abc][cd]s choose between characters in brackets and grep\n"); printf("%s Can use any combinations of above commands \n %s eg:- ./project word -v -i -w -c file.txt\n", KCYN, KGRN); } int main(int argc, char *argv[]){ if(argc == 1) { printf("use ./try --help for help \n"); return 2; } if(!strcmp(argv[1], "--help")) { showhelp(); return 0; } if(argc < 3) { printf("\n bad arguements \n"); return 130; } char files[10][20], options[10][3]; int i, count_file = 0, count_word = 0; strcpy(word[0], " "); strcpy(word[1], " "); for(i = 1; i < argc; i++){ if(isword(argv[i])) strcpy(word[count_word++], argv[i]); if(isoption(argv[i])) strcpy(options[count_option++], argv[i]); if(isfile(argv[i])) strcpy(files[count_file++], argv[i]); } a = decide_priority(options, count_option); head = getNewTrieNode(); if(isreg(argv[1])) { int dotc = 0; for(i = 0; i < strlen(argv[1]); i++) { if(argv[1][i] == '.') dotc++; } if(dotc >= 2) { strcpy(files[0], files[1]); } reg(argv[1], files[0]); //everthing about reg return 0; } if(num != INT_MAX && !(search(a, 9))){ printf("%d in command without using -m", num); exit(0); } if(count_file == 0 && search(a, 10)) { return 2; } FILE *fp; fp = fopen("temp.txt", "w"); if(search(a, 12) || search(a, 11)) { ef = 1; } if(search(a, 12) && !search(a, 11)){ for(i = 1; i < argc; i++){ if(!strcmp(argv[i], "-e") && (isword(argv[i + 1]) || ( (strlen(argv[i + 1]) > 2) && argv[i][0] == '-' ) ) ){ kmp(argv[i + 1], files[0]); } } readeachline(files[0]); } if(search(a, 12)){ for(i = 1; i < argc; i++){ if(!strcmp(argv[i], "-e") && (isword(argv[i + 1]) || ( (strlen(argv[i + 1]) > 2) && argv[i][0] == '-' ) ) ){ fputs(argv[i + 1], fp); fputc('\n', fp); } } } char str[100]; if(search(a, 11)){ FILE *fp1 = fopen(files[0], "r"); if(!fp1) { printf("File not found \n"); exit(0); } while(fgets(str, 100, fp1)){ fputs(str, fp); } } fclose(fp); if(search(a, 11) || search(a, 12)) { if(count_file == 1 && search(a, 11)) { printf("\n Bad arguements only one file specified \n"); exit(0); } fp = fopen("temp.txt", "r"); while(fgets(str, 100, fp)){ str[strlen(str) - 2] = '\0'; kmp(str, files[1]); } } if((search(a, 11) && search(a, 12)) || search(a, 11)) { readeachline(files[1]); exit(0); } if(!strcmp(word[1], " ")){ for(i = 0; i < count_file; i++) kmp(word[0], files[i]); } if(!strcmp(word[1], " ")) strcpy(word[1], word[0]); if(a[0] == 0){ rec(word[1]); } fclose(fp); remove("temp.txt"); if(nofile && search(a, 10)) { return 2; } if(search(a, 10)) { return 1; } return 0; }
C
#include<stdio.h> int main() { float a=62.15269; printf("\"Hello world\"");// Escape sequence printf("\ngitam\'s college"); printf("\n %.2f",a); }
C
#if 0 William Daniel Taylor 2/26/18 #endif #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> int main(int argc, char *argv[]) { char *address; address = argv[1]; //socket int clientSocket; clientSocket = socket(AF_INET, SOCK_STREAM, 0); //connect to an address struct sockaddr_in remote_address; remote_address.sin_family = AF_INET; remote_address.sin_port = htons(80); /*converts string address to address structure (initial_address, where_to_store) */ inet_aton(address, &remote_address.sin_addr.s_addr); //connect connect(clientSocket, (struct sockaddr *) &remote_address, sizeof(remote_address)); //request and response char request[] = "GET / HTTP/1.1\r\n\r\n"; char response[4096]; //send and recieve send(clientSocket, request, sizeof(request), 0); recv(clientSocket, &response, sizeof(response), 0); //print result and close printf("Response from the server: %s\n", response); close(clientSocket); return 0; }
C
#include <stdio.h> int main() { int p; scanf("%d", &p); if (p >= 90) { printf("AA\n"); } else if (p >= 80 && p <= 89) { printf("A\n"); } else if (p >= 70 && p <= 79) { printf("B\n"); } else if (p >= 60 && p <= 69) { printf("C\n"); } else if (p <= 59) { printf("D\n"); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define TAM_LINHA 100 #define TAM_ELEMENTO 30 #define TAM_NOME 100 #define TAM_GENERO 30 #define TAM_TABELA_HASH 29000 /// ******************************************************************** /// Informaes da Tabela Hash; /// ******************************************************************** // Informaes da Lista Encadeada de Generos struct INFO_GENERO{ char Genero[TAM_GENERO]; }; typedef struct INFO_GENERO GENEROS; // Lista Encadeada dos Generos dos Filmes // Contem: // - Lista encadeada de Generos; // - Ponteiro para o proximo genero; struct PONTEIRO_GENERO{ GENEROS Generos; struct PONTEIRO_GENERO *Prox; }; typedef struct PONTEIRO_GENERO PT_GENERO; // -------------------------------------------------------------------------------------------- // Elementos da Tabela Hash: cada elemento da tabela uma estrutura do tipo: FILME_HASH // Cada elemento possui: // - O ID do filme: FilmeID; // - A quantidade de avaliaes do filme: CountRating; // - A avaliao media do filme: Rating; // - Uma lista encadeada com os generos do filme: Generos; struct INFO_HASH{ int FilmeID; // Usado como chave da Tabela Hash int CountRating; // Quantidade de avaliaes do filme double Rating; GENEROS *Generos; // Lista encadeada dos generos do filme }; typedef struct INFO_HASH FILME_HASH; // Inicializa a Tabela Hash Aberta void InicializaTabela(FILME_HASH *TabelaHash); void AbreArquivoRating(char NomeArquivo[], FILME_HASH *TabelaHash); void AbreArquivoMovie(char NomeArquivo[], FILME_HASH *TabelaHash); void InsereTabelaHash(FILME_HASH *TabelaHash, FILME_HASH Novo); void PrintaFilme(FILME_HASH Filme); int Hashing(int FilmeID); FILME_HASH InicializaFilme(FILME_HASH Novo); PT_GENERO *CriaListaGeneros(PT_GENERO *Lista, char Elemento[]);
C
#include <stdio.h> #include <string.h> void main(void) { char string[]= "3 lions, 5 elephants 4 deer"; char*find = "0123456789"; int index; index = strcspn(string, find); printf("We fond number on %d\n",index); }
C
#include "funcoes.h" int main(int argc, char** argv) { int n,e,r; char cmd[COMMAND+1], *info; /*cmd e a variavel que guarda os comandos(so pode ter 11 no maximo)*/ queue_ptr user_vec; scanf("%d", &n); user_vec = (queue_ptr) calloc( n,sizeof(struct queue)); scanf("%s", cmd); while(strcmp(cmd,"quit")!=0) { if(strcmp(cmd,"send")==0) { info=(char*)(malloc(sizeof(char)*(MENSAGEM+1))); scanf("%d", &e); scanf("%d", &r); getchar(); fgets(info,MENSAGEM,stdin); user_vec[r] = send(e,r,info,user_vec[r]); free(info); } if(strcmp(cmd,"process")==0) { scanf("%d", &r); user_vec[r]=process(user_vec[r]); } if(strcmp(cmd,"list")==0) { scanf("%d", &r); list(user_vec[r]); } if(strcmp(cmd,"listsorted")==0) { scanf("%d", &r); listsorted( user_vec[r]); } if(strcmp(cmd,"kill")==0) { scanf("%d", &r); kill( user_vec, r); } scanf("%s", cmd); } quit(user_vec,n); return 0; }
C
/*LINTLIBRARY*/ #include "port.h" #ifdef LACK_SYS5 /* * memcpy - copy bytes */ VOIDSTAR memcpy(dst, src, size) VOIDSTAR dst; CONST VOIDSTAR src; SIZET size; { register char *d; register CONST char *s; register SIZET n; if (size <= 0) return dst; s = src; d = dst; if (s <= d && s + (size-1) >= d) { /* Overlap, must copy right-to-left. */ s += size-1; d += size-1; for (n = size; n > 0; n--) *d-- = *s--; } else for (n = size; n > 0; n--) *d++ = *s++; return dst; } #endif
C
/* Write a C Program to input a number and find all the factors of a number ? */ #include<stdio.h> void main() { int n,i; printf("Enter the value : \n"); scanf("%d",&n); for(i=1;i<=n;i++) { if(n%i==0) printf("%d ",i); } }
C
// // Created L1MeN9Yu on 2017/11/24. // #include <sys/errno.h> #include <sys/stat.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include "gtr_file_utilty.h" off_t gtr_get_file_size(const char *file_path) { struct stat st; if (stat(file_path, &st) == 0) { return st.st_size; } printf("Cannot determine size of %s: %s\n", file_path, strerror(errno)); return 0; } void gtr_create_directory_if_not_exist(const char *directory_path) { struct stat st = {0}; if (stat(directory_path, &st) == -1) { mkdir(directory_path, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); } } char *get_app_temp_directory(void) { char *env_temp_dir = getenv("TMPDIR"); if (!env_temp_dir) { env_temp_dir = P_tmpdir; } const char *temp_dir_name = "/gtr_temp"; char *temp_dir = malloc(sizeof(char) * (strlen(env_temp_dir) + strlen(temp_dir_name) + 1)); strcpy(temp_dir, env_temp_dir); strcat(temp_dir, temp_dir_name); return temp_dir; }
C
#ifndef VECTOR_GUARD #define VECTOR_GUARD #include<stdlib.h> #include<assert.h> typedef struct{ unsigned int size; int *data; unsigned int count; }vector; //Function Prototypes void __vector_resize(vector* info); vector vector_init(); void vector_push(vector* info,int data); int vector_pop(vector* info); int vector_get_index(vector* info,unsigned int index); void decon_vector(vector* info); void vector_insert(vector* info, int data, unsigned int index); vector vector_copy(vector* info); vector intarr_to_vector(int* arr,unsigned int count); void vector_sort(vector* info); //MIN TO MAX //For sorting void insert_heap(int* heap,int data); void swap(int* a,int* b); int pop_min_heap(int* heap); #endif
C
#pragma once struct Index { int id; int address; int isExist; }; struct Team { int id; char name[16]; int wins; long firstPlayerAddress; int playerNum; }; struct Player { int teamId; int id; char surname[16]; char role[16]; int isExist; long thisAddress; long nextPlayerAddress; };
C
#include<stdio.h> int main() /*Program ProgV*/ { /*DECLARCATION_BLOCK*/ int integer, i; /*CODE_BLOCK*/ scanf("%i", &integer); if(integer <= 5 || integer >= 12) { printf("%i", integer); } printf("%f", 35.000000); printf("\n"); /*for control vars*/ register int _by; static int _true=(1==1); for (integer = (-1); _by = (-1), (integer - (-5))*(_by >0) - (_by<0/_true) <=0; integer += _by) { printf("%i", integer); printf("\n"); } i = -1; for (integer = (i * i * i); _by = (i * i * i * i * i), (integer - (i * i * (i + i + i + i + i) ))*(_by >0) - (_by<0/_true) <=0; integer += _by) { printf("%i", integer); printf("\n"); } }/*End of Program*/
C
/*Enter number of rows : 3 3 2 1 2 3 2 1 2 1 */ #include<stdio.h> #include<conio.h> int main() { int r; char c; printf("Enter start aplabet :"); scanf("%[^\n]c",&c); printf("\nEnter number of rows :\t"); scanf("%d",&r); printf("\n"); pattern(r); return 0; } int pattern(int rr) //void pattern(int rr,char cc) { int i,j; for(i=rr;i>0;i--) { for(j=1;j<=rr-i;j++) printf("\t"); for(j=i*-1;j<=2*i-1;j++) { if(j&& (j!=-1)&&(j<=i)) { printf("%d\t", abs(j)); //printf("%c ", cc+abs(j)-1); } } printf("\n"); } }
C
// // Created by Bourne on 29/03/2018. // #include <stdio.h> void output(int i, int j) { printf("i= %d, j = %d\n", i, j); } int main(int argc, char* argv[]) { int a[3] = {0, 1, 2}; printf("%d\n", sizeof(a)); // 数组大小 printf("%d\n", sizeof(&a)); // 指针大小 printf("%d\n", *(a + 1)); // 输出第二个元素 // int i = 0; // output(i++, i); // 0, 1 // // i = 0; // output(++i, i); // 1, 1 // // i = 0; // output(i, ++i); // 0, 1 // // i = 0; // output(i, i++); // 0, 0 int i = 0; int x = (++i)++; // 1, 在最近的编译器中,这些操作都不被允许,会编译错误 printf("%d\n", x); //x = ++(i++); // ++得到的是一个右值,++操作需要的是一个左值。i++返回的是一个右值,不对再++了 char j = 0; (int)j = 20; // assignment to cast is illegal, lvalue casts are not supported printf("%d\n", j); return 0; }
C
#include<stdio.h> #include<conio.h> struct stack { float data[10]; int top; }s; void push(float x) { s.data[++s.top]=x; } int pop() { return(s.data[s.top--]); } float fix(char symbol, float op1, float op2) { switch(symbol) { case '+':return(op1 + op2); case '-':return(op1 - op2); case '/':return(op1 / op2); case '*':return(op1 * op2); } return 0; } void main() { s.top = -1; char postfix[10],symbol; int len, i = 0; float op2, op1, r; printf("Enter postfix expression\n"); scanf("%s",postfix); len = strlen(postfix); for (i = 0; postfix[i] != '\0'; i++) { symbol = postfix[i]; if((symbol=='-')||(symbol == '+')||(symbol == '*')||(symbol == '/')) { op2 = pop(); op1 = pop(); r = fix(symbol, op1, op2); } else { push(r); push(symbol-'0'); } } r = pop(); printf("answer is%f\t", r); getch(); }
C
#include "uart.h" int putchar(char c) { uart_putchar(c); return 0; } char getchar(void) { return uart_getchar(); } int puts(const char * s) { while (*s) { if (*s == '\n') uart_putchar('\r'); uart_putchar(*s); s++; } return 0; } char *gets(char * s) { char * buf = s; char c; while (1) { c = uart_getchar(); // if c is user input "Enter", then end if (c == '\r') break; // if c is like a, b, c, d, then fill // if c is not '\b' if (c != '\b') { *buf++ = c; uart_putchar(c); } else { // if buf > s if (buf > s) { buf--; //*buf = ' '; uart_putchar('\b'); uart_putchar(' '); uart_putchar('\b'); } } } *buf = '\0'; uart_putchar('\r'); uart_putchar('\n'); return buf; }
C
#include "malloc.h" int set_tinyheader(t_list *lst) { int i; i = 1; lst->content[0] = TRUE; while(i < 127) { lst->content[i] = FALSE; i++; } return(1); } void *first_tiny(size_t size) { void *str; int f; str = mmap(0, PSIZE * 2, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); if(str == MAP_FAILED) { printf("error MAP_FAILED"); return(NULL); } else { zone.tiny = ft_lstnew(str, PSIZE * 2); f = set_tinyheader(zone.tiny); return(str + 128); } } void *another_tiny(size_t size) { void *str; int f; t_list *lst; t_list *lst2; str = mmap(0, PSIZE * 2, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); if(str == MAP_FAILED) { printf("error MAP_FAILED"); return(NULL); } else { lst2 = browse_lst(zone.tiny); lst = ft_lstnew(str, PSIZE * 2); f = set_tinyheader(lst); lst2->next = lst; return(lst->content + 128); } } void *tiny_exist(size_t size) { t_list *lst; int i; void *str; i = 0; lst = ft_lstiter(zone.tiny, one_place_atleast); if(lst == NULL) { str = another_tiny(size); } while(i < 126) { if(lst->content[i] == FALSE) { printf("&&&&%d&&&&", i); zone.tiny->content[i] = TRUE; return(lst->content + (128 + (64 * i))); } i++; } return(lst->content); } void *size_tiny(size_t size) { if(zone.tiny) { printf("1\n"); return(tiny_exist(size)); } else { printf("2\n"); return(first_tiny(size)); } }
C
#include <stdio.h> #include <windows.h> #include <dirent.h> #include <stdbool.h> #include "saisie.h" #include "affichage.h" #include "sudoku.h" #define COLONNE 47 #define LIGNE 75 ///Commande d'affichage basique void ligne(void){ for(int i=0;i<COLONNE;i++){ printf("="); } printf("\n"); } void ligne_c(const char c){ for(int i=0; i<COLONNE; i++) printf("%c",c); printf("\n"); } void ligneLimite(const int lenght){ for(int i=0;i<lenght;i++){ printf("="); } } void ligneLimite_c(const int lenght, const char c){ for(int i=0;i<lenght;i++){ printf("%c",c); } } void titre(const char* titre){ int size = strlen(titre); ligne(); ligneLimite((COLONNE-size)/2); printf("%s", titre); if((COLONNE - size)%2 != 0) ligneLimite(((COLONNE-size)/2)+1); else ligneLimite(((COLONNE-size)/2)); ligne(); printf("\n"); } void center(const char* texte_centrer){ int size = strlen(texte_centrer); ligneLimite_c((COLONNE-size)/2,' '); printf("%s",texte_centrer); if((COLONNE - size)%2 != 0) ligneLimite_c(((COLONNE-size)/2)+1,' '); else ligneLimite_c(((COLONNE-size)/2),' '); printf("\n\n"); } void consoleParam(void){ SetConsoleTitle("SUDOKU"); system("mode con lines=75 cols=47"); } ///Fonction d'affcihage des ecrans void lister_grille(void){ //On ouvre le repertoire DIR* grille_dir = opendir("Grille/"); if(grille_dir == NULL){ perror(""); exit(1); } //Liste des fichier struct dirent* fichier_lu = NULL; while((fichier_lu = readdir(grille_dir)) != NULL){ if(strcmp(fichier_lu->d_name,".") != 0 && strcmp(fichier_lu->d_name,"..")){ printf(" %s\n", fichier_lu->d_name); } } //Fermeture du repertoire if(closedir(grille_dir) == -1){ perror(""); exit(-1); } ligne(); printf("\n"); closedir(grille_dir); } void play(void){ printf("play"); } void print(const char* name_file){ Sudoku* SUDOKU = new_Sudoku(); SUDOKU = chargeSudokuFromFile(concat("Grille/", name_file)); if(SUDOKU != NULL){ afficher_grille(SUDOKU); Sudoku_end(SUDOKU); } } void listerCmd(const int nbr_elem, char* tableauCmd[]){ printf("Liste des commandes autorise : \n"); for(int i=0;i<nbr_elem;i++){ printf(" - %s\n",tableauCmd[i]); } printf(" - man [commande] : afficher le manuel\n\n"); ligne(); }
C
#include<stdio.h> int main() { struct student { int rollno; char name[80]; char sec; }; struct student s1; printf("\n enter the rollnumber"); scanf("%d",&s1.rollno"); printf("\n enter the name"); scanf("%s",&s1.name); printf("\n enter the sec"); scanf("%s",&s1.sec); printf("\n ******student details******"); printf("\n rollno=%d",s1.rollno); printf("\n name=%s",s1.name); printf("n sec=%s",s1.sec); } 5%%s
C
ElementType Find( List L, int m ) { PtrToNode mthNode=NULL, node; //因为L带头结点,所以node为L的next,否则为L node =L->Next; //遍历链表 while(node) { //将计数器减一 --m; //如果当前计数器为0,表示正好访问过m个结点,那么第一个结点就是当前的倒数第m个结点 if(m==0) mthNode = L->Next; //如果计数器为负,则表示要把倒数第m个结点往后挪一个结点 else if(m<0) mthNode = mthNode->Next; //当前结点正常遍历 node = node->Next; } //如果倒数第m个结点存在 if(mthNode) return mthNode->Data; else return ERROR; }
C
#include <stdlib.h> #include <stdio.h> #include "print.h" #include "parser.h" #include "eval.h" static cell_t* call_dispatch(mem_t* mem, cell_t* callable, cell_t* args); static cell_t* call_lambda(mem_t* mem, cell_t* arg_names, cell_t* arg_vals, cell_t* body); static cell_t* call_macro(mem_t* mem, cell_t* arg_names, cell_t* arg_vals, cell_t* body); static cell_t* eval_progn(mem_t* mem, cell_t* body); static cell_t* eval_list(mem_t* mem, const cell_t* list); void load_file(mem_t* mem, const char* path) { FILE* f = fopen(path, "r"); cell_t* cell = NULL; if(f == NULL) error("file to load not found: %s", path); while(cell = parse_one(mem, f, NULL)) { print_sexp(cell); printf(" ~> "); print_sexp(eval(mem, cell)); printf("\n"); } fclose(f); } cell_t* eval(mem_t* mem, cell_t* exp) { debug("trying to eval %s", sprint_sexp(exp)); switch(cell_type(exp)) { case NUM: case NIL: case PRIMITIVE: case LAMBDA: case MACRO: return exp; case SYM: if(exp == mem->gvar) return mem->global_vars; if(cdr(exp) == mem->unbound) { printf("undefined variable: "); print_sexp(exp); printf("\n"); error("fatal error. "); } return cdr(exp); case PAIR: return call_dispatch(mem, car(exp), cdr(exp)); } } static cell_t* call_dispatch(mem_t* mem, cell_t* callable, cell_t* args) { callable = eval(mem, callable); if(callable == mem->unbound) error("function not found"); switch(cell_type(callable)) { case PRIMITIVE: { prim_t* fun = CAST(prim_t*, UNTAG(callable)->car); return fun(mem, args); } case LAMBDA: // a lambda has its car pointing to a // ((arg1 arg2 ...) (exp1 exp2 ...)) list return call_lambda(mem, car(car(callable)), args, (cdr(car(callable)))); case MACRO: return call_macro(mem, car(car(callable)), args, (cdr(car(callable)))); default: printf("callable: "); print_sexp(callable); printf("\n"); error("expected a callable, got a %s", cell_type_string(cell_type(callable))); break; } } static cell_t* call_lambda(mem_t* mem, cell_t* arg_names, cell_t* arg_vals, cell_t* body) { // push the initial value of the params mem_stack_push_params(mem, arg_names); // set params while(not nullp(arg_names)) { // TODO error handling cell_t* name = car(arg_names); if(name == mem->and_rest) // deal with variable number of arguments { name = car(cdr(arg_names)); UNTAG(name)->cdr = CAST(val_t, eval_list(mem, arg_vals)); break; } else UNTAG(name)->cdr = CAST(val_t, eval(mem, car(arg_vals))); arg_names = cdr(arg_names); arg_vals = cdr(arg_vals); } // eval body cell_t* ret = eval_progn(mem, body); // pop back the initial value of the params mem_stack_pop_params(mem); return ret; } static cell_t* call_macro(mem_t* mem, cell_t* arg_names, cell_t* arg_vals, cell_t* body) { // push the initial value of the params mem_stack_push_params(mem, arg_names); // set params (not evaluated !) while(not nullp(arg_names)) { // TODO error handling cell_t* name = car(arg_names); if(name == mem->and_rest) // deal with variable number of arguments { name = car(cdr(arg_names)); UNTAG(name)->cdr = CAST(val_t, arg_vals); break; } else UNTAG(name)->cdr = CAST(val_t, car(arg_vals)); arg_names = cdr(arg_names); arg_vals = cdr(arg_vals); } // create body cell_t* ret = eval_progn(mem, body); // pop back the initial value of the params mem_stack_pop_params(mem); // eval body in the upper scope ret = eval(mem, ret); return ret; } static cell_t* eval_progn(mem_t* mem, cell_t* body) { cell_t* ret = mem->nil; while(not nullp(body)) { ret = eval(mem, car(body)); body = cdr(body); } return ret; } static cell_t* eval_list(mem_t* mem, const cell_t* list) { if(nullp(list)) return mem->nil; cell_t* ret = new_pair(mem, mem->nil, mem->nil); cell_t* cur = ret; while(not nullp(list)) { UNTAG(cur)->cdr = CAST(val_t, new_pair(mem, eval(mem, car(list)), mem->nil)); list = cdr(list); cur = CAST(cell_t*, UNTAG(cur)->cdr); } return cdr(ret); }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <string.h> void main() { int i; pid_t pid; char input[100]; fprintf(stderr, "richegg-shell $ "); while(scanf("%s", input)) { if (strcmp(input, "exit") == 0) { exit(0); } pid = fork(); if (pid == 0) { execlp(input, input, NULL); exit(0); } else { wait(NULL); } fprintf(stderr, "richegg-shell $ "); } }
C
#include "thread.h" #include <stdio.h> #include <stdlib.h> #include <string.h> /* * Variables */ // There are total of 2048 pages const int NUM_PAGES; int currentThreadId = 1; /* * Implementations */ Thread *createThread() { Thread *ret = malloc(sizeof(Thread)); bzero(ret, sizeof(Thread)); ret->threadId = currentThreadId; currentThreadId++; // init page table ret->pageTable = (PageTableEntry *)malloc(sizeof(PageTableEntry) * NUM_PAGES); for (int i = 0; i < NUM_PAGES; i++) { ret->pageTable[i].physicalFrameNumber = -1; // default: not assigned ret->pageTable[i].present = 0; // default: not present on physical memory } // init allocation lists ret->stackAllocationList = createStackAllocationList(); ret->heapAllocationList = createHeapAllocationList(); return ret; } void destroyThread(Thread *thread) { // This is line is ABSOLUTELY REQUIRED for the tests to run properly. This // allows the thread to finish its work DO NOT REMOVE. if (thread->thread) pthread_join(thread->thread, NULL); free(thread->pageTable); destroyAllocationList(thread->stackAllocationList); destroyAllocationList(thread->heapAllocationList); free(thread); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* paralel_path.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: omotyliu <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/03/25 15:55:10 by omotyliu #+# #+# */ /* Updated: 2017/03/25 15:55:11 by omotyliu ### ########.fr */ /* */ /* ************************************************************************** */ #include "lemin.h" static int if_list_parallel(t_parall_path *lst, t_sorted_list *path_to_add) { t_parall_path *temp; int i; i = 1; temp = lst; if (!path_to_add->splited_steps) path_to_add->splited_steps = ft_strsplit(path_to_add->steps, '#'); while (temp) { while (path_to_add->steps[i]) { if (path_to_add->splited_steps[i + 1] == 0) break ; if (ft_strstr(temp->parallel_path, path_to_add->splited_steps[i])) return (0); i++; } i = 0; temp = temp->next; } return (1); } static int if_parallel(t_sorted_list *path1, t_sorted_list *path2) { int i; if (!path1->splited_steps) path1->splited_steps = ft_strsplit(path1->steps, '#'); i = 1; while (path1->splited_steps[i]) { if (path1->splited_steps[i + 1] == 0) break ; if (ft_strstr(path2->steps, path1->splited_steps[i])) return (0); i++; } if (!if_list_parallel(path1->parallel, path2)) return (0); return (1); } static void add_parallel(t_sorted_list *path1, t_sorted_list *path2) { add_parall(&path1->parallel, new_parall(path2->steps, path2->len)); path1->gen_len += path2->len; path1->num_of_paral++; } void find_parallel(t_sorted_list *lst, int flow) { t_sorted_list *temp; t_sorted_list *inner; temp = lst; while (temp) { inner = temp->next; while (inner) { if ((flow = calc_flow_cap(temp, inner)) < temp->flow_cap) if (if_parallel(temp, inner)) { add_parallel(temp, inner); temp->flow_cap = flow; } if ((flow = calc_flow_cap(inner, temp)) < inner->flow_cap) if (if_parallel(inner, temp)) { inner->flow_cap = flow; add_parallel(inner, temp); } inner = inner->next; } temp = temp->next; } }
C
#include <stdio.h> int main() { int arr[100], n; do { printf("Enter number of elements: "); scanf("%d", &n); if (n > 100) printf("Please enter a size within 100 elements.\n"); } while (n > 100); printf("\nEnter elements:\n"); for (int i=0; i<n; i++) scanf("%d", &arr[i]); for (int i=0; i<n-1; i++) { for (int j=0; j<n-i-1; j++) { if (arr[j] >= arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } printf("\nHere goes the sorted array:\n"); for (int i=0; i<n; i++) printf("%d\n", arr[i]); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char **argv) { char *data; int magic; sscanf(argv[1], "%s", data); sscanf(argv[2], "%d", &magic); if (magic == 0x31337987) { puts("Found VERY specific magic number"); } if (magic < 100 && magic % 15 == 2 && magic % 11 == 6) { puts("Found convoluted magic number"); } int count = 0; for (int i = 0; i < 100; i++) { if (data[i] == 'Z') { count++; } } if (count >= 8 && count <= 16) { puts("Found correct range of Zs"); } return 0; }
C
#pragma once #include <pthread.h> //#include <sched.h> //#include <semaphore.h> typedef int counter_t; /*Sets val to 0 and initializes the mutex.*/ void init_counter(counter_t *counter); /*Increments val by one.*/ void increment_counter(counter_t *counter); /*Decrements val by one*/ void decrement_counter(counter_t *counter); /*Returns the current value of val*/ int get_counter(counter_t *counter); /*Tests the current value of val against test_value and if equal sets it to new_value. Must return 0 upon failure and 1 upon success.*/ int test_and_set_counter(counter_t *counter, int test_value, int new_value);