blob_id
large_stringlengths
40
40
language
large_stringclasses
1 value
repo_name
large_stringlengths
4
124
path
large_stringlengths
2
969
src_encoding
large_stringclasses
35 values
length_bytes
int64
6
2.95M
score
float64
2.52
5.44
int_score
int64
3
5
detected_licenses
large listlengths
0
58
license_type
large_stringclasses
2 values
text
stringlengths
9
2.95M
download_success
bool
1 class
308f265976cbca94c4c869b0bd8b784b19d23475
C
easyli/OpenJudgeC
/1w/4.c
UTF-8
136
2.734375
3
[]
no_license
#include <stdio.h> int main(void) { char c; int x; scanf("%d",&x); c=(char)x; printf("%c",c); return 0; }
true
90d1046420b7b6e4b89aa4c75933e740efeddb22
C
CurlyWurly-1/STM8S103F3P6-development-board
/CODE/ZST_Workspace_FOLDER/main_adc_test.c
UTF-8
3,606
3
3
[]
no_license
// reads value on ADC channel 2, which is AIN2 on Pin PC4 (pin 14) // and send it via UART #include "stm8s.h" #include "stdafx.h" #define WITH_UART_EXP 1 char count = 0; char digit[5] = ""; int main( void ){ uint16_t i; // Always use standardized variable types... uint16_t nCount = 0; uint16_t adc_value = 0; uint8_t adc_h = 0; uint8_t adc_l = 0; uint16_t nAdc_Buffer[10] = {0,0,0,0,0,0,0,0,0,0}; uint16_t nAdc_Hold = 0; // Reset GPIO port B and set up output for onboard LED (pin 5) GPIO_DeInit(GPIOB); GPIO_Init(GPIOB, GPIO_PIN_5, GPIO_MODE_OUT_PP_LOW_FAST); //Initialization of the clock /* Clock divider to HSI/1 */ //CLK_HSIPrescalerConfig(CLK_PRESCALER_HSIDIV1); UART_Config(); // UART Config ADC_Config(); // ADC Config ADC1_StartConversion(); // Start your ADC engine! // The main loop while(1){ delay_ms(500); // Light on board LED GPIO_WriteLow(GPIOB, GPIO_PIN_5); // Read 10 times (it works, but not a great idea) for ( nCount = 0; nCount< 10; nCount++){ nAdc_Buffer[nCount] = ADC1_GetConversionValue(); nAdc_Hold += nAdc_Buffer[nCount]; } // Overwrite average into first cell nAdc_Buffer[0] = nAdc_Hold / 10; adc_value = nAdc_Buffer[0]; adc_h = (uint8_t)((adc_value & 0xff00)>>8); adc_l = (uint8_t)((adc_value & 0x00ff)); for ( nCount = 0; nCount< 10; nCount++){ nAdc_Buffer[nCount] = 0; } nAdc_Hold = 0; #ifdef WITH_UART_EXP // UART1_SendData8((uint8_t)0x00); // UART1_SendData8((uint8_t)adc_h); // UART1_SendData8((uint8_t)0x20); // UART1_SendData8((uint8_t)adc_l); // UART1_SendData8((uint8_t)adc_value); if (adc_value == 0){ UART1_SendData8((char)'0'); // Single space while (UART1_GetFlagStatus(UART1_FLAG_TXE) == RESET); // wait for sending UART1_SendData8((char)' '); // Single space while (UART1_GetFlagStatus(UART1_FLAG_TXE) == RESET); // wait for sending }else{ while (adc_value != 0) //split the int to char array { digit[count] = adc_value%10; count++; adc_value = adc_value/10; } while (count !=0) //print char array in correct direction { UART1_SendData8(digit[count-1] + 0x30); // Send number as a character while (UART1_GetFlagStatus(UART1_FLAG_TXE) == RESET); // wait for sending count--; } UART1_SendData8((char)' '); // Single space while (UART1_GetFlagStatus(UART1_FLAG_TXE) == RESET); // wait for sending // UART1_SendData8((uint8_t)0x0A); // Line Feed // while (UART1_GetFlagStatus(UART1_FLAG_TXE) == RESET); // wait for sending }; #endif // WITH_UART_EXP // LED Off GPIO_WriteHigh(GPIOB, GPIO_PIN_5); } } static void UART_Config(void){ //Reset uart UART1_DeInit(); UART1_Init((uint32_t) 9600, UART1_WORDLENGTH_8D, UART1_STOPBITS_1, UART1_PARITY_NO, UART1_SYNCMODE_CLOCK_DISABLE, UART1_MODE_TXRX_ENABLE ); } static void ADC_Config( void ){ // GPIO_Init(GPIOB, GPIO_PIN_0, GPIO_MODE_IN_FL_NO_IT ); GPIO_Init (GPIOC, GPIO_PIN_4, GPIO_MODE_IN_FL_IT); ADC1_DeInit(); // ADC1_Init(ADC1_CONVERSIONMODE_CONTINUOUS, ADC1_CHANNEL_0, ADC1_PRESSEL_FCPU_D2, ADC1_EXTTRIG_TIM,DISABLE, ADC1_ALIGN_RIGHT, ADC1_SCHMITTTRIG_CHANNEL0, DISABLE ); ADC1_Init(ADC1_CONVERSIONMODE_CONTINUOUS, ADC1_CHANNEL_2, ADC1_PRESSEL_FCPU_D2, ADC1_EXTTRIG_TIM,DISABLE, ADC1_ALIGN_RIGHT, ADC1_SCHMITTTRIG_CHANNEL2, DISABLE ); }
true
801c1a4669f1f3e81b1d6034b265247b97e8d634
C
avue7/551
/p2b/tmin_backup.c
UTF-8
7,938
3.390625
3
[]
no_license
/** * @file tmin.c * * @brief * This program performs a numerical integration using the * Trapezoidal Method. The upper and lower bound is accepted * as the inputs and t to represent the minimum trapezoids * need in order to be as accurate as we can to 14 significant * figures of the true value of 4754.0192288588181366. The * function to be integrated is hardcoded below. This program * is a parallel program using MPI to calculate the definite * integral. * * @author Athit Vue * @date 10/01/2017 */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <mpi.h> /* Function Prototype */ long double estimate_integral(long double a, long double b, int n, long double h); long double abs_relative_true_error(long double approximate_value); long double f(long double x); /* For MPI */ void get_input(int my_rank, int comm_sz, long double* a, long double* b, int* n); void create_mpi_type(long double* a, long double *b, int* n, MPI_Datatype* input_data_struct); /* Global variables */ const long double TRUE_VALUE = 4754.0192288588181366; const long double ACCEPTABLE_ERROR = .5E-14; /** * int main * * This is the main function. This function accepts inputs as the * left and right bound of the integral, and an input for the number * of trapezoids in order to search for the tmin. Once this function * is done calling the working functions, then it will print the * integration result, the absolute relative true error, and the tmin * used. */ int main(void) { /* Declaration and initialization of variables */ int comm_sz = 0; // Number of processes int my_rank = 0; int n = 0; // Trapezoids int local_n = 0; long double a = 0.0; // Left bound long double b = 0.0; // Right bound long double local_a = 0.0; // Local a long double local_b = 0.0; // Local b long double h = 0.0; long double local_approx_value = 0.0; long double total_approx_value = 0.0; double local_start_time = 0.0; double local_finish_time = 0.0; double local_elapsed_time = 0.0; double elapsed_time = 0.0; // Initialize MPI MPI_Init(NULL, NULL); // Get my rank MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); // Get number of processes being used MPI_Comm_size(MPI_COMM_WORLD, &comm_sz); // Get input get_input(my_rank, comm_sz, &a, &b, &n); // Block needed to start timer MPI_Barrier(MPI_COMM_WORLD); // Start the timer local_start_time = MPI_Wtime(); /* Set the local variables for all ranks */ h = (b-a)/n; local_n = n/comm_sz; // Same number of trapezoids for all local_a = a + my_rank*local_n*h; local_b = local_a + local_n*h; // Calculate the local_integral local_approx_value = estimate_integral(local_a, local_b, local_n, h); printf("LOCAL approx value = %.13e\n", (double) local_approx_value); // Add up all the local approximated values of each process MPI_Reduce(&local_approx_value, &total_approx_value, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); // Record the local finish time local_finish_time = MPI_Wtime(); local_elapsed_time = local_finish_time - local_start_time; // Get the min local elapsed time and store it in variable elapsed_time MPI_Reduce(&local_elapsed_time, &elapsed_time, 1, MPI_DOUBLE, MPI_MIN, 0, MPI_COMM_WORLD); /* PRINT OUT */ if (my_rank == 0) { printf("Elapsed time = %e seconds\n", elapsed_time); printf("With n = %d trapezoids, our estimate\n", n); printf("of the integral from %f to %f = %.13e\n",(double) a, (double) b, (double) total_approx_value); printf("true value = %.19e\n", (double) TRUE_VALUE); // Get the abs relative true error long double relative_true_error = 0.0; relative_true_error = abs_relative_true_error(total_approx_value); printf("absolute relative true error = %.19e\n", (double) relative_true_error); if(relative_true_error > ACCEPTABLE_ERROR) { printf(" is NOT less than criteria = %.19e\n", (double) ACCEPTABLE_ERROR); } } // Clean up and shut down MPI MPI_Finalize(); } /** * long double abs_relative_true_error * * Calculates the absolute relative error. * * @param approximate_value The approximate_value attained from integration. * @return relative_true_error The relative true error. */ long double abs_relative_true_error(long double approximate_value) { long double true_error = 0.0; true_error = TRUE_VALUE - approximate_value; long double relative_true_error = 0.0; relative_true_error = true_error / TRUE_VALUE; // Get the absolute value if (relative_true_error < 0) { relative_true_error = -relative_true_error; } return relative_true_error; } /** * long double estimate_integral * * THis function uses the trapazoidal rule to approximate the result. * * @param a The left bound of the integral. * @param b The right bound of the integral. * @t The number of trapezoids inputed. * @return approx The approximated result. */ long double estimate_integral(long double a, long double b, int n, long double h) { long double approx = 0.0; long double x_i = 0.0; int i = 0; approx = (f(a) + f(b))/2.0; for (i = 1; i <= n-1; i++) { x_i = a + i*h; approx += f(x_i); } approx = h*approx; return approx; } /** * long double f * * This function calculates the integral for the given x * and returns it. * * @param x The lower or upper bound to estimate the function. * @return Returns the estimated value. */ long double f(long double x) { return -3*cosl(x/6) + sqrtl(powl((5*sinl(x/9))+(8*sinl(x/2)),4)) + 1; } /** * void get_input * * Gets the input from user and instead of broadcasting the three * different datatypes 3 times define a derived datatype and call * MPI_Bcast only once. * * note: Borrowed from Pacheco's mpi_trap4.c example. * * @param a Pointer to the left endpoint * @param b Pointer to the right endpoint * @param n Pointer to the number of trapezoids */ void get_input(int my_rank, int comm_sz, long double* a, long double* b, int* n) { MPI_Datatype input_data_struct; // Buld the mpi type create_mpi_type(a, b, n, &input_data_struct); if (my_rank == 0) { printf("Enter a, b, and n\n"); // scan for user input for a, b, and t. scanf(" %LF %LF %d", a, b, n); // printf("Testing scan done!\n"); printf("Running on %d cores.\n", comm_sz ); } /* Now we can broadcast it only once */ MPI_Bcast(a, 1, input_data_struct, 0, MPI_COMM_WORLD); // Free the data structure created MPI_Type_free(&input_data_struct); } /** * void create_mpi_type * * Creates the data structure for the derived types. * * note: Borrowed from Pacheco's mpi_trap4.c example. * * @param a Pointer to the left bound. * @param b Pointer to the right bound * @param n Pointer to the number of trapezoids. * @param input_data_struct Pointer to the data structure. */ void create_mpi_type(long double* a, long double* b, int* n, MPI_Datatype* input_data_struct) { // Size of block int blocklengths_array[3] = {1,1,1}; // Declare the MPI_types of each element in the array block MPI_Datatype types_array[3] = {MPI_LONG_DOUBLE, MPI_LONG_DOUBLE, MPI_INT}; // Declare MPI_Aint type variable to store displacement MPI_Aint displacements_array[3] = {0}; // Declare address variables to store the address MPI_Aint a_addr, b_addr, n_addr; /* Get the displacements for a, b, and n */ MPI_Get_address(a, &a_addr); MPI_Get_address(b, &b_addr); MPI_Get_address(n, &n_addr); /* Set the address displacement for each type of datatypes*/ displacements_array[1] = b_addr - a_addr; displacements_array[2] = n_addr - a_addr; // Create the derived data type MPI_Type_create_struct(3, blocklengths_array, displacements_array, types_array, input_data_struct); // Must commit to allow MPI to optimize the internal representation MPI_Type_commit(input_data_struct); }
true
1f86ce04e4971db82373e3ea30dd71699f8047f4
C
karinepcdc/search-algorithms
/includes/searching.h
UTF-8
1,185
2.765625
3
[]
no_license
#ifndef SEARCHING_H #define SEARCHING_H //=== Alias using value_type = long int ; //!< Simple alias to help code maintenance. // iterative linear search const value_type * lsearch( const value_type *, const value_type *, value_type); // iterative binary search const value_type * bsearch_it( const value_type *, const value_type *, value_type); // recursive binary search main const value_type * bsearch_rec( const value_type *, const value_type *, value_type); // recursive binary search recursive part const value_type * bsearch_recursivePart( const value_type *, const value_type *, value_type); // iterative ternary search const value_type * tsearch_it( const value_type *, const value_type *, value_type); // recursive binary search main const value_type * tsearch_rec(const value_type *, const value_type *, value_type); // recursive ternary search recursive part const value_type * tsearch_recursivePart( const value_type *, const value_type *, value_type); // jump search const value_type * jumpsearch(const value_type *, const value_type *, value_type); // fibonacci search const value_type * fibsearch(const value_type *, const value_type *, value_type); #endif
true
c66f4c38a315bb59b84c3b8c016d6eae3fecdb31
C
mgpsp/LCOM-FEUP
/lab2/lab2.c
UTF-8
2,169
3.015625
3
[]
no_license
#include <minix/drivers.h> #include "timer.h" static int proc_args(int argc, char *argv[]); static unsigned long parse_ulong(char *str, int base); static void print_usage(char *argv[]); int main(int argc, char **argv) { /* Initialize service */ sef_startup(); if (argc == 1) { print_usage(argv); return 0; } else proc_args(argc, argv); return 0; } static void print_usage(char *argv[]) { printf("Usage: one of the following:\n" "\t service run %s -args \"test_square <freq>\" \n" "\t service run %s -args \"test_int <time>\" \n" "\t service run %s -args \"test_config <timer>\" \n", argv[0], argv[0], argv[0]); } static int proc_args(int argc, char *argv[]) { unsigned long timer, freq, time; if (strncmp(argv[1], "test_square", 11) == 0) { if (argc != 3) { printf("timer: wrong no of arguments for timer_test_square()"); return 1; } if ((freq = parse_ulong(argv[2], 10)) == ULONG_MAX) return 1; printf("timer:: timer_test_square(%lu)\n", freq); return timer_test_square(freq); } else if (strncmp(argv[1], "test_int", 8) == 0) { if (argc != 3) { printf("timer: wrong no of arguments for timer_test_int()"); return 1; } if ((time = parse_ulong(argv[2], 10)) == ULONG_MAX) return 1; printf("timer:: timer_test_int(%lu)\n", time); return timer_test_int(time); } else if (strncmp(argv[1], "test_config", 11) == 0) { if (argc != 3) { printf("timer: wrong no of arguments for timer_test_config()"); return 1; } if ((timer = parse_ulong(argv[2], 10)) == ULONG_MAX) return 1; printf("timer:: timer_test_config(%lu)\n", timer); return timer_test_config(timer); } else { printf("timer: non valid function \"%s\" to test\n", argv[1]); return 1; } } static unsigned long parse_ulong(char *str, int base) { char *endptr; unsigned long val; val = strtoul(str, &endptr, base); if ((errno == ERANGE && val == ULONG_MAX ) || (errno != 0 && val == 0)) { perror("strtol"); return ULONG_MAX; } if (endptr == str) { printf("timer: parse_ulong: no digits were found in %s \n", str); return ULONG_MAX; } //Successful conversion return val; }
true
233c30b8a27a8cb92c7c0afe7a6c7c5c3eab6cac
C
angadgill/antenna_analyzer
/psoc/antenna_analyzer.cydsn/main.c
UTF-8
6,003
2.8125
3
[ "MIT" ]
permissive
#include <project.h> #define HIGH 1u #define LOW 0u #define FREQ_SCALE 4294967295/125000000 #include "stdio.h" #define RX_LEN 20 #define ERR_MSG ": invalid input_str. Type 'help' to see available input_strs\r\n" #define CMD_LEN 4 #define OPTION_LEN 4 #define NUM_LEN 15 const char help_message[] = "\r\nHi! This is a PC controlled Antenna Analyzer.\r\n" "input_strs:\r\n" " 'help' to see this help message.\r\n" " 'ant' to control the Antenna Analyzer.\r\n" ; double dds_freq = (double) 14150e3; uint amux_chan = 1u; void dds_transfer_byte(uint8 data); void dds_set_frequency(double frequency); void dds_reset(); void extract_first_word(char * input_str, char * first_word, const uint word_len); void send_help_msg(); void send_crlf(); void send_error_msg(char * input_str); void send_uint(uint value); void execute_input_str(char * input_str); int main() { ADC_Start(); ADC_StartConvert(); LED_Write(1u); // Enable serial mode on AD9850 DDS module Pin_DDS_Freq_Update_Write(HIGH); Pin_DDS_Freq_Update_Write(LOW); dds_set_frequency(dds_freq); LED_Write(0u); UART_Start(); uint32 rx_data; char rx_str[RX_LEN]; int rx_str_idx = 0; UART_SpiUartPutArray(help_message, strlen(help_message)); UART_SpiUartWriteTxData('>'); for(;;) { if (UART_SpiUartGetRxBufferSize()!=0){ while(UART_SpiUartGetRxBufferSize() != 0){ rx_data = UART_SpiUartReadRxData(); if(rx_data=='\n'){ if(rx_str_idx > 1){ /* rx_str is more than just "\r" */ rx_str[rx_str_idx-1] = '\0'; // set trailing "\r" to null execute_input_str(rx_str); } rx_str_idx = 0; memset(rx_str, '\0', RX_LEN); UART_SpiUartWriteTxData('>'); } else{ rx_str[rx_str_idx]=rx_data; rx_str_idx++; } } } } } void dds_transfer_byte(uint8 data) { // Transfer 1 byte of data to the AD9850 DDS module using the Data pin int i; for (i=0; i<8; i++) { Pin_DDS_Data_Write(data&0x01); // Toggle Word Clock pin to indicate that data bit is ready Pin_DDS_Word_Clock_Write(HIGH); Pin_DDS_Word_Clock_Write(LOW); data >>= 1; } } void dds_set_frequency(double frequency) { // Set desired frequency at the AD9850 DDS module // frequency calc from datasheet page 8 = <sys clock> * <frequency tuning word>/2^32 // Based on Arduino sketch by Andrew Smallbone at www.rocketnumbernine.com int32 freq = frequency * FREQ_SCALE; // note 125 MHz clock on 9850 int b; for (b=0; b<4; b++) { dds_transfer_byte(freq & 0xFF); freq >>= 8; } // Final control byte, all 0 for 9850 chip dds_transfer_byte(0x00); // Toggle Frequency Update pin to indicate that the data transfer is done Pin_DDS_Freq_Update_Write(HIGH); Pin_DDS_Freq_Update_Write(LOW); } void dds_reset(){ Pin_DDS_Reset_Write(HIGH); Pin_DDS_Reset_Write(LOW); } void extract_first_word(char * input_str, char * first_word, const uint word_len){ unsigned int i; for(i=0; i<strlen(input_str) && i<word_len; i++){ if(input_str[i]==' ') break; else first_word[i] = input_str[i]; } } void send_help_msg(){ UART_SpiUartPutArray(help_message, strlen(help_message)); } void send_crlf(){ UART_SpiUartPutArray("\r\n", 2); } void send_error_msg(char * input_str){ UART_SpiUartPutArray(input_str, strlen(input_str)); UART_SpiUartPutArray(ERR_MSG, strlen(ERR_MSG)); } void send_uint(uint value){ char value_str[NUM_LEN]; sprintf(value_str, "%d", value); UART_SpiUartPutArray(value_str, strlen(value_str)); send_crlf(); } void execute_input_str(char * input_str){ char cmd[CMD_LEN] = ""; extract_first_word(input_str, cmd, CMD_LEN); /* help */ if(strcmp(input_str, "help")==0) send_help_msg(); /* dds */ else if(strcmp(cmd, "ant")==0){ const char cmd_format[] = "ant format: dds <option> [property] [number]\r\n" "option:\r\n" " set\r\n" " get\r\n" "property:\r\n" " f: frequency from AD850 DDS\r\n" " s: switch resistor bridge input\r\n" " 1: ref\r\n" " 2: antenna\r\n" " m: VMAG reading from AD8302 [get only]\r\n" " multiply with (1.8*2/4096) to convert to Volts\r\n" " p: VPHS reading from AD8302 [get only]\r\n" " multiply with (1.8*2/4096) to convert to Volts\r\n" ; char option[OPTION_LEN] = ""; extract_first_word(input_str+4, option, OPTION_LEN); char property = input_str[8]; char number_str[NUM_LEN] = ""; extract_first_word(input_str+10, number_str, NUM_LEN); uint number = 0; sscanf(number_str, "%u", &number); if(strcmp(option, "get")==0){ if(property=='f') send_uint(AMuxControl_Read()); else if(property=='s') send_uint(amux_chan); else if(property=='m') send_uint((uint)ADC_GetResult16(0u)); else if(property=='p') send_uint((uint)ADC_GetResult16(1u)); else UART_SpiUartPutArray(cmd_format, strlen(cmd_format)); } else if(strcmp(option, "set")==0){ if(property=='f'){ dds_freq = number; dds_set_frequency(dds_freq); send_uint(dds_freq); } else if(property=='s'){ AMuxControl_Write(number); send_uint(AMuxControl_Read()); } else UART_SpiUartPutArray(cmd_format, strlen(cmd_format)); } else UART_SpiUartPutArray(cmd_format, strlen(cmd_format)); } /* no match */ else send_error_msg(input_str); }
true
bc49c450f97c151945bf3e2218b6943f501d9b39
C
mritunjay7065/StartingWithDSA
/Assignment 1.c
UTF-8
2,052
3.78125
4
[]
no_license
#include<stdio.h> #include<stdlib.h> struct BST { int data; struct BST *left; struct BST *right; }; typedef struct BST node; node * insertintoBST(node *root,int key) ///OK { node *temp,*curr,*p; temp=(node*)malloc(sizeof(node)); temp->data=key; temp->left=temp->right=NULL; if(root==NULL) { root=temp; return root; } else { curr=root; ///p is temp pointer to target node(because curr will be NULL at a place) and curr is also pointer to target node while(curr) { p=curr; if (key < curr->data) curr=curr->left; else curr=curr->right; } /// p pointer mil gaya !!! if(key < p->data) p->left=temp; else p->right=temp; } return root; } void inorder(node *root) ///OK { if(root) { inorder(root->left); printf("%d ",root->data); inorder(root->right); } } void preorder(node *root) ///OK { if(root) { printf("%d ",root->data); preorder(root->left); preorder(root->right); } } void postorder(node *root) ///OK { if(root) { postorder(root->left); postorder(root->right); printf("%d ",root->data); } } int findheightBST(node*root) //OK { int x,y; if(root==NULL) return 0; x=findheightBST(root->left); y=findheightBST(root->right); if(x>=y) return (x+1); else return (y+1); } int main() { int height; node *root = NULL; root=insertintoBST(root,8); root=insertintoBST(root,3); root=insertintoBST(root,1); root=insertintoBST(root,6); root=insertintoBST(root,4); root=insertintoBST(root,7); root=insertintoBST(root,10); root=insertintoBST(root,14); root=insertintoBST(root,13); printf("\nInorder : "); inorder(root); printf("\nPreorder : "); preorder(root); height = findheightBST(root); printf("Height is = %d",height); }
true
e09340b5f35c5f1384ddbc49ac7902336292e326
C
0pankajkumar/LearningCCPP
/InfixToPostfix.c
UTF-8
612
3.34375
3
[]
no_license
#include<stdio.h> #include<conio.h> int main() { char *p = "3+5/9"; char *cur = p; char *cur2 = p; while(*cur) { //printf("%c",*cur); if((*cur) == '/' || (*cur) == '*') { } else if(*cur == '+' || *cur == '-') { *cur = 's'; /* printf("Inside + -\n"); char temp = *cur; ++cur; *cur = temp; */ } ++cur; } while(*cur2) { printf("%c",*cur2); ++cur2; } return 0; }
true
f92b915dd2838eb2009eec6f8427caab6f8c2c53
C
handoso/C-Programming
/Fall Season/lab9-2.c
UTF-8
476
3.296875
3
[]
no_license
#include<stdio.h> #define pr printf #define sc scanf void read(int a[], int n){ int i; for (i = 0; i < n; i++) sc("%d", &a[i]); } void print(int a[], int n){ int i=0; for(i; i<n; i++){ pr("%d ", a[i]); } } main(){ int a[100],b[100],n,m; pr("a array: "); sc("%d",&n); pr("b array: "); sc("%d",&m); read(a ,n); pr("b array: \n"); read( b, m); pr("\n"); print(a,n); pr("\n"); print(b,m); return 0; }
true
a7c2377f914f1952ba3d8eb1d9ddc7bb4fbd948d
C
robert-hrusecky/initrdtest
/main.c
UTF-8
649
2.53125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <unistd.h> /* Import user configuration: */ #include <uk/config.h> #include <uk/plat/memory.h> #include <uk/hexdump.h> #include <uk/alloc.h> #include <dirent.h> int main() { DIR *dr = opendir("/"); struct dirent *de; while ((de = readdir(dr)) != NULL) { printf("%s\n", de->d_name); } int fd = open("/testfile", O_RDWR); if (fd < 0) { return -1; } char buf[1024]; if (read(fd, &buf[0], 100) < 0) { return -2; } buf[100] = '\0'; printf("The message in testile is: %s", buf); return 0; }
true
3e2da9a1a475e1e70fe80e7134f64db4fd45821b
C
tantalu/onlinejudge
/hduoj/hdu1410.c
GB18030
640
2.890625
3
[]
no_license
// P(w:lʤ) = P(w:0) + P(w:1) + ... + 1/2P(w:l) // = P(w-1:0) + P(w-1:1) + ... + P(w-1:l) // WA Ҳ #include<math.h> #include<stdio.h> int main(void) { int hp1, hp2, ap1, ap2; double res, lgcom; int w, l, s; int i; while (scanf("%d%d%d%d", &hp1, &hp2, &ap1, &ap2) !=EOF) { w = (hp2-1) / ap1 + 1; l = (hp1-1) / ap2 + 1; s = w + l - 1; lgcom = log2(1.0);// com = 1.0; res = pow(2, lgcom-s); for (i=1; i<l; ++i) { lgcom += log2((double)(s+1-i)/i);// com = com * (s+1-i) / i; res += pow(2, lgcom-s);// res += com*pow(2, -s); } printf("%.4f\n", 100*res); } return 0; }
true
5431259396bbc40737ac17fb8d2f5a408d1bf473
C
kangyechan/OSS_Practice
/OSS_project/Occupation_Search_System/OSS.c
UTF-8
14,371
3.453125
3
[]
no_license
#include "json.h" void printCompanies(Company *companies, int count) { char *sizeToStr; printf("\n*********************** Companies *************************\n"); for (int i = 0; i < count; i++) { if (companies[i].size == 1) sizeToStr = "Large"; else if (companies[i].size == 2) sizeToStr = "Medium"; else if (companies[i].size == 3) sizeToStr = "Small"; else if (companies[i].size == 4) sizeToStr = "Startup"; printf("\r\n[%d] %s \r\n", i + 1, companies[i].name); printf("Size : %s \r\n", sizeToStr); printf("Recruiting # : %d \r\n", companies[i].recruitNum); printf("Coding Test : %s \r\n", companies[i].coding); printf("Salary : %d \r\n", companies[i].salary); printf("Location : %s \r\n", companies[i].location); printf("City : %s \r\n", companies[i].city); printf("Available Positions : \r\n"); for(int j = 0; j < companies[i].positionCount; j++){ printf(" %d. %s \r\n", j + 1, companies[i].positions[j]); } } printf("************************************************************\n\n"); } void printschools(School *schools, int count) { char *sizeToStr; printf("\n*********************** Graduate Schools List *************************\n"); for (int i = 0; i < count; i++) { printf("\r\n[%d] %s \r\n", i + 1, schools[i].name); printf("Location : %s \r\n", schools[i].location); printf("Type : \r\n"); for(int j = 0; j < schools[i].typeCount; j++){ printf(" %d. %s \r\n", j + 1, schools[i].type[j]); } } printf("*************************************************************************\n\n"); } void chooseGraduateSchool(School *schools, int count){ char name[20]; char *sizeToStr; int num=0; printf("Enter a graduate school name: "); scanf("%s", name); printf("\n************************************************************************"); printf("\nResults:"); for (int i = 0; i < count; i++) { // printf("%s",companies[i].name); if(!(strcmp(name, schools[i].name))){ printf("\r\n[%d] %s \r\n", i + 1, schools[i].name); printf("Available Types : \r\n"); for(int j=0; j<schools[i].typeCount; j++){ printf(" %d. %s \r\n", j+1,schools[i].type[j]); } } } printf("\n************************************************************************\n"); printf("Where do you wnat to apply? Choose the number.\n"); while(num != 4){ scanf("%d", &num); switch (num) { case 1: case 2: case 3: printf("I recommad you to apply Lee Won Hyung professor's lab"); printf(" Choose again\n"); break; case 4: printf("Apply now \nemail: whlee@handong.edu"); break; default: break; } } } void searchByName(Company *companies, int count){ char name[20]; char *sizeToStr; int noExistCount = 0; printf("Enter a company name: "); scanf("%s", name); for (int i = 0; i < count; i++) { if(toLower(strlen(companies[i].name), name, companies[i].name)) { if (companies[i].size == 1){ sizeToStr = "Large"; } else if (companies[i].size == 2){ sizeToStr = "Medium"; } else if (companies[i].size == 3){ sizeToStr = "Small"; } else{ sizeToStr = "Startup"; } printf("\r\n[%d] %s \r\n", i + 1, companies[i].name); printf("Recruiting # : %d \r\n", companies[i].recruitNum); printf("Coding Test : %s \r\n", companies[i].coding); printf("Salary : %d \r\n", companies[i].salary); printf("Available Positions : \r\n"); for(int j=0; j<companies[i].positionCount; j++){ printf(" %d. %s \r\n", j+1,companies[i].positions[j]); } } else { noExistCount++; } } if(noExistCount == count) { noExist(); } printf("\n"); } void searchBySize(Company *companies, int count){ char size[10]; char *sizeToStr; int selectedComapny; bool companyInput = true; int noExistCount = 0; do { printf("Enter size of company (ex. large, medium, small, startup): "); scanf("%s", size); if(toLower(5, "Small", size) || toLower(5, "Large", size) || toLower(6, "Medium", size) || toLower(7, "Startup", size)) { companyInput = false; } else { printf("kind of company size Large or medium or small or startup.\n"); } } while(companyInput); for (int i = 0; i < count; i++) { //convert size number to string equivalent if (companies[i].size == 1){ sizeToStr = "Large"; } else if (companies[i].size == 2){ sizeToStr = "Medium"; } else if (companies[i].size == 3){ sizeToStr = "Small"; } else{ sizeToStr = "Startup"; } if(toLower(strlen(sizeToStr), sizeToStr, size)){ //if user input and company size are equal printf("\r\n[%d] %s \r\n", i + 1, companies[i].name); printf("Size : %s \r\n", sizeToStr); } else { noExistCount++; } } if(noExistCount == count) { noExist(); } else { printf("Enter number of company for more information: "); scanf("%d", &selectedComapny); printf("\r\n%s \r\n", companies[selectedComapny-1].name); printf("\r\nRecruiting # : %d \r\n", companies[selectedComapny-1].recruitNum); printf("Coding Test : %s \r\n", companies[selectedComapny-1].coding); printf("Salary : %d \r\n", companies[selectedComapny-1].salary); printf("Available Positions : \r\n"); for(int j=0; j<companies[selectedComapny-1].positionCount; j++){ printf(" %d. %s \r\n", j+1,companies[selectedComapny-1].positions[j]); } } printf("\n"); } void searchBySalary(Company *companies, int count){ int minSalary; char *sizeToStr; int selectedComapny; int noExistCount = 0; printf("Enter desired minimum salary : "); scanf("%d", &minSalary); for (int i = 0; i < count; i++) { if(companies[i].salary > minSalary){ //if user input and company size are equal printf("\r\n[%d] %s \r\n", i + 1, companies[i].name); printf("Salary : %d \r\n", companies[i].salary); } else { noExistCount++; } } if(noExistCount == count) { noExist(); } else { printf("Enter number of company for more information: "); scanf("%d", &selectedComapny); //convert size number to string equivalent if (companies[selectedComapny-1].size == 1){ sizeToStr = "Large"; } else if (companies[selectedComapny-1].size == 2){ sizeToStr = "Medium"; } else if (companies[selectedComapny-1].size == 3){ sizeToStr = "Small"; } else{ sizeToStr = "Startup"; } printf("Size : %s \r\n", sizeToStr); printf("\r\n%s \r\n", companies[selectedComapny-1].name); printf("\r\nRecruiting # : %d \r\n", companies[selectedComapny-1].recruitNum); printf("Coding Test : %s \r\n", companies[selectedComapny-1].coding); printf("Salary : %d \r\n", companies[selectedComapny-1].salary); printf("Available Positions : \r\n"); for(int j=0; j<companies[selectedComapny-1].positionCount; j++){ printf(" %d. %s \r\n", j+1,companies[selectedComapny-1].positions[j]); } } printf("\n"); } void searchByJob(Company *companies, int companyCount, char jobs[][40], int jobCount){ int jobSelection; char *sizeToStr; int selectedComapny; char jobToSearch[40]; for (int c = 0; c < jobCount; c++) { printf("[%d] %s \r\n", c + 1, jobs[c]); } printf("Enter your choice from position list : "); scanf("%d", &jobSelection); strcpy(jobToSearch,jobs[jobSelection-1]); printf("Selected job is : %s \r\n", jobToSearch); for (int i = 0; i < companyCount; i++) { // printf("%s",companies[i].name); for(int j =0; j < companies[i].positionCount; j++){ if(!strcmp(companies[i].positions[j], jobToSearch)){ //if job is found //print company info if (companies[i].size == 1){ sizeToStr = "Large"; } else if (companies[i].size == 2){ sizeToStr = "Medium"; } else if (companies[i].size == 3){ sizeToStr = "Small"; } else{ sizeToStr = "Startup"; } printf("\r\n[%d] %s \r\n", i + 1, companies[i].name); printf("Position: \r\n"); printf(" %s \r\n", companies[i].positions[j]); } } } printf("Enter number of company for more information: "); scanf("%d", &selectedComapny); //convert size number to string equivalent if (companies[selectedComapny-1].size == 1){ sizeToStr = "Large"; } else if (companies[selectedComapny-1].size == 2){ sizeToStr = "Medium"; } else if (companies[selectedComapny-1].size == 3){ sizeToStr = "Small"; } else{ sizeToStr = "Startup"; } printf("Size : %s \r\n", sizeToStr); printf("\r\n%s \r\n", companies[selectedComapny-1].name); printf("\r\nRecruiting # : %d \r\n", companies[selectedComapny-1].recruitNum); printf("Coding Test : %s \r\n", companies[selectedComapny-1].coding); printf("Salary : %d \r\n", companies[selectedComapny-1].salary); printf("Available Positions : \r\n"); for(int j=0; j<companies[selectedComapny-1].positionCount; j++){ printf(" %d. %s \r\n", j+1,companies[selectedComapny-1].positions[j]); } printf("\n"); } void enterInfo(User* ourUser,Company *companies, int companyCount){ char answer[5]; char salary[10]; int selected[companyCount]; int qnum = 0; char *sizeToStr; int selectedComapny = 0; printf(">> What is your name? : "); scanf("%s", ourUser[0].name); printf("Hi %s, Welcome!", ourUser[0].name); printf("\r\n\n>>Where do you live or want to work? : "); scanf("%s", ourUser[0].city); printf("So you want to work at %s.\r\n", ourUser[0].city); qnum++; printf("\n>>How about working abroad? Yes/No: "); scanf("%s", answer); if(!strcmp(answer, "Yes")){ ourUser[0].workAbroad=1; }else{ ourUser[0].workAbroad=0; } if(ourUser[0].workAbroad){ printf("So you don't mind working overseas!\r\n"); }else{ printf("Okay we understand. You like staying closer to home.\r\n"); } printf("\n>>How much salary would be okay for you? : "); scanf("%s", salary); ourUser[0].salary = atoi(salary); if( ourUser[0].salary>=7000){ printf("%d is quite a bit of money!\r\n", ourUser[0].salary); }else{ printf("%d sounds like a good amount.\r\n", ourUser[0].salary); } qnum++; printf("\n>>Now we will run our algorithm....\r\n"); Sleep(1800); // sleep(1.8); printf("Making calculations...\r\n"); Sleep(1800); // sleep(1.8); printf("Making a cup of coffee...\r\n"); Sleep(1800); // sleep(1.8); printf("Finalyzing.."); for (int g = 0; g < 6; g++) { Sleep(600); // sleep(0.6); printf("..."); } printf("\r\n\n>>Here are the results!\r\n"); Sleep(1500); // sleep(1.5); //recommend for (int i = 0; i < companyCount; i++){ selected[i] = 0; } for (int i = 0; i < companyCount; i++) { if (companies[i].salary >= ourUser[0].salary) { selected[i]++; } if (strstr(ourUser[0].city, companies[i].city) != NULL) { selected[i]++; } if (ourUser[0].workAbroad==1){ if (strstr(companies[i].city, "Seoul")==NULL){ selected[i]++; } } } for (int selectedComapny = 0; selectedComapny < companyCount; selectedComapny++) { if (selected[selectedComapny] == qnum) { if (companies[selectedComapny].size == 1) { sizeToStr = "Large"; } else if (companies[selectedComapny].size == 2) { sizeToStr = "Medium"; } else if (companies[selectedComapny].size == 3) { sizeToStr = "Small"; } else { sizeToStr = "Startup"; } printf("\r\n[%d] %s \r\n", selectedComapny,companies[selectedComapny].name); printf("Size : %s", sizeToStr); printf("\r\nRecruiting # : %d \r\n", companies[selectedComapny].recruitNum); printf("Coding Test : %s \r\n", companies[selectedComapny].coding); printf("Salary : %d \r\n", companies[selectedComapny].salary); printf("Location : %s \r\n", companies[selectedComapny].city); printf("Available Positions : \r\n"); for (int j = 0; j < companies[selectedComapny].positionCount; j++) { printf(" %d. %s \r\n", j + 1, companies[selectedComapny].positions[j]); } } } if(selectedComapny == 0){ printf("\nOops... seems like there is no company for you. Sorry :( \n"); } } bool toLower(int strLen, char* voca, char* comvoca) { int totalLen = 0; for(int i = 0; i < strLen; i++) { if(tolower(voca[i]) == tolower(comvoca[i])) { totalLen++; } } if(totalLen == strLen) { return true; } return false; } void noExist() { printf("There is no company that meets the conditions.\n\n"); }
true
d93189f15cad20781b06f562974a3c448543aa06
C
driftluo/LearningC
/The_C_Programing_Language/Chapter_2/exercise_2.6.c
UTF-8
724
4
4
[]
no_license
#include <stdio.h> /* 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. */ unsigned getbits(unsigned x, int p, int n); unsigned setbits(unsigned x, int p, int n, unsigned y); void main() { unsigned i; i = setbits(12, 3, 1, 2); printf("%u\n", i); } /* getbits: get n bits from position p */ unsigned getbits(unsigned x, int p, int n) { return (x >> (p+1-n)) & ~(~0 << n); } unsigned setbits(unsigned x, int p, int n, unsigned y) { unsigned tmp1; unsigned tmp2; tmp1 = ((y & ~(~0 << n))) << (p+1-n); tmp2 = ~0 << (p+1) | ~(~0 << (p+1-n)); return (x & tmp2) | tmp1; }
true
97b88b54328b996004c3cb0d406d26d94bd2ea84
C
kate-levoshko/Kate-repos
/courses/prog_base_2/labs/lab1/test.c
UTF-8
2,865
2.859375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #include <stddef.h> #include <setjmp.h> #include <cmocka.h> #include "header.h" static void createNewHeap_emptyHeap_zeroCount(void ** state){ heap_t * heap1 = heap_new(5); assert_null(heap_amountOfObjects(heap1)); heap_free(heap1); } static void createNewHeap_numberOfProcessLessThanNull_status(void ** state){ heap_t * heap1 = heap_new(-5); assert_int_equal(heap_getStatus(heap1), HEAP_INRORRECTNUMBER); heap_free(heap1); } static void freeMemory_addAndRemoveSameMemory_statusEmpty(void ** state){ heap_t * heap1 = heap_new(5); heap_addMemory(heap1); heap_freeMemory(heap1, 0); assert_int_equal(heap_getStatus(heap1), HEAP_EMPTY); heap_free(heap1); } static void addMemory_hasPointerToStructure_countOne(void ** state){ heap_t * heap1 = heap_new(5); heap_addMemory(heap1); assert_int_equal(heap_amountOfObjects(heap1), 1); assert_int_equal(heap_getStatus(heap1), HEAP_OK); heap_freeMemory(heap1, 0); heap_free(heap1); } static void freeMemory_incorrectIndex_status(void ** state){ heap_t * heap1 = heap_new(5); heap_freeMemory(heap1, 0); heap_freeMemory(heap1, 4); assert_int_equal(heap_getStatus(heap1), MEMORY_INCORRECTDATA); heap_free(heap1); } static void freeMemory_deleteFromEmptyMemory_status(void ** state){ heap_t * heap1 = heap_new(5); heap_freeMemory(heap1, 0); assert_int_equal(heap_getStatus(heap1), MEMORY_EMPTY); heap_free(heap1); } static void addMemory_overflowMemory_status(void ** state){ heap_t * heap1 = heap_new(5); for (int i = 0; i < MAX_AMOUNT_OF_OBJECTS; i++){ heap_addMemory(heap1); } assert_true(heap_amountOfObjects(heap1) == MAX_AMOUNT_OF_OBJECTS); heap_free(heap1); } static void writeBytesInMemory_overflowMemory_status(void ** state){ heap_t * heap1 = heap_new(5); memory_t * mem; mem = heap_addMemory(heap1); memory_writeBytesInMemory(mem, "0123456789"); assert_true(strlen("0123456789") + memory_getSize(mem) < MAX_AMOUNT_OF_BYTES); heap_free(heap1); } static void areadBytesfromMemory_hasNoData_status(void **state){ heap_t * heap1 = heap_new(5); memory_t * mem; mem = heap_addMemory(heap1); assert_null(memory_readBytesfromMemory(mem)); heap_free(heap1); } int runTests(void){ const struct CMUnitTest tests[] = { cmocka_unit_test(createNewHeap_emptyHeap_zeroCount), cmocka_unit_test(createNewHeap_numberOfProcessLessThanNull_status), cmocka_unit_test(freeMemory_addAndRemoveSameMemory_statusEmpty), cmocka_unit_test(addMemory_hasPointerToStructure_countOne), cmocka_unit_test(freeMemory_incorrectIndex_status), cmocka_unit_test(freeMemory_deleteFromEmptyMemory_status), cmocka_unit_test(writeBytesInMemory_overflowMemory_status), cmocka_unit_test(areadBytesfromMemory_hasNoData_status) }; return cmocka_run_group_tests(tests, NULL, NULL); }
true
fa500065c63db614f878e99e6380857caab7b8a5
C
BHARATHIJOTHI/c-program
/bubblu/add.c
UTF-8
157
3.09375
3
[]
no_license
#include<stdio.h> void main() { int a; printf("enter the num"); scanf("%d",&a); if(a<0) printf("the num is negative"); else printf("the num is positive"); }
true
43adcb455d43cf0505e04d25e788826061404f6b
C
MentalBlood/twm
/workArea.c
UTF-8
669
2.53125
3
[]
no_license
typedef struct { int x, y; int width, height; } WorkAreaData; WorkAreaData* getWorkAreaData() { WorkAreaData **workAreaData = (WorkAreaData**)malloc(sizeof(WorkAreaData*)); *workAreaData = (WorkAreaData*)malloc(sizeof(WorkAreaData)); RECT workAreaSystemData; SystemParametersInfo(SPI_GETWORKAREA, 0, &workAreaSystemData, 0); (*workAreaData)->x = workAreaSystemData.left; (*workAreaData)->y = workAreaSystemData.top; (*workAreaData)->width = workAreaSystemData.right - workAreaSystemData.left; (*workAreaData)->height = workAreaSystemData.bottom - workAreaSystemData.top; return *workAreaData; }
true
de914aa1f9608299c6f4ae83fec27716936ef7e3
C
LihuaZhao/vx.vim
/templates/skeleton.c
UTF-8
2,789
2.59375
3
[]
no_license
/** \file \brief fooLib.c - foo function library */ /** * \internal \copyright * * Copyright (c) 2019 Wind River Systems, Inc. * * The right to copy, distribute, modify, or otherwise make use * of this software may be licensed only pursuant to the terms * of an applicable Wind River license agreement. */ /** * \internal modification history -------------------- 01oct14,rdl update coding standard for test file format (VXW7-1299) 15sep97,nfs added defines MAX_FOOS and MIN_FATS. 15feb96,dnw added functions fooGet() and fooPut(); added check for invalid index in fooFind(). 10feb84,dnw written. */ /** * ### Description * This module is an example of the Wind River Systems C coding conventions. * ... * * ### Include Files * fooLib.h * * \cond internal */ /* includes */ #include <vxWorks.h> #include <fooLib.h> /* defines */ #define MAX_FOOS 112U /* max # of foo entries */ #define MIN_FATS 2U /* min # of FAT copies */ /* typedefs */ typedef struct fooMsg /* FOO_MSG */ { STATUS (*func) /* pointer to function to invoke */ ( int arg1, int arg2 ); int arg [FOO_MAX_ARGS]; /* args for function */ } FOO_MSG; /* globals */ char * pGlobalFoo; /* global foo table */ /* locals */ LOCAL uint_t numFoosLost; /* count of foos lost */ /* forward declarations */ LOCAL uint_t fooMat (list * aList, int fooBar, BOOL doFoo); FOO_MSG fooNext (void); STATUS fooPut (FOO_MSG inPar); /*******************************************************************************/ /** * * \brief **fooGet** - get an element from a foo * * ### Description * This function finds the element of a specified index in a specified * foo. The value of the element found is copied to *pValue*. The value can * be gronk or blah value, it is the responsibility of the user to know what * type is contained in foo. * * \param [in] foo a foo structure array -- foo in which to find * the element * \param [in] index a positive integer -- element to be found * in foo * \param [out] * pValue any integer -- where to put value * * \returns * OK, or ERROR if the element is not found or the index does not * exist * * ### ERRNO: * * * S_fooLib_BLAH * The blah element was not found. * * * S_fooLib_GRONK * The gronk element was not found. * * ### See Also: * fooSet(), fooPrint() * * \internal * *fooGlobalLock* - fooGet() takes the fooGlobalLock and may * cause some latency as a result * \endinternal */ STATUS fooGet ( FOO foo, /* foo in which to find element */ int index, /* element to be found in foo */ int * pValue /* where to put value */ ) { ... } /** * \endcond */
true
073683dae517da93935a227051efe91395cfa805
C
IdarV/PG3400_C
/school/f06/lec5/exercise01.c
UTF-8
242
2.9375
3
[]
no_license
#include <stdio.h> void increase_std(){ static int svalue = 1; printf("svalue: %d\n", svalue++); printf("HE"); } int main(int argc, char *argv[]){ for(int i = 0; i < 5; i++){ increase_std(); } return 0; }
true
39d11045c00199afd13f51a0d240e44b986bcb55
C
GGunnison/LED-Cube
/USART/firmware/main.c
UTF-8
1,702
3.015625
3
[]
no_license
/* Name: main.c * Author: <insert your name here> * Copyright: <insert your copyright message here> * License: <insert your license reference here> */ #include <avr/io.h> // #include "USARTInit.h" #include <avr/interrupt.h> #include <util/delay.h> #define bit_set(p,m) ((p) |= (m)); #define bit_flip(p,m) ((p) ^= (1<<m)); #define bit_clear(p,m) ((p) &= ~(m)); unsigned int BAUDRATE = 9600; unsigned char newData = 0; int one = 0x63; int zero = 0x00; int two = 0x44; void uart_transmit(unsigned char data){ while (!(UCSRA & (1<<UDRE))); // wait while register is free UDR = data; // load data in the register } unsigned char uart_receive(){ while(!((UCSRA) & (1<<RXC))); // wait while data is being received return UDR; // return 8-bit data } void USART_Init (unsigned int baud) { //Put the upper part of the baud number here (bits 8 to 11) UBRRH = (unsigned char) (baud >> 8); //Put the remaining part of the baud number here UBRRL = (unsigned char) baud; //Enable the receiver and transmitter UCSRB = (1 << RXEN) | (1 << TXEN); //Set 2 stop bits and data bit length is 8-bit UCSRC = (1 << URSEL) | (1 << USBS) | (3 << UCSZ0); } int main(data) { DDRA |= 0xFF; USART_Init(103); char ReceivedByte; for (;;) // Loop forever { while ((UCSRA & (1 << RXC)) == 0) {}; // Do nothing until data have been recieved and is ready to be read from UDR ReceivedByte = UDR; // Fetch the recieved byte value into the variable "ByteReceived" while ((UCSRA & (1 << UDRE)) == 0) {}; // Do nothing until UDR is ready for more data to be written to it UDR = ReceivedByte; // Echo back the received byte back to the computer } }
true
f0068a140f91688d772b52a65d7fda79abbedb43
C
Coggroach/Quarks
/Control/Shapes.h
UTF-8
413
2.640625
3
[]
no_license
#ifndef SHAPES_H #define SHAPES_H #include "Colour.h" typedef struct Point { unsigned short x, y; } Point; typedef struct Rect { unsigned short x, y; unsigned short width, height; } Rect; typedef struct Circle { unsigned short x, y; unsigned short radius; } Circle; unsigned short doesRectContainPoint(Rect rect, Point point); unsigned short doesCircleContainPoint(Circle circle, Point point); #endif
true
cb9ad36bf040e4b201c724cec11b905929387cb4
C
githuanghaining/device_src
/src/traceroute/ly_trace.h
GB18030
636
2.53125
3
[]
no_license
#ifndef _LY_TRACE_H #define _LY_TRACE_H #define MAX_IP_ADDR 50 #define MAX_DOMAIN 150 #define PROBE_NUMBER 3 typedef struct route_info{ int ttl; // char domain[PROBE_NUMBER][MAX_DOMAIN]; // char ip[PROBE_NUMBER][MAX_IP_ADDR]; //IPַ int time[PROBE_NUMBER]; //ÿ̽ʱ䣬λ } route_info_t; /* ip[in]: Ҫĵַ ttl_num[out]: ص route_info_list: ص·Ϣб ʹҪעͷroute_info_listռõڴ */ void trace_route(char* ip,int* ttl_num, route_info_t** route_info_list); #endif
true
74dc2a142eb8dfc79d9abe43c93e5ce07582bbf4
C
aakidev/c-programming
/msub.c
UTF-8
1,187
3.171875
3
[]
no_license
#include<stdio.h> #define r 2 #define c 3 int main() { int i,j; int a[r][c]; int b[r][c]; int t[r][c]; printf("enter first matrix:\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { scanf("%d",&a[i][j]); } } printf("enter second matrix:\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { scanf("%d",&b[i][j]); } } printf("first matrix:\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("%d\t",a[i][j]); }printf("\n"); } printf("second matrix:\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("%d\t",b[i][j]); }printf("\n"); } printf("substraction is :\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { t[i][j]=a[i][j]-b[i][j]; } } for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("%d\t",t[i][j]); } printf("\n"); } }
true
d1dc0446947628d2e960e1410dd12ea08814f7bd
C
monoflop/USBNameTagLEDTool
/src/main.c
UTF-8
6,847
2.78125
3
[]
no_license
/******************************************************* LEDTool Alternative tool to upload messages to the VADIV LED Nametag Device 12x48 (VID:0x483, PID:0x5750) STMicroelectronics 0STM32 Composite MSC+HID Philipp Kutsch ********************************************************/ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <unistd.h> #include <string.h> #include <stdbool.h> #include <unistd.h> #include <getopt.h> #include <inttypes.h> #include <errno.h> #include "led.h" #include "hidapi.h" /* Argument handling with getopt */ int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex); extern char *optarg; extern int optind, opterr, optopt; static const struct option long_options[] = { { "help", no_argument, 0, 'h' }, { "time", required_argument, 0, 't' }, { "blink", no_argument, 0, 'b' }, { "animation", required_argument, 0, 'a' }, { "aspeed", required_argument, 0, 's' }, { "line", required_argument, 0, 'l' }, { "ospeed", required_argument, 0, 'o' }, { "verbose", no_argument, 0, 'v' }, {0} }; void print_usage(); /* Display all debug messages */ bool verbose = false; int main(int argc, char **argv) { /* Default LED tag options. struct is updated after all arguments are read */ struct led_options options; options.display_time = 100; options.animation_type = 0; options.animation_speed = 5; options.border_type = 0; options.border_speed = 5; options.blinking = false; /* Parse arguments using getopt */ while (1) { int index = -1; int result = getopt_long(argc, argv, "ht:ba:s:l:o:v", long_options, &index); if (result == -1) break; switch (result) { /* Parse help argument */ case 'h': { print_usage(); return 0; } case 't': { /* Parse time argument */ uintmax_t value = strtoumax(optarg, NULL, 10); if((value == UINTMAX_MAX && errno == ERANGE) || value > 255 || value == 0) { printf("Invalid argument: -t TIME, --time TIME Display time (Range 1...255)\n"); return 0; } options.display_time = (uint8_t)value; }break; case 'b': { /* Parse blink argument */ options.blinking = true; }break; case 'a': { /* Parse animation argument */ uintmax_t value = strtoumax(optarg, NULL, 10); if((value == UINTMAX_MAX && errno == ERANGE) || value > 11) { printf("Invalid argument: -a ANIM, --animation ANIM Set building text animation\n"); return 0; } options.animation_type = (uint8_t)value; }break; case 's': { /* Parse animation speed argument */ uintmax_t value = strtoumax(optarg, NULL, 10); if((value == UINTMAX_MAX && errno == ERANGE) || value > 9 || value == 0) { printf("Invalid argument: -s ASPEED, --aspeed ASPEED Animation speed (Range 1...9)\n"); return 0; } options.animation_speed = (uint8_t)value; }break; case 'l': { /* Parse outline argument */ uintmax_t value = strtoumax(optarg, NULL, 10); if((value == UINTMAX_MAX && errno == ERANGE) || value > 14) { printf("Invalid argument: -l LINE, --line LINE Set building outline\n"); return 0; } options.border_type = (uint8_t)value; }break; case 'o': { /* Parse outline speed argument */ uintmax_t value = strtoumax(optarg, NULL, 10); if((value == UINTMAX_MAX && errno == ERANGE) || value > 9 || value == 0) { printf("Invalid argument: -o LSPEED, --ospeed LSPEED Outline animation speed (Range 1...9)"); return 0; } options.border_speed = (uint8_t)value; }break; case 'v': { /* Parse verbose argument */ verbose = true; led_tag_enable_verbose_output(); }break; } } /* @TODO read message from argument list */ /* @TODO maybe add other options later like bitmaps, build in images, etc.*/ char *output_string; while (optind < argc) { output_string = argv[optind++]; } /* Initialise LED tag */ uint8_t res = led_tag_init(); if(res != 0) { fprintf(stderr, "Failed to initialise led tag.\n"); return -1; } /* Connect to LED tag */ res = led_tag_connect(); if(res != 0) { fprintf(stderr, "Failed to connect led tag.\n"); led_tag_exit(); return -1; } /* Send text to LED tag */ res = led_tag_display_text(output_string, &options); if(res != 0) { fprintf(stderr, "Failed to send data to led tag.\n"); led_tag_disconnect(); led_tag_exit(); return -1; } /* Disconnect LED tag and finialize */ led_tag_disconnect(); led_tag_exit(); return 0; } /* Print usage message */ void print_usage() { printf("Usage: ledtool [-h] [-t TIME] [-b] [-a ANIM] [-s ASPEED]\n"); printf(" [-l LINE] [-o LSPEED] [-d] MESSAGE\n\n"); printf("Alternative tool to upload messages to the VADIV LED Nametag\n"); printf("Device 12x48 (VID:0x483, PID:0x5750) STMicroelectronics 0STM32 Composite MSC+HID\n\n"); printf("Arguments:\n"); printf("-h, --help\t\t\t Display this message\n"); printf("-t TIME, --time TIME\t\t Display time (Range 1...255)\n"); printf("-b, --blink\t\t\t Toggle text blinking\n"); printf("-a ANIM, --animation ANIM\t Set building text animation\n"); printf("\t\t\t\t\t 0: No animation (DEFAULT)\n"); printf("\t\t\t\t\t 1, 2, 3, 4: Move up/down/left/right\n"); printf("\t\t\t\t\t 5: Snow\n"); printf("\t\t\t\t\t 6: Horizontal louvre\n"); printf("\t\t\t\t\t 7: Vertical louvre\n"); printf("\t\t\t\t\t 8, 9, 10, 11: Pull up/down/left/right\n"); printf("-s ASPEED, --aspeed ASPEED\t Animation speed (Range 1...9)\n"); printf("-l LINE, --line LINE\t\t Set building outline\n"); printf("\t\t\t\t\t 0: No outline (DEFAULT)\n"); printf("\t\t\t\t\t 1: Random outline\n"); printf("\t\t\t\t\t 2: Static outline\n"); printf("\t\t\t\t\t 3: Static single dotted outline\n"); printf("\t\t\t\t\t 4: Static double dotted outline\n"); printf("\t\t\t\t\t 5: Blinking outline\n"); printf("\t\t\t\t\t 6: Blinking single dotted outline\n"); printf("\t\t\t\t\t 7: Blinking double dotted outline\n"); printf("\t\t\t\t\t 8, 9, 10, 11: Rotating single/double/four/eight dotted outline\n"); printf("\t\t\t\t\t 12: Two static outlines\n"); printf("\t\t\t\t\t 13: One static outline\n"); printf("\t\t\t\t\t 14: One dotted outline\n"); printf("-o LSPEED, --ospeed LSPEED\t Outline animation speed (Range 1...9)\n"); printf("-v, --verbose\t\t\t Enable verbose output\n"); }
true
880b1bdc881280c8fbf1704862183478dc457629
C
syedqaisar/Data_Structure
/linklist Data Structure/Array/insert.c
UTF-8
1,338
3.359375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> int main() { int n, i, *ptr, update, entry, j, num, x; int a[3]; ptr = a; printf("how many number yoou want in array:"); scanf("%d", &n); ptr = (int *)calloc(n, sizeof(int)); int size = sizeof(a); printf("%d", size); // for (i = 0; i < n; i++) // { // scanf("%d", (ptr + i)); // } // printf("the orignal array is: \n"); // for (i = 0; i < n; i++) // { // printf("%d, ", *(ptr + i)); // } // printf("enter the update expanded siza:\n"); // scanf("%d", &update); // update = n + update; // ptr = (int *)realloc(ptr, update * sizeof(int)); // printf("\nIn which place you want to update the array"); // scanf("%d", &entry); // // for (j = 1; j < update - n; j++) // // { // for (i = update - 1; i >= entry; i--) // { // *(ptr + (n-1)) = *(ptr + n); // n--; // } // // } // x = update - entry - 1; // // for (i = entry; i <= x; i++) // // { // scanf("%d", &num); // *(ptr + entry) = num; // // entry++; // // } // printf("after update the array is: \n"); // for (i = 0; i < update; i++) // { // printf("%d, ", *(ptr + i)); // } free(ptr); return 0; }
true
4631b740d1a19b0d243b61d283d6da42c7de6186
C
IyaneG10/Moteur-de-workflows-en-C
/AJAC_S8/Socket/libsck.c
UTF-8
3,626
3.015625
3
[]
no_license
/** * @file libsck.c * @brief * @version 0.1 * @date 2020-01-30 * * @copyright Copyright (c) 2020 * */ /* Fichier d'inclusion */ #include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <unistd.h> #include <stddef.h> #include <fcntl.h> #include <errno.h> #include <netdb.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/stat.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <fcntl.h> #include "libsck.h" #include "libthrd.h" /** * @brief Initialisation de la communication réseau * * @param port port passé en argument de la fonction main dans Workflow_engine * @return int socket */ int initialisationServeur(char *port) { struct addrinfo precisions,*resultat,*origine; // liste chainée pour trouver des adresses int statut; int s; // descripteur de fichier pour la socket serveur TCP // Construction de la structure adresse memset(&precisions,0,sizeof precisions); precisions.ai_family=AF_UNSPEC; // aucune précision, donc prend aussi en compte les clients IPv4 et IPv6 precisions.ai_socktype=SOCK_STREAM; // Type de socket: TCP (mode flux, connecté) => SOCK_STREAM precisions.ai_flags=AI_PASSIVE; // On veut un serveur (ne fait qu'écouter) => AI_PASSIVE (AI_ACTIVE pour client) statut=getaddrinfo(NULL,port,&precisions,&origine); if(statut<0){ perror("initialisationServeur.getaddrinfo"); exit(EXIT_FAILURE); } struct addrinfo *p; for(p=origine,resultat=origine;p!=NULL;p=p->ai_next) { if(p->ai_family==AF_INET6){ resultat=p; break; } // chercher des adresses jusqu'à IP v6 } /** * @brief Création d'une socket * */ s=socket(resultat->ai_family,resultat->ai_socktype,resultat->ai_protocol); if(s<0){ perror("initialisationServeur.socket"); exit(EXIT_FAILURE); } printf("Socket TCP crée avec succes\n"); /** * @brief Options utiles * */ int vrai=1; /** * @brief socket=s; niveau"reseau (sol_socket)"=; option= adresse reutilisable * */ if(setsockopt(s,SOL_SOCKET,SO_REUSEADDR,&vrai,sizeof(vrai))<0){ perror("initialisationServeur.setsockopt (REUSEADDR)"); exit(EXIT_FAILURE); } /** * @brief Options utiles * socket=s; niveau"couche de transport (mode TCP)"=; option= pas de retard (delay) pour envoyer les messages * */ if(setsockopt(s,IPPROTO_TCP,TCP_NODELAY,&vrai,sizeof(vrai))<0){ perror("initialisationServeur.setsockopt (NODELAY)"); exit(EXIT_FAILURE); } /** * @brief Spécification de l'adresse de la socket * */ statut=bind(s,resultat->ai_addr,resultat->ai_addrlen); if(statut<0) return -1; printf("Socket TCP \"bindé\" avec succes\n"); /** * @brief Liberation de la structure d'informations * */ // freeaddrinfo(origine); /** * @brief écoute sur la file d'attentes de taille=[connecions] * */ statut=listen(s,NB_CONNEXIONS); printf("En attente de connexion avec les clients TCP\n"); if(statut<0) return -1; return s; } void dummy(void *dialogue, void* (*action)(void *)) { action(dialogue); } /** * @brief boucle d'attente des connexions * * @param socket * @param fonction * @param action * @return long */ long boucleServeur(long socket, void(*fonction)(void *, void *(*)(void*)), void* (*action)(void*)) { long dialogue; // socket pour le dialogue entre serveur et clients while(1) { socklen_t taille=sizeof(adresse); // Attente d'une connexion if((dialogue=accept(socket,(struct sockaddr *)&adresse,&taille))<0) return -1; // Passage de la socket de dialogue a la fonction de traitement fonction((void*)dialogue,action); } return socket; }
true
0f26f19cc036611e8d65aa7a7fbfed3e5779e90f
C
isabella232/AnghaBench
/source/robotjs/src/extr_str_io.c_createMMBitmapFromString.c
UTF-8
2,371
2.578125
3
[]
no_license
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef int /*<<< orphan*/ uint8_t ; typedef int /*<<< orphan*/ * MMBitmapRef ; typedef int /*<<< orphan*/ MMBMPStringError ; /* Variables and functions */ int /*<<< orphan*/ STR_BITS_PER_PIXEL ; size_t STR_BYTES_PER_PIXEL ; int /*<<< orphan*/ * base64decode (int /*<<< orphan*/ const*,size_t,int /*<<< orphan*/ *) ; int /*<<< orphan*/ * createMMBitmap (int /*<<< orphan*/ *,size_t,size_t,size_t,int /*<<< orphan*/ ,size_t) ; int /*<<< orphan*/ free (int /*<<< orphan*/ *) ; int /*<<< orphan*/ getSizeFromString (int /*<<< orphan*/ const*,size_t,size_t*,size_t*,size_t*) ; int /*<<< orphan*/ kMMBMPStringDecodeError ; int /*<<< orphan*/ kMMBMPStringDecompressError ; int /*<<< orphan*/ kMMBMPStringInvalidHeaderError ; int /*<<< orphan*/ kMMBMPStringSizeError ; int /*<<< orphan*/ * zlib_decompress (int /*<<< orphan*/ *,size_t*) ; MMBitmapRef createMMBitmapFromString(const uint8_t *buffer, size_t buflen, MMBMPStringError *err) { uint8_t *decoded, *decompressed; size_t width, height; size_t len, bytewidth; if (*buffer++ != 'b' || !getSizeFromString(buffer, --buflen, &width, &height, &len)) { if (err != NULL) *err = kMMBMPStringInvalidHeaderError; return NULL; } buffer += len; buflen -= len; decoded = base64decode(buffer, buflen, NULL); if (decoded == NULL) { if (err != NULL) *err = kMMBMPStringDecodeError; return NULL; } decompressed = zlib_decompress(decoded, &len); free(decoded); if (decompressed == NULL) { if (err != NULL) *err = kMMBMPStringDecompressError; return NULL; } bytewidth = width * STR_BYTES_PER_PIXEL; /* Note that bytewidth is NOT * aligned to a padding. */ if (height * bytewidth != len) { if (err != NULL) *err = kMMBMPStringSizeError; return NULL; } return createMMBitmap(decompressed, width, height, bytewidth, STR_BITS_PER_PIXEL, STR_BYTES_PER_PIXEL); }
true
e75d5097b14096ea661e5c911f9925e21075027c
C
enzorossetto/uri-online-judge-problems
/c/1581.c
UTF-8
1,031
3.53125
4
[]
no_license
#include <stdio.h> //Bibliotecas utilizadas #include <stdlib.h> #include <string.h> int main() { char L[100][21]; //Matriz para receber os idiomas falados por cada pessoa int k, n; //Variáveis para recebimento de quantias scanf("%i", &n); //Recebe quantos casos for (int i = 0; i < n; i++) { //Executa o precesso por "n" casos int dif = 0, cont = 0; //Variáveis de controle scanf("%i", &k); //Recebe quantas pessoas estão no grupo fflush(stdin); for (int j = 0; j < k; j++) { //Recebimento dos idiomas scanf("%s ", L[j]); } //Comparação entre os idiomas para saber se há algum diferente while ((cont < k) && (dif == 0)) { dif = strcmp(L[0], L[cont]); cont = cont + 1; } //Mostra qual idioma deve ser falado no grupo if (dif != 0) printf("ingles\n"); else printf("%s\n", L[0]); } return (0); }
true
d8a08d36b7d902bf55a83871e45b227318c2ed29
C
ihavec/JsonRPC_c
/block.c
UTF-8
1,499
2.96875
3
[]
no_license
#include <string.h> #include <math.h> #include <stdlib.h> #include "block.h" block_t * block_Alloc( size_t i_size ) { block_t *p_block = malloc( sizeof(block_t) ); if ( !p_block ) return NULL; size_t i_max = ceil( i_size * 1.0 / 4096 ) * 4096; p_block->p_buffer = malloc( i_max ); if ( !p_block->p_buffer ) { free( p_block ); return NULL; } p_block->i_buffer = 0; p_block->i_maxlen = i_max; return p_block; } block_t *block_Realloc( block_t *p_block, size_t i_addsize ) { size_t i_max = ceil( i_addsize * 1.0 / 4096 ) * 4096; p_block->p_buffer = realloc( p_block->p_buffer, p_block->i_maxlen + i_max ); if ( !p_block->p_buffer ) { block_Release( p_block ); return NULL; } p_block->i_maxlen += i_max; return p_block; } void block_Release( block_t *p_block ) { free( p_block->p_buffer ); free( p_block ); } block_t *block_Append( block_t *p_block, uint8_t *p_buf, size_t i_buf ) { if ( p_block->i_buffer + i_buf >= p_block->i_maxlen ) { //if ( p_block->i_buffer > 65535 ) // log_Warn( "block append found i_buffer big than 65535" ); p_block = block_Realloc( p_block, i_buf ); if ( !p_block ) { //log_Err( "no memory" ); return NULL; } } memcpy( p_block->p_buffer + p_block->i_buffer, p_buf, i_buf ); p_block->i_buffer += i_buf; return p_block; }
true
9bdc055ffa2681bb41d94316920fedca02071c63
C
nhegde610/c_programs
/posorneg.c
UTF-8
280
3.875
4
[]
no_license
#include<stdio.h> int main(){ int num; printf("enter a number to determine if it is positive or negative:"); scanf("%d",&num); if (num < 0) printf("The number is negative\n"); else { printf("The number is positive\n"); } return 0; }
true
c690cc819a801c6e23eefd1d9c4ac4de420997e4
C
kuller416/matrix
/proga.c
UTF-8
2,924
3.296875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { /* m - line , n - pillars */ int m, n; int x, z; /* SCH */ int mem; int min; int xmin; int zmin; int o; int p; min = 150; srand(time(NULL)); m = rand() % 10 + 3; n = rand() % 10 + 4; int massive[m][n]; int delmas[m-1][n-1]; int k; printf("\nmassive\n"); for (x = 0; x < m; x++) { for (z = 0;z < n; z++) { massive[x][z] = rand() % 99+1; printf("%d \t", massive[x][z]); } printf("\n"); } printf("\n\n\n"); printf("\ndef massive\n"); for(z = 0; z < n/2; z++) { mem = massive[0][z]; massive[0][z] = massive [0][n-1-z]; massive[0][n-1-z] = mem; mem = massive[m-1][z]; massive[m-1][z] = massive[m-1][n-1-z]; massive[m-1][n-1-z] = mem; } for (z = 0; z < n; z++) { mem = massive[0][z]; massive[0][z] = massive[m-1][z]; massive[m-1][z] = mem; } printf("\n"); for (x = 0; x < m; x++) { for (z = 0;z < n; z++) printf("%d \t", massive[x][z]); printf("\n"); } printf("\n\n"); printf("\nmassive min\n"); for (x = 0; x < m; x++) { for (z = 0;z < n; z++) { if (massive[x][z] < min) { min = massive[x][z]; xmin = x; zmin = z; } } } for (x = 0; x < m; x++) { for (z = 0; z < n; z++) { if (x != xmin && z != zmin) { delmas[x][z] = massive[x][z]; printf("%d \t", delmas[x][z]); } } if (x != xmin) printf("\n"); } printf("min element %d \n" , min); printf("matrix size (line <Enter> pillar "); scanf("%d", &o); scanf("%d", &p); int c[o][p]; printf("\nyour massive\n"); for (x = 0; x < o; x++) { for (z = 0; z < p; z++) { scanf("%d", &c[x][z]); } } for (x = 0; x < o; x++) { for (z = 0; z < p; z++) { printf("%d \t", c[x][z]); } printf("\n"); } int res[m-1][p]; if (o != n-1) { printf("NO \n"); } else { for(x = 0; x < m-1; x++) { for(z = 0; z < p; z++) { res[x][z] = 0; for(k = 0; k < n-1; k++) { res[x][z] = delmas[x][k] * c[k][z]; } } } printf("\nthe result of multiplying\n"); for (x = 0; x < m-1; x++) { for (z = 0; z < p; z++) { printf("%d \t", res[x][z]); } printf("\n"); } } return 0; }
true
aeaf6cb626ae21ce882e3acfd31ae3118f70e340
C
Emile442/Epitech
/Tek1/C_Pool/Rush-2/rush2.c
UTF-8
2,245
3.21875
3
[]
no_license
/* ** EPITECH PROJECT, 2018 ** rush2 ** File description: ** Rush 2 Detect Lang */ #include "my.h" #include "rush.h" int count_alpha(const char *str); int count_letter(const char *str, char c) { int counter = 0; char *tmp = str; tmp = my_strlowcase(tmp); if (c >= 65 && c <= 90) c = c + 32; for (int i = 0; str[i]; i++) { if (tmp[i] == c) counter++; } return (counter); } void display(const char c, int nbr, int length__total) { float frequency = 0; int uni = 0; int dec = 0; float nbr_f = nbr; frequency = nbr_f / length__total * 100; uni = frequency / 1; dec = frequency * 100; my_putchar(c); my_putchar(':'); my_put_nbr(nbr); my_putchar(' '); my_putchar('('); my_put_nbr(uni); my_putchar('.'); my_put_nbr(dec % 100); if (!(dec % 100)) my_putchar(48); my_putchar('%'); my_putchar(')'); my_putchar('\n'); } char *lang(float en, float fr, float ge, float es) { if (fr > en && fr > ge && fr > es) return ("=> French"); if (en > fr && en > ge && en > es) return ("=> English"); if (ge > en && ge > fr && ge > es) return ("=> German"); if (es > en && es > fr && es > ge) return ("=> Spanish"); return ("=> Unknow"); } void result(const char *str, int length_total) { float collect[27]; float en = 0; float fr = 0; float ge = 0; float es = 0; char letter = 97; char *tmp = str; for (int i = 0; i < 26; i++) { collect[i] = count_letter(my_strlowcase(tmp), letter); letter++; } for (int i = 0; i < 26; i++) { en += collect[i] * STATS[i][0]; fr += collect[i] * STATS[i][1]; ge += collect[i] * STATS[i][2]; es += collect[i] * STATS[i][3]; } my_putstr(lang(en, fr, ge, es)); } int main(int argc, char const **argv) { int length = 0; int counter = 0; if (argc == 1) return (84); length = count_alpha(argv[1]); for (int i = 2; i < argc; i++) { int tmp; tmp = count_letter(argv[1], argv[i][0]); counter += tmp; display(argv[i][0], tmp, length); } result(argv[1], length); return (0); }
true
aad8a2ce52671e47e2b83c31ec536488c51b4a96
C
sbenning42/42
/proj/42sh/srcs/exec/exec_sep.c
UTF-8
1,388
2.578125
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* exec_sep.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbenning <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/09/12 13:53:23 by sbenning #+# #+# */ /* Updated: 2016/09/12 14:04:45 by sbenning ### ########.fr */ /* */ /* ************************************************************************** */ #include "sh.h" int exec_strict_sep(t_sh *sh, t_tree *root) { exec_root(sh, root->l); exec_root(sh, root->r); return (0); } int exec_and_sep(t_sh *sh, t_tree *root) { int status; status = exec_root(sh, root->l); if (status != 0) return (status); status = exec_root(sh, root->r); return (status); } int exec_or_sep(t_sh *sh, t_tree *root) { int status; status = exec_root(sh, root->l); if (status == 0) return (status); status = exec_root(sh, root->r); return (status); }
true
a7bdc2447de4a2aac3dfca39cd4a24a4a85c6654
C
DvGentoo/StudentWorks
/Algorithms/Bubble Sort/Bubble sort.c
UTF-8
573
3.84375
4
[]
no_license
#include <stdio.h> int bubbleSort(int arr[], int sizeArr); int main() { int array[] = {2,6,7,8,1,9}; int sizeArray = sizeof(array) / sizeof(int); bubbleSort(array,sizeArray); return 0; } int bubbleSort(int arr[], int sizeArr) { int result = 1; while(result) { result = 0; for(int i = 0; i < sizeArr; i++) { if(arr[i] > arr[i+1]) { int foo = arr[i]; arr[i] = arr[i+1]; arr[i+1] = foo; result = 1; } } } }
true
bc7c4e246e2376ed995740f3f22a3a4f0286c254
C
Takanashi-Rikka-O/C
/C/Linux_C/PIPE/pipe2.c
UTF-8
889
3.125
3
[]
no_license
#include<unistd.h> #include<sys/types.h> #include<stdlib.h> #include<stdio.h> #include<string.h> int main(void) { int data_processed; int file_pipes[2]; const char some_data[]="123"; char buffer[BUFSIZ+1]; pid_t fork_result; memset(buffer,'\0',sizeof(buffer)); if (pipe(file_pipes) == 0) { fork_result=fork(); // fork_result is PID if (fork_result == -1) { perror("Fork failure.."); exit(EXIT_FAILURE); } else; if (fork_result == 0) { data_processed=read(file_pipes[0],buffer,BUFSIZ); printf("Read %d bytes: %s\n",data_processed,buffer); exit(15); } else{ data_processed=write(file_pipes[1],some_data,strlen(some_data)); printf("Wrote %d bytes\n",data_processed); int re=0; re=wait(); printf("Process %d is over..\n",re); } } else { perror("pipe failed.."); exit(5); } //wait(&fork_result); exit(EXIT_SUCCESS); }
true
2727cc69503c4d5012f675915f0d5adc34a19c16
C
mohanlalyadav222/Basic-Beginners-Code-C-Language
/a5.c
UTF-8
293
3.359375
3
[]
no_license
#include<stdio.h> /*Print Fahrenheit-Celsius table for fahr=0,20,40....300*/ int main(){ int fahr,celsius,lower,upper,step; lower=0;//lower limit upper=300;//upper limit step=20; while(fahr<=upper){ celsius=5*(fahr-32)/9; printf("%d\t %d\n",fahr,celsius); fahr=fahr+step; } }
true
c6a5704c299f07063d98ca3af644fea2d309d360
C
choijam/BOJ
/3943.c
UTF-8
335
3.28125
3
[]
no_license
#include <stdio.h> int max; int hailstone(int n){ if(max<=n) max=n; if(n%2==0) hailstone(n/2); else if(n%2==1&&n!=1) hailstone(n*3+1); else if(n==1) return max; } int main() { int t; int n,result; scanf("%d",&t); while(t--){ scanf("%d",&n); max=n; printf("%d\n",hailstone(n)); max=0; } return 0; }
true
f05633046f346d02617bcae4301d955d95f0f1be
C
lgcardeas/system_command
/find_inside.c
UTF-8
2,797
3.5625
4
[]
no_license
#include <dirent.h> #include <errno.h> #include <stdio.h> #include <string.h> #include <stdio.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> char *Pattern; /*Prototipo de funciones usadas*/ int isFile(char *path); int isDirectory(char *path); void movDir(char *path); int BruteForce(int fd); int main(int argc, char *argv[]) { int fd; if (argc != 3) { fprintf(stderr,"Use %s <Directorio>|<Archivo> <Patron> \n",argv[0]); return -1; } Pattern = argv[2]; if (isDirectory(argv[1])) movDir(argv[1]); else if (isFile(argv[1])) if ((fd = open(argv[1],O_RDONLY)) == -1) fprintf(stderr,"Error al abrir el archivo %s",argv[1]); else if(BruteForce(fd) == 0) printf("%s\n",argv[1]); else { fprintf(stderr,"%s no es ni archivo ni directorio"); return -1; } return 0; } /*Funcion para moverse dentro de los directorios*/ void movDir(char *path) { struct dirent *dp; DIR *dir; char dirPATH[1024]; int fd; if ((dir = opendir(path)) == NULL) fprintf(stderr,"Error al abrir el directorio %s \n",path); else { while((dp = readdir(dir)) != NULL) { if ((strcmp(dp->d_name,".") == 0) || (strcmp(dp->d_name,"..") == 0)) continue; sprintf(dirPATH,"%s/%s",path,dp->d_name); if (isDirectory(dirPATH)) movDir(dirPATH); else if (isFile(dirPATH)) if((fd = open(dirPATH,O_RDONLY)) == -1) fprintf(stderr,"No se puede abrir el archivo %s\n",dirPATH); else if (BruteForce(fd) == 0){ printf("FILE %s \n",dirPATH); } } while((closedir(dir) == -1) && (errno == EINTR)); } } /*Prgunta si lo pasodo por parametro es un archivo*/ int isFile(char *path) { struct stat statbuf; if (stat(path,&statbuf) == -1) { fprintf(stderr,"No se puede acceder al archivo %s \n",path); return 0; } else return S_ISREG(statbuf.st_mode); } /*Pregunta si lo pasado por parametro es un directorio*/ int isDirectory(char *path) { struct stat statbuf; if (stat(path, &statbuf) == -1) { fprintf(stderr,"No se puede acceder %s\n",path); return 0; } else return S_ISDIR(statbuf.st_mode); } /*Algoritmo ForceBrutal para buscar un patron en un archivo*/ int BruteForce(int fd) { char c; int j = 0; int n = strlen(Pattern) - 1; int numRead = 1; printf("%d %s \n",n,Pattern); while(numRead) { if((numRead = read(fd,&c,1)) == -1) { fprintf(stderr,"Error de lectura"); return 1; } else if (numRead == 1) { if (*(Pattern + j) == c) j++; else j = 0; if (j == n) { close(fd); return 0; } } } close(fd); return 1; }
true
9863ca6bc856f0a0a95fb7a27a5578f45d6e2879
C
sofixa/Pipex
/libft/ft_strsplit.c
UTF-8
1,702
3.0625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strsplit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kmesas <kmesas@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/02/09 22:51:26 by kmesas #+# #+# */ /* Updated: 2014/03/26 01:27:37 by kmesas ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static char *get_begin(char *s, char c) { while (*s != '\0' && *s == c) s++; return (s); } static char *get_end(char *s, char c) { while (*s != '\0' && *s != c) s++; return (s); } static int count_word(char *str, char c) { char *s; int count; s = get_begin(str, c); count = 0; while (*s != '\0') { s = get_end(s, c); s = get_begin(s, c); count++; } return (count); } char **ft_strsplit(char *str, char c) { char *s; char *end; int count; char **tab; if (str == 0) return (0); count = count_word(str, c); tab = (char **)malloc((count + 1) * sizeof(char *)); s = get_begin(str, c); count = 0; while (*s != '\0') { end = get_end(s, c); tab[count] = ft_strndup(s, end - s); s = end; s = get_begin(s, c); count++; } tab[count] = 0; return (tab); }
true
5945da714488c7cfafdd44cafb83cefdec702774
C
AndreaFalanti/middleware-2020-falanti-ferri-faltaous
/project4/individual.c
UTF-8
1,230
2.78125
3
[ "MIT" ]
permissive
#include <stdio.h> #include <stddef.h> #include "individual.h" const char* statusNames[] = { "susceptible", "infected", "immune" }; void printIndividualState(individual i) { printf("[ID: %d] status: %s, position: (%f, %f), speed: (%f, %f), cumulated time: %ld\n", i.id, statusNames[i.status], i.pos.x, i.pos.y, i.vel.x, i.vel.y, i.status_cumulated_time); } void commitIndividualTypeMPI(MPI_Datatype *mpi_type, MPI_Datatype MPI_TUPLE) { int struct_len = 5; // 5 variables int block_lens[5] = {1, 1, 1, 1, 1}; MPI_Datatype types[5] = {MPI_INT, MPI_TUPLE, MPI_TUPLE, MPI_INT, MPI_LONG}; // MPI type for each variable // We need to compute the displacement to be really portable // (different compilers might align structures differently) MPI_Aint displacements[struct_len]; displacements[0] = offsetof(individual, id); displacements[1] = offsetof(individual, vel); displacements[2] = offsetof(individual, pos); displacements[3] = offsetof(individual, status); displacements[4] = offsetof(individual, status_cumulated_time); MPI_Type_create_struct(struct_len, block_lens, displacements, types, mpi_type); MPI_Type_commit(mpi_type); }
true
c23047e266ea55fc6dce0824d492a1728a57fbdd
C
AlexanderNevarko/Alex-compiler
/node.h
UTF-8
2,119
2.9375
3
[]
no_license
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #define NODE #include "tree_def.h" enum types_t { BAD_OP = -1, TEXT = 0, NUMBER = 1, VARIABLE = 2, CALL = 3, OPERATOR = 4, COMPARISON = 5, ASSIGN = 6, IF_T = 7, ELSE_T = 8, WHILE_T = 9, DECL_T = 10, FUNC_T = 11, SIN_T = 12, COS_T = 13, TAN_T = 14, LN_T = 15, SQRT_T = 16, DIVIDER = 17, START = 18, RETURN_T = 19, TERMINATOR = 20, INPUT_T = 21, OUTPUT_T = 22 }; struct Node_t { Node_t* parent; char* data; int type; Node_t* left; Node_t* right; }; Node_t* Node_Ctor (const char* info, int type); bool Node_Dtor (Node_t* node); bool Node_OK (Node_t* node); bool Node_Dump (Node_t* node); char* my_str_dup (const char* str, int size) { char* new_str = (char*) calloc (size + 1, sizeof (*new_str)); strcpy (new_str, str); return new_str; } Node_t* Node_Ctor (const char* info, int type) { assert (info); Node_t* node = (Node_t*) calloc (1, sizeof (Node_t)); PAR = NULL; DATA = my_str_dup (info, strlen (info)); TYPE = type; LEFT = NULL; RIGHT = NULL; return node; } bool Node_Dtor (Node_t* node) { assert (node); free (DATA); DATA = NULL; free (node); node = NULL; return true; } bool Node_OK (Node_t* node) { return (node) ? DATA && (TYPE > BAD_OP) : NULL; } bool Node_Dump (Node_t* node) { if (node == NULL) { printf ("Node Dump (ERROR!!!) NULL POINTER!\n"); return false; } bool t = Node_OK (node); printf ("Node Dump (%s) [%0X]\n{\n" "\tparent [%0X]\n" "\tdata: %s\n" "\ttype = %d\n" "\tleft [%0X]\n" "\tright [%0X]\n" "}\n", t ? "OK" : "ERROR!!!", node, PAR, DATA, TYPE, LEFT, RIGHT); return t ? true : false; } #undef NODE
true
eb01b09a3df779ecb2da0c7cf9ebfadfa5c70938
C
SandKierkegaard/intelligent_camera_trap
/Turret/NINJA_168/NINJA_168/src/StepperMotor/StepperMotorSTM.c
UTF-8
6,830
2.609375
3
[]
no_license
#include "./Header/StepperMotorSTM.h" #include "./Header/StepperMotorTimer.h" #include "./Header/StepperMotorIO.h" #include "./Header/StepperMotorPosition.h" #include "./Header/Constant.h" unsigned char panSpeedAdjustment(unsigned char direction) { static unsigned char directionHistory [4] = {STAY_PUT,STAY_PUT,STAY_PUT,STAY_PUT}; unsigned char accelerate = SPEED_SLOWEST; directionHistory[3] = directionHistory[2] ; directionHistory[2] = directionHistory[1] ; directionHistory[1] = directionHistory[0] ; directionHistory[0] = direction ; if ((direction != STAY_PUT) && (directionHistory[3] == directionHistory[2]) && (directionHistory[2] == directionHistory[1]) && (directionHistory[1] == directionHistory[0])) { accelerate = SPEED_ACCELERATE; if (directionHistory[0] == MOVING_LEFT) { directionHistory[0] = MOVING_LEFT_ACC; } else if (directionHistory[0] == MOVING_RIGHT) { directionHistory[0] = MOVING_RIGHT_ACC; } } else if ((directionHistory[0] == MOVING_LEFT && (directionHistory[1] == MOVING_LEFT_ACC || directionHistory[1] == MOVING_LEFT )) || (directionHistory[0] == MOVING_RIGHT && (directionHistory[1] == MOVING_RIGHT_ACC || directionHistory[1] == MOVING_RIGHT ))) { accelerate = SPEED_CONSTANT; } else { accelerate = SPEED_SLOWEST; } return accelerate; } static unsigned char panMoving = FALSE; static unsigned char panDirection = STAY_PUT; unsigned char getPanMoving(void) { return panMoving; } unsigned char getPanDirection(void) { return panDirection; } void panStepMotorSTM(void) { unsigned char doneMoving = FALSE; unsigned char speedDecision = SPEED_CONSTANT; decrementPanQuarterStepTimer(); if(expiredPanQuarterStepTimer()) { if (panMoving == TRUE) { doneMoving = panSteppingInDirection(panDirection); if (doneMoving == TRUE) { panDirection = nextPanDirection(); speedDecision = panSpeedAdjustment(panDirection); if (panDirection != STAY_PUT) { panMoving = TRUE; if (speedDecision == SPEED_ACCELERATE) { panAccelerate(); } else if (speedDecision == SPEED_SLOWEST) { resetPanSpeed(); } panSteppingInDirection(panDirection); } else { panMoving = FALSE; resetPanSpeed(); } } }else { //Should we be moving? panDirection = nextPanDirection(); speedDecision = panSpeedAdjustment(panDirection); if (panDirection != STAY_PUT) { panMoving = TRUE; panSteppingInDirection(panDirection); } } resetPanQuarterStepTimer(); } } void initPanPositionToCenter() { unsigned char position; position = checkPanPosition(); position = checkPanPosition(); position = checkPanPosition(); if (position == POSITION_LEFT) { setCurrentPanPosition(LEFT_LIMIT); } else if (position == POSITION_RIGHT) { setCurrentPanPosition(RIGHT_LIMIT); } setTargePanPosition(CENTER_PAN); } //Tilt unsigned char tiltSpeedAdjustment(unsigned char direction) { static unsigned char directionHistory [4] = {STAY_PUT,STAY_PUT,STAY_PUT,STAY_PUT}; unsigned char accelerate = SPEED_SLOWEST; directionHistory[3] = directionHistory[2] ; directionHistory[2] = directionHistory[1] ; directionHistory[1] = directionHistory[0] ; directionHistory[0] = direction ; if ((direction != STAY_PUT) && (directionHistory[3] == directionHistory[2]) && (directionHistory[2] == directionHistory[1]) && (directionHistory[1] == directionHistory[0])) { accelerate = SPEED_ACCELERATE; if (directionHistory[0] == MOVING_DOWN) { directionHistory[0] = MOVING_DOWN_ACC; } else if (directionHistory[0] == MOVING_UP) { directionHistory[0] = MOVING_UP_ACC; } } else if ((directionHistory[0] == MOVING_DOWN && (directionHistory[1] == MOVING_DOWN_ACC || directionHistory[1] == MOVING_DOWN )) || (directionHistory[0] == MOVING_UP && (directionHistory[1] == MOVING_UP_ACC || directionHistory[1] == MOVING_UP ))) { accelerate = SPEED_CONSTANT; } else { accelerate = SPEED_SLOWEST; } return accelerate; } static unsigned char tiltMoving = FALSE; static unsigned char tiltDirection = STAY_PUT; unsigned char getTiltMoving(void) { return tiltMoving; } unsigned char getTiltDirection(void) { return tiltDirection; } void tiltStepMotorSTM(void) { unsigned char doneMoving = FALSE; unsigned char speedDecision = SPEED_CONSTANT; decrementTiltQuarterStepTimer(); if(expiredTiltQuarterStepTimer()) { if (tiltMoving == TRUE) { doneMoving = tiltSteppingInDirection(tiltDirection); if (doneMoving == TRUE) { tiltDirection = nextTiltDirection(); speedDecision = tiltSpeedAdjustment(tiltDirection); if (tiltDirection != STAY_PUT) { tiltMoving = TRUE; if (speedDecision == SPEED_ACCELERATE) { tiltAccelerate(); } else if (speedDecision == SPEED_SLOWEST) { resetTiltSpeed(); } tiltSteppingInDirection(tiltDirection); } else { tiltMoving = FALSE; resetTiltSpeed(); } } }else { //Should we be moving? tiltDirection = nextTiltDirection(); speedDecision = tiltSpeedAdjustment(tiltDirection); if (tiltDirection != STAY_PUT) { tiltMoving = TRUE; tiltSteppingInDirection(tiltDirection); } } resetTiltQuarterStepTimer(); } } void initTiltPositionToCenter() { unsigned char position; position = checkTiltPosition(); position = checkTiltPosition(); position = checkTiltPosition(); if (position == POSITION_DOWN) { setCurrentTiltPosition(DOWN_LIMIT); } else if (position == POSITION_UP) { setCurrentTiltPosition(UP_LIMIT); } setTargeTiltPosition(CENTER_TILT); }
true
b0d4adf4dd6c76f1dad0c3fe469e0fea7eb941f0
C
Neon-20/My-library-for-CP
/data structure/BIT.h
UTF-8
351
3.234375
3
[]
no_license
struct BIT { int n; vector<int>bit; BIT(int _n) { n=_n; bit.resize(n+1); } void update(int indx,int val) { if(indx>0) for(;indx<=n;indx+=(indx&-indx)) bit[indx]+=val; } int sum(int indx) { int tot=0; for(;indx>0;indx-=(indx&-indx)) tot+=bit[indx]; return tot; } int sum(int l,int r) { return sum(r)-sum(l-1); } };
true
e52fb9018508963ae0d5a4678f2d0ede865d47b8
C
daniellycosta/parallel-programming-exercises
/ch3/q19.c
UTF-8
2,455
3.421875
3
[]
no_license
/* File: q19.c * * Purpose: A program in which multiple MPI processes receive a slice of two vectors (v1,v2) * and a escalar (a) and makes: (a*v1) * v2 * * Compile: mpicc -g -Wall -o q19 q09.c * Usage: mpiexec -n <number of processes> ./q19 * * Input: arrays size, escalar, array elements * Output: Answer vector */ #include <stdio.h> #include <stdlib.h> #include <mpi.h> #include <string.h> //#define DEBUG true void Read_Escalars(int *n_p, int my_rank, MPI_Comm comm); void Read_Matrix(char vector_name[], int matrix[], int n, int my_rank, MPI_Datatype type, MPI_Comm comm); void Print_answer(int matrix[], int n); int main(void) { int my_rank, comm_sz; int n; int *matrix, *block_len, *displ; MPI_Comm comm = MPI_COMM_WORLD; MPI_Datatype my_datatype; MPI_Init(NULL, NULL); MPI_Comm_size(comm, &comm_sz); MPI_Comm_rank(comm, &my_rank); Read_Escalars(&n, my_rank, comm); block_len = malloc(n * sizeof(int)); displ = malloc(n * sizeof(int)); for (int i = 0; i < n; i++) { block_len[i] = n - i; displ[i] = i * (n + 1); } MPI_Type_indexed(n, block_len, displ, MPI_INT, &my_datatype); MPI_Type_commit(&my_datatype); matrix = malloc(n * n * sizeof(int)); Read_Matrix("Matrix", matrix, n, my_rank, my_datatype, comm); if (my_rank) Print_answer(matrix, n); free(matrix); MPI_Finalize(); return 0; } /* main */ void Read_Matrix( char vector_name[] /* in */, int matrix[] /* out */, int n /* in */, int my_rank /* in */, MPI_Datatype type, MPI_Comm comm /* in */) { int i; if (my_rank == 0) { printf("Enter the matrix %s (%d elements)\n", vector_name, n * n); for (i = 0; i < n * n; i++) scanf("%d", &matrix[i]); MPI_Send(matrix, 1, type, 1, 0, comm); } else if (my_rank == 1) { MPI_Recv(matrix, 1, type, 0, 0, comm, MPI_STATUS_IGNORE); } } /* Read_vector */ void Read_Escalars( int *n_p /* out */, int my_rank /* in */, MPI_Comm comm /* in */) { if (my_rank == 0) { printf("Enter the number of elements\n"); scanf("%d", n_p); } MPI_Bcast(n_p, 1, MPI_INT, 0, comm); } /* Read_Escalars */ void Print_answer( int matrix[] /* in */, int n /* in */) { int i, j; printf("\nThe Result: \n"); for (i = 0; i < n; i++) { for (j = i; j < n; j++) { printf("%d ", matrix[i * n + j]); } printf("\n"); } printf("\n"); } /* Print_answer */
true
be78485cf42a550d52a6c21cd0e4e9b43f950ca8
C
AlexIsaacT/github-project
/C_programming/chapter1/ex1.18.c
UTF-8
665
3.546875
4
[]
no_license
#include <stdio.h> #define MAXLINE 1000 int getlines(char s[], int max); int main() { int len, i; char line[MAXLINE]; while ((len = getlines(line, MAXLINE)) != 0) { if (len > 1) { for (i = len-1; (line[i] == ' ' || line[i] == '\t' || line[i] == '\n'); i--) ; line[++i] = '\0'; printf("%s\n", line); } } return 0; } int getlines(char s[], int max) { int i, c; for (i=0; i<max-1 && (c=getchar())!=EOF && c!='\n'; i++) { s[i] = c; } if (c == '\n') { s[i] = c; i++; } s[i] = '\0'; return i; }
true
b9cca8d3fa049de15dc1f33e62bbdd302c49fd0a
C
ShresthaBaburam/dataStructure
/array.c
UTF-8
3,518
4.6875
5
[]
no_license
#include<stdio.h> int main(){ int i, n , m; /* Arrays Arrays are defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char, double, float, etc. Array is the simplest data structure where each data element can be randomly accessed Properties Each element is of same data type and carries a same size i.e. int = 4 bytes. Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location. Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of data element. The syntax of declaring an array int arr[10]; char arr[10]; float arr[5]; */ // Array declaration by specifying size n printf("Enter the size of the array(n):"); scanf("%d",&n); int math[n]; for(i=0; i<n;i++){ printf("Enter the number in maths of [%d] Student:",i+1); scanf("%d",&math[i]); } // Array declaration by specifying size int science[5]; for(i=0; i<5;i++){ printf("Enter the number in science of [%d] Student:", i+1); scanf("%d",&science[i]); } // Array declaration by specifying size and value int geology[10] = {53,6,4,67,4,52,32,14, 23, 52}; // Array declaration by specifying without size and value printf("Enter the size of the array(m):"); scanf("%d",&m); int social[m]; for(i=0; i<m;i++){ printf("Enter the number in Social of [%d] Student:",i+1); scanf("%d",&science[i]); } /* Need of using Array The most of the cases requires to store the large number of data of similar type. To store such amount of data, we need to define a large number of variables. It would be very difficult to remember names of all the variables while writing the programs. Instead of naming all the variables with a different name, it is better to define an array and store all the elements into it. Advantages of Array Array provides the single name for the group of variables of the same type therefore, it is easy to remember the name of all the elements of an array. Traversing an array is a very simple process, we just need to increment the base address of the array in order to visit each element one by one. Any element in the array can be directly accessed by using the index. Use of less line of code as it creates a single array of multiple elements. Sorting becomes easy as it can be accomplished by writing less line of code. Disadvantages of an Array Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in C is not dynamic. Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation. */ //Accessing Array Elements printf("%d,%d,%d,%d,%d", math[0],math[1],math[2], math[3],math[4],math[5]); for(i=0; i<10;i++){ printf("%d\n", science[i+1]); } //Array as the argument printf("%d",average_math(n, math[n])); return 0; } int average_math(int a, int math_number[a]){ int i, average_marks=0; for(i=0; i<a;i++){ average_marks += math_number[i]; } average_marks /=a; return average_marks; }
true
3bb5a20c99197b0f2bf7a40ecfb8cfdc4d95063a
C
JoshuaTPierce/Learning_Repo1
/Lafore_OOCPP/Random, Various/Arduino C Programs/simpleTimer.C
UTF-8
626
3.1875
3
[]
no_license
/* * Simple Timer * Demonstrates the use of a non-core Arduino Library and Serial Communications * Joshua Pierce */ #include <SimpleTimer.h> SimpleTimer timer; //Constructor for the timer function from SimpleTimer boolean currentLEDState; int ledPin = 13; void setup(){ currentLEDState = false; pinMode(ledPin, OUTPUT); timer.setInterval(120, blink); //sets a 120 ms pause without calling a pause() function } void loop(){ timer.run(); } void blink(){ if(!currentLEDState){ digitalWrite(ledPin, HIGH); } else { digitalWrite(ledPin, LOW); currentLEDState = !currentLEDState; //invert boolean } }
true
cb62471c27c9c41b3169052325a5b1e99a96cf4c
C
Soos99/rexp
/Tree.c
UTF-8
1,245
3.46875
3
[]
no_license
#include <stdlib.h> #include <stdio.h> #include "Tree.h" Tree makeNode0(char *x, int indent){ Tree root; root = (Tree) malloc(sizeof(struct Node)); root->label = x; root->child = NULL; root->sibling = NULL; root->indent = indent; root->freeable = false; return root; } Tree makeNode1(char *x, Tree t, int indent){ Tree root; root = makeNode0(x,indent); root->child = t; return root; } Tree makeNode2(char *x, Tree t1, Tree t2,int indent){ Tree root; root = makeNode1(x,t1,indent); t1->sibling = t2; return root; } Tree makeNode3(char *x, Tree t1, Tree t2, Tree t3, int indent){ Tree root; root = makeNode1(x,t1,indent); t1->sibling = t2; t2->sibling = t3; return root; } Tree makeNode4(char *x, Tree t1, Tree t2, Tree t3, Tree t4, int indent){ Tree root; root = makeNode1(x,t1,indent); t1->sibling = t2; t2->sibling = t3; t3->sibling = t4; return root; } void freeTree(Tree tree) { if (tree->child) freeTree(tree->child); if (tree->sibling) freeTree(tree->sibling); if (tree->freeable) free(tree->label); free(tree); } void printError(){ printf("The input is not well-formed\n"); }
true
55b4ed35b15725da50b38ae24733f74e5a285fd2
C
JamesWright52/BeInfo
/include/intersect.h
UTF-8
1,073
3.1875
3
[]
no_license
#ifndef INTERSECT_H #define INTERSECT_H #include <stdio.h> #include <stdlib.h> #include "fonction.h" /* Ici, on est oblige d'utiliser la notation struct listepoint, car la structure s'auto-reference!*/ typedef struct elemListe { POINT p; VECTEUR vecteur; struct elemListe* suivant ; } ELEMT ; typedef struct Liste{ ELEMT *premier; } LISTE; //fonction qui prends une matrice de coordonnees et une côte en argument //renvoie la liste des points d'intersections entre le plan z et l'objet //(format [[P1,P2,P3],...,[P3n,,P3n+1,P3n+2]]) LISTE* intersect(TRIANGLE* matrice, int* pnligne, double cote); // Renvoie le plus petit réel parmi 3. double min(double z1, double z2, double z3); // Renvoie le plus grand réel parmi 3. double max(double z1, double z2, double z3); //renvoie 1 si le segment entre z1 et z2 intersecte le plan int segment_intersecte(double cote,double z1, double z2); //compte le nombre de fois où point apparaît int compteOccurence(LISTE* liste, POINT point); //Elimine les points en double LISTE* listeSansDoublon(LISTE* liste); #endif
true
c6d579bc3dc161395b665d6b06e2c91ad9530441
C
bradduthie/Inbreeding
/vectorrank.c
UTF-8
1,002
3.21875
3
[]
no_license
/***********************************************************************************/ /* Program: arraysort2D.c By: Brad Duthie Description: Sorts a 2D array by the value of a column element. Compile: gcc randpois.c -ansi -Wall -pedantic */ /***********************************************************************************/ #include <stdio.h> #include "array.h" void vectorrank(double *vec, double **Rank, int xlen){ int i, j; double *r, m, n; MAKE_1ARRAY(r,xlen*xlen); for(i=0; i<(xlen*xlen); i++){ r[i] = 0; for(j=0; j<(xlen*xlen); j++){ if(vec[i] > vec[j]){ r[i]++; } } } m = 0.0; /*row */ n = 0.0; /* column */ for(i=0; i<(xlen*xlen); i++){ Rank[i][0] = m; Rank[i][1] = n; Rank[i][2] = r[i]; m++; if(m==xlen){ n++; m = 0; } } FREE_1ARRAY(r); }
true
df1164ba16e6fc4141e4d55e26a45a44c735063c
C
J0nhy/Tarefa5-Ficheiros
/Tarefa5/ficheiro03.c
UTF-8
794
2.734375
3
[]
no_license
//All rights reserved to Custodio Co. Copyright 2020 #include<stdio.h> #include<stdlib.h> #include <locale.h> int main(){ setlocale(LC_ALL, "Portuguese"); FILE *fp; char username[100]; char password[50]; char ponto[1] = {';'}; int i; fp = fopen("user.dat","wb"); if(!fp){ printf("Erro na abertura do arquivo."); exit(0);} else { printf("O ficheiro aberto corretamente!"); } printf("\n--------------------------Login:----------------------"); printf("\nInsira o username: "); gets(username); printf("\nInsira a password: "); gets(password); for(i=0; username[i]; i++) fputc(username[i], fp); fputc(';', fp); for(i=0; password[i]; i++) fputc(password[i], fp); fputc(';', fp); fclose(fp); return 0; }
true
3e0d4c94b533138456498fb86f1e14b085274bd7
C
joyeepeng/pjCLibs
/pjJpegFile/pjJpegFile.c
UTF-8
9,091
2.59375
3
[]
no_license
/******************************************************************************* * File Name: pjJpegFile.c * Author: Joyee Peng * Email: joyee.peng@gmail.com * Github: https://github.com/joyeepeng * Blog: http://blog.csdn.net/pengqianhe * History: 2012-10-23 initial release version *******************************************************************************/ #include "pjJpegFile.h" static void PjLibJpeg_error_exit (j_common_ptr cinfo) { /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */ my_error_ptr myerr = (my_error_ptr) cinfo->err; /* Always display the message. */ /* We could postpone this until after returning, if we chose. */ (*cinfo->err->output_message) (cinfo); /* Return control to the setjmp point */ longjmp(myerr->setjmp_buffer, 1); } /******************************************************************************* * Version * version = major.minor.patch 8-bits 8-bits 8-bits *******************************************************************************/ /*************************************** * pjJpegFile_GetVersionPatch ***************************************/ int pjJpegFile_GetVersionPatch( void ){ return PJJPEGFILE_VERSION_PATCH; } /*************************************** * pjJpegFile_GetVersionMinor ***************************************/ int pjJpegFile_GetVersionMinor( void ){ return PJJPEGFILE_VERSION_MINOR; } /*************************************** * pjJpegFile_GetVersionMajor ***************************************/ int pjJpegFile_GetVersionMajor( void ){ return PJJPEGFILE_VERSION_MAJOR; } /*************************************** * pjJpegFile_GetVersion ***************************************/ long int pjJpegFile_GetVersion( void ){ return (PJJPEGFILE_VERSION_MAJOR<<16) | (PJJPEGFILE_VERSION_MINOR<<8) | PJJPEGFILE_VERSION_PATCH; } /******************************************************************************* * Public Methods *******************************************************************************/ /*************************************** * pjJpegFile_ReadFile ***************************************/ int pjJpegFile_ReadFile( char* fileName, pjJpegFile* jpegFile ){ struct jpeg_decompress_struct cinfo; struct PjLibJpeg_error_mgr jerr; FILE* infile; JSAMPROW row_pointer[1]; int row_stride; int counter = 0; int i = 0; if( ( infile = fopen(fileName,"rb") ) == NULL ){ fprintf( stderr,"can't open %s to read.\n", fileName ); return 0; } cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = PjLibJpeg_error_exit; if( setjmp(jerr.setjmp_buffer) ){ jpeg_destroy_decompress(&cinfo); fclose(infile); return 0; } jpeg_create_decompress(&cinfo); jpeg_stdio_src(&cinfo,infile); jpeg_read_header(&cinfo,TRUE); jpeg_start_decompress(&cinfo); row_stride = cinfo.output_width * cinfo.output_components; row_pointer[0] = (unsigned char*)malloc( cinfo.output_width * cinfo.num_components ); jpegFile->Width = cinfo.output_width; jpegFile->Height = cinfo.output_height; jpegFile->Stride = row_stride; jpegFile->Pixels = (unsigned char*)malloc( cinfo.output_width * cinfo.output_height * cinfo.output_components * sizeof(char) ); while( cinfo.output_scanline < cinfo.output_height ){ jpeg_read_scanlines( &cinfo, row_pointer, 1 ); for(i = 0;i < (cinfo.image_width * cinfo.num_components); i++) jpegFile->Pixels[counter++] = row_pointer[0][i]; } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); fclose(infile); free(row_pointer[0]); return 1; } /*************************************** * pjJpegFile_WriteFile ***************************************/ int pjJpegFile_WriteFile( const pjJpegFile* jpegFile, char* fileName, int quality ){ struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; FILE * outfile; /* target file */ JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */ int row_stride; /* physical row width in image buffer */ int counter = 0; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); if ((outfile = fopen(fileName, "wb")) == NULL) { fprintf(stderr, "can't open %s to write.\n", fileName); exit(1); } jpeg_stdio_dest(&cinfo, outfile); cinfo.image_width = jpegFile->Width; /* image width and height, in pixels */ cinfo.image_height = jpegFile->Height; cinfo.input_components = 3; /* # of color components per pixel */ cinfo.in_color_space = JCS_RGB; /* colorspace of input image */ jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */); jpeg_start_compress(&cinfo, TRUE); while (cinfo.next_scanline < cinfo.image_height) { /* jpeg_write_scanlines expects an array of pointers to scanlines. * Here the array is only one element long, but you could pass * more than one scanline at a time if that's more convenient. */ row_pointer[0] = & jpegFile->Pixels[cinfo.next_scanline * cinfo.image_width * cinfo.input_components]; (void) jpeg_write_scanlines(&cinfo, row_pointer, 1); } jpeg_finish_compress(&cinfo); fclose(outfile); jpeg_destroy_compress(&cinfo); return 1; } /*************************************** * pjJpegFile_GetPixel ***************************************/ pjJpegColor pjJpegFile_GetPixel( const pjJpegFile* jpegFile, unsigned int row, unsigned int col ){ pjJpegColor color; if( !(jpegFile->Height > row && row >= 0) ){ fprintf(stderr, "row must be in 0 to %d.\r\n", jpegFile->Height-1); return color; } if( !( jpegFile->Width >col && col >= 0 ) ){ fprintf(stderr, "col must be in 0 to %d.\r\n", jpegFile->Width-1); return color; } color.R = (unsigned char)*(jpegFile->Pixels+jpegFile->Stride*row+col*3); color.G = (unsigned char)*(jpegFile->Pixels+jpegFile->Stride*row+col*3+1); color.B = (unsigned char)*(jpegFile->Pixels+jpegFile->Stride*row+col*3+2); return color; } /*************************************** * pjJpegFile_SetPixel ***************************************/ void pjJpegFile_SetPixel( pjJpegFile* jpegFile, unsigned int row, unsigned int col, pjJpegColor clr ){ if( !(jpegFile->Height > row && row >= 0) ){ fprintf(stderr, "row must be in 0 to %d.\r\n", jpegFile->Height-1); return; } if( !( jpegFile->Width >col && col >= 0 ) ){ fprintf(stderr, "col must be in 0 to %d.\r\n", jpegFile->Width-1); return; } *(jpegFile->Pixels+jpegFile->Stride*row+col*3) = clr.R; *(jpegFile->Pixels+jpegFile->Stride*row+col*3+1) = clr.G; *(jpegFile->Pixels+jpegFile->Stride*row+col*3+2) = clr.B; } /*************************************** * pjJpegFile_SetRegionColor ***************************************/ void pjJpegFile_SetRegionColor( pjJpegFile* jpegFile, unsigned int x, unsigned int y, unsigned int width, unsigned int height, pjJpegColor clr ){ int i = 0, j = 0; for( i = x; i < (x + width); i++ ){ for( j = y; j < (y + height); j++ ){ pjJpegFile_SetPixel( jpegFile, j, i, clr ); } } } /*************************************** * pjJpegFile_New ***************************************/ pjJpegFile* pjJpegFile_New(){ return (pjJpegFile*)malloc( sizeof(pjJpegFile) ); } /*************************************** * pjJpegFile_Delete ***************************************/ void pjJpegFile_Delete( pjJpegFile* jpegFile ){ if( jpegFile != 0 ){ if( jpegFile->Pixels != NULL ){ free(jpegFile->Pixels); jpegFile->Pixels = 0; } free( jpegFile ); jpegFile = 0; } }
true
8dd810b0589423ac431505520d83346ef714c6d8
C
AlexEzzeddine/Crypto
/src/base64/base64.c
UTF-8
3,287
2.609375
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* base64.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: aezzeddi <aezzeddi@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/01/29 19:47:52 by aezzeddi #+# #+# */ /* Updated: 2018/01/30 00:19:44 by aezzeddi ### ########.fr */ /* */ /* ************************************************************************** */ #include "base64.h" t_base64_options g_base64_options = {ENCODE, 0, 1}; t_uchar *base64_encode(t_uchar *message, int *len) { int i; t_uchar *cipher; i = 0; cipher = (t_uchar *)ft_strnew(4 * (*len / 3 + ((*len % 3) ? 1 : 0))); while (i < *len / 3) { pad_0(cipher + i * 4, message + i * 3); i++; } if (*len % 3 == 2) pad_1(cipher + i * 4, message + i * 3); else if (*len % 3 == 1) pad_2(cipher + i * 4, message + i * 3); if (*len) { cipher = (t_uchar *)ft_strfjoin((char *)cipher, "\n"); *len = 4 * (*len / 3 + ((*len % 3) ? 1 : 0)) + 1; } cipher = add_newlines(cipher, len); return (cipher); } t_uchar *base64_decode(t_uchar *cipher, int *len) { int i; t_uchar *message; i = 0; *len = base64_check_padding(cipher, *len); message = (t_uchar *)ft_strnew(3 * (*len / 4) + (*len % 4 - 1)); while (i < *len / 4) { message[3 * i + 0] = (base64_revchar(*(cipher + i * 4)) << 2) + ((base64_revchar(*(cipher + i * 4 + 1)) & 0x30) >> 4); message[3 * i + 1] = (base64_revchar(*(cipher + i * 4 + 1)) << 4) + (base64_revchar(*(cipher + i * 4 + 2)) >> 2); message[3 * i + 2] = (base64_revchar(*(cipher + i * 4 + 2)) << 6) + base64_revchar(*(cipher + i * 4 + 3)); i++; } if (*len % 4 > 1) message[3 * i + 0] = (base64_revchar(*(cipher + i * 4)) << 2) + ((base64_revchar(*(cipher + i * 4 + 1)) & 0x30) >> 4); if (*len % 4 == 3) message[3 * i + 1] = (base64_revchar(*(cipher + i * 4 + 1)) << 4) + (base64_revchar(*(cipher + i * 4 + 2)) >> 2); *len = 3 * (*len / 4) + (*len % 4 - 1); return (message); } static int base64_read_all(int fd, t_uchar **output) { char *result; char *old; char *buf; int n; int len; buf = ft_strnew(8); result = NULL; len = 0; while ((n = read(fd, buf, 8)) > 0) { old = result; result = ft_strnew(len + n + 1); ft_memcpy(result, old, len); ft_memcpy(result + len, buf, n); len += n; free(old); ft_bzero(buf, 8); } *output = (t_uchar *)result; return (len); } void base64(char **args, int size) { t_uchar *input; t_uchar *output; int len; base64_parse_args(args, size); len = base64_read_all(g_base64_options.fd_in, &input); close(g_base64_options.fd_in); if (g_base64_options.mode == ENCODE) output = base64_encode(input, &len); else output = base64_decode(input, &len); free(input); write(g_base64_options.fd_out, output, len); free(output); close(g_base64_options.fd_out); }
true
cde1357d0cc9e56b8f70a296c9b9ba81c0cb77f9
C
zwshen/mudos-game-ds
/ds/cmds/std/shoot.c
BIG5
1,486
2.6875
3
[]
no_license
// use.c #include <ansi.h> #include <skill.h> inherit SSERVER; int main(object me, string arg) { object target,weapon,arrow,creater; seteuid(getuid()); if( !weapon=me->query_temp("weapon") ) return 0; if( weapon->query("skill_type")=="bow") { if( !arrow=present("arrow", me ) ) return notify_fail(" ASb, gC\n"); } else { if(!weapon->query("can_shoot")) return notify_fail("ثeϥΪZLkϥήgOC\n"); if(weapon->query_temp("loaded") < 1 ) return notify_fail("ZSu, Aݭn˶(reload)~ogC\n"); } if( me->is_busy() || me->is_block() ) return notify_fail("( AW@Ӱʧ@٨SMgC)\n"); if(!arg) target = offensive_target(me); else target = present(arg, environment(me)); if( !target ) return notify_fail("[shoot] error: 䤣ؼСC\n"); if(!userp(me)) { if(creater=me->query("creater")) { if(!creater->can_fight(target)) return creater->can_fight(target); } } if(!me->can_fight(target)) return me->can_fight(target); if(weapon->do_shoot(me,target)) //ZiH]pSʧ@Mԭz { return 1; } return notify_fail("[shoot] error: ZL]w(do_shoot)C\n"); } int help (object me) { write(@HELP O榡Rshoot [<H>] ϥήgZ, Owg˳ƪZ, pGOj(Gun), hnu. HELP ); return 1; }
true
53d3fc94135305df3f67ac5cd077d5c4de26d349
C
wangtaooo/Linux
/algo/02_data_struct/03_集合/source/set.h
UTF-8
1,171
3.03125
3
[ "Apache-2.0" ]
permissive
#ifndef __SET_H__ #define __SET_H__ typedef List Set; void set_init(Set *set, int (*match)(const void *key1, const void *key2), void (*destory)(void *data)); #define set_destory list_destory /** * 插入操作成功返回0;如果插入的成员在集合中已经存在返回1;否则返回-1 * 复杂度O(n) * */ int set_insert(Set *set, const void *data); /** * 如果移除操作成功返回0,否则返回-1 * */ int set_remove(Set *set, void **data); /** * 成功返回0,否则返回-1 * 建立一个集合,其结果为set1和set2所指定结合的并集.返回后,setu就代表这个并集 * */ int set_union(Set *setu, const Set *set1, const Set *set2); /** * 交集计算成功返回0,否则返回-1 * 复杂度O(mn) * */ int set_intersection(Set *seti, const Set *set1, const Set *set2); /** * 计算差集成功返回0,否则返回-1 * */ int set_difference(Set *setd, const Set *set1, const Set *set2); int set_is_member(const Set *set, const void *data); int set_is_subset(const Set *set1, const Set *set2); int set_is_equal(const Set *set1, const Set *set2); #define set_size(set) ((set)->size) #endif /* __SET_H__ */
true
c63dd7d61cf542df26c8d077bd5197d6df85bda2
C
NightShop/cs50
/2019-x-crack/crack.c
UTF-8
2,545
2.75
3
[]
no_license
#define _XOPEN_SOURCE #include <cs50.h> #include <stdio.h> #include <crypt.h> #include <string.h> #include <unistd.h> int main(int argc, string argv[]) { if (argc == 2) { string salt1 = argv[1]; char salt[3]; strncpy(salt, salt1, 2); salt[2] ='\0'; char input[6]; int zg = 130; //50l0NWdjxDj/w //// ABCDE 509fm.6m30.ok for (int i = 65; i < zg; i++) { input[0] = (char) i; printf("%s\n", input); if(strcmp(crypt(input, salt), argv[1]) == 0) { printf("PASS: %s\n", input); return 0; } for (int j = 65; j < zg; j++) { input[1] = (char) j; printf("%s\n", input); if(strcmp(crypt(input, salt), argv[1]) == 0) { printf("PASS: %s\n", input); return 0; } for (int k = 65; k < zg; k++) { input[2] = (char) k; printf("%s\n", input); if(strcmp(crypt(input, salt), argv[1]) == 0) { printf("PASS: %s\n", input); return 0; } for (int f = 65; f < zg; f++) { input[3] = (char) k; printf("%s\n", input); if(strcmp(crypt(input, salt), argv[1]) == 0) { printf("PASS: %s\n", input); return 0; } for (int l = 65; l < zg; l++) { input[4] = (char) l; printf("%s\n", input); if(strcmp(crypt(input, salt), argv[1]) == 0) { printf("PASS: %s\n", input); return 0; } printf("%s\n", input); } } } } } } else { printf("Wrong input\n"); return 1; } }
true
5074298966fece8cbf4d717c4fcd086295093fe7
C
alcap-org/AlcapDAQ
/www/html/online/trend_plots/runsummary/tutorials/principal.C
UTF-8
2,889
3.171875
3
[]
no_license
#include "TPrincipal.h" #include "iomanip.h" void principal(Int_t n=10, Int_t m=10000) { // // Principal Components Analysis (PCA) example // // Example of using TPrincipal as a stand alone class. // // We create n-dimensional data points, where c = trunc(n / 5) + 1 // are correlated with the rest n - c randomly distributed variables. // // Here's the plot of the eigenvalues Begin_Html // <IMG SRC="gif/principal_eigen.gif"> // End_Html Int_t c = n / 5 + 1; cout << "*************************************************" << endl; cout << "* Principal Component Analysis *" << endl; cout << "* *" << endl; cout << "* Number of variables: " << setw(4) << n << " *" << endl; cout << "* Number of data points: " << setw(8) << m << " *" << endl; cout << "* Number of dependent variables: " << setw(4) << c << " *" << endl; cout << "* *" << endl; cout << "*************************************************" << endl; // Initilase the TPrincipal object. Use the empty string for the // final argument, if you don't wan't the covariance // matrix. Normalising the covariance matrix is a good idea if your // variables have different orders of magnitude. TPrincipal* principal = new TPrincipal(n,"N"); // Use a pseudo-random number generator TRandom* random = new TRandom; // Make the m data-points // Make a variable to hold our data // Allocate memory for the data point Double_t* data = new Double_t[n]; for (Int_t i = 0; i < m; i++) { // First we create the un-correlated, random variables, according // to one of three distributions for (Int_t j = 0; j < n - c; j++) { if (j % 3 == 0) data[j] = random->Gaus(5,1); else if (j % 3 == 1) data[j] = random->Poisson(8); else data[j] = random->Exp(2); } // Then we create the correlated variables for (Int_t j = 0 ; j < c; j++) { data[n - c + j] = 0; for (Int_t k = 0; k < n - c - j; k++) data[n - c + j] += data[k]; } // Finally we're ready to add this datapoint to the PCA principal->AddRow(data); } // We delete the data after use, since TPrincipal got it by now. delete [] data; // Do the actual analysis principal->MakePrincipals(); // Print out the result on principal->Print(); // Test the PCA principal->Test(); // Make some histograms of the orginal, principal, residue, etc data principal->MakeHistograms(); // Make two functions to map between feature and pattern space principal->MakeCode(); // Start a browser, so that we may browse the histograms generated // above TBrowser* b = new TBrowser("principalBrowser", principal); }
true
6863a679378bd419d724d63e138dfdb7d40d080a
C
iakoviid/Embeeded-Systems
/extra/periodic_thread/sampl_cor.c
UTF-8
3,322
3.125
3
[]
no_license
#include <sys/time.h> #include <signal.h> #include <unistd.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <math.h> // calculates addition of positive arguments void add(struct timeval * a, long b) { a->tv_usec = a->tv_usec + b; if (a->tv_usec >= 1000000) { a->tv_sec++; a->tv_usec -= 1000000; } } int set_timer(long period,sigset_t *sigset){ printf("Setting timer\n"); struct itimerval t; int offs=1; t.it_value.tv_sec = offs / 1000000; t.it_value.tv_usec = offs % 1000000; t.it_interval.tv_sec = period / 1000000; t.it_interval.tv_usec = period % 1000000; /* Clear the signal set and include the SIGALRM signal */ sigemptyset(sigset); sigaddset(sigset, SIGALRM); sigprocmask(SIG_BLOCK, sigset, NULL); /* Creates a periodic timer */ return setitimer(ITIMER_REAL, &t, NULL); } int main(int argc, char **argv) { if(argc<3){ printf("Usage sampl t (total_time) dt (time_interval) \n"); return 1; } float t,dt; t = atof(argv[1]); // Total time dt = atof(argv[2]); // period int N =(int)t/dt; //number of samples long period= (long) (dt*1000000); // period in ms float* result=(float *)malloc(sizeof(float)*N ); //array of results printf("Total time t=%f and time interval dt=%f\n",t,dt ); printf("Number of samples %d\n",N ); struct timeval periodic, now; // time values of the current time and the periodic i*dt static sigset_t sigset; //For SIGALRM signal used int status =set_timer(period,&sigset); if(status<0){ printf("Error setting timer\n"); return -1;} int i=0; int dummy; int set=0; float dif ; int number=0; float max=0; float min=dt*1000+1000; float mean=0; float cyclic[64]; for(i=0;i<64; i++){ cyclic[i]=0; } i=0; while(i<N){ /*Wait for signal*/ sigwait(&sigset,&dummy ); /* Do work*/ gettimeofday(&now, NULL); if(i==0 ){ gettimeofday(&periodic, NULL); }else{ add(&periodic,period);} dif = (now.tv_sec - periodic.tv_sec) * 1000.0; // sec to ms dif += (now.tv_usec - periodic.tv_usec) / 1000.0; // us to ms result[i]=dif; mean=(mean*64-cyclic[i%64]+dif)/64; cyclic[i%64]=dif; printf("%f\n",dif ); if(dif<min){ min=dif; } if(dif>max){ max=dif; } i++; if(fabs(dif)>0.1){ number++; } if(i%500==0){ number=0; } if((fabs(mean)>0.1 && number>10 ) || fabs(dif) >10){ set ++; /*Restart Timer*/ struct itimerval t; struct timeval temp; gettimeofday(&now, NULL); temp.tv_sec=periodic.tv_sec; temp.tv_usec=periodic.tv_usec; add(&temp, period); float difnext = (temp.tv_sec - now.tv_sec) * 1000.0; // sec to ms difnext += (temp.tv_usec - now.tv_usec) / 1000.0; // us to ms long offs=(difnext*1000); t.it_value.tv_sec = offs / 1000000; t.it_value.tv_usec = offs % 1000000; t.it_interval.tv_sec = period / 1000000; t.it_interval.tv_usec = period % 1000000; /* Creates a periodic timer */ status =setitimer(ITIMER_REAL, &t, NULL); if(status<0){ printf("Error setting timer\n"); return -1;} mean=0; for(int j=0;j<64; j++){ cyclic[j]=0; } number=0; } } printf("min %f \n",min); printf("max %f \n",max); printf("Number of timer resets %d",set); return 0; }
true
c4d243b503b9db0fdf8e734f4a76057502a0f1d0
C
Wil12Fred/InteraccionHumanoComputador
/Vector_tools.h
UTF-8
4,652
3
3
[]
no_license
//#include <stdio.h> //#include "Vector_tools.h" #define TRUE 1 #define FALSE 0 #define VECTOR_EPSILON 0.00001f #define DISTANCE_EPSILON 1e-08f #define ANGLE_EPSILON 0.00872665f #define MOD(A,B,C) (float) sqrt( A*A + B*B + C*C ) #define PI_VALUE 3.14159265359f #define DEGREE_TO_RAD 0.0174533f #define RAD_TO_DEGREE 57.2958f void VectorNormalize(int *ierr, float *vx, float *vy, float *vz) { float A, B, C; float modf; double mod; if (*ierr) return; A = *vx; B = *vy; C = *vz; mod = A * A + B * B + C*C; if (mod > VECTOR_EPSILON) { modf = (float) (1. / sqrt(mod)); *vx = A * modf; *vy = B * modf; *vz = C * modf; } else { *vx = 0.0; *vy = 0.0; *vz = 1.0; *ierr = TRUE; } } void UnitVectorPP(int *ierr, float *wx, float *wy, float *wz, float ax, float ay, float az, float bx, float by, float bz) { // given two points SET a unit vector that goes from A to B if (*ierr) return; *wx = bx - ax; *wy = by - ay; *wz = bz - az; VectorNormalize(ierr, wx, wy, wz); } void UnitVectorVV(int *ierr, float *wx, float *wy, float *wz, float ux, float uy, float uz, float vx, float vy, float vz) { // Vector product : w = u ^ v if (*ierr) return; *wx = uy * vz - uz * vy; *wy = uz * vx - ux * vz; *wz = ux * vy - uy * vx; VectorNormalize(ierr, wx, wy, wz); } void VectorRotY(float *vIn, float inc) { float alpha; float modZX; float mod; // __________________> X // |* // | * // | * // | * // | * // | * // | * // | alpha * // | * // v // Z mod = MOD(vIn[0], vIn[1], vIn[2]); if (mod < VECTOR_EPSILON) return; vIn[0] = vIn[0] / mod; vIn[1] = vIn[1] / mod; vIn[2] = vIn[2] / mod; // if vector is too parallel to the "y" axis do nothing if (fabs(vIn[1]) > sin(PI_VALUE / 2.0 - ANGLE_EPSILON)) return; modZX = (float) sqrt(vIn[0] * vIn[0] + vIn[2] * vIn[2]); alpha = (float) acos(vIn[2] / modZX); if (vIn[0] < 0.0f) alpha = 2.0f * PI_VALUE - alpha; alpha += inc; vIn[0] = (float) sin(alpha) * modZX; vIn[2] = (float) cos(alpha) * modZX; vIn[0] = vIn[0] * mod; vIn[1] = vIn[1] * mod; vIn[2] = vIn[2] * mod; } void VectorRotXZ(float *vIn, float inc, int flagStop) { float alpha, beta; float mod; float maxAngle = 90.0f * DEGREE_TO_RAD - ANGLE_EPSILON; // Plane that contains the vector and the "y" axis // // Y // ^ // | // | // | * // | * // | * // | * // | * // | * // | * // | * beta // |* // ------------------> X-Z // mod = MOD(vIn[0], vIn[1], vIn[2]); if (mod < VECTOR_EPSILON) return; vIn[0] = vIn[0] / mod; vIn[1] = vIn[1] / mod; vIn[2] = vIn[2] / mod; // if vector is too parallel to the "y" axis do nothing if (fabs(vIn[1]) > sin(maxAngle)) return; // 1 Compute alpha & beta alpha = (float) acos(vIn[2] / sqrt(vIn[0] * vIn[0] + vIn[2] * vIn[2])); if (vIn[0] < 0.0f) alpha = 2.0f * PI_VALUE - alpha; // hypotenuse must be always 1.0 (because v is a unit vector) // first we measure beta from X-Z up to our vector // the result will be among -90 and +90 beta = (float) asin(vIn[1]); // 2 ConstantIncrement beta (two possibilities) if (flagStop) { // when beta goes further than pi/2 or -pi/2 => stop avoiding a vertical position beta += inc; if (beta > maxAngle) beta = maxAngle; else if (beta < -maxAngle) beta = -maxAngle; } else { // to keep a constant rotation direction inc must be a positive value if (alpha > PI_VALUE) beta += inc; else beta -= inc; } // 3 Compute new vector vIn[0] = (float) cos(beta) * (float) sin(alpha); vIn[1] = (float) sin(beta); vIn[2] = (float) cos(beta) * (float) cos(alpha); vIn[0] = vIn[0] * mod; vIn[1] = vIn[1] * mod; vIn[2] = vIn[2] * mod; }
true
3aa3b6b8fe3855e325fba875ba61db4e5b72ba3c
C
luccalm/Algoritmos-SENAC
/Lista 8/ex01.c
UTF-8
282
3.859375
4
[]
no_license
/*1. Escreva uma função que imprime todos os inteiros de 1 a 1000. Escreva também um programa que chama essa função.*/ #include <stdio.h> void contador(); int main() { contador(); return 0; } void contador() { int i; for(i = 1; i <= 1000; i++) { printf("%d\n", i); } }
true
45897e768e375b9f572bed80f702abfca0077c7c
C
andreaslindner/Balanced-arm-project
/inc/motor.h
UTF-8
1,594
2.90625
3
[]
no_license
#ifndef MOTOR_H_ #define MOTOR_H_ /* ---MOTOR CONFIGURATION-- */ /** * @brief Init both motors * @param Nothing * @return Nothing * @note Nothing */ void Init_Motor(); /** * @brief Start both motors * @param Nothing * @return Nothing * @note Nothing */ void Motor_Start(); /** * @brief Stop both motors * @param Nothing * @return Nothing * @note Nothing */ void Motor_Stop(); /** * @brief Change the direction of both motors * @param forward : FORWARD (10) for set the direction as forward and BACKWARD (11) for backward * @return Nothing * @note Nothing */ void Motor_changeDir(uint8_t forward); /* ---MOTOR MOVEMENT--- */ /** * @brief Set both motors to move backward * @param perPower : percent (not really a percent because its on PERIOD_RESET_(R or L)MOTOR and not 100, PERIOD_RESET_(R or L)MOTOR = 5V) of power desired * @return Nothing * @note Nothing */ void Motor_Backward(uint16_t perPower); /** * @brief Set both motors to move forward * @param perPower : percent (not really a percent because its on PERIOD_RESET_(R or L)MOTOR and not 100, PERIOD_RESET_(R or L)MOTOR = 5V) of power desired * @return Nothing * @note Nothing */ void Motor_Forward(uint16_t perPower); /** * @brief Set the power of both motors * @param motorPower : percent (not really a percent because its on PERIOD_RESET_(R or L)MOTOR and not 100, PERIOD_RESET_(R or L)MOTOR = 5V) of power desired, can be negative * @return Nothing * @note negative value means go forward and a positive one go backward */ void Motor_setPower(float motorPower); #endif /* MOTOR_H_ */
true
59417d05e6ee4218ede8313ca60728a94602ee91
C
arkrwn/Praktikum
/Stuktur Data/Posttest/Roni Dwi Kurniawan_2015470052.c
UTF-8
1,371
3.640625
4
[ "MIT" ]
permissive
#include <stdio.h> #include <stdlib.h> #include <string.h> struct mahasiswa { char nim[20]; char namamhs[20]; struct mahasiswa *next; }; struct mahasiswa *ujung; int tambah_data_mhs() { struct mahasiswa *tampung; int j=0; char jawab[2]; printf(" Linked List LIFO(Last In First Out) "); printf("\n"); printf("_____________________________________"); while (1) { ujung = (struct mahasiswa*)malloc(sizeof(struct mahasiswa)); fflush(stdin); printf("\n"); printf(" Nama : "); scanf("%s", &ujung->namamhs); printf("\n"); printf(" NIM : "); scanf("%s", &ujung->nim); if (j == 0) { ujung->next = NULL; tampung = ujung; } else { tampung->next = tampung; tampung = ujung; } printf("\n"); printf("Tambah Data Mahasiswa (Y/T): "); scanf("%s", &jawab); if (strcmp(jawab, "Y") == 0) { j ++; continue; } else if (strcmp(jawab, "T") == 0) break; } return 0; } void tampil_data() { struct mahasiswa *tampil; printf("\n\n"); printf(" Data Mahasiswa Yang telah Diinputkan : \n"); printf("\n"); printf(" NIM | Nama\n\n"); tampil = ujung; while (tampil != NULL) { printf(" %s\t| %s\t", tampil->nim, tampil->namamhs); tampil = tampil->next; } } int main() { tambah_data_mhs(); tampil_data(); return 0; }
true
6256a7a280f1e34acc31552b25c698e6a69197fd
C
dhanalakshmigutha/Hackerrank-Solution
/Algorithms/Implementation/Birthday Chocolate.c
UTF-8
533
2.84375
3
[]
no_license
#include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <limits.h> #include <stdbool.h> int main() { int n,i,j,c=0,s; scanf("%d", &n); int *ar = malloc(sizeof(int) * n); for(i = 0; i < n; i++){ scanf("%d",&ar[i]); } int d; int m; scanf("%d %d", &d, &m); for(i=0;i<n;i++){ s=0; for(int l=0,j=i;l<m;j++,l++){ s=s+ar[j]; } if(s==d) c++; } printf("%d",c); return 0; }
true
27586e5b8c1ff7039ec339a37d67e285b363314f
C
anshi595/c_codes
/Test/Test_01/08_largestno_bitwise.c
UTF-8
256
3.5
4
[]
no_license
#include <stdio.h> #include <stdlib.h> int max(int x, int y) { return x^((x^y) & -(x < y)); } int main() { int a, b; printf("Enter the two no:\n"); scanf("%d \n %d", &a, &b); printf("The maximun of two no is : %d", max(a, b)); return 0; }
true
3a3f9f8d9736efb9bdf6e08878f33c679f68dc10
C
MrBrant/FanController
/Firmware/Initialize.c
UTF-8
1,575
2.59375
3
[]
no_license
/* * File: Initialize.c * Author: Craig * * Created on August 4, 2011, 10:03 PM */ #include "pic.h" void initialize(); void initialize() { //Programming /* MCLREN;//Enables the MCLR pin to reset the PIC MCLRE = 1;//MCLR set as MCLR //I need access to CONFIG as a register for so many reasons! See pg 54 for where to look (hint check out the grey box at top right) */ //GPIO TRIS0 = 1;//ICSP DAT TRIS1 = 1;//ICSP CLK TRIS2 = 1;//Temperature reading 1 (A2D) - AN2 TRIS3 = 1;//MCLR TRIS4 = 1;//Temperature reading 2 (A2D) - AN3 TRIS5 = 0;//Controlls a relay or LED //WDT Setup // WDTE = 1;//Enable the WDT PSA = 1;//Prescaler is used for WDT PS0 = 1; PS1 = 1; PS2 = 1;//Prescaler set for 1:128, with no prescaler it times out in 18 ms, so we time out at 2.304 Seconds now //Interupts GIE = 0;//Disables all interupts PEIE = 0;//Disables all peripheral interupts T0IE = 0;//Disables the TMR0 interupt T0IF = 0;//TMR0 register did not overflow //A2D ADFM = 1;//Right justified VCFG = 0;//VDD reference voltage CHS1 = 1;//Always set, selects A2D channel (limits to AN2 or AN3) CHS0 = 0;//0 = AN2, 1 = AN3 GODONE = 0;//A/D conversion completed/not in progress ADON = 1;//A/D converter module is operating ANS0 = 0; ANS1 = 0;//Pins setup as digital outputs, or somethingelse, who knows... ANS2 = 1; ANS3 = 1;//Pins setup as analog inputs ADCS0 = 1; ADCS1 = 1; ADCS2 = 1;//Conversion clock is dedicated internal 500 kHz clock return; }
true
796c0c4bfac1a5aa60ad777fd28a8031d5259d5e
C
bhargavi-muppirisetti/Stepin-Unit-Converter-and-Calculator
/implementation/main.c
UTF-8
8,709
3.96875
4
[]
no_license
#include "Stepin-Unit-Converter-and-Calculator.h" #include<stdio.h> int main() { int choice; double input1,input2; double result; int res1; int in1,out; double triginput,trigoutput; int a=0; int b=0; int c=0; int d=0; int z=0; int n,ram=0; int year; printf("\nPlease select the required operation to be performed \n"); printf("1.Addition\n"); printf("2.Subtraction\n"); printf("3.Multiplication\n"); printf("4.Division\n"); printf("5.Square Root\n"); printf("6.Modulus\n"); printf("7.Factorial\n"); printf("8.Temperature\n"); printf("9.Power\n"); printf("10.log value\n"); printf("11.log10 value\n"); printf("12.Exponential\n"); printf("13.To Find a number is even or odd\n"); printf("14.Enter the year to know leap year or not \n"); printf("15.Enter an integer to check whether it is prime or not \n"); printf("16.Length Conversion\n"); printf("\nEnter you choice: "); scanf("%d",&choice); switch(choice) { case 1: printf("\nEnter two number to add"); scanf("%lf %lf",&input1,&input2); result = add(input1,input2); printf("%lf",result); break; case 2: printf("\nEnter two number to subtract"); scanf("%lf %lf",&input1,&input2); result = subtract(input1,input2); printf("%lf",result); break; case 3: printf("\nEnter two number to multiply"); scanf("%lf %lf",&input1,&input2); result = multiply(input1,input2); printf("%lf",result); break; case 4: printf("\nEnter two number to Divide"); scanf("%lf %lf",&input1,&input2); result = divide(input1,input2); printf("%lf",result); break; case 5: printf("\nEnter a number for squareroot"); scanf("%lf",&triginput); trigoutput =squareroot(triginput); printf("%lf",trigoutput); break; case 6: printf("\nEnter the operators to perform modulus operation"); scanf("%d %d",a,b); result =modulo(a,b); printf("%d",result); break; case 7: printf("\nEnter a number for factorial"); scanf("%d",&in1); out = fact(in1); printf("%d",out); break; case 8: temperature(); break; case 9: printf("Enter the base number: "); scanf("%lf", &input1); printf("Enter the power raised: "); scanf("%lf",&input2); result=power(input1,input2); printf("%d\n",result); break; case 10: printf("Enter the number to find log value\n"); scanf("%lf",&input1); result=logvalue(input1); printf("%lf",result); break; case 11: printf("Enter the number to find log10 value\n"); scanf("%lf",&input1); result=log10value(input1); printf("%lf",result); break; case 12: printf("Enter the number to find Exponential value\n"); scanf("%lf",&input1); result=exp(input1); printf("%lf",result); break; case 13: printf("Enter the number to find even or odd\n"); scanf("%d",&a); c=even_or_odd(a); if(c==0) { printf("Number is Even"); break; } else { printf("Number is Odd"); break; } case 14: printf("Enter any year : "); scanf("%d", &year); if(leap(year)) { printf("\n%d is leap year",year); break; } else { printf("\n%d is not leap year",year); break; } case 15: printf("Enter an integer to check whether it is prime or not.\n"); scanf("%d",&n); ram = prime(n); if (ram == 1) { printf("%d is prime.\n", n); break; } else { printf("%d is not prime.\n", n); break; } case 16: length(); break; default : printf("Please choose valid choice to perform respective operation"); } } void temperature() { int choice; double result,input1; printf("choose the respective operation for different temperature conversions\n"); printf("1.fahrenheit to celsius\n"); printf("2.celsius to fahrenheit\n"); printf("3.fahrenheit to kelvin\n"); printf("4.kelvin to fahrenheit\n"); printf("5.celsius to kelvin\n"); printf("6.kelvin to celsius\n"); printf("Enter the choice\n"); scanf("%d",&choice); switch(choice) { case 1: printf("\nEnter temp to convert fahrenheit into celsius"); scanf("%lf",&input1); result=fahrenheit_to_celsius(input1); printf("%lf",result); break; case 2: printf("\nEnter temp to convert celsius into fahrenheit"); scanf("%lf",&input1); result=celsius_to_fahrenheit(input1); printf("%lf",result); break; case 3: printf("\nEnter temp to convert fahrenheit into kelvin"); scanf("%lf",&input1); result=fahrenheit_to_kelvin(input1); printf("%lf",result); break; case 4: printf("\nEnter temp to convert kelvin into fahrenheit"); scanf("%lf",&input1); result=kelvin_to_fahrenheit(input1); printf("%lf",result); break; case 5: printf("\nEnter temp to convert celsius into kelvin"); scanf("%lf",&input1); result=celsius_to_kelvin(input1); printf("%lf",result); break; case 6: printf("\nEnter temp to convert kelvin into celsius"); scanf("%lf",&input1); result=kelvin_to_celsius(input1); printf("%lf",result); break; } return 0; } void length() { int choice; double result,input1; printf("choose the respective operation for different length conversions\n"); printf("1.kilometer to miles\n"); printf("2.miles to kilometer\n"); printf("3.kilometer to foot\n"); printf("4.foot to kilometer\n"); printf("5.miles to inches\n"); printf("6.inches to miles\n"); printf("Enter the choice\n"); scanf("%d",&choice); switch(choice) { case 1: printf("\nEnter length to convert kilometer to miles"); scanf("%lf",&input1); result=kilometer_to_miles(input1); printf("%lf",result); break; case 2: printf("\nEnter length to convert miles to kilometer"); scanf("%lf",&input1); result=miles_to_kilometer(input1); printf("%lf",result); break; case 3: printf("\nEnter length to convert kilometer to foot"); scanf("%lf",&input1); result=kilometer_to_foot(input1); printf("%lf",result); break; case 4: printf("\nEnter length to convert foot to kilometer"); scanf("%lf",&input1); result=foot_to_kilometer(input1); printf("%lf",result); break; case 5: printf("\nEnter length to convert miles to inches"); scanf("%lf",&input1); result=miles_to_inches(input1); printf("%lf",result); break; case 6: printf("\nEnter length to convert inches to miles"); scanf("%lf",&input1); result=inches_to_miles(input1); printf("%lf",result); break; } return 0; }
true
fa6edcdab8c3092602e7d513ab4e9bbd337394f1
C
astrotycoon/Cplusplus
/6_3/6_3.c
UTF-8
239
3.953125
4
[]
no_license
#include <stdio.h> int isBigger(int a, int b) { int x1, x2; x1 = a; x2 = b; if (x1 > x2) return 1; else return -1; } int main(void) { int a = 5; int b = 10; printf("The bigger values is %d\n", isBigger(a,b)); return 0; }
true
e61bcbe20c813f4df50508364c32a496bbaafe08
C
ayush-kadakia/CS-211
/pa1/seventh/seventh.c
UTF-8
227
3.171875
3
[]
no_license
#include<stdio.h> #include<stdlib.h> #include<string.h> int main(int argc, char** argv){ int i; for(i = 1; i < argc; i++){ int len = strlen(argv[i]); printf("%c", argv[i][len-1]); } printf("\n"); return 0; }
true
0e74dc68553dd550f418d90718f8208c987eb7d8
C
ramiterdos1/C-progs
/contest programs/PE57.c
UTF-8
2,079
3.375
3
[]
no_license
#include <stdlib.h> #include <time.h> #include <stdio.h> #include <math.h> struct frac{ long long num;long long denom; }; typedef struct frac * FP; //fraction-ponter FP get_fraction() { FP f=(FP)malloc(sizeof(struct frac)); return f; } long long gcd(long long a,long long b) { if(a<b)return gcd(b,a); else { if(b==0)return a; else return gcd(b,a%b); } } void reduce_to_lowest_terms(FP f) { long long hcf=gcd(f->num,f->denom); f->num/=hcf; f->denom/=hcf; } FP add( FP f1, FP f2) { FP f=get_fraction(); int g=gcd(f1->denom,f2->denom); int l=((f1->denom)/g)*f2->denom; f->denom=l; f->num=f1->num*(l/f1->denom) + f2->num*(l/f2->denom); reduce_to_lowest_terms(f); return f; } void inv ( FP f) { long long tmp=f->num; f->num=f->denom; f->denom=tmp; } int chk(FP f) { long long n=f->num,i=0; while(n){n/=10;i++;} n=f->denom; while(n){n/=10;i--;} return i; } void copy(FP c1, FP c2) //c2 's values get copied to c1 { c1->num=c2->num; c1->denom=c2->denom; } int main() { //starting clock_t begin=clock(),end;time_t b=time(&b),e; //middle-actual code FP f=get_fraction(); int i=1,count=0; FP strt=get_fraction(),two=get_fraction(),one=get_fraction(),tmp=get_fraction(); two->num=2;one->num=1;two->denom=one->denom=1; copy(strt,two); while(i<=1000) { if(i>1) { copy(strt,tmp); //inv(strt); //strt=add(strt,two); strt->num+=((strt->denom)<<1); reduce_to_lowest_terms(strt); } inv(strt); copy(tmp,strt); //printf("b4add1.. %ld--%ld\n",strt->num,strt->denom); strt->num+=strt->denom; //printf("before:gcd--%ld:%ld\n",strt->num,strt->denom); reduce_to_lowest_terms(strt); if(chk(strt)){ count++; printf("%d, %d--> %lld:%lld\n",count,i,strt->num,strt->denom); } i++; } //ending end=clock();e=time(&e); printf(" Processor Time taken is %f.\n",(double)((end-begin)/(double)CLOCKS_PER_SEC)); printf(" Time taken is %f.\n",difftime(e,b)); return 0; }
true
c0fc8eea2f8f202c203db2fed7b6675278d47ffd
C
HedbergMartin/MatchC
/src/datatypes/vector.c
UTF-8
3,070
3.53125
4
[ "MIT" ]
permissive
#include "vector.h" //#include "time.h" #include <memory.h> #include <stdio.h> #include <errno.h> /* * Implementation of C++ like vector in C. * * Author: Martin Hedberg * * Version information: * 2021-05-13: v1.1, added back poping. * 2021-04-21: v1.0, first implementation. */ struct vector { void** data; size_t capacity; size_t default_capacity; size_t size; }; vector *vector_init() { vector* v = calloc(1, sizeof(vector)); if (!v) { perror("Vector"); exit(1); } v->default_capacity = 10; return v; } void vector_reserve(vector* v, size_t capacity) { if (!v) { return; //Error } v->default_capacity = capacity; } /*double timePushBack = 0; clock_t pushBackStart ; clock_t pushBackEnd;*/ void vector_push_back(vector* v, void* value) { //pushBackStart = clock(); if (!v) { return; //Error? } if (v->capacity <= v->size) { if (v->capacity == 0) { v->capacity = v->default_capacity; v->data = malloc(v->capacity * sizeof(void*)); } else { void** newDataLoc = malloc(v->capacity * 3 * sizeof(void*)); memcpy(newDataLoc, v->data, v->capacity * sizeof(void*)); free(v->data); v->data = newDataLoc; v->capacity *= 2; } } v->data[v->size] = value; v->size++; /*pushBackEnd = clock(); timePushBack += (double)(pushBackEnd - pushBackStart) / CLOCKS_PER_SEC;*/ } /*double timePopBack = 0; clock_t popBackStart; clock_t popBackEnd;*/ void vector_pop_back(vector* v, free_func_callback free_func) { //popBackStart = clock(); if (!v) { return; } if (v->size > 0) { v->size--; if (free_func) { free_func(v->data[v->size]); } } /*popBackEnd = clock(); timePopBack += (double)(popBackEnd - popBackStart) / CLOCKS_PER_SEC;*/ } void* vector_at(vector* v, size_t index) { if (!v) { return NULL; //Error? } if (v->size <= index) { return NULL; //Out of bounds } return v->data[index]; } void** vector_data(vector* v) { if (!v) { return NULL; //Error? } return v->data; } void vector_set(vector* v, size_t index, void* value) { if (!v) { return; //Error? } if (v->size <= index) { return; //Out of bounds } v->data[index] = value; } size_t vector_size(vector* v) { if (!v) { return 0; //Error } return v->size; } size_t vector_capacity(vector* v) { if (!v) { return 0; //Error } return v->capacity; } void vector_clear(vector* v, free_func_callback free_func) { if (free_func) { for (int i = 0; i < v->size; i++) { free_func(v->data[i]); } } v->size = 0; } void** vector_copy(vector* v) { if (!v) { return NULL; } if (v->size == 0) { return NULL; } void** copy = malloc(v->size * sizeof(void*)); memcpy(copy, v->data, v->size * sizeof(void*)); return copy; } /*void vector_print_push_pop() { fprintf(stderr, "Time Pushback: %f, Time popback: %f\n", timePushBack, timePopBack); }*/ void vector_free(vector* v, free_func_callback free_func) { if (!v) { return; //Error } if (free_func) { for (int i = 0; i < v->size; i++) { free_func(v->data[i]); } } if (v->data != NULL) { free(v->data); } free(v); }
true
14dd1b91e164d5de87f0d4b32cede7a07e238c6a
C
york-rwsa/EMBR
/Assessment2/Stages/Stage2/lcd.h
UTF-8
815
2.828125
3
[]
no_license
#include "lpc_types.h" #include "lcd_commands.h" #define LCD_ADDRESS 0x3b #define DDRAM_SIZE 80 void lcd_init(); /** * Sends data to the lcd address: LCD_ADDRESS in lcd.h * @param data array of 8 bit ints to send * @param length lenth of the array. use LEN() macro from utils */ void lcd_send_data(uint8_t *data, uint32_t length); /** * sends an ascii string to the 2x16 lcd screen. * for non-shift mode line 1 is addr 0x00 to 0x0F, line 2 is 0x40 to 0x4F * NB the max length is DDRAM is 80 registers * @param string \0 terminated string (array of chars or uint8) * @param start_addr starting address for the DDRAM - 0x40 is the start second line */ void lcd_send_string(char *string, uint8_t start_addr); /** * Clears the lcd display by overwriting each cell with ' ' */ void lcd_clear_display();
true
47e6ec1f1c82bbe4536f794acad4c1968b9d664e
C
venetya/cs_assignments
/exercises/address.c
UTF-8
170
3.375
3
[]
no_license
#include <stdio.h> int main(){ int x = 10; int y = 15; printf("The address of x: %p\n", &x); printf("The address of y: %p\n", &y); return 0; }
true
27c1af34cd063d9f299bb4c90ac5dd1942efedf8
C
Kakisuke1005/Image_Information_Processing
/2nd/ex1.c
UTF-8
822
3.515625
4
[]
no_license
#include<stdio.h> #include<stdlib.h> #define MAX_SIZE 100 int main() { FILE *fp1,*fp2; int c1,c2; char file_name[2][MAX_SIZE]; printf("比較するファイルを入力して下さい: "); scanf("%s %s",file_name[0],file_name[1]); fp1=fopen(file_name[0],"rb"); if(fp1==NULL){ printf("Cannot open the %s!!\n",file_name[0]); exit(1); } fp2=fopen(file_name[1],"rb"); if(fp2==NULL){ printf("Cannot open the %s!!\n",file_name[1]); exit(1); } c1=fgetc(fp1); c2=fgetc(fp2); while((c1!=EOF)||(c2!=EOF)){ if(c1!=c2){ printf("二つのファイルの内容は異なっています\n"); exit(0); }else{ c1=fgetc(fp1); c2=fgetc(fp2); } } printf("二つのファイルの内容は同じです\n"); fclose(fp1); fclose(fp2); return 0; }
true
3898093fb9e34947a6e6c89897ff3763bf87cc76
C
Nhoutain/benchmark
/fork/fork.c
UTF-8
1,107
2.640625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <unistd.h> // mesure copy-on-write, also with pthread #include "benchmark.h" #define N 42 int main (int argc, char *argv[]) { timer *t = timer_alloc(); recorder *parent_rec = recorder_alloc("parent.csv"); recorder *child_rec = recorder_alloc("child.csv"); pid_t pid; int status, i; for (i = 0; i < N; i++) { start_timer(t); pid = fork(); if (pid == -1) { // erreur à l'exécution de fork perror("fork"); return EXIT_FAILURE; } // pas d'erreur // BEGIN if (pid == 0) { // processus fils write_record(child_rec, i, stop_timer(t)); recorder_free(child_rec); recorder_free(parent_rec); timer_free(t); return EXIT_SUCCESS; } else { // processus père write_record(parent_rec, i, stop_timer(t)); pid = waitpid(pid, &status, 0); if (pid == -1) { perror("wait"); return EXIT_FAILURE; } } // END } recorder_free(child_rec); recorder_free(parent_rec); timer_free(t); return EXIT_SUCCESS; }
true
00d44871b5d20844d1e1790f708a31487332c921
C
stakenschneider/git.polytest
/OS/9/listings/priorities.c
UTF-8
954
3.09375
3
[ "Apache-2.0" ]
permissive
#include <stdio.h> #include <sched.h> int main (void) { struct sched_param shdprm; printf ("SCHED_FIFO : from %d to %d\n", sched_get_priority_min (SCHED_FIFO), sched_get_priority_max (SCHED_FIFO)); printf ("SCHED_RR : from %d to %d\n", sched_get_priority_min (SCHED_RR), sched_get_priority_max (SCHED_RR)); printf ("SCHED_OTHER: from %d to %d\n", sched_get_priority_min (SCHED_OTHER), sched_get_priority_max (SCHED_OTHER)); printf ("Current policy for this proccess: "); switch (sched_getscheduler (0)) { case SCHED_FIFO: printf ("SCHED__FIFO\n"); break; case SCHED_RR: printf ("SCHED_RR\n"); break; case SCHED_OTHER: printf ("SCHED_OTHER\n"); break; case -1: perror ("SCHED_GETSCHEDULER"); break; default: printf ("Unknown policy\n"); } if (sched_getparam (0, &shdprm) == 0) { printf ("Current priority for this proccess: %d\n", shdprm.sched_priority); } else { perror ("SCHED_GETPARAM"); } return 0; }
true
0cc8562d174bc62fa51573ebeac14602dc965f0e
C
ishafie/filesystem
/my_cp.c
UTF-8
3,423
3
3
[]
no_license
#include "filesystem.h" int copy_file_to_fs(t_fs *fs, int prev_inode) { char *tmp; int nb_blocks; int index_block; int index_block_prev; int len; int i; int inode; inode = 0; while (inode < MAXBLOC && fs->tab_inode[inode].available == FALSE) { inode++; } if (already_exist(fs, fs->tab_inode[prev_inode].name)) return (fprintf(stderr, "cannot copy file %s/’: File exists\n", fs->tab_inode[prev_inode].name)); if (inode == MAXBLOC) return (fprintf(stderr, "No space left in filesystem\n")); i = 0; nb_blocks = 0; len = ft_strlen(fs->tab_inode[prev_inode].name); index_block = search_available_block(fs, fs->tab_inode[prev_inode].size, &nb_blocks); if (index_block == -1) { err_handler("espace insuffisant."); } index_block_prev = search_block_inode(fs, prev_inode); tmp = ft_strsub(fs->data, fs->blocks[index_block_prev].pos + SIZEHEADER, fs->tab_inode[prev_inode].size); // RECUPERER LE CONTENU add_file_to_filestruct(fs, fs->tab_inode[prev_inode].name, index_block, inode, fs->tab_inode[prev_inode].size); add_info_line_to_fs_by_inode(fs, fs->tab_inode[prev_inode], fs->tab_inode[prev_inode].name, len, fs->blocks[index_block].pos, nb_blocks); strncpy(&(fs->data[fs->blocks[index_block].pos + SIZEHEADER]), tmp, fs->tab_inode[prev_inode].size); while (i < nb_blocks) { setbusy(fs, index_block + i, inode); i++; } fs->nb_files += 1; return (1); } int copy_one_file_to_folder(t_fs *fs, char **args) { int prev_i_currentfolder; int inode; int i; int inode2; int begin; char *tmp; inode2 = 0; begin = 0; i = 0; prev_i_currentfolder = fs->i_currentfolder; /* CHERCHER LE PREMIER ARGUMENT, STOCKER SON INODE DANS LA VARIABLE INODE. */ if ((begin = cut_with_slashes(fs, args[1], &i)) == -1) { fs->i_currentfolder = prev_i_currentfolder; return (0); } tmp = ft_strsub(args[1], begin, i - begin); inode = search_inode_name(fs, tmp); if (inode == -1) { fs->i_currentfolder = prev_i_currentfolder; fprintf(stderr, "cp: cannot find '%s': No such file or directory\n", args[1]); return (0); } if (fs->tab_inode[inode].type == TYPEFOLDER) { fs->i_currentfolder = prev_i_currentfolder; fprintf(stderr, "cp: cannot copy directories yet\n"); return (0); } ft_strdel(&tmp); fs->i_currentfolder = prev_i_currentfolder; /* CHERCHER LE DEUXIEME ARGUMENT (un dossier) ET RECUPERER SON INODE POUR POUVOIR STOCKER INODE1 DANS INODE2 */ begin = 0; i = 0; if ((begin = cut_with_slashes(fs, args[2], &i)) == -1) { fs->i_currentfolder = prev_i_currentfolder; return (0); } tmp = ft_strsub(args[2], begin, i - begin); inode2 = search_inode_name(fs, tmp); if (strcmp(tmp, "..") == 0) fs->i_currentfolder = fs->tab_inode[fs->i_currentfolder].folder_inode; else if ((strcmp(tmp, ".") == 0)) ; else if (inode2 == -1 || fs->tab_inode[inode2].type != TYPEFOLDER) { fs->i_currentfolder = prev_i_currentfolder; fprintf(stderr, "cp: cannot find '%s': No such directory\n", args[2]); return (0); } else fs->i_currentfolder = inode2; copy_file_to_fs(fs, inode); fs->i_currentfolder = prev_i_currentfolder; return (1); } int my_cp(t_fs *fs, char **args) { int nb; nb = count_args(args); if (nb != 3) return (fprintf(stderr, "cp: too many/few arguments\n")); copy_one_file_to_folder(fs, args); return (1); }
true
6c02860c1b5339931657bb83d7f09b17ca4691ca
C
FrenzyJay/connect4
/libft/ft_get_next_line.c
UTF-8
2,274
2.8125
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jvincent <jvincent@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2013/12/21 05:56:19 by jvincent #+# #+# */ /* Updated: 2013/12/21 08:59:39 by jvincent ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> #include "libft.h" static char *ft_getline(char *file) { size_t len; char *line; len = 0; while (file[len] != '\n' && file[len] != '\0') len++; line = ft_strnew(len + 1); line = ft_strncpy(line, file, len); ft_strdel(&file); return (line); } static int ft_readfile(int const fd, char **file) { char *buff; char *tmp; int ret; if ((buff = ft_strnew(BUFF_SIZE + 1)) == NULL) return (-1); while ((ret = read(fd, buff, BUFF_SIZE)) > 0) { tmp = *file; *file = ft_strjoin(*file, buff); ft_strdel(&tmp); if (ft_strchr(buff, '\n') != NULL) { ft_strdel(&buff); return (ret); } } ft_strdel(&buff); ft_strdel(file); return (ret); } static int ft_getfile(int const fd, char **line, char **file) { int ret; if (!*file) *file = ft_strnew(2); if (ft_strchr(*file, '\n') != NULL) { *line = *file; *file = ft_strdup((ft_strchr(*file, '\n') + 1)); *line = ft_getline(*line); return (1); } else { ret = ft_readfile(fd, file); if (ret == 0 || ret == -1) return (ret); *line = *file; *file = ft_strdup((ft_strchr(*file, '\n')) + 1); *line = ft_getline(*line); return (1); } } int get_next_line(int const fd, char **line) { static char *file; int ret; if (BUFF_SIZE < 1 || !line || fd < 0) return (-1); ret = ft_getfile(fd, line, &file); if (ret == -1 || ret == 0) return (ret); return (1); }
true
313627344f0e41f447244934eb52493b5a1e2cc3
C
JerryZhou/isee
/code/foundation/container/ineighbor.c
UTF-8
2,270
2.890625
3
[ "Apache-2.0" ]
permissive
#include "foundation/container/ineighbor.h" /* ineighbor destructor */ void ineighbor_destructor(const imeta* meta, iptr o) { ineighbor *neighbor = icast(ineighbor, o); ineighborclean(neighbor); } /* set the relation entry in graphics */ void ineighborbuild(ineighbor *neighbors, ientryrefjointresrelease entry) { icheck(neighbors); neighbors->neighbors_resfree = entry; } /* remove the node from the graphics */ void ineighborclean(ineighbor *node) { irefjoint* joint = NULL; ineighbor *neighbor = NULL; icheck(node); /* disconnect to others */ joint = ireflistfirst(node->neighbors_to); while (joint) { neighbor = icast(ineighbor, joint->value); ireflistremove(neighbor->neighbors_from, irefcast(node)); joint = joint->next; } iassign(node->neighbors_to, NULL); /* disconnect from others */ joint = ireflistfirst(node->neighbors_from); while (joint) { neighbor = icast(ineighbor, joint->value); ireflistremove(neighbor->neighbors_to, irefcast(node)); joint = joint->next; } iassign(node->neighbors_from, NULL); } /* graphics: add a edge-way */ void ineighboradd(ineighbor *from, ineighbor *to) { ineighboraddvalue(from, to, NULL, NULL); } /* graphics: add a edge-way with value append */ void ineighboraddvalue(ineighbor *from, ineighbor *to, void *from_to, void *to_from) { icheck(from); icheck(to); if (!from->neighbors_to) { from->neighbors_to = ireflistmakeentry(from->neighbors_resfree); } ireflistaddres(from->neighbors_to, irefcast(to), from_to); if (!to->neighbors_from) { to->neighbors_from = ireflistmakeentry(to->neighbors_resfree); } ireflistaddres(to->neighbors_from, irefcast(from), to_from); } /* graphics: delete a edge-way */ void ineighbordel(ineighbor *from, ineighbor *to) { ireflistremove(from->neighbors_to, irefcast(to)); ireflistremove(to->neighbors_from, irefcast(from)); } /* graphics: in */ size_t ineighborindegree(ineighbor *node) { icheckret(node, 0); return ireflistlen(node->neighbors_from); } /* graphics: out */ size_t ineighboroutdegree(ineighbor *node) { icheckret(node, 0); return ireflistlen(node->neighbors_to); }
true
2b31deb3f2ca80f120194c28cccca80a958be4b8
C
namsu5857/Learned-c
/Whetting your Apitite/C language/5_Operators/5.3.2IncreAndDecre.c
UTF-8
4,358
3.96875
4
[]
no_license
/*************** Whetting Your Apitite ***************/ /*************** C Language ***************/ /*************** Chapter No.5 ***************/ /*************** Operators ***************/ #include <stdio.h> int main(){ /*************** Increment/Decrement Operators * Token Generation. * In Compilation process there are many phase! * Lexical analysis is the first phase in the compilation process. * lexical analysis is performed by lexical analyzer.Lexical analyzer(scanner) * scans the whole source program and when it finds the meaningful sequence of * characters(lexemes).Then it convert it into a token. * Token:lexemes mapped into token-name and attribute-value. * Example: int -> <keyword, int>. * It always matches the longest character sequence. * lexical analyzer job is to find meaningful sequence of Characters. * let see how! * int a = 5; lexical analyzer first scan int this is meaningfull so analyzer * will generate a separte token for it as keyword |int| Token is nothing but a * container. Next analyzer will scan a blank space and then find a that is variable * name.Analyzer will generate a separte token for it as identifier or variable name * |a| next is assignment operator = analyzer will generater separte token for it |=| * next is constant value 5 fro this analyzer will also generate a seprate token |5| * next is simicolon ; that is termination of line for this analyzer will also generate * a separte token for it |;| * This is behaviour of lexical analyzer.How actually work now its not need to know! * Because This is part of compiler designing But here we are studying C language Only! * ***************/ int a = 5, b = 4; printf("%d \n", a+++b); /*************** As we discuss above Token generation,In above line lexical analyzer will * generate token.first of all it will scan a and then + so a+ is no meaningful character * So analyzer will generate only token of a as |a| then scan next here + is meaningfull * but next is again + so ++ is meaningfull but +++ is not so lexical analyzer will generat * a token for ++ as |++| next again + operator and next is b so +b is not meaningful for both * analyzer will generate separte tokens as |+| and |b|.Now it will become. * |a| |++| |+| |b| * As we know ++ is unary operator and need only one operand that is "a" available and next is addition * operator(+) that need two operands one is "a++" and second is "b" so addition will happen. * Here first of all a++ means first a will assignment(Here will use in equation) and then increment * will happen So a++ will be 5 and then 5 + b Here put value of b that is 4 => 5 + 4 * => 9 So answer will be 9 ***************/ /*************** Now What will be value of this * statement as above discussion ***************/ int x = 5, y = 4; printf("%d \n", x + ++y); /*************** As we discuss above So * lexical analyzer will generate tokens for this also as * first of all "x" variable token will generate because after a is blank space and then addition operator * so first token will |x| then another token for addition operator(+) only because next is blank space and then * "+" So Only |+| token will generate and next is for ++y token will generate as |++y| * finally it will be... * |x| |+| |++y| * as we know x = 5 + ++y, ++y means first increment then assignment(Use in Equation) happen * so it will be y = 5,And "+" is Binery Operator so it required two oprand one is a and second is ++y * So finally it will be 5 + 5 => 10 * The Answer will be 10 ***************/ /*************** Now What will be value of this * statement.You can also relate this as above "i++" one token, "+" is second token and "++j" is * third token finally it will be as * 5 + 5 => 10 Answer will be 10 ***************/ int i = 5, j = 4; printf("%d \n", i++ + ++j); return 0; }
true
811b9ad2e9125aecfa1559ec70dc5acaaaaaefc8
C
yorickdewid/DynnOS
/src/kcommon/file.c
UTF-8
2,249
2.953125
3
[]
no_license
#include <kcommon/call.h> #include <kcommon/file.h> #include <kcommon/memory.h> #include <kcommon/string.h> void file_close(unsigned int fd) { call_close(fd); } unsigned int file_info(char *name, struct file_info *info) { return call_info(name, info); } int file_open(char *name) { return call_open(name); } unsigned int file_read(unsigned int fd, unsigned int count, void *buffer) { // return call_read(fd, buffer, count); } unsigned int file_read_byte(unsigned int fd, char c) { // return file_read(fd, 1, &c); } unsigned int file_write(unsigned int fd, unsigned int count, void *buffer) { // return call_write(fd, buffer, count); } unsigned int file_write_bcd(unsigned int fd, unsigned char num) { // return file_write_dec(fd, num >> 4) + file_write_dec(fd, num & 0x0F); } unsigned int file_write_byte(unsigned int fd, char c) { // return file_write(fd, 1, &c); } unsigned int file_write_dec(unsigned int fd, unsigned int num) { // return file_write_num(fd, num, 10); } unsigned int file_write_hex(unsigned int fd, unsigned int num) { // return file_write_num(fd, num, 16); } unsigned int file_write_num(unsigned int fd, unsigned int num, unsigned int base) { if(!num) { return file_write_byte(fd, '0'); } char buffer[32] = {0}; int i; for(i = 30; num && i; --i, num /= base) { buffer[i] = "0123456789abcdef"[num % base]; } return file_write_string(fd, buffer + i + 1); } unsigned int file_write_string(unsigned int fd, char *buffer) { return file_write(fd, strlen(buffer), buffer); } unsigned int file_write_string_format(unsigned int fd, char *buffer, void **args) { if(!args) { return file_write(fd, strlen(buffer), buffer); } unsigned int i; unsigned int length = strlen(buffer); unsigned int size = 0; for(i = 0; i < length; i++) { if(buffer[i] != '%') { size += file_write_byte(fd, buffer[i]); continue; } i++; switch(buffer[i]) { case 'c': size += file_write_byte(fd, **(char **)args); break; case 'd': size += file_write_num(fd, **(int **)args, 10); break; case 's': size += file_write_string(fd, *(char **)args); break; case 'x': size += file_write_num(fd, **(int **)args, 16); break; } args++; } return size + i; }
true
7f01d8e84dc4691489c0c485a0d430ef6ef048c9
C
ThaisLuca/EDA-UFF-2019
/Lista6/fila.c
UTF-8
900
3.640625
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include "fila.h" //Cria a fila TFila* criaFila(void){ TFila *f = (TFila *) malloc(sizeof(TFila)); f->ini = f->fim = NULL; return f; } int filaVazia(TFila *f){ return f->ini == NULL; } //Insere um elemento na fila void insere(TFila *f, int x){ TNO *novo = (TNO *) malloc(sizeof(TNO)); novo->info = x; novo->prox = NULL; if(filaVazia(f)){ f->ini = f->fim = novo; } else { f->fim->prox = novo; f->fim = novo; } } //Retira um elemento da fila int retira(TFila *f){ if(filaVazia(f)) exit(1); int resp = f->ini->info; TNO *q = f->ini; f->ini = f->ini->prox; if(!f->ini) f->fim = NULL; free(q); return resp; } //Libera a fila void liberaFila(TFila *f){ TNO *q = f->ini, *t; while(q){ t = q; q = q->prox; free(t); } free(f); } //Imprime a fila void imprimeFila(TFila *f){ while(!filaVazia(f)){ printf("%d\n", retira(f)); } }
true
19019a964fff25e629767288c8659c96b035cdab
C
SrB30/Competitive-Programming
/UVA/371 - Ackermann Functions.c
UTF-8
776
3.375
3
[]
no_license
#include <stdio.h> int main() { long long int L, H, V, S, cnt, temp, temp1, i; while (scanf("%lld%lld", &L, &H)) { if (L == 0 && H == 0) return 0; if (L > H) { temp1 = L; L = H; H = temp1; } S = 0; for (i=L; i<=H; i++) { temp = i; cnt = 0; do { temp = ((temp%2 != 0) ? ((3*temp) + 1) : (temp / 2)); cnt++; } while (temp > 1); if (S < cnt) { S=cnt; V=i; } } printf("Between %lld and %lld, %lld generates the longest sequence of %lld values.\n", L, H, V, S); } }
true
b64ce6d51ece4c550fedc7dbac9a8a336006ebf9
C
ynain/ece368
/Project3/mapping.c
UTF-8
8,971
3
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <string.h> #include <limits.h> #include "mapping.h" #define INF INT_MAX int main(int argc, char * argv[]) { if (argc != 3) { fprintf(stderr, "Input format: ./proj3 mapfile queryfile\n"); return EXIT_FAILURE; } // Read file, build graph Graph * graph = readGraph(argv[1]); if (graph == NULL) { fprintf(stderr, "Unable to build graph from file\n"); return EXIT_FAILURE; } // Build adjacency matrix or adjacency lists List ** adjLists = buildAdjacencyLists(graph); if (adjLists == NULL) { fprintf(stderr, "Unable to build adjacency matrix from graph\n"); destroyGraph(graph); return EXIT_FAILURE; } // Read queries, perform minimum search for each query if (processQueries(argv[2], adjLists, graph->vertexCount)) { fprintf(stderr, "Unable to process queries from file\n"); destroyLists(adjLists, graph->vertexCount); destroyGraph(graph); return EXIT_FAILURE; } destroyLists(adjLists, graph->vertexCount); destroyGraph(graph); return EXIT_SUCCESS; } int processQueries(char * Filename, List ** lists, int vCount) { FILE * fp = fopen(Filename, "r"); if (fp == NULL) { return 1; } int queryCount = 0, v1 = 0, v2 = 0; fscanf(fp, "%d", &queryCount); for (int i = 0; i < queryCount; i++) { fscanf(fp, "%d %d", &v1, &v2); // find shortest path for all nodes from source dijkstra(vCount, lists, 0, v1, v2); } fclose(fp); return 0; } void minimizeHeap(Heap * h, int v, int dist) { int a = h->pos[v]; h->arr[a]->dist = dist; while(a && h->arr[a]->dist < h->arr[(a-1)/2]->dist) { h->pos[h->arr[a]->v] = (a-1)/2; h->pos[h->arr[(a-1)/2]->v] = a; swapNodes(&(h->arr[a]), &(h->arr[(a-1)/2])); a = (a-1)/2; } /* int b = (a-1)/2; while(a && h->arr[a]->dist < h->arr[b]->dist) { h->pos[h->arr[a]->v] = b; h->pos[h->arr[b]->v] = a; swapNodes(&(h->arr[a]), &(h->arr[b])); b = (b-1)/2; } */ } void swapNodes(HeapNode ** a, HeapNode ** b) { HeapNode * temp = *a; *a = *b; *b = temp; } HeapNode * getMinimumNode(Heap * h) { if (h->size == 0) { return NULL; } HeapNode * root = h->arr[0], * last = h->arr[h->size -1]; h->arr[0] = last; h->pos[root->v] = h->size - 1; h->pos[last->v] = 0; h->size--; heapify(h, 0); return root; } void heapify(Heap * h, int i) { int min = i, l = 2*i + 1, r = 2*i + 2; if ((l < h->size) && (h->arr[l]->dist < h->arr[min]->dist)) { min = l; } if ((r < h->size) && (h->arr[r]->dist < h->arr[min]->dist)) { min = r; } if (min != i) { HeapNode * minNode = h->arr[min]; HeapNode * iNode = h->arr[i]; h->pos[minNode->v] = i; h->pos[iNode->v] = min; swapNodes(&(h->arr[min]), &(h->arr[i])); heapify(h, min); } } void dijkstra(int a, List ** lists, int weightTotal, int src, int dest) { // Initialize single source // The main function that calulates distances of shortest paths from src to all // int * distance = malloc(sizeof(distance) * a); // Create minimum heap, sort by distances // Set distance of all nodes from source to infinity, set source dist to 0 Heap * h = buildHeap(a, src); for (int i = 0; i < a; distance[i++] = INF); char ** paths = malloc(sizeof(*paths) * a); for (int j = 0; j < a; j++) { //paths[j] = malloc(sizeof(paths[0][0]) * ((j/10)+3)); paths[j] = malloc(sizeof(paths[0][0]) * ((log10(j+1)) + 3)); sprintf(paths[j], "%d ", j); } distance[src] = 0; minimizeHeap(h, src, distance[src]); while (h->size != 0) { HeapNode * min = getMinimumNode(h); int m = min->v; destroyHeapNode(min); List * cur = lists[m]; while (cur != NULL) { int n = cur->ptr->label; if ((h->pos[n] < h->size) && (distance[m] != INF) && (cur->weight+distance[m] < distance[n])) { distance[n] = distance[m] + cur->weight; minimizeHeap(h, n, distance[n]); free(paths[n]); char * buffer = malloc(sizeof(*buffer) * ((log10(n+1)) + 3)); sprintf(buffer, "%d ", n); paths[n] = addToPath(paths[m], buffer); free(buffer); } cur = cur->next; } } if (distance[dest] != INF) { printf("%d\n", distance[dest]); printf("%s\n", paths[dest]); } else { printf("INF\n"); printf("%d %d\n", src, dest); } destroyHeap(h); destroyPaths(paths, a); free(distance); } char * addToPath(char * str1, char * str2) { char * retval = malloc(sizeof(*retval) * (strlen(str1) + strlen(str2) + 1)); strcpy(retval, str1); strcat(retval, str2); return retval; } void destroyPaths(char ** paths, int p) { for (int i = 0; i < p; i++){ free(paths[i]); } free(paths); } Heap * buildHeap(int v, int src) { Heap * heap = malloc(sizeof(*heap)); heap->pos = malloc(sizeof(*(heap->pos)) * v); heap->arr = malloc(sizeof(**(heap->arr)) * v); heap->size = v, heap->maxSize = v; for (int i = 0; i < v; i++) { heap->pos[i] = i; heap->arr[i] = buildHeapNode(i, INF); } heap->arr[src]->dist = 0; return heap; } HeapNode * buildHeapNode(int i, int dist) { HeapNode * node = malloc(sizeof(*node)); node->v = i; node->dist = dist; return node; } int ** buildAdjacencyMatrix(Graph * g) { int ** matrix = malloc(sizeof(*matrix) * g->vertexCount); if (matrix == NULL) { return NULL; } for (int a = 0; a < g->vertexCount; matrix[a++] = malloc(sizeof(**matrix) * g->vertexCount)); for (int x = 0; x < g->vertexCount; x++) { for (int y = 0; y < g->vertexCount; y++) { matrix[x][y] = 0; } } Vertex * st, * ed; for (int i = 0; i < g->edgeCount; i++) { st = g->edges[i]->start; ed = g->edges[i]->end; matrix[st->label][ed->label] = (int) sqrt((double) (pow(st->x - ed->x, 2) + pow(st->y - ed->y, 2))); } return matrix; } List ** buildAdjacencyLists(Graph * g) { List ** lists = malloc(sizeof(*lists) * g->vertexCount); if (lists == NULL) { return NULL; } // Find all connections and order them by weight for (int i = 0; i < g->vertexCount; i++) { lists[i] = buildList(g->vertices[i], g->vertices[i]); } for (int j = 0; j < g->edgeCount; j++) { int ls = g->edges[j]->start->label; // Build list node, insert in correct position List * newList = buildList(g->edges[j]->end, g->edges[j]->start); List * temp = lists[ls]; while (newList->weight < temp->weight) { temp = temp->next; } newList->next = temp->next; temp->next = newList; } return lists; } /* * Reads file + constructs graph * First values read are number of vertices and number of edges * Read in all vertices + edges and append to graph */ Graph * readGraph(char * Filename) { FILE * fp = fopen(Filename, "r"); if (fp == NULL) { return NULL; } int numVertices = 0, numEdges = 0, vertexLabel = 0, x = 0, y = 0, startInd = 0, endInd = 0; Graph * graph = malloc(sizeof(*graph)); if (graph == NULL) { fclose(fp); return NULL; } fscanf(fp, "%d %d", &numVertices, &numEdges); graph->vertices = malloc(sizeof(*(graph->vertices)) * numVertices); graph->edges = malloc(sizeof(*(graph->edges)) * numEdges); graph->vertexCount = numVertices; graph->edgeCount = numEdges; for(int i = 0; i < numVertices; i++) { fscanf(fp, "%d %d %d", &vertexLabel, &x, &y); graph->vertices[i] = buildVertex(vertexLabel, x, y); } for (int j = 0; j < numEdges; j++) { fscanf(fp, "%d %d", &startInd, &endInd); graph->edges[j] = buildEdge(graph->vertices[startInd], graph->vertices[endInd]); } fclose(fp); return graph; } /* Build vertex */ Vertex * buildVertex(int label, int x, int y) { Vertex * v = malloc(sizeof(*v)); v->label = label; v->x = x; v->y = y; return v; } /* Build edge */ Edge * buildEdge(Vertex * start, Vertex * end) { Edge * e = malloc(sizeof(*e)); e->start = start; e->end = end; return e; } /* Build list node */ List * buildList(Vertex * ptr, Vertex * root) { List * list = malloc(sizeof(*list)); list->ptr = ptr; list->next = NULL; list->weight = (int) sqrt((double) (pow(root->x - ptr->x, 2) + pow(root->y - ptr->y, 2))); return list; } void destroyHeap(Heap * h) { if (h != NULL) { while (h->size > 0) { destroyHeapNode(h->arr[h->size - 1]); h->size--; } free(h->pos); free(h->arr); free(h); } } void destroyHeapNode(HeapNode * h) { if (h != NULL) { free(h); } } void destroyMatrix(int ** matrix, int ct) { for (int i = 0; i < ct; free(matrix[i++])); free(matrix); } void destroyLists(List ** lists, int ct) { for (int i = 0; i < ct; i++) { List * temp; while (lists[i] != NULL) { temp = lists[i]; lists[i] = lists[i]->next; free(temp); } } free(lists); } /* Clears all memory associated with graph */ void destroyGraph(Graph * g) { for (int i = 0; i < g->vertexCount; free(g->vertices[i++])); free(g->vertices); for (int j = 0; j < g->edgeCount; free(g->edges[j++])); free(g->edges); free(g); } void printLists(List ** lists, int v) { for(int i = 0; i < v; i++) { List * temp = lists[i]; while (temp != NULL) { printf("%d:%d -> ", temp->ptr->label, temp->weight); temp = temp->next; } printf("NULL\n"); } }
true
621b4140f722e81c40dac9942b867ddc889f447c
C
YuhanLiin/Cryptopals-C
/set1/break_repeating_xor.c
UTF-8
4,709
3.328125
3
[]
no_license
#include <assert.h> #include <stdlib.h> #include "type.h" #include "letter_score.h" #include "xor.h" #define MAX_KEYSIZE 40 #define MIN_KEYSIZE 2 size_t edit_distance(const byte_t * str1, const byte_t * str2, const size_t len) { size_t total = 0; for (size_t i = 0; i < len; ++i) { byte_t xor = str1[i] ^ str2[i]; for (size_t _ = 0; _ < 8; ++_) { total += xor & 1u; xor >>= 1; } } return total; } struct Key_tuple { float norm_dist; size_t key_len; }; // Comparison function for key tuples. Finds the best key size by sorting the edit distances int keycmp(const void * a, const void * b) { const struct Key_tuple * ka = a; const struct Key_tuple * kb = b; return ka->norm_dist - kb->norm_dist; } // With a given keysize, allocate and return the normalized letter score of the entire text. // Decrypts the cipher in place and populates a buffer with the key bytes. // On error or invalid plaintext MINIMUM_TEXT_SCORE is returned. static float find_key(byte_t * bytes, const size_t len, byte_t * key, const size_t keysize) { const size_t blk_cap = len / keysize + 1; int total_score = MINIMUM_TEXT_SCORE; for (size_t k = 0; k < keysize; k++) { byte_t block[blk_cap]; size_t blk_len = 0; // Form a block of all the characters encrypted with byte k of the repeated key for (size_t i = k; i < len; i += keysize, blk_len++) { block[blk_len] = bytes[i]; } assert(blk_len <= blk_cap); // Decode the block using single byte xor. This also reveals the kth byte of the key. int score; byte_t key_byte; byte_t * decoded_blk = break_xor_cipher(block, blk_len, &score, &key_byte); if (decoded_blk == NULL) break; // Minimum score means that this key length produces invalid characters if (score == MINIMUM_TEXT_SCORE) break; key[k] = key_byte; total_score += score; // Decrypt the block with the single-byte key for (size_t i = k; i < len; i += keysize) { bytes[i] ^= key_byte; } free(decoded_blk); } return total_score / (float)len; } // Number of keysized chunks to use to compute the edit distance used to determine keysizes #define KEYSIZED_CHUNKS_COUNT 4 // Returns the repeated key and its length as well as decrypting the byte string in place. // On failure (no memory or valid key) null is returned and the length and byte string are invalidated. byte_t * break_repeating_xor(byte_t * bytes, const size_t len, size_t * key_len) { // Algorithm only works on strings at least 4 keysizes long if (len < MIN_KEYSIZE * KEYSIZED_CHUNKS_COUNT) { return NULL; } // As such, the max keysize can't be more than half the string length const size_t max_keysize = MIN(len / KEYSIZED_CHUNKS_COUNT, MAX_KEYSIZE); struct Key_tuple key_tuples[max_keysize - MIN_KEYSIZE + 1]; for (size_t keysize = MIN_KEYSIZE; keysize <= max_keysize; keysize++) { // Find edit distances between consecutive keysized chunks of the string size_t dist1 = edit_distance(&bytes[0], &bytes[keysize], keysize); size_t dist2 = edit_distance(&bytes[keysize], &bytes[keysize * 2], keysize); size_t dist3 = edit_distance(&bytes[keysize * 2], &bytes[keysize * 3], keysize); // Normalize distance by dividing by keysize. // The keysize with the lowest normalized edit distance is the right one float norm_dist = (dist1 + dist2 + dist3) / (float)keysize; key_tuples[keysize - MIN_KEYSIZE] = (struct Key_tuple){.norm_dist = norm_dist, .key_len = keysize}; } const size_t key_tuples_len = sizeof(key_tuples) / sizeof(struct Key_tuple); qsort( key_tuples, key_tuples_len, sizeof(struct Key_tuple), &keycmp ); byte_t cpy[len]; byte_t * key = malloc(max_keysize); if (key == NULL) return NULL; size_t best_key_len = MIN_KEYSIZE; float best_key_score = MINIMUM_TEXT_SCORE; // Take the 5 best key lengths and find the one with the best score for (size_t i = 0; i < MIN(5, key_tuples_len); i++) { memcpy(cpy, bytes, len); size_t k_len = key_tuples[i].key_len; float score = find_key(cpy, len, key, k_len); if (score > best_key_score) { best_key_len = k_len; best_key_score = score; } } // Retrieve the plaintext and key of the best key length find_key(bytes, len, key, best_key_len); *key_len = best_key_len; return key; }
true
e14216c6df11a8a17a906c29229d14440f2928ad
C
bsuverzabaek/Code-Chef-Exercises
/Hard/teamSelection/teamSelection.c
UTF-8
962
3.03125
3
[]
no_license
#include <stdio.h> #include <assert.h> #include <stdlib.h> int main(void){ int T,N,curSum,ans,bestDiff; scanf("%d",&T); assert(T>=1 && T<=100); while(T>0){ scanf("%d",&N); assert(N>=1 && N<=100); ans = 0; curSum = 0; int ele[N]; int sum[450002]; for(int i=0;i<N;i++){ scanf("%d",&ele[i]); assert(ele[i]>=1 && ele[i]<=450); curSum += ele[i]; if((i&1)!=0){ ans += ele[i]; } } for(int i=0;i<=curSum;i++){ sum[i] = 0; } sum[0] = 1; curSum = 0; for(int i=0;i<N;i++){ for(int j=curSum+ele[i];j>=ele[i];j--){ sum[j] |= (sum[j-ele[i]]<<1); } curSum += ele[i]; } bestDiff = abs(curSum-2*ans); for(int i=0;i<=curSum;i++){ if((sum[i]&(1<<(N/2)))!=0 || (sum[i]&(1<<(N-N/2)))!=0){ if(bestDiff>abs(curSum-2*i)){ ans = i; bestDiff = abs(curSum-2*i); } } } if(ans>curSum-ans){ ans = curSum-ans; } printf("%d %d\n",ans,curSum-ans); T--; } return 0; }
true
400b58a5ef6121a0f5ffddb4172ebb87cc6baeba
C
4rterius/cgtfs
/tests/tests_records/tests-records_trips.c
UTF-8
2,371
2.859375
3
[ "MIT", "CC-BY-3.0", "CC-BY-4.0" ]
permissive
#ifndef CGTFS_TESTS_RECORDS_TRIPS_C #define CGTFS_TESTS_RECORDS_TRIPS_C #include "greatest/greatest.h" #include "records/trip.h" TEST trip_read(void) { #define FIELDS_NUM_13 10 char *field_names[FIELDS_NUM_13] = { "route_id", "service_id", "trip_id", "trip_headsign", "trip_short_name", "direction_id", "block_id", "shape_id", "wheelchair_accessible", "bikes_allowed" }; char *field_values[FIELDS_NUM_13] = { "A", "WE", "AWE1", "Downtown", "Some short name", "", "11", "8", "1", "2" }; trip_t tr_1; read_trip(&tr_1, FIELDS_NUM_13, (const char **)field_names, (const char **)field_values); ASSERT_STR_EQ("A", tr_1.route_id); ASSERT_STR_EQ("WE", tr_1.service_id); ASSERT_STR_EQ("AWE1", tr_1.id); ASSERT_STR_EQ("Downtown", tr_1.headsign); ASSERT_STR_EQ("Some short name", tr_1.short_name); ASSERT_STR_EQ("11", tr_1.block_id); ASSERT_STR_EQ("8", tr_1.shape_id); ASSERT_EQ(0, tr_1.direction_id); ASSERT_EQ(WA_POSSIBLE, tr_1.wheelchair_accessible); ASSERT_EQ(BA_NOT_POSSIBLE, tr_1.bikes_allowed); PASS(); } TEST trip_compare(void) { trip_t a = { .route_id = "RT1", .service_id = "123", .id = "RT1_888", .headsign = "The Grand Tour", .short_name = "TGT", .direction_id = 1, .block_id = "lbkc", .shape_id = "shpe", .wheelchair_accessible = WA_UNKNOWN, .bikes_allowed = BA_POSSIBLE }; trip_t b = { .route_id = "RT1", .service_id = "123", .id = "RT1_888", .headsign = "The Grand Tour", .short_name = "TGT", .direction_id = 1, .block_id = "lbkc", .shape_id = "shpe", .wheelchair_accessible = WA_UNKNOWN, .bikes_allowed = BA_POSSIBLE }; trip_t c = { .route_id = "RT2", .service_id = "123", .id = "RT2_888", .headsign = "The Grand Tour", .short_name = "TGT", .direction_id = 0, .block_id = "lbskc", .shape_id = "shpe", .wheelchair_accessible = WA_UNKNOWN, .bikes_allowed = BA_POSSIBLE }; ASSERT_EQ(1, equal_trip(&a, &b)); ASSERT_EQ(0, equal_trip(&a, &c)); ASSERT_EQ(0, equal_trip(&b, &c)); PASS(); } SUITE(CGTFS_RecordTrip) { RUN_TEST(trip_read); RUN_TEST(trip_compare); } #endif
true
db0e8dee274de7d4c52a5e881e08106fa2a7e1e7
C
wabilin/OJSols
/leetcode/split-a-string-in-balanced-strings.c
UTF-8
505
3.71875
4
[ "Unlicense" ]
permissive
// Runtime: 0 ms, faster than 100.00% of C online submissions for Split a String in Balanced Strings. // Memory Usage: 5.1 MB, less than 100.00% of C online submissions for Split a String in Balanced Strings. int balancedStringSplit(char * s){ int r = 0; int l = 0; int count = 0; while(*s) { if (*s == 'R') { ++r; } else if (*s == 'L') { ++l; } if (r == l) { ++count; } ++s; } return count; }
true
90f1bcc3d127569467c18f8a25f2f586377e3157
C
fegemo/cefet-lfui
/descbin.c
UTF-8
3,383
3.890625
4
[]
no_license
#include <stdio.h> #define TAM 12 #define TRUE 0 #define FALSE -1 #define MAX_LINHAS 800 // A implementação (corpo) destas funções está lá embaixo void imprime_numero(char, unsigned int); // imprime em binário ou hexadecimal void imprime_vazios(char, int); // imprime espaços vazios // Este programa lê um arquivo e o imprime de duas formas: // 1. em binário/hexadecimal // 2. em texto (segundo a tabela ASCII) // int main(int argc, char* argv[]) { FILE *arqptr; unsigned int ch; int j, not_eof; unsigned char string[TAM+1]; char* caminho_arquivo = argv[2]; unsigned int linhas_lidas = 0; // Pára se encontra erros if (argc != 3) { // Erro de chamada: precisa chamar o programa com um argumento printf("Como usar o aplicativo descbin:\n\n"); printf("C:> descbin.exe base arq.xxx\n\n Onde:\n"); printf("\t - 'base' deve ser a letra 'b' para binario ou 'h' para hexadecimal\n"); printf("\t - 'arq.xxx' deve ser o caminho para um arquivo\n"); return(0); } char base = argv[1][0]; // 'b' ou 'h' if ((arqptr = fopen(caminho_arquivo, "rb")) == NULL) { // Erro ao abrir o arquivo: provavelmente o arquivo especificado na chamada // não foi encontrado printf("Nao posso abrir o arquivo %s.", caminho_arquivo); return(0); } not_eof = TRUE; do { for (j=0; j<TAM && not_eof == TRUE; j++) { // Lê um caractere do arquivo ch = getc(arqptr); if (ch == (unsigned)EOF) { not_eof = FALSE; // Imprime espaços vazios imprime_vazios(base, (TAM-j-1)); } else { // Imprime o caractere lido, no formato de número hexadecimal imprime_numero(base, ch); printf(" "); // Na tabela ASCII, os códigos de 0 a 31 não representam caracteres, // mas operações (nova linha, tab, nulo etc.) if (ch > 31) { // Salva na variável "string" o conteúdo do arquivo *(string+j) = ch; } else { // Salva na variável "string" o caractere '.' *(string+j) = '.'; } } } // Termina a linha (ao colocar '\0' no final) *(string+j) = '\0'; // Imprime a variável linha contendo TAM caracteres printf(" %s\n", string); linhas_lidas++; } while (not_eof == TRUE && linhas_lidas < MAX_LINHAS); fclose(arqptr); return 0; } void imprime_binario(unsigned int v) { int bytes = 1; unsigned int i, s = 1<<((bytes<<3)-1); for (i = s; i; i>>=1) { printf("%d", v & i || 0 ); } } void imprime_hexadecimal(unsigned int v) { // Referência da função printf: // http://www.cplusplus.com/reference/cstdio/printf/ printf("%02x", v); } void imprime_vazios(char base, int espacos) { for (; espacos>=0; espacos--) printf(base == 'h' ? " " : " "); } void imprime_numero(char base, unsigned int num) { switch (base) { case 'b': imprime_binario(num); break; case 'h': default: imprime_hexadecimal(num); break; } }
true
9ce30fa3b3eea2aa847390fd2fdabf47968b6383
C
nicecoolwinter/learn_c
/明解C語言/實作篇/chapter04/List4-17/List4-17.c
UTF-8
1,384
3.515625
4
[]
no_license
/* 將單字從檔案讀入並顯示 */ #include <ctype.h> #include <stdio.h> #include <string.h> #define Q_NO 3 /* 問題個數 */ FILE* fp; /*--- 初始處理 ---*/ int initialize(void) { fp = fopen("DATA", "r"); return ((fp == NULL) ? 0 : 1); } /*--- 結束處理 ---*/ void ending(void) { fclose(fp); } /*--- 主函式 ---*/ int main(void) { if (initialize()) { int q, ch; char qus[20] = ""; /* 問題用字串 */ char ans[20] = ""; /* 解答用字串 */ for (q = 0; q < Q_NO; q++) { int i; strcpy(ans, ""); /* 沒有照預期的動作? */ strcpy(qus, ""); /* " */ ch = fgetc(fp); if (ch == EOF) { goto ending; } for (i = 0; !(isspace(ch)); i++) { qus[i] = ch; qus[i + 1] = '\0'; /* 後來才代入 */ ch = fgetc(fp); } ch = fgetc(fp); for (i = 0; !(isspace(ch)); i++) { ans[i] = ch; ans[i + 1] = '\0'; /* 後來才代入 */ ch = fgetc(fp); } printf("問題=%s 解答=%s\n", qus, ans); } ending: ending(); } system("PAUSE"); return (0); }
true
73262917abc81b84abbe8b18abb330539817efd7
C
Asylumrots/C-Study
/C1/06多文件编程/01test.c
UTF-8
160
2.828125
3
[]
no_license
#include <stdio.h> #include "test.h" int main() { printf("%d", max(10, 20)); return 0; } int max(int a, int b) { if (a > b) return a; else return b; }
true
5788a6c4118ca900d550754409aa959b40dae763
C
mhscardoso/Labs-Alg.Prog
/Lab2/ex12.c
UTF-8
656
3.90625
4
[]
no_license
#include <stdio.h> int main(void) { int n, iguais; double a1, a2, soma, produto; soma = 0; produto = 1; iguais = 0; printf("Quantos pares de numeros? "); scanf("%i", &n); for (int i = 0; i < n; ++i) { printf("Digite a1: "); scanf("%d", &a1); printf("Digite a2: "); scanf("%d", &a2); if (a1 > a2) { soma += a1; produto *= a2; } else if (a1 < a2) { soma += a2; produto *= a1; } else { ++iguais; } printf("\n"); } printf("A soma dos maiores numeros eh: %d\n", soma); printf("O produto dos menores numeros eh: %d\n", produto); printf("A quantidade de pares iguais eh: %i\n", iguais); return 0; }
true
a7771e6545b5d0aaba83e13e1bdb8d65fe12d398
C
miz060/Parallel-Programming-Practice
/MPI_Ring/svalidate.c
UTF-8
2,589
3.796875
4
[]
no_license
/** @file * \brief a small set of validation functions for strings * \author Mingcheng Zhu * \email zhumc11@gmail.com * \date 19 Jan 2018 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> #include "svalidate.h" /** * \fn char * trim (char * input) * \param input * \brief trim leading and trailing white space from input string * \return pointer to beginning of trimmed string * \note Potential side-effect modifies: can modify the input to place c-terminator * in the appropriate location to trim trailing whitespace */ char * trim (char * input) { /* check null string */ if (!input) return input; char * rstr = input; char * p = input; /* trim leading space */ while ( isspace(*p)) p++; rstr = p; /* trim trailing white space */ p = rstr + strlen(rstr) - 1; while ( isspace(*p)) p--; *(p+1) = '\0'; return rstr; } /** * \fn char * trimCopy( char *input) * \param input * \brief trim leading and trailing white space from input string * \return a malloced copy of trimmed string */ char * trimCopy( char *input) { /* check null string */ if ( !input ) return input; char * rstr; while ( isspace(*input) ) input++; if ( strlen(input) > 0 ) { rstr = malloc((strlen(input) + 1)*sizeof(char)); strcpy(rstr,input); return trim(rstr); } return (char *) NULL; } /** * \fn int isInteger(char * input) * \param input - string that is trimmed of leading/trailing whitespace * \brief determine if input could be converted to an int * \return 1 if string could be converted to an int, 0 otherwise */ int isInteger(char * input) { /* check null string */ if (!input) return FALSE; if (*input == '+' || *input == '-') input++; do { if ( ! isdigit(*input)) return FALSE; } while (*(++input)); return TRUE; } /** * \fn int isFloat(char * input) * \param input - string that is trimmed of leading/trailing whitespace * \brief determine if input could be converted to a float * \return 1 if string could be converted to a float, 0 otherwise */ int isFloat(char * input) { float tval; char *endp; tval = strtof(input,&endp); // Check for various errors (see man strtof) if ( *endp != '\0' ) return FALSE; if ( tval == 0 && endp == input ) return FALSE; if ( errno == ERANGE ) return FALSE; return TRUE; } int isDouble(char * input) { double tval; char *endp; tval = strtod(input,&endp); // Check for various errors (see man strtof) if ( *endp != '\0' ) return FALSE; if ( tval == 0 && endp == input ) return FALSE; if ( errno == ERANGE ) return FALSE; return TRUE; }
true
6d698772ddcfdac85990924ada740e82fb1fafde
C
kateyose/Hole-punching-chat
/udp_client.c
UTF-8
2,671
2.75
3
[ "Unlicense" ]
permissive
#include <arpa/inet.h> #include <netinet/in.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #define BUFLEN 512 #define NPACK 10 #define PORT 6868 #define SRV_IP "18.225.5.21" static int s; struct client { int host; short port; }; void diep(char *s) { perror(s); exit(1); } void *send_message_to_peer(void *si_other) { char buffer[BUFLEN]; size_t size; // I couldn't figure out why only the first conversation magically disappears somewhere. // So I enforce the silent first conversation. if (sendto(s, "", BUFLEN, 0, (struct sockaddr *)si_other, sizeof(struct sockaddr_in)) == -1) diep("sendto peer"); while (1) { fgets(buffer, BUFLEN, stdin); if (sendto(s, buffer, BUFLEN, 0, (struct sockaddr *)si_other, sizeof(struct sockaddr_in)) == -1) diep("sendto peer"); } } int main(int argc, char *argv[]) { struct sockaddr_in si_me, si_other; int i, f, j, k, slen = sizeof(si_other); struct client buf; struct client server; int n = 0; if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) diep("socket"); memset((char *)&si_me, 0, sizeof(si_me)); si_me.sin_family = AF_INET; si_me.sin_port = htons(PORT); si_me.sin_addr.s_addr = htonl(INADDR_ANY); memset((char *)&si_other, 0, sizeof(si_other)); si_other.sin_family = AF_INET; si_other.sin_port = htons(PORT); if (inet_aton(SRV_IP, &si_other.sin_addr) == 0) diep("aton"); server.host = si_other.sin_addr.s_addr; server.port = si_other.sin_port; if (sendto(s, "i", 1, 0, (struct sockaddr *)(&si_other), slen) == -1) diep("sendto server"); if (recvfrom(s, &buf, sizeof(buf), 0, (struct sockaddr *)(&si_other), &slen) == -1) diep("recvfrom server"); printf("Received packet from %s:%d\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port)); if (server.host == si_other.sin_addr.s_addr && server.port == (short)(si_other.sin_port)) { si_other.sin_addr.s_addr = buf.host; si_other.sin_port = buf.port; printf("Your peer %s:%d\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port)); } else { diep("recieve from unknown server"); } pthread_t send_thread; if (pthread_create(&send_thread, NULL, send_message_to_peer, &si_other)) { fprintf(stderr, "Error creating thread\n"); return 1; } while (1) { char bufc[BUFLEN]; if (recvfrom(s, &bufc, sizeof(bufc), 0, (struct sockaddr *)(&si_other), &slen) == -1) diep("recvfrom peer"); printf("%s", bufc); } close(s); return 0; }
true
97ec6649e3a653d51a8b0c58e5530a4b8a28baeb
C
nikopapp/SoftwareEngineering-1
/encryption.c
UTF-8
7,202
3.0625
3
[ "MIT" ]
permissive
/*next steps 1. implemnet the grid 2. implement key presses with SDL 3. test if everything works*/ #include "encryption.h" #define GRIDSIZE 10 void enc_shufle(char word[LENGTH], int size); int enc_isenc_vowel(char c); char enc_vowel(); char enc_constant(); void enc_changeRow(char word[LENGTH], int size); void enc_change(char word[LENGTH], int size, int game); void enc_printGrid(char grid[GRIDSIZE][GRIDSIZE]); void enc_gridInit(char grid[GRIDSIZE][GRIDSIZE]); void enc_wordInsert(char grid[GRIDSIZE][GRIDSIZE], char word[LENGTH], int size, int row); void enc_compare(char word[LENGTH]); int enc_play(char grid[GRIDSIZE][GRIDSIZE], char avatar, int wordLength, int wordStart, char word[LENGTH]); int enc_gridCheck(char grid[GRIDSIZE][GRIDSIZE], int y, int x, int yPlus, int xPlus); char enc_alphabetCheck(char letter); int enc_winCheck(char grid[GRIDSIZE][GRIDSIZE], int wordLength, int wordStart, char word[LENGTH]); int encryption(void) { char *list[] = {"frondo", "gandalf","elrond", "legolas", "gimli", "aragorn","saouron"}; char rand_word[LENGTH], shuffle_word[LENGTH]; int i, word_size; char grid[GRIDSIZE][GRIDSIZE], avatar = '@'; srand(time(NULL)); if (sscanf(list[(rand()%LIST_SIZE)], "%s", rand_word) != 1){ printf("couldn't get a word from the list\n"); return 1; } word_size = strlen(rand_word); for (i=0; i<word_size; i++){ shuffle_word[i] = rand_word[i]; } shuffle_word[word_size] = '\0'; printf("\nThe initial word is %s and ", shuffle_word); enc_gridInit(grid); enc_shufle(shuffle_word, word_size); enc_wordInsert(grid, shuffle_word, word_size, 2); printf("%s\n", shuffle_word); enc_printGrid(grid); enc_play(grid, avatar, word_size, 2, rand_word); //enc_compare(rand_word); return 0; } int enc_play(char grid[GRIDSIZE][GRIDSIZE], char avatar, int wordLength, int wordStart, char Word[LENGTH]){ char move; int x_ava=5, y_ava=5; grid[5][5] = avatar; while(scanf("%c",&move)==1){ switch (move) { case 'i': // move up if(enc_gridCheck(grid, y_ava, x_ava, -1, 0)==1){ printf("yay!\n"); break; } else{ grid[y_ava][x_ava] = ' '; y_ava--; grid[y_ava][x_ava] = avatar; //printf("yay!\n"); break; } case 'j': // move left grid[y_ava][x_ava] = ' '; x_ava--; grid[y_ava][x_ava] = avatar; break; case 'l' : // move right grid[y_ava][x_ava] = ' '; x_ava++; grid[y_ava][x_ava] = avatar; break; case 'k': // move down grid[y_ava][x_ava] = ' '; y_ava++; grid[y_ava][x_ava] = avatar; break; } enc_printGrid(grid); if (enc_winCheck(grid, wordLength, wordStart, Word)==1){ printf("you have won!!\n"); return 1; } } /*res=BinResult(byte); printf("result %d\n",res ); if(res==goal){ break; }*/ return 0; } int enc_winCheck(char grid[GRIDSIZE][GRIDSIZE], int wordLength, int wordStart, char word[LENGTH]){ int cnt; wordLength=wordLength-2; //printf("wordLength=%d wordStart=%d word=%s\n", wordLength, wordStart, word); for(cnt=0; cnt<wordLength+wordStart; cnt++){ //printf("grid %c secret %c ", grid[2][cnt+wordStart-1], word[cnt]); if(grid[2][cnt+wordStart-1]!=word[cnt]){ return 0; } } return 1; } /*checks whether there is a letter, if there is a letter then it increments the letter by one*/ int enc_gridCheck(char grid[GRIDSIZE][GRIDSIZE], int y, int x, int yPlus, int xPlus){ if(grid[y+yPlus][x+xPlus]>='a' && grid[y+yPlus][x+xPlus]<='z'){ grid[y+yPlus][x+xPlus]=enc_alphabetCheck(grid[y+yPlus][x+xPlus]); return 1; } else{ return 0; } } char enc_alphabetCheck(char letter){ // function to make sure that letter wraps around if(letter=='z'){ return 'a'; } else{ return letter+1; } } void enc_compare(char word[LENGTH]){ char user_word[LENGTH]; int condition = FALSE; while(condition == FALSE){ printf("\nTry to find the correct word\n"); scanf("%s",user_word); if (strcmp(user_word,word) == 0){ printf("Congrats you have found the hidden word\n"); condition = TRUE; } } } void enc_wordInsert(char grid[GRIDSIZE][GRIDSIZE], char word[LENGTH], int size, int row){ int cnt; for(cnt=0; cnt<size; cnt++){ grid[row][cnt+1]=word[cnt]; } } void enc_gridInit(char grid[GRIDSIZE][GRIDSIZE]){ int cntW, cntH; for (cntH=0; cntH<GRIDSIZE; cntH++){ for (cntW=0; cntW<GRIDSIZE; cntW++){ if ((cntH == 0) || (cntH == (GRIDSIZE-1))){ grid[cntH][cntW] = '_'; } else if ((cntW==0) || (cntW == (GRIDSIZE-1))){ grid[cntH][cntW] = '|'; } else{ grid[cntH][cntW]=' '; } } } } void enc_printGrid(char grid[GRIDSIZE][GRIDSIZE]){ int cntW, cntH; for (cntH=0; cntH<GRIDSIZE; cntH++){ for (cntW=0; cntW<GRIDSIZE; cntW++){ printf("%c", grid[cntH][cntW]); } printf("\n"); } } void enc_shufle(char word[LENGTH], int size){ int game ; game = rand()%3; switch (game){ case 0: printf("we are going to enc_change a enc_vowel\n\n"); enc_change(word, size, game); break; case 1 : printf("we are going to enc_change a enc_constant\n\n" ); enc_change(word, size, game); break; case 2 : printf("we are going to switch the whole row\n\n" ); enc_changeRow(word, size); break; } } void enc_change(char word[LENGTH], int size, int game){ int condition=TRUE, letter, i; char c; do { if (game == 0){ letter = rand()%size; /* pick random letter*/ if(enc_isenc_vowel(word[letter])){ /* see if the letter is a enc_vowel*/ if((c=enc_vowel()) != word[letter]){ /* see if the enc_vowel is different of the on I had */ for (i=0; i<size; i++){ if (word[i] == word[letter]){ /* I want to check if there are more */ word[i] = c; /* than one same letters in my initial word */ condition = FALSE; } } } } } else if (game == 1 ){ letter = rand()%size; /* same here */ if(enc_isenc_vowel(word[letter]) == 0){ if((c=enc_constant()) != word[letter]){ for (i=0; i<size; i++){ if (word[i] == word[letter]){ word[i] = c; condition = FALSE; } } } } } } while (condition); } void enc_changeRow(char word[LENGTH], int size){ int shift, i; shift = rand()%ALPHABET; for (i=0; i<size; i++){ word[i] = word[i] - shift; if ((int)word[i] < (int) 'a'){ word[i] = word[i] + ALPHABET; } } } int enc_isenc_vowel(char c){ c=tolower(c); if ((c=='a') || (c=='e') || (c=='u') || (c=='o') || (c=='i')){ return 1; } else{ return 0; } } char enc_vowel(){ char letter[] = {'a','e','i','o','u'}; return letter[rand()%5]; } char enc_constant(){ char letter[] = {'b','c','d','f','g','h','j','k','l','m','n','p','q', 'r','s','t','v','w','x','y','z'}; return letter[rand()%21]; }
true
4727b944c1a8f828f3747887f8774277705ca182
C
aadamsaleem/Data-Structures-Using-C
/sorting Techniques/MERGEREC.C
UTF-8
1,013
3.71875
4
[]
no_license
/* Implement Merge Sort through Recursion */ #include<stdio.h> #include<conio.h> #define MAX 20 int array[MAX]; void merge(int low, int mid, int high ) { int temp[MAX]; int i = low; int j = mid +1 ; int k = low ; while( (i <= mid) && (j <=high) ) { if (array[i] <= array[ j]) temp[k++] = array[i++] ; else temp[k++] = array[ j++] ; } while( i <= mid ) temp[k++]=array[i++]; while( j <= high ) temp[k++]=array[j++]; for (i= low; i <= high ; i++) array[i]=temp[i]; } void merge_sort(int low, int high ) { int mid; if ( low != high ) { mid = (low+high)/2; merge_sort( low , mid ); merge_sort( mid+1, high ); merge(low, mid, high ); } } void main() { int i,n; clrscr(); printf ("\nEnter the number of elements :"); scanf ("%d",&n); for (i=0;i<n;i++) { printf ("\nEnter element %d :",i+1); scanf ("%d",&array[i]); } printf ("\nUnsorted list is :\n"); for ( i = 0 ; i<n ; i++) printf ("%d", array[i]); merge_sort( 0, n-1); printf ("\nSorted list is :\n"); for ( i = 0 ; i<n ; i++) printf ("%d", array[i]); getch(); }
true
db616c2a1e929f2e5283ad930583d7e2ca8e2720
C
kushagratandon1997/DSA-CODES
/DSA_LAB_8_part_b.c
UTF-8
5,319
3.484375
3
[]
no_license
#include<stdio.h> #include<stdlib.h> int truck_on_road[100],r=-1; /*array for trucks on road*/ int truck_in_garage[100],days_of_stay[100]; /* circular queue 1 for truck in garage and circular queue 2 for days of stay of truck in garage*/ int front=0,rear=-1,truck,c; int charge(); int garage_empty(); void entry_on_road(); int entry_in_garage(); void exiting_road(); void exiting_garage(); void display_road_truck(); void display_garage_truck(); int main() { int menu,choice,i; char j; printf(" \nWelcome, to Truck Operations using Circular Queue Implementation \n\n "); printf("\nEnter the charge for stay of truck in the garage : "); scanf("%d",&c); do { printf("\nEnter the choice:\n"); printf("1. Enter the truck on road\n2. Enter the truck in the garage\n3. Exit the truck from garage\n4. Show trucks on garage/road\n"); scanf("%d",&choice); switch(choice) { case 1: { entry_on_road(); break; } case 2: { i=entry_in_garage(); if(i==1) exiting_road(); break; } case 3: { exiting_garage(); break; } default: { printf("Enter the choice:\n"); printf("\n1. The trucks in garage \n2. The trucks on road\n"); scanf("%d",&menu); if(menu==1) display_garage_truck(); else if(menu==2) display_road_truck(); break; } } printf("Do you want to continue ? (y/n) : "); scanf("%s",&j); printf("\n"); } while(j=='y'); return 0; } int charge(int d) { return d*c; } int garage_empty() { if(rear<front) return 1; else return 0; } void entry_on_road() { int id; printf("\nEnter the truck id for entry on road : "); scanf("%d",&id); r++; truck_on_road[r]=id; } int entry_in_garage() { int id,t,j,days,temp1,temp2,count=0; if(r==-1) printf("\n Sorry, The road is empty "); else { printf("\nEnter the trucks id which has to move from road to garage : "); scanf("%d",&id); for(t=0;t<=r;t++) if(truck_on_road[t]==id) { count++; } if(count==0) { printf("\nTruck id -> %d is not present on the road\n",id); return 0; } else { printf("\nEnter the number of days the truck is going to stay in garage : "); scanf("%d",&days); for(t=0;t<=r;t++) { if(truck_on_road[t]==id) { truck=t; rear++; truck_in_garage[rear]=id; days_of_stay[rear]=days; break; } } for(t=front;t<rear;t++) /*swapping of trucks in garage according to days of stay in ascending order*/ { for(j=t+1;t<=rear;j++) { if(days_of_stay[j]<days_of_stay[t]) { temp1=days_of_stay[j]; temp2=truck_in_garage[j]; days_of_stay[j]=days_of_stay[t]; truck_in_garage[j]=truck_in_garage[t]; days_of_stay[t]=temp1; truck_in_garage[t]=temp2; } } } return 1; } } } void exiting_road() { int t; printf("\nTruck id -> %d is moving in the garage from road \n",truck_on_road[truck]); for(t=truck+1;t<=r;t++) truck_on_road[t-1]=truck_on_road[t]; /* here the swapping takes place in the array of trucks on road one place forward after one truck moves into the garage*/ r--; } void exiting_garage() { int id,pay,i,count=0; if(garage_empty()==1) printf("\n Garage is empty !\n "); else { printf("\nEnter the truck id which wants to exit from garage : "); scanf("%d",&id); for(i=front;i<=rear;i++) { if(truck_in_garage[i]==id) count++; } if(count==0) printf("\nSorry, Truck id -> %d is not present in the garage\n",id); else { if(truck_in_garage[front]==id) { pay=charge(days_of_stay[front]); printf("\nThe charge for stay of truck id -> %d is Rs. %d\n",id,pay); printf("\nTruck id -> %d has successfully moved out of the garage\n",id); front++; } else printf("\nTruck id -> %d cannot be moved out of the garage \n",id); } } } void display_road_truck() { int t; for(t=0;t<=r;t++) printf("\nTrucks present on the road are : %d\n",truck_on_road[t]); } void display_garage_truck() { int t; for(t=front;t<=rear;t++) printf("\nTrucks present in the garage are : %d\n",truck_in_garage[t]); }
true
89b3ac2c9ab13c5518f82123147f23f225c0067a
C
gazfaris/dot_julia
/packages/Ccluster/i80C5/local/include/ccluster/numbers/compRat.h
UTF-8
3,550
2.71875
3
[]
no_license
/* ************************************************************************** */ /* Copyright (C) 2018 Remi Imbach */ /* */ /* This file is part of Ccluster. */ /* */ /* Ccluster is free software: you can redistribute it and/or modify it under */ /* the terms of the GNU Lesser General Public License (LGPL) as published */ /* by the Free Software Foundation; either version 2.1 of the License, or */ /* (at your option) any later version. See <http://www.gnu.org/licenses/>. */ /* ************************************************************************** */ #ifndef COMPRAT_H #define COMPRAT_H #ifdef NUMBERS_INLINE_C #define NUMBERS_INLINE #else #define NUMBERS_INLINE static __inline__ #endif #include "numbers/realRat.h" #ifdef __cplusplus extern "C" { #endif typedef struct { realRat real; realRat imag; } compRat; typedef compRat compRat_t[1]; typedef compRat * compRat_ptr; #define compRat_realref(X) (&(X)->real) #define compRat_imagref(X) (&(X)->imag) /* memory managment */ NUMBERS_INLINE void compRat_init(compRat_t x) { realRat_init(compRat_realref(x)); realRat_init(compRat_imagref(x)); } NUMBERS_INLINE void compRat_clear(compRat_t x) { realRat_clear(compRat_realref(x)); realRat_clear(compRat_imagref(x)); } /* members access */ NUMBERS_INLINE realRat_ptr compRat_real_ptr(compRat_t x) { return compRat_realref(x); } NUMBERS_INLINE realRat_ptr compRat_imag_ptr(compRat_t x) { return compRat_imagref(x); } NUMBERS_INLINE void compRat_get_real(realRat_t re, const compRat_t x) { realRat_set(re, compRat_realref(x)); } NUMBERS_INLINE void compRat_get_imag(realRat_t im, const compRat_t x) { realRat_set(im, compRat_imagref(x)); } /* setting */ NUMBERS_INLINE void compRat_set_2realRat(compRat_t x, const realRat_t re, const realRat_t im) { realRat_set(compRat_realref(x), re); realRat_set(compRat_imagref(x), im); } NUMBERS_INLINE void compRat_set_sisi(compRat_t x, slong preal, ulong qreal, slong pimag, ulong qimag) { realRat_set_si(compRat_realref(x), preal, qreal); realRat_set_si(compRat_imagref(x), pimag, qimag); } NUMBERS_INLINE int compRat_set_str (compRat_t x, const char * strReN, const char * strReD, const char * strImN, const char * strImD, int b){ if (realRat_set_str(compRat_realref(x), strReN, strReD, b) == 0) return realRat_set_str(compRat_imagref(x), strImN, strImD, b); else return -1; } NUMBERS_INLINE void compRat_set(compRat_t dest, const compRat_t src) { realRat_set(compRat_realref(dest), compRat_realref(src)); realRat_set(compRat_imagref(dest), compRat_imagref(src)); } /* geometric operations */ /* sets dest to abs(x.real-y.real) + i*abs(x.imag-y.imag) */ void compRat_comp_distance( compRat_t dest, const compRat_t x, const compRat_t y ); /* comparisons */ /* returns negative if x.real<y.real or (x.real=y.real and x.imag<y.imag) */ /* 0 if x.real=y.real and x.imag=y.imag */ /* positive if x.real>y.real or (x.real=y.real and x.imag>y.imag) */ int compRat_cmp (const compRat_t x, const compRat_t y); /* printing */ void compRat_fprint(FILE * file, const compRat_t x); NUMBERS_INLINE void compRat_print(const compRat_t x) { compRat_fprint(stdout, x); } #ifdef __cplusplus } #endif #endif
true
2a91eb05b1b0fb3c2c9de02fb8067b895c396e96
C
alanamiyai/MTP
/aula20170921/iif3.c
UTF-8
366
3.390625
3
[]
no_license
#include <stdio.h> #include <conio.h> int main() { double fat, n; printf("Insira um valor para o qual deseja calcular seu fatorial: "); scanf("%lf", &n); if (n <= 20) { for(fat = 1; n > 1; n = n - 1) fat = fat * n; printf("\nFatorial calculado: %lf", fat); } else printf("Dados invalidos!"); getche (); return 0; }
true
1216fc30ae3d05234668ed198968fc97e0447675
C
cfkcoder/CODE
/Project26/Project26/text.c
ISO-8859-7
2,577
3.375
3
[]
no_license
#include <stdio.h> #include <malloc.h> #include <stdbool.h> #include <assert.h> #pragma warning(disable:4996) #define ElemType int typedef struct LinkQueueNode { ElemType data; struct LinkQueueNode *link; }LinkQueueNode; typedef struct LinkQueue{ struct LinkQueueNode *head; struct LinkQueueNode *tail; }LinkQueue; void LinkQueueInit(LinkQueue *pq); void LinkQueueEn(LinkQueue *pq,ElemType x); void LinkQueueDe(LinkQueue *pq); ElemType LinkQueueFront(LinkQueue *pq); bool LinkQueueEmpty(LinkQueue *pq); int LinkQueueSize(LinkQueue *pq); void LinkQueueDestroy(LinkQueue *pq); void LinkQueueShow(LinkQueue *pq); ////////////////////////////////////////////////////////////////////////////////////// void LinkQueueInit(LinkQueue *pq) { assert(pq != NULL); pq->head =pq->tail= NULL; } void LinkQueueEn(LinkQueue *pq,ElemType x) { assert(pq != NULL); LinkQueueNode *node = (LinkQueueNode*)malloc(sizeof(LinkQueueNode)); assert(node != NULL); node->data = x; node->link = NULL; if (pq->head ==NULL) { pq->head = pq->tail = node; } else { pq->tail->link = node; pq->tail = node; } } void LinkQueueDe(LinkQueue *pq) { assert(pq != NULL); if (pq->head!=NULL) { if (pq->head == pq->tail) { pq->head = pq->tail = NULL; } else { LinkQueueNode *p = pq->head; pq->head = p->link; free(p); } } } ElemType LinkQueueFront(LinkQueue *pq) { assert(pq != NULL); if (pq->head != NULL) { return pq->head->data; } } int LinkQueueSize(LinkQueue *pq) { assert(pq != NULL); LinkQueueNode *p = pq->head; int size = 0; while (p) { size++; p = p->link; } return size; } bool LinkQueueEmpty(LinkQueue *pq) { assert(pq != NULL); return pq->head == NULL; } void LinkQueueShow(LinkQueue *pq) { assert(pq != NULL); LinkQueueNode *p = pq->head; while (p) { printf("%d ", p->data); p = p->link; } printf("\n"); } void LinkQueueDestroy(LinkQueue *pq) { assert(pq != NULL); LinkQueueNode *p = pq->head; if (pq->head == pq->tail) { pq->head = pq->tail = NULL; } else { while (p) { pq->head = p->link; free(p); p = pq->head; } } } int main() { LinkQueue Q; LinkQueueInit(&Q); LinkQueueEn(&Q,1); LinkQueueEn(&Q, 2); LinkQueueEn(&Q, 3); LinkQueueEn(&Q, 4); LinkQueueEn(&Q, 5); LinkQueueDe(&Q); LinkQueueShow(&Q); int front_val = 0; while (!LinkQueueEmpty(&Q)) { front_val = LinkQueueFront(&Q); printf("%d .\n",front_val); LinkQueueDe(&Q); } /*LinkQueueDe(&Q); LinkQueueFront(&Q); LinkQueueSize(&Q);*/ LinkQueueDestroy(&Q); return 0; }
true
550abeda43d1685354a488c01b477c8fb0dbca48
C
bianca-bouleanu/Hash-Table
/Hash-Table/functions.c
UTF-8
6,533
3.765625
4
[]
no_license
/** * Tema 1 SO - Hash table * * Copyright (C) 2018, Oana-Bianca Bouleanu 333CA * <oana.bouleanu@stud.acs.upb.ro> * * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "hash.h" #include "utils.h" #include "functions.h" #define false 0 #define true 1 /* Functia aloca memorie pentru hash table, mai exact, size * bucket-uri. * In caz de succes, returneaza hash-ul creat, altfel, o eroare. */ HashTable *createHashTable(int size) { HashTable *hashTable = malloc(sizeof(HashTable)); if (hashTable == NULL) return NULL; hashTable->size = size; hashTable->buckets = calloc(size, sizeof(HashNode *)); if (hashTable->buckets == NULL) return NULL; return hashTable; } /* Functia insereaza cuvantul word in hash table-ul hashTable. * In caz de succes, returneaza 1, daca word exista deja in hash, * returneaza 2, iar survine o eroare de alocare a memoriei, -1. */ int insert(char *word, HashTable *hashTable) { HashNode *insertIndexNode; HashNode *newNode; unsigned int index; char *newWord; index = hash(word, hashTable->size); newNode = malloc(sizeof(HashNode)); if (newNode == NULL || strlen(word) == 0) return -1; if (find(word, hashTable)) return 2; newWord = malloc(strlen(word) + 1); if (newNode == NULL) return -1; strcpy(newWord, word); newNode->word = newWord; newNode->next = NULL; insertIndexNode = hashTable->buckets[index]; if (insertIndexNode == NULL) hashTable->buckets[index] = newNode; else { for ( ; insertIndexNode->next != NULL; insertIndexNode = insertIndexNode->next) ; insertIndexNode->next = newNode; } return 1; } /* Functia sterge cuvantul target din hash table-ul * hashTable, daca acesta exista. * In caz de succes, se va returna valoarea 1, * daca nu exista cuvantul, 2, altfel, -1. */ int remove_word(char *target, HashTable *hashTable) { HashNode *next; HashNode *currentNode; HashNode *previousNode; unsigned int index; if (!find(target, hashTable)) return 2; index = hash(target, hashTable->size); if (hashTable->buckets[index] != NULL) { if (strcmp(hashTable->buckets[index]->word, target) == 0) { next = hashTable->buckets[index]->next; free(hashTable->buckets[index]->word); free(hashTable->buckets[index]); hashTable->buckets[index] = NULL; hashTable->buckets[index] = next; return 1; } else { currentNode = hashTable->buckets[index]; previousNode = hashTable->buckets[index]; while (currentNode->next != NULL) { previousNode = currentNode; currentNode = currentNode->next; if (strcmp(currentNode->word, target) == 0) { previousNode->next = currentNode->next; free(currentNode->word); free(currentNode); currentNode = NULL; return 1; } } } } return -1; } /* Functia cauta cuvantul target in hash table-ul hashTable. * In caz acesta se gaseste in hash, se returneaza true, in caz * contrar, false. */ bool find(char *target, HashTable *hashTable) { HashNode *currentNode; unsigned int i = 0; for (i = 0; i < hashTable->size; i++) { if (hashTable->buckets[i] != NULL) { if (strcmp(hashTable->buckets[i]->word, target) == 0) return true; currentNode = hashTable->buckets[i]; while (currentNode->next != NULL) { currentNode = currentNode->next; if (strcmp(currentNode->word, target) == 0) return true; } } } return false; } /* Functia printeaza bucket-ul cu numarul index din hash table-ul * hashTable, in fisierul file sau la consola, daca acesta este * NULL. * In caz de succes, functia intoarce 1, altfel, -1. */ int print_bucket(HashTable *hashTable, int index, char *file) { HashNode *printNode; FILE *fp; printNode = hashTable->buckets[index]; if (printNode == NULL) return 1; if (file != NULL) { fp = fopen(file, "a"); if (fp == NULL) return -1; } while (printNode != NULL) { if (file != NULL) fprintf(fp, "%s ", printNode->word); else printf("%s ", printNode->word); printNode = printNode->next; } if (file != NULL) { fprintf(fp, "\n"); fclose(fp); } else printf("\n"); return 1; } /* Functia printeaza intregul hash table hashTable in fisierul file * sau la consola, daca acesta este NULL. * In caz de succes, functia intoarce 1, altfel, -1. */ int print_hashTable(HashTable *hashTable, char *file) { HashNode *printNode; FILE *fp; unsigned int i = 0; if (file != NULL) { fp = fopen(file, "a"); if (fp == NULL) return -1; } for (i = 0; i < hashTable->size; i++) { printNode = hashTable->buckets[i]; while (printNode != NULL) { if (file != NULL) fprintf(fp, "%s ", printNode->word); else printf("%s ", printNode->word); printNode = printNode->next; } if (hashTable->buckets[i] != NULL) { if (file != NULL) fprintf(fp, "\n"); else printf("\n"); } } if (file != NULL) { fprintf(fp, "\n"); fclose(fp); } else printf("\n"); return 1; } /* Functia returneaza un nou hashTable cu numar bucket-uri * dublat/injumatatit fata de hash-ul primit ca parametru. */ HashTable *resize(HashTable *hashTable, char *size_modification) { HashTable *resizedHashTable; HashNode *t; HashNode *next; unsigned int i = 0; if (strcmp(size_modification, "double") == 0) resizedHashTable = createHashTable(hashTable->size * 2); else if (strcmp(size_modification, "halve") == 0) resizedHashTable = createHashTable(hashTable->size / 2); for (i = 0; i < hashTable->size; i++) { if (hashTable->buckets[i] != NULL) { t = hashTable->buckets[i]; insert(t->word, resizedHashTable); t = t->next; while (t != NULL) { next = t->next; insert(t->word, resizedHashTable); free(t->word); free(t); t = next; } free(hashTable->buckets[i]->word); free(hashTable->buckets[i]); } } free(hashTable->buckets); free(hashTable); return resizedHashTable; } /* Functia distruge hash-ul hashTable, eliberand memoria alocata * pentru acesta. * Va fi returnata valoarea 1. */ int clear(HashTable *hashTable) { unsigned int i = 0; HashNode *t; HashNode *next; for (i = 0; i < hashTable->size; i++) { if (hashTable->buckets[i] != NULL) { t = hashTable->buckets[i]; t = t->next; while (t != NULL) { next = t->next; free(t->word); free(t); t = next; } free(hashTable->buckets[i]->word); free(hashTable->buckets[i]); } } free(hashTable->buckets); free(hashTable); return 1; }
true
07d98dc4d7ba597c6418252eea6bd526cd87a220
C
Ebloin/orazio_logger
/test_queue.c
UTF-8
282
3.390625
3
[]
no_license
#include <stdio.h> #include "queue.h" int main() { queue_t* c = createQueue(); int a[10] = {0,1,2,3,4,5,6,7,8,9}; int i; for (i=0; i<10; i++) { enqueue(c, &a[i]); } for (i=0; i<10; i++) { int* e = dequeue(c); printf("dequeued %d\n", *e); } return 0; }
true