language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include "shell.h" /** * main - Imput function for the program * @argc: ARGument Counter * @argv: ARGument Vector * @env: ENviroment Variables * Return: Always 0 (success) */ int main(int argc, char *argv[], char *env[]) { _getenv(env); (void)argc; prompt(argv); return (0); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> // Декларация и инициализация разрешенных на вход флагов const char * const allowedFlags[] = { "--size", "--sort", "--antg" }; const unsigned int const allowedFlagsLength = sizeof allowedFlags / sizeof allowedFlags[0]; void validateFlags(const char * const flags[], const int const length) { bool flagExists = false; int incorrectFlagIndex = -1; // Элемент с индексом 0 в массиве флагов - это имя нашей программы, // пропускаем его for (int i = 1; i < length; i++) { // Обнуляем состояние флага сигнализирующего // присутствие переданного аргумента в массиве разрешенных аргументов flagExists = false; // Проходим по массиву разрешенных флагов и ищем вхождение аргумента for (int j = 0; j < allowedFlagsLength; j++) { // Проверяем, равны ли строки, если да, то // меняем состоянии на true, и обнуляем флаг incorrectFlagIndex if (strcmp(flags[i], allowedFlags[j]) == 0) { // Фиксируем совпадение, аргумент найден в списке разрешенных! flagExists = true; incorrectFlagIndex = -1; } else incorrectFlagIndex = i; } // Если флаг не найден (состояние flagExists осталось прежним - false) и // incorrectFlagIndex не равен -1(то есть был взят индекс некорректного флага), то... if (!flagExists && incorrectFlagIndex != -1) { printf("[-] Error: %s incorrect flag was given!\n", flags[incorrectFlagIndex]); // Не даем программе двигаться с ошибкой дальше // Завершаем выполнение программы с кодом ошибки exit(EXIT_FAILURE); } } } int main(const int const argc, const char * const argv[]) { if (argc > 1) validateFlags(argv, argc); printf("[+] Congratulations!\n"); return EXIT_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> #include "head.h" int compare(tree R,tree R2) { if((R==NULL)&&(R2==NULL)) return 1; else if (R->val!=R2->val) return 0 ; else { return compare(R->l,R2->l) && compare(R->r,R2->r); } } tree add(tree R,int val) { struct node* neww; if(R==NULL) { neww=(struct node*)malloc(sizeof(struct node)); neww->val=val; neww->l=NULL; neww->r=NULL; R=neww; } else { if(val<=R->val) R->l=add(R->l,val); else R->r=add(R->r,val); } return R; } int main() { tree R=NULL ; tree R2=NULL; int i,val ; // to fill a tree with 7 nodes for example for(i=1;i<=7;i++) { printf("val of tree1= "); scanf("%d",&val); R=add(R,val); } printf("\n"); // to fill a secpnd tree with 7 nodes for example for(i=1;i<=7;i++) { printf("val of tree2= "); scanf("%d",&val); R2=add(R2,val); } printf("%d",compare(R,R2)); return 0; }
C
/** * @file filters_test.c * @brief Test of filters module. * @author Henrick Deschamps * @version 1.0.0 * @date 2016-06-10 */ #include <rrosace_filters.h> #include <stdio.h> #include <stdlib.h> #include "test_common.h" #define MODULE "filters" static int test_one_filter(rrosace_filter_type_t type, rrosace_filter_frequency_t frequency); static int test_step_func(); static int test_one_filter(rrosace_filter_type_t type, rrosace_filter_frequency_t frequency) { int ret = EXIT_FAILURE; const double h = 0; double h_f; rrosace_filter_t *p_filter = rrosace_filter_new(type, frequency); if (!p_filter) { goto out; } ret = rrosace_filter_step(p_filter, h, &h_f); out: rrosace_filter_del(p_filter); return (ret); } static int test_step_func() { int ret = EXIT_SUCCESS; rrosace_filter_type_t type; for (type = RROSACE_ALTITUDE_FILTER; type <= RROSACE_VERTICAL_ACCELERATION_FILTER; ++type) { rrosace_filter_frequency_t frequency; for (frequency = RROSACE_FILTER_FREQ_100HZ; frequency <= RROSACE_FILTER_FREQ_25HZ; ++frequency) { if (test_one_filter(type, frequency) == EXIT_FAILURE) { ret = EXIT_FAILURE; } } } return (ret); } int main() { int ret; const test_t test_step = {"step", test_step_func}; const test_t *p_tests[2]; p_tests[0] = &test_step; p_tests[1] = NULL; ret = exec_tests(MODULE, p_tests); return (ret); } #undef MODULE
C
#include<sys/socket.h> #include<netinet/in.h> #include<netdb.h> #include<unistd.h> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<errno.h> #define NUMSTR 3 char *reqlines[NUMSTR] = { "GET /le2soft/ HTTP/1.1\r\n", "Host: www.fos.kuis.kyoto-u.ac.jp\r\n", "\r\n", }; int main(int argc, char* argv[]) { FILE *fp; char hostname[128]; int i, s, port; struct hostent *hp; struct sockaddr_in sin; char buf[128]; port = 80; if ((hp = gethostbyname("www.fos.kuis.kyoto-u.ac.jp")) == NULL) { fprintf(stderr, "%s: unknown host.\n", hostname); exit(1); } s = socket(AF_INET, SOCK_STREAM, 0); bzero(&sin, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons(port); memcpy(&sin.sin_addr, hp->h_addr, hp-> h_length); printf("hoge\n"); if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) == -1) { perror("client connect()"); exit(1); } fp = fdopen(s, "r"); // send request to server for(i = 0; i < NUMSTR; i++) { send(s, reqlines[i], strlen(reqlines[i]), 0); } printf("hoge\n"); // receive contents from server while (fgets(buf, sizeof(buf), fp) != NULL) { printf("%s", buf); } close(s); return 0; }
C
#include<stdio.h> #include<conio.h> #include<stdlib.h> void insertAtBeginning(int); void insertAtEnd(int); void insertBetween(int,int,int); void display(); void removeBeginning(); void removeEnd(); void removeSpecific(int); struct Node { int data; struct Node *next; }*head = NULL; void main() { int n=0; while(1){ printf("\nEnter 1 to enter, 2 to display and 3 to exit\n"); scanf("%d",&n); switch(n) { case 1: printf("\nEnter value"); scanf("%d",&n); insertAtBeginning(n); break; case 2:display(); break; case 3: exit(0); break; default:printf("Invalid entry"); break; } } } void insertAtBeginning(int value) { struct Node *newNode; newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->data = value; if(head == NULL) { newNode->next = NULL; head = newNode; } else { newNode->next = head; head = newNode; } printf("\nOne node inserted!!!\n"); } void display() { int n=0,b=0; if(head==NULL) { printf("\nList is Empty\n"); } else { struct Node *temp = head; printf("\n\nList elements are - \n"); while(temp != NULL) { n= n*10+ temp->data; temp = temp->next; } printf("%d\n\n",n); while(n != 0) { b= b*10 + n%10; n=n/10; } printf("%d",b); } }
C
#include "machine.h" #include "WFF.h" #include "WFFlist.h" #include <time.h> /* Global WFF structure */ extern struct WFFglobal_st WFFglobal; long _WFFmain_print_listing (form, label1, label2, filename) Form form; int label1; int label2; char *filename; { long status; int i, *cols = NULL; int selected; int displayed; int num_cols, frozen_cols; char *time_string = NULL; time_t time_now; MEMptr buffer = NULL; static char *fname = "_WFFmain_print_listing"; long _WFFmain_print_to_file (); _NFIdebug ((fname, " Label1 = <%d>\n", label1)); _NFIdebug ((fname, " Label2 = <%d>\n", label2)); /* Get the output filename for the listing */ switch (WFFglobal.current_list) { case WFF_LIST_WORKFLOWS: strcpy (filename, "workflow.list"); break; case WFF_LIST_CLASSES: strcpy (filename, "classes.list"); break; case WFF_LIST_STATES: strcpy (filename, "states.list"); break; case WFF_LIST_TRANSITIONS: strcpy (filename, "trans.list"); break; case WFF_LIST_CLASS_ACCESS: strcpy (filename, "access.list"); break; case WFF_LIST_COMMANDS: strcpy (filename, "commands.list"); break; default: _NFIdebug ((fname, "there is no list to print\n")); ERRload_struct (NFI, NFI_I_NO_LISTING, NULL); _NFIdebug ((fname, " returning FAILURE\n")); return (NFI_I_NO_LISTING); } /* Get the current date/time */ if ((time_now = time ((long *) 0)) == -1) { _NFIdebug ((fname, "failed to get current date/time; errno = <%d>\n", errno)); ERRload_struct (NFI, NFI_E_TIME, "%d", errno); _NFIdebug ((fname, " returning FAILURE\n")); return (NFI_E_TIME); } /* Convert the time into a string */ if ((time_string = ctime (&time_now)) == NULL) { _NFIdebug ((fname, "failed to convert current date/time; errno = <%d>\n", errno)); ERRload_struct (NFI, NFI_E_TIME, "%d", errno); _NFIdebug ((fname, " returning FAILURE\n")); return (NFI_E_TIME); } buffer = WFFglobal.list_buffer; if ((cols = (int *) malloc (buffer->columns * (sizeof (int)))) == NULL) { _NFIdebug ((fname, "malloc failed; size = <%d>\n", buffer->columns * (sizeof (int)))); ERRload_struct (NFI, NFI_E_MALLOC, "%d", buffer->columns * (sizeof (int))); _NFIdebug ((fname, " returning FAILURE\n")); return (NFI_E_MALLOC); } /* Find out how many columns are in label1 */ if ((status = (long) FImcf_get_num_cols (form, label1, &num_cols)) != FI_SUCCESS) { _NFIdebug ((fname, "FImcf_get_num_cols = <%d>\n", status)); if (cols) free (cols); ERRload_struct (NFI, NFI_E_FORM, "%s%d", "FImcf_get_num_cols", status); _NFIdebug ((fname, " returning FAILURE\n")); return (NFI_E_FORM); } frozen_cols = num_cols; displayed = 0; for (i = 0; i < num_cols; ++i) { /* See if this attribute is to be printed */ if ((status = (long) FIfld_get_select (form, label1, 0, i, &selected)) != FI_SUCCESS) { _NFIdebug ((fname, "FIfld_get_select = <%d>\n", status)); if (cols) free (cols); ERRload_struct (NFI, NFI_E_FORM, "%s%d", "FIfld_get_select", status); _NFIdebug ((fname, " returning FAILURE\n")); return (NFI_E_FORM); } if (selected == FALSE) { _NFIdebug ((fname, "Buffer column %d is NOT to be printed\n", i)); cols[i] = -1; } else { _NFIdebug ((fname, "Buffer column %d IS to be printed\n", i)); cols[i] = displayed; ++displayed; } } if (num_cols < buffer->columns) { /* Find out how many columns are in label2 */ if ((status = (long) FImcf_get_num_cols (form, label2, &num_cols)) != FI_SUCCESS) { _NFIdebug ((fname, "FImcf_get_num_cols = <%d>\n", status)); if (cols) free (cols); ERRload_struct (NFI, NFI_E_FORM, "%s%d", "FImcf_get_num_cols", status); _NFIdebug ((fname, " returning FAILURE\n")); return (NFI_E_FORM); } for (i = 0; i < num_cols; ++i) { /* See if this attribute is to be printed */ if ((status = (long) FIfld_get_select (form, label2, 0, i, &selected)) != FI_SUCCESS) { _NFIdebug ((fname, "FIfld_get_select = <%d>\n", status)); if (cols) free (cols); ERRload_struct (NFI, NFI_E_FORM, "%s%d", "FIfld_get_select", status); _NFIdebug ((fname, " returning FAILURE\n")); return (NFI_E_FORM); } if (selected == FALSE) { _NFIdebug ((fname, "Buffer column %d is NOT to be printed\n", i)); cols[i + frozen_cols] = -1; } else { _NFIdebug ((fname, "Buffer column %d IS to be printed\n", i)); cols[i + frozen_cols] = displayed; ++displayed; } } } /* See if any columns have been selected */ if (displayed == 0) { _NFIdebug ((fname, "there are no columns selected to print\n")); if (cols) free (cols); ERRload_struct (NFI, NFI_P_SELECT_ATTRIBUTES, NULL); _NFIdebug ((fname, " returning FAILURE\n")); return (NFI_P_SELECT_ATTRIBUTES); } /* Print a message (it might take a few seconds) */ _WFFmessage (NFI_I_PRINTING, NULL); /* Call function to actually write to the file */ if ((status = _WFFmain_print_to_file (cols, time_string, filename)) != NFI_S_SUCCESS) { _NFIdebug ((fname, "_WFFmain_print_to_file = <0x%.8x>\n", status)); if (cols) free (cols); _WFFerase_message (); _NFIdebug ((fname, " returning FAILURE\n")); return (status); } if (cols) free (cols); /* Erase the message */ _WFFerase_message (); ERRload_struct (NFI, NFI_I_PRINT_LISTING, "%s", filename); _NFIdebug ((fname, " returning SUCCESS\n")); return (NFI_I_PRINT_LISTING); } long _WFFmain_print_to_file (cols, time_string, filename) int *cols; /* i - array of selected columns to print */ char *time_string; /* i - current date/time as a 26 character string */ char *filename; /* i - name of file to print listing to */ { int i, j, k; int length; int fields; long status; char *blanks; char **attr_ptr = NULL; char **data_ptr = NULL; char *output_string; FILE *outfile, *fopen (); MEMptr attr_list = NULL; MEMptr data_list = NULL; static char *fname = "_WFFmain_print_to_file"; if ((outfile = fopen (filename, "a")) == NULL) { _NFIdebug ((fname, "fopen failed; filename = <%s>\n", filename)); ERRload_struct (NFI, NFI_E_OPEN_FILE_APPEND, "%s", filename); _NFIdebug ((fname, " returning FAILURE\n")); return (NFI_E_OPEN_FILE_APPEND); } attr_list = WFFglobal.attr_list; data_list = WFFglobal.list_buffer; if (attr_list != NULL) { attr_ptr = (char **) attr_list->data_ptr; /* Make sure the buffers are in sync */ if (attr_list->rows != data_list->columns) { _NFIdebug ((fname, "attribute buffer has %d rows\n", attr_list->rows)); _NFIdebug ((fname, "data buffer has %d columns\n", data_list->columns)); _NFIdebug ((fname, "buffers are out of sync\n")); fclose (outfile); ERRload_struct (NFI, NFI_E_BUFFER, NULL); _NFIdebug ((fname, " returning FAILURE\n")); return (NFI_E_BUFFER); } } /* Scan the data_list for the length of the rows */ length = 0; data_ptr = (char **) data_list->format_ptr; for (i = 0; i < data_list->columns; ++i) { /* See if this data is to be output */ if (cols[i] == -1) continue; /* Determine what the datatype is */ if ((strcmp (data_ptr[i], "integer")) == 0) { if (strlen (attr_ptr[i]) > 15) { cols[i] = strlen (attr_ptr[i]); length += cols[i]; } else { length += 15; cols[i] = 15; } _NFIdebug ((fname, "datatype of column %d is integer\n", i)); } else if ((strcmp (data_ptr[i], "smallint")) == 0) { if (strlen (attr_ptr[i]) > 15) { cols[i] = strlen (attr_ptr[i]); length += cols[i]; } else { length += 15; cols[i] = 15; } _NFIdebug ((fname, "datatype of column %d is smallint\n", i)); } else if ((strcmp (data_ptr[i], "double")) == 0) { if (strlen (attr_ptr[i]) > 50) { cols[i] = strlen (attr_ptr[i]); length += cols[i]; } else { length += 50; cols[i] = 50; } _NFIdebug ((fname, "datatype of column %d is double\n", i)); } else if ((strcmp (data_ptr[i], "real")) == 0) { if (strlen (attr_ptr[i]) > 50) { cols[i] = strlen (attr_ptr[i]); length += cols[i]; } else { length += 50; cols[i] = 50; } _NFIdebug ((fname, "datatype of column %d is real\n", i)); } else if ((strcmp (data_ptr[i], "decimal")) == 0) { if (strlen (attr_ptr[i]) > 50) { cols[i] = strlen (attr_ptr[i]); length += cols[i]; } else { length += 50; cols[i] = 50; } _NFIdebug ((fname, "datatype of column %d is decimal\n", i)); } else if ((strcmp (data_ptr[i], "date")) == 0) { if (strlen (attr_ptr[i]) > 15) { cols[i] = strlen (attr_ptr[i]); length += cols[i]; } else { length += 15; cols[i] = 15; } _NFIdebug ((fname, "datatype of column %d is date\n", i)); } else if ((strncmp (data_ptr[i], "char(", 5)) == 0) { if ((status = sscanf (data_ptr[i], "char(%d)", &(cols[i]))) == EOF) { _NFIdebug ((fname, "sscanf = <%d>\n", status)); fclose (outfile); ERRload_struct (NFI, NFI_E_BUFFER, NULL); _NFIdebug ((fname, " returning FAILURE\n")); return (NFI_E_BUFFER); } /* Add 1 for the NULL and 1 for an extra blank */ ++cols[i]; length += cols[i] + 1; if (strlen (attr_ptr[i] + 1) > cols [i]) { cols[i] = strlen (attr_ptr[i] + 1); length += cols[i] + 1; } _NFIdebug ((fname, "datatype of column %d is char(%d)\n", i, cols[i])); } } if (_NFMdebug_st.NFIdebug_on) { for (i = 0; i < data_list->columns; ++i) _NFIdebug ((fname, "cols[%d] = <0x%.8x>\n", i, cols[i])); } _NFIdebug ((fname, "length = <%d>\n", length)); /* Allocate space for the output string */ if ((output_string = (char *) malloc (length)) == NULL) { _NFIdebug ((fname, "malloc failed; size = <%d>\n", length)); fclose (outfile); ERRload_struct (NFI, NFI_E_MALLOC, "%d", length); _NFIdebug ((fname, " returning FAILURE\n")); return (NFI_E_MALLOC); } /* Initialize the string */ strcpy (output_string, ""); /* Allocate space for padding with blanks */ if ((blanks = (char *) malloc (length)) == NULL) { _NFIdebug ((fname, "malloc failed; size = <%d>\n", length)); fclose (outfile); if (output_string) free (output_string); ERRload_struct (NFI, NFI_E_MALLOC, "%d", length); _NFIdebug ((fname, " returning FAILURE\n")); return (NFI_E_MALLOC); } if (attr_list != NULL) { attr_ptr = (char **) attr_list->data_ptr; /* Write the column headings first */ fields = attr_list->columns * attr_list->rows; for (i = 0; i < fields; ++i) { /* See if this data is to be output */ if (cols[i] == -1) continue; /* Build the output string */ strncat (output_string, attr_ptr[i], (size_t) cols[i]); _NFIdebug ((fname, "output_string = <%s>\n", output_string)); if ((strlen (attr_ptr[i])) < cols[i]) { /* Pad the remaining space with blanks */ sprintf (blanks, "%*s", cols[i] - (strlen (attr_ptr[i])), " "); strcat (output_string, blanks); } } } else { attr_ptr = (char **) data_list->column_ptr; /* Write the column names in the data_list */ for (i = 0; i < data_list->columns; ++i) { /* See if this data is to be output */ if (cols[i] == -1) continue; /* Build the output string */ strncat (output_string, attr_ptr[i], (size_t) cols[i]); _NFIdebug ((fname, "output_string = <%s>\n", output_string)); if ((strlen (attr_ptr[i])) < cols[i]) { /* Pad the remaining space with blanks */ sprintf (blanks, "%*s", cols[i] - (strlen (attr_ptr[i])), " "); strcat (output_string, blanks); } } } /* Write the current date/time to the file */ _NFIdebug ((fname, "Writing <%s> to file\n", time_string)); if ((status = (long) fputs (time_string, outfile)) == EOF) { _NFIdebug ((fname, "fputs = <%d>\n", status)); fclose (outfile); if (output_string) free (output_string); if (blanks) free (blanks); ERRload_struct (NFI, NFI_E_APPEND_FILE, NULL); _NFIdebug ((fname, " returning FAILURE\n")); return (NFI_E_APPEND_FILE); } /* Write column headers to the file */ _NFIdebug ((fname, "Writing <%s> to file\n", output_string)); if ((status = (long) fputs (output_string, outfile)) == EOF) { _NFIdebug ((fname, "fputs = <%d>\n", status)); fclose (outfile); if (output_string) free (output_string); if (blanks) free (blanks); ERRload_struct (NFI, NFI_E_APPEND_FILE, NULL); _NFIdebug ((fname, " returning FAILURE\n")); return (NFI_E_APPEND_FILE); } if ((status = (long) fputs ("\n\n", outfile)) == EOF) { _NFIdebug ((fname, "fputs = <%d>\n", status)); fclose (outfile); if (output_string) free (output_string); if (blanks) free (blanks); ERRload_struct (NFI, NFI_E_APPEND_FILE, NULL); _NFIdebug ((fname, " returning FAILURE\n")); return (NFI_E_APPEND_FILE); } /* Write the values in the file */ data_ptr = (char **) data_list->data_ptr; for (i = 0, k = -1; i < data_list->rows; ++i) { strcpy (output_string, ""); for (j = 0; j < data_list->columns; ++j) { ++k; /* See if this data is to be output */ if (cols[j] == -1) continue; /* Build the output string */ strncat (output_string, data_ptr[k], (size_t) cols[j]); _NFIdebug ((fname, "output_string = <%s>\n", output_string)); if ((strlen (data_ptr[k])) < cols[j]) { /* Pad the remaining space with blanks */ sprintf (blanks, "%*s", cols[j] - (strlen (data_ptr[k])), " "); strcat (output_string, blanks); } } /* Write listing data to the file */ _NFIdebug ((fname, "Writing <%s> to file\n", output_string)); if ((status = (long) fputs (output_string, outfile)) == EOF) { _NFIdebug ((fname, "fputs = <%d>\n", status)); fclose (outfile); if (output_string) free (output_string); if (blanks) free (blanks); ERRload_struct (NFI, NFI_E_APPEND_FILE, NULL); _NFIdebug ((fname, " returning FAILURE\n")); return (NFI_E_APPEND_FILE); } if ((status = (long) fputs ("\n", outfile)) == EOF) { _NFIdebug ((fname, "fputs = <%d>\n", status)); fclose (outfile); if (output_string) free (output_string); if (blanks) free (blanks); ERRload_struct (NFI, NFI_E_APPEND_FILE, NULL); _NFIdebug ((fname, " returning FAILURE\n")); return (NFI_E_APPEND_FILE); } } /* Put a blank line at the end (file was opened for append) */ if ((status = (long) fputs ("\n", outfile)) == EOF) { _NFIdebug ((fname, "fputs = <%d>\n", status)); fclose (outfile); if (output_string) free (output_string); if (blanks) free (blanks); ERRload_struct (NFI, NFI_E_APPEND_FILE, NULL); _NFIdebug ((fname, " returning FAILURE\n")); return (NFI_E_APPEND_FILE); } /* Close the file and deallocate space */ fclose (outfile); if (output_string) free (output_string); if (blanks) free (blanks); _NFIdebug ((fname, " returning SUCCESS\n")); return (NFI_S_SUCCESS); }
C
#include<stdlib.h> #include"extracted.h" /* C <- A+B * A et B sont à coeffs nuls en dehors des blocs de tailles * mA*nA, mB*nB et on a ("left") mA>=mB, nA>=nB * */ void _addl (int * A, int * B, int * C, // Dim des sous-matrices int mA, int nA, int mB, int nB, // Nombre de colonnes des matrices totales int width_A, int width_B, int width_C) { int i,j; // Matrice avec le moins de zones vides à gauche // Lignes de B for (i = 0 ; i < mB ; i++) { // Colonnes de B non vides for (j = 0 ; j < nB ; j++) C[j+i*width_C] = A[j+i*width_A] + B[j+i*width_B]; // Colonnes de A "seules" for (j = nB ; j < nA ; j++) C[j+i*width_C] = A[j+i*width_A]; } // Lignes de A "seules" (et non vides) for (i = mB ; i < mA ; i++) for (j = 0 ; j < nA ; j++) C[j+i*width_C] = A[j+i*width_A]; return; } void _addr (int * A, int * B, int * C, // Dim des sous-matrices int mA, int nA, int mB, int nB, // Nombre de colonnes des matrices totales int width_A, int width_B, int width_C) { int i,j; // Matrice avec le moins de zones vides à droite for (i = 0 ; i < mA ; i++) { for (j = 0 ; j<nA ; j++) C[j+i*width_C] = A[j+i*width_A]+B[j+i*width_B]; for (j = nA ; j<nB ; j++) C[j+i*width_C] = B[j+i*width_B]; } // Lignes de A "seules" (et non vides) for (i = mA ; i < mB ; i++) for (j = 0 ; j < nB ; j++) C[j+i*width_C] = B[j+i*width_B]; return; } void _subl (int * A, int * B, int * C, // Dim des sous-matrices int mA, int nA, int mB, int nB, // Nombre de colonnes des matrices totales int width_A, int width_B, int width_C) { int i,j; // Matrice avec le moins de zones vides à gauche // Lignes de B for (i = 0 ; i < mB ; i++) { // Colonnes de B non vides for (j = 0 ; j < nB ; j++) C[j+i*width_C] = A[j+i*width_A] - B[j+i*width_B]; // Colonnes de A "seules" for (j = nB ; j < nA ; j++) C[j+i*width_C] = A[j+i*width_A]; } // Lignes de A "seules" (et non vides) for (i = mB ; i < mA ; i++) for (j = 0 ; j < nA ; j++) C[j+i*width_C] = A[j+i*width_A]; return; } void _subr (int * A, int * B, int * C, // Dim des sous-matrices int mA, int nA, int mB, int nB, // Nombre de colonnes des matrices totales int width_A, int width_B, int width_C) { int i,j; for (i = 0 ; i < mA ; i++) { for (j = 0 ; j<nA ; j++) C[j+i*width_C] = A[j+i*width_A]-B[j+i*width_B]; for (j = nA ; j<nB ; j++) C[j+i*width_C] = -B[j+i*width_B]; } // Lignes de A "seules" (et non vides) for (i = mA ; i < mB ; i++) for (j = 0 ; j < nB ; j++) C[j+i*width_C] = -B[j+i*width_B]; return; }
C
/* * Exercise 3-5 * * Write the function itob(n,s,b) that converts the integer n into a base b * character representation in the string s. In particular, itob(n,s,16) * formats n as a hexadecimal integer in s. * * Not sure what would be the best solution for negative values since different * bases suggest a sign bit. */ #include <stdio.h> #include <string.h> #include <limits.h> #define MAX_CHAR 128 void itob(int n, char s[], int b); void reverse(char s[]); int main() { int x1 = 37; int x2 = -9; int x3 = 299792458; int x4 = INT_MIN; char res[MAX_CHAR]; itob(x1, res, 2); printf("%d == %s\n", x1, res); itob(x1, res, 8); printf("%d == %s\n", x1, res); itob(x1, res, 16); printf("%d == %s\n", x1, res); itob(x2, res, 8); printf("%d == %s\n", x2, res); itob(x3, res, 16); printf("%d == %s\n", x3, res); itob(x4, res, 16); printf("%d == %s\n", x4, res); } void itob(int n, char s[], int b) { int i, sign; if ((sign = n) < 0) n = -n; i = 0; do { int temp = n % b; s[i++] = (temp > 9) ? temp - 10 + 'A' : temp + '0'; } while ((n /= b) > 0); if (sign < 0) s[i++] = '-'; s[i] = '\0'; reverse(s); } void reverse(char s[]) { int c, i, j; for (i = 0, j = strlen(s) - 1; i < j; ++i, --j) { c = s[i]; s[i] = s[j]; s[j] = c; } }
C
#ifndef __FT_STRNCMP__ #define __FT_STRNCMP__ int ft_strncmp(char *s1, char *s2, unsigned int n) { int i; i = 0; while((s1[i] || s2[i]) && (i < n)){ if(s1[i] < s2[i]){ return (-1); } if(s1[i] > s2[i]){ return (1); } i++; } return (0); } #endif
C
#include <stdio.h> #include <stdlib.h> static unsigned int testvar = 0xdeadbeef; void print_test() { printf("Test var: 0x%x\n", testvar); } int main (int argc, char** argv) { int i; int* tmp = malloc(sizeof(int)); for (i = 0; i < 4; i++) { printf("Old %i: %x\n", i, tmp[i]); tmp[i] = 0x10101010; printf("New %i: %x\n", i, tmp[i]); } for (i = 0; i < 4; i++) { print_test(); } return 0; }
C
// compile with gcc -fopenmp parallel_calc_pi.c # include <stdio.h> # include <omp.h> # include <math.h> static long n_stp = (int) 1e10; // number of discretizations double t0, dt, pi, dx = 0.0; // variables int i; int main() { dx = 1.0 / (double) n_stp; // the size of the step to take t0 = omp_get_wtime(); // start the timer # pragma omp parallel { double x = 0.0; // the part for this thread # pragma omp for reduction (+:pi) schedule(guided) nowait for (i = 0; i < n_stp; i++) { x = (i + 0.5) * dx; // midpoint rule pi += 4.0 / (1.0 + x*x); // increment the thread sum } } pi *= dx; // pull dx multiplication ouside sum dt = omp_get_wtime() - t0; // time to compute printf("pi = %.2e \t pi - pi_true = %.2e \t dt = %.2e\n", pi, pi - M_PI, dt); }
C
#include <stdio.h> int main(){ long long a, b; scanf("%lld %lld", &a, &b); while(1){ int chk=0; if ( !a || !b ) break; if ( a>= 2*b ) a%=(2*b), chk=1; if ( !chk && b>= 2*a ) b%= (2*a), chk=1; if ( !chk) break; } printf("%lld %lld\n", a, b); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_split.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fgwyneth <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/09/29 11:35:56 by fgwyneth #+# #+# */ /* Updated: 2020/10/30 12:18:53 by fgwyneth ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static size_t count_words(char const *s, char c) { int num; int i; int len; num = 0; i = 0; len = ft_strlen(s); while (i != len - 1) { if (s[i] == c && s[i + 1] != c) num++; i++; } return (num + 1); } static char *strdup_(const char *str, char c) { char *ptr; int i; i = 0; if (!(ptr = (char *)malloc(sizeof(char) * (ft_strlen(str) + 1)))) return (NULL); while (str[i] != '\0' && str[i] != c) { ptr[i] = str[i]; i++; } ptr[i] = '\0'; return (ptr); } char **ft_split(char const *s, char c) { int i; int j; int k; char **strs; j = 0; k = 0; if (s == NULL || ft_strlen(s) == 0) return (NULL); if (!(strs = (char**)malloc(sizeof(char*) * (count_words(s, c) + 1)))) return (NULL); while (j <= ft_strlen(s)) { i = j; while (s[j] != c && s[j] != '\0') ++j; if (j != i) { strs[k++] = strdup_(&s[i], c); } ++j; } strs[k] = (void*)0; return (strs); }
C
#include <stdio.h> int main(void) { unsigned short u = 0; short s = 0; int i = 0; for (i=0; i<0xFFFF+2; i++) { u = i; s = i; printf("%d %u %d\n", i, u, s); } return 0; }
C
#include <gtk/gtk.h> #include <stdio.h> #include <stdlib.h> #include "manager.h" #include "createWindow.h" #include "createProject.h" #include "fileIO.h" #include "chooseFolder.h" // GUI information #define FILENAME "createProject" #define STRUCT_SIZE 7 static const char *WidgetNames[STRUCT_SIZE] = { FILENAME, "lblProjectName", "lblLocation", "entProjectName", "btnConfirm", "btnLocation", "btnPythonScript" }; /** * Quit the program. */ void on_createProject_destroy(void) { gtk_main_quit(); } /** * Back to manager button. * - When pushed, destroy the current window * and go back to the manager window. * * @param ptr_button, contains button signals. * @param ptr_widgets, contains all widgets used * in the window. */ void on_btnBack_clicked(GtkButton *button, CreateProjectWidgets *widgets) { DESTROY_WIDGET(widgets->widget[0]); manager(); } void on_btnNext_clicked(GtkButton *button, CreateProjectWidgets *widgets) { } /** * Directory location button. * - When pushed, open the choose folder window. */ void on_btnLocation_clicked(GtkButton *location, CreateProjectWidgets *widgets) { char *dir = NULL; // Disable widgets ENABLE_WIDGETS(widgets->widget[0], FALSE); ENABLE_WIDGETS(widgets->widget[5], FALSE); chooseFolder(); // Pop up window // Enable widgets ENABLE_WIDGETS(widgets->widget[0], TRUE); ENABLE_WIDGETS(widgets->widget[5], TRUE); int ferror = readFile("../src/Files/folderName.dat", &dir); if (ferror == EXIT_SUCCESS) { gtk_label_set_label(GTK_LABEL(widgets->widget[2]), dir); const char *pName = gtk_label_get_label(GTK_LABEL(widgets->widget[1])); char *projectDir = (char*)malloc(sizeof(char) * (strlen(dir) + strlen(pName))); sprintf(projectDir, "%s/%s", dir, pName); // dirCreate(projectDir); ENABLE_WIDGETS(widgets->widget[5], FALSE); ENABLE_WIDGETS(widgets->widget[6], TRUE); free(dir); free(projectDir); } } /** * Confirm button. * - When pushed, update the label field which * contains the Name of the Project. The text * that is entered in the entry box is the projects * name. * * @param ptr_confirm, contains button signals. * @param ptr_widgets, contains all widgets used * in the window. */ void on_btnConfirm_clicked(GtkButton *btnConfirm, CreateProjectWidgets *widgets) { const char *pName = gtk_entry_get_text(GTK_ENTRY(widgets->widget[3])); if (strlen(pName) == EXIT_SUCCESS); // pop up dialog box !!! else { gtk_label_set_label(GTK_LABEL(widgets->widget[1]), pName); ENABLE_WIDGETS(widgets->widget[4], FALSE); ENABLE_WIDGETS(widgets->widget[5], TRUE); } } /** * Runs glades createProject GUI application, passes * information about the window in the function * createWindow. */ void createProject(void) { CreateProjectWidgets *widgets = NULL; // Casting Widgets to the default Widget struct createWindow((Widget*)&widgets, WidgetNames, FILENAME, STRUCT_SIZE); }
C
//ftp-manager.h #ifndef _FTP_MANAGER_H_ #define _FTP_MANAGER_H_ /*FTP OPERATION CODE*/ typedef enum FTP_STATE { FTP_UPLOAD_SUCCESS, FTP_UPLOAD_FAILED, FTP_DOWNLOAD_SUCCESS, FTP_DOWNLOAD_FAILED }FTP_STATE; /*FTP OPERATIONS OPTIONS*/ typedef struct FTP_OPT { char *url; /*url of ftp*/ char *user_key; /*username:password*/ char *file; /*filepath*/ }FTP_OPT; #ifdef __cplusplus extern "C" { #endif /*upload file to ftp server*/ FTP_STATE ftp_upload(const FTP_OPT ftp_option); /*download file from ftp server*/ FTP_STATE ftp_download(const FTP_OPT ftp_option); #ifdef __cplusplus } #endif #endif
C
/** * History: * ================================================================ * 2017-05-28 qing.zou created * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <getopt.h> #include <time.h> #include <sys/time.h> #include "vpk.h" #if defined(_X86_) #else #endif #include <errno.h> static int use_monotonic; static void detect_monotonic(void) { struct timespec ts; static int use_monotonic_initialized = 0; if (use_monotonic_initialized) return; if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) use_monotonic = 1; LOG_D("ts: %d %ld", ts.tv_sec, ts.tv_nsec); use_monotonic_initialized = 1; } #define CLOCK_SYNC_INTERVAL -1 static time_t last_updated_clock_diff = 0; static struct timeval tv_clock_diff; static int gettime(struct timeval *tp) { //if (base->tv_cache.tv_sec) { // *tp = base->tv_cache; // return (0); //} if (use_monotonic) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1) return (-1); tp->tv_sec = ts.tv_sec; tp->tv_usec = ts.tv_nsec / 1000; if (last_updated_clock_diff + CLOCK_SYNC_INTERVAL < ts.tv_sec) { struct timeval tv; vpk_gettimeofday(&tv,NULL); vpk_timersub(&tv, tp, &tv_clock_diff); last_updated_clock_diff = ts.tv_sec; LOG_D("real time: %d %d, clock mono: %d %ld, diff: %d %d", tv.tv_sec, tv.tv_usec, ts.tv_sec, ts.tv_nsec, tv_clock_diff.tv_sec, tv_clock_diff.tv_usec); } return (0); } return (vpk_gettimeofday(tp, NULL)); } #include <fcntl.h> #include <limits.h> //#include <sys/types.h> #include <sys/epoll.h> /* On Linux kernels at least up to 2.6.24.4, epoll can't handle timeout * values bigger than (LONG_MAX - 999ULL)/HZ. HZ in the wild can be * as big as 1000, and LONG_MAX can be as small as (1<<31)-1, so the * largest number of msec we can support here is 2147482. Let's * round that down by 47 seconds. */ #define MAX_EPOLL_TIMEOUT_MSEC (35*60*1000) #define MAX_SECONDS_IN_MSEC_LONG \ (((LONG_MAX) - 999) / 1000) long tv_to_msec(const struct timeval *tv) { if (tv->tv_usec > 1000000 || tv->tv_sec > MAX_SECONDS_IN_MSEC_LONG) return -1; return (tv->tv_sec * 1000) + ((tv->tv_usec + 999) / 1000); } int make_socket_closeonexec(int fd) { int flags; if ((flags = fcntl(fd, F_GETFD, NULL)) < 0) { LOG_E("fcntl(%d, F_GETFD)", fd); return -1; } if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) { LOG_E("fcntl(%d, F_SETFD)", fd); return -1; } return 0; } static int epoll_test(struct timeval *tv) { int fd; if ((fd = epoll_create(32000)) == -1) { if (errno != ENOSYS) LOG_E("epoll_create"); return -1; } make_socket_closeonexec(fd); struct epoll_event *events = malloc(32 * sizeof(struct epoll_event)); if (events == NULL) { close(fd); return -1; } int res; long timeout = -1; if (tv != NULL) { timeout = tv_to_msec(tv); if (timeout < 0 || timeout > MAX_EPOLL_TIMEOUT_MSEC) { /* Linux kernels can wait forever if the timeout is * too big; see comment on MAX_EPOLL_TIMEOUT_MSEC. */ timeout = MAX_EPOLL_TIMEOUT_MSEC; } } //unlock LOG_D("epoll_wait %ld(ms)", timeout); res = epoll_wait(fd, events, 32, timeout); //EVBASE_ACQUIRE_LOCK(base, th_base_lock); if (res == -1) { if (errno != EINTR) { LOG_E("epoll_wait"); return (-1); } return (0); } //for (i = 0; i < res; i++) { // int what = events[i].events; // short ev = 0; // if (what & (EPOLLHUP|EPOLLERR)) { // ev = EV_READ | EV_WRITE; // } else { // if (what & EPOLLIN) // ev |= EV_READ; // if (what & EPOLLOUT) // ev |= EV_WRITE; // } // if (!ev) // continue; // evmap_io_active(base, events[i].data.fd, ev | EV_ET); //} free(events); close(fd); return 0; } void time_test() { time_t timestamp; struct tm *locals; //char timestr[] = "2018-11-01 11:30:00"; timestamp = time(NULL); LOG_D("timestamp: %ld", timestamp); LOG_D("ctime: %s", ctime(&timestamp)); locals = localtime(&timestamp); LOG_D("%d-%d-%d %02d:%02d:%02d", locals->tm_year+1900, locals->tm_mon+1, locals->tm_mday, locals->tm_hour, locals->tm_min, locals->tm_sec); timestamp = mktime(locals); LOG_D("timestamp: %ld\n", timestamp); } #if 1 static void set_timer(int seconds, int mseconds) { struct timeval temp; temp.tv_sec = seconds; temp.tv_usec = mseconds; select(0, NULL, NULL, NULL, &temp); printf("timer\n"); return ; } #elif 0 #elif 0 #endif #include "vpk_timer.h" static struct timeval prev; static void task_heart_beat(int fd, short event, void *arg) { //int value = HEART_BEAT_MESSAGE_VALUE; double elapsed; struct timeval nowtime, difference; vpk_gettimeofday(&nowtime, NULL); vpk_timersub(&nowtime, &prev, &difference); elapsed = difference.tv_sec + (difference.tv_usec / 1.0e6); prev = nowtime; LOG_D("task_heart_beat, at %d: %.6f seconds elapsed.", nowtime.tv_sec, elapsed); } static int timer_test(void) { vpk_events task_event; vpk_timer_t* base = vpk_timer_create(); int flags = VPK_EV_PERSIST; //flags = 0; vpk_event_assign(&task_event, base, 0, flags, task_heart_beat, NULL); struct timeval tv; vpk_timerclear(&tv); tv.tv_sec = 5; vpk_gettimeofday(&prev, NULL); vpk_timer_event_add(&task_event, &tv); vpk_timer_loop(base, 0); return 0; } int timer_main(int argc, char *argv[]) { // int ret = 0; // // vpk_system_init(argc, argv); // vpk_logging_level_set("DEBUG"); //char* pathname = "./ipc"; //int proj_id = 0x10; char* type = "time"; //if (argc > 1) //{ // type = argv[1]; //} int o; static const struct option long_options[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 'V' }, { "sample", required_argument, NULL, 'd' }, { "type", required_argument, NULL, 't' }, { "keycode", required_argument, NULL, 'k' }, { "file", required_argument, NULL, 'f' }, { "url", required_argument, NULL, 'u' }, { "log", optional_argument, NULL, 'l' }, { NULL, 0, NULL, 0 } }; optind = 1; //LOG_I("22 optind = %d, argc = %d", optind, argc); while ((o = getopt_long(argc, argv, "hVd:t:k:f:u:l", long_options, NULL)) >= 0) { //printf("opt = %c\n", o); //printf("optarg = %s\n", optarg); //printf("optind = %d\n", optind); //printf("argv[optind - 1] = %s\n", argv[optind - 1]); switch(o) { case 't': type = optarg; break; default: break; } } LOG_D("type = %s", type); double elapsed; struct timeval result, prev, next; time_test(); detect_monotonic(); struct timeval now; gettime(&now); LOG_D("now: %d %d\n", now.tv_sec, now.tv_usec); gettimeofday(&prev, 0); if (strcasecmp(type, "select") == 0) { set_timer(5, 10); } else if (strcasecmp(type, "epoll") == 0) { struct timeval tv; tv.tv_sec = 5; tv.tv_usec = 500000; epoll_test(&tv); } else { timer_test(); } gettimeofday(&next, 0); vpk_timersub(&next, &prev, &result); //time_sub(&result, &prev, &next); elapsed = result.tv_sec + (result.tv_usec / 1.0e6); LOG_D("vpk time elapsed: %.6f, %d(s) %d(us) \n", elapsed, result.tv_sec, result.tv_usec); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <math.h> #include <pthread.h> #include <stdint.h> #define POS_X 0 #define POS_Y 1 #define MASS 2 const double epsilon_0 = 0.001; //declare node structure (X) //maybe good idea is to compact it! (ie no padding) typedef struct tree_node{ int depth; int body_id; int is_used; double x_lim; //x division (middle point in x) double y_lim; // y division (middle point in y) double width; //width of the box double cm_x; // = 0, this points to 0 and double cm_y; //center of mas s of the quadrant double tot_mass; // = 0, total mass of the quadrant struct tree_node *left_down; //Q3 child struct tree_node *left_up; //Q2 child struct tree_node *right_down; //Q4 child struct tree_node *right_up; //Q1 child }node_t; void print_qtree(node_t* node){ if(node == NULL){printf("Tree is empty \n"); return;} if(node != NULL){ printf("Depth: %d, id:%d, total mass: %lf, cm: (%lf, %lf) limits: (%lf,%lf)\t", node->depth, node->body_id, node->tot_mass, node->cm_x, node->cm_y, node->x_lim, node->y_lim); } if (node->right_up != NULL) printf("RU : total mass %lf,", node->right_up->tot_mass); if (node->left_up != NULL) printf("LU: total mass: %lf,", node->left_up->tot_mass); if (node->left_down != NULL) printf("LD: total mass: %lf,", node->left_down->tot_mass); if (node->right_down != NULL) printf("RD: total mass; %lf,", node->right_down->tot_mass); printf("\n"); if (node->right_up != NULL) print_qtree(node->right_up); if (node->left_up != NULL) print_qtree(node->left_up); if (node->left_down != NULL) print_qtree(node->left_down); if (node->right_down != NULL) print_qtree(node->right_down); return; } void create_children(node_t* node, double * pow_2){ if(node->right_up != NULL){printf("L178, create_children. Something went wrong RU children already exist"); return;} //create right up //printf("Creating RU\n"); node->right_up=(node_t*)malloc(sizeof(node_t)); node->right_up->is_used = 0; node->right_up->depth = node->depth +1; node->right_up->body_id = -1; node->right_up->x_lim = node->x_lim + pow_2[node->right_up->depth]; node->right_up->y_lim = node->y_lim + pow_2[node->right_up->depth]; node->right_up-> width = pow_2[node->depth]; node->right_up-> cm_x = 0; node->right_up-> cm_y = 0; node->right_up-> tot_mass = -1.0; node->right_up->left_down = NULL; node->right_up->left_up = NULL; node->right_up->right_down = NULL; node->right_up->right_up = NULL; if(node->right_down != NULL){printf("L178, create_children. Something went wrong RD children already exist"); return;} //create right down //printf("Creating RD\n"); node->right_down=(node_t*)malloc(sizeof(node_t)); node->right_down->is_used=0; node->right_down->depth = node->depth +1; node->right_down->body_id = -1; node->right_down->x_lim = node->x_lim + pow_2[node->right_down->depth]; node->right_down->y_lim = node->y_lim - pow_2[node->right_down->depth]; node->right_down-> width = pow_2[node->depth]; node->right_down-> cm_x = 0; node->right_down-> cm_y = 0; node->right_down-> tot_mass = -1.0; node->right_down->left_down = NULL; node->right_down->left_up = NULL; node->right_down->right_down = NULL; node->right_down->right_up = NULL; if(node->left_up != NULL){printf("L178, create_children. Something went wrong RU children already exist"); return;} //create left_up //printf("Creating LU\n"); node->left_up=(node_t*)malloc(sizeof(node_t)); node->left_up->is_used = 0; node->left_up->depth = node->depth +1; node->left_up->body_id = -1; node->left_up->x_lim = node->x_lim - pow_2[node->left_up->depth]; node->left_up->y_lim = node->y_lim + pow_2[node->left_up->depth]; node->left_up-> width = pow_2[node->depth]; node->left_up-> cm_x = 0; node->left_up-> cm_y = 0; node->left_up-> tot_mass = -1.0; node->left_up->left_down = NULL; node->left_up->left_up = NULL; node->left_up->right_down = NULL; node->left_up->right_up = NULL; if(node->left_down != NULL){printf("L178, create_children. Something went wrong RU children already exist"); return;} //create left down //printf("Creating LD\n"); node->left_down=(node_t*)malloc(sizeof(node_t)); node->left_down->is_used=0; node->left_down->depth = node->depth +1; node->left_down->body_id = -1; node->left_down->x_lim = node->x_lim - pow_2[node->left_down->depth]; node->left_down->y_lim = node->y_lim - pow_2[node->left_down->depth]; node->left_down-> width = pow_2[node->depth]; node->left_down-> cm_x = 0; node->left_down-> cm_y = 0; node->left_down-> tot_mass = -1.0; node->left_down->left_down = NULL; node->left_down->left_up = NULL; node->left_down->right_down = NULL; node->left_down->right_up = NULL; } //modify what node we are using (ie pointing to) void insert(node_t **node, double x_pos, double y_pos, double mass, double* pow_2, int id){ // inserts given bodyin tree, creating new nodes if necessary such that //every external node (leaf) contains only one body. //each node represents a quadrant and contains coordinates of //its center of mass and total mass within the quadrant. // N if((*node) == NULL){ printf("ERROR: Given node is NULL"); return;} //if node X does not contain a body, we put the new body in it. if((*node)->tot_mass == -1.0){ //the node contains no bodies so we can insert the new one in it. (*node)-> cm_x = x_pos; (*node)-> cm_y = y_pos; (*node)-> tot_mass = mass; (*node)->body_id= id; }else{ /*The node contains a body. If node is an internal node i.e has children we: update the center of mass and total mass of the node and go deeper to appropiate child (RU, RD, LU or LD) */ if((*node)->right_up != NULL){ //Node is internal (not a leaf) //UPDATE cm and MASS double cm_mass = (*node)->tot_mass; //update center of mass new_cm = (old_mass*old_cm + pos_new_particle*mass_new_particle)/(new total mass) (*node)->tot_mass+=mass; //we can save operations in here by declaring new varaibles (*node)->cm_x = cm_mass/(*node)->tot_mass * (*node)->cm_x + x_pos*(mass/(*node)->tot_mass); // Note: This maybe we can do more efficently (*node)->cm_y = cm_mass/(*node)->tot_mass* (*node)->cm_y + y_pos*(mass/(*node)->tot_mass); //FIND APPROPIATE CHILD and call insert with child as new node int expr = 2*(x_pos>(*node)->x_lim) + (y_pos >(*node)->y_lim); switch (expr) { case 0: //False, False we go left down node= &(*node)->left_down; break; case 1: //False, True we go left_up node= &(*node)->left_up; break; case 2: //True False, we go right down node = &(*node)->right_down; break; case 3: //True True we go right up node = &(*node)->right_up; break; } //insert with correct node insert(node, x_pos, y_pos, mass, pow_2, id); }else{ //The node has mass but no children hence its a leaf //If it is an external node (leafs) we have //to create new children (furhter subdivide the space) create_children((*node), pow_2); //printf("We created children\n"); //print_qtree((*node)); //insert particle that was occupying the leaf, it will go to appropiate //quadrant double mass_in_node = (*node)->tot_mass; //set the mass to 0 since we remove a particle from the node (*node)->tot_mass = 0; //save position in the tree node_t ** parent_node = node; //insert particle that was already in node insert(parent_node, (*node)->cm_x, (*node)->cm_y, mass_in_node, pow_2, (*node)->body_id); //printf("We pushed particle that was already on the node\n"); (*node)->body_id = -1; //print_qtree((*node)); //try inserting particle i again insert(node, x_pos, y_pos, mass, pow_2, id); //printf("We inserted particle i \n"); //print_qtree((*node)); } } return; } void delete_tree(node_t** node){ if((*node)== NULL){return;} //If you can go to a child, ie child not null //go to it and call the function again if((*node)->right_up){ delete_tree(&(*node)->right_up); } if((*node)->right_down){ delete_tree(&(*node)->right_down); } if((*node)->left_up){ delete_tree(&(*node)->left_up); } if((*node)->left_down){ delete_tree(&(*node)->left_down); } //everything is NULL so we can free the node free((*node)->right_up); free((*node)->right_down); free((*node)->left_up); free((*node)->left_down); free((*node)); (*node)=NULL; return; } void mark_as_not_use_tree(node_t** node){ if((*node)== NULL || !(*node)->is_used){return;} //If you can go to a child, ie child not null //go to it and call the function again if((*node)->right_up && (*node)->right_up->is_used){ //tree has a kid which is marked as used, so we go to it mark_as_not_use_tree(&(*node)->right_up); } if((*node)->right_down && (*node)->right_down->is_used){ mark_as_not_use_tree(&(*node)->right_down); } if((*node)->left_up && (*node)->left_up->is_used){ mark_as_not_use_tree(&(*node)->left_up); } if((*node)->left_down && (*node)->left_down->is_used){ mark_as_not_use_tree(&(*node)->left_down); } //everything is NULL or marked as not used so we can mark this node //as unused (*node)->is_used = 0; return; } typedef struct thread_arg{ int thid; int i1; int i2; double theta_max; double G; double delta_t; double* pos_x; double* pos_y; double* vx; double* vy; node_t* node; }arg_t; void * worker_get_acc(void* arg){ /* This takes as arguments the root node of the tree, vector for positions and vector for velocities. Performs one update step for the particles i1 to i2-1 then deletes the tree. */ arg_t* myarg = (arg_t*)arg; int i1 = myarg->i1; int i2 = myarg->i2; node_t* root = myarg->node; node_t** node; double G= myarg->G; double theta_max =myarg->theta_max; double total_acc_x=0; double total_acc_y=0; //printf("We are in worker for thread %d\n", myarg->thid); for(int i=i1; i <i2; i ++){ node = &root; //calculate forces int c=0; while(root->is_used == 0){ c++; //printf("We entered on while %d times \n",c ); //printf("CURRENTLY ON NODE: %d, %lf, %lf \n", (*node)->depth, (*node)->cm_x, //(*node)->cm_y); //print_qtree(root); // Look if we are on a external node. double x_direction = (myarg->pos_x)[i] - (*node)->cm_x; //printf("x_direction : %lf \n", x_direction); double y_direction = (myarg->pos_y)[i] - (*node)->cm_y; //printf("y_direction: %lf \n", y_direction); double dist_to_node = sqrt(x_direction*x_direction + y_direction*y_direction); double tol= 1.0e-10; // if((*node)->is_used || dist_to_node < tol || (*node)->tot_mass < 0){ //its the same particle or its already used (*node)->is_used = 1; node = &root; }else if((*node)->right_up && (*node)->width/dist_to_node > theta_max){ /*its internal node, and we need to go deeper*/ int exp= (*node)->right_up->is_used + (*node)->right_down->is_used + (*node)->left_up->is_used + (*node)->left_down->is_used; //printf("exp: %d \n", exp); switch (exp) { case 0: //no child is used so we start with right up node = &(*node)->right_up; break; case 1: node = &(*node)->right_down; break; case 2: node = &(*node)->left_up; break; case 3: node = &(*node)->left_down; break; case 4: { //every child is used so we mark current node as used and go to root (*node)->is_used = 1; node = &root; break; } //we need brackets to define scope since we are declaring a variable default: printf("Something went quite wrong"); } }else{ double denominator = (dist_to_node+epsilon_0)*(dist_to_node+epsilon_0)*(dist_to_node+epsilon_0); //add to the global varaibles total_acc_x += G* (*node)->tot_mass*x_direction/denominator; total_acc_y += G* (*node)->tot_mass*y_direction/denominator; (*node)->is_used = 1; node = &root; } } //printf("Updating postion for particle %d, in thread %d \n", i, myarg->thid); //printf("Acceleration on %d: (%lf , %lf ) \n", i+1, total_acc_x, total_acc_y); myarg->vx[i] += myarg->delta_t * total_acc_x; myarg->vy[i] += myarg->delta_t * total_acc_y; myarg->pos_x[i] += myarg->delta_t * myarg->vx[i]; myarg->pos_y[i] += myarg->delta_t * myarg->vy[i]; //printf("pos: (%lf, %lf) \n", myarg->pos_x[i], myarg->pos_y[i]); //set acceleration to 0 and mark the tree as not used //once again for the next particle total_acc_x=0; total_acc_y=0; mark_as_not_use_tree(&root); } //we are done with the tree so we delete it. delete_tree(&root); //pthread_exit((void*) (intptr_t) myarg->thid); } int main(int argc, char *args[]){ if (argc!=8){ printf("Invalid number of arguments \n"); printf("galsim expects: N filename nsteps delta_t theta_max graphics NUM_THREADS\n"); return -1; } clock_t begin = clock(); char *file_name = args[2]; const int N = atoi(args[1]); const int n_steps = atoi(args[3]); /*not sure if this is the correct way of converting from character to double, maybe a single cast would suffice */ const double delta_t = atof(args[4]); const double theta_max = atof(args[5]); const int NUM_THREADS = atoi(args[7]); const double G = -100/(double)N; //Read the file with initial conditions FILE *file; file = fopen(file_name , "rb"); /*maybe in this case we could allocate memory for this matrix statically*/ if(file_name == NULL){ printf("ERROR reading the file"); } /*maybe in this case we could allocate memory for this matrix statically*/ double *pos_x = (double *)malloc(N*sizeof(double)); double *pos_y = (double *)malloc(N*sizeof(double)); double *vel_x = (double *)malloc(N*sizeof(double)); double *vel_y = (double *)malloc(N*sizeof(double)); double *ma = (double *)malloc(N*sizeof(double)); double *bri = (double *)malloc(N*sizeof(double)); for (int i = 0 ; i<(N) ; i++){ double x , y , vx , vy , mass , bright; fread(&x , sizeof(double) , 1 ,file); fread(&y , sizeof(double) , 1 ,file); fread(&mass , sizeof(double) , 1 ,file); fread(&vx , sizeof(double) , 1 ,file); fread(&vy , sizeof(double) , 1 ,file); fread(&bright, sizeof(double) , 1 ,file); pos_x[i] = x; pos_y[i] = y; ma[i] = mass; vel_x[i] = vx; vel_y[i] = vy; bri[i] = bright; } fclose(file); printf("We read the file \n"); //find powers of two so we only have to do it once const int K=200; double pow_2[K]; pow_2[0]=1.0; for(int i=1; i< K; i++) pow_2[i]= pow_2[i-1]/2; //initialize root // insert particles in quad tree one by one //we pass a pointer to the node since we want to //modify what node we are using (ie pointing to) //printf("Particles: \n"); //for(int i=0; i<N; i++){ // printf("particle %d: m = %lf, (%lf,%lf) \n", i, arr[i][MASS], // arr[i][POS_X], arr[i][POS_Y]); //} //printf("Printing tree .. \n"); //print_qtree(root); for (int k = 0 ; k<n_steps ; k++){ //printf("We are on step %d\n", k); //create as many trees as threads //printf("Allocating mem for root \n"); node_t** trees_root = (node_t**)malloc(sizeof(node_t*)*NUM_THREADS); for(int i=0; i< NUM_THREADS; i++){ node_t* root = (node_t*)malloc(sizeof(node_t)); root->depth = 1; root->body_id = i; root->x_lim = 0.5; root->y_lim = 0.5; root->is_used = 0; root->width = 0.5; root->tot_mass = -1.0; root->left_down = NULL; root->left_up = NULL; root->right_up=NULL; root->right_down=NULL; trees_root[i] = root; //printf("Created root %d ... \n", i); /* int depth; int body_id; int is_used; double x_lim; //x division (middle point in x) double y_lim; // y division (middle point in y) double width; //width of the box double cm_x; // = 0, this points to 0 and double cm_y; //center of mas s of the quadrant double tot_mass; // = 0, total mass of the quadrant struct tree_node *left_down; //Q3 child struct tree_node *left_up; //Q2 child struct tree_node *right_down; //Q4 child struct tree_node *right_up; //Q1 child*/ } /// CHECKING IF ITS OK arg_t* arg_thread = (arg_t*)malloc(NUM_THREADS*sizeof(arg_t)); for(int t = 0; t< NUM_THREADS; t++){ printf("Root %d, depth: %d, %lf. Pls be different: %d\n", t, trees_root[t]->depth, trees_root[t]->x_lim, trees_root[t]->body_id ); } int id_tar; //Create the trees for step K for(int j =0; j < NUM_THREADS; j++){ for(int i=0; i<N; i++){ id_tar = i; insert(&(trees_root[j]),pos_x[i], pos_y[i], ma[i], pow_2, id_tar); } } //printf("Inserted nodes ...\n"); //Start threads int rc; int t; pthread_t *thread = (pthread_t*)malloc(sizeof(pthread_t)*NUM_THREADS); pthread_attr_t attr; /* Initialize thread attr and set to JOINABLE*/ pthread_attr_init(&attr); //initializes thread attributes with default values pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); //set it to detached //printf("ceating threads \n"); for(t=0; t<NUM_THREADS; t++) { printf("Main: creating thread %d\n", t); //prepare thread arguments arg_t* thread_arg = &arg_thread[t]; thread_arg->thid = t; thread_arg->i1 = N/NUM_THREADS*t; thread_arg->i2 = N/NUM_THREADS*(t+1); thread_arg->theta_max = theta_max; thread_arg->G = G; thread_arg->delta_t = delta_t; thread_arg->pos_x = &pos_x[0]; thread_arg->pos_y = &pos_y[0]; thread_arg->vx = &vel_x[0]; thread_arg->vy= &vel_y[0]; thread_arg->node = trees_root[t]; rc = pthread_create(&thread[t], &attr, worker_get_acc, thread_arg); /*if (rc) { printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); }*/ } //free(arg_thread); // MAIN CAN TAKE CARE OF THE REST. (calling worker again) //destroy thread attr and join before deleting tree pthread_attr_destroy(&attr); void* status; for(int t=0; t<NUM_THREADS; t++) { rc = pthread_join(thread[t], &status); if (rc) { //printf("ERROR; return code from pthread_join() is %d\n", rc); exit(-1); } // printf("Main: completed join with thread %d having a status of %ld\n",t,(long)status); } //delete trees THIS IS probably better to put it on the worker function for each //thread free(thread); free(trees_root); free(arg_thread); } FILE * fout = fopen("result.gal", "w+"); //check succesful creation/opening of results file if (fout == NULL){ printf("ERROR opening the output file"); exit(1); // added exit to stop prgram too } // print_struct(n,galaxy); for (int j=0; j<N; j++){ double x , y , vx , vy; x = pos_x[j]; y = pos_y[j]; vx = vel_x[j]; vy = vel_y[j]; fwrite(&x, sizeof(double), 1, fout); fwrite(&y, sizeof(double), 1, fout); fwrite(&ma[j] , sizeof(double), 1, fout); fwrite(&vx , sizeof(double), 1, fout); fwrite(&vy, sizeof(double), 1, fout); fwrite(&bri[j], sizeof(double), 1, fout); } // print_file(N, fout); // print_file(N,fout); fclose(fout); free(pos_x); free(pos_y); free(vel_x); free(vel_y); free(ma); free(bri); return 0; }
C
/* ------------------------------------------------------------------------------ Licensing information can be found at the end of the file. ------------------------------------------------------------------------------ cute_math2d.h - v1.00 SUMMARY: 2d vector algebra implementation in C++. Makes use of operator overloading and function overloading, so not quite compatible with pure C. Here's a recommended alternative for pure C in 2d/3d: https://github.com/ferreiradaselva/mathc Note: No SIMD support. Many 2d applications run quite fast in scalar operations without the need for any vectorization. Adding SIMD support to cute_math2d would increase implementation difficulty and bloat the header quite a bit. As such the initial release went with pure scalar. Note: This header is basically a C++ port of the math from cute_c2.h: https://github.com/RandyGaul/cute_headers/blob/master/cute_c2.h Revision history: 1.00 (11/02/2017) initial release */ #if !defined(CUTE_MATH2D_H) // 2d vector struct v2 { v2() {} v2(float x, float y) : x(x), y(y) {} float x; float y; }; using vec2 = v2; // 2d rotation composed of cos/sin pair struct rotation { float s; float c; }; // 2d matrix struct m2 { v2 x; v2 y; }; // 2d affine transformation struct transform { rotation r; v2 p; // translation, or position }; // 2d plane, aka line struct halfspace { v2 n; // normal float d; // distance to origin; d = ax + by = dot(n, p) }; struct ray { v2 p; // position v2 d; // direction (normalized) float t; // distance along d from position p to find endpoint of ray }; struct raycast { float t; // time of impact v2 n; // normal of surface at impact (unit length) }; struct circle { float r; v2 p; }; struct aabb { v2 min; v2 max; }; #define CUTE_MATH2D_INLINE inline #include <cmath> // scalar ops CUTE_MATH2D_INLINE float min(float a, float b) { return a < b ? a : b; } CUTE_MATH2D_INLINE float max(float a, float b) { return b < a ? a : b; } CUTE_MATH2D_INLINE float clamp(float a, float lo, float hi) { return max(lo, min(a, hi)); } CUTE_MATH2D_INLINE float sign(float a) { return a < 0 ? -1.0f : 1.0f; } CUTE_MATH2D_INLINE float intersect(float da, float db) { return da / (da - db); } // vector ops CUTE_MATH2D_INLINE v2 operator+(v2 a, v2 b) { return v2(a.x + b.x, a.y + b.y); } CUTE_MATH2D_INLINE v2 operator-(v2 a, v2 b) { return v2(a.x - b.x, a.y - b.y); } CUTE_MATH2D_INLINE v2& operator+=(v2& a, v2 b) { return a = a + b; } CUTE_MATH2D_INLINE v2& operator-=(v2& a, v2 b) { return a = a - b; } CUTE_MATH2D_INLINE float dot(v2 a, v2 b) { return a.x * b.x + a.y * b.y; } CUTE_MATH2D_INLINE v2 operator*(v2 a, float b) { return v2(a.x * b, a.y * b); } CUTE_MATH2D_INLINE v2 operator*(v2 a, v2 b) { return v2(a.x * b.x, a.y * b.y); } CUTE_MATH2D_INLINE v2& operator*=(v2& a, float b) { return a = a * b; } CUTE_MATH2D_INLINE v2& operator*=(v2& a, v2 b) { return a = a * b; } CUTE_MATH2D_INLINE v2 operator/(v2 a, float b) { return v2(a.x / b, a.y / b); } CUTE_MATH2D_INLINE v2& operator/=(v2& a, float b) { return a = a / b; } CUTE_MATH2D_INLINE v2 skew(v2 a) { return v2(-a.y, a.x); } CUTE_MATH2D_INLINE v2 ccw90(v2 a) { return v2(a.y, -a.x); } CUTE_MATH2D_INLINE float det2(v2 a, v2 b) { return a.x * b.y - a.y * b.x; } CUTE_MATH2D_INLINE v2 min(v2 a, v2 b) { return v2(min(a.x, b.x), min(a.y, b.y)); } CUTE_MATH2D_INLINE v2 max(v2 a, v2 b) { return v2(max(a.x, b.x), max(a.y, b.y)); } CUTE_MATH2D_INLINE v2 clamp(v2 a, v2 lo, v2 hi) { return max(lo, min(a, hi)); } CUTE_MATH2D_INLINE v2 abs(v2 a ) { return v2(abs(a.x), abs(a.y)); } CUTE_MATH2D_INLINE float hmin(v2 a ) { return min(a.x, a.y); } CUTE_MATH2D_INLINE float hmax(v2 a ) { return max(a.x, a.y); } CUTE_MATH2D_INLINE float len(v2 a) { return sqrt(dot(a, a)); } CUTE_MATH2D_INLINE float distance(v2 a, v2 b) { return sqrt(powf((a.x - b.x), 2) + powf((a.y - b.y), 2)); } CUTE_MATH2D_INLINE v2 norm(v2 a) { return a / len(a); } CUTE_MATH2D_INLINE v2 operator-(v2 a) { v2(-a.x, -a.y); } CUTE_MATH2D_INLINE v2 lerp(v2 a, v2 b, float t) { return a + (b - a) * t; } CUTE_MATH2D_INLINE int operator<(v2 a, v2 b) { return a.x < b.x && a.y < b.y; } CUTE_MATH2D_INLINE int operator>(v2 a, v2 b) { return a.x > b.x && a.y > b.y; } CUTE_MATH2D_INLINE int operator<=(v2 a, v2 b) { return a.x <= b.x && a.y <= b.y; } CUTE_MATH2D_INLINE int operator>=(v2 a, v2 b) { return a.x >= b.x && a.y >= b.y; } CUTE_MATH2D_INLINE int parallel(v2 a, v2 b, float tol) { float k = len(a) / len(b); b = b * k; if (abs(a.x - b.x) < tol && abs(a.y - b.y) < tol ) return 1; return 0; } // rotation ops CUTE_MATH2D_INLINE rotation make_rotation(float radians) { rotation r; r.s = sin(radians); r.c = cos(radians); return r; } CUTE_MATH2D_INLINE rotation make_rotation() { rotation r; r.c = 1.0f; r.s = 0; return r; } CUTE_MATH2D_INLINE v2 x_axis(rotation r) { return v2(r.c, r.s); } CUTE_MATH2D_INLINE v2 y_axis(rotation r) { return v2(-r.s, r.c); } CUTE_MATH2D_INLINE v2 mul(rotation a, v2 b) { return v2(a.c * b.x - a.s * b.y, a.s * b.x + a.c * b.y); } CUTE_MATH2D_INLINE v2 mulT(rotation a, v2 b) { return v2(a.c * b.x + a.s * b.y, -a.s * b.x + a.c * b.y); } CUTE_MATH2D_INLINE rotation mul(rotation a, rotation b) { rotation c; c.c = a.c * b.c - a.s * b.s; c.s = a.s * b.c + a.c * b.s; return c; } CUTE_MATH2D_INLINE rotation mulT(rotation a, rotation b) { rotation c; c.c = a.c * b.c + a.s * b.s; c.s = a.c * b.s - a.s * b.c; return c; } CUTE_MATH2D_INLINE v2 mul(m2 a, v2 b) { v2 c; c.x = a.x.x * b.x + a.y.x * b.y; c.y = a.x.y * b.x + a.y.y * b.y; return c; } CUTE_MATH2D_INLINE v2 mulT(m2 a, v2 b) { v2 c; c.x = a.x.x * b.x + a.x.y * b.y; c.y = a.y.x * b.x + a.y.y * b.y; return c; } CUTE_MATH2D_INLINE m2 mul(m2 a, m2 b) { m2 c; c.x = mul(a, b.x); c.y = mul(a, b.y); return c; } CUTE_MATH2D_INLINE m2 mulT(m2 a, m2 b) { m2 c; c.x = mulT(a, b.x); c.y = mulT(a, b.y); return c; } // transform ops CUTE_MATH2D_INLINE transform make_transform() { transform x; x.p = v2(0, 0); x.r = make_rotation(); return x; } CUTE_MATH2D_INLINE transform make_transform(v2 p, float radians) { transform x; x.r = make_rotation(radians); x.p = p; return x; } CUTE_MATH2D_INLINE v2 mul(transform a, v2 b) { return mul(a.r, b) + a.p; } CUTE_MATH2D_INLINE v2 mulT(transform a, v2 b) { return mulT(a.r, b - a.p); } CUTE_MATH2D_INLINE transform mul(transform a, transform b) { transform c; c.r = mul(a.r, b.r); c.p = mul( a.r, b.p ) + a.p; return c; } CUTE_MATH2D_INLINE transform mulT(transform a, transform b) { transform c; c.r = mulT(a.r, b.r); c.p = mulT(a.r, b.p - a.p); return c; } // halfspace ops CUTE_MATH2D_INLINE v2 origin(halfspace h) { return h.n * h.d; } CUTE_MATH2D_INLINE float distance(halfspace h, v2 p) { return dot(h.n, p) - h.d; } CUTE_MATH2D_INLINE v2 project(halfspace h, v2 p) { return p - h.n * distance(h, p); } CUTE_MATH2D_INLINE halfspace mul(transform a, halfspace b) { halfspace c; c.n = mul(a.r, b.n); c.d = dot(mul(a, origin(b) ), c.n); return c; } CUTE_MATH2D_INLINE halfspace mulT(transform a, halfspace b) { halfspace c; c.n = mulT(a.r, b.n); c.d = dot(mulT(a, origin(b) ), c.n); return c; } CUTE_MATH2D_INLINE v2 intersect(v2 a, v2 b, float da, float db) { return a + (b - a) * (da / (da - db)); } // aabb helpers CUTE_MATH2D_INLINE aabb make_aabb(v2 min, v2 max) { aabb bb; bb.min = min; bb.max = max; return bb; } CUTE_MATH2D_INLINE aabb make_aabb_center_half_extents(v2 center, v2 half_extents) { aabb bb; bb.min = center - half_extents; bb.max = center + half_extents; return bb; } CUTE_MATH2D_INLINE float width(aabb bb) { return bb.max.x - bb.min.x; } CUTE_MATH2D_INLINE float height(aabb bb) { return bb.max.y - bb.min.y; } CUTE_MATH2D_INLINE float half_width(aabb bb) { return width(bb) * 0.5f; } CUTE_MATH2D_INLINE float half_height(aabb bb) { return height(bb) * 0.5f; } CUTE_MATH2D_INLINE v2 half_extents(aabb bb) { return (bb.max - bb.min) * 0.5f; }; CUTE_MATH2D_INLINE v2 min(aabb bb) { return bb.min; } CUTE_MATH2D_INLINE v2 max(aabb bb) { return bb.max; } CUTE_MATH2D_INLINE v2 midpoint(aabb bb) { return (bb.min + bb.max) * 0.5f; } CUTE_MATH2D_INLINE v2 top_left(aabb bb) { return v2(bb.min.x, bb.max.y); } CUTE_MATH2D_INLINE v2 top_right(aabb bb) { return v2(bb.max.x, bb.max.y); } CUTE_MATH2D_INLINE v2 bottom_left(aabb bb) { return v2(bb.min.x, bb.min.y); } CUTE_MATH2D_INLINE v2 bottom_right(aabb bb) { return v2(bb.max.x, bb.min.y); } CUTE_MATH2D_INLINE int contains(aabb bb, v2 p) { p >= bb.min && p <= bb.max; } CUTE_MATH2D_INLINE int contains(aabb a, aabb b) { a.min >= b.min && a.max <= b.max; } CUTE_MATH2D_INLINE float surface_area(aabb bb) { return 2.0f * width(bb) * height(bb); } CUTE_MATH2D_INLINE float area(aabb bb) { return width(bb) * height(bb); } CUTE_MATH2D_INLINE v2 clamp(aabb bb, v2 p) { return clamp(p, bb.min, bb.max); } CUTE_MATH2D_INLINE aabb clamp(aabb a, aabb b) { return make_aabb(clamp(a.min, b.min, b.max), clamp(a.max, b.min, b.max)); } CUTE_MATH2D_INLINE int overlaps(aabb a, aabb b) { int d0 = b.max.x < a.min.x; int d1 = a.max.x < b.min.x; int d2 = b.max.y < a.min.y; int d3 = a.max.y < b.min.y; return !(d0 | d1 | d2 | d3); } CUTE_MATH2D_INLINE aabb make_aabb(v2* verts, int count) { v2 min = verts[0]; v2 max = min; for (int i = 0; i < count; ++i) { min = ::min(min, verts[i]); max = ::max(max, verts[i]); } return make_aabb(min, max); } CUTE_MATH2D_INLINE void aabb_verts(v2* out, aabb* bb) { out[0] = bb->min; out[1] = v2(bb->max.x, bb->min.y); out[2] = bb->max; out[3] = v2(bb->min.x, bb->max.y); } // circle helpers CUTE_MATH2D_INLINE float area(circle c) { return 3.14159265f * c.r * c.r; } CUTE_MATH2D_INLINE float surface_area(circle c) { return 2.0f * 3.14159265f * c.r; } CUTE_MATH2D_INLINE circle mul(transform tx, circle a) { circle b; b.p = mul(tx, a.p); b.r = a.r; return b; } // ray ops CUTE_MATH2D_INLINE v2 impact(ray r, float t) { return r.p + r.d * t; } CUTE_MATH2D_INLINE int ray_to_halfpsace(ray A, halfspace B, raycast* out) { float da = distance(B, A.p); float db = distance(B, impact(A, A.t)); if (da * db > 0) return 0; out->n = B.n * sign(da); out->t = intersect(da, db); } CUTE_MATH2D_INLINE int ray_to_circle(ray A, circle B, raycast* out) { v2 p = B.p; v2 m = A.p - p; float c = dot(m, m) - B.r * B.r; float b = dot(m, A.d); float disc = b * b - c; if (disc < 0) return 0; float t = -b - sqrt(disc); if (t >= 0 && t <= A.t) { out->t = t; v2 impact = ::impact(A, t); out->n = norm(impact - p); return 1; } return 0; } CUTE_MATH2D_INLINE int ray_to_aabb(ray A, aabb B, raycast* out) { v2 inv = v2(1.0f / A.d.x, 1.0f / A.d.y); v2 d0 = (B.min - A.p) * inv; v2 d1 = (B.max - A.p) * inv; v2 v0 = min(d0, d1); v2 v1 = max(d0, d1); float lo = hmax(v0); float hi = hmin(v1); if (hi >= 0 && hi >= lo && lo <= A.t) { v2 c = midpoint(B); c = impact(A, lo) - c; v2 abs_c = abs(c); if (abs_c.x > abs_c.y) out->n = v2(sign(c.x), 0); else out->n = v2(0, sign(c.y)); out->t = lo; return 1; } return 0; } #define CUTE_MATH2D_H #endif /* ------------------------------------------------------------------------------ This software is available under 2 licenses - you may choose the one you like. ------------------------------------------------------------------------------ ALTERNATIVE A - zlib license Copyright (c) 2017 Randy Gaul http://www.randygaul.net This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 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. ------------------------------------------------------------------------------ */
C
/* smartmed.c: SmartMedia Flash ROM emulation The SmartMedia is a Flash ROM in a fancy card. It is used in a variety of digital devices (still cameras...) and can be interfaced with a computer. References: Datasheets for various SmartMedia chips were found on Samsung and Toshiba's sites (http://www.toshiba.com/taec and http://www.samsung.com/Products/Semiconductor/Flash/FlashCard/SmartMedia) TODO: * support multi-plane mode? * use HD-format images instead of our experimental custom format? Raphael Nabet 2004 */ #include "emu.h" #include "smartmed.h" #include "harddisk.h" #include "imagedev/harddriv.h" #define MAX_SMARTMEDIA 1 /* machine-independent big-endian 32-bit integer */ typedef struct UINT32BE { UINT8 bytes[4]; } UINT32BE; INLINE UINT32 get_UINT32BE(UINT32BE word) { return (word.bytes[0] << 24) | (word.bytes[1] << 16) | (word.bytes[2] << 8) | word.bytes[3]; } #ifdef UNUSED_FUNCTION INLINE void set_UINT32BE(UINT32BE *word, UINT32 data) { word->bytes[0] = (data >> 24) & 0xff; word->bytes[1] = (data >> 16) & 0xff; word->bytes[2] = (data >> 8) & 0xff; word->bytes[3] = data & 0xff; } #endif /* SmartMedia image header */ typedef struct disk_image_header { UINT8 version; UINT32BE page_data_size; UINT32BE page_total_size; UINT32BE num_pages; UINT32BE log2_pages_per_block; } disk_image_header; typedef struct disk_image_format_2_header { UINT8 data1[3]; UINT8 padding1[256-3]; UINT8 data2[16]; UINT8 data3[16]; UINT8 padding2[768-32]; } disk_image_format_2_header; enum { header_len = sizeof(disk_image_header) }; enum sm_mode_t { SM_M_INIT, // initial state SM_M_READ, // read page data SM_M_PROGRAM, // program page data SM_M_ERASE, // erase block data SM_M_READSTATUS,// read status SM_M_READID, // read ID SM_M_30 }; enum pointer_sm_mode_t { SM_PM_A, // accessing first 256-byte half of 512-byte data field SM_PM_B, // accessing second 256-byte half of 512-byte data field SM_PM_C // accessing spare field }; typedef struct _smartmedia_t smartmedia_t; struct _smartmedia_t { int page_data_size; // 256 for a 2MB card, 512 otherwise int page_total_size;// 264 for a 2MB card, 528 otherwise int num_pages; // 8192 for a 4MB card, 16184 for 8MB, 32768 for 16MB, // 65536 for 32MB, 131072 for 64MB, 262144 for 128MB... // 0 means no card loaded int log2_pages_per_block; // log2 of number of pages per erase block (usually 4 or 5) UINT8 *data_ptr; // FEEPROM data area UINT8 *data_uid_ptr; sm_mode_t mode; // current operation mode pointer_sm_mode_t pointer_mode; // pointer mode int page_addr; // page address pointer int byte_addr; // byte address pointer int addr_load_ptr; // address load pointer int status; // current status int accumulated_status; // accumulated status UINT8 *pagereg; // page register used by program command UINT8 id[3]; // chip ID UINT8 mp_opcode; // multi-plane operation code int mode_3065; }; /*************************************************************************** INLINE FUNCTIONS ***************************************************************************/ INLINE smartmedia_t *get_safe_token(device_t *device) { assert(device != NULL); assert(device->type() == SMARTMEDIA); return (smartmedia_t *)downcast<legacy_device_base *>(device)->token(); } INLINE const smartmedia_cartslot_config *get_config(const device_t *device) { assert(device != NULL); assert(device->type() == SMARTMEDIA); return (const smartmedia_cartslot_config *) downcast<const legacy_device_base *>(device)->inline_config(); } /* Init a SmartMedia image */ static DEVICE_START( smartmedia ) { smartmedia_t *sm = get_safe_token(device); sm->page_data_size = 0; sm->page_total_size = 0; sm->num_pages = 0; sm->log2_pages_per_block = 0; sm->data_ptr = NULL; sm->data_uid_ptr = NULL; sm->mode = SM_M_INIT; sm->pointer_mode = SM_PM_A; sm->page_addr = 0; sm->byte_addr = 0; sm->status = 0x40; sm->accumulated_status = 0; sm->pagereg = NULL; sm->id[0] = sm->id[1] = sm->id[2] = 0; sm->mp_opcode = 0; sm->mode_3065 = 0; } /* Load a SmartMedia image */ static DEVICE_IMAGE_LOAD( smartmedia_format_1 ) { device_t *device = &image.device(); smartmedia_t *sm = get_safe_token(device); disk_image_header custom_header; int bytes_read; bytes_read = image.fread(&custom_header, sizeof(custom_header)); if (bytes_read != sizeof(custom_header)) { return IMAGE_INIT_FAIL; } if (custom_header.version > 1) { return IMAGE_INIT_FAIL; } sm->page_data_size = get_UINT32BE(custom_header.page_data_size); sm->page_total_size = get_UINT32BE(custom_header.page_total_size); sm->num_pages = get_UINT32BE(custom_header.num_pages); sm->log2_pages_per_block = get_UINT32BE(custom_header.log2_pages_per_block); sm->data_ptr = auto_alloc_array(device->machine(), UINT8, sm->page_total_size*sm->num_pages); sm->data_uid_ptr = auto_alloc_array(device->machine(), UINT8, 256 + 16); sm->mode = SM_M_INIT; sm->pointer_mode = SM_PM_A; sm->page_addr = 0; sm->byte_addr = 0; sm->status = 0x40; if (image.is_readonly()) sm->status |= 0x80; sm->accumulated_status = 0; sm->pagereg = auto_alloc_array(device->machine(), UINT8, sm->page_total_size); sm->id[0] = sm->id[1] = sm->id[2] = 0; if (custom_header.version == 0) { image.fread(sm->id, 2); image.fread(&sm->mp_opcode, 1); } else if (custom_header.version == 1) { image.fread(sm->id, 3); image.fread(&sm->mp_opcode, 1); image.fread(sm->data_uid_ptr, 256 + 16); } image.fread(sm->data_ptr, sm->page_total_size*sm->num_pages); return IMAGE_INIT_PASS; } static int detect_geometry( smartmedia_t *sm, UINT8 id1, UINT8 id2) { int result = 0; switch (id1) { case 0xEC : { switch (id2) { case 0xA4 : sm->page_data_size = 0x0100; sm->num_pages = 0x00800; sm->page_total_size = 0x0108; sm->log2_pages_per_block = 0; result = 1; break; case 0x6E : sm->page_data_size = 0x0100; sm->num_pages = 0x01000; sm->page_total_size = 0x0108; sm->log2_pages_per_block = 0; result = 1; break; case 0xEA : sm->page_data_size = 0x0100; sm->num_pages = 0x02000; sm->page_total_size = 0x0108; sm->log2_pages_per_block = 0; result = 1; break; case 0xE3 : sm->page_data_size = 0x0200; sm->num_pages = 0x02000; sm->page_total_size = 0x0210; sm->log2_pages_per_block = 0; result = 1; break; case 0xE6 : sm->page_data_size = 0x0200; sm->num_pages = 0x04000; sm->page_total_size = 0x0210; sm->log2_pages_per_block = 0; result = 1; break; case 0x73 : sm->page_data_size = 0x0200; sm->num_pages = 0x08000; sm->page_total_size = 0x0210; sm->log2_pages_per_block = 0; result = 1; break; case 0x75 : sm->page_data_size = 0x0200; sm->num_pages = 0x10000; sm->page_total_size = 0x0210; sm->log2_pages_per_block = 0; result = 1; break; case 0x76 : sm->page_data_size = 0x0200; sm->num_pages = 0x20000; sm->page_total_size = 0x0210; sm->log2_pages_per_block = 0; result = 1; break; case 0x79 : sm->page_data_size = 0x0200; sm->num_pages = 0x40000; sm->page_total_size = 0x0210; sm->log2_pages_per_block = 0; result = 1; break; } } break; case 0x98 : { switch (id2) { case 0x75 : sm->page_data_size = 0x0200; sm->num_pages = 0x10000; sm->page_total_size = 0x0210; sm->log2_pages_per_block = 0; result = 1; break; } } break; } return result; } static DEVICE_IMAGE_LOAD( smartmedia_format_2 ) { device_t *device = &image.device(); smartmedia_t *sm = get_safe_token(device); disk_image_format_2_header custom_header; int bytes_read, i, j; bytes_read = image.fread(&custom_header, sizeof(custom_header)); if (bytes_read != sizeof(custom_header)) { return IMAGE_INIT_FAIL; } if ((custom_header.data1[0] != 0xEC) && (custom_header.data1[0] != 0x98)) { return IMAGE_INIT_FAIL; } if (!detect_geometry( sm, custom_header.data1[0], custom_header.data1[1])) { return IMAGE_INIT_FAIL; } sm->data_ptr = auto_alloc_array(device->machine(), UINT8, sm->page_total_size*sm->num_pages); sm->data_uid_ptr = auto_alloc_array(device->machine(), UINT8, 256 + 16); sm->mode = SM_M_INIT; sm->pointer_mode = SM_PM_A; sm->page_addr = 0; sm->byte_addr = 0; sm->status = 0x40; if (image.is_readonly()) sm->status |= 0x80; sm->accumulated_status = 0; sm->pagereg = auto_alloc_array(device->machine(), UINT8, sm->page_total_size); memcpy( sm->id, custom_header.data1, 3); sm->mp_opcode = 0; for (i=0;i<8;i++) { memcpy( sm->data_uid_ptr + i * 32, custom_header.data2, 16); for (j=0;j<16;j++) sm->data_uid_ptr[i*32+16+j] = custom_header.data2[j] ^ 0xFF; } memcpy( sm->data_uid_ptr + 256, custom_header.data3, 16); image.fread(sm->data_ptr, sm->page_total_size*sm->num_pages); return IMAGE_INIT_PASS; } static DEVICE_IMAGE_LOAD( smartmedia ) { int result; UINT64 position; // try format 1 position = image.ftell(); result = DEVICE_IMAGE_LOAD_NAME(smartmedia_format_1)(image); if (result != IMAGE_INIT_PASS) { // try format 2 image.fseek( position, SEEK_SET); result = DEVICE_IMAGE_LOAD_NAME(smartmedia_format_2)(image); } return result; } /* Unload a SmartMedia image */ static DEVICE_IMAGE_UNLOAD( smartmedia ) { device_t *device = &image.device(); smartmedia_t *sm = get_safe_token(device); sm->page_data_size = 0; sm->page_total_size = 0; sm->num_pages = 0; sm->log2_pages_per_block = 0; sm->data_ptr = NULL; sm->data_uid_ptr = NULL; sm->mode = SM_M_INIT; sm->pointer_mode = SM_PM_A; sm->page_addr = 0; sm->byte_addr = 0; sm->status = 0x40; sm->accumulated_status = 0; sm->pagereg = auto_alloc_array(device->machine(), UINT8, sm->page_total_size); sm->id[0] = sm->id[1] = sm->id[2] = 0; sm->mp_opcode = 0; sm->mode_3065 = 0; return; } int smartmedia_present(device_t *device) { smartmedia_t *sm = get_safe_token(device); return sm->num_pages != 0; } int smartmedia_protected(device_t *device) { smartmedia_t *sm = get_safe_token(device); return (sm->status & 0x80) != 0; } /* write a byte to SmartMedia command port */ void smartmedia_command_w(device_t *device, UINT8 data) { smartmedia_t *sm = get_safe_token(device); if (!smartmedia_present(device)) return; switch (data) { case 0xff: sm->mode = SM_M_INIT; sm->pointer_mode = SM_PM_A; sm->status = (sm->status & 0x80) | 0x40; sm->accumulated_status = 0; sm->mode_3065 = 0; break; case 0x00: sm->mode = SM_M_READ; sm->pointer_mode = SM_PM_A; sm->page_addr = 0; sm->addr_load_ptr = 0; break; case 0x01: if (sm->page_data_size <= 256) { logerror("smartmedia: unsupported upper data field select (256-byte pages)\n"); sm->mode = SM_M_INIT; } else { sm->mode = SM_M_READ; sm->pointer_mode = SM_PM_B; sm->page_addr = 0; sm->addr_load_ptr = 0; } break; case 0x50: sm->mode = SM_M_READ; sm->pointer_mode = SM_PM_C; sm->page_addr = 0; sm->addr_load_ptr = 0; break; case 0x80: sm->mode = SM_M_PROGRAM; sm->page_addr = 0; sm->addr_load_ptr = 0; memset(sm->pagereg, 0xff, sm->page_total_size); break; case 0x10: case 0x15: if (sm->mode != SM_M_PROGRAM) { logerror("smartmedia: illegal page program confirm command\n"); sm->mode = SM_M_INIT; } else { int i; sm->status = (sm->status & 0x80) | sm->accumulated_status; for (i=0; i<sm->page_total_size; i++) sm->data_ptr[sm->page_addr*sm->page_total_size + i] &= sm->pagereg[i]; sm->status |= 0x40; if (data == 0x15) sm->accumulated_status = sm->status & 0x1f; else sm->accumulated_status = 0; sm->mode = SM_M_INIT; } break; /*case 0x11: break;*/ case 0x60: sm->mode = SM_M_ERASE; sm->page_addr = 0; sm->addr_load_ptr = 0; break; case 0xd0: if (sm->mode != SM_M_PROGRAM) { logerror("smartmedia: illegal block erase confirm command\n"); sm->mode = SM_M_INIT; } else { sm->status &= 0x80; memset(sm->data_ptr + (sm->page_addr & (-1 << sm->log2_pages_per_block)), 0, (size_t)(1 << sm->log2_pages_per_block)); sm->status |= 0x40; sm->mode = SM_M_INIT; if (sm->pointer_mode == SM_PM_B) sm->pointer_mode = SM_PM_A; } break; case 0x70: sm->mode = SM_M_READSTATUS; break; /*case 0x71: break;*/ case 0x90: sm->mode = SM_M_READID; sm->addr_load_ptr = 0; break; /*case 0x91: break;*/ case 0x30: sm->mode = SM_M_30; break; case 0x65: if (sm->mode != SM_M_30) { logerror("smartmedia: unexpected address port write\n"); sm->mode = SM_M_INIT; } else { sm->mode_3065 = 1; } break; default: logerror("smartmedia: unsupported command 0x%02x\n", data); sm->mode = SM_M_INIT; break; } } /* write a byte to SmartMedia address port */ void smartmedia_address_w(device_t *device, UINT8 data) { smartmedia_t *sm = get_safe_token(device); if (!smartmedia_present(device)) return; switch (sm->mode) { case SM_M_INIT: logerror("smartmedia: unexpected address port write\n"); break; case SM_M_READ: case SM_M_PROGRAM: if (sm->addr_load_ptr == 0) { switch (sm->pointer_mode) { case SM_PM_A: sm->byte_addr = data; break; case SM_PM_B: sm->byte_addr = data + 256; sm->pointer_mode = SM_PM_A; break; case SM_PM_C: if (!sm->mode_3065) sm->byte_addr = (data & 0x0f) + sm->page_data_size; else sm->byte_addr = (data & 0x0f) + 256; break; } } else sm->page_addr = (sm->page_addr & ~(0xff << ((sm->addr_load_ptr-1) * 8))) | (data << ((sm->addr_load_ptr-1) * 8)); sm->addr_load_ptr++; break; case SM_M_ERASE: sm->page_addr = (sm->page_addr & ~(0xff << (sm->addr_load_ptr * 8))) | (data << (sm->addr_load_ptr * 8)); sm->addr_load_ptr++; break; case SM_M_READSTATUS: case SM_M_30: logerror("smartmedia: unexpected address port write\n"); break; case SM_M_READID: if (sm->addr_load_ptr == 0) sm->byte_addr = data; sm->addr_load_ptr++; break; } } /* read a byte from SmartMedia data port */ UINT8 smartmedia_data_r(device_t *device) { UINT8 reply = 0; smartmedia_t *sm = get_safe_token(device); if (!smartmedia_present(device)) return 0; switch (sm->mode) { case SM_M_INIT: case SM_M_30: logerror("smartmedia: unexpected data port read\n"); break; case SM_M_READ: if (!sm->mode_3065) reply = sm->data_ptr[sm->page_addr*sm->page_total_size + sm->byte_addr]; else reply = sm->data_uid_ptr[sm->page_addr*sm->page_total_size + sm->byte_addr]; sm->byte_addr++; if (sm->byte_addr == sm->page_total_size) { sm->byte_addr = (sm->pointer_mode != SM_PM_C) ? 0 : sm->page_data_size; sm->page_addr++; if (sm->page_addr == sm->num_pages) sm->page_addr = 0; } break; case SM_M_PROGRAM: logerror("smartmedia: unexpected data port read\n"); break; case SM_M_ERASE: logerror("smartmedia: unexpected data port read\n"); break; case SM_M_READSTATUS: reply = sm->status & 0xc1; break; case SM_M_READID: if (sm->byte_addr < 3) reply = sm->id[sm->byte_addr]; sm->byte_addr++; break; } return reply; } /* write a byte to SmartMedia data port */ void smartmedia_data_w(device_t *device, UINT8 data) { smartmedia_t *sm = get_safe_token(device); if (!smartmedia_present(device)) return; switch (sm->mode) { case SM_M_INIT: case SM_M_READ: case SM_M_30: logerror("smartmedia: unexpected data port write\n"); break; case SM_M_PROGRAM: sm->pagereg[sm->byte_addr] = data; sm->byte_addr++; if (sm->byte_addr == sm->page_total_size) sm->byte_addr = (sm->pointer_mode != SM_PM_C) ? 0 : sm->page_data_size; break; case SM_M_ERASE: case SM_M_READSTATUS: case SM_M_READID: logerror("smartmedia: unexpected data port write\n"); break; } } /* Initialize one SmartMedia chip: may be called at driver init or image load time (or machine init time if you don't use MESS image core) */ static DEVICE_RESET(smartmedia) { smartmedia_t *sm = get_safe_token(device); sm->mode = SM_M_INIT; sm->pointer_mode = SM_PM_A; sm->status = (sm->status & 0x80) | 0x40; sm->accumulated_status = 0; } /*------------------------------------------------- DEVICE_IMAGE_SOFTLIST_LOAD(smartmedia) -------------------------------------------------*/ static DEVICE_IMAGE_SOFTLIST_LOAD(smartmedia) { return image.load_software(swlist, swname, start_entry); } DEVICE_GET_INFO( smartmedia ) { switch ( state ) { case DEVINFO_INT_TOKEN_BYTES: info->i = sizeof(smartmedia_t); break; case DEVINFO_INT_INLINE_CONFIG_BYTES: info->i = sizeof(smartmedia_cartslot_config); break; case DEVINFO_INT_IMAGE_TYPE: info->i = IO_MEMCARD; break; case DEVINFO_INT_IMAGE_READABLE: info->i = 1; break; case DEVINFO_INT_IMAGE_WRITEABLE: info->i = 1; break; case DEVINFO_INT_IMAGE_CREATABLE: info->i = 0; break; case DEVINFO_FCT_START: info->start = DEVICE_START_NAME( smartmedia ); break; case DEVINFO_FCT_RESET: info->reset = DEVICE_RESET_NAME( smartmedia ); break; case DEVINFO_FCT_IMAGE_LOAD: info->f = (genf *) DEVICE_IMAGE_LOAD_NAME( smartmedia ); break; case DEVINFO_FCT_IMAGE_UNLOAD: info->f = (genf *) DEVICE_IMAGE_UNLOAD_NAME(smartmedia ); break; case DEVINFO_STR_NAME: strcpy( info->s, "SmartMedia Flash ROM"); break; case DEVINFO_STR_FAMILY: strcpy(info->s, "SmartMedia Flash ROM"); break; case DEVINFO_STR_SOURCE_FILE: strcpy(info->s, __FILE__); break; case DEVINFO_STR_IMAGE_FILE_EXTENSIONS: strcpy(info->s, "smc"); break; case DEVINFO_FCT_IMAGE_SOFTLIST_LOAD: info->f = (genf *) DEVICE_IMAGE_SOFTLIST_LOAD_NAME(smartmedia); break; case DEVINFO_STR_IMAGE_INTERFACE: if ( device && downcast<const legacy_image_device_base *>(device)->inline_config() && get_config(device)->interface ) { strcpy(info->s, get_config(device)->interface ); } break; } } DEFINE_LEGACY_IMAGE_DEVICE(SMARTMEDIA, smartmedia);
C
#include "stdio.h" #define ListSize 100 typedef int DataType; typedef struct { DataType data[ListSize]; int length; } SeqList; typedef struct node { DataType data; struct node *next; } ListNode; typedef ListNode *LinkList; LinkList CreateListF() { LinkList head; ListNode *p; char ch; head = NULL; ch = getchar(); while (ch != '\n') { p = (ListNode *) __attribute_malloc__(sizeof(ListNode)); p->data = ch; p->next = head; head = p; ch = getchar(); } /* * 1 * 2 3 * */ return head; } ListNode *SortTwoLink(LinkList la, LinkList lb) { ListNode *lc, *headA, *headB; headA = la; headB = lb; while (headA != NULL && headB != NULL) { lc = headA->data > headB->data ? headA : headB; // init lc->next = headA->data < headB->data ? headA : headB; // second lc = lc->next; headA = headA->next; headB = headB->next; } return lc; } int main() { return 0; } void removeList(SeqList *seqList, int index) { if (index < 0 || index > seqList->length - 1) { printf("you are wrong"); } DataType k; for (k = index; k < seqList->length - 2; k++) { seqList->data[k] = seqList->data[k + 1]; } seqList->length--; } void insertList(SeqList *seqList, int i, DataType j) { if (i < 0 || i > (seqList->length + 1)) { printf("error "); return; } for (j = seqList->length - 1; j >= i - 1; j++) { seqList->data[j + 1] = seqList->data[j]; } seqList->data[i - 1] = j; seqList->length++; }
C
#include "../../lv_examples.h" #if LV_USE_DROPDOWN && LV_BUILD_EXAMPLES /** * Create a drop down, up, left and right menus */ void lv_example_dropdown_2(void) { static const char * opts = "Apple\n" "Banana\n" "Orange\n" "Melon"; lv_obj_t * dd; dd = lv_dropdown_create(lv_scr_act()); lv_dropdown_set_options_static(dd, opts); lv_obj_align(dd, LV_ALIGN_TOP_MID, 0, 10); dd = lv_dropdown_create(lv_scr_act()); lv_dropdown_set_options_static(dd, opts); lv_dropdown_set_dir(dd, LV_DIR_BOTTOM); lv_dropdown_set_symbol(dd, LV_SYMBOL_UP); lv_obj_align(dd, LV_ALIGN_BOTTOM_MID, 0, -10); dd = lv_dropdown_create(lv_scr_act()); lv_dropdown_set_options_static(dd, opts); lv_dropdown_set_dir(dd, LV_DIR_RIGHT); lv_dropdown_set_symbol(dd, LV_SYMBOL_RIGHT); lv_obj_align(dd, LV_ALIGN_LEFT_MID, 10, 0); dd = lv_dropdown_create(lv_scr_act()); lv_dropdown_set_options_static(dd, opts); lv_dropdown_set_dir(dd, LV_DIR_LEFT); lv_dropdown_set_symbol(dd, LV_SYMBOL_LEFT); lv_obj_align(dd, LV_ALIGN_RIGHT_MID, -10, 0); } #endif
C
#include <sys/socket.h> #include <unistd.h> #include <linux/in.h> #include <signal.h> #include <string.h> #include <stdio.h> char buf[10000]; int main(){ int connfd,sock_fd; struct sockaddr_in client,info; socklen_t len; sock_fd=socket(AF_INET,SOCK_STREAM,0); bzero(&client,sizeof(client)); client.sin_family=AF_INET; client.sin_port=htons(10222); client.sin_addr.s_addr=inet_addr("192.168.0.15"); if(connect(sock_fd,(struct sockaddr*)&client,sizeof(client))<0)printf("connect error\n"); else printf("success\n"); while(scanf("%s",buf)!=EOF){ write(sock_fd,buf,strlen(buf)); read(sock_fd,buf,sizeof(buf)); printf("BUF:%s\n",buf); } return 0; }
C
//bibliotecas #include<stdio.h> #include<stdlib.h> //declaração de variaveis globais para utilizar na pilha e no programa int tam = 8, topo = -1, valor; int pilha[8]; //empilha void empilha() { if(topo == tam - 1) { printf("\n **Pilha cheia**\n"); } else { topo++; pilha[topo] = valor; } } //desempilha void desempilha() { if(topo == -1) { printf("\n **Pilha vazia**\n"); } else { valor = pilha[topo]; topo--; } } int main() { int placa, z = 0, i, aux = 0; for(i = 0; i<tam; i++) { printf("Digite a placa do %do carro: ", z++); scanf("%d", &pilha[i]); valor = pilha[i]; empilha(); } printf("Qual a placa que voce deseja consultar: "); scanf("%d", &placa); for(i = 0; i < tam; i++) { desempilha(); if(pilha[i] == placa) { aux = 1; } } if(aux = 1) { printf("\no carro da placa %d esta na vila\n", placa); } else { printf("\no carro da placa %d nao esta na vila\n", placa); } printf("\n"); for(i = tam -1; i >= 0 ; i--) { if(pilha[i] == placa) { break; } else { printf("\nO carro da placa %d precisa sair para o carro da placa %d sair.\n", pilha[i], placa); } } system("pause"); }
C
// // cdata.h // cthread // // Created by Henrique Valcanaia on 15/09/16. // Copyright © 2016 Henrique Valcanaia. All rights reserved. // #ifndef cdata_h #define cdata_h #include "support.h" enum THREAD_STATE { CREATION = 0, READY = 1, EXEC = 2, BLOCKED = 3, FINISH = 4 }; /*! @struct s_TCB @abstract Struct que representa um TCB(Thread Control Block) @field tid Thread id @field state Estado atual da thread (THREAD_STATE) @field ticket Ticket sorteado pelo escalonador @field context ucontext_t @discussion Struct utilizada para definicao do TCB. É importante ressaltar que o tipo ucontex_t NÃO é mais utilizado em versões recentes de UNIX/POSIX. */ typedef struct s_TCB { int tid; int state; int ticket; ucontext_t context; } TCB_t; typedef struct s_sem { int count; // indica se recurso está ocupado ou não (livre > 0, ocupado ≤ 0) PFILA2 fila; // ponteiro para uma fila de threads bloqueadas no semáforo } csem_t; #endif /* cdata_h */
C
#define F_CPU 16000000UL #include <avr/io.h> #include <stdlib.h> #include "LCD4bits.h" //#define data_direction DDRD //#define data_ports PORTD //#define RS PD2 //#define EN_pin PD3 int main(void) { LCD_Initialization(); //LCD_dataCharacter('t'); LCD_dataString("All work well"); int increments_Amount = 0; while (1) { char showincrementiontimes [16]; itoa(increments_Amount, showincrementiontimes, 10); LCD_position(2,1); LCD_dataString("Sure "); LCD_dataString(showincrementiontimes); LCD_dataString(" times"); _delay_ms(1000); increments_Amount++; } }
C
#include "holberton.h" /** * reset_to_98 - this function reset the valuo to 98 * @n: input pointer variable. * */ void reset_to_98(int *n) { *n = 98; }
C
#include <curl/curl.h> #include "js.h" typedef struct { char* ptr; size_t len; } string; typedef struct { char* url; napi_ref cb; napi_async_work work; string body; } req_t; static void init_string(string* s) { s->len = 0; // FIXME: replace with js_malloc s->ptr = malloc(s->len + 1); if (s->ptr == NULL) { fprintf(stderr, "malloc() failed\n"); exit(EXIT_FAILURE); } s->ptr[0] = '\0'; } static size_t write_func(void* ptr, size_t size, size_t nmemb, string* s) { size_t new_len = s->len + size * nmemb; // FIXME: replace with js_realloc s->ptr = realloc(s->ptr, new_len + 1); if (s->ptr == NULL) { fprintf(stderr, "realloc() failed\n"); exit(EXIT_FAILURE); } memcpy(s->ptr + s->len, ptr, size * nmemb); s->ptr[new_len] = '\0'; s->len = new_len; return size * nmemb; } static void execute(napi_env env, void* data) { req_t* req = (req_t*)data; CURL* curl = curl_easy_init(); if (curl) { init_string(&req->body); curl_easy_setopt(curl, CURLOPT_URL, req->url); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_func); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &req->body); CURLcode res = curl_easy_perform(curl); if (res != CURLE_OK) { JS_LOG_E("curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } curl_easy_cleanup(curl); } } static void complete(napi_env env, napi_status status, void* data) { req_t* req = (req_t*)data; napi_value argv[1]; JS_NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, req->body.ptr, req->body.len, argv)); napi_value callback; JS_NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, req->cb, &callback)); napi_value global; JS_NAPI_CALL_RETURN_VOID(env, napi_get_global(env, &global)); napi_value result; JS_NAPI_CALL_RETURN_VOID(env, napi_call_function(env, global, callback, 1, argv, &result)); JS_NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, req->cb)); JS_NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, req->work)); js_free(req->url); // FIXME: replace with js_free free(req->body.ptr); js_free(req); } static napi_value do_get(napi_env env, napi_callback_info info) { req_t* req = (req_t*)js_malloc(sizeof(req_t)); size_t argc = 2; napi_value argv[argc]; JS_NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); napi_valuetype t; JS_NAPI_CALL(env, napi_typeof(env, argv[0], &t)); JS_NAPI_ASSERT(env, t == napi_string, "Wrong first argument, string expected."); JS_NAPI_CALL(env, napi_typeof(env, argv[1], &t)); JS_NAPI_ASSERT(env, t == napi_function, "Wrong second argument, function expected."); size_t length; JS_NAPI_CALL(env, napi_get_value_string_utf8(env, argv[0], NULL, 0, &length)); req->url = (char*)js_malloc(length + 1); JS_NAPI_CALL(env, napi_get_value_string_utf8(env, argv[0], req->url, length, &length)); req->url[length] = '\0'; JS_NAPI_CALL(env, napi_create_reference(env, argv[1], 1, &req->cb)); napi_value nurl; JS_NAPI_CALL(env, napi_create_string_utf8(env, "url", NAPI_AUTO_LENGTH, &nurl)); JS_NAPI_CALL(env, napi_create_async_work(env, NULL, nurl, execute, complete, req, &req->work)); JS_NAPI_CALL(env, napi_queue_async_work(env, req->work)); napi_value undefined_value; napi_get_undefined(env, &undefined_value); return undefined_value; } static napi_value init_curl(napi_env env, napi_value exports) { JS_NAPI_SET_NAMED_METHOD(env, exports, "get", do_get); return exports; } NAPI_MODULE(curl, init_curl);
C
#include<stdio.h> #include<stdlib.h> #include<string.h> void get_memory(char** p){ *p = (char*) malloc(10); } char* get_value(){ char *p = (char*)malloc(10); strcpy(p,"haha"); return p; } int main(){ char* p = NULL; get_memory(&p); strcpy(p,"hello world"); printf("%s\n",p); free(p); p = NULL; char* value = get_value(); printf("%s \n", value); free(value); value = NULL; return 0; }
C
#ifndef _XN_SPRITE_3D_H_ #define _XN_SPRITE_3D_H_ #include <windows.h> #include "xnList.h" #pragma pack (push) #pragma pack (16) struct Vertex { float x, y, z, w; WORD fu, fv; }; #pragma pack (pop) struct UVPoint { float u, v; }; struct Triangle { DWORD a, b, c; }; struct xnUV_List { UVPoint * pUV_PointBuffer; DWORD uvPointBufferSize; DWORD uvCount; static xnUV_List * Create(DWORD bufferSize); void Free(void); void AddUV(UVPoint * uvPoint); UVPoint * GetUV(DWORD index); }; struct xnFrame3D { DWORD maxCount; DWORD vertexCount; Vertex * vertices; static xnFrame3D * Create(DWORD vertexCount); void Free(void); void AddVertex(Vertex *vertex); Vertex * GetVertex(DWORD index); void SetPosition(Vertex * pPos); void SetScale(float scale); void RotateX(float angle); void RotateY(float angle); void RotateZ(float angle); }; struct xnFrame3DList { xnList * pFrameList; xnFrame3D * pCurrFrame; static xnFrame3DList * Create(); void Free(void); void AddFrame(xnFrame3D * pFrame); xnFrame3D * GetFrame(float index); void SetUV(xnUV_List * pUV_List, WORD textWidth, WORD textHeight); }; struct xnTriangleList { Triangle * triangles; DWORD maxCount; DWORD triangleCount; static xnTriangleList * Create(DWORD triangleCount); void Free(void); void AddTriangle(Triangle * pTriangle); Triangle * GetTriangle(DWORD index); }; struct xnSprite3D_Obj { char * name; xnTriangleList * pTriangleList; static xnSprite3D_Obj * Create(char * name, DWORD triangleCount); void Free(void); xnList * GetVertexList(xnFrame3D * pFrame); }; struct xnSprite3D { xnFrame3DList * pFrameList; xnUV_List * pUVPointList; xnList * pObjectList; static xnSprite3D * LoadSprite(char * sprite3DName); void Free(void); void SetTextureSize(WORD w, WORD h); xnSprite3D_Obj * GetObject(char * objName); }; #endif
C
#include <stdio.h> int main() { int score[5]; int i, max =0; for(i = 0; i<5; i++) { printf("%d л α׷ Էϼ. : ", i+1); scanf("%d", &score[i]); } for(i = 0; i<5; i++) if(max < score[i]) max = score[i]; printf("ְ : %d", max); }
C
#include <stdio.h> int main() { int x[15], cont = 0; for(int i = 0; i < 15; i++) { printf("Insira o termo %d do vetor X\n", i+1); scanf("%d", &x[i]); } for(int i = 0; i < 15; i++) { if(x[i] % 2 == 0) { cont++; } } printf("O numero de termos pares e: %d\n", cont); return 0; }
C
#pragma warning(disable:4996) #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int get_number_of_elements(); int *get_array_elements(int n); int merge_sort(int *n, int min, int max); void merge(int *n, int min, int middle, int middle2, int max); void print_elemts(int*n, int size, int *n2); int main() { int n = 0; int *numbers; int numbers2[20]; n = get_number_of_elements(); numbers = get_array_elements(n); memcpy(numbers2, numbers, n * sizeof(numbers)); merge_sort(numbers, 0, n - 1); print_elemts(numbers, n, numbers2); getch(); return 0; } int get_number_of_elements() { int n = 0; printf("Input number of elements: "); scanf("%d", &n); return n; } int *get_array_elements(int n) { int k = 0; int i = 0; time_t t; k = n; int *numbers = (int*)calloc(n, sizeof(int)); srand(time(0)); if (numbers == NULL) { fputs("Error allocating memory", stderr); exit(0); } for (i = 0; i < n; i++) { numbers[i] = rand() % 100; } return numbers; } int merge_sort(int *n, int min, int max) { int middle; if (min < max) { middle = (min + max) / 2; merge_sort(n, min, middle); merge_sort(n, middle + 1, max); merge(n, min, middle, middle + 1, max); } } void merge(int *n, int min, int middle, int middle2, int max) { int temp[20]; int l = 0; int i = min; int j = middle2; while (i <= middle && j <= max) { if (n[i] < n[j]) { temp[l++] = n[i++]; } else { temp[l++] = n[j++]; } } while (i <= middle) { temp[l++] = n[i++]; } while (j <= max) { temp[l++] = n[j++]; } for (l = min, j = 0; l <= max; l++, j++) { n[l] = temp[j]; } } void print_elemts(int *n, int size, int *n2) { int i = 0; printf("Given array is "); printf("\n\n"); for (i = 0; i < size; i++) { printf("%d ", n2[i]); } printf("\nSorted array is"); printf("\n\n"); for (i = 0; i < size; i++) { printf("%d ", n[i]); } }
C
#pragma once struct Point { Point() = delete; explicit Point(double x_, double y_):x(x_), y(y_){}; double x, y; };
C
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <time.h> #include <malloc.h> /* Data Type Define */ #define OK 1 #define ERROR 0 #define UNSIGN -1 #define MAXNUM 230000 //MAX_NUMָӾ伯Ӿ #define PL 11 //PLָĿٵά #define SET_TIME 5 //SET_TIMEǹ涨ʱ typedef int Status; typedef struct NewTable { int elem; int state; }NewTable;// /* End of Data Type Define */ /****************************************************************************************/ /* Data Struct Define */ typedef struct Table { int Variate;//ñֱţ bool judge;//ñǷΪ߱ bool diverse;//ñǷѾת }Table;//жϱ״̬Ԫ typedef struct Node { int VariateValue;//ӾбȡֵʼֵֵΪ-1 int Variate;//Ӿڵеı struct Node* next;//ָһӾڵ } Node;//Ӿṹ typedef struct Hnode { int VariateNum;//ӾбĿ int Sat;//ӾȡֵΪ1ıĿ int Unsat;//ӾȡֵΪ0ıĿ /*int UnsignedNum;//ӾûиֵıĿ*/ bool s;//ʾӾǷ1ʾڣ0ʾ Node* first;//ָӾһָ } Hnode;//Ӿͷڵṹ typedef struct Word { int ClauseNum;//Ӿţ1ʼ struct Word* next;//ָһ } Word;//ṹ typedef struct HWord { int col30;//Ӿ伯֮ϵԭʼֵ,޸ģжϸôǷӦı int VariateValue;// Word* first, * last;//ֱָһһ int n=0; } HWord; //ͷṹ typedef struct SAT { int ClauseNum;//ʾӾĿ int VariateNum;//ʾĿ Hnode list[230000];//Ӿͷ HWord relist[230000];//ͷ Table stack[230000];//жϱ״̬Ԫջ int top;//ջλñ int num;//ջջ׵ľ߱ }SAT;//SATڽӱ洢ռ typedef struct SAT2 { int ClauseNum;//ʾӾĿ int VariateNum;//ʾĿ Hnode list[230000];//Ӿͷ HWord relist[230000];//ͷ Table stack[230000];//жϱ״̬Ԫջ int top;//ջλñ int num;//ջջ׵ľ߱ int n;//Ľ int puzzle[PL][PL];//ʹõ }SAT2;//SAT洢ռ /* End of Data Struct Define */ void paixu(SAT *S); int SelectVariate4(SAT* S); /****************************************************************************************/ /*In The File "MATH.cpp" */ int cmn(int m, int n);//nѡm int Number5(int a, int b, int c, int d, int e);//Ӧ5λʮ int Number4(int a, int b, int c, int d);//Ӧ4λʮ int Number3(int a, int b, int c);//Ӧ3λʮ int PW(int i, int j, int n);//ӶӦֵĺ int NW(int i, int j, int n);//ӶӦֵĺ bool has(NewTable b[], int n);//ѡϵĺ int Verse(int x);//ֶӦֺ void Cell(SAT2* S, int x, int* i, int* j);//ֶӦĸ int Trab(int x);//ֵԭĺ /* End of File "MATH.cpp" */ /****************************************************************************************/ /* SAT of CNF */ Status Iniate(SAT** S);//ݽṹĴʼ Status Input(FILE* in, SAT *S);//ļڽӱ Status deletel(SAT* S, int x);//ȥҪӾ Status deletew(SAT* S, int x);//ɾ int danzijuselect(SAT* S);//ѰҵӾ Status deletec(SAT* S);//õӾ򻯼Ӿ伯 int bianliangselect(SAT* S);//һֵ֧2////////////!!!!!Ż int JudgeClause(SAT* S,int i);//жijӾǷ bool JudgeSATEmpty(SAT* S);//жӾ伯ǷΪ bool JudgeListEmpty(SAT* S);//жӾ伯ǷڿӾ Status Solve1(SAT* S, FILE* in, int* t);//DPLLSAT֧Ż Status CopyValue(SAT* S, int x);//ֵ Status ReCopyValue(SAT* S, int x);//תֵ Status InStack(SAT* S, int x, bool s);//ջ Status OutStack(SAT* S);//ջֵָ bool EmptyStack(SAT* S);//жջǷΪ Status Solve3(SAT* S, FILE* in, int* t);//DPLLSAT֧Żǰ int SelectVariate3(SAT* S);//һֵ֧1 /* End of CNF */ /****************************************************************************************/ /* SAT of BinaryPuzzle */ Status Iniate2(SAT2** S);//ݽṹĴʼ Status PuzzleInnital(SAT2* S);//ʼ߼Ӿϵ Status R1(SAT2* S, int a, int b);//һӾ伯 Status R2(SAT2* S, int a, int b);//Ӿ伯 Status R3(SAT2* S, int a);//Ӿ伯 Status DeleteList2(SAT2* S, int x);//ȥҪӾ Status DeleteWord2(SAT2* S, int x);//ɾ int SelectClause2(SAT2* S);//ѰҵӾ Status DeleteClause2(SAT2* S);//õӾ򻯼Ӿ伯 int SelectVariate2(SAT2* S);//һֵ֧ bool JudgeSATEmpty2(SAT2* S);//жӾ伯ǷΪ bool JudgeListEmpty2(SAT2* S);//жӾ伯ǷڿӾ bool Solve2(SAT2* S);//DPLLSAT֧ Status CopyValue2(SAT2* S, int x);//ֵ Status ReCopyValue2(SAT2* S, int x);//תֵ Status InStack2(SAT2* S, int x, bool s);//ջ Status OutStack2(SAT2* S);//ջֵָ bool EmptyStack2(SAT2* S);//жջǷΪ bool LasVegas(SAT2* S, int t);//˹ά˹㷨 bool GenerateByDigMethod(int f[][PL], int n, int level);//ϵ¡˳ڶ bool CheckUnique(int f[][PL], int n, int r, int c);//жǷΨһ bool CheckSudokuSolution(int f[][PL], int n);//жϽǷȷȫ bool CheckSudokuSolution2(int f[][PL], int n, int i, int j, bool v);//жϽǷȷֲ Status PlayPuzzle(int f[][PL],int puzzle2[][PL], int n);//õˣ /* End of BinaryPuzzle */ /****************************************************************************************/ /* In The File "DFS.cpp" to use in BinaryPuzzle */ bool solve(int (*f)[PL], int n);//DFS⺯ڶרã bool r1(int (*f)[PL], int n, int i, int j, bool v);//֤1Ƿ bool r2(int (*f)[PL], int n, int i, int j, bool v);//֤2Ƿ bool r3(int (*f)[PL], int n, int i, int j, bool v);//֤3Ƿ /* End of The File "DFS.cpp" to use in BinaryPuzzle */ /****************************************************************************************/ /* In The File "Print.cpp" */ Status PrintClause(SAT* S);//ӡӾ伯 Status PrintWord(SAT* S, FILE* out, int s, int time);//ӡ Status PrintPuzzle(int f[][PL], int n);//ӡ Status PrintPuzToCNF(SAT2* S);//ӡԼɵCNFӾ伯ļڲɣ Status CopyPuzzle(int f[][PL], int b[][PL], int n);// /* End of The File "Print.cpp" */ /****************************************************************************************/ /* In The File "New.cpp" */ Status ReCoverValue(SAT* S, int x);//ֵлֵָCNFд Status ReCoverValue2(SAT2* S, int x);//ֵлֵָд Status NewCopyValue(SAT2* S, int i, int j, bool v);//Ըôиֵ Status NewReCoverValue(SAT2* S, int i, int j);//Ըôлֵָ /* End of The File "New.cpp" */ /****************************************************************************************/
C
#include <stdio.h> //Temperature Conversion execise main(){ int f, c; int start, limit, incr; start=0; limit=300; incr=20; while(f<=limit){ c = 5*(f-32)/9; printf("%d\t %d\n", c, f); f=f+20; } } // This changing int to float did not work, so two ways to fix this, line 27 for info /* #include <stdio.h> main(){ float f, c; int start, limit, incr; start=0; limit=300; incr=20; while(f<=limit){ c = (5/9)*f; //above you can do 5.0/9 or ((float)5/9) but I still don't get my -17 so will go with original printf("%f\t %f\n", c, f); f=f+incr; } } */ //exercise 1.5 I DID IT! changed three things, f's initial value, less than to greater than with start //then minus 20 instead of plus /* #include <stdio.h> main(){ int f, c; f=300; int start, limit, incr; start=0; limit=300; incr=20; while(f>=start){ c = 5*(f-32)/9; printf("%d\t %d\n", c, f); f=f-20; } } */ main(){ int c; c=getchar(); while (c!=EOF){ putchar(c); c = getchar(); } }
C
// // main.c // 单项链表 // // Created by 张耘博 on 2018/10/16. // Copyright © 2018 张耘博. All rights reserved. // #include <stdio.h> #include "LinkList.h" //用尖括号报错:'LinkList.h' file not found with <angled> include; use "quotes" instead提示引号代替:原因:这个头问价为用户自己定义的 typedef struct PERSON{ char name[64]; int age ; int score; }Person; void Myprint(void* data){ Person* p= (Person*)data; printf("name:%s Age:%d Scord%d\n",p->name,p->age,p->score); } int main(int argc, const char * argv[]) { //创建链表 LinkList* list = Init_LinkList(); //创建数据类型 Person p1={"aaa",18,100}; Person p2={"bbb",19,99}; Person p3={"ccc",20,50}; Person p4={"ddd",17,77}; Person p5={"eee",16,88}; //数据插入链表 Insert_LinkList(list, 0, &p1); Insert_LinkList(list, 0, &p2); Insert_LinkList(list, 0, &p3); Insert_LinkList(list, 0, &p4); Insert_LinkList(list, 0, &p5); //1、打印 print_LinkList(list, Myprint); //删除3 RemoveByPos_LinkList(list, 3); //2、打印 printf("-----------删除节点后-------------\n"); print_LinkList(list, Myprint); //返回第一个节点 printf("------------查找第一个结果------------------\n"); Person* ret = (Person*)Front_LinkList(list); printf("name:%s Age:%d Scord%d\n",ret->name,ret->age,ret->score); //销毁链表 FreeSpace_LinkList(list); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* event.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: paperrin <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/10/29 21:15:40 by paperrin #+# #+# */ /* Updated: 2017/10/30 07:27:18 by paperrin ### ########.fr */ /* */ /* ************************************************************************** */ #include "wolf3d.h" static void event_key_toggle(int key, int state, void *param) { t_app *app; app = (t_app*)param; if (key == KC_A) app->player.left_pressed = state; if (key == KC_D) app->player.right_pressed = state; if (key == KC_W) app->player.up_pressed = state; if (key == KC_S) app->player.down_pressed = state; } int event_key_press(int key, void *param) { event_key_toggle(key, 1, param); return (0); } int event_key_release(int key, void *param) { t_app *app; event_key_toggle(key, 0, param); app = (t_app*)param; if (key == KC_ESCAPE) destroy_app(app, EXIT_SUCCESS); return (0); } int event_cross(void *param) { t_app *app; app = (t_app*)param; destroy_app(app, EXIT_SUCCESS); return (0); }
C
#include "List.h" #include <stddef.h> /** * Compares the one specified list with another for equality. * * @param ptr The one list to be compared for equality * @param sizePtr The list size function * @param getPtr The list get function * @param o The other list to be compared for equality * @param sizeO The other list size function * @param getO The other list get function * @param equals The list element equals function * @return true if the one specified list is equal to the other */ bool equalsList(void *ptr, int32_t (*sizePtr)(void *), void *(*getPtr)(void *, int32_t), void *o, int32_t (*sizeO)(void *), void *(*getO)(void *, int32_t), bool (*equals)(const void *, const void *)) { // comparing pointers if (ptr == o) { return true; } // testing the pointer for a NULL value if (o == NULL) { return false; } int length = sizePtr(ptr); // comparing the list sizes if (sizeO(o) != length) { return false; } // comparing the corresponding elements of the lists int32_t i; for (i = 0; i < length; i++) { void *o1 = getPtr(ptr, i); void *o2 = getO(o, i); bool e = o1 == NULL ? o2 == NULL : equals(o1, o2); if (!e) { return false; } } return true; }
C
#include <stdio.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <string.h> #define SOCK_NAME "mysocket" int main (int argc, char ** argv) { int sock; struct sockaddr_un addr; if (argc < 2) { fprintf (stderr, "Too few arguments\n"); return 1; } sock = socket (PF_UNIX, SOCK_STREAM, 0); if (sock == -1) { fprintf (stderr, "socket() error\n"); return 1; } addr.sun_family = AF_UNIX; strcpy (addr.sun_path, SOCK_NAME); if (connect (sock, (struct sockaddr *) &addr, SUN_LEN (&addr)) == -1) { fprintf (stderr, "connect() error\n"); return 1; } if (write (sock, argv[1], strlen (argv[1])) == -1) { fprintf (stderr, "write() error\n"); return 1; } close (sock); return 0; } // $ gcc -o socket2-server socket2-server.c // $ ./socket2-server // Откроем теперь другое терминальное окно и начнем передавать серверу запросы: // $ gcc -o socket2-client socket2-client.c // $ ./socket2-client Hello // $ ./socket2-client World // $ ./socket2-client Linux
C
#include <stdio.h> #include <stdlib.h> void merge(int a[], int l, int m, int u) { //merges arrays in sorted order int i, j, k; int n1, n2; //number of elements in each temp array n1 = m - l + 1; n2 = u - m; int b[n1]; int c[n2]; for (int x = 0; x < n1; x++) //copying data to temp arrays b[x] = a[l+x]; for (int y = 0; y < n2; y++) c[y] = a[m+y+1]; i = 0; //array counters j = 0; k = l; /*k=l so that arr starts filling from the position of the lowermost element currently supplied to the function. That is, if l = 2, u = 5, arr starts filling from arr[2] to arr[5]. */ while (i < n1 && j < n2) { //sort arr in ascending order till either i=n1 or j=n2 if(b[i] <= c[j]) { a[k] = b[i]; i++; } else { a[k] = c[j]; j++; } k++; } while (i < n1) //fill up leftover elements from either left or right array. { a[k] = b[i]; i++; k++; } while (j < n2) { a[k] = c[j]; j++; k++; } } int mergesort(int *a, int low, int up) { //divides into multiple arrays int mid = (low + up - 1)/2; if (low < up) { mergesort(a, low, mid); //first half mergesort(a, mid+1, up); //second half merge(a, low, mid, up); } } //test case int main() { int arr[] = {42, 46, 12, 42, 56, 23, 76}; int n = sizeof(arr)/sizeof(int); mergesort(arr, 0, n-1); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); }
C
/* 可变参数 */ #include <stdio.h> #include <stdarg.h> double average(int num, ...) { va_list valist; double sum = 0.0; int i; // 为 num 个参数初始化 valist va_start(valist, num); int tmp = 0; // 访问所有赋给valist 的参数 for (i = 0; i < num; i++) { tmp = va_arg(valist, int); printf("print valist : %d, ptr = %p\n", tmp, &tmp); sum += tmp; } // 清理为valist保留的内存 va_end(valist); return sum / num; } int main() { // average(4,2,3,4,5) 第一个4是参数个数 printf("Average of 2,3,4,5 = %f\n", average(4, 2, 3, 4, 5)); printf("Average of 5, 10, 15 =%f\n", average(3, 5, 10, 15)); return 0; }
C
/* Write a program to display a right angle triangle with N number of rows, like below. Input: 5 Output: 1 12 123 1234 12345 */ #include <stdio.h> int main() { int number, i, j; scanf("%d", &number); for(i = 1; i <= number; i++){ for(j = 1; j <= i; j++){ printf("%d", j); } printf("\n"); } return 0; }
C
/* * gpio.h * * Created on: 13 Jun 2015 * Author: am5514 */ #ifndef GPIO_H_ #define GPIO_H_ /* Physical addresses of the pin accesses in memory */ #define GPIO_PINS_20_29 0x20200008 #define GPIO_PINS_10_19 0x20200004 #define GPIO_PINS_0_9 0x20200000 /* Addreses of the control and setting pins */ #define GPIO_CONTROL_CLEAR 0x20200028 /* Clears a pin */ #define GPIO_CONTROL_SET 0x2020001C /* Sets a pin (turns it on) */ #include <stdint.h> #include <stdio.h> #include <stdbool.h> /* Checks for GPIO memory accesses, returns true on access */ bool checkGPIOAccess(uint32_t memoryAddress); /* Prints which GPIO pin was triggered */ void checkGPIOPin(uint32_t memoryAddress); #endif /* GPIO_H_ */
C
#include "string.h" char * strcpy(char * destination, const char * source) { char * result = destination; while (*(destination++) = *(source++)); return result; } size_t strlen(const char * string) { size_t result = 0; while (string[result]) result++; return result; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* move_3.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: elchouai <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/12/21 22:58:42 by elchouai #+# #+# */ /* Updated: 2018/12/22 00:36:01 by ysalihi ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" void rot_rl_y(t_mlx *param, double theta) { int i; int j; double x; double z; i = 0; while (i < param->dim[0]) { j = 0; while (j < param->dim[1]) { x = param->map[i][j].x; z = param->map[i][j].h; param->map[i][j].h = z * cos(theta) - x * sin(theta); param->map[i][j].x = z * sin(theta) + x * cos(theta); j++; } i++; } } void rot_rl_x(t_mlx *param, double theta) { int i; int j; double y; double z; i = 0; while (i < param->dim[0]) { j = 0; while (j < param->dim[1]) { y = param->map[i][j].y; z = param->map[i][j].h; param->map[i][j].h = y * sin(theta) + z * cos(theta); param->map[i][j].y = y * cos(theta) - z * sin(theta); j++; } i++; } } void rot_rl_z(t_mlx *param, double theta) { int i; int j; double x; double y; i = 0; while (i < param->dim[0]) { j = 0; while (j < param->dim[1]) { x = param->map[i][j].x; y = param->map[i][j].y; param->map[i][j].x = x * cos(theta) - y * sin(theta); param->map[i][j].y = y * cos(theta) + x * sin(theta); j++; } i++; } } int deal_key(int key, t_mlx *param) { deal_key_1(key, param); deal_key_2(key, param); deal_key_3(key, param); deal_key_4(key, param); deal_key_5(key, param); return (0); } int mlx_dealer(t_mlx *param) { mlx_clear_window(param->mlx_p, param->mlx_win); center_map(param, (WIN_WIDTH) / 2, (WIN_HEIGHT) / 2); draw_map(param); return (0); }
C
/* ============================================================================ Name : testC.c Author : Tomasz Strzałka Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <time.h> #include <stdlib.h> #include <stddef.h> #include <math.h> const int TESTSNO = 12; const char* TESTPATHS[12] = { "TMH_Tests/gr/USA-road-d/USA-road-d.NY.gr", "TMH_Tests/gr/USA-road-d/USA-road-d.BAY.gr", "TMH_Tests/gr/USA-road-d/USA-road-d.COL.gr", "TMH_Tests/gr/USA-road-d/USA-road-d.FLA.gr", "TMH_Tests/gr/USA-road-d/USA-road-d.NW.gr", "TMH_Tests/gr/USA-road-d/USA-road-d.NE.gr", "TMH_Tests/gr/USA-road-d/USA-road-d.CAL.gr", "TMH_Tests/gr/USA-road-d/USA-road-d.LKS.gr", "TMH_Tests/gr/USA-road-d/USA-road-d.E.gr", "TMH_Tests/gr/USA-road-d/USA-road-d.W.gr", "TMH_Tests/gr/USA-road-d/USA-road-d.CTR.gr", "TMH_Tests/gr/USA-road-d/USA-road-d.USA.gr" }; const char* SAVE[12] = { "50xUSA-road-d.NY.gr", "50xUSA-road-d.BAY.gr", "50xUSA-road-d.COL.gr", "50xUSA-road-d.FLA.gr", "50xUSA-road-d.NW.gr", "50xUSA-road-d.NE.gr", "50xUSA-road-d.CAL.gr", "50xUSA-road-d.LKS.gr", "50xUSA-road-d.E.gr", "50xUSA-road-d.W.gr", "50xUSA-road-d.CTR.gr", "50xUSA-road-d.USA.gr", "50xUSA-road-d.CTR.gr", "50xUSA-road-d.USA.gr" }; static void modGraphData( FILE* const dataFile, const char* savePath, int PARAM ); static double standard_deviation(unsigned int data[], unsigned long int n); int main(void) { FILE* dataFile = NULL; int i; for (i=0; i <TESTSNO; i ++ ) { printf("%s\n",TESTPATHS[i]); dataFile = fopen(TESTPATHS[i],"r"); modGraphData(dataFile,SAVE[i],50); } return EXIT_SUCCESS; } static void modGraphData( FILE* const dataFile, const char* savePath, int PARAM ) { unsigned int numberOfNodes; unsigned int numberOfArcs; unsigned int fromNodeID,toNodeID; unsigned int distanceLabel; unsigned int maxArcCost = 0; unsigned int* costTab = NULL; FILE* saveFile = NULL; saveFile = fopen(savePath,"w"); double stdD = 0.0, avg = 0.0; unsigned long int i = 0; while ( !feof(dataFile) ) { switch (fgetc(dataFile)) { case 'c': fscanf(dataFile, "%*[^\n]\n"); break; case 'p': fscanf(dataFile," %*[^ ] %u %u\n",&numberOfNodes,&numberOfArcs); printf("%u %u\n",numberOfNodes,numberOfArcs); costTab = malloc(numberOfArcs*sizeof(unsigned int)); fprintf(saveFile,"p sp %u %u\n",numberOfNodes,numberOfArcs); break; case 'a': fscanf(dataFile," %u %u %u\n",&fromNodeID,&toNodeID,&distanceLabel); fprintf(saveFile,"a %u %u %u\n",fromNodeID,toNodeID,distanceLabel*PARAM); maxArcCost = ( (maxArcCost < distanceLabel) ? distanceLabel : maxArcCost); avg += distanceLabel; costTab[i++] = distanceLabel; } } stdD = standard_deviation(costTab,numberOfArcs); avg = avg/numberOfArcs; printf("%d,\n",maxArcCost/5); printf("& $%d$ & $%.2f$ & $%.2f$ & \\\\\n",maxArcCost,avg,stdD); free(costTab); fclose(dataFile); fclose(saveFile); return; } static double standard_deviation(unsigned int data[], unsigned long int n) { float mean=0.0, sum_deviation=0.0; int i; for(i=0; i<n;++i) { mean+=data[i]; } mean=mean/n; for(i=0; i<n;++i) { sum_deviation+=(data[i]-mean)*(data[i]-mean); } return sqrt(sum_deviation/n); }
C
#include <stdio.h> int main(int argc, char const *argv[]) { char buf[1000]; scanf("%s", buf); if (buf[0] >= 97 && buf[0] <= 122) { buf[0] -= 32; } printf("%s\n", buf); return 0; }
C
#ifndef SD_ICONV_H_20081229 #define SD_ICONV_H_20081229 #ifdef __cplusplus extern "C" { #endif #ifndef _int32 #define _int32 int #endif #ifndef _u32 #define _u32 unsigned int #endif #ifndef _u8 #define _u8 unsigned char #endif #ifndef _u16 #define _u16 unsigned short #endif #ifndef BOOL #define BOOL char #endif #ifndef TRUE #define TRUE (1) #endif #ifndef FALSE #define FALSE (0) #endif #ifndef NULL #define NULL (0) #endif #ifndef SUCCESS #define SUCCESS (0) #endif enum CODE_PAGE { _CP_ACP = 0, _CP_GBK , _CP_UTF8 ,_CP_BIG5 }; /* ²ַıʽ:CP_ACP=0, CP_GBK , CP_UTF8 Notice: úڲ²ַıʽֻܲ²ֱַ ASCII뷵CP_ACPļGBK뷵CP_GBKUTF8뷵CP_UTF8ķBIG5CP_BIG5 ڸúһ100%ܲȷԣݲͬķֵҪע⣺ 1.ֵΪCP_ACPַһǴASCII룬ʽı룻 2.ֵΪUTF8ַһUTF8룬ʽı룻 3.ֵΪCP_BIG5ַҲпUTF8룬CP_ACPCP_GBKʽı룻Ҫע⡣ 4.ֵΪCP_GBKַҲпCP_BIG5UTF8룬ǴASCII룻ҲҪע⡣ */ enum CODE_PAGE sd_conjecture_code_page( const char* src_str ); _int32 sd_utf8_2_gbk(const char *p_input, _u32 input_len, char *p_output, _u32 *output_len); _int32 sd_gbk_2_utf8(const char *p_input, _u32 input_len, char *p_output, _u32 *output_len); _int32 sd_utf8_2_big5(const char *p_input, _u32 input_len, char *p_output, _u32 *output_len); _int32 sd_big5_2_utf8(const char *p_input, _u32 input_len, char *p_output, _u32 *output_len); _int32 sd_big5_2_gbk(const char *p_input, _u32 input_len, char *p_output, _u32 *output_len); _int32 sd_unicode_2_gbk(const _u16 *p_input, _u32 input_len, char *p_output, _u32 *output_len); _int32 sd_gbk_2_unicode(const char *p_input, _u32 input_len, _u16 *p_output, _u32 *output_len); _int32 sd_utf8_2_unicode(_u8* utf8, _u32 input_len, _u16* unicode,_u32 *output_len); _int32 sd_unicode_2_utf8(_u16* unicode,_u32 input_len, _u8* utf8,_u32 *output_len); /* ɹ, *output_lenռڴ泤(byte)*/ _int32 sd_any_format_to_gbk( const char *input,_u32 input_len, _u8* gbk,_u32 *output_len); /* ɹ, *output_lenռڴ泤(byte)*/ _int32 sd_any_format_to_utf8( const char *input,_u32 input_len, char * p_utf8,_u32 *output_len); /* ɹ, *output_lenunicodeַ(ֽ)*/ _int32 sd_any_format_to_unicode( const char *input,_u32 input_len, _u16* p_unicode,_u32 *output_len); #ifdef __cplusplus } #endif #endif /* SD_ICONV_H_20081229 */
C
#include "Hostel.h" int checkIfRoomExists(Hostel* ht, int roomNumber); // Name: Almog Afuta // Id:319114245 // Name: Gil Didi // Id:318353422 /****************************************************************************** Name: Hostle AddRoom Inputs: ht(HOstle*), room(Room*) Output: Hostle* Description: Add a new room to an existing Hostel ********************************************************************************/ Hostel* AddRoom(Hostel* ht, const Room* room) { //check of pointer ht exists, if no create "unknown hostel" //if exists check if room number exists, if exists update values and done //if room does not exist, create new room, add it to room* array, number of rooms++. //in order to add new room to list of rooms //I create new rooms ** which has size+1 //copy relevant rooms into new array //add new room into new aray //delete old pointer array //move new pointer into field rooms //I need to check if room exists inside the hostel //I need to write a function that does it! if (ht == NULL) // if the hostel is NULL, create a new { ht = (Hostel*)malloc(sizeof(Hostel));//memory allocation if (ht == NULL)//memory allocation failed { return NULL; } ht->hostel_name = "Unknown Hostel";//set the values ht->rate = 0; ht->num_of_rooms = 1; ht->rooms = (Room**)malloc(sizeof(Room*));//memory allocation if (ht->rooms == NULL) { free(ht); return NULL; } ht->rooms[0] = DuplicateRoom(room);// add's room to hostel return ht; } //now ht not NULL int check = checkIfRoomExists(ht, room->number);//-1 if room not in list, returns index otherwise if (check == -1)//fail to find, now I need to Add new room to rooms { Room** temp = (Room**)malloc(sizeof(Room*) * (ht->num_of_rooms + 1));//creates new space for extra room if (temp == NULL) { free(ht); return NULL; } for (int j = 0; j < ht->num_of_rooms; j++) { temp[j] = DuplicateRoom(ht->rooms[j]); FreeRoom(ht->rooms[j]); } ht->rooms = temp; ht->rooms[ht->num_of_rooms] = DuplicateRoom(room); ht->num_of_rooms++;//update num of rooms return ht; } else//manage to find,check holds index of room inside rooms //now I need to update values { FreeRoom(ht->rooms[check]); ht->rooms[check] = DuplicateRoom(room);//result is the same as directly updating values } return ht; } /****************************************************************************** Name: checkIfRoomExists Inputs: ht(HOstle*), roomNumber(int) Output: int Description: checks if room exists inside hostel, if exists return index inside rooms if not returns -1 This is a local function only, should not be used outside of Hostel.c scope ********************************************************************************/ int checkIfRoomExists(Hostel* ht, int roomNumber) { if (ht == NULL) { return -1;//no hostel no room } int count = ht->num_of_rooms;//number of rooms for for loop int i; for (i = 0; i < count; i++) { if (roomNumber == ht->rooms[i]->number)//if number is the same, done { return i; } } return -1;//if not room number matches, we return value for failure } /********************************************************************** Name: printHostel Inputs: ht(Holstel*) Output: - Description: prints the values of all fields of the hostel, primarily used for debugging the code ***********************************************************************/ void printHostel(Hostel* ht) { printf("Name of Hostel:%s\n", ht->hostel_name); printf("Rate:%f\n", ht->rate); printf("Number of rooms:%d\n", ht->num_of_rooms); int i; for (i = 0; i < ht->num_of_rooms; i++) { printRoom(ht->rooms[i]); } } /********************************************************************************* Name: Hostel DuplicateHostel Inputs: source(const Hostel*) Outputs: Hostel* Description: Duplicate Hostel, duplicates all the fields of the struct **********************************************************************************/ Hostel* DuplicateHostel(const Hostel* source) { if (source == NULL)//nothing to copy { return NULL; } Hostel* copy = (Hostel*)malloc(sizeof(Hostel));// memory allocation for new hostel if (copy == NULL) { return NULL; } copy->rooms = (Room**)malloc(sizeof(Room*) * (source->num_of_rooms));// memory allocation for rooms if (copy->rooms == NULL) { free(copy); return NULL; } copy->rate = source->rate; copy->num_of_rooms = 0; copy->hostel_name = (char*)(malloc((strlen(source->hostel_name) + 1) * sizeof(char)));//memory allocation for hostel name if (copy->hostel_name == NULL) { FreeHostel(copy); return NULL; } strcpy(copy->hostel_name, source->hostel_name);//copy of string int i; for (i = 0; i < source->num_of_rooms; i++)//duplicate room in loop { copy->rooms[i] = DuplicateRoom(source->rooms[i]); if (copy->rooms[i] == NULL)//if fail, trouble { FreeHostel(copy); return NULL; } copy->num_of_rooms++;// update the num of rooms } return copy; } /********************************************************************************* Name: FreeHostel Inputs: ht(const Hostel*) Outputs: - Description:Frees all relevant memory **********************************************************************************/ void FreeHostel(Hostel* ht) { if (ht == NULL) { return; } int i; for (i = 0; i < ht->num_of_rooms; i++)// free all the rooms in loop { FreeRoom(ht->rooms[i]); } free(ht->rooms); if (strcmp(ht->hostel_name, "Unknown Hostel") != 0) { free(ht->hostel_name); } free(ht); } /********************************************************************************* Name: GetAvailableRooms Inputs: ht(const Hostel*), type( const char*) Outputs: int Description:Cheak if the room is available **********************************************************************************/ int GetAvailableRooms(const Hostel* ht, const char* type) { if (ht == NULL) { return 0;//if no hostel there are no rooms } int counter = 0; int i; for (i = 0; i < ht->num_of_rooms; i++) { if (strcmp(ht->rooms[i]->type, type) == 0 && ((ht->rooms[i]->available) == 1))//compration between 2 types { counter++;//update } } return counter; }
C
/* ** game.c for in /home/thomas/Documents/epitech/CPE_2015_Allum1 ** ** Made by Thomas HENON ** Login <[email protected]> ** ** Started on Mon Feb 15 16:12:37 2016 Thomas HENON ** Last update Sun Feb 21 12:08:18 2016 thomas */ #include "allum.h" char win(int nbr_lines, int *allums) { int i; i = 0; while (i < nbr_lines) { if (allums[i] != 0) return (0); i++; } return (1); } void init_allums(int nbr_lines, int *allums) { int i; i = 0; while (i < nbr_lines) { allums[i] = i * 2 + 1; i++; } } char my_turn(int nbr_lines, int *allums, int *turn) { int line; int matches; matches = 0; my_putstr("Your turn:\n"); while (!matches) { if (-1 == (line = line_user_input(nbr_lines, allums))) return (0); if (-1 == (matches = matches_user_input(nbr_lines, allums, line))) return (0); } allums[line-1] -= matches; my_putstr("Player removed "); my_put_nbr(matches); my_putstr(" match(es) from line "); my_put_nbr(line); my_putchar('\n'); *turn = AI_TURN; return (1); } char ai_turn(int nbr_lines, int *allums, int *turn) { int matches; int line; matches = 0; line = 0; if (!ai(allums, nbr_lines, &line, &matches)) return (0); my_putstr("AI's turn...\n"); my_putstr("AI removed "); my_put_nbr(matches); my_putstr(" match(es) from line "); my_put_nbr(line); my_putstr("\n"); *turn = MY_TURN; return (1); }
C
// C Program to check whether a number is Armstrong or not #include<stdio.h> #include<math.h> void ArmstrongNumber(int n){ int num=n, rem, sum=0; // Counting number of digits int digits = (int) log10(num) + 1; while(num > 0) { rem = num % 10; sum = sum + pow(rem,digits); num = num / 10; } if(n==sum) printf("%d is an Armstrong number.",n); else printf("%d is not an Armstrong number.",n); } int main(){ int num; printf("Enter the number: "); scanf("%d",&num); ArmstrongNumber(num); return 0; } /* Sample input/output: Example 1: Enter the number: 153 153 is an Armstrong number. Example 2: Enter the number: 1094 1094 is not an Armstrong number. Time Complexity= O(log(n)) Space Complexity= O(1) */
C
#include<sys/epoll.h> #include <errno.h> #include "../include/epollmp.h" #include "../include/iomp.h" #include "../include/zmemory.h" #define mpSetError setError typedef struct mpState { int epfd; struct epoll_event* events; fireEvent* fevents; int maxEv; } mpState; static mpState* state = 0; int mpCreate(char*err,int maxEv) { state = zmalloc(sizeof(mpState)); //Since Linux 2.6.8, the size argument is ignored, but must be greater than zero; see NOTES below. state->epfd = epoll_create(maxEv); if(state->epfd == -1){ mpSetError(err, "epoll_create: %s\n", strerror(errno)); return NET_RET_ERROR; } state->events = zmalloc(sizeof(struct epoll_event) * maxEv); state->fevents = zmalloc(sizeof(fireEvent) * maxEv); state->maxEv = maxEv; return NET_RET_OK; } void mpRelease() { CHECK_PTR_ERR(state) zfree(state->events); zfree(state->fevents); close(state->epfd); zfree(state); state = 0; } // 客户端异常关闭,并不会通知服务器。正常关闭时read到0后,异常断开时检测不到的。服务器再给一个已经关闭 // 的socket写数据时,会出错,这时候,服务器才明白对方可能已经异常断开了(读也 // 可以)。 // Epoll中就是向已经断开的socket写或者读,会发生EPollErr,即表明已经断开。 int mpAdd( char* err,int fd, int oldmask,int addmask) { CHECK_PTR_ERR(state) int mask = oldmask | addmask; if(mask == oldmask){ return NET_RET_OK; } struct epoll_event ee; ee.data.fd = fd; ee.events = 0; if (mask & EV_MASK_READ) ee.events |= EPOLLIN; //对端正常关闭 触发 read == 0 if (mask & EV_MASK_WRITE) ee.events |= EPOLLOUT; if (mask & EV_MASK_ERROR) ee.events |= EPOLLERR; //对端异常关闭 本端进行读写时触发 if(oldmask == EV_MASK_NONE){ if( epoll_ctl(state->epfd, EPOLL_CTL_ADD, fd, &ee) < 0 ){ mpSetError(err, "mpAdd(epoll_ctl-EPOLL_CTL_ADD): %s\n", strerror(errno)); return NET_RET_ERROR; } } else{ if( epoll_ctl(state->epfd, EPOLL_CTL_MOD, fd, &ee) < 0 ){ mpSetError(err, "mpAdd(epoll_ctl-EPOLL_CTL_MOD): %s\n", strerror(errno)); return NET_RET_ERROR; } } return NET_RET_OK; } int mpDel(char* err,int fd,int oldmask,int delmask) { CHECK_PTR_ERR(state) struct epoll_event ee; ee.data.fd = fd; ee.events = 0; int mask = oldmask & (~delmask); if(mask == oldmask){ return 0; } if(mask == EV_MASK_NONE){ if( epoll_ctl(state->epfd, EPOLL_CTL_DEL, fd, 0) < 0){ mpSetError(err, "mpDel(epoll_ctl-EPOLL_CTL_DEL): %s\n", strerror(errno)); return NET_RET_ERROR; } } else{ if (mask & EV_MASK_READ) ee.events |= EPOLLIN; if (mask & EV_MASK_WRITE) ee.events |= EPOLLOUT; if (mask & EV_MASK_ERROR) ee.events |= EPOLLERR; if( epoll_ctl(state->epfd, EPOLL_CTL_MOD, fd, &ee) < 0) { mpSetError(err, "mpDel(epoll_ctl-EPOLL_CTL_MOD): %s\n", strerror(errno)); return NET_RET_ERROR; } } return NET_RET_OK; } int mpWait(char* err,int w) { CHECK_PTR_ERR(state) int cnt = epoll_wait(state->epfd, state->events, state->maxEv, w); if(cnt < 0){ mpSetError(err, "mpWait(epoll_wait): %s\n", strerror(errno)); return NET_RET_ERROR; } for (size_t i = 0; i < cnt; i++) { struct epoll_event* e= &(state->events[i]); state->fevents[i].read = e->events & EPOLLIN ? 1 : 0; state->fevents[i].write = e->events & EPOLLOUT ? 1 : 0; state->fevents[i].error = e->events & EPOLLERR? 1 : 0; state->fevents[i].fd = e->data.fd; int mask = 0; if(e->events & EPOLLIN ) mask |= EV_MASK_READ; if(e->events & EPOLLOUT ) mask |= EV_MASK_WRITE; if(e->events & EPOLLERR ) mask |= EV_MASK_ERROR; } return cnt; } fireEvent* mpGetFireEvents(){ CHECK_PTR_ERR(state) return state->fevents; }
C
#ifndef _CYCLELKLIST_H_ #define _CYCLELKLIST_H_ #include "type.h" #include "common.h" /** * ѭ * *headָͷָ * *currentָǰָ * lengthΪij */ typedef struct CycleLkList { LkNode *head;//ָѭͷ LkNode *current;//ָǰ LkNode *trail;//ָѭβ int length;//ij }CycleLkList; //ѭʼ WORD cycleLkListInit(CycleLkList**); //ѭ WORD cycleLkListClear(CycleLkList*); //жѭǷΪ WORD cycleLkListIsEmpty(CycleLkList*); //ѭһ WORD cycleLkListCreate(CycleLkList*, LkNode); //ѭ WORD cycleLkListDisplay(CycleLkList*); //ѭͷ巨 WORD cycleLkListHeadInsert(CycleLkList*, LkNode); //ѭβ巨 WORD cycleLkListTrailInsert(CycleLkList*, LkNode); //ɾָ WORD cycleLkListDeleteByOrder(CycleLkList*,const int); //Ÿָ WORD cycleLkListUpdateByOrder(CycleLkList*,const int, LkNode); //ָź߲һ WORD cycleLkListInsertByOrder(CycleLkList*,const int, LkNode); //Ųָ WORD cycleLkListFindByOrder(CycleLkList*, const int, LkNode*); //еijԱǷҳн WORD cycleLkListFindByLkNodeMember(CycleLkList*, CycleLkList*, WORD (*LkNodeMemberInput)(LkNode*),WORD (*LkNodeMemberEqual)(LkNode*, LkNode*)); #endif
C
#include <stdio.h> #pragma warning( disable : 6031) int main(void) { printf("Enter x: "); double x = 0.0; scanf("%lf", &x); double res = 0.0; if (x <= 0) res = -x; if (x > 0 && x < 2) res = x * x; if (x >= 2) res = 4; printf("f = %lf", res); }
C
#include "snake.h" //ýṹָʼϢ void initSnake(Snake *s){ s->x = 1; s->y = 1; s->pre = NULL; s->next = NULL; } //жϷͷϷ int isSnakeEatItself(Snake *head){ int gameOver = 0; Snake *pt = head->next; while (pt){ if (head->x == pt->x && head->y == pt->y){ gameOver = 1; break; } pt = pt->next; } return gameOver; } //ǷԵʳ int isSnakeEatMeetFood(Snake *snake, Food *food){ if (snake->x == food->x && snake->y == food->y) return 1; else return 0; } //һ Snake *snakeGrow(Snake *head){ Snake *p = (Snake *)malloc(sizeof(Snake)); Snake *pt = head; //ͷ while (pt->next) //ȡβַָ pt = pt->next; p->pre = pt; //һṹpreָԭβһַָ pt->next = p; //ԭβһṹnextַָָ p->next = NULL; return p; } //ʳ void createFood(Food *food){ food->x = rand() % LENGTH; food->y = rand() % WIDTH; food->c = 65 + rand() % 26; } //ʳصصʳ int avoidOverlap(Snake *head, Food *food){ int t = 0, flag = 1; while (flag){ if (t > OVERLAP) break; flag = 0; t++; Snake *pt = head; while (pt){ if (isSnakeEatMeetFood(pt, food)){ flag = 1; createFood(food); break; } pt = pt->next; } } return t; } //ʳصصֵⷧ˶ķʳ void setFoodLocation(Food *food, Snake *head, int numOverlap, char c){ if (numOverlap > OVERLAP){ if (c == 'd'){ food->x = head->x + 1; food->y = head->y + 1; if (food->x >= LENGTH) food->x -= LENGTH; } else if (c == 'a'){ food->x = head->x - 1; food->y = head->y - 1; if (food->x >= LENGTH) food->x -= LENGTH; } else if (c == 'w'){ food->x = head->x + 1; food->y = head->y + 1; if (food->x >= LENGTH) food->x -= LENGTH; } else if (c == 's'){ food->x = head->x - 1; food->y = head->y - 1; if (food->x >= LENGTH) food->x -= LENGTH; } } } //õǰ char setCurKeyButton(char c){ char c1 = _getch(); if (c1 == 27) return 'x'; if (c != 'd'&&c1 == 'a') c = c1; else if (c != 'a' && c1 == 'd') c = c1; else if (c != 'w' && c1 == 's') c = c1; else if (c != 's'&& c1 == 'w') c = c1; return c; } //ߵƶ void snakeMove(Snake *head, Snake *rear, char c){ Snake *pt = rear; while (pt != head){ pt->x = pt->pre->x; pt->y = pt->pre->y; pt = pt->pre; } if (c == 's'){ head->y += 1; if (head->y >= WIDTH) head->y -= WIDTH; } else if (c == 'a'){ head->x -= 1; if (head->x >= LENGTH) head->x -= LENGTH; } else if (c == 'w'){ head->y -= 1; if (head->y >= WIDTH) head->y -= WIDTH; } else if (c == 'd'){ head->x += 1; if (head->x >= LENGTH) head->x -= LENGTH; } } //ߡʳΧǽ void drawPicture(Snake *head, Food *food){ int flag; Snake *pt; system("cls"); printf("------------------------------------------\n"); //Χǽ for (int j = 0; j < WIDTH; j++){ printf("|"); //Χǽ for (int i = 0; i < LENGTH; i++){ flag = 0; pt = head; while (pt){ // if (i == pt->x&&j == pt->y){ if (pt == head) printf(""); //ͷ else printf(""); // flag = 1; break; } pt = pt->next; } if (flag == 0){ //ʳ if (i == food->x&&j == food->y){ putchar(food->c); putchar(food->c); continue; } printf(" "); } } printf("|"); //Χǽ putchar('\n'); } printf("------------------------------------------\n"); //Χǽ }
C
#include<stdio.h> #include<string.h> int Cmp(char *A, char *B); void Reverse(char *str, int len); void Add(char *A, char *B, char *Result); void Sub(char *A, char *B, char *Result); void Mul(char *A, char *B, char *Result); void Mul_(char *A, char *B, char *Result); int main() { char A[65] = {0}; char B[65] = {0}; while(scanf("%s %s", A, B)!=EOF) { char R1[65] = {0}; char R2[65] = {0}; char R3[125] = {0}; Add(A, B, R1); Sub(A, B, R2); Mul(A, B, R3); printf("%s + %s = %s\n", A, B, R1); printf("%s - %s = %s\n", A, B, R2); printf("%s * %s = %s\n", A, B, R3); } return 0; } void Reverse(char *str, int len) { char *p, *q; p = str; q = p + len - 1; while(p<q) { char t = *p; *p = *q; *q = t; p++, q--; } } int Cmp(char *A, char *B) { if(strlen(A)>strlen(B)) return 1; if(strlen(A)<strlen(B)) return -1; char *pA = A, *pB = B; while(*pA) { if(*pA>*pB) return 1; else if(*pA<*pB) return -1; pA++, pB++; } return 0; // A = B } void Add(char *A, char *B, char *Result) { char *pA, *pB, *pR; pA = A, pB = B, pR = Result; if(strlen(A)<strlen(B)) pA = B, pB = A; Reverse(A, strlen(A)); Reverse(B, strlen(B)); while(*pB) { *pR += *pA + *pB - '0'; if(*pR>'9') { *pR -= 10; *(pR+1) = 1; } pA++, pB++, pR++; } while(*pA) { *pR += *pA; if(*pR>'9') { *pR -= 10; *(pR+1) = 1; } pA++, pR++; } if(*pR!='\0' && *pR<'0') *pR +='0'; Reverse(A, strlen(A)); Reverse(B, strlen(B)); Reverse(Result, strlen(Result)); } void Sub(char *A, char *B, char *Result) { // A - B char *pA, *pB, *pR; pA = A, pB = B, pR = Result; int sign = 0; if(Cmp(A, B)<0) { pA = B, pB = A; sign = 1; *pR++ = '-'; } else if(Cmp(A, B)==0) { *pR = '0'; return; } Reverse(A, strlen(A)); Reverse(B, strlen(B)); while(*pB) { *pR += *pA - *pB + '0'; if(*pR<'0') { *pR += 10; *(pR+1) = -1; } pA++, pB++, pR++; } while(*pA) { *pR += *pA; if(*pR<'0') { *pR += 10; *(pR+1) = -1; } pA++, pR++; } while(--pR>Result && *pR=='0') *pR ='\0'; Reverse(A, strlen(A)); Reverse(B, strlen(B)); Reverse(Result+sign, strlen(Result)-sign); } void Mul(char *A, char *B, char *Result) { Reverse(A, strlen(A)); Reverse(B, strlen(B)); Mul_(A, B, Result); Reverse(Result, strlen(Result)); Reverse(A, strlen(A)); Reverse(B, strlen(B)); } void Mul_(char *A, char *B, char *Result) { if(*B=='\0') return; char *pA = A, *pR = Result; while(*pA) { if(*pR>='0') *pR -= '0'; *pR += (*B-'0') * (*pA-'0'); if(*pR>9) { if(*(pR+1)=='\0') *(pR+1) += '0'; *(pR+1) += *pR/10; *pR %= 10; } *pR += '0'; pA++, pR++; } Mul_(A, B+1, Result+1); }
C
/*By:Yash Mudgal Date:12/09/2019*/ #include<stdio.h> void main() { int i=0; for(;i<100;i++) if((i/10)%2==1) printf("%d ",i); }
C
#include<stdio.h> #include<math.h> #include < string.h > int strle(const char *str) { return(strlen(*str)); } char *find(const char *str, const char *substr) { char *p; p = strchr(str, substr); char o = (p - str + 1); return(&o); } void delete(char *str, const char *substr) { printf("pos: %d\n", strstr(str, substr) - str); str = strstr(str, substr) - str; } void main() { printf("Task1\r\n"); char *str = "rfadfg", *substr = "a"; printf("%d\r\n",strlen(str)); printf("Task2\r\n"); printf("%d\r\n", find(str, substr)); printf("Task3\r\n"); delete(str, substr); system("pause"); }
C
#include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> int ft_iterative_factorial(int nb) { int ftl; ftl = 1; if (nb < 0) ftl = 0; while (nb != 0 && nb > 0) { ftl = ftl * nb; nb--; } return(ftl); } int main() { printf("%d\n", ft_iterative_factorial(-1)); return (0); }
C
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int isPrime(long int); int main(){ long int t, count,i; scanf("%ld", &t); long int num,max; while(t--){ max = 0; count = 0; num = 0; char *str = (char*)malloc(100000*sizeof(char)); scanf("%s", str); for(i=0; i<strlen(str)+1; i++){ if(str[i] >= '0' && str[i] <= '9'){ num *= 10; num += (int)(str[i] - '0'); } else{ if(isPrime(num)){ count++; if(num>max) max = num; } num=0; } } printf("%ld %ld\n", count, max); } return 0; } int isPrime(long int n){ int i; if(n==1) return 0; if (n==2) return 1; if (n%2==0) return 0; for (i=3;i<=(int)sqrt(n);i+=2){ if (n%i==0) return 0; } return 1; }
C
#include <stdio.h> struct node{ int data; struct node* link; }; void main(void){ struct node n1, n2, n3; n1.data = 10; n1.link = &n2; n2.data = 20; n2.link = &n1; n3.data = 30; n3.link = &n3; printf("%d %d %d \n", n1.data, n2.data, n3.data); // 10 20 30 printf("%d %d %d \n", n2.link -> data, n1.link -> data, n3.link -> data); //10 20 30 return 0; }
C
#include "variadic_functions.h" /** * print_all - function that prints anything. * @format: const char pointer * Return: void **/ void print_all(const char * const format, ...) { va_list list; char *s; int j = 0, k = 1; va_start(list, format); while (format && format[j]) { switch (format[j]) { case 'c': printf("%c", va_arg(list, int)); break; case 'i': printf("%d", va_arg(list, int)); break; case 'f': printf("%f", va_arg(list, double)); break; case 's': s = va_arg(list, char *); if (s == NULL) { printf("(nil)"); break; } printf("%s", s); break; default: k = 0; } if (format[j + 1] != 0 && k) printf(", "); j++; k++; } va_end(list); printf("\n"); }
C
#include <stdio.h> #include <math.h> void app35(int a,int b,int c,int d) { if (a == b + c + d || b == a + c + d || c == a + b + d || d == a + b + c) { printf("true\n"); }else{ printf("false\n"); } } void main() { int a,b,c,d; printf("a:"); scanf("%d",&a); printf("\n"); printf("b:"); scanf("%d",&b); printf("\n"); printf("c:"); scanf("%d",&c); printf("\n"); printf("d:"); scanf("%d",&d); printf("\n"); app35(a,b,c,d); }
C
/* * This work is part of the White Rabbit project * * Copyright (C) 2011 CERN (www.cern.ch) * Author: Tomasz Wlostowski <[email protected]> * * Released according to the GNU GPL, version 2 or any later version. */ #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { if (argc < 3) return -1; FILE *f = fopen(argv[1], "rb"); if (!f) return -1; unsigned char x[4]; int i = 0; int n = atoi(argv[2]); int base = 0; int file_pos = 0; if(argc >= 5) { file_pos = atoi(argv[3]); base = atoi(argv[4]); } fseek(f, file_pos, SEEK_SET); while (!feof(f) && (n == 0 || (i < n))) { fread(x, 1, 4, f); printf("write %x %02X%02X%02X%02X\n", base + i, x[3], x[2], x[1], x[0]); i++; } for (; i < n;) { printf("write %x %02X%02X%02X%02X\n", base + i, 0, 0, 0, 0); i++; } fclose(f); return 0; }
C
#include <stdio.h> #include <stdlib.h> void triplePointeur(int *pointeurSurNombre); int main() { int nombre = 5; int *pointeur = &nombre; //pointeur prend l'adresse de nombre. triplePointeur(pointeur); //on envoie pointeur (l'adresse de nombre) à la fonction. printf("%d\n", *pointeur); //on affiche la valeur de nombre avec *pointeur. return 0; } void triplePointeur(int *pointeurSurNombre) { *pointeurSurNombre *= 3; //on multiplie par 3 la valeur de nombre. }
C
#include<stdio.h> main() { int x,n,s=1,i; printf("Enter the value of base,x: "); scanf("%d",&x); printf("Enter the value of power,n: "); scanf("%d",&n); if (n>=0) { for(i=0;i<n;i++) s=s*x; printf("\nValue of %d to the power %d is: %d\n",x,n,s); } else return 0; }
C
#include "stdio.h" int main() { int n,c,m,i,max,num,tmp=0; scanf("%d %d %d",&n,&c,&m); max=c*m; for(i=0;i<n;i++) { scanf("%d",&num); if(num>max) tmp=1; } if(tmp) printf("No\n"); else printf("Yes\n"); return 0; } /* Alice owns a company that transports tour groups between two islands. She has n trips booked, and each trip i has pi passengers. Alice has m boats for transporting people, and each boat's maximum capacity is c passengers. Given the number of passengers going on each trip, determine whether or not Alice can perform all n trips using no more than m boats per individual trip. If this is possible, print Yes; otherwise, print No. Input Format The first line contains three space-separated integers describing the respective values of n (number of trips), c (boat capacity), and m (total number of boats). The second line contains n space-separated integers describing the values of p0,p1,....,pn-1. Constraints 1<=n,c,m<=100 1<=pi<=100 Output Format Print Yes if Alice can perform all n booked trips using no more than m boats per trip; otherwise, print No. Sample Input 0 5 2 2 1 2 1 4 3 Sample Output 0 Yes Explanation 0 Alice has m=2 boats and a maximum capacity of c=2 passengers per boat. This means she can transport at most m*c=4 passengers at a time. There are n=5 tour groups, and the largest tour group contains p3=4 passengers. Because Alice will be able to transport each group using <=m boats per group, we print Yes. Sample Input 1 5 1 2 1 2 1 4 1 Sample Output 1 No Explanation 1 Alice has m=2 boats and a maximum capacity of c=1 passenger per boat. This means she can transport at most m*c=2 passengers at a time. There are n=5 tour groups, and the largest tour group contains p3=4 passengers. Because Alice does not have enough boats to transport a group of four passengers, we print No. */
C
#include "minishell.h" void free_tab(char **str) { int i; int len; i = 0; len = 0; while (str[len]) len++; while (i < len) { free(str[i]); i++; } }
C
#include <stdio.h> //float subset_methx(FILE *, const int includes, const int excludes, const int n_samples) { // // const int INIT_SIZE = 10000; // float data[INIT_SIZE][n_samples]; // return data; //} int main(){ FILE *ifile; const int includes = 5, excludes = 32, n_samples = 16; //float data[][]; int filesize, n_rows, n_items = 0; int pos; char flag; float meth[n_samples]; int i; float *data; // pointer to the data array ifile = fopen("/scratch/project_2003907/King/features/methylation_features.matrix", "r"); fseek(ifile, 0, SEEK_END); filesize = ftell(ifile); fseek(ifile, 0, SEEK_SET); n_rows = filesize / (sizeof(int) + sizeof(char) + sizeof(float) * n_samples); for (i = 0; i < n_rows; i++){ fread(&pos, sizeof(int), 1, ifile); fread(&flag, sizeof(char), 1, ifile); fread(&meth, sizeof(float), n_samples, ifile); if (((flag & includes) == includes) && ((flag & excludes) == 0)) { n_items += 1; } } printf("Matching rows: %d out of %d\n", n_items, n_rows); data = (float*)malloc(n_items*sizeof(float)*n_samples); }
C
#include <stdio.h> #include <string.h> char *mx_strchr(const char *s ,int c); int mx_strlen(const char *s); int mx_strncmp(const char *s1, const char *s2, int n ); char *mx_strstr(const char *s1, const char *s2) { int len1 = mx_strlen(s1); //int len2 = mx_strlen(s2); // int c = 0; // mx_strncmp(s1,s2,len2); for (int i = 0; s2[i]; i++) { if (mx_strncmp(s1, &s2[i], len1 - 1) == 0){ //c = s2[i]; return (char *) &s2[i]; } } return NULL; } // int main(){ // const char s1[] = "qui"; // const char s2[] = "The quick brown fox"; // printf("the substring is: %s",mx_strstr(s1,s2)); // }
C
#include <stdio.h> #include <stdint.h> float absoluteValue (float x){ if ( x < 0 ) x = -x; return (x); } // Function to compute the square root of a number float squareRoot (float x, float epsilon){ //const float epsilon = .00001; float guess = 1.0; while ( absoluteValue (guess * guess - x) >= epsilon ) guess = ( x / guess + guess ) / 2.0; return guess; } uint32_t main(uint32_t argc, uint8_t *argv[]){ printf ("squareRoot (2.0) = %f\n", squareRoot (2.0 , 0.00001 )); printf ("squareRoot (2.0) = %f\n", squareRoot (2.0 , 0.1 )); printf ("squareRoot (2.0) = %f\n", squareRoot (2.0 , 1.0 )); return 0; }
C
#include<errno.h> #include<unistd.h> #include<stdlib.h> #include<stdio.h> #include<unistd.h> #include<fcntl.h> #include<string.h> #include<sys/types.h> #include<sys/stat.h> #include<sys/prctl.h> #include<sys/mman.h> typedef struct map { long long int addr; long long int length; char* path; } map; int set_exe_file(char *path){ int fd = open(path, O_RDONLY); if(prctl(PR_SET_MM, PR_SET_MM_EXE_FILE, fd, 0, 0)){ perror("prctl error has occured"); exit(1); } } void unmap(map maps[], int count){ for(int i = 0; i < count; i++){ if(munmap((int*)maps[i].addr, maps[i].length)){ perror("munmap error has occured"); exit(1); } } } int get_file_maps(map *maps, char* old_path){ FILE *file = fopen("/proc/self/maps", "r"); char line[1024]; char *path; int length = 0; int mapIndex = 0; unsigned long start, end; while (!feof(file)) { if (fgets(line, sizeof(line) / sizeof(char), file) == NULL) { break; } if (sscanf(line, "%lx-%lx", &start, &end) != 2) { continue; // could not parse. fail gracefully and try again on the next line. } int pathIndex = 0; int permIndex = 0; for(int i = 0; line[i] != '\0'; i++){ if(permIndex == 0 && line[i] == ' '){ permIndex = i+1; } if(line[i] == '/'){ pathIndex = i; break; } } if(pathIndex == 0){ continue; // Not a file map } // Check for executable permission to preserve GOT //if(line[permIndex+2] == '-'){ //continue; //} path = malloc(1024); if(sscanf(line + pathIndex, "%s", path) == 0){ continue; // failed to parse } if(strcmp(old_path, path) != 0){ continue; // This isn't the requested map } length = end - start; map m = {start, length, path}; maps[mapIndex] = m; mapIndex += 1; } fclose(file); return mapIndex; } void change_exe(char* new_path){ char old_path[1024]; char new_path_copy[1024]; map maps[32]; int mapsCount = 0; int size = 0; // Old data segment will be destroyed, we don't risk new_path being stored there so we copy strcpy(new_path_copy, new_path); size = readlink("/proc/self/exe", old_path, 1024); old_path[size] = '\0'; if(strcmp(old_path, new_path_copy) == 0){ return; } mapsCount = get_file_maps(maps, old_path); unmap(maps, mapsCount); printf("Successfully unmapped!"); set_exe_file(new_path_copy); printf("Done!\n"); sleep(1000); }
C
/* ** main.c for in /home/nicolas/horbac_n/my_sort_int_tab ** ** Made by HORBACZ Nicolas ** Login <[email protected]> ** ** Started on Thu Mar 23 10:10:40 2017 HORBACZ Nicolas ** Last update Thu Mar 23 17:45:25 2017 HORBACZ Nicolas */ #include <stdio.h> void my_sort_int_tab(int *tab, int size); int main() { int tab[5] = {'5', '2', '8', '4', '9'}; int test; my_sort_int_tab(tab, 5); printf("%d", test); return(0); }
C
/************************************************************************* > File Name: sequence_reverse.c > Author: zhuxinquan > Mail: [email protected] > Created Time: 2015年09月20日 星期日 17时42分27秒 ************************************************************************/ #include<stdio.h> #include<stdlib.h> #define N 20 struct seqlist{ int data[N]; int length; }; typedef struct seqlist * Sequence; void CreatSequence(Sequence L) { int x, i = 0; printf("please input and enter -1 end:\n"); scanf("%d", &x); while(x != -1) { L->data[i++] = x; scanf("%d", &x); } L->length = i; } void reverse(Sequence L) { int i, temp; int middle = (L->length + 1)/2; for(i = 0; i < middle; i++) { temp = L->data[i]; L->data[i] = L->data[L->length - i -1]; L->data[L->length -i -1] = temp; } } void PrintSequence(Sequence L) { int i; for(i = 0; i < L->length; i++) { printf("%3d", L->data[i]); } printf("\n"); } int main(void) { Sequence L; L = (Sequence)malloc(sizeof(struct seqlist)); CreatSequence(L); PrintSequence(L); reverse(L); PrintSequence(L); }
C
/* * Delta programming language */ #include "delta/delta.h" #include <string.h> #include <ctype.h> /** * @category modules/core/string * * @brief Trim right side of a string of whitespace. */ DELTA_FUNCTION(rtrim) { // prepare incoming arguments int size, i; char *arg0 = delta_cast_new_string(DELTA_ARG0, &size); // count the spaces int spaces = 0; for(i = size - 1; i >= 0; --i) { if(!isspace(arg0[i])) break; ++spaces; } arg0[size - spaces] = '\0'; // return DELTA_RETURN_BINARY_STRING(arg0, size - spaces); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* keyhandle.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jwolf <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/10 14:54:12 by jwolf #+# #+# */ /* Updated: 2018/07/10 14:54:13 by jwolf ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/wolf3d.h" void rotate(int key, t_wolf *w) { double olddirx; double oldplanex; double angle; angle = w->rotspeed; olddirx = w->p.dirx; oldplanex = w->panex; if (key == D || key == ARROW_RIGHT) { w->p.dirx = w->p.dirx * cos(-angle) - w->p.diry * sin(-angle); w->p.diry = olddirx * sin(-angle) + w->p.diry * cos(-angle); w->panex = w->panex * cos(-angle) - w->paney * sin(-angle); w->paney = oldplanex * sin(-angle) + w->paney * cos(-angle); } if (key == A || key == ARROW_LEFT) { w->p.dirx = w->p.dirx * cos(angle) - w->p.diry * sin(angle); w->p.diry = olddirx * sin(angle) + w->p.diry * cos(angle); w->panex = w->panex * cos(angle) - w->paney * sin(angle); w->paney = oldplanex * sin(angle) + w->paney * cos(angle); } } void move_x_y(int key, t_wolf *w) { double ms; ms = w->movespeed; if (w->p.x + w->p.dirx * ms > 0 && w->p.y + w->p.diry * ms > 0 && w->p.x + w->p.dirx * ms < w->h && w->p.y + w->p.diry * ms < w->w) { if ((key == W || key == ARROW_UP)) { if (w->pnts[(int)(w->p.x + w->p.dirx * ms)][(int)(w->p.y)].type < 1) w->p.x += w->p.dirx * ms; if (w->pnts[(int)(w->p.x)][(int)(w->p.y + w->p.diry * ms)].type < 1) w->p.y += w->p.diry * ms; } } if (w->p.x - w->p.dirx * ms > 0 && w->p.y - w->p.diry * ms > 0 && w->p.x - w->p.dirx * ms < w->h && w->p.y - w->p.diry * ms < w->w) { if ((key == S || key == ARROW_DOWN)) { if (w->pnts[(int)(w->p.x - w->p.dirx * ms)][(int)(w->p.y)].type < 1) w->p.x -= w->p.dirx * ms; if (w->pnts[(int)(w->p.x)][(int)(w->p.y - w->p.diry * ms)].type < 1) w->p.y -= w->p.diry * ms; } } } int key_press_hook(int key, t_wolf *w) { if (key == ESC) exit_hook(key, w); move_x_y(key, w); rotate(key, w); return (0); } int exit_hook(int but, t_wolf *w) { (void)w; (void)but; exit(0); return (0); }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include "matrix.h" // cria uma matriz de zeros com dimensão especificada matrix *create_matrix(unsigned long n_lin, unsigned long n_col) { unsigned long i; matrix *m = malloc(sizeof(matrix)); m->lin = n_lin; m->col = n_col; m->val = (double **) calloc(m->lin, sizeof(double *)); for (i = 0; i < m->lin; i++) m->val[i] = (double *) calloc(m->col + 1, sizeof(double)); return m; } // carrega a matriz do caminho especificado matrix *load_matrix(char *filepath) { unsigned long i, j; double v; matrix *m; FILE *file = fopen(filepath, "r"); if (file == NULL) { printf("Unable to read file, exiting...\n"); exit(1); } if (!fscanf(file, "%lu", &i)) { printf("Unable to read file, exiting...\n"); exit(1); } if (!fscanf(file, "%lu", &j)) { printf("Unable to read file, exiting...\n"); exit(1); } m = create_matrix(i, j); while (true) { if (fscanf(file, "%lu", &i) == EOF) break; if (fscanf(file, "%lu", &j) == EOF) break; if (fscanf(file, "%lf", &v) == EOF) break; m->val[i-1][j-1] = v; } fclose(file); return m; } // carrega a matriz de forma transposta do caminho especificado matrix *load_matrix_t(char *filepath) { unsigned long i, j; double v; matrix *m; FILE *file = fopen(filepath, "r"); if (file == NULL) { printf("Unable to read file, exiting...\n"); exit(1); } if (!fscanf(file, "%lu", &i)) { printf("Unable to read file, exiting...\n"); exit(1); } if (!fscanf(file, "%lu", &j)) { printf("Unable to read file, exiting...\n"); exit(1); } m = create_matrix(j, i); while (true) { if (fscanf(file, "%lu", &i) == EOF) break; if (fscanf(file, "%lu", &j) == EOF) break; if (fscanf(file, "%lf", &v) == EOF) break; m->val[j-1][i-1] = v; } fclose(file); return m; } // salva a matriz no caminho especificado void save_matrix(char *filepath, matrix *m) { unsigned long i, j; FILE *file = fopen(filepath, "w"); fprintf(file, "%lu %lu\n", m->lin, m->col); for (i = 0; i < m->lin; i++) for (j = 0; j < m->col; j++) fprintf(file, "%lu %lu %lf\n", i + 1, j + 1, m->val[i][j]); fclose(file); } // desaloca a matriz da memoria void destroy_matrix(matrix *m) { unsigned long i; for (i = 0; i < m->lin; i++) free(m->val[i]); free(m->val); free(m); }
C
/* * Application.c * * Created on: Jul 1, 2013 * Author: Erich Styger */ #include "Application.h" #include "SW1.h" #include "LEDR.h" #include "LEDG.h" #include "LEDB.h" #include "WAIT1.h" #include "HIDJ1.h" #include "AD1.h" #include "SW1.h" #include "SW2.h" #include "SW3.h" #include "SW4.h" #include "SW5.h" #include "SW6.h" #include "SW7.h" static uint16_t midPointX, midPointY; static int8_t ToSigned8Bit(uint16_t val, bool isX) { int32_t tmp; if (isX) { tmp = (int32_t)val-midPointX; } else { tmp = (int32_t)val-midPointY; } if (tmp>0) { tmp = (tmp*128)/0x7fff; } else { tmp = (-tmp*128)/0x7fff; tmp = -tmp; } if (tmp<-128) { tmp = -128; } else if (tmp>127) { tmp = 127; } return (int8_t)tmp; } static uint8_t GetXY(uint16_t *x, uint16_t *y, int8_t *x8, int8_t *y8) { uint8_t res; uint16_t values[2]; res = AD1_Measure(TRUE); if (res!=ERR_OK) { return res; } res = AD1_GetValue16(&values[0]); if (res!=ERR_OK) { return res; } if (x!=NULL) { *x = values[0]; } if (y!=NULL) { *y = values[1]; } /* transform into -128...127 with zero as mid position */ if (x8!=NULL) { *x8 = ToSigned8Bit(values[0], TRUE); } if (y8!=NULL) { *y8 = ToSigned8Bit(values[1], FALSE); } return ERR_OK; } static void CheckButtons(void) { uint8_t hatPos; /* push buttons */ //HIDJ1_SetButton(0, SW1_GetVal()==0); //HIDJ1_SetButton(1, SW2_GetVal()==0); //HIDJ1_SetButton(2, SW3_GetVal()==0); //HIDJ1_SetButton(3, SW4_GetVal()==0); HIDJ1_SetButton(0, SW5_GetVal()==0); /* E */ HIDJ1_SetButton(1, SW6_GetVal()==0); /* F */ HIDJ1_SetButton(2, SW7_GetVal()==0); /* center */ /* hat switch with 4 */ if (SW1_GetVal()==0) { /* A */ hatPos = 0; /* top */ } else if (SW2_GetVal()==0) { /* B */ hatPos = 1; /* right */ } else if (SW3_GetVal()==0) { /* C */ hatPos = 2; /* bottom */ } else if (SW4_GetVal()==0) { /* D */ hatPos = 3; /* left */ } else { hatPos = -1; /* center */ } HIDJ1_SetHatPos(hatPos); } void APP_Run(void) { int cnt=0; /* counter to slow down LED blinking */ uint8_t res; int8_t x, y; (void)GetXY(&midPointX, &midPointY, NULL, NULL); /* get initial mid point values */ for(;;) { res = GetXY(NULL, NULL, &x, &y); /* get potentiometer values */ HIDJ1_SetXY(x, y); /* set X and Y position */ HIDJ1_SetThrottle(x); /* Set throttle */ CheckButtons(); /* check push buttons */ WAIT1_Waitms(10); /* wait some time */ cnt++; if (HIDJ1_App_Task()==ERR_OK) { /* run the USB application task: this will send the buffer */ if ((cnt%100)==0) { /* slow down blinking */ LEDR_Off(); LEDG_Neg(); /* blink green LED if connected */ } } else { if ((cnt%200)==0) { LEDG_Off(); LEDR_Neg(); /* blink red LED if not connected */ } } } }
C
#include "rAlgo.h" #define DET_NUM 200 char **selfSet; int **matrix, ma; void initMat() { int i, j; matrix=(int **)malloc(sizeof(int *)*ma); for(i=0; i<ma; i++) matrix[i]=(int *)malloc(sizeof(int)*ma); for(i=0; i<ma; i++) for(j=0; j<ma; j++) matrix[i][j]=0; } int getDetector(int r1, int rc) { char temp[STR_LENGTH+1]; int r; while(1) { generateRandStr(temp); r=rAlgo(temp, selfSet, r1, rc+1-r1); if(r!=rc+1) return r; } } int main() { int i, j, rc, r1, count, r; FILE *fout; srand((unsigned)time(NULL)); selfSet=(char **)malloc(sizeof(char *)*LINE_NUM); for(i=0; i<LINE_NUM; i++) selfSet[i]=(char *)malloc(sizeof(char)*(STR_LENGTH+1)); loadSelfSet("./randomized/sample", selfSet); ma=rcmax-r1min+1; initMat(); printf("init matrix over.\n"); fflush(stdout); matrix[0][0]=DET_NUM; for(rc=r1min+1; rc<=rcmax; rc++) { printf("rc=%d\n", rc); fflush(stdout); r1=r1min; count=0; while(count!=DET_NUM) { r=getDetector(r1, rc); matrix[r-r1min][rc-r1min]+=1; count+=1; if(count%10==0) { printf("\t%d of %d\n", count, DET_NUM); fflush(stdout); } } } fout=fopen("./randomized/case1.out","w"); for(rc=r1min; rc<=rcmax; rc++) for(r=r1min; r<=rc; r++) printf("r=%d, rc=%d %d\n", r, rc, matrix[r-r1min][rc-r1min]); for(rc=r1min; rc<=rcmax; rc++) for(r=r1min; r<=rc; r++) fprintf(fout, "r=%d, rc=%d %d\n", r, rc, matrix[r-r1min][rc-r1min]); fflush(fout); fclose(fout); return 0; }
C
#include <stdio.h> #include <stdint.h> int main(int argc, char* argv[]) { // Ensure proper usage if (argc != 2) { fprintf (stderr,"Error! Usage: ./recover forensic image\n"); return 1; } // Opening the card file in read mode FILE *fptr = fopen(argv[1],"r"); if (fptr == NULL) { fprintf (stderr,"Error! file %s can't be opened\n",argv[1]); return 2; } // Declare a file pointer to place the JPEG's pixel in new file FILE* pic = NULL; int count = 0; // Declaring a buffer of size 512 unsigned char buffer[512]; // To read 512 blocks in one go while ( fread(buffer, sizeof(unsigned char), 512, fptr) == 512) { // To detect JPEG's signature if ((buffer[0] == 0xff) && (buffer[1] == 0xd8) && (buffer[2] == 0xff) && ((buffer[3] & 0xf0) == 0xe0)) { if (count != 0) { fclose(pic); } // String to determmine JPEG's name char filename[10]; sprintf(filename, "%03i.jpg", count); // Increment count by 1 for a JPEG count++; // Opening a new file in write mode to place JPEG's pixels pic = fopen(filename, "w"); if (pic == NULL) { fprintf(stderr,"Error! Can't write in file %s\n",filename); return 3; } // Writing to the file 512 bytes in one go fwrite(buffer, sizeof(unsigned char), 512, pic); } // If the old JPEG's pixels aren't over yet else if (pic != NULL) { fwrite(buffer, sizeof(unsigned char), 512, pic); } } // closing file fclose(fptr); }
C
/* ************************************************************************** */ /* */ /* :::::::: */ /* ft_realloc.c :+: :+: */ /* +:+ */ /* By: lsmit <[email protected]> +#+ */ /* +#+ */ /* Created: 2020/02/19 18:34:28 by lsmit #+# #+# */ /* Updated: 2020/03/10 21:00:29 by lsmit ######## odam.nl */ /* */ /* ************************************************************************** */ #include "../inc/cub3d.h" int **ft_memcpyint(int **dest, int **src, size_t n, t_vars *vars) { int i; size_t j; j = 0; while (j < n) { i = 0; while (i < vars->linelen[j]) { dest[j][i] = src[j][i]; i++; } j++; } return (dest); } double **ft_memcpydouble(double **dest, double **src, size_t n, size_t linelen) { size_t i; size_t j; j = 0; while (j < n) { i = 0; while (i < linelen) { dest[j][i] = src[j][i]; i++; } j++; } return (dest); } int **ft_reallocmap(int **array, size_t newsize, t_vars *vars) { int **newarray; size_t i; i = 0; if (newsize == 1) return (malloc(sizeof(int **) * 1)); newarray = (int **)malloc(sizeof(int **) * newsize); if (!newarray) ft_error("\e[33mMalloc failed\n\e[39m"); while (i < newsize - 1) { newarray[i] = (int*)malloc(sizeof(int *) * vars->linelen[i]); if (!newarray[i]) ft_error("\e[33mMalloc failed\n\e[39m"); i++; } newarray = ft_memcpyint(newarray, array, newsize - 1, vars); ft_free((void **)array, newsize - 1); free(array); return (newarray); } double **ft_reallocsprit(double **array, size_t newsize) { double **newarray; size_t i; i = 0; if (newsize == 1) return (malloc(sizeof(double **) * 1)); newarray = (double **)malloc(sizeof(double **) * newsize); while (i < newsize - 1) { newarray[i] = (double*)malloc(sizeof(double *) * 5); if (!newarray[i]) ft_error("\e[33mMalloc failed\n\e[39m"); i++; } newarray = ft_memcpydouble(newarray, array, newsize - 1, 5); ft_free((void **)array, (int)newsize - 1); free(array); return (newarray); } int *ft_realloc(int *array, size_t newsize) { int *newarray; if (newsize == 1) return (malloc(sizeof(int *) * 1)); newarray = malloc(sizeof(int *) * newsize); if (!newarray) ft_error("\e[33mMalloc failed\n\e[39m"); newarray = ft_memcpy(newarray, array, newsize - 1); free(array); return (newarray); }
C
#include "LCD.h" #include <stdint.h> #include "ST7735.h" #include "LineDrawer.h" extern const unsigned short ClockFace_24bit[]; uint32_t TimeX = 0; uint32_t TimeY = 1; uint32_t AlarmX = 2; uint32_t AlarmY = 3; uint32_t StatusX_ON = 4; uint32_t StatusY_ON = 5; uint32_t StatusX_OFF = 6; uint32_t StatusY_OFF = 7; void LCDArrayInit(char Time[], char Alarm[], uint32_t Cursor[]){ // Initialize Time and Alarm Arrays to be "12:00 am" Time[0] = 0x31; // 1 Alarm[0] = 0x31; Time[1] = 0x32; // 2 Alarm[1] = 0x32; Time[2] = 0x3A; // colon Alarm[2] = 0x3A; Time[3] = 0x30; // 0 Alarm[3] = 0x30; Time[4] = 0x30; // 0 Alarm[4] = 0x30; Time[5] = 0x20; // space Alarm[5] = 0x20; Time[6] = 0x61; // a or p (a = 0x61, p = 0x70) Alarm[6] = 0x61; Time[7] = 0x6D; // m Alarm[7] = 0x6D; Time[8] = 0; // null terminated Alarm[8] = 0; Cursor[TimeX] = 8; // Initialize Coordinates Array Cursor[TimeY] = 0; Cursor[AlarmX] = 8; Cursor[AlarmY] = 2; Cursor[StatusX_ON] = 15; Cursor[StatusY_ON] = 4; Cursor[StatusX_OFF] = 17; Cursor[StatusY_OFF] = 4; ST7735_InitR(INITR_REDTAB); // Set up display ST7735_SetCursor(0, 0); ST7735_OutString("Time:"); ST7735_SetCursor(0, 2); ST7735_OutString("Alarm:"); ST7735_SetCursor(0, 4); ST7735_OutString("Alarm Status:"); } void LCDDisplayInit(char Time[], char Alarm[], uint32_t Cursor[]){ ST7735_SetCursor(Cursor[TimeX], Cursor[TimeY]); ST7735_OutString(Time); ST7735_SetCursor(Cursor[AlarmX], Cursor[AlarmY]); ST7735_OutString(Alarm); ST7735_SetCursor(Cursor[StatusX_OFF], Cursor[StatusY_OFF]); ST7735_OutString("OFF"); ST7735_DrawBitmap(14, 155, ClockFace_24bit, 100, 100); ST7735_Line(64, 106, 64, 73, ST7735_GREEN); ST7735_Line(64, 106, 64, 90, ST7735_RED); } void DrawHands(uint32_t MinuteX[], uint32_t MinuteY[], uint32_t HourX[], uint32_t HourY[], uint32_t HourCounter, uint32_t MinuteCounter, uint32_t PreviousHour, uint32_t PreviousMinute){ ST7735_Line(64, 106, MinuteX[PreviousMinute], MinuteY[PreviousMinute], ST7735_BLACK); ST7735_Line(64, 106, HourX[4*(PreviousHour%12)+(PreviousMinute/15)], HourY[4*(PreviousHour%12)+(PreviousMinute/15)], ST7735_BLACK); ST7735_Line(64, 106, MinuteX[MinuteCounter], MinuteY[MinuteCounter], ST7735_GREEN); ST7735_Line(64, 106, HourX[4*(HourCounter%12)+(MinuteCounter/15)], HourY[4*(HourCounter%12)+(MinuteCounter/15)], ST7735_RED); }
C
/* * * pre_execute * En base a sus parametros, devuelve una estructura * sencilla con los datos necesarios para operar el * proceso. Entre ellos, se encuentra el grafo del programa. * * */ process_params_t pre_execute(status_t program, graph_t mem); /* * * true_step * setea el nodo current en verdadero, * y llama al proximo paso. * * */ void true_step(process_params_t par); /* * * false_step * setea el nodo current en falso, * y llama al proximo paso * * */ void false_step(process_params_t par); /* * * conditional_step * setea el nodo current en una expresion condicional * y llama al proxima paso * * */ void conditional_step(process_params_t par); /* * * run_process * ejecuta un nuevo thread, en base a la instruccion * seleccionada, y con los parametros adecuados * * * */ void run_process(status_t c_program, void * (* execute_func) (void *)); /* * * get_params_from_pid * devuelve una estructura que contiene la informacion para * cada ipc, y la identifica univocamente por su pid. * * * */ ipc_params_t get_params_from_pid(int pid, int type, int shm_size, int aux_semid); /* * * end_process * libera los procesos de memoria * * */ void end_process();
C
#include<stdio.h> #define AREA (2*10); int main() { int AREA=2; printf("%d",AREA); return 0; }
C
// Ordering three integers // 12/03/2017 // By Anthony Xu - [email protected] #include <stdio.h> int main(void) { int a, b, c; printf("Enter integer: "); scanf("%d", &a); printf("Enter integer: "); scanf("%d", &b); printf("Enter integer: "); scanf("%d", &c); printf("The integers in order are: "); if (a <= b && b <= c) { printf("%d %d %d\n", a, b, c); } else if (b <= a && a <= c) { printf("%d %d %d\n", b, a, c); } else if (c <= b && b <= a) { printf("%d %d %d\n", c, b, a); } else if (a <= c && c <= b) { printf("%d %d %d\n", a, c, b); } else if (c <= a && a <= b) { printf("%d %d %d\n", c, a, b); } else { printf("%d %d %d\n", b, c, a); } return 0; }
C
/* ** EPITECH PROJECT, 2017 ** my_strncmp.c ** File description: ** compare to string up to n size */ #include "my.h" int my_strncmp(char const *s1, char const *s2, int n) { int i = 0; while (*s1 == *s2 && i <= n) { ++s1; ++s2; ++i; } return (*s1 - *s2); }
C
#include <stdio.h> void main() { int i, fact = 1, no; printf("Enter the n0:\n"); scanf("%d", &no); if (no<= 0) fact = 1; else { for (i = 1; i <= no; i++) { fact = fact * i; } } printf("Factorial of %d = %5d\n", num, fact) }
C
/* ** EPITECH PROJECT, 2020 ** NWP_myteams_2019 ** File description: ** client_execute_cmd.c */ #include <string.h> #include "client.h" #include "utils.h" static void execute(client_t *client, char **tab) { char **tmp_tab = tab; if (tmp_tab == NULL || tmp_tab[0] == NULL) return; for (int i = 0; MESSAGES_LOG[i].code != NULL; i++) { if (strncmp(tmp_tab[0], MESSAGES_LOG[i].code, 3) == 0) { tmp_tab = MESSAGES_LOG[i].ptr(tmp_tab); return execute(client, tmp_tab); } } } void client_execute_cmd(client_t *client) { char **tab = NULL; if (!client->reader) return; tab = split(client->reader, "\r\n"); if (!tab) return; execute(client, tab); if (strncmp(client->printer, "/logout", 7) == 0) run(true); for (int i = 0; tab[i]; i++) free(tab[i]); free(tab); free(client->reader); client->reader = NULL; }
C
#include "sys.h" #include "delay.h" #include "led.h" #include "usart.h" #include "mpu.h" #include "lcd.h" #include "sdram.h" #include "usmart.h" #include "key.h" #include "stmflash.h" //ALIENTEK STM32H7 ʵ37 //FLASHģEEPROM ʵ //֧֣www.openedv.com //ӿƼ޹˾ //Ҫд뵽STM32 FLASHַ const u8 TEXT_Buffer[]={"STM32 FLASH TEST"}; #define TEXT_LENTH sizeof(TEXT_Buffer) //鳤 #define SIZE TEXT_LENTH/4+((TEXT_LENTH%4)?1:0) #define FLASH_SAVE_ADDR 0X08020000 //FLASH ַ(Ϊ4ı,Ҫڱռõ. //,дʱ,ܻᵼ²,Ӷ𲿷ֳʧ.. int main(void) { u8 led0sta=1; u8 key=0; u16 i=0; u8 datatemp[SIZE]; Stm32_Clock_Init(160,5,2,4); //ʱ,400Mhz delay_init(400); //ʱʼ uart_init(100,115200); //ڳʼΪ115200 usmart_dev.init(100); //ʼUSMART LED_Init(); //ʼLEDӵӲӿ MPU_Memory_Protection(); //ش洢 SDRAM_Init(); //ʼSDRAM LCD_Init(); //ʼLCD KEY_Init(); //ʼ POINT_COLOR=RED; //Ϊɫ LCD_ShowString(30,50,200,16,16,"Apollo STM32F4/F7/H7"); LCD_ShowString(30,70,200,16,16,"FLASH EEPROM TEST"); LCD_ShowString(30,90,200,16,16,"ATOM@ALIENTEK"); LCD_ShowString(30,110,200,16,16,"2018/7/18"); LCD_ShowString(30,130,200,16,16,"KEY1:Write KEY0:Read"); while(1) { key=KEY_Scan(0); if(key==KEY1_PRES) //KEY1,дSTM32 FLASH { LCD_Fill(0,170,239,319,WHITE);// LCD_ShowString(30,170,200,16,16,"Start Write FLASH...."); STMFLASH_Write(FLASH_SAVE_ADDR,(u32*)TEXT_Buffer,SIZE); LCD_ShowString(30,170,200,16,16,"FLASH Write Finished!");//ʾ } if(key==KEY0_PRES) //KEY0,ȡַʾ { LCD_ShowString(30,170,200,16,16,"Start Read FLASH.... "); STMFLASH_Read(FLASH_SAVE_ADDR,(u32*)datatemp,SIZE); LCD_ShowString(30,170,200,16,16,"The Data Readed Is: ");//ʾ LCD_ShowString(30,190,200,16,16,datatemp);//ʾַ } i++; delay_ms(10); if(i==20) { LED0(led0sta^=1);//ʾϵͳ i=0; } } }
C
#include <stdio.h> int count(int from, int to, void (*myOut)(int i)) { int j = 0, rv = 0; if (from >= to) { rv = -1; } else { for(j = 0; j < to - from; j++) { rv += from + j; } } (*myOut)(rv); return 0; } void displayU(int i) { /* display the result in upper case. */ printf("WE GOT: %d\n", i); } void displayL(int i) { /* display the result in lower case. */ printf("we got: %d\n", i); } int main() { count(1, 50000, &displayU); count(10, 5, &displayL); printf("all done.\n"); return 0; }
C
#include <sys/types.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #define BSIZE 1024 // buffer size #define FPERM 0644 // file permission int main(int argc, char *argv[]){ int fd1, fd2, n; char buf[BSIZE]; if(argc < 3){ fprintf(stderr, "Usage: %s src dest\n", argv[0]); exit(1); } if((fd1 = open(argv[1], O_RDONLY)) < 0){ perror("file open error"); exit(1); } if((fd2 = creat(argv[2], FPERM)) < 0){ perror("file creation error"); exit(1); } while((n=read(fd1, buf, BSIZE)) > 0){ write(fd2, buf, n); } close(fd1); close(fd2); }
C
#include <stdio.h> #include <stdlib.h> #define tam 5 main(){ int m,m2,n, a[tam],i,b, suma,me,c[tam],e[tam]; do{ system("cls"); printf("1 Capturar\n"); printf("2 Mostrar\n"); printf("3 Buscar\n"); printf("4 Promedio\n"); printf("5 Minimo\n"); printf("6 Invertir\n"); printf("7 Suma un vector\n"); printf("8 Salir\n"); scanf("%d",&m); switch(m){ case 1: printf("Por favor ingrese su valor\n"); for(i=0;i<tam;i++){ printf("Valor en la posicion: %d\n", i); scanf("%d",&a[i]); } break; case 2: printf("Sus Valores de su arreglo son\n"); for(i=0;i<5;i++){ printf("Valor para la posicion %d es %d\n",i,a[i]); } system("pause"); break; case 3: do{ printf("1. Posicion\n"); printf("2. Valor\n"); printf("3. Regresar\n"); scanf("%d",&m2); switch(m2){ case 1: printf("Busqueda Por Posicion\n"); printf("Ingrese su Posicion\n"); scanf("%d",&n); for(i=0;i<tam;i++){ if(i == n){ printf("En la posicion %d fue encontrado en el valor %d\n",i,a[i]); } } system("pause"); break; case 2: b=0; printf("Busqueda Por Valor\n"); printf("Ingrese su Valor\n"); scanf("%d",&n); for(i=0;i<tam;i++){ if(a[i] == n){ b++; printf("El Valor %d fue encontrado en la posicion %d\n",a[i],i); } } if(b==1) printf("El valor %d fue encontrado %d vez\n",n,b); if(b>1) printf("El valor %d fue encontrado %d veces\n",n,b); if(b==0) printf("El valor %d No fue encontrado\n",n); printf("\n"); system("pause"); break; case 3: break; default: printf("Incorrecto\n"); } }while(m2 != 3); break; case 4: suma=0; printf("Promedio\n"); for(i=0;i<tam;i++){ suma=a[i]+suma; } suma=suma/tam; printf("Tu promedio es %d\n", suma); system("pause"); break; case 5: me=0; printf("Numero Minimo\n"); for(i=0;i<tam;i++){ if(i==0) me=a[i]; if(a[i] < me) me=a[i]; } printf("Tu numero menor es %d\n",me); system("pause"); break; case 6: printf("Invertir\n"); for(i=tam-1;i>=0;i--){ printf("Poscicion %d Valor es %d\n",i,a[i]); } system("pause"); break; case 7: printf("Suma Un Vector\n"); printf("ingrese sus Valores del nuevo vector\n"); for(i=0;i<tam;i++){ printf("Ingrese el valor en posicion %d",i); scanf("%d",&c[i]); } for(i=0;i<tam;i++){ e[i]=a[i]+c[i]; } for(i=0;i<tam;i++){ printf("%d + %d = %d\n", a[i],c[i],e[i]); } system("pause"); break; case 8: break; default: printf("Incorrecto\n"); } }while(m != 8); }
C
/* Bryan Wood lib.h input, output, word, x, wordlength, linelength */ #include <iostream.h> #include <fstream.h> #include <iomanip.h> #include <stdlib.h> #include <ctype.h> #include <string.h> /*------------------------------------------------------- opens files to be used as input and output Receives: input, output Returns: nothing ---------------------------------------------------------*/ void openfiles (ifstream input, ofstream output); /*------------------------------------------------------- closes files used as input and output Receives: input, output Returns: nothing ---------------------------------------------------------*/ void closefiles (ifstream input, ofstream output); /*------------------------------------------------------- Translates the input file to pig latin using two other functions and then outputs the translated verion into the output file Receives: input, output Returns: nothing ---------------------------------------------------------*/ void manipstr (ifstream input, ofstream output); /*------------------------------------------------------- Translates the input file to pig latin Receives: input, output, word, x, wordlength Returns: word, x, wordlength ---------------------------------------------------------*/ void piglatin (ifstream input, ofstream output, char word[], int &x, int &wordlength); /*------------------------------------------------------- Outputs the translated version to the output file and controls the format of the output. Receives: output, word, wordlength, linelength Returns: word, wordlength, linelength ---------------------------------------------------------*/ void manipout (ofstream output, char word[], int &wordlength, int &linelength);
C
#include <math.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* Get input as string to prevent overstep the boundary */ int GetInputAsString(char *lpszInput, unsigned int uSize) { int iResult; char szFormat[5] = "%"; char szSize[3]; itoa(uSize - 1, szSize, 10); strcat(szFormat, szSize); strcat(szFormat, "s"); /* Get the format string "%ns", n indicates the number of characters to read */ iResult = scanf(szFormat, lpszInput); fflush(stdin); return iResult; } /* Check the input is a valid integer or floating number */ bool CheckNumValid(char *lpszInputstring, bool bIsInt) { unsigned int uLength = strlen(lpszInputstring); unsigned int i; bool bDotExist = false; if (bIsInt) { /* for integer */ for (i = 0; i < uLength; i++) { if (lpszInputstring[i] < '0' || lpszInputstring[i] > '9') return false; } } else { /* for floating number */ for (i = 0; i < uLength; i++) { if (lpszInputstring[i] < '0' || lpszInputstring[i] > '9') { if (!bDotExist && lpszInputstring[i] == '.') /* decimal point can only appear once */ bDotExist = true; else return false; } } } return true; } /* Read the loan method */ char GetLoanMethod() { char szLoanMethod[3]; printf("请选择您的贷款方式\n\t1、商业贷款\n\t2、公积金贷款\n\t3、组合贷款\n请输入对应序号(1-3):"); GetInputAsString(szLoanMethod, sizeof szLoanMethod); /* Make sure that the input is 1, 2 or 3 */ while (1) { if (strlen(szLoanMethod) == 1) { if (szLoanMethod[0] >= '1' && szLoanMethod[0] <= '3') break; } printf("请输入有效对应序号(1-3):"); GetInputAsString(szLoanMethod, sizeof szLoanMethod); fflush(stdin); } if (szLoanMethod[0] == '1') printf("您选择的贷款方式为商业贷款\n>>>>>>>>>>>>>>>\n"); else if (szLoanMethod[0] == '2') printf("您选择的贷款方式为公积金贷款\n>>>>>>>>>>>>>>>\n"); else printf("您选择的贷款方式为组合贷款\n>>>>>>>>>>>>>>>\n"); return szLoanMethod[0]; } /* Get total loan according to loan method */ double *GetTotalLoan(char loanMethod) { char szTotalLoan[16]; static double fTotalLoan[2]; if (loanMethod == '1' || loanMethod == '2') { printf("请输入您的贷款总额(万):"); GetInputAsString(szTotalLoan, sizeof szTotalLoan); /* Make sure that the input is a number above 0 */ while (1) { if (CheckNumValid(szTotalLoan, false)) { fTotalLoan[0] = atof(szTotalLoan); if (fTotalLoan[0] > 0) break; } printf("请输入有效贷款总额(万):"); GetInputAsString(szTotalLoan, sizeof szTotalLoan); } printf("您的总贷款金额为%f万元\n>>>>>>>>>>>>>>>\n", fTotalLoan[0]); fTotalLoan[0] = fTotalLoan[0] * 10000; fTotalLoan[1] = 0; } else { printf("请输入您的商业贷款总额(万):"); GetInputAsString(szTotalLoan, sizeof szTotalLoan); while (1) { if (CheckNumValid(szTotalLoan, sizeof szTotalLoan)) { fTotalLoan[0] = atof(szTotalLoan); if (fTotalLoan[0] > 0) break; } printf("请输入有效商业贷款总额(万):"); GetInputAsString(szTotalLoan, sizeof szTotalLoan); } printf("请输入您的公积金贷款总额(万):"); GetInputAsString(szTotalLoan, sizeof szTotalLoan); while (1) { if (CheckNumValid(szTotalLoan, sizeof szTotalLoan)) { fTotalLoan[1] = atof(szTotalLoan); if (fTotalLoan[1] > 0) break; } printf("请输入有效公积金贷款总额(万):"); GetInputAsString(szTotalLoan, sizeof szTotalLoan); } printf("您的商业贷款金额为%f万元\n您的公积金贷款金额为%f万元\n总贷款金额为%f万元\n>>>>>>>>>>>>>>>\n", fTotalLoan[0], fTotalLoan[1], (fTotalLoan[0] + fTotalLoan[1])); fTotalLoan[0] = fTotalLoan[0] * 10000; /* bank total loan */ fTotalLoan[1] = fTotalLoan[1] * 10000; /* provident total loan */ } return fTotalLoan; } /* Read payment method */ char GetPaymentMethod() { char szPaymentMethod[3]; printf("请选择您的还款方式\n\t1、等额本息(每月等额还款)\n\t2、等额本金(每月递减还款)\n请输入对应序号(1-2):"); GetInputAsString(szPaymentMethod, sizeof szPaymentMethod); /* Make sure that the input is 1 or 2 */ while (1) { if (strlen(szPaymentMethod) == 1) if (szPaymentMethod[0] == '1' || szPaymentMethod[0] == '2') break; printf("请输入有效对应序号(1-2):"); GetInputAsString(szPaymentMethod, sizeof szPaymentMethod); } if (szPaymentMethod[0] == '1') printf("您选择的还款方式为等额本息\n>>>>>>>>>>>>>>>\n"); else printf("您选择的还款方式为等额本金\n>>>>>>>>>>>>>>>\n"); return szPaymentMethod[0]; } /* Get payment months */ unsigned int GetPaymentMonths() { char szPaymentYears[4]; unsigned int uPaymentYears; printf("请输入还款年数(1-30):"); GetInputAsString(szPaymentYears, sizeof szPaymentYears); /* Make sure that the input is a integer and between 1 and 30 */ while (1) { if (CheckNumValid(szPaymentYears, true)) { uPaymentYears = (unsigned int)atoi(szPaymentYears); if (uPaymentYears >= 1 && uPaymentYears <= 30) break; } printf("请输入有效还款年数(1-30):"); GetInputAsString(szPaymentYears, sizeof szPaymentYears); } printf("您的还款年数为%u年,共%u个月\n>>>>>>>>>>>>>>>\n", uPaymentYears, uPaymentYears * 12); return uPaymentYears * 12; } /* Read loan interest rate according to the loan method */ float *GetLoanInterestRate(char cLoanMethod) { char szLoanInterestRate[8]; static float fLoanInterestRate[2]; if (cLoanMethod == '1') { printf("请输入贷款利率,截止2019年末,银行贷款利率如下\n\t7折(3.43%%)\n\t8折(3.92%%)\n\t8.3折(4.067%%)\n\t8.5折(4.165%%)\n\t8.8折(4.312%%)\n\t9折(4.41%%)\n\t9.5折(4.655%%)\n\t基准利率(4.9%%)\n\t1.05倍(5.145%%)\n\t1.1倍(5.39%%)\n\t1.15倍(5.635%%)\n\t1.2倍(5.88%%)\n\t1.25倍(6.125%%)\n\t1.3倍(6.37%%)\n\t1.35倍(6.615%%)\n\t1.4倍(6.86%%)\n请输入具体数值(%%):"); GetInputAsString(szLoanInterestRate, sizeof szLoanInterestRate); /* make sure that the input is a number above 0 below 100 */ while (1) { if (CheckNumValid(szLoanInterestRate, false)) { fLoanInterestRate[0] = atof(szLoanInterestRate); if (fLoanInterestRate[0] > 0 && fLoanInterestRate[0] < 100) break; } printf("请输入有效贷款利率:"); GetInputAsString(szLoanInterestRate, sizeof szLoanInterestRate); } printf("您的贷款利率为%.3f%%\n>>>>>>>>>>>>>>>\n", fLoanInterestRate[0]); fLoanInterestRate[0] /= 100; fLoanInterestRate[1] = 0; } else if (cLoanMethod == '2') { printf("请输入公积金贷款利率,截止2019年末,公积金贷款利率如下\n\t基准利率(3.25%%)\n\t1.1倍(3.575%%)\n\t1.2倍(3.9%%)\n请输入具体数值(%%):"); GetInputAsString(szLoanInterestRate, sizeof szLoanInterestRate); while (1) { if (CheckNumValid(szLoanInterestRate, false)) { fLoanInterestRate[0] = atof(szLoanInterestRate); if (fLoanInterestRate[0] > 0 && fLoanInterestRate[0] < 100) break; } printf("请输入有效公积金贷款利率:"); GetInputAsString(szLoanInterestRate, sizeof szLoanInterestRate); } printf("您的公积金贷款利率为%.3f%%\n>>>>>>>>>>>>>>>\n", fLoanInterestRate[0]); fLoanInterestRate[0] /= 100; fLoanInterestRate[1] = 0; } else if (cLoanMethod == '3') { printf("请输入贷款利率,截止2019年末,银行贷款利率如下\n\t7折(3.43%%)\n\t8折(3.92%%)\n\t8.3折(4.067%%)\n\t8.5折(4.165%%)\n\t8.8折(4.312%%)\n\t9折(4.41%%)\n\t9.5折(4.655%%)\n\t基准利率(4.9%%)\n\t1.05倍(5.145%%)\n\t1.1倍(5.39%%)\n\t1.15倍(5.635%%)\n\t1.2倍(5.88%%)\n\t1.25倍(6.125%%)\n\t1.3倍(6.37%%)\n\t1.35倍(6.615%%)\n\t1.4倍(6.86%%)\n请输入具体数值(%%):"); GetInputAsString(szLoanInterestRate, sizeof szLoanInterestRate); while (1) { if (CheckNumValid(szLoanInterestRate, false)) { fLoanInterestRate[0] = atof(szLoanInterestRate); if (fLoanInterestRate[0] > 0 && fLoanInterestRate[0] < 100) break; } printf("请输入有效银行贷款利率:"); GetInputAsString(szLoanInterestRate, sizeof szLoanInterestRate); } printf("请输入公积金贷款利率,截止2019年末,公积金贷款利率如下\n\t基准利率(3.25%%)\n\t1.1倍(3.575%%)\n\t1.2倍(3.9%%)\n请输入具体数值(%%):"); GetInputAsString(szLoanInterestRate, sizeof szLoanInterestRate); while (1) { if (CheckNumValid(szLoanInterestRate, false)) { fLoanInterestRate[1] = atof(szLoanInterestRate); if (fLoanInterestRate[1] > 0 && fLoanInterestRate[1] < 100) break; } printf("请输入有效公积金贷款利率:"); GetInputAsString(szLoanInterestRate, sizeof szLoanInterestRate); } printf("您的银行贷款利率为%.3f%%,公积金贷款利率为%.3f%%\n>>>>>>>>>>>>>>>\n",fLoanInterestRate[0], fLoanInterestRate[1]); fLoanInterestRate[0] /= 100; /* bank loan interest rate */ fLoanInterestRate[1] /= 100; /* provident fund loan interest rate */ } return fLoanInterestRate; } /* Get payment every month by the way of average captial plus interest */ float AverageCaptialPlusInterest(double fTotalLoan, unsigned int uMonths, float fInterestRate) { float fMonthRate = fInterestRate / 12; return fTotalLoan * fMonthRate * pow(1 + fMonthRate, uMonths) / (pow(1 + fMonthRate, uMonths) - 1); } /* Get payment of uMonth month by the way of average captial */ float AverageCaptial(double fTotalLoan, unsigned int uMonths, float fInterestRate, unsigned int uMonth) { float fMonthRate = fInterestRate / 12; return fTotalLoan / uMonths * (1 + (uMonths - uMonth) * fMonthRate); } int main(int argc, char *argv[]) { char cLoanMethod, cPaymentMethod; float *lpfLoanInterestRate; double *lpfTotalLoan; unsigned int uPaymentMonths, m; float fMonthPayment[2] = {0, 0}; double fTotalPayment = 0, fTotalInterest; cLoanMethod = GetLoanMethod(); lpfTotalLoan = GetTotalLoan(cLoanMethod); cPaymentMethod = GetPaymentMethod(); uPaymentMonths = GetPaymentMonths(); lpfLoanInterestRate = GetLoanInterestRate(cLoanMethod); if (cPaymentMethod == '1') { /* for average capital plus interest method */ if (cLoanMethod == '1' || cLoanMethod == '2') { /* for commercial or provident fund loan method */ fMonthPayment[0] = AverageCaptialPlusInterest(lpfTotalLoan[0], uPaymentMonths, lpfLoanInterestRate[0]); fTotalPayment = fMonthPayment[0] * uPaymentMonths; fTotalInterest = fTotalPayment - lpfTotalLoan[0]; printf("每月需还款%.2f元\n\t还款总额%.6f万\n\t支付利息%.6f万\n\t贷款总额%.6f万\n", fMonthPayment[0], fTotalPayment / 10000, fTotalInterest / 10000, lpfTotalLoan[0] / 10000); } else { /* for syndicated loan method */ fMonthPayment[0] = AverageCaptialPlusInterest(lpfTotalLoan[0], uPaymentMonths, lpfLoanInterestRate[0]); /* bank payment every month */ fMonthPayment[1] = AverageCaptialPlusInterest(lpfTotalLoan[1], uPaymentMonths, lpfLoanInterestRate[1]); /* provident fund payment every month */ fTotalPayment = (fMonthPayment[0] + fMonthPayment[1]) * uPaymentMonths; fTotalInterest = fTotalPayment - (lpfTotalLoan[0] + lpfTotalLoan[1]); printf("每月需还款%.2f元\n\t还款总额%.6f万\n\t支付利息%.6f万\n\t贷款总额%.6f万\n", (fMonthPayment[0] + fMonthPayment[1]), fTotalPayment / 10000, fTotalInterest / 10000, (lpfTotalLoan[0] + lpfTotalLoan[1]) / 10000); } } else { /* for average capital method */ if (cLoanMethod == '1' || cLoanMethod == '2') { /* for commercial or provident fund loan method */ for (m = 0; m < uPaymentMonths; m++) { fTotalPayment += AverageCaptial(lpfTotalLoan[0], uPaymentMonths, lpfLoanInterestRate[0], m); } fTotalInterest = fTotalPayment - lpfTotalLoan[0]; printf("还款总额%.6f万\n支付利息%.6f万\n贷款总额%.6f万\n", fTotalPayment / 10000, fTotalInterest / 10000, lpfTotalLoan[0] / 10000); } else { /* for syndicated loan method */ for (m = 0; m < uPaymentMonths; m++) { fTotalPayment += (AverageCaptial(lpfTotalLoan[0], uPaymentMonths, lpfLoanInterestRate[0], m) + AverageCaptial(lpfTotalLoan[1], uPaymentMonths, lpfLoanInterestRate[1], m)); } fTotalInterest = fTotalPayment - (lpfTotalLoan[0] + lpfTotalLoan[1]); printf("还款总额%.6f万\n支付利息%.6f万\n贷款总额%.6f万\n", fTotalPayment / 10000, fTotalInterest / 10000, (lpfTotalLoan[0] + lpfTotalLoan[1]) / 10000); } } system("pause"); return 0; }
C
//Allen Zou 9/18/2020 #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include "driver/uart.h" #include "esp_vfs_dev.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "driver/gpio.h" #include "sdkconfig.h" #define BLINK_GPIO CONFIG_BLINK_GPIO /* Can use project configuration menu (idf.py menuconfig) to choose the GPIO to blink, or you can edit the following line and set a number here. */ #define LEDPIN0 12 #define LEDPIN1 27 #define LEDPIN2 33 #define LEDPIN3 15 void app_main(void) { /* Configure the IOMUX register for pad LEDPIN0 (some pads are muxed to GPIO on reset already, but some default to other functions and need to be switched to GPIO. Consult the Technical Reference for a list of pads and their default functions.) */ gpio_set_direction(LEDPIN0, GPIO_MODE_OUTPUT); gpio_set_direction(LEDPIN1, GPIO_MODE_OUTPUT); gpio_set_direction(LEDPIN2, GPIO_MODE_OUTPUT); gpio_set_direction(LEDPIN3, GPIO_MODE_OUTPUT); gpio_pad_select_gpio(LEDPIN0); gpio_pad_select_gpio(LEDPIN1); gpio_pad_select_gpio(LEDPIN2); gpio_pad_select_gpio(LEDPIN3); int counter = 0; int temp; while (1) { temp = counter; if (temp / 8 == 1) { gpio_set_level(LEDPIN0, 1); temp = temp - 8; } else { gpio_set_level(LEDPIN0, 0); } if (temp / 4 == 1) { gpio_set_level(LEDPIN1, 1); temp = temp - 4; } else { gpio_set_level(LEDPIN1, 0); } if (temp / 2 == 1) { gpio_set_level(LEDPIN2, 1); temp = temp - 2; } else { gpio_set_level(LEDPIN2, 0); } if (temp / 1 == 1) { gpio_set_level(LEDPIN3, 1); temp = temp - 1; } else { gpio_set_level(LEDPIN3, 0); } counter++; if (counter == 16) { counter = 0; } vTaskDelay(1000 / portTICK_PERIOD_MS); } }
C
/* * Vorlesung "Rechnerstrukturen", Blatt 4, Aufgabe 14. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include "boolean.h" #include "stdint.h" #include "colored_output.h" #include "ipaddress.h" /** * Wandle eine IPv4 Addresse in eine ganzzahlige usigned 32-bit Darstellung um. * * @param address * IPv4 Adresse * @return * uint32_t-Darstellung der Adresse. */ uint32_t convertAddress(ipv4 address) { uint32_t converted = 0; converted += address.a << 24; converted += address.b << 16; converted += address.c << 8; converted += address.d; return converted; } /** * Wandle eine als ganzzahlige usigned 32-bit Darstellung dargestellte IPv4 Addresse in Octalschreibweise um. * * @param converted * IPv4 Adresse im uint32_t Format * @return * Octaldarstellung der Adresse als ipv4-Struct. */ ipv4 covertFromAddress(uint32_t converted){ ipv4 address; address.a = converted >> 24; address.b = converted >> 16; address.c = converted >> 8; address.d = converted; return address; } /** * Erzeugt zu einem gegebenen Präfix eine passende IPv4-Subnetzmaske als uint32_t. * * @param prefix * Anzahl der Host-Bits in der IP-Adresse. Muss im Bereich 0<=x<=32 sein. * @return * Octaldarstellung der zugehoerigen Subnetz-Adresse im uint32_t Format */ uint32_t getSubnetmaskFromPrefix(int prefix){ uint32_t octalPrefix = 0; for ( int i = 0; i < prefix; ++i ) { octalPrefix += 1 << 31 - i; } return octalPrefix; } /** * Erzeugt zu einer IPv4-Adresse und einem gegebenen Präfix * die zugehörige IPv4-Network-Adresse als uint32_t. * @param address * IP-Adresse innerhalb des Subnetzes zu der die Netzwerk-Adresse * bestimmt werden soll. Vom Typ uint32_t. * * @param prefix * Anzahl der Host-Bits in der IP-Adresse. Muss im Bereich 0<=x<=32 sein. * @return * Octaldarstellung der zugehoerigen Network-Adresse im uint32_t Format */ uint32_t getNetwork(uint32_t address, int prefix){ return address & getSubnetmaskFromPrefix( prefix ); } /** * Erzeugt zu einer IPv4-Adresse und einem gegebenen Präfix * die zugehörige IPv4-Broadcast-Adresse als uint32_t. * @param address * IP-Adresse innerhalb des Subnetzes zu der die Broadcast-Adresse * bestimmt werden soll. Vom Typ uint32_t. * * @param prefix * Anzahl der Host-Bits in der IP-Adresse. Muss im Bereich 0<=x<=32 sein. * @return * Octaldarstellung der zugehoerigen Broadcast-Adresse im uint32_t Format */ uint32_t getBroadcast(uint32_t address, int prefix){ return address | ~getSubnetmaskFromPrefix( prefix ); } /** * Liefert zu einem gegebenen Präfix die maximale Anzahl an eindeutig adressibaren * Host innerhalb eines IPv4-Subnetzmaske zu gebenen Präfix. * * @param prefix * Anzahl der Host-Bits in der IP-Adresse. Muss im Bereich 0<=x<=32 sein. * @return * maximale Anzahl an eindeutig adressierbaren Host innerhalb des Subnetzes */ uint32_t getNumberOfHost(int prefix) { if ( prefix == 0 ) return 4294967294; if ( prefix == 31 ) return 2; if ( prefix == 32 ) return 1; uint32_t numberOfHosts = (1 << (32 - prefix)) - 2; return numberOfHosts; } /** * Erzeugt zu einer IPv4-Adresse und einem gegebenen Präfix * die erste gültige IPv4-Host-Adresse als uint32_t. * @param address * IP-Adresse innerhalb des Subnetzes zu der die erste Host-Adresse * bestimmt werden soll. Vom Typ uint32_t. * * @param prefix * Anzahl der Host-Bits in der IP-Adresse. Muss im Bereich 0<=x<=32 sein. * @return * erste gueltige Hostadresse im zugehoerigen Subnetz im uint32_t Format */ uint32_t getFirst(uint32_t address, int prefix){ if ( prefix >= 31 ) return address; return getNetwork( address, prefix ) + 1; } /** * Erzeugt zu einer IPv4-Adresse und einem gegebenen Präfix * die letzte gültige IPv4-Host-Adresse als uint32_t. * @param address * IP-Adresse innerhalb des Subnetzes zu der die letzte Host-Adresse * bestimmt werden soll. Vom Typ uint32_t. * * @param prefix * Anzahl der Host-Bits in der IP-Adresse. Muss im Bereich 0<=x<=32 sein. * @return * letzte gueltige Hostadresse im zugehoerigen Subnetz im uint32_t Format */ uint32_t getLast(uint32_t address, int prefix){ if ( prefix >= 31 ) return getBroadcast( address, prefix ); return getBroadcast( address, prefix ) - 1; } /** * Berechnet ob sich zwei Subnetze überlappen. Die Subnetze werden aus den * übergebenen IPv4-Adressen mittels jeweiligen Präfixe bestimmt. * @param ip1 * IP-Adresse innerhalb des ersten Subnetzes * @param prefix1 * Anzahl der Host-Bits in der ersten IP-Adresse. Muss im Bereich 0<=x<=32 sein. * @param ip2 * IP-Adresse innerhalb des zweiten Subnetzes * @param prefix1 * Anzahl der Host-Bits in der zweiten IP-Adresse. Muss im Bereich 0<=x<=32 sein. * @return * TRUE, falls die Subnetze sich überlappen oder sogar enthalten, FALSE sonst. */ int doIntersect(uint32_t ip1, int prefix1, uint32_t ip2, int prefix2) { if ( getBroadcast( ip1, prefix1 ) >= getNetwork( ip2, prefix2 ) && getNetwork( ip1, prefix1 ) <= getBroadcast( ip2, prefix2 ) ) return 1; if ( getBroadcast( ip2, prefix2 ) >= getNetwork( ip1, prefix1 ) && getNetwork( ip2, prefix2 ) <= getBroadcast( ip1, prefix1 ) ) return 1; return 0; } #include "tests_network.h" int main(int argc, char **argv) { return run_tests(); }
C
#include<stdio.h> void sortPancakes(int [], int); void listReverse(int [], int, int); int main(){ int a[10], i, k, n; printf("How many Pancakes: "); scanf("%d",&n); printf("Enter the size of the Pancakes: "); for(i = 0; i < n; i++){ scanf("%d",&a[i]); } sortPancakes(a, n); printf("After sorting the Pancakes: "); for(i = 0; i < n; i++){ printf("%d ",a[i]); } return 0; } void sortPancakes(int a[], int n){ int i, k, l = 0, r=n-1, max; while(r > 0){ k = 0; for(i = 0; i <= r; i++){ if(a[k] < a[i]){ k = i; } } if(k == r){ r--; continue; } listReverse(a, l, k); listReverse(a, l, r); r--; } } void listReverse(int b[], int l, int r){ int temp; while (l < r) { temp = b[l]; b[l] = b[r]; b[r] = temp; l++; r--; } }
C
#include "headers.h" long long get_time(void) { struct timeval now_time; long long milisec; gettimeofday(&now_time, NULL); milisec = (now_time.tv_sec * 1000) + (now_time.tv_usec / 1000); return (milisec); } int ft_strcmp(char *s1, char *s2) { int i; i = 0; while (s1[i] == s2[i] && s1[i] != 0 && s2[i] != 0) i++; return (s1[i] - s2[i]); } int args_init(t_args *args, char **argv, int argc) { args->phil_count = ft_atoi(argv[1]); args->die_time = ft_atoi(argv[2]); args->eat_time = ft_atoi(argv[3]); args->sleep_time = ft_atoi(argv[4]); args->cycles = 0; if (argc == 6) { args->cycles = ft_atoi(argv[5]); if (args->cycles <= 0) return (0); } if (args->phil_count < 2 || args->phil_count > 200 || args->die_time < 60 || args->eat_time < 60 || args->sleep_time < 60) return (0); pthread_mutex_init(&args->display_block, NULL); return (1); } void display(char *msg, t_phil *phil) { char *str; pthread_mutex_lock(&phil->args->display_block); str = ft_itoa(get_time() - phil->args->start_time); str = ft_strjoin(str, phil->index); str = ft_strjoin(str, msg); write(1, str, ft_strlen(str)); if (!ft_strcmp(msg, " died\n")) return ; pthread_mutex_unlock(&phil->args->display_block); } void display_end(t_phil *phil) { pthread_mutex_lock(&phil->args->display_block); printf(BOLDGREEN"End of cycles"BOLDMAGENTA" [%d:%d]\n"RESET"", phil->args->cycles, phil->args->cycles * phil->args->phil_count); }