language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <math.h> int testaForte(int n); int calculaForte(int i); int fatorial(int i); int soma = 0; int main(){ int i; scanf("%d", &i); calculaForte(i); if(testaForte(i)){ printf("SIM"); }else{ printf("NAO"); } return 0; } int calculaForte(int i){ int j; int contaDigitos =0; int valorI=i; if (i == 0){ contaDigitos = 1; }else{ while (valorI != 0) { contaDigitos++; valorI = valorI / 10; } } int digitos[contaDigitos],mod=pow(10,contaDigitos),dividir=pow(10,contaDigitos-1); for(j=0;j<contaDigitos; j++, mod/=10, dividir/=10){ digitos[j]=(i%mod)/dividir; } for(j=0;j<contaDigitos; j++, mod/=10, dividir/=10){ soma += fatorial(digitos[j]); } } int fatorial(int i){ int resultado; if(i==0){ resultado=1; }else{ resultado=i*fatorial(i-1); } return resultado; } int testaForte(int n){ if(n == soma){ return 1; }else{ return 0; } }
C
#include <stdio.h> #include <Windows.h> int main(){ int num1, num2; double dnum=3.12; num1=1; num2=2; printf("%d %d %f\n", num1, num2, dnum); printf("%%\n"); printf("\"\n"); //PC̃{[グĂs printf("\a\a\a\n"); printf("abcde"); Sleep(1000); printf("\b"); Sleep(500); printf("\b"); Sleep(500); printf("\b"); Sleep(500); printf("0"); Sleep(500); printf("0"); Sleep(500); printf("0"); Sleep(500); printf("0"); Sleep(500); return 0; }
C
/** * This module serves to tile and compute the feed forward * results for a convolutional neural network. * * The eventual goal of this is to offload the low level * computations to the FPGA. * * Once we can do this reliably, we want to expose a higher * level API such that the performance gains of the feed- * forward being done in the FPGA can be evaluated. */ #ifndef FEED_FORWARD_TRANSLATION_H_INCLUDED #define FEED_FORWARD_TRANSLATION_H_INCLUDED #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include "layer.h" #include "hardware_emulator.h" #include "utilities.h" #define FF_LAYER_TYPE_CHECK 0x01 #define FF_FC_LAYER 0x00 #define FF_CONV_LAYER 0x01 typedef struct conv_indices { uint32_t ozt; uint32_t oyt; uint32_t oxt; uint32_t t_ofm_z; uint32_t t_ofm_y; uint32_t t_ofm_x; } conv_indices; /** * This function is the interface with the outside world. * * It takes in a set of parameters defining the layer we * are operating on and it dispatches this to the relevant * processing elements. */ void feed_forward(struct LayerParameters * params); /** * This function feeds forward if we have a fully connected layer. */ void feed_forward_fc(struct LayerFC * layer_spec); /** * This function handles feed forward for convolutional layers. */ void feed_forward_conv(struct LayerConv * layer_spec); /** * Move range of kernels into weight buffer. */ void write_kernels_to_buffer(uint32_t start, uint32_t end, struct LayerConv * layer_spec); /** * Move range of input feature maps into input buffer. */ void write_ifm_to_buffer(uint32_t oxt, uint32_t oyt, uint32_t t_ofm_y, uint32_t t_ofm_x, struct LayerConv * layer_spec); /** * Move biases to the output buffer for conv layers. */ void write_conv_bias_to_buffer(struct LayerConv *layer_spec, struct conv_indices *indices); /** * Allow the hardware parameters to be set externally. */ void set_hardware_model(uint32_t input_buffer_size, uint32_t weight_buffer_size, uint32_t output_buffer_size, uint32_t mo, uint32_t mi); /** * Initialize the buffers as arrays. */ void initialize_hardware_model(); /** * Free the memory required for the array pointers. */ void teardown_hardware_model(); #endif // FEED_FORWARD_TRANSLATION_H_INCLUDED
C
#include<iostream> using namespace std; int sum(int a, int b) { int s = a+b; return s; } int main() { int x, y; cin>>x>>y; int sum = sum(x, y); cout<<sum; }
C
#include "MO445.h" #include <stdio.h> #include <dirent.h> #include <string.h> struct S_image{ char name[1024]; Image *img; }; struct S_features{ char name_query[1024]; double *distances; char **result_names; }; int partition (struct S_features arr, int low, int high) { double pivot = arr.distances[high]; int i = (low - 1); for (int j = low; j <= high- 1; j++) { if (arr.distances[j] <= pivot) { i++; double temp = arr.distances[i]; arr.distances[i] = arr.distances[j]; arr.distances[j] = temp; char name[1024]; strcpy(name,arr.result_names[i]); strcpy(arr.result_names[i],arr.result_names[j]); strcpy(arr.result_names[j],name); } } double temp = arr.distances[i+1]; arr.distances[i+1] = arr.distances[high]; arr.distances[high] = temp; char name[1024]; strcpy(name,arr.result_names[i+1]); strcpy(arr.result_names[i+1],arr.result_names[high]); strcpy(arr.result_names[high],name); return (i + 1); } void quickSort(struct S_features arr, int low, int high) { if (low < high) { int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } int main(int argc,char **argv){ int size, i = 0, j, fixedlen = 1400; /* Estrutura para ler todas as imagens do diretorio imgs/ */ char dir_name[1024] = "../mpeg7_new/"; // char dir_name[1024] = "/home/vinicius/Dropbox/Mestrado - IC-UNICAMP/1st Semester/Information Retrieval/assignment 07/MO445-descriptors/examples/imgs/"; DIR *d; struct dirent *dir; d = opendir(dir_name); /* Estrutura para salvar os resultados */ FILE * fp; fp = fopen ("results.csv","w"); /* Estrutura para salvar as imagens */ struct S_image *imgs; imgs = calloc(fixedlen,sizeof(struct S_image)); /* Estrutura para salvar os vetores de caractericas de Segment Saliences */ FeatureVector1D ** v_ss; v_ss = calloc(fixedlen,sizeof(FeatureVector1D)); /* Estrutura para salvar os vetores de caractericas de Multiscale Fractal Dimension */ FeatureVector1D ** v_mfd; v_mfd = calloc(fixedlen,sizeof(FeatureVector1D)); /* Estrutura para salvar os resultados das distancias */ struct S_features *sfeatures_ss; sfeatures_ss = calloc(fixedlen,sizeof(struct S_features)); struct S_features *sfeatures_mfd; sfeatures_mfd = calloc(fixedlen,sizeof(struct S_features)); printf("Lendo imagens...\n"); if (d){ while ((dir = readdir(d)) != NULL){ if(strcmp(dir->d_name,".") == 1 && strcmp(dir->d_name,"..") == 1){ char image_url[1024]; strcpy(image_url, dir_name); strcat(image_url, dir->d_name); strcpy(imgs[i].name, dir->d_name); imgs[i].img = ReadImage(image_url); i++; } } closedir(d); } size = i; printf("%d\n", size); printf("Extraindo caracteristicas...\n"); /* Extracao dos vetores de caracteristicas */ for(i = 0; i < size; i++){ v_ss[i] = SS_ExtractionAlgorithm(imgs[i].img); v_mfd[i] = MS_ExtractionAlgorithm(imgs[i].img); } printf("Calculando as distancias...\n"); for(i = 0; i < size; i++){ sfeatures_ss[i].result_names = malloc(sizeof(char *) * size); sfeatures_mfd[i].result_names = malloc(sizeof(char *) * size); sfeatures_ss[i].distances = calloc(size,sizeof(double)); sfeatures_mfd[i].distances = calloc(size,sizeof(double)); for(j = 0; j < size; j++){ double vss = SS_DistanceAlgorithm(v_ss[i],v_ss[j]); strcpy(sfeatures_ss[i].name_query,imgs[i].name); sfeatures_ss[i].distances[j] = vss; sfeatures_ss[i].result_names[j] = (char*) malloc(strlen(imgs[j].name) + 1); strcpy(sfeatures_ss[i].result_names[j],imgs[j].name); double vmdf = MS_DistanceAlgorithm(v_mfd[i],v_mfd[j]); strcpy(sfeatures_mfd[i].name_query,imgs[i].name); sfeatures_mfd[i].distances[j] = vmdf; sfeatures_mfd[i].result_names[j] = (char*) malloc(strlen(imgs[j].name) + 1); strcpy(sfeatures_mfd[i].result_names[j],imgs[j].name); } } printf("Ordenando os resultados...\n"); for(i = 0; i < size; i++){ quickSort(sfeatures_ss[i],0,size-1); quickSort(sfeatures_mfd[i],0,size-1); } printf("Salvando os resultados mais proximos\n"); printf("Segment Saliences\n"); for(i = 0; i < size; i++){ fprintf(fp,"1 %s", sfeatures_ss[i].name_query); for(j = 0; j < size; j++){ fprintf(fp," %s", sfeatures_ss[i].result_names[j]); } fprintf(fp,"\n"); } printf("Multiscale Fractal Dimension\n"); for(i = 0; i < size; i++){ fprintf(fp,"2 %s", sfeatures_mfd[i].name_query); for(j = 0; j < size; j++){ fprintf(fp," %s", sfeatures_mfd[i].result_names[j]); } fprintf(fp,"\n"); } fclose (fp); printf("Destruindo as imagens e vetores de caracteristicas...\n"); /* Liberando memoria */ for(i = 0; i < size; i++){ DestroyImage(&imgs[i].img); DestroyFeatureVector1D(&v_ss[i]); DestroyFeatureVector1D(&v_mfd[i]); } return 0; }
C
/* Functions that operate on Containers and their contents */ #ifndef CONTAINER_H #define CONTAINER_H #include "types.h" /* Create new node_containers from existing node_containers. Map: node_container -> node_container Inputs: Screen - for current Space offsetting Container - start with copy of current Container Outputs: node_container - split node_container based on the input Node */ node_container LeftVerticalContainerSplit(screen_info *Screen, const node_container &Container); node_container RightVerticalContainerSplit(screen_info *Screen, const node_container &Container); node_container UpperHorizontalContainerSplit(screen_info *Screen, const node_container &Container); node_container LowerHorizontalContainerSplit(screen_info *Screen, const node_container &Container); /* Determine whether to split Vertically or Horizontally based on Node->Container. Map: node_container -> split_mode Input: Container - get dimensions of container Output: split_mode - vertical split or horizontal split */ split_mode GetOptimalSplitMode(const node_container &Container); /* Mux ContainerType to select which node_container to create Map: node_container -> node_container Input: Screen - pass through to create container functions Parent - Node whose container to use as baseline ContainerType - Left/Right/Top/Bottom Output: node_container - new container dimensions for split. */ node_container CreateNodeContainer(screen_info *Screen, const node_container &ParentContainer, const container_type &ContainerType); /* Mux SplitMode to select which ContainerTypes to use for CreateNodeContainer Map: node_container -> node_container Input: Screen - pass through to create container functions Parent - Node whose children containers are being created. SplitMode - whether to split horizontally or vertically. Output: tree_node *Parent - mutate Left and Right children containers */ void CreateNodeContainerPair(screen_info *Screen, tree_node *Parent, const split_mode &SplitMode); /* Create Container for RootNode Map: Screen Pos -> node_container Input: Screen - for position info Output: node_container *Container */ void SetRootNodeContainer(screen_info *Screen, node_container *Container); /* SET -- KWMScreen.SplitRatio */ void ChangeSplitRatio(double Value); /* Mutate existing container based on Screen state */ void ResizeContainer(screen_info *Screen, node_container *Container); bool ModifyContainerSplitRatio(node_container *Container, const double &Offset); void ToggleContainerSplitMode(node_container *Container); #endif
C
/* SYNOPSIS Solution for exercise 63-05. REQUIREMENT Modify the program in Listing 63-9 (self_pipe.c) to use poll() instead of select(). SOLUTION Copy source file from "tlpi/altio/self_pipe.c" to "tlpi/altio/self_pipe_63-5.c" and add executable to "tlpi/altio/Makefile". Modify new source file to use poll() instead of select(). Add few message to terminal to inform information. Create loop to monitor in infinite. Monitor STDIN_FILENO and SIGUSR1 instead of SIGINT for terminable. USAGE TERMINAL 1 # start monitor program in background to see process identity $ ./tlpi/altio/self_pipe_63-5 & [1] 1254 # restore program into forground fg 1 # try input to stdin hello ... => stdin: hello # result from terminal 2 ... => signal: 10 - User defined signal 1 TERMINAL 2 # try send signal to monitor program # result will appeare in terminal 1 kill -s SIGUSR1 1254 AUTHORS Kevin Leptons <kevin.leptons@gmail.com> */ #include <stdlib.h> #include <stdio.h> int main(int argc, char *argv[]) { printf("Goto %s to see solution\n", __FILE__); return EXIT_SUCCESS; }
C
/* INVOKE.exe COMn (Transmit MSP430 BSL invoke pattern on DTR and RTS) This program was written in C for the LCC-Win32 compiler. */ #include <stdio.h> #include <conio.h> #include <mmsystem.h> /* Must also add winmm.lib to the Link. */ int comport = 0; int filearg = 0; int filelen = 0; unsigned int pulsetime = 10; /* Period in ms of first positive pulse on RTS */ /*======== Display proper usage of program if /?, -h or error. ===========*/ void Usage(char *programName) { printf("\n%s usage:\n \n",programName); printf("Transmit BSL invoke pattern on DTR(/Reset) and RTS(Test): %s COMn \n",programName); } /*======== Process command line arguments. ==========*/ void HandleOptions(int argc,char *argv[]) { int i; for (i=1; i< argc;i++) { if (argv[i][0] == '/' || argv[i][0] == '-') { continue; } else if (strnicmp(argv[i], "COM", 3) == 0) { comport = i; } else return; } return; } /*============MAIN==========*/ int main(int argc,char *argv[]) { /*handle the program options*/ HandleOptions(argc,argv); if (comport == 0) { Usage(argv[0]); return 0; } char CFcomport[20] = "\\\\.\\"; strcat (CFcomport,argv[comport]); /* Open COM port */ HANDLE hMasterCOM = CreateFile(CFcomport, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 0); if (hMasterCOM == INVALID_HANDLE_VALUE) { int err = GetLastError(); printf("Error opening port \n"); return err; } else { printf("COM port Opened \n"); } /* DTR and RTS are inverted at final output, so CLR means High and SET means Low */ EscapeCommFunction(hMasterCOM, CLRDTR); /* start with both lines high */ EscapeCommFunction(hMasterCOM, CLRRTS); /* MOSFET Off because GS = 0 */ timeBeginPeriod(1); /* Change system tick resolution from 15ms to 1ms */ Sleep(100); /* Capacitor charges */ EscapeCommFunction(hMasterCOM, SETDTR); /* Bring both lines low */ EscapeCommFunction(hMasterCOM, SETRTS); /* MOSFET On because capacitor still charged */ Sleep(pulsetime); /* Capacitor discharging, but still high enough */ EscapeCommFunction(hMasterCOM, CLRRTS); /* First pulse on RTS - RTS high */ Sleep(pulsetime); /* Capacitor recharging */ EscapeCommFunction(hMasterCOM, SETRTS); /* RTS back low */ Sleep(pulsetime); /* Capacitor now discharging, but still high enough */ EscapeCommFunction(hMasterCOM, CLRRTS); /* Second pulse on RTS - RTS high */ Sleep(pulsetime); /* Capacitor recharging */ EscapeCommFunction(hMasterCOM, CLRDTR); /* DTR back high in the middle of second pulse */ Sleep(pulsetime); /* MOSFET Off because GS = 0 */ EscapeCommFunction(hMasterCOM, SETRTS); /* RTS back low */ Sleep(150); /* Capacitor now fully discharges, and stays that way */ /* so DTR no longer connected to /Reset */ timeEndPeriod(1); /* Restore system tick */ printf("BSL invoke pattern transmitted \n"); CloseHandle(hMasterCOM); /* Close port - DTR = high. RTS = low */ hMasterCOM = INVALID_HANDLE_VALUE; }
C
/* Periodic Timer with interrupt*/ #include "TM4C123.h" // Device header #define BLUE (1U<<2) #define RED (1U<<1) //Prototypes void timer1_1Hz_init(void); void timer2_10Hz_init(void); int main(void){ SYSCTL->RCGCGPIO |= 0x20; //enable clock on GPIOF GPIOF->DIR |= BLUE | RED; //enable output GPIOF->DEN |= BLUE | RED; //digital enable timer1_1Hz_init(); // timer2_10Hz_init(); __enable_irq(); while(1){ } } void timer1_1Hz_init(void){ SYSCTL->RCGCTIMER |= (1U << 1); //enable clock on timer1 TIMER1->CTL &= ~(0x01); //disable timer TIMER1->CFG = 0x04; //configure timer for 16 bits TIMER1->TAMR |= 0x02; //TAMR bits: periodic timer mode TIMER1->TAPR = 250; // 16.000.000/250 = 64.000 TIMER1->TAILR = 64000; //Load Timer with number that's count for 1 sec. Clock @ 16MHz TIMER1->ICR |= 0x01; //clear raw interrupt TIMER1->IMR |= 0x01; //interrup mask register TIMER1->CTL |= 0x01; //enable timer NVIC->ISER[0] |= 0x00200000; //enable IRQ21 (D21) for ISER[0] } void timer2_10Hz_init(void){ SYSCTL->RCGCTIMER |= (1U << 2); //enable clock on timer2 TIMER2->CTL &= ~(0x01); //disable timer TIMER2->CFG = 0x00; //configure timer for 32 bits TIMER2->TAMR |= 0x02; //TAMR bits: periodic timer mode // TIMER2->TAPR = 250; // Prescaler only works on 16 bits mode TIMER2->TAILR = 160000000; //Load Timer with number that's count for 10 sec. Clock @ 16MHz TIMER2->ICR |= 0x01; //clear raw interrupt TIMER2->IMR |= 0x01; //interrup mask register TIMER2->CTL |= 0x01; //enable timer NVIC->ISER[0] |= 0x00800000; //enable IRQ23 (D23) for ISER[0] } void TIMER1A_Handler(void){ GPIOF->DATA ^= BLUE; TIMER1->ICR |= 0x01; } void TIMER2A_Handler(void){ GPIOF->DATA ^= RED; TIMER2->ICR |= 0x01; }
C
/* * * config.c * */ #include <unistd.h> #include <stdlib.h> #include "ex_alarm.h" #include "config.h" #include "utils.h" #include "log.h" #define CF_STR_EMAIL "email" #define CF_STR_EMAIL_SMTP "smtp_server" #define CF_STR_EMAIL_SMTP_PORT "smtp_port" #define CF_STR_EMAIL_FROM "from" #define CF_STR_EMAIL_NAME "name" #define CF_STR_EMAIL_PASSWORD "password" #define CF_STR_EMAIL_TO "to" #define CF_STR_EMAIL_CC "cc" #define CF_STR_EMAIL_USE_TLS_SSL "use_tls_ssl" static int parse_cf_email_config ( email_config_t * email_config, char * value, char * error_msg ); static int read_config_from_file ( char * config_file_path, email_config_t * email_config, char * error_msg ); static int check_email_addr_format ( char * email_addr, int email_addr_len ); /* * Function to read config from file * @config_file_path: path of config file * @ex_alarm_config:: pointer to alarm config * @alarm_items: pointer to alarm items * @error_msg: pointer to error message * RET 0 or 1 on success, otherwise return a negative number */ static int read_config_from_file ( char * config_file_path, email_config_t * email_config, char * error_msg ) { int ret = -1; char errmsg [ ALARM_ERRMSG_LEN ]; int str_len = 0; FILE * config_file; #define padding_len 8 /* line buffer */ char line_buffer [ MAX_CONFIG_FILE_LINE_LEN + padding_len ]; bzero ( email_config, sizeof ( email_config ) ); /* open file */ config_file = fopen ( config_file_path, "r" ); if ( config_file == NULL ) { strerror_r ( errno, errmsg, ALARM_ERRMSG_LEN ); if ( errno == ENOENT ) { cs_log ( LOG_ERROR, "open config file %s error: file not exsit, %s", \ config_file_path, errmsg ); sprintf ( error_msg, "open config file %s error: file not exsit, %s", \ config_file_path, errmsg ); return -2; /* file not exist */ } else { cs_log ( LOG_ERROR, "open config file %s error, errno is %d, %s", config_file_path, errno, errmsg ); sprintf ( error_msg, "open config file %s error, errno is %d, %s", config_file_path, errno, errmsg ); return -3; /* open file error */ } } /* read a line */ while ( fgets ( line_buffer, MAX_CONFIG_FILE_LINE_LEN, config_file ) ) { str_len = strlen ( line_buffer ); line_buffer [ str_len - 1 ] = 0; str_len --; if ( line_buffer [ str_len - 2 ] == '\r' ) { line_buffer [ str_len - 2 ] = 0; str_len --; } /* too long */ if ( str_len > MAX_CONFIG_FILE_LINE_LEN ) { cs_log ( LOG_WARN, "line too long, discard, %s", line_buffer ); sprintf ( error_msg, "line too long, discard, %s", line_buffer ); return -4; } char * line_buffer_trim_head = trim_head ( line_buffer, str_len ); /* start with # */ if ( * line_buffer_trim_head == '#' ) { continue; } if ( * line_buffer_trim_head == 0 ) { continue; } /* parse a config line */ ret = parse_alarm_config_line ( line_buffer_trim_head, email_config, error_msg ); if ( ret < 0 ) { return -5; } } /* close file */ fclose ( config_file ); return 0; } /* * Function to parse alarm config line * @config_line: config line * @ex_alarm_config:: pointer to alarm config * @alarm_items pointer to alarm items * @error_msg pointer to error message * RET 0 or 1 on success, otherwise return a negative number */ int parse_alarm_config_line ( char * config_line, email_config_t * email_config, char * error_msg ) { if ( config_line == NULL || email_config == NULL) { cs_log ( LOG_ERROR, "invalid parameters" ); return -1; } int ret; char config_item [ MAX_CONFIG_ITEM_LEN + 1 ]; char * delim = " \t\r\n\f\v"; char * saveptr; char * token; char * str = config_line; token = strtok_r ( str, delim, & saveptr ); /* empty line */ if ( token == NULL ) { cs_log ( LOG_DEBUG, "empty line" ); sprintf ( error_msg, "%s", "empty line" ); return -2; } /* item too long */ if ( strlen ( token ) > MAX_CONFIG_ITEM_LEN ) { cs_log ( LOG_WARN, "%s %s", "config item too long", token ); sprintf ( error_msg, "%s %s", "config item too long", token ); return -3; } strcpy ( config_item, token ); /* config item */ /* email config */ if ( strcmp ( config_item, CF_STR_EMAIL ) == 0 ) { ret = parse_cf_email_config ( email_config , saveptr, error_msg ); if ( ret < 0 ) { return -7; } } return 0; } /* * Function to parse email config * @email_config: email config * @str: pointer to config string * @error_msg pointer to error message * RET 0 or 1 on success, otherwise return a negative number */ static int parse_cf_email_config ( email_config_t * email_config, \ char * str, char * error_msg ) { if ( email_config == NULL || str == NULL || error_msg == NULL || str [ 0 ] == '\0' ) { return -1; } char * delim = " =\t"; char * saveptr; char * token; for ( ; ; str = NULL ) { token = strtok_r ( str, delim, & saveptr ); if ( token == NULL ) { break; } /* smtp server */ else if ( strcmp ( token, CF_STR_EMAIL_SMTP ) == 0 ) { token = strtok_r ( NULL, delim, & saveptr ); if ( token == NULL ) { sprintf ( error_msg, "invalid email config no smtp" ); return -2; } else if ( strlen ( token ) + 1 > sizeof ( email_config -> smtp_server ) ) { sprintf ( error_msg, "invalid email config smtp too long %s", token ); return -3; } strcpy ( email_config -> smtp_server, token ); // printf("__FILE__=%s, __LINE__=%d, smtp_server=%s\n", __FILE__, __LINE__, email_config->smtp_server); } /* from */ else if ( strcmp ( token, CF_STR_EMAIL_FROM ) == 0 ) { token = strtok_r ( NULL, delim, & saveptr ); if ( token == NULL ) { sprintf ( error_msg, "invalid email config no from" ); return -4; } else if ( strlen ( token ) + 1 > sizeof ( email_config -> from ) ) { sprintf ( error_msg, "invalid email config from too long %s", token ); return -5; } int eret = check_email_addr_format ( token, strlen ( token ) ); if ( eret < 0 ) { sprintf ( error_msg, "invalid email format, %s", token ); return - ( 5 + 0x0f00 ); } strcpy ( email_config -> from, token ); } /* user name */ else if ( strcmp ( token, CF_STR_EMAIL_NAME ) == 0 ) { token = strtok_r ( NULL, delim, & saveptr ); if ( token == NULL ) { sprintf ( error_msg, "invalid email config no name" ); return -4; } else if ( strlen ( token ) + 1 > sizeof ( email_config -> name) ) { sprintf ( error_msg, "invalid email config name too long %s", token ); return -5; } strcpy ( email_config -> name, token ); } /* password */ else if ( strcmp ( token, CF_STR_EMAIL_PASSWORD ) == 0 ) { token = strtok_r ( NULL, delim, & saveptr ); if ( token == NULL ) { sprintf ( error_msg, "invalid email config no paaaword" ); return -6; } else if ( strlen ( token ) + 1 > sizeof ( email_config -> password ) ) { sprintf ( error_msg, "invalid email config password too long %s", token ); return -7; } strcpy ( email_config -> password, token ); } /* to */ else if ( strcmp ( token, CF_STR_EMAIL_TO ) == 0 ) { token = strtok_r ( NULL, delim, & saveptr ); if ( token == NULL ) { sprintf ( error_msg, "invalid email config no to" ); return -8; } char * email_to_delim = " ;"; char * email_to_saveptr; char * email_to_token; char * email_to_str = token; int email_to_ix = 0; /* every to */ for ( email_to_ix = 0; email_to_ix < MAX_EMAIL_TO_STR_NUM; email_to_str = NULL, email_to_ix ++ ) { email_to_token = strtok_r ( email_to_str, email_to_delim, & email_to_saveptr ); if ( email_to_token == NULL ) { break; } if ( strlen ( email_to_token ) + 1 > \ sizeof ( email_config -> to [ email_to_ix ] ) ) { sprintf ( error_msg, "invalid email config to too long %s", token ); return -9; } /* check addr format */ int eret = check_email_addr_format ( email_to_token, strlen ( email_to_token ) ); if ( eret < 0 ) { sprintf ( error_msg, "invalid email format, %s", email_to_token ); return - ( 9 + 0x0f00 ); } strcpy ( email_config -> to [ email_to_ix ], email_to_token ); } } /* cc */ else if ( strcmp ( token, CF_STR_EMAIL_CC ) == 0 ) { token = strtok_r ( NULL, delim, & saveptr ); if ( token == NULL ) { sprintf ( error_msg, "invalid email config no cc" ); return -10; } char * email_cc_delim = " ;"; char * email_cc_saveptr; char * email_cc_token; char * email_cc_str = token; int email_cc_ix = 0; for ( email_cc_ix = 0; email_cc_ix < MAX_EMAIL_CC_STR_NUM; email_cc_str = NULL, email_cc_ix ++ ) { email_cc_token = strtok_r ( email_cc_str, email_cc_delim, & email_cc_saveptr ); if ( email_cc_token == NULL ) { break; } /* too long */ if ( strlen ( email_cc_token ) + 1 > \ sizeof ( email_config -> cc [ email_cc_ix ] ) ) { sprintf ( error_msg, "invalid email config cc too long %s", token ); return -11; } /* check format */ int eret = check_email_addr_format ( email_cc_token, strlen ( email_cc_token ) ); if ( eret < 0 ) { sprintf ( error_msg, "invalid email format, %s", email_cc_token ); return - ( 9 + 0x0f00 ); } strcpy ( email_config -> cc [ email_cc_ix ], email_cc_token ); } } /* smtp port */ else if ( strcmp ( token, CF_STR_EMAIL_SMTP_PORT ) == 0 ) { token = strtok_r ( NULL, delim, & saveptr ); if ( token == NULL ) { sprintf ( error_msg, "invalid email config no smtp port" ); return -12; } else { unsigned short int smtp_port; int smtp_ret = parse_port ( token, & smtp_port ); if ( smtp_ret == 0 ) { email_config -> smtp_port = smtp_port; } else { sprintf ( error_msg, "smtp port is invalid %s" , token ); return -13; } } } /* use tls ssl */ else if ( strcmp ( token, CF_STR_EMAIL_USE_TLS_SSL ) == 0 ) { token = strtok_r ( NULL, delim, & saveptr ); if ( token == NULL ) { sprintf ( error_msg, "invalid email config no tls ssl value" ); return -15; } else { long long int use_tls_ssl; int smtp_ret = parse_long_long_int ( token, & use_tls_ssl ); if ( smtp_ret == 0 ) { if ( use_tls_ssl == 0 || use_tls_ssl == 1 ) { email_config -> use_tls_ssl = ( int ) use_tls_ssl; } else { sprintf ( error_msg, "smtp use tls ssl value is invalid %s" , token ); return -16; } } else { sprintf ( error_msg, "smtp use tls ssl value is invalid %s" , token ); return -17; } } } } /* check email config */ if ( email_config -> smtp_server [ 0 ] == '\0' || \ email_config -> from [ 0 ] == '\0' ||\ email_config -> password [ 0 ] == '\0' ||\ email_config -> to [ 0 ] [ 0 ] == '\0' ) { sprintf ( error_msg, "invalid email config" ); return -14; } return 0; } /* * Function to init config * @config_file_path: path of config file * @ex_alarm_config:: pointer to alarm config * @alarm_items: pointer to alarm items * @error_msg: pointer to error message * RET 0 or 1 on success, otherwise return a negative number */ //int init_config ( char * config_file_path, ex_alarm_config_t * ex_alarm_config, \ // alarm_items_t * alarm_items, char * error_msg ) { int init_config ( char * config_file_path, email_config_t * email_config, char * error_msg ) { int ret = 0; /* read config from file */ ret = read_config_from_file ( config_file_path, email_config, error_msg ); if ( ret < 0 ) { return -2; } return 0; } /* * Function to check email address format * @email_addr: email address string * @email_addr_len:: length of email address * RET 0 or 1 on success, otherwise return a negative number */ static int check_email_addr_format ( char * email_addr, int email_addr_len ) { if ( email_addr == NULL || email_addr [ 0 ] == '\0' || email_addr_len < 3 ) { return -1; } char * chr = strchr ( email_addr, ( int ) '@' ); if ( chr == NULL || chr == email_addr || chr == email_addr + email_addr_len - 1 ) { return -2; } return 0; } /*end of file*/
C
/***************************************************************************//** * @file * @brief A wrapper for the Ember minimalistic implementation of printf() * to call standard printf() format specifiers. This saves space if * the application wants to use the standard printf(), since there is no * point in including the Ember printf implementation. ******************************************************************************* * # License * <b>Copyright 2018 Silicon Laboratories Inc. www.silabs.com</b> ******************************************************************************* * * The licensor of this software is Silicon Laboratories Inc. Your use of this * software is governed by the terms of Silicon Labs Master Software License * Agreement (MSLA) available at * www.silabs.com/about-us/legal/master-software-license-agreement. This * software is distributed to you in Source Code format and is governed by the * sections of the MSLA applicable to Source Code. * ******************************************************************************/ #include PLATFORM_HEADER #include "stack/include/ember-types.h" #include "stack/include/error.h" #include "hal/hal.h" #include "serial/serial.h" #include <stdarg.h> #include <stdio.h> //============================================================================= // Globals #if defined(EMBER_AF_PLUGIN_STANDARD_PRINTF_SUPPORT) #define MAX_STRING_REWRITE_SIZE EMBER_AF_PLUGIN_STANDARD_PRINTF_SUPPORT_MAX_BUFFER_LENGTH #else #define MAX_STRING_REWRITE_SIZE 80 #endif #if !defined(APP_SERIAL) #define APP_SERIAL serialPort #endif //============================================================================= EmberStatus emberSerialWriteHex(uint8_t port, uint8_t dataByte) { printf("%02x", dataByte); return EMBER_SUCCESS; } EmberStatus emberSerialPrintCarriageReturn(uint8_t port) { printf("\n"); return EMBER_SUCCESS; } // Convert Ember Printf format specifiers to stardard specifiers // %x => %02x // %2x => %04x // %4x => %08x // %p => %s EmberStatus emberSerialPrintfVarArg(uint8_t port, PGM_P formatString, va_list ap) { char newFormatString[MAX_STRING_REWRITE_SIZE + 1]; // +1 to allow for '\0' at end const char* ptr = formatString; uint16_t length = strlen(formatString); if (length > MAX_STRING_REWRITE_SIZE) { length = MAX_STRING_REWRITE_SIZE; } uint16_t newFormatIndex = 0; newFormatString[MAX_STRING_REWRITE_SIZE] = '\0'; bool previousWasPercentSymbol = false; uint8_t byteToWrite; while (*ptr != '\0' && newFormatIndex < MAX_STRING_REWRITE_SIZE) { byteToWrite = *ptr; if (!previousWasPercentSymbol && *ptr == '%') { previousWasPercentSymbol = true; } else if (previousWasPercentSymbol) { previousWasPercentSymbol = false; switch (byteToWrite) { case 'p': byteToWrite = 's'; break; case 'x': case 'X': newFormatString[newFormatIndex++] = '0'; newFormatString[newFormatIndex++] = '2'; break; case '2': case '4': if (*(ptr + 1) == 'x' || *(ptr + 1) == 'X') { newFormatString[newFormatIndex++] = '0'; byteToWrite = (byteToWrite == '2' ? '4' : '8'); } break; default: break; } } newFormatString[newFormatIndex++] = byteToWrite; ptr++; } newFormatString[newFormatIndex] = '\0'; vprintf(newFormatString, ap); return EMBER_SUCCESS; } EmberStatus emberSerialPrintf(uint8_t port, PGM_P formatString, ...) { EmberStatus status; va_list ap; va_start(ap, formatString); status = emberSerialPrintfVarArg(port, formatString, ap); va_end(ap); return status; } EmberStatus emberSerialPrintfLine(uint8_t port, PGM_P formatString, ...) { EmberStatus status; va_list ap; va_start(ap, formatString); status = emberSerialPrintfVarArg(port, formatString, ap); va_end(ap); printf("\n"); return status; } EmberStatus emberSerialGuaranteedPrintf(uint8_t port, PGM_P formatString, ...) { EmberStatus status; va_list ap; va_start(ap, formatString); status = emberSerialPrintfVarArg(port, formatString, ap); va_end(ap); printf("\n"); return status; } // The low-level output routine for IAR's printf(). size_t __write(int handle, const unsigned char * buffer, size_t size) { // A little white lie. We don't know how many bytes were actually written, // so we pretend it was 0. I don't know of code that handles anything // other than expectedSize != actualSize, in other words to handle recovery // of partial writes. return (EMBER_SUCCESS == emberSerialWriteData(APP_SERIAL, (uint8_t*)buffer, size) ? size : 0); }
C
#include <stdio.h> void quicksort(int left, int right); int array[200], n; int main (void) { int n, i, array[200]; printf("Please define the length:\n"); scanf("%d", &n); printf("%d", n); for (i = 0; i <n; i++) { printf("continue!"); scanf("%d", &array[i]); } printf("i got it!\n"); quicksort(0,n-1); for (i = 0; i < n; i++) { printf("%d ", array[i]); } } void quicksort(int left, int right) { int key, i, j; int change_left, change_right; i = left; j = right; key = array[left]; while (i != j && i < j) { while (key < array[i]) { i++; } while (key > array[j]) { j--; } array[i] ^= array[j]; array[j] ^= array[i]; array[i] ^= array[j]; } array[i] = key; quicksort(left, i - 1); quicksort(i + 1, right); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_lstmap.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fenedina <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/10/19 21:14:31 by fenedina #+# #+# */ /* Updated: 2021/10/19 21:14:33 by fenedina ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static int ft_null(t_list *new_el, t_list *lst, void (*del)(void *)) { int flag; flag = 1; if (0 == new_el) { ft_lstclear(&lst, del); flag = 0; } return (flag); } t_list *ft_lstmap(t_list *lst, void *(*f)(void *), void (*del)(void *)) { t_list *list; t_list *new_el; if (!lst || !f) return (NULL); new_el = ft_lstnew(f(lst->content)); ft_null(new_el, lst, del); list = new_el; lst = lst->next; while (lst) { new_el = ft_lstnew(f(lst->content)); if (0 == new_el) { ft_lstclear(&lst, del); ft_lstclear(&list, del); return (NULL); } lst = lst->next; ft_lstadd_back(&list, new_el); } return (list); }
C
/* Write a function setbits(x,p,n,y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged. Example input: x=10011101 (157), p=4, n=3, y=10010101 (149) Example output: 10010101 (149) */ #include <stdio.h> #include <assert.h> unsigned setbits(unsigned x, int p, int n, unsigned y); int main() { assert(setbits(157, 4, 3, 149) == 149); } unsigned setbits(unsigned x, int p, int n, unsigned y) { unsigned rmost_n_ones = ~(~0 << n); // 00000111 unsigned x_mask = ~(rmost_n_ones << p + 1 - n); // 11100011 unsigned x_masked = x & x_mask; // 10000001 (= 10011101 & 11100011) unsigned rmost_n_bits_of_y = rmost_n_ones & y; // 00000101 unsigned y_mask = rmost_n_bits_of_y << p + 1 - n; // 00010100 return x_masked | y_mask; // 10010101 (= 10000001 | 00010100) }
C
#include <stdio.h> #include <stdlib.h> /* Algorithm: * 1. Flip all the bits on the right side of the rightmost 0 in x. * 2. Flip rightmost 0 in x. * 3. Return x (because now x has become x + 1) */ int add_one_func(int x) { int one = 1; /* The precedence of != is higher then bitwise &. Thus, we put (x & one) * in bracket. If we don't do it, this will be interpreted as: * x & (one != 0). */ while ((x & one) != 0) { x ^= one; one <<= 1; } x ^= one; return x; } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: \n"); fprintf(stderr, "./add_one <input arg>\n"); exit(EXIT_FAILURE); /* In case of failure, we can exit the program with exit status: EXIT_FAILURE * EXIT_FAILURE is defined as -1 * In case of success, we can exit the program with exit status: EXIT_SUCCESS * EXIT_SUCCESS is defined as 0 */ } printf("(%d + 1) = %d\n", atoi(argv[1]), add_one_func(atoi(argv[1]))); return 0; }
C
//hex presentation of all the custom chars unsigned char halfBar[8] = { 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03 }; unsigned char cTwo[8] = { 0x00, 0x00, 0x09, 0x15, 0x13, 0x00, 0x00, 0x00 }; unsigned char cFour[8] = { 0x00, 0x00, 0x1F, 0x04, 0x1C, 0x00, 0x00, 0x00 }; unsigned char cFive[8] = { 0x00, 0x00, 0x16, 0x15, 0x1D, 0x00, 0x00, 0x00 }; unsigned char cSix[8] = { 0x00, 0x00, 0x13, 0x15, 0x0F, 0x00, 0x00, 0x00 }; unsigned char cSeven[8] = { 0x00, 0x00, 0x18, 0x14, 0x13, 0x00, 0x00, 0x00 }; unsigned char cEight[8] = { 0x00, 0x00, 0x1F, 0x15, 0x1F, 0x00, 0x00, 0x00 }; unsigned char cNine[8] = { 0x00, 0x00, 0x1E, 0x15, 0x1D, 0x00, 0x00, 0x00 }; unsigned char empty[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; /* * Iterates the saved character pattern to given array * TODO should be changed to pass only pointer */ int iterateArray(unsigned char numberPattern[], unsigned char pattern[]) { for(int i = 0; i< 9; i++) { numberPattern[i] = pattern[i]; } return 0; } // maps the given index (lcd memory addres) to corrseponding character pattern int getCustomCharPattern(int number, unsigned char pattern[]) { switch (number) { case 0: iterateArray(pattern, halfBar); return 0; case 2: iterateArray(pattern, cTwo); return 0; case 4: iterateArray(pattern, cFour); return 0; case 5: iterateArray(pattern, cFive); return 0; case 6: iterateArray(pattern, cSix); return 0; case 7: iterateArray(pattern, cSeven); return 0; case 8: iterateArray(pattern, cEight); return 0; case 9: iterateArray(pattern, cNine); return 0; default: iterateArray(pattern, empty); return 1; } }; // returns lcd character that resemble the given character sideways // 0, 1, 3 are reused preset symbols unsigned char getRemappedChar(char key) { switch (key) { case 'B': return (unsigned char) 0x00; // B is just a placeholder key, currently not in use case '0': return (unsigned char) 0x6F; // "o" symbol case '1': return (unsigned char) 0x2D; // "-" symbol case '2': return (unsigned char) 0x01; // Address of the custom 2 symbol in lcd memory case '3': return (unsigned char) 0x6D; // "similar looking to w" case '4': return (unsigned char) 0x02; // Address of the custom 4 symbol in lcd memory case '5': return (unsigned char) 0x03; //... case '6': return (unsigned char) 0x04; case '7': return (unsigned char) 0x05; case '8': return (unsigned char) 0x06; case '9': return (unsigned char) 0x07; default: return (unsigned char) 0xFF; //returns a filled square } } // remaps given char array to the sideways symbols int remapText(char inputText[], unsigned char mappedText[]) { for (int i = 0; i < 2; i++) { mappedText[i] = getRemappedChar(inputText[i]); } return 0; }
C
#include "calcom.h" int main() { int s=0 ; while(s != 4) { printf("1=add\n"); printf("2=subtract\n"); printf("3=multiply\n"); printf("4=divide\n"); printf("select operation: "); scanf("%d", &s); switch(s) { case 1: printf("Input a and b\n"); scanf("%lf %lf %lf %lf", &a->real, &a->img, &b->real, &b->img); add( a->real, a->img, b->real, b->img ); printf("(%lf, %lf)\n", c->real, c->img); break; case 2: printf("Input a and b\n"); scanf("%lf %lf %lf %lf", &a->real, &a->img, &b->real, &b->img); sub( a->real, a->img, b->real, b->img ); printf("(%lf, %lf)\n", c->real, c->img); break; case 3: printf("Input a and b\n"); scanf("%lf %lf %lf %lf", &a->real, &a->img, &b->real, &b->img); mult( a->real, a->img, b->real, b->img ); printf("(%lf, %lf)\n", c->real, c->img); break; case 4: printf("Input a and b\n"); scanf("%lf %lf %lf %lf", &a->real, &a->img, &b->real, &b->img); divide( a->real, a->img, b->real, b->img ); printf("(%lf, %lf)\n", c->real, c->img); break; default: break; } } return 0; }
C
/* [문제 - 블랙잭] 카지노에서 제일 인기 있는 게임 블랙잭의 규칙은 상당히 쉽다. 카드의 합이 21을 넘지 않는 한도 내에서, 카드의 합을 최대한 크게 만드는 게임이다. 블랙잭은 카지노마다 다양한 규정이 있다. 한국 최고의 블랙잭 고수 김정인은 새로운 블랙잭 규칙을 만들어 상근, 창영이와 게임하려고 한다. 김정인 버전의 블랙잭에서 각 카드에는 양의 정수가 쓰여 있다. 그 다음, 딜러는 N장의 카드를 모두 숫자가 보이도록 바닥에 놓는다. 그런 후에 딜러는 숫자 M을 크게 외친다. 이제 플레이어는 제한된 시간 안에 N장의 카드 중에서 3장의 카드를 골라야 한다. 블랙잭 변형 게임이기 때문에, 플레이어가 고른 카드의 합은 M을 넘지 않으면서 M과 최대한 가깝게 만들어야 한다. N장의 카드에 써져 있는 숫자가 주어졌을 때, M을 넘지 않으면서 M에 최대한 가까운 카드 3장의 합을 구해 출력하시오. [입력] 첫째 줄에 카드의 개수 N(3 ≤ N ≤ 100)과 M(10 ≤ M ≤ 300,000)이 주어진다. 둘째 줄에는 카드에 쓰여 있는 수가 주어지며, 이 값은 100,000을 넘지 않는 양의 정수이다. 합이 M을 넘지 않는 카드 3장을 찾을 수 있는 경우만 입력으로 주어진다. 5 21 5 6 7 8 9 [출력] 첫째 줄에 M을 넘지 않으면서 M에 최대한 가까운 카드 3장의 합을 출력한다. 21 */ #include <stdio.h> int main() { int card_cnt; int limit_num; int m = 0; int card_num[100]; int sum = 0; int max = 0; //int min_diff = 0; int cnt = 0; //카드의 개수와 제한된 수 입력 scanf("%d %d", &card_cnt, &limit_num); //카드에 적힌 숫자 입력 for (int i = 0; i < card_cnt; i++) { scanf("%d", &card_num[i]); } //카드 뽑기 for (int i = 0; i < card_cnt; i++) { for (int j = 0; j < card_cnt; j++) { for (int k = 0; k < card_cnt; k++) { //중복된 카드를 뽑지 않고, 제한된 수보다 작거나 같을 시 if ((i != j) && (j != k) && (k != i) && (limit_num >= (card_num[i] + card_num[j] + card_num[k]))) { sum = (card_num[i] + card_num[j] + card_num[k]); if (max < sum) { max = sum; } } } } } printf("%d\n", max); return 0; }
C
#define CTEST_MAIN #include <ctest.h> #include <sort.h> CTEST(sort, sort_2_words) { char **words = (char **)malloc(sizeof(char *) * 3); words[0] = "hello"; words[1] = "again"; words[2] = NULL; sortWords(words); ASSERT_EQUAL(strcmp(words[0], "again"), 0); ASSERT_EQUAL(strcmp(words[1], "hello"), 0); ASSERT_EQUAL(words[2] == NULL, 1); free(words); } int main(int argc, const char** argv) { return ctest_main(argc, argv); }
C
#include <stdio.h> #include "point.h" int main(){ /* Kamus */ POINT p1, p2; float gx, gy, arc; /* Algoritma */ printf("Hello Guys, selamat datang di program point \n"); printf("\nMasukkan nilai absis dan ordinat point pertama: "); BacaPOINT(&p1); printf("\nMasukkan nilai absis dan ordinat point kedua: "); BacaPOINT(&p2); printf("\nPoint yang terbaca "); TulisPOINT(p1); printf(" dan "); TulisPOINT(p2); printf("\nMenjalankan Test....\n"); if (EQ(p1,p2)){ printf("Point 1 dan 2 adalah sama\n"); } else if (NEQ(p1,p2)){ printf("Point 1 dan 2 tidak sama\n"); } if (IsOrigin(p1)){ printf("Point 1 adalah titik origin\n"); } if (IsOnSbX(p1)){ printf("Point 1 terletak di sumbu x\n"); } if (IsOnSbY(p1)){ printf("Point 1 terletak di sumbu y\n"); } printf("Point 1 terletak di kuadran %d", Kuadran(p1)); printf("\nApabila digeser sejauh satu sejajar sumbu x positif, point 1 menjadi "); TulisPOINT(NextX(p1)); printf("\nApabila digeser sejauh satu sejajar sumbu y positif, point 1 menjadi "); TulisPOINT(NextY(p1)); printf("\nTest geser point sejajar sumbu x sebesar: "); scanf("%f", &gx); printf("\nTest geser point sejajar sumbu y sebesar: "); scanf("%f", &gy); printf("\nHasil apabila digeser: "); TulisPOINT(PlusDelta(p1,gx,gy)); printf("\nPoint 1 apabila dicerminkan terhadap sumbu x: "); TulisPOINT(MirrorOf(p1, true)); printf("\nPoint 1 apabila dicerminkan terhadap sumbu x: "); TulisPOINT(MirrorOf(p1, false)); printf("\nJarak point ke titik pusat: %f\n", Jarak0(p1)); printf("Panjang garis antara point 1 dan 2 : %f\n", Panjang(p1,p2)); printf("\nGeser point sejajar sumbu x sebesar: "); scanf("%f", &gx); printf("\nGeser point sejajar sumbu y sebesar: "); scanf("%f", &gy); printf("\nMenggeser point menjadi: "); Geser(&p1,gx,gy); TulisPOINT(p1); printf("\nMenggeser point ke sumbu x menjadi: "); GeserKeSbX(&p1); TulisPOINT(p1); printf("\nMenggeser point ke sumbu y menjadi: "); GeserKeSbY(&p1); TulisPOINT(p1); printf("\nMencerminkan point terhadap sumbu x menjadi: "); Mirror(&p1, true); TulisPOINT(p1); printf("\nMencerminkan point terhadap sumbu y menjadi: "); Mirror(&p1, false); TulisPOINT(p1); printf("\nPutar point sejauh berapa derajat: "); scanf("%f",&arc); printf("\nPoint diputar menjadi: "); Putar(&p1, arc); TulisPOINT(p1); return 0; }
C
#include<stdio.h> void judjement(int x); int main() { int a; printf("请输入要判断的整数:"); scanf("%d",&a); judjement(a); return 0; } void judjement(int x) { int i; if(x<=2) printf("%d是素数。\n",x); else for(i=2;i<x;i++) { if((x%i)==0) break; } if(i==x) printf("%d是素数。\n",x); else printf("%d不是素数。\n",x); }
C
#include "snake.h" #include "GLCD.h" #include "stdint.h" #include "stddef.h" #include "stm32f10x_cl.h" #include "core_cm3.h" #include "system_stm32f10x_cl.h" #include "cmsis_os.h" #include "RTX_CM_lib.h" void createSnake(Snake *snake) { snake->x = 5; snake->y = 5; snake->direction = 1; snake->tailSize = 5; } void display(void const *argument) { for (;;) { //display code osSignalWait(0x01, osWaitForever); osSignalSet(movementThread, 0x01); } } void movement(void const *argument) { for (;;) { osSignalWait(0x01, osWaitForever); osSignalSet(scoreThread, 0x01); //traverse linked list struct TailSegment *temp = start; //Move to First Node int prevX; int prevY; do { //Do Your Operation //Statement 1-N temp->x = prevX; temp->y = prevY; temp = temp->next; //Move Pointer to Next Node } while (temp != NULL); } } void score(void const *argument) { for (;;) { osSignalWait(0x01, osWaitForever); osSignalSet(displayThread, 0x01); } } /*Main - initialise, start RTX kernel and play game */ int main(void) { SystemCoreClockUpdate(); GLCD_Initialize(); GLCD_SetBackColor(Black); GLCD_Clear(Black); GLCD_SetTextColor(White); mut_GLCD = ofMutexCreate(osMutex(mut_GLCD)); createSnake(*player); //wait //osSignalWait(0x01, osWaitForever); //update ? scoreThread = osThreadCreate(osThread(score), NULL); movementThread = osThreadCreate(osThread(movement), NULL); displayThread = osThreadCreate(osThread(display), NULL); osSignalSet(displayThread, 0x01); //start first thread // /* osSignalSet(scoreThread, 0x01); osSignalSet(movementThread, 0x01); osSignalSet(displayThread, 0x01); */ }
C
include<stdio.h> //This header defines various functions for performing input output operations #include<fcntl.h> //Used to define arguments for open ,close functions #include<unistd.h> //This header file is for misscelaneous functions declaration #include<termios.h> // It contains the definitions used by terminal input output interfaces #include<string.h> //This is used for defining strings etc. int main(){ int file, count; file = open("/dev/ttyO1", O_RDWR); //this function open the file associated with Uart1 struct termios options; //declaration of a struct options tcgetattr(file, &options); //This function get parameters associated with terminal and store them in termios options.c_cflag = B9600 | CS8 | CREAD | CLOCAL; options.c_iflag = IGNPAR | ICRNL; tcflush(file, TCIFLUSH); //This function is used to clear input and output queue associated with terminal files tcsetattr(file, TCSANOW, &options); // if (count = write(file, data, strlen(data))<0){ // perror("Failed to write to the output\n"); // } // printf("Data write Successfully !!"); // usleep(100000); // } // return 0; unsigned char receive[100]; //recieve array declaration while(1) { count = read(file, (void*)receive, 100); //This variable count the number of bytes if (count==0) printf("There was no data available to read!\n"); else if(count>0) {
C
#include "../../includes/minirt.h" static double min(double a, double b) { if (a > b) return (b); return (a); } static double *get_coeff_light(t_light *light, t_params *obj, t_cam *cam, t_scene *scene) { double *coeff_light; double local_intensity; coeff_light = ft_calloc(sizeof(double), 3); while (light) { local_intensity = get_intensity(light, obj, cam, scene); coeff_light[0] += local_intensity * light->colors[0] / 255; coeff_light[1] += local_intensity * light->colors[1] / 255; coeff_light[2] += local_intensity * light->colors[2] / 255; light = light->next; } free(obj->point); free(obj->normal); return (coeff_light); } int get_color(t_params *obj, t_scene *scene, t_cam *cam) { int color; double coeff_amb[3]; double *coeff_light; coeff_amb[0] = scene->amb->ratio * scene->amb->colors[0] / 255; coeff_amb[1] = scene->amb->ratio * scene->amb->colors[1] / 255; coeff_amb[2] = scene->amb->ratio * scene->amb->colors[2] / 255; coeff_light = get_coeff_light(scene->light, obj, cam, scene); color = 0; color |= ((int)min(obj->colors[0] * (coeff_amb[0] + coeff_light[0]), 255)) << 16; color |= ((int)min(obj->colors[1] * (coeff_amb[1] + coeff_light[1]), 255)) << 8; color |= ((int)min(obj->colors[2] * (coeff_amb[2] + coeff_light[2]), 255)); free(coeff_light); return (color); }
C
#include <stdint.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <fcntl.h> #include <sys/ioctl.h> #include <linux/types.h> #include <linux/spi/spidev.h> #include <string.h> #include <errno.h> #include "bulldog.h" #include "bulldogSpi.h" int spiOpen(char* busDevice, int mode, int speed, int bitsPerWord, int lsbFirst) { int fd; int ret; if ((fd = open (busDevice, O_RDWR)) < 0) { errorMessage("open failed: %s", strerror(errno)); return -1; } if(spiConfig(fd, mode, speed, bitsPerWord, lsbFirst) < 0) { errorMessage("open failed: %s", strerror(errno)); return -1; } return fd; } int spiConfig(int fileDescriptor, int mode, int speed, int bitsPerWord, int lsbFirst) { if(ioctl(fileDescriptor, SPI_IOC_WR_MODE, &mode) < 0) { errorMessage("cannot set spi mode: %s", strerror(errno)); return -1 ; } if(ioctl(fileDescriptor, SPI_IOC_RD_MODE, &mode) < 0) { errorMessage("cannot get spi mode: %s", strerror(errno)); return -1 ; } if(ioctl(fileDescriptor, SPI_IOC_WR_BITS_PER_WORD, &bitsPerWord) < 0) { errorMessage("cannot set spi bits per word: %s", strerror(errno)); return -1; } if(ioctl(fileDescriptor, SPI_IOC_RD_BITS_PER_WORD, &bitsPerWord) < 0) { errorMessage("cannot get spi bits per word: %s", strerror(errno)); return -1; } if(ioctl(fileDescriptor, SPI_IOC_WR_MAX_SPEED_HZ, &speed) < 0) { errorMessage("cannot set spi speed: %s", strerror(errno)); return -1; } if(ioctl(fileDescriptor, SPI_IOC_RD_MAX_SPEED_HZ, &speed) < 0) { errorMessage("cannot get spi speed: %s", strerror(errno)); return -1; } int lsb = lsbFirst > 0 ? SPI_LSB_FIRST : 0; if(ioctl(fileDescriptor, SPI_IOC_WR_LSB_FIRST, &lsb) < 0) { errorMessage("cannot set lsb first: %s", strerror(errno)); return -1; } if(ioctl(fileDescriptor, SPI_IOC_RD_LSB_FIRST, &lsb) < 0) { errorMessage("cannot get lsb first: %s", strerror(errno)); return -1; } return 0; } int spiTransfer(int fileDescriptor, unsigned int* txBuffer, unsigned int* rxBuffer, int transferLength, int delay, int speed, int bitsPerWord) { struct spi_ioc_transfer tr = { tr.tx_buf = (unsigned long) txBuffer, tr.rx_buf = (unsigned long) rxBuffer, tr.len = (uint32_t) transferLength, tr.delay_usecs = (uint16_t) delay, tr.speed_hz = (uint32_t) speed, tr.bits_per_word = (uint8_t) bitsPerWord, }; int ret = ioctl(fileDescriptor, SPI_IOC_MESSAGE(1), &tr); if(ret < 0) { errorMessage("spi message transfer failed: %s", strerror(errno)); } return ret; } int spiClose(int fileDescriptor) { return close(fileDescriptor); }
C
//Write a program to demo of datatype in c #include<stdio.h> #include<conio.h> main(){ int a; float b; double c; char h; clrscr(); printf("enter char"); scanf("%c",&h); printf("%c",h); printf("\nenter integer number"); scanf("%d",&a); printf("\ninteger=%d",a); printf("\nenter float number"); scanf("%f",&b); printf("\nfloat=%f",b); printf("\nenter double number"); scanf("%ld",&c); printf("\ndouble=%lf",c); getch(); return 0; }
C
/* struct operation */ struct str1 { int i; char c; }; struct str2 { int *i; char *c; struct str3 { int *i; char *c; } st; }; struct str3 { /* error, redeclaration of struct str3 */ int *i; char *c; }; int main(void) { int i1; char c1; struct str1 st1; struct str2 st2; struct str1 *pst1; struct str2 *pst2; pst1 = &st1; pst2 = st1; /* error */ pst2 = &st2; i1 = st1.i; c1 = st1.i; /* error */ i1 = *st2.c; /* error */ i1 = *(pst2->st.i); i1 = *(pst2->st.c); /* error */ return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <jni.h> #include "JNITest.h" char *data; int allocated = 0; JNIEXPORT void JNICALL Java_JNITest_freeMemory(JNIEnv *env, jobject obj) { if(allocated) { free(data); allocated = 0; } } JNIEXPORT jint JNICALL Java_JNITest_allocateAndFillMemory(JNIEnv *env, jobject obj, jint num) { size_t i; size_t size = num * 1024l * 1024l; if(allocated) { free(data); } printf("Int: %lu\n", sizeof(int)); printf("size_t: %lu\n", sizeof(size_t)); data = malloc(size); if(data) { printf("[JNI]: Successfully allocated %d MB\n\n", num); int filled = -1; size_t multiplier = 10l; for(i = 0; i < size; i++) { data[i] = 1; if(i % (1024l * 1024l * multiplier) == 0) { filled++; if(filled != 0) { printf("[JNI]: Filled %lu MB ...\n", filled * multiplier); } } } allocated = 1; printf("[JNI]: Successfully filled %lu MB.\n\n", i / (1024l * 1024l)); } else { printf("[JNI]: Failed to allocate %d MB.\n\n", num); allocated = 0; } return allocated; }
C
#ifndef LIBFT_H # define LIBFT_H # include <stdlib.h> # include <unistd.h> # include <stdint.h> enum { TRUE = 1, MAX_RANK = 1000000000, }; typedef struct s_list { unsigned long value; struct s_list *next; struct s_list *prev; } t_list; size_t ft_strlen(const char *s); char *ft_strchr(const char *s, int c); void ft_bzero(void *s, size_t n); int ft_atoi(const char *nptr); void *ft_calloc(size_t nmemb, size_t size); int ft_isalpha(int c); int ft_isdigit(int c); int ft_isspace(int c); char *ft_strdup(const char *s); size_t ft_strlcat(char *dst, const char *src, size_t dst_size); size_t ft_strlcpy(char *dst, const char *src, size_t dst_size); char *ft_strndup(const char *s, size_t len); unsigned int ft_abs(int n); void ft_putchar_fd(char c, int fd); t_list *ft_lstnew(uint64_t value); void ft_lstadd_front(t_list **lst, t_list *new); t_list *ft_lstlast(t_list *lst); void ft_lstclear(t_list **lst); void ft_lstnormalizer(t_list *lst); void fill_with(char c, unsigned int amount); void ft_putnbr_base(uint64_t nbr, uint8_t base, char *symbs); size_t count_symbs(uint64_t nbr, uint8_t base); int32_t ft_power(int32_t nbr, int32_t power); void ft_bignummultiply(t_list **lst, uint64_t value, int16_t power); void ft_bignumaddition(t_list *lst, t_list **extra); #endif
C
#include "_stdio.h" #include "epdk.h" #undef ioctl // 豸ԭ int ioctl(FILE *stream, int request, int aux, void *pBuffer) { return eLIBs_fioctrl((ES_FILE *)stream, request, aux, pBuffer); } #include "direct.h" int mkdir(const char *dp) { return (int)eLIBs_mkdir(dp); } int rmdir(const char *dp) { return (int)eLIBs_rmdir(dp); } DIR *opendir(const char *dirname) { return (DIR *)eLIBs_opendir(dirname); } int closedir(DIR * p) { return (int)eLIBs_closedir((ES_DIR *)p); } struct dirent * readdir(DIR * dirp) { ES_DIRENT *t; t = eLIBs_readdir((ES_DIR *)dirp); // ת, ĿǰҪ, ΪESDIRECTṹΪ //typedef struct __ESDIRENT //{ // __u32 d_ino; // to be POSIX conform // __u8 fatdirattr; // FAT only. Contains the "DIR_Attr" field of an entry. // __u64 d_size; // file size, if directory it will be 0 // __u8 d_name[260]; // }ES_DIRENT; return (struct dirent *)t; } int rewinddir(DIR * dir) { eLIBs_rewinddir((ES_DIR *)dir); return 0; }
C
#include <stdio.h> int main() { int i; int arr[10]; for (i=0;i<10;i++) arr[i]=i; for (i=0;i<10;i++) printf(" arr[%d] = %d \n",i,arr[i]); return 0; }
C
/*Pg no 51 Aim : to find a given character is an arithmatic operator or not*/ #include <stdio.h> int main(){ char ch; scanf("%c",&ch); switch(ch){ case '+': case '-': case '*': case '/': case '%': printf("%c is an arithmatic operator",ch); break; default: printf("%c is not an arithmatic operator",ch); break; } }
C
#include<stdio.h> #include<stdlib.h> #include"Ex2TAED.h" #define MAX 10 int main(){ int i=0,r,f; Lista *p; p=cria_lista(); imprime_lista(p); do{ int q,v; printf("\nDeseja adicionar ordenadamente um elemento na sua lista?\n1-Yes\n2-No\n\n"); scanf("%d",&v); if(v==1){ printf("\nDigite o elemento:\n"); scanf("%d",&q); if(insere_ord(p,q)==0)printf("\n------------------------------------------------------\nErro,Impossivel inserir elemento a lista.\n------------------------------------------------------\n"); }else break; }while(1); imprime_lista(p); Lista *a,*b,*c; a=cria_lista(); b=cria_lista(); c=cria_lista(); imprime_lista(a); insere_ord(a,7); insere_ord(a,4); insere_ord(a,6); insere_ord(a,1); imprime_lista(a); imprime_lista(b); insere_ord(b,3); insere_ord(b,8); insere_ord(b,4); insere_ord(b,1); imprime_lista(b); imprime_lista(c); c=intercala(a,b); printf("\nTamanho da lista = %d\n",tamanho(c)); printf("Lista intercalada: "); imprime_lista(c); printf("Maior elemento da lista = %d\n",maior(c)); remove_par(c); printf("\nLista sem elementos pares : "); imprime_lista(c); printf("\nTamanho da lista = %d\n",tamanho(c)); printf("Maior elemento da lista = %d\n",maior(c)); printf("\n\n\n"); imprime_lista(a); imprime_lista(b); int iguais=compara(a,b); if(iguais == 0)printf("As listas sao iguais...\n"); else printf("As listas nao sao iguais..."); printf("\n\n\n"); }
C
#include "time.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <limits.h> #include <math.h> #include <sys/stat.h> //Zachary Snyder project 4 main file. //Initiates both parts of the program. #define LEN 100 typedef struct Data{ int days; int lines; char** dataMeasure; int frequency[LEN]; char units[LEN]; } Data;//structure for storing specifications input from files char* getMeasure(char * line, int which); Data gather_input(); typedef struct Specs{ int batches;//Number of batches of items int items;//Number of items in each batch int bad_batches;//Percentage of batches containing bad items int bad_items;//Percentage of items that are bad in a bad batch int samples;//Items sampled from each batch } Specs;//structure for storing specifications input from files Specs gather_specs(int n_file); void write_data(Specs c, int n_file); Specs generate_data(Specs c, int n_file); void analyze_data(Specs c, Specs s, int n_file); void make_directory(const char* name); //Zachary Snyder part 1 of project 4 //calculate error of monte carlo sim Specs gather_specs(int n_file){ Specs c; FILE *fp; char filename[PATH_MAX]; sprintf(filename, "c%d.txt", n_file); fp = fopen(filename, "r"); fscanf(fp, " %d\n", &c.batches); fscanf(fp, " %d\n", &c.items); fscanf(fp, " %d\n", &c.bad_batches); fscanf(fp, " %d\n", &c.bad_items); fscanf(fp, " %d\n", &c.samples); fclose(fp); return c; } void write_data(Specs c, int n_file){ FILE *fp; char filename[PATH_MAX], cwd[PATH_MAX]; int n_batches, n_items, is_bad = 0; sprintf(filename, "c%d", n_file); make_directory(filename); for(n_batches = 1; n_batches < c.batches; n_batches++){ is_bad = 0; if (getcwd(cwd, sizeof(cwd)) != NULL) { sprintf(filename, "%s/c%d/ds%d.txt", cwd, n_file, n_batches); } fp = fopen(filename, "w"); if(((rand() % 100)+1) <= c.bad_batches) is_bad = 1; if(is_bad){ for(n_items = 1; n_items < c.items; n_items++){ if((rand() % 100)+1 <= c.bad_items && is_bad) fprintf(fp, "b\n"); else fprintf(fp, "g\n"); } } else{ for(n_items = 1; n_items < c.items; n_items++) fprintf(fp, "g\n"); } fclose(fp); } } Specs generate_data(Specs c, int n_file){ FILE *fp; char filename[PATH_MAX], cwd[PATH_MAX]; char data_in; Specs d = {0}; printf("Simulation %d:\n", n_file); printf("\tNumber of batches of items:\t\t\t%d\n", c.batches); printf("\tNumber of items in each batch:\t\t\t%d\n", c.items); printf("\tPercentage of batches containing bad items:\t%d%%\n", c.bad_batches); printf("\tPercentage of items that are bad in a bad set:\t%d%%\n", c.bad_items); printf("\tItems sampled from each set\t\t\t%d\n", c.samples); printf("\nGenerating data sets:\n"); for(d.batches = 1; d.batches < c.batches; d.batches++){ d.bad_items = 0; if (getcwd(cwd, sizeof(cwd)) != NULL) { sprintf(filename, "%s/c%d/ds%d.txt", cwd, n_file, d.batches); } fp = fopen(filename, "r"); for(d.items = 1; d.items < c.items; d.items++){ data_in = fgetc(fp); fgetc(fp); if((data_in == 'b')){ d.bad_items++; d.samples++; } } fclose(fp); if(d.bad_items > 0){ d.bad_batches++; printf("\tCreate bad set batch #%3d, totBad = %3d total = %3d badpct = %0.f\n", d.batches, d.bad_items, c.items, (float)d.bad_items/c.items*100); } } printf("\tTotal bad sets = %d\n\n", d.bad_batches); return d; } void analyze_data(Specs c, Specs s, int n_file){ FILE *fp; char filename[PATH_MAX], cwd[PATH_MAX]; char data_in; Specs d = {0}; float base, failure_to_detect, batch_is_good, bad_batch_detected; printf("Analyzing data sets:\n"); for(d.batches = 1; d.batches < c.batches; d.batches++){ d.bad_items = 0; if (getcwd(cwd, sizeof(cwd)) != NULL) { sprintf(filename, "%s/c%d/ds%d.txt", cwd, n_file, d.batches); } fp = fopen(filename, "r"); for(d.samples = 1; d.samples < c.samples; d.samples++){ d.items = (rand() % c.items) + 1; data_in = fgetc(fp); fgetc(fp); if((data_in == 'b')){ d.bad_items++; } } fclose(fp); if(d.bad_items > 0){ d.bad_batches++; printf("\tBatch #%3d is bad.\n", d.batches); } } base = 1.0 - (float)c.bad_items/100; printf("Base = %.2f exponent = %d\n", base , c.samples); failure_to_detect = pow(base, c.samples); printf("P(failure to detect bad item) = %.3f\n", failure_to_detect); batch_is_good = 1.0 - failure_to_detect; printf("P(batch is good) = %.3f\n", batch_is_good); bad_batch_detected = (float)d.bad_batches/(s.bad_batches)*100; printf("Percentage of bad batches detected = %.2f%%\n", bad_batch_detected); } void make_directory(const char* name){ #ifdef __linux__ mkdir(name, 777); #else _mkdir(name); #endif } //Zachary Snyder part 2 of project 4 //calculate expected value from a range of data given frequency char* getMeasure(char * line, int which) { char *token; char *search = "-:"; token = strtok(line, search); if (which==1) return token; else { token = strtok(NULL, search); return token; } } Data gather_input() { Data r = {0}; FILE *fp; int temp; fp = fopen("readings.txt", "r"); int i; r.frequency[-1] = 0; fscanf(fp, " %d\n", &r.days); fscanf(fp, " %d\n", &r.lines); r.dataMeasure = (char**)malloc(r.lines * sizeof(char*)); for (i = 0; i < r.lines; i++) r.dataMeasure[i] = malloc((LEN+1) * sizeof(char)); for(i=0; i<r.lines; i++){ fscanf(fp, " %s", r.dataMeasure[i]); fscanf(fp, " %d", &temp); r.frequency[i] = temp + r.frequency[i-1]; } fscanf(fp, " %s", r.units); fclose(fp); return r; } //creates a random number over the interval min to max int get_rand_interval(int min, int max) { int r, range, x, limit; range = 1 + max - min; x = RAND_MAX / range; limit = x * range; do { r = rand(); } while (r >= limit); return min + (r / x); } int main(){ srand(time(NULL)); Specs c1, c2, c3, c4; Specs d1, d2, d3, d4; //assign the specifications gathered from files //and places them in their associated structure c1 = gather_specs(1); c2 = gather_specs(2); c3 = gather_specs(3); c4 = gather_specs(4); //create the files holding the data write_data(c1, 1); write_data(c2, 2); write_data(c3, 3); write_data(c4, 4); //generate the data sets d1 = generate_data(c1, 1); analyze_data(c1, d1, 1); d2 = generate_data(c2, 2); analyze_data(c2, d2, 2); d3 = generate_data(c3, 3); analyze_data(c3, d3, 3); d4 = generate_data(c4, 4); analyze_data(c4, d4, 4); Data r = {0}; int i, j; r.dataMeasure = malloc(r.lines * sizeof(char*)); for (i = 0; i < r.lines; i++) r.dataMeasure[i] = malloc((LEN+1) * sizeof(char)); char measure[LEN]; char temp[LEN]; char* val; int min, max; int chance; int selected = -1; float expected_value = 0; r = gather_input(); for(j = 0; j < r.days; j++){ chance = rand() % r.days; for(i = 0; i < r.lines; i++){ if(chance <= r.frequency[i]){ selected = i; } strcpy(measure, r.dataMeasure[selected]); strcpy(temp, measure); val = getMeasure(temp,1); min = atoi(val); strcpy(temp, measure); val = getMeasure(temp,2); max = atoi(val); expected_value += get_rand_interval(min, max); } } expected_value /= (float)r.days; printf("\nAnalytical model: 8500.0 Expected value is in the %s%s range.\n", r.dataMeasure[r.lines/2], r.units); printf("Simulation: %.1f. Expected value is in the %s%s range.\n", expected_value, r.dataMeasure[r.lines/2], r.units); return 0; }
C
/* Kullancnn girdii 25 tane tam saydan en kucuk ve en buyuk sayilari bulan program kullanici -500000 ile 500000 arasi deger girecektir. */ #include<stdio.h> int main(){ int i,a,eb,ek; //eb=enbuyuk ek=enkucuk eb=-500000; ek=500000; for(i=1;i<=25;i++){ printf("sayi gir: "); scanf("%d",&a); if(a>eb){ eb=a; } if(a<ek){ ek=a; } } printf("en buyuk: %d\n",eb); printf("en kucuk: %d\n",ek); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "wolf3d.h" int find_pos(char c, char *str) { int i; i = 0; while (str[i] != '\0') { if (str[i] == c) return (i); i = i + 1; } return (-1); } int my_getnbr_base(char *str, char *base) { int result; int len_base; int len_str; int fact; if (str[0] == '-') return (-my_getnbr_base(&str[1], base)); fact = 1; len_base = my_strlen(base); len_str = my_strlen(str) - 1; result = 0; while (len_str >= 0) { result = result + find_pos(str[len_str], base) * fact; fact = len_base * fact; len_str = len_str - 1; } return (result); }
C
#include <stdlib.h> #include <stdio.h> #include <time.h> void losowanie(int *od, int *doo) { for(; od<doo; od++) { *od=rand()%100+1; } } void wyswietl(int *od, int *doo) { for(; od<doo; od++) { printf("%d\n", *od); } } void wyswietlPosortowana(int **od, int **doo) { for(; od<doo; od++) { printf("%d\n", **od); } } void zamien(int **od, int **doo) { int zmiana; int **schowek; do { zmiana=0; for(int **i=od; i<doo; i++) { if(**i>**(i+1)) { zmiana=zmiana+1; *schowek=*i; *i=*(i+1); *(i+1)=*schowek; } } }while(zmiana!=0); } int main() { int A[10]; const int rozmiar=sizeof(A)/sizeof(A[0]); srand(time(NULL)); losowanie(A, A+rozmiar); printf("Zawartosc tablicy A przed losowaniem: \n"); wyswietl(A, A+rozmiar); int *B[10]; for(int i=0; i<rozmiar; i++) { B[i]=(A+i); } zamien(B, B+rozmiar-1); printf("Posortowana tablica w tablicy wskaznikow B : \n"); wyswietlPosortowana(B, B+rozmiar); printf("Zawartosc tablicy A po sortowaniu: \n"); wyswietl(A, A+rozmiar); }
C
// Set pointer to videobuffer char *video = (char*)0xB8000; int main() { // Set string char *hello = "Hello World"; for(video+=4000; video !=(char*)0xB8000; video--) { *video=0; } while(*video) { *video=*hello; video++; *video = 0x07; video++; hello++; } while(1); return 0; }
C
#include <stdio.h> #include <setjmp.h> #include <stdint.h> #include "the_worst.c" jmp_buf buf; // Returns 0 on success, non-zero otherwise int32_t the_worst_wrapper(callback_t* callback) { printf("[the_worst_wrapper]: enter\n"); switch (setjmp(buf)) { case 0: the_worst(callback); break; case 42: printf("[the_worst_wrapper]: exit error\n"); return 42; } printf("[the_worst_wrapper]: exit success\n"); return 0; } // Can be called from the callback to return an error void callback_error(int32_t i) { printf("[callback_error]: enter with error %d\n", i); longjmp(buf, i); }
C
#include "console_control.h" #include "ui.h" #include "slot.h" int slot(void) { int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; int count = 0; int n= 0; int flag; char slot[size][10] = { "int", "long", "long long", "float", "double", "char", "string" }; char ch; int i = 0; int sc = 100; srand((unsigned)time(NULL)); showMenu(); while (1) { a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, count = 0, i = 0, sc = 100, n = 0, flag = 0; do { printf("Ͻ ݾ Էּ\n"); printf("100$ ~ 10000$\n"); scanf("%d", &a); system("CLS"); } while (a < 100 || a>10000); showMoney(a); printf(" 2 ñX2 : %d\n", a * 2); printf(" 3 ñX5 : %d\n", a * 5); printf("1).int 2).long 3).long long 4).float 5).double 6).char 7).string\n"); scanf("%d", &b); system("cls"); printf("\n"); gotoxy(0, 1); printf(""); gotoxy(40, 1); printf(""); gotoxy(0, 2); printf("\n"); gotoxy(40, 3); printf(" :߷ ƹŰ ּ\n"); while(1) { c = rand() % 7; d = rand() % 7; e = rand() % 7; gotoxy(2, 1); printf(" "); gotoxy(2, 1); printf("%10s |", slot[c]); if (flag) sc += 20; Sleep(sc); gotoxy(15, 1); printf(" "); gotoxy(15, 1); printf("%10s |", slot[d]); if (flag) sc += 20; Sleep(sc); gotoxy(28, 1); printf(" "); gotoxy(28, 1); printf("%10s ", slot[e]); if (flag) sc += 20; Sleep(sc); if (GetAsyncKeyState(VK_SPACE)) flag = 1; if (flag) { n++; } if (n > 12) break; } printf("\n"); if (slot[c] == slot[d]) count++; if (slot[d] == slot[e]) count++; if (slot[c] == slot[e]) count++; if (count == 3) a = a * 5; else if (count == 1) a = a * 2; gotoxy(0, 4); showMoney(a); do { printf("\n"); printf("1). Ѵ. 2). Ѵ.\n"); scanf("%d", &f); if (f == 1) { system("CLS"); break; } } while (f != 1 || f != 2); if (f == 2) break; } return 0; }
C
#include <linux/init.h> #include <linux/module.h> #include <linux/device.h> #include <linux/kernel.h> #include <linux/fs.h> #include<linux/slab.h> #include <asm/uaccess.h> #include <linux/sched.h> #define DEVICE_NAME "process_list" #define CLASS_NAME "proc" MODULE_LICENSE("GPL"); static int majorNumber; static struct class* processClass = NULL; static struct device* processDevice = NULL; static ssize_t dev_read(struct file *, char *, size_t, loff_t *); static struct file_operations fops = { .read = dev_read }; static int __init char_init(void) { majorNumber = register_chrdev(0, DEVICE_NAME, &fops); if (majorNumber<0){ printk(KERN_ALERT "Failed to register a major number\n"); return majorNumber; } printk(KERN_INFO "Registered correctly with major number %d\n", majorNumber); processClass = class_create(THIS_MODULE, CLASS_NAME); if (IS_ERR(processClass)){ unregister_chrdev(majorNumber, DEVICE_NAME); printk(KERN_ALERT "Failed to register device class\n"); return PTR_ERR(processClass); } processDevice = device_create(processClass, NULL, MKDEV(majorNumber, 0), NULL, DEVICE_NAME); if (IS_ERR(processDevice)){ class_destroy(processClass); unregister_chrdev(majorNumber, DEVICE_NAME); printk(KERN_ALERT "Failed to create the device\n"); return PTR_ERR(processDevice); } return 0; } static void __exit char_exit(void) { device_destroy(processClass, MKDEV(majorNumber, 0)); class_unregister(processClass); class_destroy(processClass); unregister_chrdev(majorNumber, DEVICE_NAME); } static ssize_t dev_read(struct file *filep, char *buffer, size_t len, loff_t *offset) { int error_count = 0; char * my1 = kmalloc(len,GFP_KERNEL); struct task_struct *task; for_each_process(task) { int d=task->state; char *cstate; if(d==0) cstate="TASK_RUNNING"; else if(d==1) cstate="TASK_INTERRUPTIBLE"; else if(d==2) cstate="TASK_UNINTERRUPTIBLE"; else if(d==4) cstate="__TASK_STOPPED"; else if (d==8) cstate="TASK_TRACED"; else if (d==64) cstate="TASK_DEAD"; else if (d==128) cstate="TASK_WAKEKILL"; else if (d==128) cstate="TASK_WAKEKILL"; else if (d==256) cstate="TASK_WAKING"; else if (d==512) cstate="TASK_PARKED"; else if (d==1024) cstate="TASK_NOLOAD"; else if (d==2048) cstate="TASK_NEW"; else if (d==4096) cstate="TASK_STATE_MAX"; sprintf(my1+strlen(my1),"PID:%d PPID:%d CPU:%d STATE:%s\n", task->pid, task_ppid_nr(task), task_cpu(task), cstate); } error_count = copy_to_user(buffer, my1, strlen(my1)); } module_init(char_init); module_exit(char_exit);
C
/********************************* * Jordan Mai, jmai12 * 2020 Spring CSE101 PA5 * Dictionary ADT ********************************/ #include "Dictionary.h" #include <assert.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> typedef struct NodeObj { char *key; int value; struct NodeObj *left; struct NodeObj *right; struct NodeObj *parent; } NodeObj; typedef NodeObj *Node; typedef struct DictionaryObj { Node root; int unique; int size; Node cursor; // for move functions } DictionaryObj; Node newNode(char *k, int v) { Node n = malloc(sizeof(NodeObj)); assert(n); n->key = k; n->value = v; n->left = NULL; n->right = NULL; return n; } void freeNode(Node *pN) { if (pN != NULL && *pN != NULL) { free(*pN); *pN = NULL; } } // PROF TANTALLO void deleteAll(Node R) { if (R != NULL) { deleteAll(R->left); deleteAll(R->right); freeNode(&R); } } Dictionary newDictionary(int unique) { Dictionary d = malloc(sizeof(struct DictionaryObj)); assert(d); d->root = NULL; d->size = 0; d->cursor = NULL; if (unique == 0) { d->unique = 0; } else { d->unique = 1; } return d; } void freeDictionary(Dictionary *pD) { if (pD != NULL && *pD != NULL) { makeEmpty(*(pD)); free(*pD); *pD = NULL; } } // returns how many pairs int size(Dictionary D) { if (D == NULL) { printf("ERROR on size"); exit(1); } return D->size; } int getUnique(Dictionary D) { if (D == NULL) { printf("ERROR get UNIQU"); exit(1); } // 1 == duplicates if (D->unique == 1) { return 1; } else { return 0; } } // recursive to determine key // PROF TANTALLO Node findKey(Node n, KEY_TYPE k) { if (n == NULL || KEY_CMP(k, n->key) == 0) { return n; } if (strcmp(k, n->key) < 0) { return findKey(n->left, k); } else { return findKey(n->right, k); } } VAL_TYPE lookup(Dictionary D, KEY_TYPE k) { if (D == NULL) { printf("ERROR on lookup"); exit(1); } Node n; n = findKey(D->root, k); if (n != NULL) { return n->value; } return VAL_UNDEF; } void insert(Dictionary D, KEY_TYPE k, VAL_TYPE v) { if (D == NULL) { printf("ERROR on insert"); exit(1); } // no duplicates if (getUnique(D) == 1) { if (lookup(D, k) == VAL_UNDEF) { Node A = D->root; Node temp = NULL; Node new = newNode(k, v); while (A != NULL) { temp = A; if (KEY_CMP(k, A->key) < 0) { A = A->left; } else if (KEY_CMP(k, A->key) > 0) { A = A->right; } } new->parent = temp; if (temp == NULL) { D->root = new; } else if (KEY_CMP(new->key, temp->key) < 0) { temp->left = new; } else { temp->right = new; } D->size++; } } else if (getUnique(D) == 0) { Node A = D->root; Node temp = NULL; Node new = newNode(k, v); while (A != NULL) { temp = A; if (KEY_CMP(k, A->key) < 0) { A = A->left; } else if (KEY_CMP(k, A->key) >= 0) { A = A->right; } } new->parent = temp; if (temp == NULL) { D->root = new; } else if (KEY_CMP(new->key, temp->key) < 0) { temp->left = new; } else { temp->right = new; } D->size++; } } // PROF TanTallo void delete (Dictionary D, KEY_TYPE k) { if (D == NULL) { printf("ERROR on delete"); exit(1); } if (lookup(D, k) != VAL_UNDEF) { Node A = D->root; Node P = NULL; while (A != NULL) { if (KEY_CMP(k, A->key) == 0) { break; } if (KEY_CMP(k, A->key) < 0) { A = A->left; } else { A = A->right; } } if (D->cursor == A) { D->cursor = NULL; } if (A == NULL) { printf("ERROR on delete"); exit(1); } if (A->left == NULL && A->right == NULL) { if (A == D->root) { D->root = NULL; freeNode(&A); } else { P = A->parent; if (P->right == A) { P->right = NULL; } else { P->left = NULL; } freeNode(&A); } } else if (A->right == NULL) { if (A == D->root) { D->root = A->left; freeNode(&A); } else { P = A->parent; if (P->right == A) { P->right = A->left; } else { P->left = A->left; } freeNode(&A); } } else if (A->left == NULL) { if (A == D->root) { D->root = A->right; freeNode(&A); } else { P = A->parent; if (P->right == A) { P->right = A->right; } else { P->left = A->right; } freeNode(&A); } } else { Node S = A->right; while (S->left != NULL) { S = S->left; } A->key = S->key; A->value = S->value; P = S->parent; if (P->right == S) { P->right = S->right; } else { P->left = S->right; } freeNode(&S); } D->size--; } } void makeEmpty(Dictionary D) { if (D == NULL) { fprintf(stderr, "ERROR on makeEmpty"); exit(1); } deleteAll(D->root); D->root = NULL; D->size = 0; D->cursor = NULL; } // set cursor at first smallest node VAL_TYPE beginForward(Dictionary D) { if (D == NULL) { printf("error on beginforward"); exit(1); } if (size(D) > 0) { Node A = D->root; while (A->left != NULL) { A = A->left; } D->cursor = A; return A->value; } return VAL_UNDEF; } // set cursor to last biggest node VAL_TYPE beginReverse(Dictionary D) { if (D == NULL) { printf("error on beginReverse"); exit(1); } if (size(D) > 0) { Node A = D->root; while (A->right != NULL) { A = A->right; } D->cursor = A; return A->value; } return VAL_UNDEF; } // cursor key KEY_TYPE currentKey(Dictionary D) { if (D == NULL) { printf("ERROR ON currentKEY"); exit(1); } if (D->cursor != NULL) { return D->cursor->key; } return KEY_UNDEF; } // cursor value VAL_TYPE currentVal(Dictionary D) { if (D == NULL) { printf("ERROR ON currentKEY"); exit(1); } if (D->cursor != NULL) { return D->cursor->value; } return VAL_UNDEF; } // move to next node from cursor VAL_TYPE next(Dictionary D) { if (D == NULL) { printf("ERROR on next"); exit(1); } if (D->cursor == NULL) { return VAL_UNDEF; } Node A = D->cursor; if (A->right != NULL) { Node current = A->right; while (current->left != NULL) { current = current->left; } D->cursor = current; return current->value; } Node temp = A->parent; while (temp != NULL && A == temp->right) { A = temp; temp = temp->parent; } if (temp == NULL) { D->cursor = NULL; return VAL_UNDEF; } D->cursor = temp; return temp->value; } // move prev node from cursor VAL_TYPE prev(Dictionary D) { if (D == NULL) { fprintf(stderr, "ERROR on prev"); exit(1); } if (D->cursor == NULL) { return VAL_UNDEF; } Node A = D->cursor; if (A->left != NULL) { Node current = A->left; while (current->right != NULL) { current = current->right; } D->cursor = current; return current->value; } Node temp = A->parent; while (temp != NULL && A == temp->left) { A = temp; temp = temp->parent; } if (temp == NULL) { D->cursor = temp; return VAL_UNDEF; } D->cursor = temp; return temp->value; } void printDictionary(FILE *out, Dictionary D) { if (D == NULL) { printf("ERRORon print"); exit(1); } beginForward(D); for (int i = 0; i < size(D); i++) { fprintf(out, "%s %d\n", currentKey(D), currentVal(D)); next(D); } }
C
/* The MIT License (MIT) Copyright (c) 2015 Mike Taghavi (mitghi) <mitghi@me.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <time.h> #include "pqueue.h" #define CHECK_COND(cond) if (__sync_bool_compare_and_swap(&cond,1,1)) break; #define SWAP_COND(cond,a,b) while(1){if (__sync_bool_compare_and_swap(&cond,a,b)) break; } volatile unsigned int cond = 0; void *consumer(void *arg){ Node *d = (Node *) malloc(sizeof(Data)); Priqueue *h = (Priqueue *)arg; usleep(10); for(;;){ d = priqueue_pop(h); if (d != NULL){ printf("\n %s %u\n",(char *)d->data->data,(unsigned int)pthread_self()); priqueue_node_free(h,d); } sched_yield(); CHECK_COND(cond); } } int main(){ pthread_t t; pthread_t t2; Priqueue *heap = priqueue_initialize(10); pthread_create(&t,NULL,consumer,(void *)heap); pthread_create(&t2,NULL,consumer,(void *)heap); Data *value = (Data *) malloc(sizeof(Data) * 100); unsigned int i; for(i = 0; i < 100; i++){ value[i].type = 1; value[i].data = (char *) malloc(6* sizeof(char *)); sprintf(value[i].data,"test %d.",i); priqueue_insert(heap,&value[i],i); } sleep(2); SWAP_COND(cond,0,1); pthread_join(t,NULL); pthread_join(t2,NULL); priqueue_free(heap); return 0; }
C
//求两个整数之和。 //解题思路,设置三个变量a和b用来存放两个整数,sum用来存放和数。用赋值运算符“=”把想加的结果传送给sum。 # include <stdio.h> //这是编译预处理指令 int main() //定义主函数 { //函数开始 int a,b,sum; //本行是程序的声明部分,定义a,b,sum为整形变量 a = 123; //对变量a赋值 b = 456; //对变量b赋值 sum = a + b; //进行a加b的运算,并把结果存放在变量sum中 printf("sum is %d\n",sum); //输出结果 return 0; //使函数返回值为0 } //函数结束
C
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** ioisr.c ** ** Beschrijving: ISR on PORTD demonstrattion ** Target: AVR mcu ** Build: avr-gcc -std=c99 -Wall -O3 -mmcu=atmega128 -D F_CPU=8000000UL -c ioisr.c ** avr-gcc -g -mmcu=atmega128 -o ioisr.elf ioisr.o ** avr-objcopy -O ihex ioisr.elf ioisr.hex ** or type 'make' ** Author: dkroeske@gmail.com ** -------------------------------------------------------------------------*/ #define F_CPU 8000000 #include <avr/io.h> #include <util/delay.h> #include <avr/interrupt.h> void wait(int ms); void display(int digit); int count2 = 0; const unsigned char Numbers[17] = { 0b00000001, 0b00000010, 0b00000100, 0b00001000, 0b00010000, 0b00100000, 0b00000000, 0b01111111, 0b00000001, 0b00100010, 0b00010100, 0b00001000, 0b01000000, 0b00000001, 0b00000000, 0b01111111, 0b00000000, }; /******************************************************************/ void wait( int ms ) { for (int i=0; i<ms; i++) { _delay_ms( 1 ); // library function (max 30 ms at 8MHz) } } /******************************************************************/ ISR( INT1_vect ) { //wait(10); //count2++; //if (PIND0 == 0 && PIND1 == 0) //{ //count2 = 0; //} } /******************************************************************/ ISR( INT2_vect ) { //wait(10); //count2++; //if (PIND0 == 0 && PIND1 == 0) //{ //count2 = 0; //} } void display(int digit) { switch (digit) { case 0: PORTB = Numbers[0]; break; case 1: PORTB = Numbers[1]; break; case 2: PORTB = Numbers[2]; break; case 3: PORTB = Numbers[3]; break; case 4: PORTB = Numbers[4]; break; case 5: PORTB = Numbers[5]; break; case 6: PORTB = Numbers[6]; break; case 7: PORTB = Numbers[7]; break; case 8: PORTB = Numbers[8]; break; case 9: PORTB = Numbers[9]; break; case 10: PORTB = Numbers[10]; break; case 11: PORTB = Numbers[11]; break; case 12: PORTB = Numbers[12]; break; case 13: PORTB = Numbers[13]; break; case 14: PORTB = Numbers[14]; break; case 15: PORTB = Numbers[15]; break; } } /******************************************************************/ int test( void ) //make this method main to run on itself /* short: main() loop, entry point of executable inputs: outputs: notes: Slow background task after init ISR Version : DMK, Initial code *******************************************************************/ { // Init I/O DDRB = 0xFF; //PORTB all output PORTB = 0x00; //PORTB all LED's off DDRC = 0xFF; // PORTC all output DDRD = 0xF0; // PORTD(7:4) output, PORTD(3:0) input // Init Interrupt hardware EICRA |= 0x2C; // INT1 falling edge, INT0 rising edge EIMSK |= 0x06; // Enable INT2 & INT1 // Enable global interrupt system //SREG = 0x80; // Of direct via SREG of via wrapper sei(); while (1) { PORTD ^= (1<<7); // Toggle PORTD.7 wait( 500 ); if(count2 >= 18) count2 = 0; display(count2); count2++; } return 1; }
C
/* Name:Vafaee, Ashkan UT EID : av28837 Section : 16320 EE312 - Assignment 5 */ // Node for Queue typedef struct q_node { long data; struct q_node* next; } q_node; typedef struct queue { int size; q_node* head; q_node* tail; } queue; /** * Allocates memory for an empty queue object using malloc, initializes it, * and returns a pointer to the created object. */ queue* queue_init(); /** * Returns the size of the queue */ int queue_size(queue* q); /** * Adds a new entry to the queue. The new node should be dynamically created first * using malloc. */ void enqueue(queue* q, long val); /** * Removes the first added node from the queue, and returns its value */ long dequeue(queue* q); /** * Inserts an entry at the specified index. The new node should be dynamically * created using malloc. */ void insert(queue* q, long val, int index); /** * Returns the position where data was found in the queue (integer within [0 ... size - 1]), * or -1 if not found. */ int queue_index_of(queue* s, long val); /** * Prints the queue as a comma-separated list (check PDF for format) */ void queue_print(queue* q);
C
/*++ Module Name: serv1.c. Abstract: This module implements the server side of the TCP connec -tion required for the "Content preserving server" . Revision History: Date : Sep 26 2012. Author : Unmesh Joshi (S-2515965). : Koustubha Bhat (S-2516144). VUnetID : uji300 : kbt350 Desc : Created. Owner : Koustubha Bhat --*/ //=================================================================== // Requirements //=================================================================== //1. Server maintains a counter and this is a persistent variable. //2. Server listens to client requests //3. Each client request is processed by incrementing the common pers // -istent counter. //4. Server sends the incremented counter value back to the client. //5. The counter value 0 is the initial one and is never given to an // actual client. Essentially counter value cannot be negative. //=================================================================== // Test Cases //=================================================================== // ///////////////////////////////////////////////////////////////////// // H E A D E R S. ///////////////////////////////////////////////////////////////////// #include <arpa/inet.h> #include <netinet/in.h> #include "common.h" ///////////////////////////////////////////////////////////////////// // M A C R O S. ///////////////////////////////////////////////////////////////////// // #define SERVER_PORT 9999 #define SERVER_TCP_BACKLOG 5 #define COUNTER_FILE "./serv1.counter.dat" #define LOG_FILE "./log.serv1.txt" ///////////////////////////////////////////////////////////////////// // S T R U C T U R E S ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // F U N C T I O N D E F I N T I O N S ///////////////////////////////////////////////////////////////////// // // This function is (almost) copy of writen() function Richar Stevens book // int Send (int socketId, const void *pData, size_t n) { int iLeft; const char *pchData; ssize_t bytesWritten = 0; iLeft = n; pchData = pData; while (iLeft > 0) { bytesWritten = write (socketId, pchData, iLeft); if (bytesWritten <= 0) { if (errno == EINTR) { bytesWritten = 0; } else { return -1; } } iLeft -= bytesWritten; pchData += bytesWritten; } return n; } int FetchCounterFromFile() { //Reads the file and gets the value of the counter. int iCounter=0; FILE *fp; fp = fopen(COUNTER_FILE, "r"); if (NULL == fp) { // improve logging return -1; } fscanf(fp, "%d", &iCounter); fclose(fp); return iCounter; } int UpdateCounterToFile(int value) { //Reads the file and gets the value of the counter. FILE *fp; fp = fopen(COUNTER_FILE, "w+"); if (NULL == fp) { // improve logging return -1; } fprintf(fp, "%d", value); fclose(fp); return 0; //return 0 or -1 for success or failure. } int DoWork() { int iRet, iCounter = 0; FILE *fp; iRet = access(COUNTER_FILE, F_OK); if ( 0 > iRet) { // lets create it. fp = fopen(COUNTER_FILE, "w"); if (NULL == fp) { Log("fopen failed", "DoWork", LOGLEVEL_ERROR, NULL); return -1; } fprintf(fp, "%d", 0); // initialize persistent counter to zero. fclose(fp); } // read the file to fetch the counter. iCounter = FetchCounterFromFile(); UpdateCounterToFile(++iCounter); return iCounter; } int main() { int iSock, iNewSock, iRet, iLastError, iCounter, iOpt_enable=1; socklen_t clientSockAddr_len; struct sockaddr_in servSockAddr, clientSockAddr; InitLogging(LOG_FILE); iSock = socket(AF_INET, SOCK_STREAM, 0); if ( 0 > iSock) { Log("socket creation failed", "main", LOGLEVEL_FATAL_ERROR, NULL); } iRet = setsockopt(iSock, SOL_SOCKET, SO_REUSEADDR, &iOpt_enable, sizeof(iOpt_enable)); // // Initialize the sockaddr_in structure // servSockAddr.sin_family = AF_INET; servSockAddr.sin_port = htons(SERVER_PORT); servSockAddr.sin_addr.s_addr = htonl(INADDR_ANY); // // Bind a port to the socket // iRet = bind(iSock, (struct sockaddr *) &servSockAddr, sizeof(servSockAddr) ); if (0 > iRet) { close(iSock); Log("bind failed", "main", LOGLEVEL_FATAL_ERROR, NULL); } // // Listen to the socket // iRet = listen(iSock, SERVER_TCP_BACKLOG); if (0 != iRet) { iLastError = errno; Log("listen failed", "main", LOGLEVEL_FATAL_ERROR, &iLastError); } //accept connection from a client while (1) { iNewSock = accept(iSock, (struct sockaddr *)&clientSockAddr, &clientSockAddr_len); iCounter = DoWork(); iRet = Send(iNewSock, &iCounter, sizeof(iCounter)); if ( 0 > iRet) { Log("Send failed", "main", LOGLEVEL_FATAL_ERROR, NULL); } printf("Sent the counter value %d to: %s\n", iCounter, inet_ntoa(clientSockAddr.sin_addr)); close(iNewSock); } close(iSock); DeInitLogging(); return 0; }
C
#include "SerialPort.h" #include "Utility.h" static SERIALMANAGER gs_stSerialManager; void kInitializeSerialPort(void){ WORD wPortBase; kInitializeMutex( &(gs_stSerialManager.stMutex)); wPortBase = SERIAL_PORT_COM1; // 인터럽트 비활성화 kOutPortByte(wPortBase+SERIAL_PORT_INDEX_INTERRUPTENABLE, 0); // 통신 속도를 115200 으로 설정 // 라인 제어 레지스터의 DLAB 비트를 1로 설정하여 제수 래치 레지스터에 접근 kOutPortByte(wPortBase+SERIAL_PORT_INDEX_LINECONTROL, SERIAL_LINECONTROL_DLAB); // lsb 제수 래치 레지스터에 재수의 하위 8비트를 전송 kOutPortByte(wPortBase+SERIAL_PORT_INDEX_DIVISORLATCHLSB, SERIAL_DIVISORLATCH_115200); // msb 제수 래치 레지스터에 재수의 하위 8비트를 전송 kOutPortByte(wPortBase+SERIAL_PORT_INDEX_DIVISORLATCHMSB, SERIAL_DIVISORLATCH_115200 >> 8); // 송수신 방법을 설정 // 라인 제어 레지스터에 통신 방법을 8비트, 패러티 사용x 설정 // 1 stop 비트로 설정하고, 제수 래치 레지스터 사용이 끝났으므로 dlab 비트를 0으로 설정 kOutPortByte(wPortBase+SERIAL_PORT_INDEX_LINECONTROL, SERIAL_LINECONTROL_8BIT | SERIAL_LINECONTROL_NOPARITY | SERIAL_LINECONTROL_1BITSTOP); // fifo 인터럽트 발생 시점을 14바이트로 설정 kOutPortByte(wPortBase+SERIAL_PORT_INDEX_FIFOCONTROL, SERIAL_LINECONTROL_8BIT | SERIAL_FIFOCONTROL_FIFOENABLE | SERIAL_FIFOCONTROL_14BYTEFIFO); } static BOOL kIsSerialTransmitterBufferEmpty(void){ BYTE bData; // 라인 상태 레지스터 읽은 뒤 TBE 비트 확인하여 // 송신 fifo 비어 잇는지 확인 bData = kInPortByte(SERIAL_PORT_COM1+SERIAL_PORT_INDEX_LINESTATUS); if( (bData & SERIAL_LINESTATUS_TRANSMITBUFFEREMPTY) == SERIAL_LINESTATUS_TRANSMITBUFFEREMPTY) return TRUE; return FALSE; } void kSendSerialData(BYTE* pbBuffer, int iSize){ // 보낸 양 저장 int iSentByte; // 한 번 보낼 때 임시 사이즈 저장 int iTempSize; int i; kLock( &(gs_stSerialManager.stMutex)); // 요청한 바이트 수만큼 보낼때까지 반복 iSentByte = 0; while(iSentByte < iSize){ // 송신 FIFO에 데이터가 남아있다면 다 전송될때까지 대기 while(kIsSerialTransmitterBufferEmpty() == FALSE) kSleep(0); // 전송할 데이터 중에서 남은 크기와 fifo 최대 크기비교후 작은것을 선택하여 송신 시리얼 포트를 채움 iTempSize = MIN(iSize - iSentByte, SERIAL_FIFOMAXSIZE); for(i=0; i<iTempSize; i++) kOutPortByte(SERIAL_PORT_COM1+SERIAL_PORT_INDEX_TRANSMITBUFFER, pbBuffer[iSentByte+i]); iSentByte += iTempSize; } kUnlock( &(gs_stSerialManager.stMutex)); } static BOOL kIsSerialRecevieBufferFull(void){ BYTE bData; bData = kInPortByte(SERIAL_PORT_COM1+SERIAL_PORT_INDEX_LINESTATUS); if( (bData & SERIAL_LINESTATUS_RECEIVEDDATAREADY) == SERIAL_LINESTATUS_RECEIVEDDATAREADY) return TRUE; return FALSE; } int kReceivesSerialData(BYTE* pbBuffer, int iSize){ int i; kLock( &(gs_stSerialManager.stMutex)); for(i=0; i<iSize; i++){ if(kIsSerialRecevieBufferFull() == FALSE) break; pbBuffer[i] = kInPortByte(SERIAL_PORT_COM1+SERIAL_PORT_INDEX_RECEIVEBUFFER); } kUnlock( &(gs_stSerialManager.stMutex)); return i; } void kClearSerialFIFO(void){ kLock( &(gs_stSerialManager.stMutex)); kOutPortByte(SERIAL_PORT_COM1+SERIAL_PORT_INDEX_FIFOCONTROL, SERIAL_FIFOCONTROL_FIFOENABLE | SERIAL_FIFOCONTROL_14BYTEFIFO | SERIAL_FIFOCONTROL_CLEARRECEIVEFIFO | SERIAL_FIFOCONTROL_CLEARTRANSMITFIFO); kUnlock( &(gs_stSerialManager.stMutex)); }
C
#include <stdio.h> #include <stdlib.h> /* There is no suggested solution for part i * (the registry command line) of this exercise. * * For a similar example, have a look at the * 'gull' program (gull/cli.c) * * The below code demonstrates an "object oriented" * coding style in C, based on struct pointers. * */ #define REGISTRY_MAX 100 typedef struct { short age; char *name; } person_t; typedef struct { unsigned int size, maxsize; person_t **people; } registry_t; /* Person */ person_t *Person_new(char *name, short age) { person_t *person; person = malloc(sizeof(person_t)); person->name = name; person->age = age; return person; } void Person_birthday(person_t *person) { person->age++; } void Person_inspect(person_t *person) { printf("%s (%d)\n", person->name, person->age); } void Person_free(person_t *person) { free(person); } /* Registry: */ registry_t *Registry_new(int maxsize) { registry_t *registry; registry = malloc(sizeof(registry_t)); registry->maxsize = maxsize; registry->size = 0; registry->people = malloc(sizeof(person_t) * maxsize); return registry; } int Registry_add(registry_t *registry, person_t *person) { if (registry->size < registry->maxsize) { registry->people[registry->size++] = person; return 1; } else { return 0; } } void Registry_inspect(registry_t *registry) { int i; for (i = 0; i < registry->size; i++) { Person_inspect(registry->people[i]); } } void Registry_free_all(registry_t *registry) { int i; for (i = 0; i < registry->size; i++) { Person_free(registry->people[i]); } free(registry->people); free(registry); } int main(int argc, const char *argv[]) { registry_t *registry; registry = Registry_new(REGISTRY_MAX); Registry_add(registry, Person_new("Gunnar", 40)); Registry_add(registry, Person_new("Lene", 28)); Registry_add(registry, Person_new("Rui", 21)); Registry_add(registry, Person_new("Eva", 61)); Person_birthday(registry->people[0]); Registry_inspect(registry); Registry_free_all(registry); return 0; }
C
/** * @file engine.h * @author Arthur Bouvier (a.bouvier) * @brief Main Engine * @course GAM100F18 * Copyright 2018 DigiPen (USA) Corporation * @addtogroup Util * @{ */ #pragma once #include <stdbool.h> #include <C_Processing.h> #include "gamelayer.h" typedef bool (*CollCheckFunc)(Component*, Component*); ///< @brief Collision checking function signature typedef void (*CollResolveFunc)(Component*, Component*); ///< @brief Collision resolving function signature typedef void (*KeyCallbackFunc)(Key, KeyState, void*); typedef void (*MouseCallbackFunc)(MouseButton, KeyState, void*); typedef void (*WheelCallbackFunc)(float, float); /** * @brief Contains Engine data */ typedef struct Engine { List *gLayers; ///< @brief List of GameLayer s unsigned firstUpdate; ///< @brief Index of first GameLayer to update unsigned firstDraw; ///< @brief Index of first GameLayer to draw List *collChecks; ///< @brief 2D List of collision checking functions List *collResolves; /**< @brief 2D List of collision resolving functions * 2D List s looks like this: * type2 * Comp type | 1 | 2 | 3 | * 1 | func | | | * type1 2 | func | func | | * 3 | func | func | func | */ List *keyCallbacks; List *mouseCallbacks; List *wheelCallbacks; } Engine; extern Engine *engine; ///< @brief The primary game Engine object (must be initialized & deleted) /** * @brief Initialize the Engine * @param numLayers Starting number of layers */ void Engine_init(unsigned numLayers); /** * @brief Delete Engine */ void Engine_delete(); /** * @brief Update Engine */ void Engine_update(); /** * @brief Initialize GameLayer * @param layerNum GameLayer index in array * @param updateLower Update lower layers * @param drawLower Draw lower layers */ void Engine_initLayer(unsigned layerNum, bool updateLower, bool drawLower); /** * @brief Delete GameLayer * @param layerNum GameLayer index in array */ void Engine_deleteLayer(unsigned layerNum); /** * @brief Get a GameLayer * @param layerNum GameLayer index in array * @return GameLayer at given index */ GameLayer *Engine_getLayer(unsigned layerNum); /** * @brief Initialize list of collision checking & resolving functions * @param numComps Total number of Component s */ void Engine_initCollFuncList(unsigned numComps); /** * @brief Add a collision checking function to the list * @param type1 Type of first Component * @param type2 Type of second Component * @param func Collision checking function */ void Engine_addCollCheckFunc(unsigned type1, unsigned type2, CollCheckFunc func); /** * @brief Get a collision checking function from the list * @param type1 Type of first Component * @param type2 Type of second Component * @return Collision checking function */ CollCheckFunc Engine_getCollCheckFunc(unsigned type1, unsigned type2); /** * @brief Add a collision resolving function to the list * @param type1 Type of first Component * @param type2 Type of second Component * @param func Collision resolving function */ void Engine_addCollResolveFunc(unsigned type1, unsigned type2, CollResolveFunc func); /** * @brief Get a collision resolving function from the list * @param type1 Type of first Component * @param type2 Type of second Component * @return Collision resolving function */ CollResolveFunc Engine_getCollResolveFunc(unsigned type1, unsigned type2); void Engine_addKeyCallback(KeyCallbackFunc func, void *upvalue); void Engine_removeKeyCallback(KeyCallbackFunc func, void *upvalue); void Engine_addMouseCallback(MouseCallbackFunc func, void *upvalue); void Engine_removeMouseCallback(MouseCallbackFunc func, void *upvalue); void Engine_addWheelCallback(WheelCallbackFunc func, void *upvalue); void Engine_removeWheelCallback(WheelCallbackFunc func, void *upvalue); /// @}
C
#include "stdafx.h" /*************************************************************************************/ // Funkcja wczytuje dane obrazu zapisanego w formacie TGA w pliku o nazwie // FileName, alokuje pami i zwraca wskanik (pBits) do bufora w ktrym // umieszczone s dane. // Ponadto udostpnia szeroko (ImWidth), wysoko (ImHeight) obrazu // tekstury oraz dane opisujce format obrazu wedug specyfikacji OpenGL // (ImComponents) i (ImFormat). // Jest to bardzo uproszczona wersja funkcji wczytujcej dane z pliku TGA. // Dziaa tylko dla obrazw wykorzystujcych 8, 24, or 32 bitowy kolor. // Nie obsuguje plikw w formacie TGA kodowanych z kompresj RLE. /*************************************************************************************/ GLbyte *LoadTGAImage(const char *FileName, GLint *ImWidth, GLint *ImHeight, GLint *ImComponents, GLenum *ImFormat) { /*************************************************************************************/ // Struktura dla nagwka pliku TGA #pragma pack(1) typedef struct { GLbyte idlength; GLbyte colormaptype; GLbyte datatypecode; unsigned short colormapstart; unsigned short colormaplength; unsigned char colormapdepth; unsigned short x_orgin; unsigned short y_orgin; unsigned short width; unsigned short height; GLbyte bitsperpixel; GLbyte descriptor; }TGAHEADER; #pragma pack(8) FILE *pFile = NULL; TGAHEADER tgaHeader; unsigned long lImageSize; short sDepth; GLbyte *pbitsperpixel = NULL; /*************************************************************************************/ // Wartoci domylne zwracane w przypadku bdu *ImWidth = 0; *ImHeight = 0; *ImFormat = GL_BGR_EXT; *ImComponents = GL_RGB8; pFile = fopen(FileName, "rb"); if (pFile != NULL) { /*************************************************************************************/ // Przeczytanie nagwka pliku fread(&tgaHeader, sizeof(TGAHEADER), 1, pFile); /*************************************************************************************/ // Odczytanie szerokoci, wysokoci i gbi obrazu *ImWidth = tgaHeader.width; *ImHeight = tgaHeader.height; sDepth = tgaHeader.bitsperpixel / 8; /*************************************************************************************/ // Sprawdzenie, czy gbia spenia zaoone warunki (8, 24, lub 32 bity) if (tgaHeader.bitsperpixel != 8 && tgaHeader.bitsperpixel != 24 && tgaHeader.bitsperpixel != 32) { pbitsperpixel = NULL; } else { /*************************************************************************************/ // Obliczenie rozmiaru bufora w pamici lImageSize = tgaHeader.width * tgaHeader.height * sDepth; /*************************************************************************************/ // Alokacja pamici dla danych obrazu pbitsperpixel = (GLbyte*)malloc(lImageSize * sizeof(GLbyte)); if (pbitsperpixel != NULL) { if (fread(pbitsperpixel, lImageSize, 1, pFile) != 1) { free(pbitsperpixel); pbitsperpixel = NULL; } else { /*************************************************************************************/ // Ustawienie formatu OpenGL switch (sDepth) { case 3: *ImFormat = GL_BGR_EXT; *ImComponents = GL_RGB8; break; case 4: *ImFormat = GL_BGRA_EXT; *ImComponents = GL_RGBA8; break; case 1: *ImFormat = GL_LUMINANCE; *ImComponents = GL_LUMINANCE8; break; }; } } } fclose(pFile); } return pbitsperpixel; } /*************************************************************************************/
C
/** * *cap_string - capitalises every first letter of words in a string * @s: string to capitalise * * Return: capitalized string */ char *cap_string(char *s) { int i; for (i = 0; s[i] != '\0'; i++) { /*Account for first character*/ if (s[0] >= 97 && s[0] <= 122) s[0] = s[0] - 32; /* Check for separating characters */ if (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == ',' || s[i] == ';' || s[i] == '.' || s[i] == '!' || s[i] == '?' || s[i] == '"' || s[i] == '(' || s[i] == ')' || s[i] == '{' || s[i] == '}') { /* Capitalise the first letter after the separator */ if (s[i + 1] >= 97 && s[i + 1] <= 122) { s[i + 1] = s[i + 1] - 32; } } } return (s); }
C
/* * common.c - contains common functions used in 'solve.c' and 'create.c' * * Andrew Truong, Mark Gitau, Jeff Gitahi, Ryan Wu, CS50 Spring 2020 */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include <ctype.h> #define n 9 /************copy() - makes a copy of a grid*************************/ void copy(int puzzleCopy[n][n], int puzzle[n][n]) { for (int row = 0; row < n; row ++) { for (int column = 0; column < n; column ++) puzzleCopy[row][column] = puzzle[row][column]; } } /**************clear() - clears a grid by zeroing it out************/ void clear(int puzzle[n][n]) { for (int row = 0; row < n; row ++) { for (int column = 0; column < n; column ++) puzzle[row][column] = 0; } } /**********printGrid() - prints the given grid to stdout**************/ void printGrid(int grid[n][n]){ for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ fprintf(stdout, "%d ", grid[i][j]); } fprintf(stdout, "\n"); } } /********isValidInsert() - checks whether inserting a number in a certain location is legal*********/ bool isValidInsert(int grid[n][n], int row, int col, int num){ // check if the number exists elsewhere in the same row for (int i = 0; i < n; i++){ if (i != col && grid[row][i] == num){ return false; } } // check if the number exists elsewhere in the same column for (int i = 0; i < n; i++){ if (i != row && grid[i][col] == num){ return false; } } // check if the number exists elsewhere in the 3 x 3 grid int startRow = row - (row % 3); // starting row of the 3 x 3 grid int startCol = col - (col % 3); // starting column of the 3 x 3 grid for (int i = startRow; i < startRow + 3; i++){ for (int j = startCol; j < startCol + 3; j++){ if (i != row && j != col && grid[i][j] == num){ return false; } } } return true; } /********isValidPuzzle() - checks whether all the numbers in the grid obey sudoku rules*********/ bool isValidPuzzle (int puzzle[n][n]){ //loop through each value in the puzzle for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ //if the value is 0 or if it doesn't meet the requirements of isValidInsert, then it's a non-valid puzzle if (!isValidInsert(puzzle, i, j, puzzle[i][j]) || puzzle[i][j]==0){ return false; } } } return true; } /***********readPuzzle() - reads in a grid from stdin****************/ void readPuzzle (int input[n][n]){ int num; // number that has been read char c; int numCount = 0; // count of numbers read so far int i = 0, j = 0; // row and column while ((c = fgetc(stdin)) != EOF && numCount < (n * n)){ // if it's an integer, insert it in input[i][j] if ((num = atoi(&c)) != 0){ input[i][j] = num; } // if we have read a digit in the last column, increment row and wrap column back to 0 if (isdigit(c) != 0){ if (j + 1 == n){ i++; } j = (j + 1) % n; numCount++; // increment number of numbers read so far } } }
C
#include<stdio.h> #include<stdlib.h> #include<time.h> #define FMIN 180 /*numero minimo di figurine*/ #define FMAX 220 /*numero massimo di figurine*/ #define FPMIN 4 /*numero minimo di figurine per pacchetto*/ #define FPMAX 7 /*numero massimo di figurine per pacchetto*/ #define SCAMBISI 1 #define SCAMBINO 2 int getInt(char*,int,int); int uniforme(int,int); int packet(int*,int,int,int); void update(int*,int*,int); int check(int*,int); int doppioni(int*,int); void exchange(int*,int*,int); int controlla(int*,int); void scambio(int*,int*,int,int); int main() { int paolo[FMAX]={0}; int pietro[FMAX]={0}; int pacchetto[FPMAX]={0}; int nfig,nfpacchetto,scelta; /*npietro e npaolo sono i pacchetti comprati dai due collezionisti*/ int npaolo=0, npietro=0; srand48(time(0)); printf("\n\nSimulazione due bambini che completano album di figurine\n"); nfig=getInt("numero figurine per album ",FMIN,FMAX); scelta=getInt("\n1 se i bambini possono scambiarsi le figurine\n2 se non possono\n",SCAMBISI,SCAMBINO); do { /*se l'album di paolo non e finito, paolo compra pacchetto e aggiorna l'album*/ if ( check(paolo,nfig)==0 ) { nfpacchetto=packet(pacchetto,FPMIN,FPMAX,nfig); npaolo++; update(paolo,pacchetto,nfpacchetto); } /*se l'album di pietro non e finito, pietro compra pacchetto e aggiorna l'album*/ if ( check(pietro,nfig)==0 ) { nfpacchetto=packet(pacchetto,FPMIN,FPMAX,nfig); npietro++; update(pietro,pacchetto,nfpacchetto); } /*se scambi si e album non finiti, scambio figurine*/ if(scelta==SCAMBISI && check(pietro,nfig)==0 && check(paolo,nfig)==0) { exchange(pietro,paolo,nfig); } /*continua il ciclo fino a che pietro e paolo non hanno entrambi finito*/ } while ( check(paolo,nfig)!=1 || check(pietro,nfig)!=1); printf("\nAlbum di paolo: \nNumero di doppioni rimasti: %d \nNumero di pacchetti acquistati [ovvero costo pacchetti]: %d\n",doppioni(paolo,nfig),npaolo); printf("\nAlbum di pietro: \nNumero di doppioni rimasti: %d \nNumero di pacchetti acquistati [ovvero costo pacchetti]: %d\n",doppioni(pietro,nfig),npietro); exit(0); } int getInt(char *mess,int min,int max) { int n; do { printf("\nInserire %stra %d e %d: ",mess,min,max); scanf("%d",&n); if(n>max||n<min) printf("Valore non valido"); } while(n>max||n<min); return n; } int uniforme(int min,int max) { return (lrand48()%(max-min+1)+min); } int packet(int *pacchetto,int min, int max,int nfig) { int nf,i=0; nf=uniforme(min,max); do { for(i=0;i<nf;i++) { *(pacchetto+i)=uniforme(0,nfig-1); } }while(controlla(pacchetto,nf)==1); return nf; } /*"controlla" controlla che non ci siano doppioni nel pacchetto*/ int controlla(int *packet,int nf) { int j=0,control=0,i; do { i=nf-1; do { if(*(packet+i)==*(packet+j)) control=1; i--; }while(i>j && control!=1); j++; }while(j<nf-1 && control!=1); return control; } void update ( int *album,int *pacchetto, int nf) { int k; for (k=0; k< nf; k++ ) { *(album+ (*(pacchetto+k)))+=1; } } int check(int *album,int nfig) { int i=0,controlla=1; do { if(*(album+i)==0) controlla=0; i++; }while(i<nfig && controlla==1); return controlla; } int doppioni(int *album, int nfig) { int doppi=0,i; for (i=0; i < nfig; i++) { if ( *(album+i)>= 2) doppi+= *(album+i)-1; } return doppi; } /* exchange controlla se un album ha doppioni della i-esima figurina e l'altro non ha quella figurina * * della i-esima figurina. In questo caso, controlla tra le figurine successive se vi sono doppioni che * * mancano all'altro (figurina j-esima nella funzione scambio). Se anche cio e verificato, allora scambia* * la figurina i-esima con la j-esima*/ void exchange(int *paolo,int *pietro,int nfig) { int i; for(i=0;i<nfig;i++) { if(*(paolo+i)>=2 && *(pietro+i)==0) { scambio(paolo,pietro,nfig,i); } else if(*(paolo+i)==0 && *(pietro+i)>=2) { scambio(pietro,paolo,nfig,i); } } } void scambio(int *album1,int *album2,int nfig,int i) { int j,cond=0; j=i+1; do { if(*(album1+j)==0 && *(album2+j)>=2) { *(album1+j)+=1; *(album2+j)-=1; *(album1+i)-=1; *(album2+i)+=1; cond=1; } j++; }while(cond!=1 && j<nfig); }
C
//Circular LinkedList /*Includes*/ #include <stdio.h> #include <stdlib.h> /*Node*/ struct Node{ int data; struct Node* next; }; /*This function traverses the linkedlist*/ void printlist(struct Node* n){ struct Node* temp= n; if(n!=NULL) { do{ printf("%d ",n->data); n=n->next; } while(n!=temp); } } /*This function creates a new head node for linkedlist*/ void insert_first(struct Node** n,int value){ struct Node* n1=*n; struct Node* new_head=(struct Node*)malloc(sizeof(struct Node)); new_head->data=value; new_head->next=n1; *n=new_head; struct Node* temp=n1; while((n1->next)!=temp){ n1=n1->next; } n1->next=new_head; } /*This function creates a new end node for linkedlist*/ void insert_end(struct Node *n,int value){ struct Node* temp=n; struct Node* end= (struct Node*)malloc(sizeof(struct Node)); end->data=value; end->next=temp; while((n->next)!=temp){ n=n->next; } n->next=end; } /*This function inserts a new node after a given value*/ void insert_after_value(struct Node* n,int value,int new_value){ struct Node* temp=n; struct Node* temp2= (struct Node*)malloc(sizeof(struct Node)); struct Node* temp3=NULL; if(n==NULL) return; while((n->data)!=value){ n=n->next; } temp3=n->next; n->next=temp2; temp2->data=new_value; temp2->next=temp3; } /*This function inserts a new node at given position*/ void insert_at_position(struct Node** n,int position,int new_value){ struct Node* n1=*n; struct Node* temp=n1; struct Node* new_node=(struct Node*)malloc(sizeof(struct Node)); struct Node* temp2=NULL; new_node->data=new_value; if(position==0){ insert_first(&n1,new_value); *n=n1; return; } int length=find_length(n1); int count=0; if(position<=(length-1)){ while(count!=position-1){ n1=n1->next; count++; } temp2=n1->next; n1->next=new_node; new_node->next=temp2; *n=temp; } } /*This function finds the length of linked list*/ int find_length(struct Node *n){ struct Node* temp =n; int length=0; if(n==NULL){ length=0; } else{ n=n->next; length=1; } while(n!=temp){ length++; n=n->next; } return length; } /*This function splits the linkedlistin two halves*/ struct Node* split(struct Node* n){ int length=find_length(n); struct Node* temp=NULL; struct Node* temp2=n; struct Node* temp3=NULL; if(length % 2==0) length=length/2; else length=(length/2)+1; int count=0; if(length<2) return; while(length!=(count+1)){ count++; n=n->next; } if(length==(count+1)){ temp3=n->next; n->next=temp2; } struct Node* n2=temp3; while((n2->next)!=temp2){ n2=n2->next; } n2->next=temp3; return temp3; } int main() { /*Node pointers and dynamic memory allocation*/ struct Node* head=(struct Node*)malloc(sizeof(struct Node)); struct Node* second=(struct Node*)malloc(sizeof(struct Node)); struct Node* third=(struct Node*)malloc(sizeof(struct Node)); /*Linkedlist create*/ head->data=3; head->next=second; second->data=6; second->next=third; third->data=9; third->next=head; printf("\nTraversing the linkedlist\n"); printlist(head); int value1=1; printf("\nInserting %d at front\n",value1); insert_first(&head,value1); printlist(head); int value2=2; printf("\nInserting %d at end\n",value2); insert_end(head,value2); printlist(head); int length; length=find_length(head); printf("\nThe length of circulr linkedlist is %d\n",length); int value3=9; int value4=0; printf("\nInserting %d after %d value\n",value4,value3); insert_after_value(head,value3,value4); printlist(head); int value5=5; int position=5; printf("\nInserting %d at position %d\n",value5,position); insert_at_position(&head,position,value5); printlist(head); printf("\nSplitting the circular linkedlist\n"); struct Node* new_head=split(head); printlist(head); printf("\n"); printlist(new_head); }
C
/* This file is part of the reduma package. Copyright (C) * 1988, 1989, 1992, 1993 University of Kiel. You may copy, * distribute, and modify it freely as long as you preserve this copyright * and permission notice. */ /*****************************************************************************/ /* MODUL zur Darstellung von Stackelementen in Strings und auf Files */ /*-------------------------------------------------------------------------- */ /* rprint.c -- external: printstel - calls prstel */ /* s_prstel - calls prstel */ /* prstel - calls prstrstel */ /* -- internal: prstrstel - calls prnconstr, prnsingleatom */ /* prnconstr */ /* prnsingleatom */ /*****************************************************************************/ #if DEBUG #include "rstdinc.h" #include "rstackty.h" #include "rheapty.h" #include "rstelem.h" #include "rextern.h" #include "rmeasure.h" #include "case.h" #define CTRLSTR1 " %-10.10s" /* fuer DEMO */ #define CTRLSTR2 " %-.4s(%4d)" /* fuer DEMO */ #define CTRLSTR3 " %-.4s(%1d,%2d)" /* fuer DEMO */ #define CTRLSTR4 " #%8.8x " /* fuer DEMO */ #define PRNTEST(x,pname,vname ) ((x.element & pname) == vname ) #define UNDEF 0x00000c01 #define SHORT 1 typedef union { int element; struct #if ODDSEX { char class; char edit_info; short value; } #else { short value; char edit_info; char class; } #endif feld; } I_STACKELEM; /*------------------------------------------------------------------------ * Lokal verwendete globale Variablen: *------------------------------------------------------------------------ */ static char line[133]; /* Die gewuenschte Stackelementbeschreibung */ static char hilf[133]; /* Ein Hilfsstring zum Aufbau von 'line'. */ /*$P */ /*********************************************************************/ /* */ /* Die externen Funktionen: */ /* */ /*********************************************************************/ /*----------------------------------------------------------------------- * prstel -- eine kurze oder lange Beschreibung eines Stackelementes * wird auf einen File geschrieben. * parameter: XFile - der Filepointer, * Conv - das Stackelement, * Flag - bei Flag gleich eins gibt es eine kurze Beschreibung, * sonst eine Lange * calls: prstrstel. *------------------------------------------------------------------------- */ prstel (XFile, Conv, Flag) FILE * XFile; int Conv; int Flag; { prstrstel (Conv, Flag); fprintf (XFile ,"%s", line); } /*----------------------------------------------------------------------- * s_prstel -- eine kurze oder lange Beschreibung eines Stackelementes * wird in einen String geschrieben. * parameter: Xline - der Stringanfang, * Conv - das Stackelement, * Flag - bei Flag gleich eins gibt es eine kurze Beschreibung, * sonst eine Lange * calls: prstrstel. *------------------------------------------------------------------------- */ s_prstel (Xline, Conv, Flag) char * Xline; int Conv; int Flag; { prstrstel (Conv, Flag); sprintf (Xline, "%s", line); } /*----------------------------------------------------------------------- * printstel -- eine kurze oder lange Beschreibung eines Stackelementes * wird auf 'stdout' geschrieben. * parameter: Conv - das Stackelement, * Flag - bei Flag gleich eins gibt es eine kurze Beschreibung, * sonst eine Lange * calls: prstrstel. *------------------------------------------------------------------------- */ printstel (Conv, flag) int Conv; int flag; /* nur name falls 1 */ { prstel (stdout, Conv, flag); fflush(stdout); /* damit der Puffer geleert wird */ } /****************************************************************************/ /* */ /* Nur intern verwendete Hilffunktionen. */ /* */ /****************************************************************************/ /*--------------------------------------------------------------------------- * prstrstel -- steuert die Stackelementidentifizierung. Die endgueltige * Beschreibung des Stackelementes steht bei Ende des Moduls * in 'line'. * parameter: Conv - das Stackelement, * flag - kurze oder lange Beschreibung ? * calls: prnconstr, prnsingleatom. * comment: prstrstel verwendet die Struktur I_STACKELEM, um so einfach * an die Elementinformationen zu kommen. *--------------------------------------------------------------------------- */ static prstrstel (Conv, flag) int Conv; int flag; /* nur name falls 1 */ { I_STACKELEM Top; hilf[0] = line[0] = '\0'; Top.element = Conv ; /* Konvertierung eines Stackelementes in eine Struktur */ /* 1. Fall: Das Stackelement UNDEF */ if (Conv == UNDEF) if (flag != SHORT) { sprintf (hilf, "@0x%-8.8x U N D E F \n" ,Top.element); strcat (line, hilf); return; } else { sprintf (hilf, CTRLSTR1, "U N D E F"); strcat (line, hilf); return; } /* 2. Fall: Das Stackelement ist ein Pointer */ if (PRNTEST (Top, P_POINTER, POINTER)) if (flag != SHORT) { sprintf (hilf, "@0x%-8.8x Pointer \n" ,Top.element); strcat (line, hilf); return; } else { sprintf (hilf, CTRLSTR4, (Top.element)); strcat (line, hilf); return; } /* 3. Fall: kein Pointer und nicht UNDEF */ if (flag != SHORT) { /* zusaetzlich wird das editfeld und das valuefeld mit ausgegeben */ sprintf (hilf, " 0x%8.8x ", Top.element); strcat (line, hilf); sprintf (hilf, "Edit:%-5d Value:", Top.feld.edit_info); strcat (line, hilf); if (Top.feld.value >= 0) { sprintf (hilf, "+"); strcat (line, hilf); sprintf (hilf, "%-8d", Top.feld.value); strcat (line, hilf); } else { sprintf (hilf, "-"); strcat (line, hilf); sprintf (hilf, "%-8d", -Top.feld.value); strcat (line, hilf); } } Top.element = Conv & (~F_EDIT) /* alles bis auf edit */; /* die grosse Fallunterscheidung: */ if (PRNTEST (Top, P_CON, CON)) prnconstr (Top, flag); else if (PRNTEST (Top, P_SA, SA)) prnsingleatom (Top, flag); else prnstring (Top, flag); if (flag != SHORT) { sprintf (hilf, "%s", " \n"); strcat (line, hilf); } } /*--------------------------------------------------------------------------- * prnconstr -- bereitet einen Konstruktor auf. * parameter: Top - das Stackelement (breits als Struktur) * flag - kurze oder lange Beschreibung ? *--------------------------------------------------------------------------- */ static prnconstr (Top, flag) I_STACKELEM Top; int flag; { I_STACKELEM temp; temp = Top; /* warum weiss keiner so genau, vielleicht fuer NC-Compiler */ if (flag != SHORT) { if ((temp.element & P_VAR_CONSTR) == VAR_CONSTR) { sprintf (hilf, " var "); strcat (line, hilf); if ((temp.element & P_CHAINED_CONSTR) == CHAINED_CONSTR) { sprintf (hilf, "chained "); strcat (line, hilf); } else { sprintf (hilf, "no-chain"); strcat (line, hilf); } } else { sprintf (hilf, " fix "); strcat (line, hilf); if ((temp.element & P_CHAINED_CONSTR) == GROUP1_FIXCON) sprintf (hilf, "group1 "); else sprintf (hilf, "group2 "); strcat (line, hilf); } } /* ein Var- oder Fixconstruktor ? */ if (((temp.element) & P_VAR_CCONSTR) == VAR_CCONSTR) switch ((temp.element & F_CONSTR_NAME) >> O_CONSTR_NAME) { case _PM_GUARD: sprintf (hilf, CTRLSTR2, "GUARD ", ARITY (temp.element)); strcat (line, hilf); return; case _PM_EAGER: sprintf (hilf, CTRLSTR2, "EAGER ", ARITY (temp.element)); strcat (line, hilf); return; case _PM_NOMAT: sprintf (hilf, CTRLSTR2, "NOMAT ", ARITY (temp.element)); strcat (line, hilf); return; case _PM_EREC: sprintf (hilf, CTRLSTR2, "EREC ", ARITY (temp.element)); strcat (line, hilf); return; } else if (((temp.element) & P_VAR_CONSTR) == VAR_CONSTR) switch ((temp.element & F_CONSTR_NAME) >> O_CONSTR_NAME) { case _AP: sprintf (hilf, CTRLSTR2, "Apply ", ARITY (temp.element)); strcat (line, hilf); return; case _SNAP: sprintf (hilf, CTRLSTR2, "Snap ", ARITY (temp.element)); strcat (line, hilf); return; case _AP_TIC: /* not used in husch-version */ sprintf (hilf, CTRLSTR2, "Ap_tic ", ARITY (temp.element)); strcat (line, hilf); return; case _SUB: sprintf (hilf, CTRLSTR2, "Sub ", ARITY (temp.element)); strcat (line, hilf); return; case _CAP: sprintf (hilf, CTRLSTR2, "CAP ", ARITY (temp.element)); strcat (line, hilf); return; case _SUBPOST: /* not used in husch-version */ sprintf (hilf, CTRLSTR2, "Subpost", ARITY (temp.element)); strcat (line, hilf); return; case _LIST: sprintf (hilf, CTRLSTR2, "List ", ARITY (temp.element)); strcat (line, hilf); return; case _MATRIX: sprintf (hilf, CTRLSTR2, "Matrix ", ARITY (temp.element)); strcat (line, hilf); return; /* H */ case _PM_SWITCH: /* pattern - match */ sprintf (hilf, CTRLSTR2, "Case ", ARITY (temp.element)); strcat (line, hilf); return; case _PM_AS: /* pattern - match */ /* is a fix-constructor */ sprintf (hilf, CTRLSTR3, "As ", ARITY (temp.element), 2); strcat (line, hilf); return; case _PM_LIST: /* pattern - match */ sprintf (hilf, CTRLSTR3, "Plist ", ARITY (temp.element), 2); strcat (line, hilf); return; case _PM_REC: sprintf (hilf, CTRLSTR2, "PM_REC ", ARITY (temp.element)); strcat (line, hilf); return; case _PM_NCASE: sprintf (hilf, CTRLSTR2, "NCASE ", ARITY (temp.element)); strcat (line, hilf); return; case _PM_FCASE: sprintf (hilf, CTRLSTR2, "FCASE ", ARITY (temp.element)); strcat (line, hilf); return; case _PM_ECASE: sprintf (hilf, CTRLSTR2, "ECASE ", ARITY (temp.element)); strcat (line, hilf); return; /* CS */ case _LREC: sprintf (hilf, CTRLSTR2, "Lrec ", ARITY (temp.element)); strcat (line, hilf); break; default: sprintf (hilf, CTRLSTR2, "var-con?", ARITY (temp.element)); strcat (line, hilf); return; } else { /* fix constr */ if ((temp.element & P_UNCHAINED_CONSTR) == GROUP1_FIXCON) switch ((temp.element & F_CONSTR_NAME) >> O_CONSTR_NAME) { case _PRELIST: sprintf (hilf, CTRLSTR3, "Prelist", ARITY (temp.element), 2); strcat (line, hilf); return; case _PROTECT: sprintf (hilf, CTRLSTR3, "Protect", ARITY (temp.element), 1); strcat (line, hilf); return; case _PLUS: sprintf (hilf, CTRLSTR3, "Plus ", ARITY (temp.element), 1); strcat (line, hilf); return; case _MINUS: sprintf (hilf, CTRLSTR3, "Minus ", ARITY (temp.element), 1); strcat (line, hilf); return; case _SET: /* not used in husch-version */ sprintf (hilf, CTRLSTR3, "Set ", ARITY (temp.element), 1); strcat (line, hilf); return; case _COND: sprintf (hilf, CTRLSTR3, "Cond ", ARITY (temp.element), 2); strcat (line, hilf); return; case _EXP: /* Exponent ==> 1e10 */ sprintf (hilf, CTRLSTR3, "Expo ", ARITY (temp.element), 2); strcat (line, hilf); return; case _VECTOR: sprintf (hilf, CTRLSTR3, "Vector ", ARITY (temp.element), 2); strcat (line, hilf); return; case _TVECTOR: sprintf (hilf, CTRLSTR3, "Tvector", ARITY (temp.element), 2); strcat (line, hilf); return; case _PM_OTHERWISE: /* pattern - match */ sprintf (hilf, CTRLSTR3, "Oth ", ARITY (temp.element), 1); strcat (line, hilf); return; case _PM_WHEN: /* pattern - match */ sprintf (hilf, CTRLSTR3, "When ", ARITY (temp.element), 3); strcat (line, hilf); return; case _PM_MATCH: /* pattern - match */ sprintf (hilf, CTRLSTR3, "Match ", ARITY (temp.element), 3); strcat (line, hilf); return; default: sprintf (hilf, CTRLSTR2, "fix-con?", ARITY (temp.element)); strcat (line, hilf); return; } /* switch */ else switch ((temp.element & F_CONSTR_NAME) >> O_CONSTR_NAME) { case _STRING: sprintf (hilf, CTRLSTR2, "String ", ARITY (temp.element)); strcat (line, hilf); return; case _PM_IN : /* pattern - match */ sprintf (hilf, CTRLSTR3, "In ", ARITY (temp.element),2); strcat (line, hilf); return; default: sprintf (hilf, CTRLSTR2, "constru?", ARITY (temp.element)); strcat (line, hilf); return; } /** switch **/ } /** else fix-constr **/ } /*--------------------------------------------------------------------------- * prnstring -- bereitet das Element eines Zahlen- oder Ziffern-Strings auf. * parameter: Top - das Stackelement (breits als Struktur) * flag - kurze oder lange Beschreibung ? *--------------------------------------------------------------------------- */ prnstring (Top, flag) I_STACKELEM Top; int flag; { char ch; ch = (char) Top.feld.value; switch ((P_LET1 & Top.element)) { case LET0: { if (flag != SHORT) { sprintf (hilf, " last letter "); strcat (line, hilf); sprintf (hilf, " %c' ", ch); strcat (line, hilf); } else { sprintf (hilf, " %c' ", ch); strcat (line, hilf); } break; } case LET1: { if (flag != SHORT) { sprintf (hilf, " letter "); strcat (line, hilf); sprintf (hilf, " %c ", ch); strcat (line, hilf); } else { sprintf (hilf, " %c ", ch); strcat (line, hilf); } break; } case STR_CHAR : if (flag != SHORT) { sprintf (hilf, " character "); strcat (line, hilf); } sprintf (hilf, " %c ", ch); strcat (line, hilf); break; case DIG0: { if (flag != SHORT) { sprintf (hilf, " last digit "); strcat (line, hilf); sprintf (hilf, " %c' ", ch); strcat (line, hilf); } else { sprintf (hilf, " %c' ", ch); strcat (line, hilf); } break; } case DIG1: { if (flag != SHORT) { sprintf (hilf, " digit "); strcat (line, hilf); sprintf (hilf, " %c ", ch); strcat (line, hilf); } else { sprintf (hilf, " %c ", ch); strcat (line, hilf); } break; } default: { sprintf (hilf, CTRLSTR1, "str-elem ?"); strcat (line, hilf); } } } /*--------------------------------------------------------------------------- * prnsingleatom -- bereitet ein single atom auf. * parameter: Top - das Stackelement (breits als Struktur) * flag - kurze oder lange Beschreibung ? *--------------------------------------------------------------------------- */ static prnsingleatom (Top, flag) I_STACKELEM Top; int flag; { switch ((P_FUNC & Top.element)) { case FUNC: /* eine Funktion */ { if (flag != SHORT) { sprintf (hilf, " function "); strcat (line, hilf); } switch (Top.element) { case M_NOT: sprintf (hilf, CTRLSTR1, "NOT "); strcat (line, hilf); return; case M_ABS: sprintf (hilf, CTRLSTR1, "ABS "); strcat (line, hilf); return; case M_NEG: sprintf (hilf, CTRLSTR1, "NEG "); strcat (line, hilf); return; case M_TRUNCATE: sprintf (hilf, CTRLSTR1, "TRUNC "); strcat (line, hilf); return; case M_FRAC: sprintf (hilf, CTRLSTR1, "FRAC "); strcat (line, hilf); return; case M_FLOOR: sprintf (hilf, CTRLSTR1, "FLOOR "); strcat (line, hilf); return; case M_CEIL: sprintf (hilf, CTRLSTR1, "CEIL "); strcat (line, hilf); return; case M_EMPTY: sprintf (hilf, CTRLSTR1, "EMPTY "); strcat (line, hilf); return; case M_SIN: sprintf (hilf, CTRLSTR1, "SIN "); strcat (line, hilf); return; case M_COS: sprintf (hilf, CTRLSTR1, "COS "); strcat (line, hilf); return; case M_TAN: sprintf (hilf, CTRLSTR1, "TAN "); strcat (line, hilf); return; case M_LN: sprintf (hilf, CTRLSTR1, "LN "); strcat (line, hilf); return; case M_EXP: sprintf (hilf, CTRLSTR1, "EXP "); strcat (line, hilf); return; case D_PLUS: sprintf (hilf, CTRLSTR1, "PLUS "); strcat (line, hilf); return; case D_MINUS: sprintf (hilf, CTRLSTR1, "MINUS "); strcat (line, hilf); return; case D_MULT: sprintf (hilf, CTRLSTR1, "MULT "); strcat (line, hilf); return; case D_DIV: sprintf (hilf, CTRLSTR1, "DIV "); strcat (line, hilf); return; case D_OR: sprintf (hilf, CTRLSTR1, "OR "); strcat (line, hilf); return; case D_AND: sprintf (hilf, CTRLSTR1, "AND "); strcat (line, hilf); return; case D_XOR: sprintf (hilf, CTRLSTR1, "XOR "); strcat (line, hilf); return; case D_EQ: sprintf (hilf, CTRLSTR1, "EQ "); strcat (line, hilf); return; case D_NEQ: sprintf (hilf, CTRLSTR1, "NE "); strcat (line, hilf); return; case D_LESS: sprintf (hilf, CTRLSTR1, "LT "); strcat (line, hilf); return; case D_LEQ: sprintf (hilf, CTRLSTR1, "LE "); strcat (line, hilf); return; case D_GREAT: sprintf (hilf, CTRLSTR1, "GT "); strcat (line, hilf); return; case D_GEQ: sprintf (hilf, CTRLSTR1, "GE "); strcat (line, hilf); return; case D_MIN: sprintf (hilf, CTRLSTR1, "MIN "); strcat (line, hilf); return; case D_MAX: sprintf (hilf, CTRLSTR1, "MAX "); strcat (line, hilf); return; case D_MOD: sprintf (hilf, CTRLSTR1, "MOD "); strcat (line, hilf); return; case IP: /* inner product */ sprintf (hilf, CTRLSTR1, "IP "); strcat (line, hilf); return; case CLASS: sprintf (hilf, CTRLSTR1, "CLASS "); strcat (line, hilf); return; case TYPE: sprintf (hilf, CTRLSTR1, "TYPE "); strcat (line, hilf); return; case LDIMENSION: sprintf (hilf, CTRLSTR1, "LDIM "); strcat (line, hilf); return; case DIMENSION: /* uni - function */ sprintf (hilf, CTRLSTR1, "DIM "); strcat (line, hilf); return; case VDIMENSION: /* VECTOR / TVECTOR */ sprintf (hilf, CTRLSTR1, "VDIM "); strcat (line, hilf); return; case MDIMENSION: /* MATRIX */ sprintf (hilf, CTRLSTR1, "MDIM "); strcat (line, hilf); return; case C_PLUS: sprintf (hilf, CTRLSTR1, "C_PLUS "); strcat (line, hilf); return; case C_MINUS: sprintf (hilf, CTRLSTR1, "C_MINUS "); strcat (line, hilf); return; case C_MULT: sprintf (hilf, CTRLSTR1, "C_MULT "); strcat (line, hilf); return; case C_DIV: sprintf (hilf, CTRLSTR1, "C_DIV "); strcat (line, hilf); return; case C_MIN: sprintf (hilf, CTRLSTR1, "C_MIN "); strcat (line, hilf); return; case C_MAX: sprintf (hilf, CTRLSTR1, "C_MAX "); strcat (line, hilf); return; case VC_PLUS: /* VECTOR / TVECTOR */ sprintf (hilf, CTRLSTR1, "VC_PLUS "); strcat (line, hilf); return; case VC_MINUS: /* VECTOR / TVECTOR */ sprintf (hilf, CTRLSTR1, "VC_MINUS "); strcat (line, hilf); return; case VC_MULT: /* VECTOR / TVECTOR */ sprintf (hilf, CTRLSTR1, "VC_MULT "); strcat (line, hilf); return; case VC_DIV: /* VECTOR / TVECTOR */ sprintf (hilf, CTRLSTR1, "VC_DIV "); strcat (line, hilf); return; case VC_MIN: /* VECTOR / TVECTOR */ sprintf (hilf, CTRLSTR1, "VC_MIN "); strcat (line, hilf); return; case VC_MAX: /* VECTOR / TVECTOR */ sprintf (hilf, CTRLSTR1, "VC_MAX "); strcat (line, hilf); return; case F_EQ: sprintf (hilf, CTRLSTR1, "F_EQ "); strcat (line, hilf); return; case F_NE: sprintf (hilf, CTRLSTR1, "F_NE "); strcat (line, hilf); return; case LCUT: /* LIST */ sprintf (hilf, CTRLSTR1, "LCUT "); strcat (line, hilf); return; case LTRANSFORM: /* LIST */ sprintf (hilf, CTRLSTR1, "LTRANSFORM"); strcat (line, hilf); return; case LROTATE: /* LIST */ sprintf (hilf, CTRLSTR1, "LROTATE "); strcat (line, hilf); return; case LSELECT: /* LIST */ sprintf (hilf, CTRLSTR1, "LSELECT "); strcat (line, hilf); return; case LREPLACE: /* LIST */ sprintf (hilf, CTRLSTR1, "LREPLACE "); strcat (line, hilf); return; case REVERSE : /* LIST */ sprintf (hilf, CTRLSTR1, "REVERSE "); strcat (line, hilf); return; case LUNI: /* LIST */ sprintf (hilf, CTRLSTR1, "LUNITE "); strcat (line, hilf); return; case SUBSTR: /* uni - function */ sprintf (hilf, CTRLSTR1, "SUBSTR "); /* list / string */ strcat (line, hilf); return; case REPSTR: /* uni - function */ sprintf (hilf, CTRLSTR1, "REPSTR "); /* list / string */ strcat (line, hilf); return; case CUT: /* uni - function */ sprintf (hilf, CTRLSTR1, "CUT "); strcat (line, hilf); return; case ROTATE: /* uni - function */ sprintf (hilf, CTRLSTR1, "ROTATE "); strcat (line, hilf); return; case SELECT: /* uni - function */ sprintf (hilf, CTRLSTR1, "SELECT "); strcat (line, hilf); return; case REPLACE: /* uni - function */ sprintf (hilf, CTRLSTR1, "REPLACE "); strcat (line, hilf); return; case UNI: /* uni - function */ sprintf (hilf, CTRLSTR1, "UNITE "); strcat (line, hilf); return; case MCUT: /* MATRIX */ sprintf (hilf, CTRLSTR1, "MCUT "); strcat (line, hilf); return; case MROTATE: /* MATRIX */ sprintf (hilf, CTRLSTR1, "MROTATE "); strcat (line, hilf); return; case MSELECT: /* MATRIX */ sprintf (hilf, CTRLSTR1, "MSELECT "); strcat (line, hilf); return; case MREPLACE: /* MATRIX */ sprintf (hilf, CTRLSTR1, "MREPLACE "); strcat (line, hilf); return; case MREPLACE_C: /* MATRIX */ sprintf (hilf, CTRLSTR1, "MREPLACE_C"); strcat (line, hilf); return; case MREPLACE_R: /* MATRIX */ sprintf (hilf, CTRLSTR1, "MREPLACE_R"); strcat (line, hilf); return; case MUNI: /* MATRIX */ sprintf (hilf, CTRLSTR1, "MUNITE "); strcat (line, hilf); return; case VCUT: /* VECTOR / TVECTOR */ sprintf (hilf, CTRLSTR1, "VCUT "); strcat (line, hilf); return; case VROTATE: /* VECTOR / TVECTOR */ sprintf (hilf, CTRLSTR1, "VROTATE "); strcat (line, hilf); return; case VSELECT: /* VECTOR / TVECTOR */ sprintf (hilf, CTRLSTR1, "VSELECT "); strcat (line, hilf); return; case VREPLACE: /* VECTOR / TVECTOR */ sprintf (hilf, CTRLSTR1, "VREPLACE "); strcat (line, hilf); return; case VUNI: /* VECTOR / TVECTOR */ sprintf (hilf, CTRLSTR1, "VUNITE "); strcat (line, hilf); return; case TRANSPOSE: /* VECTOR , TVECTOR and MATRIX */ sprintf (hilf, CTRLSTR1, "TRANSPOSE "); strcat (line, hilf); return; case TRANSFORM: /* VECTOR , TVECTOR and MATRIX */ sprintf (hilf, CTRLSTR1, "TRANSFORM "); strcat (line, hilf); return; case TO_MAT: /* type conversion */ sprintf (hilf, CTRLSTR1, "TO_MAT "); strcat (line, hilf); return; case TO_VECT: /* type conversion */ sprintf (hilf, CTRLSTR1, "TO_VECT "); strcat (line, hilf); return; case TO_TVECT: /* type conversion */ sprintf (hilf, CTRLSTR1, "TO_TVECT "); strcat (line, hilf); return; case TO_SCAL: /* type conversion */ sprintf (hilf, CTRLSTR1, "TO_SCAL "); strcat (line, hilf); return; case TO_LIST: /* type conversion */ sprintf (hilf, CTRLSTR1, "TO_LIST "); strcat (line, hilf); return; case TO_FIELD: /* type conversion */ sprintf (hilf, CTRLSTR1, "TO_FIELD "); strcat (line, hilf); return; case MK_STRING: /* make hirarchical */ sprintf (hilf, CTRLSTR1, "MKSTRING ");/* string */ strcat (line, hilf); return; default: sprintf (hilf, CTRLSTR1, "function ?"); strcat (line, hilf); return; } /** end of switch Top.element **/ } /** end of case FUNC **/ case CONSTANT: { if ((P_DOLLAR & Top.element) == DOLLAR) { if (flag != SHORT) { sprintf (hilf, " $ Ink-Elemente"); strcat (line, hilf); } sprintf (hilf, CTRLSTR2, " $ ", ARITY (Top.element)); strcat (line, hilf); return; } if ((P_NUM & Top.element) == NUM) { if (flag != SHORT) { sprintf (hilf, " NUM-Variable "); strcat (line, hilf); } sprintf (hilf, CTRLSTR2, "NUM ", ARITY (Top.element)); strcat (line, hilf); return; } if ((P_TILDE & Top.element) == TILDE) { if (flag != SHORT) { sprintf (hilf, " TILDE-Variable "); strcat (line, hilf); } sprintf (hilf, CTRLSTR2, "TILDE ", ARITY (Top.element)); strcat (line, hilf); return; } if (flag != SHORT) { sprintf (hilf, " Constant "); strcat (line, hilf); } /* die eigentliche Fallunterscheidung */ switch (Top.element) { case ESET : /* not used in husch-version */ sprintf (hilf, CTRLSTR1, "empty set "); strcat (line, hilf); return; case DOL_CONST : sprintf (hilf, CTRLSTR1, " $ "); strcat (line, hilf); return; case PLACEH: /* not used in husch-version */ sprintf (hilf, CTRLSTR1, "PLACEH "); strcat (line, hilf); return; case HASH: /* not used in husch-version */ sprintf (hilf, CTRLSTR1, " # "); strcat (line, hilf); return; case KLAA: sprintf (hilf, CTRLSTR1, " @ "); strcat (line, hilf); return; case ENDE: sprintf (hilf, CTRLSTR1, "END_E "); strcat (line, hilf); return; case NIL: /* empty list */ sprintf (hilf, CTRLSTR1, "NIL "); strcat (line, hilf); return; case NILMAT: /* empty matrix */ sprintf (hilf, CTRLSTR1, "NILMAT "); strcat (line, hilf); return; case NILVECT: /* empty vector */ sprintf (hilf, CTRLSTR1, "NILVECT "); strcat (line, hilf); return; case NILTVECT: /* empty tvector */ sprintf (hilf, CTRLSTR1, "NILTVECT "); strcat (line, hilf); return; case NILSTRING: /* empty string */ sprintf (hilf, CTRLSTR1, "NILSTRING "); strcat (line, hilf); return; case CL_FUNCTION: sprintf (hilf, CTRLSTR1, "CL_FUNCTION"); strcat (line, hilf); return; case CL_SCALAR: sprintf (hilf, CTRLSTR1, "CL_SCALAR "); strcat (line, hilf); return; case CL_VECTOR: /* class - Vector */ sprintf (hilf, CTRLSTR1, "CL_VECTOR "); strcat (line, hilf); return; case CL_TVECTOR: /* class - TVector */ sprintf (hilf, CTRLSTR1, "CL_TVECTOR"); strcat (line, hilf); return; case CL_MATRIX: /* class - Matrix */ sprintf (hilf, CTRLSTR1, "CL_MATRIX "); strcat (line, hilf); return; case CL_SET: /* not used in husch-version */ sprintf (hilf, CTRLSTR1, "CL_SET "); strcat (line, hilf); return; case CL_TREE: /* class - List */ sprintf (hilf, CTRLSTR1, "CL_LIST "); strcat (line, hilf); return; case USERFUNC: sprintf (hilf, CTRLSTR1, "USERFUNC "); strcat (line, hilf); return; case PRIMFUNC: sprintf (hilf, CTRLSTR1, "PRIMFUNC "); strcat (line, hilf); return; case LAMBDA : /* not used in husch-version */ sprintf (hilf, CTRLSTR1, "LAMBDA "); strcat (line, hilf); return; case CONDITIONAL: /* not used in husch-version */ sprintf (hilf, CTRLSTR1, "CONDITIONAL"); strcat (line, hilf); return; case BOOL: sprintf (hilf, CTRLSTR1, "BOOL "); strcat (line, hilf); return; case DECIMAL: sprintf (hilf, CTRLSTR1, "NUMBER "); strcat (line, hilf); return; case EXPR: sprintf (hilf, CTRLSTR1, "EXPR "); strcat (line, hilf); return; case TMATRIX: /* Type - Matrix */ sprintf (hilf, CTRLSTR1, "TMATRIX "); strcat (line, hilf); return; case CHAR: sprintf (hilf, CTRLSTR1, "STRING "); strcat (line, hilf); return; case SA_TRUE: sprintf (hilf, CTRLSTR1, "TRUE "); strcat (line, hilf); return; case SA_FALSE: sprintf (hilf, CTRLSTR1, "FALSE "); strcat (line, hilf); return; case PM_FAIL: /* pattern - match */ sprintf (hilf, CTRLSTR1, "FAIL "); strcat (line, hilf); return; case PM_SUCC: /* pattern - match */ sprintf (hilf, CTRLSTR1, "OK "); strcat (line, hilf); return; case PM_END : /* pattern - match */ sprintf (hilf, CTRLSTR1, "END "); strcat (line, hilf); return; case PM_SKIP: /* pattern - match */ sprintf (hilf, CTRLSTR1, "SKIP "); strcat (line, hilf); return; case PM_SKSKIP: /* pattern - match */ sprintf (hilf, CTRLSTR1, "SKIPSKIP "); strcat (line, hilf); return; case PM_DOLLAR: /* pattern - match */ sprintf (hilf, CTRLSTR1, "DOLLAR "); strcat (line, hilf); return; default: sprintf (hilf, CTRLSTR1, "constant?"); strcat (line, hilf); return; } /* switch */ } /* CONSTANT */ default: sprintf (hilf, CTRLSTR1, "singleatom?"); strcat (line,hilf); return; } } #endif void rprintdummy() {;}
C
#include <avr/io.h> #include <util/delay.h> #include "i2c.h" #include "ds3231.h" #include "clock.h" uint8_t ClockInit() { // initialize i2c bus I2cInit(); uint8_t temp = 0; if(!DS3231Read(0x00,&temp)){return 0;} if(!DS3231Write(0x00,temp)){return 0;} // set 24 hour mode if(!DS3231Read(0x02,&temp)){return 0;} // set 24 Hour bit temp|=(0b00000000); // write back to ds3231 if(!DS3231Write(0x02,temp)){return 0;} return 1; } uint8_t GetDate() { uint8_t date, temp; DS3231Read(0x04, &temp); date = (((temp & 0b00110000)>>4)*10) + (temp & 0b00001111); return date; } uint8_t GetMonth() { uint8_t month, temp; DS3231Read(0x05, &temp); month = (((temp & 0b00110000)>>4)*10) + (temp & 0b00001111); return month; } uint16_t GetYear() { uint8_t year; uint8_t temp; uint16_t u16year; DS3231Read(0x06, &temp); year = (((temp & 0b11110000)>>4)*10) + (temp & 0b00001111); u16year = year + CURRENT_YEAR; return u16year; } uint8_t GetSecond() { uint8_t sec,temp; // read the second register DS3231Read(0x00,&temp); sec=(((temp & 0b01110000)>>4)*10)+(temp & 0b00001111); return sec; } uint8_t GetMinute() { uint8_t min,temp; // read the minute register DS3231Read(0x01,&temp); min=(((temp & 0b01110000)>>4)*10)+(temp & 0b00001111); return min; } uint8_t GetHour() { uint8_t hr,temp; // read the hour register DS3231Read(0x02,&temp); if(((temp & 0b00100000)>>5)*20 > 0) { hr=(((temp & 0b00100000)>>5)*20)+(temp & 0b00001111); }else { hr=(((temp & 0b00010000)>>4)*10)+(temp & 0b00001111); } return hr; } uint8_t GetTemp() { uint8_t temp_dec = 0; uint8_t temp = 0; uint8_t mask; // read the temp decimal register DS3231Read(0x11, &temp_dec); //DS3231Read(0x12, &temp_dp); for(mask = 0x01; mask != 0; mask <<= 1) { if(temp_dec & mask) { // bit is one temp += mask; } } return temp; } uint8_t SetDate(uint8_t date) { uint8_t temp, result; temp = ((date / 10)<<4) | (date % 10); result = DS3231Write(0x04, temp); return result; } uint8_t SetMonth(uint8_t month) { uint8_t temp, result; temp = ((month / 10)<<4) | (month % 10); result = DS3231Write(0x05, temp); return result; } uint8_t SetYear(uint16_t year) { uint8_t temp, result; year -= CURRENT_YEAR; uint8_t u8year; u8year = (uint8_t)year; temp = ((u8year / 10)<<4) | (u8year % 10); result = DS3231Write(0x06, temp); return result; } uint8_t SetSecond(uint8_t sec) { uint8_t temp,result; temp=((sec/10)<<4)|(sec%10); result=DS3231Write(0x00,temp); return result; } uint8_t SetMinute(uint8_t min) { uint8_t temp,result; temp=((min/10)<<4)|(min%10); result=DS3231Write(0x01,temp); return result; } uint8_t SetHour(uint8_t hr) { uint8_t temp,result; // set 24 hour if(hr < 20) { temp=((hr/10)<<4)|(hr%10); }else { temp=((hr/20)<<5)|(hr%10); } result=DS3231Write(0x02,temp); return result; }
C
/* * Title : Console Program Basic Square Calculators(MenghitungLuasPersegi.c) * Program Description : Calculate Wide of Square Using Arithmetic Multiplication between Length and Wide Input from Keyboard * Author : Muhammad Hasbi, S.T. * Interface : Console * IDE : Dev-C++ 5.11 * Operating System : Windows 8 Pro */ #include<stdio.h> main() { float panjang; //length (m) float lebar; //width (m) float luas; //wide (m2) (square meter) printf("Basic Console Program:Square Wide Calculator \n"); printf("Masukkan nilai dari panjang persegi: \n"); scanf("%f", &panjang); printf("Masukkan nilai dari lebar persegi: \n"); scanf("%f", &lebar); luas=panjang*lebar; printf("Luas persegi tersebut adalah = %f (m2) Square Meter \n", luas); }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ struct dentry {int /*<<< orphan*/ d_lock; struct dentry* d_parent; } ; /* Variables and functions */ int /*<<< orphan*/ DENTRY_D_LOCK_NESTED ; struct dentry* READ_ONCE (struct dentry*) ; int /*<<< orphan*/ rcu_read_lock () ; int /*<<< orphan*/ rcu_read_unlock () ; int /*<<< orphan*/ spin_lock (int /*<<< orphan*/ *) ; int /*<<< orphan*/ spin_lock_nested (int /*<<< orphan*/ *,int /*<<< orphan*/ ) ; int /*<<< orphan*/ spin_unlock (int /*<<< orphan*/ *) ; scalar_t__ unlikely (int) ; __attribute__((used)) static struct dentry *__lock_parent(struct dentry *dentry) { struct dentry *parent; rcu_read_lock(); spin_unlock(&dentry->d_lock); again: parent = READ_ONCE(dentry->d_parent); spin_lock(&parent->d_lock); /* * We can't blindly lock dentry until we are sure * that we won't violate the locking order. * Any changes of dentry->d_parent must have * been done with parent->d_lock held, so * spin_lock() above is enough of a barrier * for checking if it's still our child. */ if (unlikely(parent != dentry->d_parent)) { spin_unlock(&parent->d_lock); goto again; } rcu_read_unlock(); if (parent != dentry) spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED); else parent = NULL; return parent; }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <semaphore.h> #define BUFFER_SIZE 5 void *producer(void *arg); void *consumer(void *arg); sem_t bin_sem; sem_t empty; sem_t full; int idx=0; int items[BUFFER_SIZE]; int main() { int res; pthread_t a_thread, b_thread; void *thread_result; for(int i=0;i<BUFFER_SIZE;i++) items[i]=-1; res = sem_init(&bin_sem, 0, 0); if (res != 0) { perror("Semaphore initialization failed"); exit(EXIT_FAILURE); } res = sem_init(&empty, 0, BUFFER_SIZE); if (res != 0) { perror("Semaphore initialization failed"); exit(EXIT_FAILURE); } res = sem_init(&full, 0, 0); if (res != 0) { perror("Semaphore initialization failed"); exit(EXIT_FAILURE); } res = pthread_create(&a_thread, NULL, producer, &thread_result); if (res != 0) { perror("Thread creation failed"); exit(EXIT_FAILURE); } res = pthread_create(&b_thread, NULL, consumer, &thread_result); if (res != 0) { perror("Thread creation failed"); exit(EXIT_FAILURE); } res = pthread_join(a_thread, NULL); if (res != 0) { perror("Thread join failed"); exit(EXIT_FAILURE); } res = pthread_join(b_thread, NULL); if (res != 0) { perror("Thread join failed"); exit(EXIT_FAILURE); } printf("Thread joined\n"); sem_destroy(&bin_sem); exit(EXIT_SUCCESS); } void *producer(void *arg) { int item; while(1) { sem_wait(&empty); sem_wait(&bin_sem); //insert into array item=rand(); items[idx]=item; idx++; sem_post(&bin_sem); sem_post(&full); printf("Produced item is: %d",item); } pthread_exit(NULL); } void *consumer(void *arg) { int item; while(1) { sem_wait(&full); sem_wait(&bin_sem); //remove from array item=items[idx-1]; items[idx-1]=-1; idx--; sem_post(&bin_sem); sem_post(&empty); printf("Consumed item is: %d",item); } pthread_exit(NULL); }
C
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #define NTHREADS 4 /* Variaveis globais */ int x = 0; pthread_mutex_t x_mutex, final_mutex; pthread_cond_t x_cond, final_cond; /* Thread A */ void *A (void *t) { printf("Seja bem vindo!\n"); pthread_mutex_lock(&x_mutex); x++; if (x==1) { printf("A: x = %d, vai sinalizar a condicao \n", x); pthread_cond_broadcast(&x_cond); } pthread_mutex_unlock(&x_mutex); pthread_exit(NULL); } /* Thread B */ void *B (void *t) { pthread_mutex_lock(&x_mutex); if (x < 3) { printf("B: x= %d, vai se bloquear...\n", x); pthread_cond_wait(&x_cond, &x_mutex); x++; printf("Fique a vontade.\n"); printf("B: sinal recebido e mutex realocado, x = %d\n", x); if(x==3){ printf("B: x = %d\n", x); pthread_cond_signal(&final_cond); } } pthread_mutex_unlock(&x_mutex); pthread_exit(NULL); } /* Thread C */ void *C (void *t) { pthread_mutex_lock(&x_mutex); if (x < 3) { printf("C: x= %d, vai se bloquear...\n", x); pthread_cond_wait(&x_cond, &x_mutex); x++; printf("Sente-se por favor.\n"); printf("C: sinal recebido e mutex realocado, x = %d\n", x); if(x==3){ printf("C: x = %d\n", x); pthread_cond_signal(&final_cond); } } pthread_mutex_unlock(&x_mutex); pthread_exit(NULL); } /* Thread D */ void *D (void *t) { pthread_mutex_lock(&final_mutex); while(x < 4) { printf("D: x= %d, vai se bloquear...\n", x); pthread_cond_wait(&final_cond, &final_mutex); x++; printf("Volte sempre!\n"); printf("D: sinal recebido e mutex realocado, x = %d\n", x); } pthread_mutex_unlock(&final_mutex); pthread_exit(NULL); } /* Funcao principal */ int main(int argc, char *argv[]) { int i; pthread_t threads[NTHREADS]; /* Inicilaiza o mutex (lock de exclusao mutua) e a variavel de condicao */ pthread_mutex_init(&x_mutex, NULL); pthread_cond_init (&x_cond, NULL); pthread_mutex_init(&final_mutex, NULL); pthread_cond_init (&final_cond, NULL); /* Cria as threads */ pthread_create(&threads[3], NULL, A, NULL); pthread_create(&threads[2], NULL, B, NULL); pthread_create(&threads[1], NULL, C, NULL); pthread_create(&threads[0], NULL, D, NULL); /* Espera todas as threads completarem */ for (i = 0; i < NTHREADS; i++) { pthread_join(threads[i], NULL); } /* Desaloca variaveis e termina */ pthread_mutex_destroy(&x_mutex); pthread_cond_destroy(&x_cond); pthread_mutex_destroy(&final_mutex); pthread_cond_destroy(&final_cond); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* julia.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mhaziza <mhaziza@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/01/04 11:56:17 by mhaziza #+# #+# */ /* Updated: 2017/02/22 13:27:23 by mhaziza ### ########.fr */ /* */ /* ************************************************************************** */ #include "fractol.h" int mandelbrot(t_env *e, int x, int y) { t_cplex z; t_cplex c; float mod; float tmp; int i; i = 0; z.re = 0; z.im = 0; c.re = (x + e->tx) / e->zoom; c.im = (y + e->ty) / e->zoom; e->re_c = c.re; e->im_c = c.im; mod = 0; while (i < e->iter && (mod < 4)) { tmp = z.re; z.re = z.re * z.re - z.im * z.im + c.re; z.im = 2 * tmp * z.im + c.im; mod = z.re * z.re + z.im * z.im; i++; } if (i == e->iter) return (0); return (i); } int julia(t_env *e, int x, int y) { t_cplex z; t_cplex c; float mod; float tmp; int i; i = 0; z.re = (x + e->tx) / e->zoom; z.im = (y + e->ty) / e->zoom; c.re = e->re_c; c.im = e->im_c; mod = 0; while (i < e->iter && (mod < 4)) { tmp = z.re; z.re = z.re * z.re - z.im * z.im + c.re; z.im = 2 * tmp * z.im + c.im; mod = z.re * z.re + z.im * z.im; i++; } if (i == e->iter) return (0); return (i); } int burnship(t_env *e, int x, int y) { t_cplex z; t_cplex c; float mod; float tmp; int i; i = 0; z.re = 0; z.im = 0; c.re = (x + e->tx) / e->zoom; c.im = (y + e->ty) / e->zoom; mod = 0; while (i < e->iter && (mod < 4)) { tmp = z.re; z.re = z.re * z.re - z.im * z.im + c.re; z.im = 2 * fabsf(tmp * z.im) + c.im; mod = z.re * z.re + z.im * z.im; i++; } if (i == e->iter) return (0); return (i); }
C
#include <stdio.h> char *set_arr(char *arr, int n); int main(void) { int num; printf("Please input array members:"); scanf("%d", &num); char ch; while (scanf("%c", &ch)) if (ch == '\n') break; else continue; char ar[num]; printf("Please input source string:"); set_arr(ar, num); int i = 0; printf("Array is:\n"); for (i = 0; i < num; i ++) printf("%c -- %d\n", *(ar + i), *(ar + i)); return 0; } char *set_arr(char *arr, int n) { int i = 0; char ch; while (i < n) { ch = getchar(); if (ch == EOF) { break; } //if (ch == '\n') // continue; *(arr + i) = ch; i ++; } *(arr + i) = '\0'; return arr; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> /** 1. */ /** * 24 * 8 = 192 octets. * **/ /** 2. */ /** ... */ /** 3. */ /** ... */ int main() { short tab_entiers[] = {10, 20, 40, 70, 44, 21, 90, 999, 10, 20, 32}; void *tab; int val; tab = tab_entiers; /** 4. */ val = ((short *) tab)[3]; printf("%d\n", val); val = *(((short *) tab) + 3); printf("%d\n", val); /** 5. */ val = ((int *) tab)[3]; printf("%d\n", val); val = *(((int *) tab) + 3); printf("%d\n", val); return 0; }
C
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> #include <time.h> // serial sparse implementation of pagerank. data1.dat // R(t+1) = d M R(t) + (1-d)/N // d - damp1, N = 4 // damp2 - (1-d)/N // prnew <- R // a <- M // **************Compressed column storage technique**************// // All non zero elements will be stored as val vector // Row indices of these elements are in rowind vector // Indices of those elements which start a new column // are in colptr vector // READ ABOUT MPI SPARSE MATRIX VECTOR MULTIPLICATION #define NODES 4039 #define EDGES 176468 double sqrt(double x); int main() { printf("Program start\n"); FILE *fp; clock_t begin,end; double time_spent; int colindex, link,i,j=0,col,colmatch=0,localsum=0; int newlines = 0, linenum = 5; char ch; char line[21]; //double a[4][4] = {{0}}; int k; double * val = (double*)calloc(EDGES, sizeof(double)); int * rowind =(int*)calloc(EDGES, sizeof(int)); int * colptr = (int*)calloc(NODES+1, sizeof(int)); //missing values will be initialized to zero? no.of cols+1 int co, index; //for normalizing the array of non zero elements double * prold = (double*)malloc(NODES*sizeof(double));; //malloc and initialize to 0.25 double * prnew = (double*)calloc(NODES, sizeof(double)); double * damp1 = (double*)malloc(NODES*sizeof(double)); //malloc and initialize to 0.85 double * damp2 = (double*)malloc(NODES*sizeof(double)); //malloc and initialize to 0.15/NODES double * diff = (double*)calloc(NODES, sizeof(double)); double err = 0.00001; double norm, norm_sq; int * sum = (int*)calloc(NODES, sizeof(int)); for(i=0; i<NODES;i++) { prold[i] = 0.25; damp1[i] = 0.85; damp2[i] = 0.15/NODES; } printf("initialization complete\n"); //function start fp = fopen("data1.dat", "r"); while((ch=getc(fp)) != EOF) { if(ch == '\n') { newlines += 1; if (newlines == linenum - 1) { break; } } } for(i = 0; i<EDGES; i++) { fscanf(fp, "%d %d", &colindex, &link); //comment out the next two lines if node numbers start with zero colindex = colindex - 1; link = link - 1; rowind[i] = link; if(colmatch==colindex) { localsum += 1; } else { sum[j] = localsum; colptr[j+1] = colptr[j] + localsum; //index of val where new column starts localsum = 1; //new localsum j += 1; colmatch = colindex; //new column } val[i] = 1.0; } sum[j] = localsum; //for the last column colptr[j+1]= EDGES; //number of non zeros in the matrix fclose(fp); index = 0; for(i = 0; i<NODES; i++) { // This is to normalize the array of non zeros co = sum[i]; for(j = index; j < index+co; j++) { val[j] = val[j]/co; } index += co; } // // So much should go in the function // printf("this is the val array\n"); // for(i = 0; i<EDGES; i++) { // printf("%f\t", val[i]); // } // printf("\n"); // printf("this is the sum array\n"); // // sum array // for(j = 0; j< NODES; j++) { // printf("%d\t", sum[j]); // } // printf("\n"); // printf("this is the rowind array\n"); // for(i=0;i<EDGES;i++) { // printf("%d\t", rowind[i]); // } // printf("\nthis is the colptr array\n"); // for(i=0;i<NODES+1;i++) { // printf("%d\t", colptr[i]); // } // val, rowind, colptr calculation complete... all the above should // go to mpi file.. //checking matrix multiplication //*********Computing pagerank*******************/ printf("\nComputing page rank...\n"); // Power iteration // This can be enlosed in a function // For each submatrices, if the right values of col, val // rowind and prold are available at the processor, // multiplication can be done successfully. begin = clock(); do { memset(prnew, 0, NODES*sizeof(double)); // for(j = 0; j<NODES; j++) { // printf("%f\t", prold[j]); // } // printf("\n"); norm = 0.0; for(col = 0; col<NODES; col++) { for(j=colptr[col]; j<colptr[col+1]; j++) { prnew[rowind[j]] += val[j]*prold[col]; } } for(i = 0; i<NODES; i++) { prnew[i] = prnew[i]*damp1[i]+damp2[i]; // printf("%f\t", prnew[i]); } // printf("\n"); //norm calculation and vector copying from new to old norm_sq = 0.0; for(i=0; i<NODES;i++) { diff[i] = prnew[i] - prold[i]; norm_sq += diff[i]*diff[i]; //l2 norm || prnew-prold || // printf("%f\n",fabs(diff[i]*diff[i])); prold[i] = prnew[i]; //printf("%f\t", prold[i]); } //for(j=0; j < NODES; j++) { // printf("%f\t", prold[j]); // printf("%f\n", norm_sq); norm = sqrt(norm_sq); }while(norm>err); end = clock(); time_spent = (double)(end-begin)/CLOCKS_PER_SEC; //print pagrank vector printf("Printing first ten elements of pagerank vector\n"); for(j = 0; j< 10; j++) { printf("%f\t",prnew[j]); } printf("\nTime for solutin loop %f seconds", time_spent); return 1; }
C
int main(int argc, char* argv[]) { int n,i,j,len; scanf("%d",&n); char DNA[256]; for(i=0;i<n;i++){ scanf("%s",DNA); len=strlen(DNA); for(j=0;j<len;j++){ if(DNA[j]=='A') DNA[j]='T'; else if(DNA[j]=='T') DNA[j]='A'; else if(DNA[j]=='C') DNA[j]='G'; else if(DNA[j]=='G') DNA[j]='C'; } printf("%s\n",DNA); } return 0; }
C
#include "io.h" #include "debug.h" #include "global.h" #include "macros.h" #include "error.h" #include <termios.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <sys/ioctl.h> //---------------------------------------------------------------------------- error_t reopenAll (void) { error_t err; CLOSE(g.uartfd); CLOSE(g.termfd); FCLOSE(g.termfh); if ((err = openUART(g.uart)) != ERR_OK) return err ; if ((err = openTerm(g.term)) != ERR_OK) return err ; return ERR_OK; } //---------------------------------------------------------------------------- error_t openTerm (char* term) { // Open the terminal for key-stuffing if ((g.termfd = open(term, O_WRONLY | O_NOCTTY | O_NDELAY)) == -1) return ERR_NOTTY; // Open the terminal for terminal commands if ((g.termfh = fopen(term, "wb")) == NULL) return ERR_NOTERM ; return ERR_OK; } //---------------------------------------------------------------------------- error_t send2termfd (char* s) { if ((s[0] == '\xff') && (s[1] != 0) && (s[2] == '\0')) { if (s[1] == '\xff') ioctl(g.termfd, TIOCSTI, &s[2]) ; else if (INRANGE(s[1], 1, 26)) ioctl(g.termfd, TIOCSTI, &s[1]) ; } else { while (*s) ioctl(g.termfd, TIOCSTI, s++) ; } return ERR_OK; } //------------------------------------------------------------------------------ void send2termfh (char* s) { fprintf(g.termfh, s); fflush(g.termfh); return; } //---------------------------------------------------------------------------- // At bootup, pins 8 and 10 are already set to UART0_TXD, UART0_RXD // (ie the alt0 function) respectively. // // error_t openUART (char* uart) { struct termios tty; // OPEN THE UART // The flags (defined in fcntl.h): // Access modes: O_RDONLY - Open for reading only. // O_WRONLY - Open for writing only. // O_RDWR - Open for reading and writing. // // O_NDELAY / O_NONBLOCK (same function) - Enables nonblocking mode. // When set read requests on the file can return immediately with the // failure status of 'EAGAIN' if there is no input immediately available // (instead of blocking/waiting). // Likewise, write requests can also return immediately with a failure // status of '???' if the output can't be written immediately. // // O_NOCTTY - When set and path identifies a terminal device, // open() shall NOT cause the terminal device to become // the controlling terminal for the process. // // if ((g.uartfd = open(uart, O_RDWR | O_NOCTTY | O_NDELAY)) == -1) // 100% CPU usage - handy for debugging if ((g.uartfd = open(uart, O_RDWR | O_NOCTTY)) == -1) return ERR_NOTTY ; // Grab the current configuration options //!echk tcgetattr(g.uartfd, &tty); //CONFIGURE THE UART // The flags (defined in /usr/include/termios.h - // http://pubs.opengroup.org/onlinepubs/007908799/xsh/termios.h.html): // CSIZE - CS5, CS6, CS7, CS8 (#bits) [CSZIE is the mask] // CLOCAL - Ignore modem status lines (DTR/DCD) // CREAD - Enable receiver (Rx) // PARENB - Parity enable // PARODD - Odd parity (else even) [MARK & SPACE are also available] // IGNPAR - Ignore characters with parity errors // ICRNL - Map CR to NL on input (Use for ASCII comms to autocorrect EOL // chars. Do NOT use for bianry comms) // tty.c_cflag = CS8 | CLOCAL | CREAD; tty.c_iflag = IGNPAR; tty.c_oflag = 0; tty.c_lflag = 0; // Set In/Out (Rx/Tx) speeds // Baud rate - B1200, B2400, B4800, B9600, B19200, B38400, B57600, // B115200, B230400, B460800, B500000, B576000, B921600, // B1000000, B1152000, B1500000, B2000000, B2500000, B3000000, // B3500000, B4000000 //!echk cfsetispeed(&tty, B19200); cfsetospeed(&tty, B19200); // Flush any data currently in the UART buffer //!echk tcflush(g.uartfd, TCIFLUSH); // Write the settings to the port //!echk tcsetattr(g.uartfd, TCSANOW, &tty); return ERR_OK; } //---------------------------------------------------------------------------- // Akin to a Pascal String, // the first byte is the number of subsequent bytes to be written // error_t tx (uint8_t* buf) { int cnt, bytes; if (!buf) return ERR_NULL ; PKTDBGF("? Checksum="); switch (checksum(buf, true)) { case ERR_OK : PKTDBGF("OK : "); break ; default: case ERR_CKSM : PKTDBGF("FAIL : "); break ; case ERR_CKSM_OK : PKTDBGF("CORRECTED : "); break ; } PKTDBGF("->{"); // We may need to issue multiple write()s to send all the data for (cnt = 0; cnt < *buf; cnt += bytes) { bytes = write(g.uartfd, buf +1 +cnt, *buf -cnt); if (bytes < 0) return ERR_TXFAIL ; //!echk tcdrain(g.uartfd); #if PKT_DEBUG == 1 { // Hex dump time... int i; for (i = 0; i < bytes; i++) { printf("%02X", *(buf +1 +cnt +i)); if ( !((i >= bytes -1) && (cnt +bytes >= *buf)) ) printf(","); } } #endif } PKTDBGF("}[%d]\n", *buf); return ERR_OK; } //---------------------------------------------------------------------------- // Note the first byte of the buffer is used to store the length, // EG. A buffer of length 10 can hold 1 length byte and 9 data bytes // error_t rx (uint8_t* buf, int len) { int n; if (!buf) return ERR_NULL ; if (len < 2) return ERR_BADLEN ; // Set 0 bytes read *buf = 0; //memset(buf, 0, len); // Perform a read n = read(g.uartfd, buf +1, len -1); PKTDBGF("? [%d]", n); // Error check // We ignore EAGAIN, it means : a non-blocking read returned 0 bytes if (n < 0) return (errno == EAGAIN) ? ERR_RXNONE : ERR_RXFAIL ; *buf = n; #if PKT_DEBUG == 1 PKTDBGF("<-"); dumpBuf(buf); PKTDBGF("\n"); #endif return ERR_OK; } //---------------------------------------------------------------------------- // Set 'fix' to true if you want bad checksums to be fixed // or false if you just want to verify it // error_t checksum (uint8_t* buf, bool fix) { int i; uint8_t cksm = 0; if (!buf) return ERR_NULL ; for (i = 0; i < (*buf) -1; i++) cksm += buf[1+i] ; cksm = (~cksm) +1; // 2's complement if (buf[1+i] != cksm) { if (fix) { buf[1+i] = cksm; return ERR_CKSM_OK; } else { return ERR_CKSM; } } return ERR_OK; }
C
#include "shared.h" #include "cpu.h" #include "connections.h" t_queue* pQueue; pthread_mutex_t mutex_checkReadyProcesses; void createProcessQueue(){ pQueue = queue_create(); } void pQueueAddProcess(PCBItem* process){ queue_push(pQueue, process); } void pQueueAddProcessFirst(PCBItem* process){ t_queue* tmp = queue_create(); while(!queue_is_empty(pQueue)){ queue_push(tmp, queue_pop(pQueue)); } queue_push(pQueue, process); while(!queue_is_empty(tmp)){ queue_push(pQueue, queue_pop(tmp)); } free(tmp); } void assignProcessToCPU(CPU* cpu, PCBItem* item) { item->status = P_RUNNING; cpu->status = CPU_BUSY; cpu->process = item; cpuRunProcess(cpu); } void checkReadyProcesses(){ pthread_mutex_lock(&mutex_checkReadyProcesses); if(!queue_is_empty(pQueue) && isAnyCPUAvailable()){ CPU* cpu = findCPUAvailable(); PCBItem* item = queue_pop(pQueue); sprintf(log_buffer, "PROCESO PID-%d RUNNING.\n", item->PID); log_info(logger, log_buffer); assignProcessToCPU(cpu, item); } pthread_mutex_unlock(&mutex_checkReadyProcesses); }
C
#include<stdio.h> int main(void){ double before; int after; printf("数値を入力してください:"); scanf("%lf", &before); after=(int)before; printf("切り捨てを行った後の値は%dです。\n",after); printf("切り捨てを行う前の値は%fです。\n",before); return 0; }
C
#pragma once #include <stdint.h> #include <stddef.h> #include <string.h> #include <stdbool.h> typedef uint32_t bitarray_element; typedef uint64_t bitarray_double_element; typedef struct bitarray { bitarray_element *sequence; size_t length; size_t bitlength; } bitarray; typedef struct bitarray_range { size_t start; size_t end; } bitarray_range; #define BITARRAY_BIT_WIDTH (sizeof(bitarray_element) * 8) #define BITARRAY_REQUIRE_LENGTH(bitlength) (((bitlength) / BITARRAY_BIT_WIDTH) + ((bitlength) % BITARRAY_BIT_WIDTH? 1: 0)) #define MAKE_LOCAL_BITARRAY(varname, bitlength)\ bitarray_element __ ## varname ## _sequence[BITARRAY_REQUIRE_LENGTH(bitlength)] = {};\ bitarray __ ## varname = { __ ## varname ## _sequence, BITARRAY_REQUIRE_LENGTH(bitlength), (bitlength) };\ bitarray *varname = &__ ## varname; extern size_t bitarray_require_size (size_t); extern void bitarray_init (bitarray_element*, size_t, size_t, bitarray*); extern bitarray *make_bitarray (size_t); extern void free_bitarray (bitarray*); extern bitarray_range bitarray_slice (size_t, size_t, bitarray*); extern bitarray_range bitarray_range_slice (size_t, size_t, bitarray_range*); extern int bitarray_range_set (int, size_t, bitarray_range*, bitarray*); extern int bitarray_range_get (size_t, bitarray_range*, bitarray*, int*); extern int bitarray_range_fill (int, size_t, size_t, bitarray_range*, bitarray*); extern int bitarray_range_fillp (int, size_t, size_t, bitarray_range*, bitarray*, bool*); extern int bitarray_range_find (int, size_t, bitarray_range*, bitarray*, size_t*); extern int bitarray_range_read (size_t, size_t, bitarray_range*, bitarray*, bitarray_element*); extern int bitarray_range_write (bitarray_element, size_t, size_t, bitarray_range*, bitarray*); extern int bitarray_range_not (bitarray_range*, bitarray*); extern int bitarray_range_and (bitarray_range*, bitarray*, bitarray_range*, bitarray*); extern int bitarray_range_or (bitarray_range*, bitarray*, bitarray_range*, bitarray*); extern int bitarray_range_xor (bitarray_range*, bitarray*, bitarray_range*, bitarray*); extern size_t bitarray_range_length (bitarray_range*); extern int bitarray_set (int, size_t, bitarray*); extern int bitarray_get (size_t, bitarray*, int*); extern int bitarray_fill (int, size_t, size_t, bitarray*); extern int bitarray_fillp (int, size_t, size_t, bitarray*, bool*); extern int bitarray_find (int, size_t, bitarray*, size_t*); extern int bitarray_read (size_t, size_t, bitarray*, bitarray_element*); extern int bitarray_write (bitarray_element, size_t, size_t, bitarray*); extern int bitarray_copy (bitarray*, bitarray*); extern int bitarray_not (bitarray*); extern int bitarray_and (bitarray*, bitarray*); extern int bitarray_or (bitarray*, bitarray*); extern int bitarray_xor (bitarray*, bitarray*); extern size_t bitarray_length (bitarray*);
C
#include <stdio.h> #include <stdlib.h> #include <time.h> /* Name: Kortney Menefee PID: k4790190 Date: 01/17/19 Assignment Name: MoreFunctions Instructor: R. Leinecker */ // This isn't finished but I did the guessing game and part of the arithmetic game. void showInfo() { printf("Here are your choices:\n"); printf("1. Play an arithmetic game\n"); printf("2. Play a guessing game\n"); printf("3. See your score\n"); printf("4. Quit\n"); } double arithGame(int max, int quantity, int op); { int op, max, problems; srand(time(0)); rnd1 = rand() % max + 1; rnd2 = rand() % max + 1; printf("Would you like addition or multiplication? 1 for addition 2 for multiplication.\n"); scanf("%d", &op); printf("What would you like the max number to be?\n"); scanf("%d", &max); printf("How many problems would you like?\n"); scanf("%d", &problems); if(op == 1) { printf("What is %d + %d?", rnd1, rnd2); } int elapsedTime; int startTime = time(0); elapsedTime = time(0) - startTime; } double guessGame(int max); { int rnd, theirGuess; int max, guesses = 0; printf("What do you want your maximum number to be?\n"); scanf("%d", &max); srand(time(0)); rnd = rand() % max + 1; do { printf("Please enter your guess: "); scanf("%d", &theirGuess); guesses ++; if(theirGuess > rnd) { printf("You are too high.\n"); } else if(theirGuess < rnd) { printf("You are too low.\n"); } } while(rnd != theirGuess); printf("You got it right!!!\n"); printf("You got it in %d guesses", guesses); int elapsedTime; int startTime = time(0); elapsedTime = time(0) - startTime; score = (elapsedTime)/(2 * max); return score } void showScore() { printf("Your score is now %d\n", score); } int main() { int choice; srand(time(0)); int getUserChoice(int max) { int choice; do { showInfo(); choice = getUserChoice(4); if(choice ==1) { arithGame(); } else if(choice ==2) { guessGame(); } else if(choice ==3) { showScore(); } } while ( choice! == 4 ); return 0; }
C
/*题目:取一个整数 a 从右端开始的 4~7 位。 */ /*程序分析:可以这样考虑: */ /*(1)先使 a 右移 4 位。 */ /*(2)设置一个低 4 位全为 1,其余全为 0 的数,可用~(~0<<4)*/ /*(3)将上面二者进行 & 运算。 */ #include <stdio.h> int main() { unsigned a,b,c,d; printf("请输入整数:\n"); scanf("%o",&a); b=a>>4; c=~(~0<<4); d=b&c; printf("%o\n%o\n",a,d); return 0; }
C
/* * CSE30264: Programming Assignment 2 * Chris Foley (cfoley) * Catherine Markley (cmarkley) * Bailey Blum (bblum1) * * myftp.c (Client) * * This is our client for our PA02 TCP assignment. The client begins by establishing a connection * to the already-running server. It then accepts operations from the user (DNLD: Download, * UPLD: Upload, LIST: List, MKDR: Make Directory, RMDR: Remove Directory, CHDR: Change Directory, * CRFL: Create File, RMFL: Remove File, QUIT: Quit) and handles them appropriately via handler * methods. The client loops to allow the user to enter multiple operations. It loops until the * user enters QUIT. */ /* TODO LIST - make README - create zipped file */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <time.h> #include <netdb.h> #include <arpa/inet.h> #include <netinet/in.h> #include <errno.h> #include <sys/stat.h> #include <time.h> #define MAX_BUFFER_SIZE 4096 #define MD5SUM_LENGTH 32 #define MIN(a,b) (((a)<(b)) ? (a) : (b)) void list_handler(int); void mkdr_handler(int); void rmdr_handler(int); void chdr_handler(int); void crfl_handler(int); void rmfl_handler(int); void dnld_handler(int); void upld_handler(int); /* * getMicrotime() * * This function gets the current time in milliseconds */ static long getMicrotime() { struct timeval currentTime; gettimeofday(&currentTime, NULL); return currentTime.tv_sec * (int)1e6 + currentTime.tv_usec; } /* * send_buffer(clientSocket, buffer, size) * * Send the data within buffer parameter to the TCP connection on clientSocket */ int send_buffer(int clientSocket, char* buffer, int size) { int len; if ((len = write(clientSocket, buffer, size)) == -1) { perror("Client Send\n"); exit(1); } return len; } /* * receive_buffer(clientSocket, buffer, size) * * Receives a buffer of data from the TCP connection on clientSocket */ int receive_buffer(int clientSocket, char* buffer, int size) { int len; bzero(buffer, sizeof(buffer)); if ((len = read(clientSocket, buffer, size)) == -1) { perror("Client Receive!"); exit(1); } return len; } /* * send_int(value, clientSocket) * * Sends an int over the TCP connection on clientSocket */ int send_int(int value, int clientSocket) { int len; uint32_t temp = htonl(value); if ((len = write(clientSocket, &temp, sizeof(temp))) == -1) { perror("Client Send"); exit(1); } return len; } /* * receive_int(clientSocket) * * Receives an int over the TCP connection on clientSocket */ int receive_int(int clientSocket) { int buffer; int len; bzero(&buffer, sizeof(buffer)); if ((len = read(clientSocket, &buffer, sizeof(buffer))) == -1) { perror("Client Receive Error"); exit(1); } int temp = ntohl(buffer); return temp; } int main(int argc, char *argv[]) { // parse command line arguments if(argc != 3) { printf("%s: Incorrect usage.\n Usage: %s ADDR PORT \n", argv[0], argv[0]); exit(1); } int port = atoi(argv[2]); // Create socket int clientSocket; if((clientSocket = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) { printf("Client: Error creating socket\n"); exit(0); } struct sockaddr_in servaddr; memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = inet_addr(inet_ntoa(*((struct in_addr*) gethostbyname(argv[1])->h_addr_list[0]))); servaddr.sin_port = htons(port); // connect printf("Welcome to our client!\n"); printf("Connection to %s on port %d\n", argv[1], port); if (connect(clientSocket, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) { printf("Client: Error connecting to server: %s\n", strerror(errno)); exit(0); } printf("Connection established\n"); char *userInput; while(1) { // Prompt the user for an Operation printf("> "); fgets(userInput, 50, stdin); // Get rid of the endline character userInput[strlen(userInput)-1] = '\0'; // Get operation out of user input char * operation = strtok(userInput, " \t\n"); if (strlen(operation) != 4) { printf("Operation must be 4 characters.\n"); continue; } int sent = send_buffer(clientSocket, operation, strlen(operation)); // DNLD: Download if (strcmp(operation, "DNLD") == 0) { dnld_handler(clientSocket); } // UPLD: Upload else if (strcmp(operation, "UPLD") == 0) { upld_handler(clientSocket); } // LIST: List else if (strcmp(operation, "LIST") == 0) { list_handler(clientSocket); } // MKDR: Make Directories else if (strcmp(operation, "MKDR") == 0) { mkdr_handler(clientSocket); } // RMDR: Remove Directory else if (strcmp(operation, "RMDR") == 0) { rmdr_handler(clientSocket); } // CHDR: Change Directory else if (strcmp(operation, "CHDR") == 0) { chdr_handler(clientSocket); } // CRFL: Create File else if (strcmp(operation, "CRFL") == 0) { crfl_handler(clientSocket); } // RMFL: Remove File else if (strcmp(operation, "RMFL") == 0) { rmfl_handler(clientSocket); } // QUIT: Quit else if (strcmp(operation, "QUIT") == 0) { break; } // Default: invalid else { printf("Invalid command.\n"); } } close(clientSocket); } void list_handler(int clientSocket){ char messageBuffer[MAX_BUFFER_SIZE]; char dirList[MAX_BUFFER_SIZE]; bzero(messageBuffer, sizeof(messageBuffer)); bzero(dirList, sizeof(dirList)); // Get size of directory int directorySize = receive_int(clientSocket); // Recieve listing int bytesRecvd = 0; while(bytesRecvd < directorySize) { memset(&messageBuffer, 0, sizeof(messageBuffer)); bytesRecvd += receive_buffer(clientSocket, messageBuffer, sizeof(messageBuffer)-1); strcat(dirList, messageBuffer); bzero(messageBuffer, sizeof(messageBuffer)); // Escape reading loop if its empty or error if (bytesRecvd <= 0) { break; } } bzero(messageBuffer, sizeof(messageBuffer)); printf("%s", dirList); } void mkdr_handler(int clientSocket) { // Get directory name and size char* directory = strtok(NULL, " "); if (directory == NULL) { printf("Improper use of command. Need to include a directory\n"); exit(1); } // Send length of directory name (int) int received = send_int(strlen(directory), clientSocket); // Send directory name (string) send_buffer(clientSocket, directory, strlen(directory)); // Recieve status update and inform user int status = receive_int(clientSocket); if (status == -2) { printf("The directory already exists on the server.\n"); } else if (status == -1) { printf("Making directory.\n"); } else { printf("The directory was successfully made!\n"); } } void rmdr_handler(int clientSocket){ // Get directory name and size char* directory = strtok(NULL, " "); if (directory == NULL) { printf("Improper use of command. Need to include a file name\n"); exit(1); } // Send length of directory name (int) int received = send_int(strlen(directory), clientSocket); // Send directory name (string) send_buffer(clientSocket, directory, strlen(directory)); // Recieve status update and inform user int status = receive_int(clientSocket); if (status == -1) { // Directory DNE printf("The directory does not exist on server.\n"); } else if (status == -2) { // Directory not empty printf("The directory is not empty.\n"); } else if (status == 1) { // Directory can be deleted // Get user confirmation printf("Are you sure you would like to delete %s? [Yes/No]\n", directory); char userConfirmation[5]; bzero(userConfirmation, sizeof(userConfirmation)); fgets(userConfirmation, 5, stdin); // Get rid of the endline character userConfirmation[strlen(userConfirmation)-1] = '\0'; // Ensure last two characters are null userConfirmation[4] = '\0'; userConfirmation[5] = '\0'; // Send confirmation send_buffer(clientSocket, userConfirmation, 5); if (strcmp(userConfirmation, "Yes") == 0) { // User wants to delete int status = receive_int(clientSocket); if (status > 0) { printf("Directory deleted\n"); } else if (status < 0) { printf("Failed to delete directory\n"); } else { printf("Unknown status received for RMDR from server.\n"); } } else { // User does not want to delete printf("Delete abandoned by the user!\n"); } } else { printf("Unknown status received for RMDR from server.\n"); } } void chdr_handler(int clientSocket){ // Get directory name and size char* directory = strtok(NULL, " "); if (directory == NULL) { printf("Improper use of command. Need to include a file name\n"); exit(1); } // Send length of directory name (int) int received = send_int(strlen(directory), clientSocket); // Send directory name (string) send_buffer(clientSocket, directory, strlen(directory)); // Recieve status update and inform user int status = receive_int(clientSocket); if (status > 0) { printf("Changed current directory\n"); } else if (status == -1) { printf("Error in changing directory\n"); } else if (status == -2) { printf("The directory does not exist on server.\n"); } else { printf("Unknown status received for CHDR from server.\n"); } } void crfl_handler(int clientSocket) { // Get file name and size char* filename = strtok(NULL, " "); if (filename == NULL) { printf("Improper use of command. Need to include a file name\n"); exit(1); } // Send length of directory name (int) send_int(strlen(filename), clientSocket); // Send filename (string) send_buffer(clientSocket, filename, strlen(filename)); // Recieve status update and inform user int status = receive_int(clientSocket); if (status > 0) { printf("The file was successfully created.\n"); } else if (status < 0) { printf("The file already exists.\n"); } else { printf("Unknown status received for CRFL from server.\n"); } } void rmfl_handler(int clientSocket) { // Get file name and size char* filename = strtok(NULL, " "); if (filename == NULL) { printf("Improper use of command. Need to include a file name\n"); exit(1); } // Send length of directory name (int) int received = send_int(strlen(filename), clientSocket); // Send filename (string) send_buffer(clientSocket, filename, strlen(filename)); // Receive status update and inform user int status = receive_int(clientSocket); if (status < 0) { printf("The file does not exist on server.\n"); } else if (status > 0) { // Get user confirmation printf("Are you sure you would like to delete %s? [Yes/No]\n", filename); char userConfirmation[5]; bzero(userConfirmation, sizeof(userConfirmation)); fgets(userConfirmation, 5, stdin); // Get rid of the endline character userConfirmation[strlen(userConfirmation)-1] = '\0'; // Ensure last two characters are null userConfirmation[4] = '\0'; userConfirmation[5] = '\0'; // Send confirmation send_buffer(clientSocket, userConfirmation, 5); if (strcmp(userConfirmation, "Yes") == 0) { // User wants to delete int status = receive_int(clientSocket); if (status > 0) { printf("File deleted.\n"); } else if (status < 0) { printf("Failed to delete file\n"); } else { printf("Unknown status received for RMFL from server.\n"); } } else { // User does not want to delete printf("Delete abandoned by the user!\n"); } } else { printf("Unknown status received for RMFL from server.\n"); } } void dnld_handler(int clientSocket){ // Get file name and size char* filename = strtok(NULL, " "); //printf("in download\n"); if (filename == NULL) { printf("Improper use of command. Need to include a file name\n"); exit(1); } // Send length of filename (int) send_int(strlen(filename), clientSocket); // Send filename (string) send_buffer(clientSocket, filename, strlen(filename)); // Recieve status update and inform user int status = receive_int(clientSocket); if (status == -1) { printf("File %s does not exist on server.\n", filename); return; } else { int filesize = status; // Receive md5sum char receiveMd5sum[MD5SUM_LENGTH + 1]; bzero(receiveMd5sum, sizeof(receiveMd5sum)); receive_buffer(clientSocket, receiveMd5sum, MD5SUM_LENGTH); // Create file FILE *fp = fopen(filename, "w"); if (fp == NULL) { printf("Failed to create file.\n"); exit(1); } else { // Recieve file data int totalReceivedBytes = 0; int receivedBytes; char buffer[MAX_BUFFER_SIZE]; bzero((char*)&buffer, sizeof(buffer)); long time_start = getMicrotime(); while(totalReceivedBytes < filesize) { receivedBytes = receive_buffer(clientSocket, buffer, MIN(MAX_BUFFER_SIZE,filesize-receivedBytes)); totalReceivedBytes += receivedBytes; if (fwrite(buffer, sizeof(char), receivedBytes, fp) < receivedBytes) { printf("Writing to file error!\n"); exit(1); } bzero((char*)&buffer, sizeof(buffer)); } long time_end = getMicrotime(); // Calculate throughput long diff = time_end - time_start; double diff_s = (double)diff * 0.000001; double megabytes = (double)receivedBytes * 0.000001; double throughput = megabytes / diff_s; fclose(fp); // Calculate md5hash char calculatedMd5sum[MD5SUM_LENGTH + 1]; // buffer to hold actual sum bzero(calculatedMd5sum, sizeof(calculatedMd5sum)); char cmd[7 + strlen(filename) + 1]; // buffer to hold command for linux command sprintf(cmd, "md5sum %s", filename); // put the actual command string in its buffer FILE *p = popen(cmd, "r"); if (p == NULL) { printf("Error calculating md5sum\n"); exit(1); } // fetch the results of the command int i, ch; for (i = 0; i < 32 && isxdigit(ch = fgetc(p)); i++) { calculatedMd5sum[i] = ch; } calculatedMd5sum[MD5SUM_LENGTH] = '\0'; pclose(p); // Output data transfer printf("%d bytes transferred in %f seconds: %f MegaBytes\\sec.\n", totalReceivedBytes, diff_s, throughput); // Compare md5hash printf("MD5Hash: %s (%s)\n", calculatedMd5sum, (strcmp(receiveMd5sum, calculatedMd5sum) == 0) ? "matches" : "doesn't match"); } } } void upld_handler(int clientSocket){ // Get file name and size char* filename = strtok(NULL, " "); if (filename == NULL) { printf("Improper use of command. Need to include a file name\n"); exit(1); } // Send length of filename (int) send_int(strlen(filename), clientSocket); // Send filename (string) send_buffer(clientSocket, filename, strlen(filename)); // Wait for server acknowledgment receive_int(clientSocket); // Check if file already exists struct stat st; if (stat(filename, &st) == 0 && S_ISREG(st.st_mode)) { // Send file size int fileSize = st.st_size; int sent_size = send_int(fileSize, clientSocket); // Send the actual file FILE *fp = fopen(filename, "r"); char buffer[MAX_BUFFER_SIZE + 1]; bzero(buffer, sizeof(buffer)); // Send file in chunks of MAX_BUFFER_SIZE int sentBytes = 0; while(sentBytes < fileSize) { int bytesRead = fread(buffer, sizeof(char), MAX_BUFFER_SIZE, fp); sentBytes += send_buffer(clientSocket, buffer, bytesRead); bzero(buffer, sizeof(buffer)); } // Receive throughput double throughput; int len; if ((len = read(clientSocket, &throughput, sizeof(throughput))) == -1) { perror("Failure to read from TCP socket.\n"); exit(1); } // Receive time double diff_s; if ((len = read(clientSocket, &diff_s, sizeof(diff_s))) == -1) { perror("Failure to read from TCP socket.\n"); exit(1); } // Receive md5sum char receiveMd5sum[MD5SUM_LENGTH + 1]; bzero(receiveMd5sum, sizeof(receiveMd5sum)); receive_buffer(clientSocket, receiveMd5sum, MD5SUM_LENGTH); // Calculate md5hash char calculatedMd5sum[MD5SUM_LENGTH + 1]; // buffer to hold actual sum bzero(calculatedMd5sum, sizeof(calculatedMd5sum)); char cmd[7 + strlen(filename) + 1]; // buffer to hold command for linux command sprintf(cmd, "md5sum %s", filename); // put the actual command string in its buffer FILE *p = popen(cmd, "r"); if (p == NULL) { printf("Error calculating md5sum\n"); exit(1); } // fetch the results of the command int i, ch; for (i = 0; i < 32 && isxdigit(ch = fgetc(p)); i++) { calculatedMd5sum[i] = ch; } calculatedMd5sum[MD5SUM_LENGTH] = '\0'; printf("Calculated: %s\n", calculatedMd5sum); pclose(p); if (strcmp(receiveMd5sum, calculatedMd5sum) == 0) { printf("%d bytes transferred in %f seconds: %f Megabytes/sec\n", fileSize, diff_s, throughput); printf("\tMD5Hash: %s (%s)\n", calculatedMd5sum, (strcmp(receiveMd5sum, calculatedMd5sum) == 0) ? "matches" : "doesn't match"); } else { printf("Transfer failed.\n"); } } else { send_int(-1, clientSocket); printf("File does not exist.\n"); } return; }
C
#include <stdio.h> #include <stdlib.h> void main(void) { FILE* fPointer = NULL; fPointer = fopen("123", "w"); fprintf(fPointer, "test message\n"); fclose(fPointer); return; }
C
/*************************************************************************//** * @file fifo.c * * Simple FIFO handling * ****************************************************************************/ #include <stdio.h> #include <malloc.h> #include "fifo.h" /******************************************************************************* * Public functions ******************************************************************************/ /*************************************************************************//** * Initialize FIFO * * @param[in,out] fifo FIFO context * @param[in] size Number of items the FIFO can hold * ****************************************************************************/ void fifo_init(fifo_t *fifo, int size) { fifo->size = size; fifo->data = (void **)malloc((size + 1) * sizeof(void *)); fifo->rd = fifo->wr = 0; } /*************************************************************************//** * Finalize FIFO * * @param[in,out] fifo FIFO context * ****************************************************************************/ void fifo_done(fifo_t *fifo) { free(fifo->data); fifo->data = NULL; fifo->size = 0; } /*************************************************************************//** * Insert item into FIFO * * @param[in,out] fifo FIFO context * @param[in] item Item to be inserted * * @return zero on success, nonzero otherwise * ****************************************************************************/ int fifo_put(fifo_t *fifo, void *item) { int ret = -1; if (!FIFO_FULL(*fifo)) { fifo->data[fifo->wr] = item; fifo->wr = FIFO_NEXT(*fifo, fifo->wr); ret = 0; } return ret; } /*************************************************************************//** * Remove item from FIFO * * @param[in,out] fifo FIFO context * @param[in,out] item Storage for removed item * * @return zero on success, nonzero otherwise * ****************************************************************************/ int fifo_get(fifo_t *fifo, void **item) { int ret = -1; if (!FIFO_EMPTY(*fifo)) { *item = fifo->data[fifo->rd]; fifo->rd = FIFO_NEXT(*fifo, fifo->rd); ret = 0; } return ret; } /***************************************************************************** * End of file ****************************************************************************/
C
/* ** my_realloc_all.c for tekadventure in /home/dubret_v/delivery/semestre2/infographie/tekadventure ** ** Made by dubret_v ** Login <victor.dubret@epitech.eu> ** ** Started on Thu May 25 15:52:31 2017 dubret_v ** Last update Sat May 27 16:53:39 2017 Victor Dubret */ #include <stdlib.h> #include "tekadventure.h" #include "my.h" int *realloc_int(int *arr) { int *tmp; int i; i = 0; if (arr == NULL) { arr = malloc(sizeof(int) * 2); arr[0] = 1; arr[1] = 0; return (arr); } tmp = malloc(sizeof(int) * (arr[0] + 2)); while (i <= arr[0]) { tmp[i] = arr[i]; i++; } tmp[0] += 1; return (tmp); } int (*my_realloc_int_arr(int (*arr)[2]))[2] { int (*tmp)[2]; int i; i = 1; if (arr == NULL) { arr = malloc(sizeof(int *) * 2); if (arr == NULL) return (NULL); arr[0][0] = 1; arr[0][1] = 0; return (arr); } tmp = malloc(sizeof(int *) * (arr[0][0] + 2)); while (i <= arr[0][0]) { tmp[i][0] = arr[i][0]; tmp[i][1] = arr[i][1]; i++; } tmp[0][0] = arr[0][0] + 1; tmp[0][1] = 0; return (tmp); } t_map **realloc_next_tab(t_map **new_room) { t_map **tmp; int len; int i; i = 0; if (new_room == NULL) { new_room = malloc(sizeof(t_map *) * 2); if (new_room == NULL) return (NULL); new_room[0] = NULL; new_room[1] = NULL; return (new_room); } len = next_len(new_room); tmp = malloc(sizeof(t_map *) * (len + 2)); if (tmp == NULL) return (NULL); while (i < len) { tmp[i] = new_room[i]; i++; } tmp[i] = NULL; return (tmp); } char **my_realloc_tab(char **arr) { char **tmp; int i; i = 0; if (arr == NULL) { tmp = malloc(sizeof(char *) * 2); if (tmp == NULL) return (NULL); tmp[0] = NULL; tmp[1] = NULL; return (tmp); } tmp = malloc(sizeof(char *) * (arr_len(arr) + 2)); if (tmp == NULL) return (NULL); while (arr[i] != NULL) { tmp[i] = my_strdup(arr[i]); free(arr[i]); i++; } tmp[i] = NULL; return (tmp); }
C
#include<stdio.h> int main() { int n,m; scanf("%d%d",&n,&m); int num1=0,num0=0; int i; for (i=1;i<=n;i++) { int k; scanf("%d",&k); if (k==1){num1++;} else {num0++;} } int minnum; if (num1<num0) {minnum=2*num1;} else {minnum=2*num0;} for (i=1;i<=m;i++) { int l,r; scanf("%d%d",&l,&r); if ((r-l+1)%2!=0) {printf("0\n");continue;} else { if ((r-l+1)<=minnum) { printf("1\n");continue; } else { printf("0\n");continue; } } } return 0; }
C
#ifndef SV_MERGEITER_H_ #define SV_MERGEITER_H_ /* * sham database * sphia.org * * Copyright (c) Dmitry Simonenko * BSD License */ /* * Merge serveral sorted streams into one. * Track duplicates. * * Merger does not recognize duplicates from * a single stream, assumed that they are tracked * by the incoming data sources. */ typedef struct svmergeiter svmergeiter; struct svmergeiter { srorder order; svmerge *merge; svmergesrc *src, *end; svmergesrc *v; } srpacked; static inline void sv_mergeiter_dupreset(svmergeiter *im, svmergesrc *pos) { svmergesrc *v = im->src; while (v != pos) { v->dup = 0; v = sv_mergenextof(v); } } static inline void sv_mergeiter_gt(sriter *it) { svmergeiter *im = (svmergeiter*)it->priv; if (im->v) { im->v->dup = 0; sr_iteratornext(im->v->i); } im->v = NULL; svmergesrc *min, *src; sv *minv; minv = NULL; min = NULL; src = im->src; for (; src < im->end; src = sv_mergenextof(src)) { sv *v = sr_iteratorof(src->i); if (v == NULL) continue; if (min == NULL) { minv = v; min = src; continue; } int rc = sv_compare(minv, v, it->r->cmp); switch (rc) { case 0: assert(sv_lsn(v) < sv_lsn(minv)); src->dup = 1; break; case 1: sv_mergeiter_dupreset(im, src); minv = v; min = src; break; } } if (srunlikely(min == NULL)) return; im->v = min; } static inline void sv_mergeiter_lt(sriter *it) { svmergeiter *im = (svmergeiter*)it->priv; if (im->v) { im->v->dup = 0; sr_iteratornext(im->v->i); } im->v = NULL; svmergesrc *max, *src; sv *maxv; maxv = NULL; max = NULL; src = im->src; for (; src < im->end; src = sv_mergenextof(src)) { sv *v = sr_iteratorof(src->i); if (v == NULL) continue; if (max == NULL) { maxv = v; max = src; continue; } int rc = sv_compare(maxv, v, it->r->cmp); switch (rc) { case 0: assert(sv_lsn(v) < sv_lsn(maxv)); src->dup = 1; break; case -1: sv_mergeiter_dupreset(im, src); maxv = v; max = src; break; } } if (srunlikely(max == NULL)) return; im->v = max; } static inline void sv_mergeiter_next(sriter *it) { svmergeiter *im = (svmergeiter*)it->priv; switch (im->order) { case SR_GT: case SR_GTE: sv_mergeiter_gt(it); break; case SR_LT: case SR_LTE: sv_mergeiter_lt(it); break; default: assert(0); } } static inline int sv_mergeiter_open(sriter *i, svmerge *m, srorder o) { svmergeiter *im = (svmergeiter*)i->priv; im->merge = m; im->order = o; im->src = (svmergesrc*)(im->merge->buf.s); im->end = (svmergesrc*)(im->merge->buf.p); im->v = NULL; sv_mergeiter_next(i); return 0; } static inline void sv_mergeiter_close(sriter *i srunused) { } static inline int sv_mergeiter_has(sriter *i) { svmergeiter *im = (svmergeiter*)i->priv; return im->v != NULL; } static inline void* sv_mergeiter_of(sriter *i) { svmergeiter *im = (svmergeiter*)i->priv; if (srunlikely(im->v == NULL)) return NULL; return sr_iteratorof(im->v->i); } static inline uint32_t sv_mergeisdup(sriter *i) { svmergeiter *im = (svmergeiter*)i->priv; assert(im->v != NULL); if (im->v->dup) return SVDUP; return 0; } extern sriterif sv_mergeiter; #endif
C
#include <stdio.h> int main(void) { int n,d,sum=0; printf("enter the number:\n"); scanf("%d",&n); while(n!=0) { d=n%10; sum=sum+d; n=n/10; } printf("the sum is %d",sum); return 0; }
C
/* ex2.c * * date: 2011-11-30 * author: wwq0327 <wwq0327@gmail.com> */ #include <stdio.h> void chline(char, int, int); int main() { chline('#', 5, 20); return 0; } void chline(char ch, int i, int j) { int m, n; for (m = 0; m < i; m++) { for (n = 0; n < j; n++) putchar(ch); putchar('\n'); } putchar('\n'); }
C
#include <stdio.h> int main() { char x; int n=0,k=0; while((x=getchar())!='#') { switch(x){ case 't':k++;break; case 'h':if(k==1)k++;break; case 'e':if(k==2)k++;break; default:k=0; } if(k==3) n++; } printf("%d\n",n); return 0; }
C
/* * $Id$ * * Copyright (c) 2003-2004 Peter Bex and Vincent Driessen * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the names of Peter Bex or Vincent Driessen nor the names of any * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY PETER BEX AND VINCENT DRIESSEN AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * \brief Stacks implementation. * * \file stack.c */ #include <assert.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <gune/error.h> #include <gune/stack.h> /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * \brief Create a new empty stack. * * \return A new empty stack object, or \c NULL if an error occurred. * * \par Errno values: * - \b ENOMEM if out of memory. */ stack stack_create(void) { stack_t *s; if ((s = malloc(sizeof(stack_t))) == NULL) return NULL; /* NOTE: This test is overkill, sll_create never returns NULL. */ if ((s->top = sll_create()) == NULL) { free(s); return NULL; } return (stack)s; } /** * \brief Pop the top element off a stack. * * \attention * This function logs an error at WARN_ERROR level if the stack is empty * (which will exit the application). * Therefore, always check with the stack_empty() function to see whether * a stack is empty or not. * * \param s The stack object to pop the element off. * * \return The element that was popped off. * * \sa stack_peek, stack_push, stack_empty */ gendata stack_pop(stack s) { gendata res; assert(s != NULL); assert(s->top != NULL); if (stack_empty(s)) log_entry(WARN_ERROR, "Cannot pop from an empty stack."); res = sll_get_data(s->top); s->top = sll_remove_head(s->top, NULL); return res; } /** * \brief Peek at the top element on a stack, without actually popping it. * * \attention * This function logs an error at WARN_ERROR level if the stack is empty * (which will exit the application). * Therefore, always check with the stack_empty() function to see whether * a stack is empty or not. * * \param s The stack object to peek at. * * \return The element that is on top of the stack. * * \sa stack_pop */ gendata stack_peek(stack s) { assert(s != NULL); /* * NOTE: Should we return NULL? Pop is an illegal operation on * an empty stack, but peeking isnt (?). * Also, it currently is possible to push NULL pointers as data, * so returning NULL on an empty stack would be ambiguous. * Perhaps we should do the same as with alists. */ if (stack_empty(s)) log_entry(WARN_ERROR, "Cannot peek at top element of an" " empty stack."); return sll_get_data(s->top); } /** * \brief Push data onto a stack. * * \param s The stack object to push onto. * \param data The data to push onto the stack. * * \return The given stack s, or \c NULL in case of an error. The old * stack is still valid in case of an error. * * \par Errno values: * - \b ENOMEM if out of memory. * * \sa stack_pop */ stack stack_push(stack s, gendata data) { sll l; if ((l = sll_prepend_head(s->top, data)) == NULL) return NULL; s->top = l; return s; } /** * \brief Check whether a stack is empty. * * \param s The stack to check. * * \return Non-zero if the stack is empty, 0 if it is not. */ int stack_empty(stack s) { assert(s != NULL); return sll_empty(s->top); } /** * \brief Destroy a stack by deleting each element. * * The data is freed by calling the user-supplied function \p f on it. * * \attention * If the same data is included multiple times in the stack, the free function * gets called that many times. * * \param s The stack to destroy. * \param f The function which is used to free the data, or NULL if no action * should be taken to free the data. * * \sa stack_create */ void stack_destroy(stack s, free_func f) { assert(s != NULL); sll_destroy(s->top, f); free((stack_t *)s); }
C
/*! thanks to C0t0d0s0 for this function */ byte inttostr(int n, char* s){ int order=10; if(n<order){ *(s++)=n+'0'; return 1; } byte len=2; while((len<5)&&(n>=10*order)){ order*=10; len++; } while(order){ byte digit=(n/order); *(s++)=digit+'0'; n-=digit*order; order/=10; } return len; }
C
/*********************************************************/ /* Author : Mohamed sayed */ /* Date : 13 ‎September 2020 */ /* Version : V01 */ /*********************************************************/ #include "Std_types.h" #include "BIT_MATH.h" #include "GPIO_interface.h" #include "GPIO_private.h" ErrorStatus GPIO_InitPin(GPIO_Typedef *GPIOx , DIO_Pin_t Pin , DIO_Mode_t Mode) { /*Temp variable to store the return value*/ uint8_t retvalue = E_OK ; /*Check on Pin Value*/ if(Pin <= GPIO_PIN_15) { /*Differentiate between the high control and low rigesters*/ /*Low Control rigster CRL[0,7]*/ if(Pin <= GPIO_PIN_7) { GPIOx->CRL &= ~((uint32_t)(0xF) << (Pin * 4));/*Resetting the corrisponding pin Bits value*/ GPIOx->CRL |= ((uint32_t)(Mode) << (Pin * 4)); } /*High Control rigster CRL[8,15]*/ else if(Pin <= GPIO_PIN_15) { Pin = Pin - 8 ;/*High control rigesters controls pin[8,15] and starts with bit 0*/ GPIOx->CRH &= ~((uint32_t)(0xF) << (Pin * 4)); GPIOx->CRH |= ((uint32_t)(Mode) << (Pin * 4)); } else { /*Do nothing*/ } } else { retvalue = E_NOK; } return retvalue; } ErrorStatus GPIO_WritePin(GPIO_Typedef *GPIOx, DIO_Pin_t Pin, DIO_PinStatus_t Staus) { /*Temp variable to store the return value*/ uint8_t retvalue = E_OK ; /*Check on Pin Value*/ if(Pin <= GPIO_PIN_15) { if(Staus == GPIO_PIN_HIGH) { SET_BIT(GPIOx->ODR,Pin); } else if (Staus == GPIO_PIN_LOW) { CLR_BIT(GPIOx->ODR,Pin); } else { } } else { retvalue = E_NOK; } return retvalue; } ErrorStatus GPIO_ReadPin(GPIO_Typedef *GPIOx , DIO_Pin_t Pin, uint8_t *Buffer) { /*Temp variable to store the return value*/ uint8_t retvalue = E_OK ; /*Check on Pin Value*/ if((Pin <= GPIO_PIN_15) && (Buffer != NULL)) { *Buffer = GET_BIT(GPIOx->IDR,Pin); } else { retvalue = E_NOK; } return retvalue ; } ErrorStatus GPIO_TogglePin(GPIO_Typedef *GPIOx , DIO_Pin_t Pin) { /*Temp variable to store the return value*/ uint8_t retvalue = E_OK ; /*Check on Pin Value*/ if(Pin <= GPIO_PIN_15) { TOGGLE_BIT(GPIOx->ODR,Pin); } else { retvalue = E_NOK; } return retvalue; } ErrorStatus GPIO_LockPin(GPIO_Typedef *GPIOx , DIO_Pin_t Pin) { /*Temp variable to store the return value*/ uint8_t retvalue = 0 ; /*0x00010000*/ volatile uint32_t temp = GPIO_LCKR_LCKK ; /*Storing Value of LCKK Bit in temp variable*/ /*Check on Pin Value*/ if(Pin <= GPIO_PIN_15) { /*Oring the Pin value with the LCKK Bit*/ /*Setting the corrisponding pin bit has no effect without setting LCKK BIT*/ SET_BIT(temp , Pin); /*Set LCKK Bit and corresponding pin bit*/ GPIOx->LCKR = temp; /*Reset LCKR bit*/ GPIOx->LCKR = Pin; /*Set LCKK Bit*/ GPIOx->LCKR = temp; /*first read of the rigster is mandatory*/ temp = GPIOx->LCKR; /*second read just to confirm the lock is active*/ if(((GPIOx->LCKR) & GPIO_LCKR_LCKK)) { retvalue = E_OK; } else { retvalue = E_NOK; } } else { retvalue = E_NOK; } return retvalue; }
C
#include "helper.h" /* Macros ------------------------------------------------------------------- */ /* Private Functions -------------------------------------------------------- */ /* Global Variables --------------------------------------------------------- */ /* Function Definitions ----------------------------------------------------- */ s_list_item_t *helper__create_s_list_items(uint_fast8_t num_items) { static s_list_item_t items[HELPER__S_LIST_ITEMS_MAX]; assert(num_items <= HELPER__S_LIST_ITEMS_MAX); for (uint_fast8_t i = 0; i < num_items; i ++) { s_list_item__ctor(&items[i]); } return items; } bool_t helper__s_list_items_chained(uint_fast8_t num_items, ...) { bool_t is_chained = 1; s_list_item_t *item; s_list_item_t *next; va_list ap; if (num_items == 0) { return 1; } va_start(ap, num_items); item = va_arg(ap, s_list_item_t *); while (--num_items) { next = va_arg(ap, s_list_item_t *); if (s_list_item__next(item) != next) { is_chained = 0; } item = next; } if (!s_list_item__is_last(item)) { is_chained = 0; } va_end(ap); return is_chained; } s_list_t *helper__s_list() { static s_list_t list; s_list__ctor(&list); return &list; } bool_t helper__s_list_contains(s_list_t *list, uint_fast8_t num_items, ...) { s_list_item_t *item; va_list ap; if (num_items == 0) { return s_list__is_empty(list); } item = s_list__first(list); va_start(ap, num_items); while (item != NULL) { if (item != va_arg(ap, s_list_item_t *)) { num_items = -1; break; } item = s_list_item__next(item); --num_items; } va_end(ap); return (num_items == 0); } t_list_t *helper__t_list() { static t_list_t list; t_list__ctor(&list); return &list; } bool_t helper__t_list_contains(t_list_t *list, uint_fast8_t num_items, ...) { s_list_item_t *item; s_list_item_t *arg_item; va_list ap; if (num_items == 0) { return t_list__is_empty(list); } item = t_list__first(list); va_start(ap, num_items); while (item != NULL) { arg_item = va_arg(ap, s_list_item_t *); if (item != arg_item) { num_items = -1; break; } item = s_list_item__next(item); --num_items; } va_end(ap); if (t_list__last(list) != arg_item) { return 0; } return (num_items == 0); }
C
// Idea: Iterate on base 11 using the extra digit as the asterisk. #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_SIEVE (1234567) char sieve[MAX_SIEVE]; void fill_sieve() { int i, j; memset(sieve, 0, sizeof(sieve)); sieve[0] = sieve[1] = 1; for (i = 2; i < MAX_SIEVE; i++) if (!sieve[i]) for (j = 2 * i; j < MAX_SIEVE; j += i) sieve[j] = 1; for (i = 0; i < MAX_SIEVE; i++) sieve[i] = !sieve[i]; } void print_placeholder(long placeholder) { char buffer[32]; int i = 0, j; while (placeholder) { if (placeholder % 11 == 10) buffer[i++] = '*'; else buffer[i++] = '0' + (placeholder % 11);; placeholder /= 11; } for (j = i-1; j >=0; j--) printf("%c", buffer[j]); } int has_asterisk(long placeholder) { while (placeholder) { if (placeholder % 11 == 10) return 1; placeholder /= 11; } return 0; } // returns 0 if placeholder starts with asterisk and d == 0. long get_n(long placeholder, int d) { int mult = 1, n = 0; while (placeholder) { if (placeholder/11 == 10 && d == 0) return 0; int c = placeholder % 11; if (c == 10) n += mult * d; else n += mult * c; mult *= 10; placeholder /= 11; } return n; } int main() { fill_sieve(); long placeholder = 0; int i, n_primes, n, min = 8; while (++placeholder) { if (has_asterisk(placeholder)) { n_primes = 0; for (i = 0; i < 10; i++) { n = get_n(placeholder, i); n_primes += sieve[n]; } if (n_primes >= min) break; } } for (i = 0; i < 10; i++) { if (sieve[get_n(placeholder, i)]) { printf("Placeholder "); print_placeholder(placeholder); printf(": %d primes. First is %ld.\n", n_primes, get_n(placeholder, i)); break; } } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* md5.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fherbine <fherbine@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/03 16:27:32 by fherbine #+# #+# */ /* Updated: 2020/11/03 16:27:32 by fherbine ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/ft_ssl.h" static void initialize_md5(t_md5 *md5_struct) { md5_struct->a = MD5_H0; md5_struct->b = MD5_H1; md5_struct->c = MD5_H2; md5_struct->d = MD5_H3; } void md5_main_loop(t_md5 *ms, uint32_t *buffer) { uint32_t i; uint32_t fg[2]; i = 0; while (i < 64) { if (i <= 15) md5_helper_1(&i, ms->vars, fg); else if (i >= 16 && i <= 31) md5_helper_2(&i, ms->vars, fg); else if (i >= 32 && i <= 47) md5_helper_3(&i, ms->vars, fg); else md5_helper_4(&i, ms->vars, fg); fg[0] = fg[0] + ms->vars[0] + g_cst_md5[i] + buffer[fg[1]]; ms->vars[0] = ms->vars[3]; ms->vars[3] = ms->vars[2]; ms->vars[2] = ms->vars[1]; ms->vars[1] = ms->vars[1] + leftrotate(fg[0], g_shift_md5[i]); i++; } } static char *md5_algorithm(t_md5 md5_struct) { uint64_t i; char *o; i = 0; initialize_md5(&md5_struct); while (i * 32 < md5_struct.bits_count) { md5_struct.vars[0] = md5_struct.a; md5_struct.vars[1] = md5_struct.b; md5_struct.vars[2] = md5_struct.c; md5_struct.vars[3] = md5_struct.d; md5_main_loop(&md5_struct, &(md5_struct.blocks[i])); md5_struct.a += md5_struct.vars[0]; md5_struct.b += md5_struct.vars[1]; md5_struct.c += md5_struct.vars[2]; md5_struct.d += md5_struct.vars[3]; i += 16; } o = bword2str(reverse_edianness_32(md5_struct.a), 16, 32); o = outputs_join(o, bword2str(reverse_edianness_32(md5_struct.b), 16, 32)); o = outputs_join(o, bword2str(reverse_edianness_32(md5_struct.c), 16, 32)); o = outputs_join(o, bword2str(reverse_edianness_32(md5_struct.d), 16, 32)); return (o); } static void free_struct(t_md5 mstruct) { free(mstruct.blocks); } char *md5(t_rstream rstream) { uint64_t bcount; uint32_t *blocks; t_md5 md5_struct; char *ret; bcount = block_padding(rstream.buffer, &blocks, rstream.bytes); md5_struct.bits_count = bcount; md5_struct.blocks = blocks; ret = md5_algorithm(md5_struct); free_struct(md5_struct); return (ret); }
C
#include "CreatePopulation.h" #include "ExamStruct.h" #include "PaperListConvertion.h" #include "Random.h" #include "printfStructs.h" #include <stdio.h> Table *getPopulation(Paper *papersArr[], int size, int maxPeopleInSession, int populationNum){ Table *tabArr, arr[size]; LinkedList *pList; int i; for( i = 0; i < populationNum; i++){ shuffleArray( papersArr, size); pList = convertArrayToLinkedList( papersArr, size); // papersListIntoTable( &arr[i], pList, maxPeopleInSession); } return tabArr; } LinkedList *convertArrayToLinkedList(Paper *papersArr[], int size){ int i; LinkedList *paperList = NULL; for( i = 0 ; i < size ; i++) addDataToHead( &paperList, papersArr[i]); return paperList; } void shuffleArray( Paper *papersArr[], int size){ int i,x; Paper *temp; for( i=0 ; i < size ; i++){ x = random(size); temp = papersArr[x]; papersArr[x] = papersArr[i]; papersArr[i] = temp; } }
C
#include "libmx.h" unsigned long mx_hex_to_nbr (const char *hex) { unsigned long nbr = 0; char byte = 0; if (!hex) return 0; while (*hex) { byte = *hex++; if (byte >= '0' && byte <= '9') byte = byte - '0'; else if (byte >= 'a' && byte <= 'f') byte = byte - 'a' + 10; else if (byte >= 'A' && byte <= 'F') byte = byte - 'A' + 10; nbr = (nbr << 4) | (byte & 0xF); } return nbr; }
C
#include <stdio.h> #include <stdlib.h> struct ListNode { int val; struct ListNode *next; }; struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { unsigned long long n1=0,n2=0,nresult,nresult2; int nn; int p=1; struct ListNode* p1=l1; struct ListNode* p2=l2; struct ListNode* resultp,*newnode,*result; for(int i=0; ;i++){ if(i!=0){ p=p*10; } if(p1!=NULL){ n1=n1+(p1->val)*p; //printf("n1=%d\n",n1); p1=p1->next; } if(p2!=NULL){ n2=n2+(p2->val)*p; //printf("n2=%ld\n",n2); //printf("%d %d %ld\n",p2->val,p,p*(p2->val)); p2=p2->next; } if(p1==NULL && p2==NULL){ break; } } nresult=n1+n2; //printf("%d+%d=%d\n",n1,n2,nresult); int d=10,r=10; nresult2=nresult; if(nresult2==0){ newnode=(struct ListNode*)malloc(sizeof(struct ListNode)); newnode->val=0; newnode->next=NULL; result=newnode; return result; } for(int j=0;;j++){ if(nresult2==0){ resultp->next=NULL; break; } nn=nresult2%r; nresult2=nresult2/d; newnode=(struct ListNode*)malloc(sizeof(struct ListNode)); newnode->val=nn; newnode->next=NULL; if(j==0){ result=newnode; resultp=newnode; continue; } resultp->next=newnode; resultp=resultp->next; } return result; } int main(){ struct ListNode *l1, *l2,*newnode,*p,*result; for(int i=0;i<9;i++){ newnode=(struct ListNode*)malloc(sizeof(struct ListNode)); newnode->val=9; newnode->next=NULL; if(i==0){ l1=newnode; l1->next=NULL; p=l1; continue; } p->next=newnode; p=p->next; } for(int i=0;i<9;i++){ newnode=(struct ListNode*)malloc(sizeof(struct ListNode)); newnode->val=9; newnode->next=NULL; if(i==0){ l2=newnode; l2->next=NULL; p=l2; continue; } p->next=newnode; p=p->next; } result=addTwoNumbers(l1,l2); for(int i=0;i<15;i++){ if(result==NULL){ printf("\n"); break; } printf("%d->",result->val); result=result->next; } result=addTwoNumbers2(l1,l2); for(int i=0;i<15;i++){ if(result==NULL){ printf("\n"); break; } printf("%d->",result->val); result=result->next; } return 0; }
C
#include<stdio.h> #include<math.h> main() { int demandrate,setupcost,hcpipt,sqrt; float EOQ,TBO; printf("Enter the values of demandrate,setupcost,hcpipt"); scanf("%d %d %d",&demandrate,&setupcost,&hcpipt); EOQ=sqrt(2*demandrate*setupcost/hcpipt); TBO=sqrt(2*setupcost/demandrate*hcpipt); printf("EOQ is :%f\n",EOQ); printf("TBO is :%f",TBO); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "options.h" #include "decrypt.h" #include "help.h" char *arg1 = "", *arg2 = "", *arg3 = ""; void define_mode(int argc, char const *argv[], int *mode) { if (argc > 1) { if (strcmp(argv[1],"-d") == 0) { if (argc > 2) { if (strcmp(argv[2],"-cipher") == 0) { *mode = validate_num_arguments(argc, 6, DEBUGMODE + CIPHERMODE); } else if (strcmp(argv[2],"-key") == 0) { *mode = DEBUGMODE + KEYMODE; } else { *mode = validate_num_arguments(argc, 5, DEBUGMODE + CIPHERMODE); } } else { *mode = NUMARGERR; } } else if (strcmp(argv[1],"-cipher") == 0) { *mode = validate_num_arguments(argc, 5, CIPHERMODE); } else if (strcmp(argv[1],"-key") == 0) { *mode = KEYMODE; } else if (strcmp(argv[1],"-help") == 0) { if (argc == 3) { if (strcmp(argv[2],"-cipher") == 0) { *mode = HELPCIPHERMODE; } else if (strcmp(argv[2],"-key") == 0) { *mode = HELPKEYMODE; } else if (strcmp(argv[2],"-all") == 0) { *mode = HELPMODE; } else { *mode = DEFAULTERR; } } else if (argc == 2) { *mode = HELPMODE; } else { *mode = NUMARGERR; } } else { *mode = validate_num_arguments(argc, 4, CIPHERMODE); } } else { *mode = NUMARGERR; } define_parameters(argc, argv, *mode); } int validate_num_arguments(int argc, int num_args, int selected_mode) { if (argc == num_args) { return selected_mode; } else { return NUMARGERR; } } void define_execution(char const *argv[], int mode) { switch (mode) { case CIPHERMODE: //fprintf(stdout, "Opção Selecionada: %d - CIPHERMODE\n", CIPHERMODE); cribdrag(fopen(arg1,"rb"), fopen(arg2,"rb"), fopen(arg3,"rb")); break; case KEYMODE: //fprintf(stdout, "Opção Selecionada: %d - KEYMODE\n", KEYMODE); discover_key(fopen(arg1,"rb"), fopen(arg2,"rb"), arg3); break; case HELPMODE: //fprintf(stdout, "Opção Selecionada: %d - HELPMODE\n", HELPMODE); help_all(); break; case HELPKEYMODE: //fprintf(stdout, "Opção Selecionada: %d - HELPKEYMODE\n", HELPKEYMODE); help_key(); break; case HELPCIPHERMODE: //fprintf(stdout, "Opção Selecionada: %d - HELPCIPHERMODE\n", HELPCIPHERMODE); help_cipher(); break; case DEBUGMODE + CIPHERMODE: //fprintf(stdout, "Opção Selecionada: %d - DEBUGMODE + CIPHERMODE\n", DEBUGMODE + CIPHERMODE); debug_mode = 1; cribdrag(fopen(arg1,"rb"), fopen(arg2,"rb"), fopen(arg3,"rb")); break; case DEBUGMODE + KEYMODE: //fprintf(stdout, "Opção Selecionada: %d - DEBUGMODE + KEYMODE\n", DEBUGMODE + KEYMODE); debug_mode = 1; discover_key(fopen(arg1,"rb"), fopen(arg2,"rb"), arg3); break; case NUMARGERR: fprintf(stderr, "ERRO - número de parâmetros inválido!\n"); break; default: fprintf(stderr, "ERRO - Opção Inválida selecionada!\n"); } } void define_parameters(int argc, char const *argv[], int mode) { switch (mode) { case CIPHERMODE: case DEBUGMODE + CIPHERMODE: arg1 = argv[argc - 3]; arg2 = argv[argc - 2]; arg3 = argv[argc - 1]; break; case KEYMODE: if (argc == 5) { arg1 = argv[argc - 3]; arg2 = argv[argc - 2]; arg3 = argv[argc - 1]; } else { arg1 = argv[argc - 2]; arg2 = argv[argc - 1]; arg3 = (char*)calloc(1, sizeof(char)); } break; case DEBUGMODE + KEYMODE: if (argc == 6) { arg1 = argv[argc - 3]; arg2 = argv[argc - 2]; arg3 = argv[argc - 1]; } else { arg1 = argv[argc - 2]; arg2 = argv[argc - 1]; arg3 = (char*)calloc(1, sizeof(char)); } break; } }
C
/** Filename: map_driver.c (driver of map.h) Description: ADT Map dengan menggunakan matriks.h **/ #include "boolean.h" #include "map.h" #include <stdio.h> #include "command.h" int main() { /* KAMUS */ int X, Y; POINT P; /* MakeMATRIKS */ printf("Ukuran map : "); scanf("%d %d", &X, &Y); MakeEmptyMap(X, Y); MakeNormalPlot(); currPlayer = Nil; SelectedUnit = Nil; printf("Peta setelah MakeEmptyMap dan MakeNormalPlot :\n"); PrintMap(); printf("\n"); printf("Peta setelah MakePlayerPlot :\n"); MakePlayerPlot(); PrintMap(); printf("\n"); printf("Peta setelah CreateVillage :\n"); CreateVillage(); PrintMap(); printf("\n"); printf("Cek apakah koordinat ada di map : "); BacaPOINT(&P); printf("IsPlotInMap(M,P) = "); if(IsPlotInMap(M,P)){ printf("true\n"); } else{ printf("false\n"); } printf("\n"); return 0; }
C
// // Created by weihs on 28/04/2021. // #include <stdio.h> #include <stdlib.h> #include <omp.h> #include <time.h> void exclusive_prefix(const int32_t* arr, int32_t* ret, long length) { for (int i = 1; i < length; i++) { ret[i] = ret[i - 1] + arr[i - 1]; } } int main(int argc, char* argv[]) { if(argc != 2){ printf("Usage: name <length>\n"); exit(EXIT_FAILURE); } // initialize array long length = strtol((const char*) argv[1], NULL, 10); int32_t* arr = (int32_t*)calloc((size_t) length, (size_t) sizeof(int32_t)); if (!arr) goto cleanup_arr; int32_t* ret = (int32_t*)calloc((size_t) length, (size_t) sizeof(int32_t)); if (!ret) goto cleanup_ret; for(int i = 0; i < length; i++) arr[i] = 1; double startTime = omp_get_wtime(); exclusive_prefix(arr, ret, length); double endTime = omp_get_wtime(); printf("Wall Time: %.5f seconds\nb[-1] = %d\n", endTime - startTime, ret[length-1]); return EXIT_SUCCESS; cleanup_ret: free(ret); cleanup_arr: free(arr); return EXIT_FAILURE; }
C
/* Project 2 for COMP30023: Computer Systems * at the University of Melbourne * Semester 1, 2017 * by: Ammar Ahmed */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <inttypes.h> #include <stdbool.h> #include <signal.h> #include "server.h" #include "mine.h" #include "list.h" #include "input-handler.h" FILE* log_file; List* work_queue; int main(int argc, char **argv) { int sockfd, newsockfd, portno, servlen; struct sockaddr_in address; pthread_t tid; int n, i, j, k = 0; int client_sockets[MAX_CLIENTS], max_sd, activity; fd_set readfds; work_queue = new_list(); pthread_create(&tid, NULL, (void*)&search_for_work, NULL); // a buffer for each of the clients char** buffers = malloc(sizeof(char*)*100); char temp[256]; memset(temp, '\0', 256); log_file = fopen("log.txt", "w"); // Printing descriptors in file heading fprintf(log_file, "Time IP SocketID Message\n"); fflush(log_file); // Handling broken pipes signal(SIGPIPE, SIG_IGN); for (i = 0; i < MAX_CLIENTS; i++) client_sockets[i] = 0; if (argc < 2) { fprintf(stderr,"ERROR, no port provided\n"); exit(1); } /* Create TCP socket */ sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { perror("ERROR opening socket"); exit(1); } bzero((char *) &address, sizeof(address)); portno = atoi(argv[1]); /* Create address we're going to listen on (given port number) - converted to network byte order & any IP address for this machine */ address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(portno); // store in machine-neutral format /* Bind address to the socket */ if (bind(sockfd, (struct sockaddr *) &address, sizeof(address)) < 0) { perror("ERROR on binding"); exit(1); } //try to specify maximum of 100 pending connections for the master socket if (listen(sockfd, MAX_CLIENTS) < 0) { perror("listen"); exit(EXIT_FAILURE); } servlen = sizeof(address); log_to_file("Starting up the server", inet_ntoa(address.sin_addr), newsockfd); //TODO: change this to accomodate for windows carriage return while (true) { // Setting all the file descriptors to 0 FD_ZERO(&readfds); // Adding our original socket to the set FD_SET(sockfd, &readfds); max_sd = sockfd; for (i = 0; i < MAX_CLIENTS; i++) { if (client_sockets[i] > 0) FD_SET(client_sockets[i], &readfds); if (client_sockets[i] > max_sd) max_sd = client_sockets[i]; } // This waits for any activity in any of the sockets activity = select(max_sd + 1, &readfds, NULL, NULL, NULL); if ((activity < 0) && (errno!=EINTR)) printf("select error"); //If something happened on the master socket , //then its an incoming connection if (FD_ISSET(sockfd, &readfds)) { /* Accept a connection - block until a connection is ready to be accepted. Get back a new file descriptor to communicate on. */ if ((newsockfd = accept(sockfd, (struct sockaddr *)&address, (socklen_t*)&servlen)) < 0) { perror("accept"); exit(EXIT_FAILURE); } /* Read characters from the connection, then process */ //add new socket to array of sockets for (i = 0; i < MAX_CLIENTS; i++) { //if position is empty if( client_sockets[i] == 0 ) { client_sockets[i] = newsockfd ; buffers[i] = malloc(sizeof(char)*256); memset(buffers[i], '\0', 256); //printf("Adding to list of sockets as %d\n" , i); log_to_file("Adding new client to list of sockets", inet_ntoa(address.sin_addr), newsockfd); break; } } } //else its some IO operation on some other socket //TODO: change this to handle clients for (i = 0; i < MAX_CLIENTS; i++) { newsockfd = client_sockets[i]; if (FD_ISSET(newsockfd , &readfds)) { //Check if it was for closing , and also read the //incoming message //TODO: remove magic number for the size of val read n = read(newsockfd, temp, 256); log_to_file(temp, inet_ntoa(address.sin_addr), newsockfd); if (n+strlen(buffers[i]) > 256) { send_erro((BYTE*)"Message length too long", newsockfd); continue; } strcat(buffers[i], temp); memset(temp, '\0', 256); if (n == 0) { // Close the socket and mark as 0 in list for reuse // We also need to free all its jobs in the queue log_to_file("Disconnecting this client from the server", inet_ntoa(address.sin_addr), newsockfd); handle_abrt(newsockfd, work_queue, false); free(buffers[i]); close(newsockfd); client_sockets[i] = 0; continue; } else { for (j = 0; j < 256; j++, k++) { if (buffers[i][j] == '\0') break; if (j != 255 && buffers[i][j] == '\r' && buffers[i][j+1] == '\n') { char *message_to_process = malloc(sizeof(char) * 257); strncpy(message_to_process, buffers[i], j); message_to_process[j] = '\0'; handle_input(newsockfd, message_to_process, work_queue); k = 0; j += 2; memset(buffers[i], 0, 256); memset(message_to_process, '\0', 257); continue; } } } } } } /* close socket */ close(sockfd); return 0; } void log_to_file(char* msg, char* ip, int sockfd) { struct tm* loc_time; time_t curr_time; curr_time = time(NULL); loc_time = localtime(&curr_time); fprintf(log_file, "%02d:%02d:%02d, ", loc_time->tm_hour, loc_time->tm_min, loc_time->tm_sec); // Now we need to put in the IP-Address fprintf(log_file, "%s, ", ip); fprintf(log_file, "%d, ", sockfd); fprintf(log_file, "%s\n\n", msg); fflush(log_file); } void search_for_work() { while(true) { //fprintf(stdout, "Threads find size %d\n", work_queue->size); //fflush(stdout); if (get_size(work_queue) > 0) { //fprintf(stdout, "Starting work\n"); fflush(stdout); struct work_args * args = (struct work_args*)work_queue->head->data; work(*args); list_remove_start(work_queue); } } } void add_to_queue(void* in_args) { list_add_end(work_queue, in_args); //fprintf(stdout, "Length of queue is now %d\n", work_queue->size); }
C
#include "stdio.h" #include "stdlib.h" #define AND 2 #define OR 3 #define NOT 4 #define TRUE 1 #define FALSE 0 #define VAR 5 typedef struct node *treePointer; struct node { int value; int data; treePointer left, right; }; treePointer CreatTree(int value, int data, treePointer *father) { treePointer NewTree; NewTree = malloc(sizeof(*NewTree)); if(father != NULL) { *father = NewTree; } NewTree -> value = value; NewTree -> data = data; NewTree -> left = NULL; NewTree -> right = NULL; return NewTree; } void inorder(treePointer ptr) { if(ptr) { inorder(ptr -> left); printf("%d\n", ptr -> value); inorder(ptr -> right); } } void preorder(treePointer ptr) { if(ptr) { printf("%d\n", ptr -> value); preorder(ptr -> left); preorder(ptr -> right); } } void postorder(treePointer ptr) { if(ptr) { postorder(ptr -> left); postorder(ptr -> right); printf("%d\n", ptr -> value); } } treePointer TreeCopy(treePointer source) { treePointer temp; if(source) { temp = malloc( sizeof(temp) ); temp -> left = TreeCopy(source -> left); temp -> right = TreeCopy(source -> right); temp -> value = source -> value; return temp; } return NULL; } int TreeEqual(treePointer first, treePointer second) { return ( !first && !second ) || ( first && second && (first -> value == second -> value) && TreeEqual(first -> left, second -> left) && TreeEqual(first -> right, second -> right) ); } void postOrderEval(treePointer node) { if(node) { postOrderEval(node -> left); postOrderEval(node -> right); switch(node -> data) { case NOT : { node -> value = ~( node -> right -> value ); } break; case AND : { node -> value = (node -> right -> value) & (node -> left -> value); } break; case OR : { node -> value = (node -> right -> value) | (node -> left -> value); } break; case TRUE : { node -> value = 1; } break; case FALSE: { node -> value = 0; } break; } } } main() { treePointer master; master = CreatTree(0, OR, NULL); CreatTree(0x0, OR , &(master -> left) ); CreatTree(0x0, NOT, &(master -> right) ); CreatTree(0x0, AND, &(master -> left -> left) ); CreatTree(0x0, AND, &(master -> left -> right) ); CreatTree(0x4, VAR, &(master -> right -> right) ); CreatTree(0x1, VAR, &(master -> left -> left -> left) ); CreatTree(0x0, NOT, &(master -> left -> left -> right) ); CreatTree(0x0, NOT, &(master -> left -> right -> left) ); CreatTree(0x4, VAR, &(master -> left -> right -> right) ); CreatTree(0x2, VAR, &(master -> left -> left -> right -> right) ); CreatTree(0x1, VAR, &(master -> left -> right -> left -> right) ); // copy = TreeCopy(master); postOrderEval(master); printf("%d\n", master -> value); // printf("%d\n", TreeEqual(master, copy)); }
C
/* * dmaz - dumps an xtank maze out to a terminal. */ /* Return values for description loading */ #define DESC_LOADED 0 #define DESC_SAVED 1 #define DESC_NOT_FOUND 2 #define DESC_BAD_FORMAT 3 #define DESC_NO_ROOM 4 #define GRID_HEIGHT 30 #define GRID_WIDTH 30 #define MAZE_HEIGHT 26 #define MAZE_WIDTH 26 #define MAZE_TOP 2 #define MAZE_BOTTOM 27 #define MAZE_LEFT 2 #define MAZE_RIGHT 27 /* Flags for boxes in a maze description */ #define INSIDE_MAZE (1<<0) #define NORTH_WALL (1<<1) #define WEST_WALL (1<<2) #define NORTH_DEST (1<<3) #define WEST_DEST (1<<4) #define TYPE_EXISTS (1<<5) #define TEAM_EXISTS (1<<6) #define EMPTY_BOXES (1<<7) #define MAZE_FLAGS (INSIDE_MAZE|NORTH_WALL|WEST_WALL|NORTH_DEST|WEST_DEST) #include <stdio.h> #include <sys/types.h> typedef unsigned char Byte; typedef struct { Byte type; char *name; char *designer; char *desc; Byte *data; } Mdesc; char *mtypes[] = { "Combat", "War", "Ultimate", "Capture", "Race", }; char *derrs[] = { "none", "saved???", "Maze not found", "Maze bad format", "No room to store maze", }; main (argc, argv) int argc; char **argv; { Mdesc d; int er; char *ri, *rindex(); if(ri = rindex(argv[1],'.')) *ri = '\0'; if(er = load_mdesc(&d, argv[1])) { fputs("dmaz: ",stderr); fputs(derrs[er], stderr); putc('\n', stderr); exit(1); } fputs("Maze name: ",stdout); puts(d.name); fputs("Maze type: ",stdout); puts(mtypes[d.type]); fputs("Designer: ",stdout); puts(d.designer); fputs("Description: ",stdout); puts(d.desc); dumpmaze(&d); return 0; } /* * text layout of the maze: * north and west walls, real/dest, team, thing: * * === real wall --- dest wall * # | * # | * * === === * # A #1A * #A #A1 * */ char pics[17][4] = { " ", "FUEL", "AMMO", "ARMR", "GOAL", "OUCH", "/\\||", "-+/|", "->->", "\\|-+", "||\\/", "|/+-", "<-<-", "+-|\\", "SLIP", "SLOW", "\\//\\", }; typedef unsigned int Flag; typedef struct { Flag flags; /* bits for walls, inside maze */ Byte type; /* landmark, scroll, goal, outpost, etc. */ Byte team; /* number of team that owns the box */ } Box; extern Box box[GRID_WIDTH][GRID_HEIGHT]; dumpmaze(md) Mdesc *md; { int i, j, k; Box bp; make_maze(md); for(i=MAZE_TOP; i<=MAZE_BOTTOM+1; i++) { for(j=MAZE_LEFT; j<=MAZE_RIGHT; j++) { int bpt = (box[j][i].flags&WEST_WALL) ||(box[j-1][i].flags&NORTH_WALL); bp = box[j][i]; if(bp.flags & NORTH_WALL) { if(bp.flags & NORTH_DEST) { putchar(bpt?'+':'-'); putchar('-'); putchar('-'); } else { putchar(bpt?'#':'='); putchar('='); putchar('='); } } else { putchar(bpt?'#':' '); putchar(' '); putchar(' '); } } putchar('\n'); if(i<= MAZE_BOTTOM) for(k=0;k<4;k+=2) { for(j=MAZE_LEFT; j<=MAZE_RIGHT; j++) { bp = box[j][i]; if(bp.flags & WEST_WALL) { if(bp.flags & WEST_DEST) putchar('|'); else putchar('#'); } else putchar(' '); putchar(pics[bp.type][k]); putchar(pics[bp.type][k+1]); } putchar('\n'); } } }
C
#include <stdio.h> #include <math.h> double fract(double input) { double fractorial = 1; for(int i = 1; i <= input; i++) fractorial *= i; return fractorial; } int main() { double ex = 0; int x = 0; scanf("%d", &x); for(int i = 1; i < 200; i++) { ex += (pow(x, i) / fract(i)); } ex ++; printf("e^x = 1+x/1!+x^2/2!+x^3/3!+x^4/4!+... = %.9f...\n", ex); return 0; }
C
#include "details.h" #include <stdio.h> int main(void) { printf("This program sorts entered integers into even and odd types" " and calculates their totals.\n"); printf("Please enter integers to be analyzed(0 to quit):\n"); int n; int odd = 0; int even = 0; float total_even = 0; float total_odd = 0; float avg_even = 0; float avg_odd = 0; int n_even = 0; int n_odd = 0; while(scanf("%d", &n) != 0 && (n != 0)) { if(n % 2 == 0) { n_even++; total_even += n; } else { n_odd++; total_odd += n; } } printf("No. of even integers = %d, their total = %d and their average = %f.\n", n_even, total_even, total_even / n_even); printf("No. of odd integers = %d, their total = %d and their average = %f.\n", n_odd, total_odd, total_odd / n_odd); details(); return 0; }
C
#include <string.h> #include <errno.h> #include <stdbool.h> #include "mf_malloc.h" #include "mfdef.h" #include "log.h" #include "bug.h" #include "skiplist.h" #include "chunk.h" #include "map.h" #define HASHTABLE_SIZE 1024 static inline uint16_t hash(const hkey_t *key) { return key->idx % HASHTABLE_SIZE; } typedef struct elem { hkey_t key; hval_t val; bool valid; } elem_t; struct map { elem_t cache[HASHTABLE_SIZE]; skiplist_t *skiplist; }; /* map_t */ int map_construct(map_t **map_ptr) { int err; if(unlikely((err = mf_malloc(sizeof(map_t), (void**)map_ptr)))) { return err; } map_t *map = *map_ptr; for(int i = 0; i < HASHTABLE_SIZE; i++ ) { map->cache[i].valid = false; } return skiplist_construct(24, &map->skiplist); } int map_destruct(map_t *map) { #ifdef DEBUG if(unlikely(map == NULL)) { return EINVAL; } for(int i = 0; i < HASHTABLE_SIZE; i++ ) { map->cache[i].valid = false; } #endif skiplist_destruct(map->skiplist); return 0; } static int right_cmp(hval_t val1, hval_t val2) { off_t right1 = val1->key.idx + val1->key.len; off_t right2 = val2->key.idx + val2->key.len; return (right1 > right2) ? 1 : (right1 < right2) ? -1 : 0; } int map_add(map_t * map, hkey_t *key, hval_t val) { #ifdef DEBUG if(unlikely(map == NULL || key == NULL)) { return EINVAL; } #endif unsigned idx = hash(key); map->cache[idx].key.idx = key->idx; map->cache[idx].key.len = key->len; hval_t oldval; int err = skiplist_lookup_le(map->skiplist, key->idx, (val_t *)&oldval); if(unlikely(err && err != ENOKEY)) { return err; } if(!err && right_cmp(oldval, val) > -1) { map->cache[idx].val = oldval; map->cache[idx].valid = true; val->is_indexed = false; return EKEYREJECTED; } while(true) { err = skiplist_lookup_ge(map->skiplist, key->idx, (val_t *)&oldval); if(unlikely(err && err != ENOKEY)) { return err; } if(err == ENOKEY) { break; } if( right_cmp(oldval, val) < 1 ) { if(unlikely((err = skiplist_del(map->skiplist, oldval->key.idx)))) { return err; } oldval->is_indexed = false; map->cache[hash(&oldval->key)].valid = false; } else { break; } } val->is_indexed = true; map->cache[idx].val = val; map->cache[idx].valid = true; return skiplist_add(map->skiplist, key->idx, val); } int map_lookup_le(const map_t * map, hkey_t *key, hval_t *val_ptr) { #ifdef DEBUG if(unlikely(map == NULL || key == NULL || val_ptr == NULL)) return EINVAL; #endif elem_t elem = map->cache[hash(key)]; if(elem.valid && elem.key.idx == key->idx && elem.key.len >= key->len) { *val_ptr = elem.val; return 0; } return skiplist_lookup_le(map->skiplist, key->idx, (val_t *)val_ptr); } int map_del(map_t *map, hkey_t *key, bool is_indexed) { #ifdef DEBUG if(unlikely(map == NULL || key == NULL)) return EINVAL; #endif map->cache[hash(key)].valid = false; return is_indexed ? skiplist_del(map->skiplist, key->idx) : 0; }