language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* Testing C types (char, numbers, addresses). */ #include <stdio.h> int test_types() { long x; double y; short z; char a; char* b; } void test_division() { /* Integer arithmic is truncated to zero. */ int z = 5 / 9; float y = 5.0 / 9.0; printf("%d \t %f \n", z, y); /* Dividing integers by floats. */ int a = 5; int a_ = 9; float b = 9.0; float c = a / b; int d = a / b; /* Truncated... */ float e = a / 9; printf("%.1f \t %d \t %.1f \n", c, d, e); } void test_assignment() { /* An assignment statement returns left hand value. */ int a; printf("%d", a=5); } int main() { test_division(); }
C
// For better backtrace implementation #define __USE_GNU #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <execinfo.h> #define BUF_SIZE 1000 #define TRACEDEPTH 16 void builtin_gcc_trace( void){ printf("Builtin gcc return addresses:\n"); printf("Frame 0: PC=%p\n", __builtin_return_address(0)); printf("Frame 1: PC=%p\n", __builtin_return_address(1)); printf("Frame 2: PC=%p\n", __builtin_return_address(2)); printf("Frame 3: PC=%p\n", __builtin_return_address(3)); } static void signal_error(int sig, siginfo_t *si, void *ptr){ void *trace[TRACEDEPTH]; size_t trace_size, i; char **trace_msg; builtin_gcc_trace(); trace_size = backtrace(trace, TRACEDEPTH); trace_msg = backtrace_symbols( trace, trace_size); printf("Backtrace symbols:\n"); for( i=0; i<trace_size; i++) printf("%s\n", trace_msg[i]); free( trace_msg); exit( 1); } void fill_random_ascii_buffer(char *buffer,size_t size){ int i; for(i=0;i<size;i++){ buffer[i]=32+(int)(drand48()*(127.0-32.0)); } free( buffer); } int main(int argc, char *argv[]){ const char *buf; int j=0; char *message = "Program finished"; struct sigaction sigact; sigset_t sigset; sigact.sa_flags = SA_SIGINFO; sigact.sa_sigaction = signal_error; sigemptyset(&sigact.sa_mask); sigaction(SIGSEGV, &sigact, 0); sigemptyset(&sigset); buf=malloc(BUF_SIZE*sizeof(char)); if(buf==NULL){ printf("Buffer allocation failed!\n"); exit(1); } fill_random_ascii_buffer(buf,BUF_SIZE); for(j=0;j<BUF_SIZE;j++){ putchar(buf[j]); if(j%50==0 && j>0){ putchar('\n'); } } putchar('\n'); free( buf); puts(message); return(0); }
C
/* Program: Fill and display personal data Example of bitfield Compile: gcc main.c -o personal_data ------------------------------------- Run: ./personal_data */ #include <stdio.h> #include <string.h> typedef struct { unsigned is_male : 1; unsigned age : 7; unsigned is_healthy : 1; unsigned working_days: 3; unsigned hours_a_day : 4; } person_t; int main() { person_t john_doe; john_doe.is_male = 1; john_doe.age = 25; john_doe.is_healthy = 1; john_doe.working_days = 5; john_doe.hours_a_day = 8; char *gender = john_doe.is_male == 1 ? "Male" : "Female"; char *health = john_doe.is_healthy == 1 ? "Yes" : "No"; printf("Person size: %12li bytes\n", sizeof(john_doe)); printf("Gender: %20s\n", gender); printf("Is healthy: %15s\n", health); printf("Age: %21i\n", john_doe.age); printf("Working days in a week: %i\n", john_doe.working_days); printf("Hours per day: %10i\n", john_doe.hours_a_day); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* h_cast.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jmeier <jmeier@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/11/28 10:59:06 by jmeier #+# #+# */ /* Updated: 2019/10/17 18:46:09 by jmeier ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" void h_int_cast(va_list arg, t_all *f) { char *prec_pad; char *width_pad; char *prefix; short output; output = (short)va_arg(arg, void*); prec_pad = sign_prec_parse((long long)output, f); width_pad = sign_width_parse((long long)output, f); prefix = sign_prefix_parse((int)output, f); if (f->dash == 1) { ft_putstr_fd(prefix, f->fd); ft_putstr_fd(prec_pad, f->fd); ft_putnbrf(output, f->fd); ft_putstr_fd(width_pad, f->fd); } else { f->zero == 0 ? ft_putstr_fd(width_pad, f->fd) : 0; ft_putstr_fd(prefix, f->fd); f->zero == 1 && f->prec_flag == 0 ? ft_putstr_fd(width_pad, f->fd) : 0; ft_putstr_fd(prec_pad, f->fd); ft_putnbrf(output, f->fd); } supa_free(prec_pad, width_pad, prefix); } void h_oct_cast(va_list arg, t_all *f) { char *prec_pad; char *width_pad; char *prefix; unsigned short output; output = (unsigned short)va_arg(arg, void*); prec_pad = prec_parse((unsigned long long)output, f, 8); width_pad = width_parse((unsigned long long)output, f, 8); prefix = prefix_parse((unsigned int)output, 8, 0, f); if (f->dash == 1) { ft_putstr_fd(prefix, f->fd); ft_putstr_fd(prec_pad, f->fd); ft_putoct((unsigned long long)output, f->fd); ft_putstr_fd(width_pad, f->fd); } else { f->zero == 0 ? ft_putstr_fd(width_pad, f->fd) : 0; ft_putstr_fd(prefix, f->fd); f->zero == 1 && f->prec_flag == 0 ? ft_putstr_fd(width_pad, f->fd) : 0; ft_putstr_fd(prec_pad, f->fd); ft_putoct((unsigned long long)output, f->fd); } supa_free(prec_pad, width_pad, prefix); } void h_hex_cast(va_list arg, t_all *f) { char *prec_pad; char *width_pad; char *prefix; unsigned short output; output = (unsigned short)va_arg(arg, void*); prec_pad = prec_parse((unsigned long long)output, f, 16); width_pad = width_parse((unsigned long long)output, f, 16); prefix = prefix_parse((unsigned int)output, 16, 1, f); if (f->dash == 1) { ft_putstr_fd(prefix, f->fd); ft_putstr_fd(prec_pad, f->fd); ft_puthex((unsigned long long)output, f->fd); ft_putstr_fd(width_pad, f->fd); } else { f->zero == 0 ? ft_putstr_fd(width_pad, f->fd) : 0; ft_putstr_fd(prefix, f->fd); f->zero == 1 && f->prec_flag == 0 ? ft_putstr_fd(width_pad, f->fd) : 0; ft_putstr_fd(prec_pad, f->fd); ft_puthex((unsigned long long)output, f->fd); } supa_free(prec_pad, width_pad, prefix); } void h_lhex_cast(va_list arg, t_all *f) { char *prec_pad; char *width_pad; char *prefix; unsigned short output; output = (unsigned short)va_arg(arg, void*); prec_pad = prec_parse((unsigned long long)output, f, 16); width_pad = width_parse((unsigned long long)output, f, 16); prefix = prefix_parse((unsigned int)output, 16, 0, f); if (f->dash == 1) { ft_putstr_fd(prefix, f->fd); ft_putstr_fd(prec_pad, f->fd); ft_putlhex((unsigned long long)output, f->fd); ft_putstr_fd(width_pad, f->fd); } else { f->zero == 0 ? ft_putstr_fd(width_pad, f->fd) : 0; ft_putstr_fd(prefix, f->fd); f->zero == 1 && f->prec_flag == 0 ? ft_putstr_fd(width_pad, f->fd) : 0; ft_putstr_fd(prec_pad, f->fd); ft_putlhex((unsigned long long)output, f->fd); } supa_free(prec_pad, width_pad, prefix); } void h_uint_cast(va_list arg, t_all *f) { char *prec_pad; char *width_pad; char *prefix; unsigned short output; output = (unsigned short)va_arg(arg, void*); prec_pad = prec_parse((unsigned long long)output, f, 10); width_pad = width_parse((unsigned long long)output, f, 10); prefix = prefix_parse((unsigned int)output, 10, 0, f); if (f->dash == 1) { ft_putstr_fd(prefix, f->fd); ft_putstr_fd(prec_pad, f->fd); ft_putunbr_base_fd(output, 10, f->fd); ft_putstr_fd(width_pad, f->fd); } else { f->zero == 0 ? ft_putstr_fd(width_pad, f->fd) : 0; ft_putstr_fd(prefix, f->fd); f->zero == 1 && f->prec_flag == 0 ? ft_putstr_fd(width_pad, f->fd) : 0; ft_putstr_fd(prec_pad, f->fd); ft_putunbr_base_fd(output, 10, f->fd); } supa_free(prec_pad, width_pad, prefix); }
C
/*We assume that we have a polynomial with 5 arguments (N variable) The coefficients of this polynomial are in T array {1,-2,2,3,-5}. So the polynomial is T = x^4-2x^3+2x^2+3x-5. The program prompts the user to give a value to variable x (e.g. r=7) to compute the division between T and x-r. Prints the coefficients of the quotient polynomial and the remainder.*/ #include <stdio.h> #define N 5 main(){ double T[]={1,-2,2,3,-5}; /* x^4-2x^3+2x^2+3x-5*/ double R[N-1]; double r; /*value to variable x*/ double P; /* the remainder */ int i; printf("Give a value to x variable: "); scanf("%lf",&r); P=T[0]; R[0]=T[0]; for(i=1;i<N;i++) { P=P*r+T[i]; R[i]=P; } printf("\nRemainder = %f\n",P); printf("\n The coefficients of the quotient are:\n"); for(i=0;i<N-1;i++) printf(" %f",R[i]); printf("\n"); }
C
#include "signals.h" /** * current_handler_signal - check the current handler * Return: NULL or the pointer the current handler */ void (*current_handler_signal(void))(int) { void (*handler)(int); handler = signal(SIGINT, NULL); signal(SIGINT, handler); return (handler); }
C
#include "dominion.h" #include "dominion_helpers.h" #include <string.h> #include <stdlib.h> #include <stdio.h> #include <assert.h> #include "rngs.h" #define TEST_ALERT 0 void testDiscard() { struct gameState* G = malloc(sizeof(struct gameState)); int k[10] = {adventurer, council_room, feast, gardens, mine, remodel, smithy, village, baron, great_hall}; int init_success = -1; int i; for (i = 2; i < 5; i++) { //int player = i-2; printf("Testing %d player game\n",i); init_success = initializeGame(i, k, 1, G); if (init_success != -1) { printf("Game initialized successfully\n"); } else { printf("Game failed to initialize, exiting\n"); exit(1); } int j; for(j=0;j<i;j++) { printf("Testing player %d\n",j+1); int discarded = -1; int pre_hand_count = 0; pre_hand_count = G->handCount[j]; int post_hand_count = 0; discarded = discardCard(1,j,G,0); post_hand_count = G->handCount[j]; if(pre_hand_count < post_hand_count) { printf("Test 1 passed\n"); } else { printf("Test 1 failed\n"); } if(pre_hand_count-1 == post_hand_count) { printf("Test 2 passed\n"); } else { printf("Test 2 failed\n"); } G->handCount[j]++; G->hand[j][G->handCount[j]-1] = copper; int pre_hand_pos = G->hand[j][G->handCount[j]-1]; int post_hand_pos = 0; if(pre_hand_pos != -1) { printf("Test 3 passed\n"); } else { printf("Test 3 failed\n"); } discardCard(G->handCount[j]-1,j,G,0); post_hand_pos = G->hand[j][G->handCount[j]-1]; if(pre_hand_pos != post_hand_pos) { printf("Test 4 passed\n"); } else { printf("Test 4 failed\n"); } if(post_hand_pos == -1) { printf("Test 5 passed\n"); } else { printf("Test 5 failed\n"); } //assert } } } int main() { testDiscard(); return 0; }
C
/*** Author : Group 17 * Rahul Varshneya * Anvit Singh Tawar * Shivam Agarwal * Alankar Saxena Date Sun 08 April 2012 02:42:38 PM IST gait.c : File contains various walking and turning motion functions for the hexapod Please include gait.h file to call function from this file */ /******************************************************************************** Copyright (c) 2010, ERTS Lab IIT Bombay erts@cse.iitb.ac.in -*- c -*- All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holders nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Source code can be used for academic purpose. For commercial use permission form the author needs to be taken. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Software released under Creative Commence cc by-nc-sa licence. For legal information refer to: http://creativecommons.org/licenses/by-nc-sa/3.0/legalcode ********************************************************************************/ #include "hexapod_macro.h" #include "hexapod_basic.h" #include "hexapod.h" extern double movementScaling; /** Tripod gait moves the hexapod in the direction dir1 for steps. Three legs forming a tripod move first then the other three legs move Used for normal gait of the hexapod @param dir1 : Direction of motion @param steps : number of steps */ void tripod_gait(unsigned char dir1, unsigned char steps) { unsigned char dir3 = ((dir1 + 1) % 6) + 1; unsigned char dir5 = ((dir3 + 1) % 6) + 1; unsigned char dir2 = 7 - dir5; unsigned char dir4 = 7 - dir3; unsigned char dir6 = 7 - dir1; unsigned char step_forward = 70; unsigned char step_side = 50; unsigned char lift = 40; int delay_time = 150;//TWO_HUNDRED_FIFTY_MSEC; // The following is done to keep dir3 to the left of dir1 and dir5 to the right of dir1 if(dir1%2 == 0) { swap(&dir2, &dir4); swap(&dir3, &dir5); } while (steps-- > 0) { //picking up even tripod angle(dir2, MOTOR_B, lift); angle(dir4, MOTOR_B, lift); angle(dir6, MOTOR_B, lift); delay(delay_time); //moving body on odd tripod angle(dir1, MOTOR_C, 90); angle(dir3, MOTOR_A, 90); angle(dir5, MOTOR_A, 90); //moving legs even forward in air angle(dir2, MOTOR_A, 90 - step_side); angle(dir4, MOTOR_A, 90 + step_side); angle(dir6, MOTOR_C, 90 - step_forward); delay(delay_time); //putting down even legs angle(dir2, MOTOR_B, 90); angle(dir4, MOTOR_B, 90); angle(dir6, MOTOR_B, 90); delay(HUNDRED_MSEC); //picking up odd legs angle(dir1, MOTOR_B, lift); angle(dir3, MOTOR_B, lift); angle(dir5, MOTOR_B, lift); delay(delay_time); //moving the odd legs in air angle(dir1, MOTOR_C, 90 + step_forward); angle(dir3, MOTOR_A, 90 - step_side); angle(dir5, MOTOR_A, 90 + step_side); //moving the body forward on even tripod angle(dir2, MOTOR_A, 90); angle(dir4, MOTOR_A, 90); angle(dir6, MOTOR_C, 90); delay(delay_time); //puuting down odd tripod angle(dir1, MOTOR_B, 90); angle(dir3, MOTOR_B, 90); angle(dir5, MOTOR_B, 90); delay(HUNDRED_MSEC); } } /** Tripod Gait 2 : Better suited for uneven terrain @param dir1 : Direction of motion @param steps : number of steps */ void tripod_gait_2(unsigned char dir1, unsigned char steps) { unsigned char dir3 = ((dir1 + 1) % 6) + 1; unsigned char dir5 = ((dir3 + 1) % 6) + 1; unsigned char dir2 = 7 - dir5; unsigned char dir4 = 7 - dir3; unsigned char dir6 = 7 - dir1; unsigned char step_forward = 60; unsigned char step_side = 60; unsigned char lift = 40; int delay_time = ONE_SEC; int delay_time1 = ONE_SEC; if(dir1%2 == 0) { swap(&dir2, &dir4); swap(&dir3, &dir5); } while (steps-- > 0) { //puuting down odd tripod angle(dir1, MOTOR_C, 90); angle(dir3, MOTOR_C, 90); angle(dir5, MOTOR_C, 90); angle(dir1, MOTOR_B, 90); angle(dir3, MOTOR_B, 90); angle(dir5, MOTOR_B, 90); delay(delay_time1); //picking up even tripod angle(dir2, MOTOR_B, lift); angle(dir4, MOTOR_B, lift); angle(dir6, MOTOR_B, lift); angle(dir2, MOTOR_C, 0); angle(dir4, MOTOR_C, 0); angle(dir6, MOTOR_C, 0); delay(delay_time); //moving body on odd tripod angle(dir1, MOTOR_A, 90); angle(dir3, MOTOR_A, 90); angle(dir5, MOTOR_A, 90); delay(delay_time); //moving legs even forward in air angle(dir2, MOTOR_C, 180); angle(dir4, MOTOR_C, 180); angle(dir6, MOTOR_C, 180); angle(dir2, MOTOR_A, 90 - step_side); angle(dir4, MOTOR_A, 90 + step_side); angle(dir6, MOTOR_A, 90 + step_forward); delay(delay_time); //putting down even legs angle(dir2, MOTOR_C, 90); angle(dir4, MOTOR_C, 90); angle(dir6, MOTOR_C, 90); angle(dir2, MOTOR_B, 90); angle(dir4, MOTOR_B, 90); angle(dir6, MOTOR_B, 90); delay(delay_time1); //picking up odd legs angle(dir1, MOTOR_B, lift); angle(dir3, MOTOR_B, lift); angle(dir5, MOTOR_B, lift); angle(dir1, MOTOR_C, 0); angle(dir3, MOTOR_C, 0); angle(dir5, MOTOR_C, 0); delay(delay_time); //moving the odd legs in air angle(dir1, MOTOR_C, 180); angle(dir3, MOTOR_C, 180); angle(dir5, MOTOR_C, 180); angle(dir1, MOTOR_A, 90 + step_forward); angle(dir3, MOTOR_A, 90 - step_side); angle(dir5, MOTOR_A, 90 + step_side); delay(delay_time); //moving the body forward on even tripod angle(dir2, MOTOR_A, 90); angle(dir4, MOTOR_A, 90); angle(dir6, MOTOR_A, 90); delay(delay_time); } } /** Two leg gait in which two legs are moved at a time @param dir1 : Direction of motion @param dir2 : Direction of motion @param steps : number of steps */ void two_leg_gait(unsigned char dir1, unsigned char dir2, int steps) { unsigned char legs_anticlock[] = {0,2,3,6,1,4,5}; unsigned char legs_clock[] = {0,4,1,2,5,6,3}; unsigned char dir3 = legs_anticlock[dir2]; unsigned char dir4 = legs_clock[dir1]; unsigned char dir5 = legs_clock[dir4]; unsigned char dir6= legs_anticlock[dir3]; unsigned char step_forward = 50 * movementScaling; unsigned char step_side = 40 * movementScaling; unsigned char lift = 40; int delay_time1 = FIVE_HUNDRED_MSEC; int delay_time2 = FIVE_HUNDRED_MSEC; while(steps-- > 0) { //putting down legs 5 & 6 angle(dir5, MOTOR_B, 90); angle(dir6, MOTOR_B, 90); //picking up 1 & 2 legs angle(dir1, MOTOR_B, lift); angle(dir2, MOTOR_B, lift); //delay delay(delay_time1); //moving body on legs 5 & 6 angle(dir5, MOTOR_A, 90 - step_forward); angle(dir6, MOTOR_A, 90 + step_forward); //moving 1 & 2 legs in air angle(dir1, MOTOR_A, 90 + step_forward); angle(dir2, MOTOR_A, 90 - step_forward); //delay delay(delay_time1); //putting 1 & 2 legs down angle(dir1, MOTOR_B, 90); angle(dir2, MOTOR_B, 90); //picking up 3 & 4 legs angle(dir3, MOTOR_B, lift); angle(dir4, MOTOR_B, lift); delay(delay_time1); //moving body on legs 1 & 2 angle(dir1, MOTOR_A, 90 - step_forward); angle(dir2, MOTOR_A, 90 + step_forward); //moving legs 3 & 4 in air angle(dir3, MOTOR_A, 90 - step_side); angle(dir4, MOTOR_A, 90 + step_side); delay(delay_time2); //putting down legs 3 & 4 angle(dir3, MOTOR_B, 90); angle(dir4, MOTOR_B, 90); //picking up legs 5 & 6 angle(dir5, MOTOR_B, lift); angle(dir6, MOTOR_B, lift); delay(delay_time1); //moving body on legs 3 & 4 angle(dir3, MOTOR_A, 90 + step_side); angle(dir4, MOTOR_A, 90 - step_side); //moving legs 5 & 6 in air angle(dir5, MOTOR_A, 90 + step_forward); angle(dir6, MOTOR_A, 90 - step_forward); delay(delay_time2); } } /** Tripod turn gait: turns hexapod in specified direction for specified number of cycles. Description: * There are 2 tripods. Even tripod (leg no 1, 3, 5) and odd tripod (leg no 2, 4, 6). * When even tripod moves in air, odd tripod supports the bot (are at 90 degrees). * When odd tripod moves in air, even tripod supports the bot. * This cycle repeats. @param rot_dir : Direction of rotation (one of CLOCKWISE or ANTI_CLOCKWISE) @param steps : number of steps */ void tripod_turn_gait(unsigned char rot_dir, unsigned char steps) { // making the LEG_1 as default leg for our movement // Other legs are defined wrt {@code: dir1} unsigned char dir1 = LEG_1; unsigned char dir3 = ((dir1 + 1) % 6) + 1; unsigned char dir5 = ((dir3 + 1) % 6) + 1; unsigned char dir2 = 7 - dir5; unsigned char dir4 = 7 - dir3; unsigned char dir6 = 7 - dir1; // Parameters which control motor movement. int step_side = 50 * movementScaling; // Angle by which legs are raised in air. unsigned char lift = 40; // delay time between two subsequent motion commands. int delay_time = 150; // If rotation direction is anti-clockwise rot_dir = 0 else rot_dir = 1. Adjust step_side accordingly. step_side = step_side*(1 - 2*rot_dir); // The following is done to keep dir3 to the left of dir1 and dir5 to the right of dir1 if(dir1%2 == 0) { swap(&dir2, &dir4); swap(&dir3, &dir5); } while (steps-- > 0) { //picking up even tripod angle(dir2, MOTOR_B, lift); angle(dir4, MOTOR_B, lift); angle(dir6, MOTOR_B, lift); delay(delay_time); //moving body on odd tripod angle(dir1, MOTOR_A, 90); angle(dir3, MOTOR_A, 90); angle(dir5, MOTOR_A, 90); //rotating legs even in air angle(dir2, MOTOR_A, 90 + step_side); angle(dir4, MOTOR_A, 90 + step_side); angle(dir6, MOTOR_A, 90 + step_side); delay(delay_time); //putting down even legs angle(dir2, MOTOR_B, 90); angle(dir4, MOTOR_B, 90); angle(dir6, MOTOR_B, 90); delay(HUNDRED_MSEC); //picking up odd legs angle(dir1, MOTOR_B, lift); angle(dir3, MOTOR_B, lift); angle(dir5, MOTOR_B, lift); delay(delay_time); //moving the odd legs in air angle(dir1, MOTOR_A, 90 + step_side); angle(dir3, MOTOR_A, 90 + step_side); angle(dir5, MOTOR_A, 90 + step_side); //rotating the body on even tripod angle(dir2, MOTOR_A, 90); angle(dir4, MOTOR_A, 90); angle(dir6, MOTOR_A, 90); delay(delay_time); //puuting down odd tripod angle(dir1, MOTOR_B, 90); angle(dir3, MOTOR_B, 90); angle(dir5, MOTOR_B, 90); delay(HUNDRED_MSEC); } } /** Tripod turn gait continuous: turns hexapod in specified direction for specified number of cycles. Description: * There are two tripods - odd tripod (leg 1, 3, 5) and even tripod (leg 2, 4, 6). * When odd tripod is in air, even tripod moves from maximum positive displacement to maximum negative displacement. * Similar is the case when even tripod is in air. * This gives wider range of motion to hexapod and thus increase the turning speed. @param rot_dir : Direction of rotation (one of CLOCKWISE or ANTI_CLOCKWISE) @param steps : number of steps */ void tripod_turn_gait_continuous(unsigned char rot_dir, unsigned char steps) { // We can choose any leg as the primary leg. Other legs are referred relative to the chosen leg. unsigned char dir1 = LEG_1; unsigned char dir3 = ((dir1 + 1) % 6) + 1; unsigned char dir5 = ((dir3 + 1) % 6) + 1; unsigned char dir2 = 7 - dir5; unsigned char dir4 = 7 - dir3; unsigned char dir6 = 7 - dir1; // Angle moved by the motors sideways. // Scaling factor {@code: movementScaling} controls the turning speed. int step_side = 45 * movementScaling; // Angle by which legs are raised in air. unsigned char lift = 40; // Delay time between two successive motion commands. int delay_time = 150; // If rotation direction is anti-clockwise rot_dir = 0 else rot_dir = 1 step_side = step_side*(1 - 2*rot_dir); // The following is done to keep dir3 to the left of dir1 and dir5 to the right of dir1 if(dir1%2 == 0) { swap(&dir2, &dir4); swap(&dir3, &dir5); } while (steps-- > 0) { //picking up even tripod angle(dir2, MOTOR_B, lift); angle(dir4, MOTOR_B, lift); angle(dir6, MOTOR_B, lift); delay(delay_time); //moving body on odd tripod angle(dir1, MOTOR_A, 90 - step_side); angle(dir3, MOTOR_A, 90 - step_side); angle(dir5, MOTOR_A, 90 - step_side); //rotating legs even in air angle(dir2, MOTOR_A, 90 + step_side); angle(dir4, MOTOR_A, 90 + step_side); angle(dir6, MOTOR_A, 90 + step_side); delay(delay_time); //putting down even legs angle(dir2, MOTOR_B, 90); angle(dir4, MOTOR_B, 90); angle(dir6, MOTOR_B, 90); delay(HUNDRED_MSEC); //picking up odd legs angle(dir1, MOTOR_B, lift); angle(dir3, MOTOR_B, lift); angle(dir5, MOTOR_B, lift); delay(delay_time); //moving the odd legs in air angle(dir1, MOTOR_A, 90 + step_side); angle(dir3, MOTOR_A, 90 + step_side); angle(dir5, MOTOR_A, 90 + step_side); //rotating the body on even tripod angle(dir2, MOTOR_A, 90 - step_side); angle(dir4, MOTOR_A, 90 - step_side); angle(dir6, MOTOR_A, 90 - step_side); delay(delay_time); //puuting down odd tripod angle(dir1, MOTOR_B, 90); angle(dir3, MOTOR_B, 90); angle(dir5, MOTOR_B, 90); delay(HUNDRED_MSEC); } } /** Two legged turn gait: turns hexapod in specified direction for specified number of cycles. Description: * There are three pairs - pair1 (leg 1, 6), pair2 (leg 2, 5), pair (3, 4). * When one pair of legs is in air, other legs support the bot. * Support from 4 legs at a time, makes the hexapod highly stable during turning. @param rot_dir : Direction of rotation (one of CLOCKWISE or ANTI_CLOCKWISE) @param steps : number of steps */ void two_legged_turn_gait(unsigned char rot_dir, unsigned char steps) { unsigned char dir1 = LEG_1; unsigned char dir3 = ((dir1 + 1) % 6) + 1; unsigned char dir5 = ((dir3 + 1) % 6) + 1; unsigned char dir2 = 7 - dir5; unsigned char dir4 = 7 - dir3; unsigned char dir6 = 7 - dir1; // Step size during turning. // {@code: movementScaling} controls the motion of the motors. int step_side = 50 * movementScaling; // Angle by the which the legs are raised in air. unsigned char lift = 40; // Time delay between succesive movement commands. int delay_time = 150; // If rotation direction is anti-clockwise rot_dir = 0 else rot_dir = 1 step_side = step_side*(1 - 2*rot_dir); // The following is done to keep dir3 to the left of dir1 and dir5 to the right of dir1 if(dir1%2 == 0) { swap(&dir2, &dir4); swap(&dir3, &dir5); } while (steps-- > 0) { //picking up first duplet angle(dir1, MOTOR_B, lift); angle(dir6, MOTOR_B, lift); delay(delay_time); //moving body on second duplet angle(dir2, MOTOR_A, 90); angle(dir5, MOTOR_A, 90); //rotating first duplet in air angle(dir1, MOTOR_A, 90 + step_side); angle(dir6, MOTOR_A, 90 + step_side); delay(delay_time); //putting down first duplet angle(dir1, MOTOR_B, 90); angle(dir6, MOTOR_B, 90); delay(HUNDRED_MSEC); //picking up third duplet angle(dir3, MOTOR_B, lift); angle(dir4, MOTOR_B, lift); delay(delay_time); //moving the third duplet in air angle(dir3, MOTOR_A, 90 + step_side); angle(dir4, MOTOR_A, 90 + step_side); //rotating the body on first duplet angle(dir1, MOTOR_A, 90); angle(dir6, MOTOR_A, 90); delay(delay_time); //putting down third duplet angle(dir3, MOTOR_B, 90); angle(dir4, MOTOR_B, 90); delay(HUNDRED_MSEC); //picking up second duplet angle(dir2, MOTOR_B, lift); angle(dir5, MOTOR_B, lift); delay(delay_time); //moving the second duplet in air angle(dir2, MOTOR_A, 90 + step_side); angle(dir5, MOTOR_A, 90 + step_side); //rotating the body on third duplet angle(dir3, MOTOR_A, 90); angle(dir4, MOTOR_A, 90); delay(delay_time); //putting down second duplet angle(dir2, MOTOR_B, 90); angle(dir5, MOTOR_B, 90); delay(HUNDRED_MSEC); } } /** Tripod gait continuous: moves the hexapod in the direction {@code: dir1} for {@code: steps}. Description * There are 2 tripods. Even tripod (leg no 1, 3, 5) and odd tripod (leg no 2, 4, 6). * When odd tripod is in air, even tripod moves from maximum positive displacement to maximum negative displacement. * Similar is the case when even tripod is in air. * This gives wider range of motion to hexapod and thus increase the movement speed. @param dir1 : Direction of motion @param steps : number of steps */ void tripod_gait_continuous(unsigned char dir1, unsigned char steps) { // Set the given {@code: dir1} as primary leg (movement direction). // Label other legs relative to primary motion direction. unsigned char dir3 = ((dir1 + 1) % 6) + 1; unsigned char dir5 = ((dir3 + 1) % 6) + 1; unsigned char dir2 = 7 - dir5; unsigned char dir4 = 7 - dir3; unsigned char dir6 = 7 - dir1; // Movement given to front and back leg. unsigned char step_forward = 50 * movementScaling; // Movement given to side legs. unsigned char step_side = 55 * movementScaling; // Angle by which legs are raised in air. unsigned char lift = 40; // Delay time between successive movement commands. int delay_time = 150; // The following is done to keep dir3 to the left of dir1 and dir5 to the right of dir1 if(dir1%2 == 0) { swap(&dir2, &dir4); swap(&dir3, &dir5); } while (steps-- > 0) { //picking up even tripod angle(dir2, MOTOR_B, lift); angle(dir4, MOTOR_B, lift); angle(dir6, MOTOR_B, lift); delay(delay_time); //moving body on odd tripod angle(dir1, MOTOR_C, 90 - step_forward); angle(dir3, MOTOR_A, 90 + step_side); angle(dir5, MOTOR_A, 90 - step_side); //moving legs even forward in air angle(dir2, MOTOR_A, 90 - step_side); angle(dir4, MOTOR_A, 90 + step_side); angle(dir6, MOTOR_C, 90 - step_forward); delay(delay_time); //putting down even legs angle(dir2, MOTOR_B, 90); angle(dir4, MOTOR_B, 90); angle(dir6, MOTOR_B, 90); delay(HUNDRED_MSEC); //picking up odd legs angle(dir1, MOTOR_B, lift); angle(dir3, MOTOR_B, lift); angle(dir5, MOTOR_B, lift); delay(delay_time); //moving the odd legs in air angle(dir1, MOTOR_C, 90 + step_forward); angle(dir3, MOTOR_A, 90 - step_side); angle(dir5, MOTOR_A, 90 + step_side); //moving the body forward on even tripod angle(dir2, MOTOR_A, 90 + step_side); angle(dir4, MOTOR_A, 90 - step_side); angle(dir6, MOTOR_C, 90 + step_forward); delay(delay_time); //putting down odd tripod angle(dir1, MOTOR_B, 90); angle(dir3, MOTOR_B, 90); angle(dir5, MOTOR_B, 90); delay(HUNDRED_MSEC); } } /** Tripod gait insect continuous: moves the hexapod in the direction {@code: dir1} for {@code: steps}. Description * There are 2 tripods. Even tripod (leg no 1, 3, 5) and odd tripod (leg no 2, 4, 6). * The direction of motion is between two neighbouring legs. There are 3 legs on each side on movement direction. * When odd tripod is in air, even tripod moves from maximum positive displacement to maximum negative displacement. * Similar is the case when even tripod is in air. * This gives wider range of motion to hexapod and thus increase the movement speed. @param dir1 : Direction of motion @param steps : number of steps */ void tripod_gait_insect_continuous(unsigned char dir1, unsigned char steps) { // Set the given {@code: dir1} as primary leg (movement direction). // Label other legs relative to primary motion direction. unsigned char dir3 = ((dir1 + 1) % 6) + 1; unsigned char dir5 = ((dir3 + 1) % 6) + 1; unsigned char dir2 = 7 - dir5; unsigned char dir4 = 7 - dir3; unsigned char dir6 = 7 - dir1; // Angle by which front legs can move in forward direction. unsigned char step_front_forward = 30 * movementScaling; // Angle by which front legs can move in backward direction. unsigned char step_front_backward = 70 * movementScaling; // Angle by which side legs move. unsigned char step_side =40 * movementScaling; // Angle by which legs are raised in air. unsigned char lift = 40; // Delay time between successive movement commands. int delay_time = 150;//TWO_HUNDRED_FIFTY_MSEC; // The following is done to keep dir3 to the left of dir1 and dir5 to the right of dir1 if(dir1%2 == 0) { swap(&dir2, &dir4); swap(&dir3, &dir5); } while (steps-- > 0) { //picking up even tripod angle(dir2, MOTOR_B, lift); angle(dir4, MOTOR_B, lift); angle(dir6, MOTOR_B, lift); delay(delay_time); //moving body on odd tripod angle(dir1, MOTOR_A, 90 - step_front_backward); angle(dir3, MOTOR_A, 90 + step_side); angle(dir5, MOTOR_A, 90 - step_front_forward); //moving legs even forward in air angle(dir2, MOTOR_A, 90 - step_front_forward); angle(dir4, MOTOR_A, 90 + step_side); angle(dir6, MOTOR_A, 90 - step_front_backward); delay(delay_time); //putting down even legs angle(dir2, MOTOR_B, 90); angle(dir4, MOTOR_B, 90); angle(dir6, MOTOR_B, 90); delay(HUNDRED_MSEC); //picking up odd legs angle(dir1, MOTOR_B, lift); angle(dir3, MOTOR_B, lift); angle(dir5, MOTOR_B, lift); delay(delay_time); //moving the odd legs in air angle(dir1, MOTOR_A, 90 + step_front_forward); angle(dir3, MOTOR_A, 90 - step_side); angle(dir5, MOTOR_A, 90 + step_front_backward); //moving the body forward on even tripod angle(dir2, MOTOR_A, 90 + step_front_backward); angle(dir4, MOTOR_A, 90 - step_side); angle(dir6, MOTOR_A, 90 + step_front_forward); delay(delay_time); //putting down odd tripod angle(dir1, MOTOR_B, 90); angle(dir3, MOTOR_B, 90); angle(dir5, MOTOR_B, 90); delay(HUNDRED_MSEC); } } /** Wave gait: moves the hexapod in the direction {@code: dir1} for {@code: steps}. Description * Hexapod moves in a direction between two neighbouring legs. * In the Wave Gait, all legs on one side are moved forward in succession, starting with the rear-most leg. * This is then repeated on the other side. * Since only 1 leg is ever lifted at a time, with the other 5 being down, the animal is always in a highly-stable posture. @param dir1 : Direction of motion @param steps : number of steps */ void wave_gait(unsigned char dir1, int steps) { // Hexapod moves in direction between dir1 and dir4. // dir1 is provided by the user. Other directions are marked accordingly. unsigned char dir3 = ((dir1 + 1) % 6) + 1; unsigned char dir5 = ((dir3 + 1) % 6) + 1; unsigned char dir2 = 7 - dir5; unsigned char dir4 = 7 - dir3; unsigned char dir6 = 7 - dir1; // Movement given to front and hind legs. unsigned char step_forward = 70; // Movement given to side legs. unsigned char step_side = 50; // Angle by which legs are raised in air. unsigned char lift = 40; // Delay time between two successive movement commands. int delay_time = 100; // Variables to store the order in which legs should be moved. unsigned char leg_order[6]; // Variable which stores the maximum allowed movement for different legs. int leg_distance[6]; // Variable to store the current displacement of various legs. int leg_current[] = {0, 0, 0, 0, 0, 0}; leg_order[0] = dir1; leg_order[1] = dir2; leg_order[2] = dir3; leg_order[3] = dir4; leg_order[4] = dir5; leg_order[5] = dir6; leg_distance[0] = -step_forward; leg_distance[1] = -step_side; leg_distance[2] = -step_forward; leg_distance[3] = step_forward; leg_distance[4] = step_side; leg_distance[5] = step_forward; while(steps-- > 0) { int i, j, k; for (i = 0; i < 6; i++){ // Putting down leg i and pick up leg i+1 angle(leg_order[i], MOTOR_B, 90); angle(leg_order[(i+1) % 6], MOTOR_B, lift); delay(delay_time); // Moving body on leg i and move leg i+1 in air leg_current[(i+1) % 6] = 90 + leg_distance[(i+1) % 6]; angle(leg_order[(i+1) % 6], MOTOR_A, leg_current[(i+1) % 6]); // Move the other legs backward to push the ground. for (j = 1; j <= 5; j++){ k = (i + 1 + j) % 6; leg_current[k] = leg_current[k] - (2 * leg_distance[k]) / 5; angle(leg_order[k], MOTOR_A, leg_current[k]); } delay(delay_time); } angle(leg_order[i % 6], MOTOR_B, 90); delay(delay_time); } } /** Ripple gait: moves the hexapod in the direction {@code: dir1} for {@code: steps}. Description * Hexapod moves in a direction between two neighbouring legs. * In the Ripple Gait, on each side a local wave comprising non-overlapping lift phases is being performed, * and that the 2 opposite side waves are exactly 180 degrees out of phase with one another @param dir1 : Direction of motion @param steps : number of steps */ void ripple_gait(unsigned char dir1, int steps) { // Hexapod moves in direction between dir1 and dir4. // dir1 is provided by the user. Other directions are marked accordingly. unsigned char dir3 = ((dir1 + 1) % 6) + 1; unsigned char dir5 = ((dir3 + 1) % 6) + 1; unsigned char dir2 = 7 - dir5; unsigned char dir4 = 7 - dir3; unsigned char dir6 = 7 - dir1; // Movement given to front and hind legs. unsigned char step_forward = 50; // Movement given to side legs. unsigned char step_side = 40; // Angle by which legs are raised in air. unsigned char lift = 40; // Delay time between two successive movement commands. int delay_time1 = 100; int delay_time2 = 100; // Variables to store the order in which legs should be moved. unsigned char leg_order[6]; // Variable which stores the maximum allowed movement for different legs. int leg_distance[6]; // Variable to store the current displacement of various legs. int leg_current[] = {0, 0, 0, 0, 0, 0}; leg_order[0] = dir1; leg_order[1] = dir2; leg_order[2] = dir3; leg_order[3] = dir4; leg_order[4] = dir5; leg_order[5] = dir6; leg_distance[0] = -step_forward; leg_distance[1] = -step_side; leg_distance[2] = -step_forward; leg_distance[3] = step_forward; leg_distance[4] = step_side; leg_distance[5] = step_forward; while(steps-- > 0) { int i, j, k; for (i = 0; i < 3; i++) { // Putting down leg i and pick up leg i+1 angle(leg_order[i], MOTOR_B, 90); angle(leg_order[(i+1) % 3], MOTOR_B, lift); delay(delay_time1); // Wave on opposite side is 180 degrees out of phase. angle(leg_order[((i+2) % 3) + 3], MOTOR_B, 90); angle(leg_order[(i % 3) + 3], MOTOR_B, lift); delay(delay_time2); // Moving body on leg i and move leg i+1 in air leg_current[(i+1) % 3] = 90 + leg_distance[(i+1) % 3]; angle(leg_order[(i+1) % 3], MOTOR_A, leg_current[(i+1) % 3]); // Move the other legs backward to push the ground. for (j = 1; j <= 2; j++) { k = (i + 1 + j) % 3; leg_current[k] = leg_current[k] - leg_distance[k]; angle(leg_order[k], MOTOR_A, leg_current[k]); } delay(delay_time1); // Moving body on leg i and move leg i+1 in air leg_current[(i % 3) + 3] = 90 + leg_distance[(i % 3) + 3]; angle(leg_order[(i % 3) + 3], MOTOR_A, leg_current[(i % 3) + 3]); // Move the other legs backward to push the ground. for (j = 1; j <= 2 ; j++) { k = ((i + j) % 3) + 3; leg_current[k] = leg_current[k] - leg_distance[k]; angle(leg_order[k], MOTOR_A, leg_current[k]); } delay(delay_time2); } angle(leg_order[(i + 1) % 3], MOTOR_B, 90); angle(leg_order[(i % 3) + 3], MOTOR_B, 90); delay(delay_time1); } }
C
#include<stdio.h> #include<fcntl.h> #include<dirent.h> #include<stdlib.h> #include<string.h> int main(int argc, char *argv[]){ if(argc != 2){ printf("Invalid number of arguments\n"); printf("Usage: PROG_NAME FILE_NAME\n"); exit(1); } char *filename = argv[1]; creat(filename,0777); int fd = open(filename, O_WRONLY,0); DIR *dirptr = opendir("/home/fahim/Desktop/CSE325/Lab/assignment"); if(dirptr == NULL){ printf("Cannot open directory\n"); exit(1); } struct dirent *entry = readdir(dirptr); while(entry!=NULL){ int n = strlen(entry->d_name); if(entry->d_name[n-1] == 't' && entry->d_name[n-2] == 'x' && entry->d_name[n-3] == 't' && entry->d_name[n-4] == '.'){ char buf[1024]; int fd1 = open(entry->d_name,O_RDONLY, 0); int szr = read(fd1, buf, 1024); lseek(fd,0,2); int szw = write(fd, buf, szr); } entry = readdir(dirptr); } return 0; }
C
#include <stdio.h> #include <time.h> void selectionSort(int v[], int n) { int i, j, min, temp; for(i = 0; i < n - 1; i++) { min = i; for(j = i + 1; j < n; j++) if(v[j] < v[min]) min = j; temp = v[i]; v[i] = v[min]; v[min] = temp; } } void insertionSort(int vet[], int n) { int i, j, temp; for (j = 1; j < n; j++) { temp = vet[j]; for (i = j-1; i >= 0 && vet[i] > temp; i--) vet[i+1] = vet[i]; vet[i+1] = temp; } } void bubbleSort(int v[], int n) { int i,j,temp; for(i = n - 1; i >= 0; i--) for(j = 1; j <= i; j++) if(v[j-1] > v[j]) { temp = v[j-1]; v[j-1] = v[j]; v[j] = temp; } } void intercala(int vet[],int inicio, int meio, int fim) { int i, j, k, *vet_aux; vet_aux = malloc((fim-inicio)*sizeof(int)); i = inicio; j = meio; k = 0; while( i < meio && j < fim) { if(vet[i] <= vet[j]) vet_aux[k++] = vet[i++]; else vet_aux[k++] = vet[j++]; } while (i < meio) vet_aux[k++] = vet[i++]; while (j < fim) vet_aux[k++] = vet[j++]; for(i = inicio; i < fim; i++) vet[i] = vet_aux[i-inicio]; free(vet_aux); } void mergeSort(int v[], int inicio, int fim) { if( inicio < fim - 1) { int meio = (inicio + fim) / 2; mergeSort(v, inicio, meio); mergeSort(v, meio, fim); intercala(v, inicio, meio, fim); } } int separa(int vet[], int inicio, int fim) { int pivo, j, k, temp; pivo = vet[fim]; j = inicio; for(k = inicio; k < fim; k++) { if(vet[k] <= pivo) { temp = vet[j]; vet[j] = vet[k]; vet[k] = temp; j++; } } vet[fim] = vet[j]; vet[j] = pivo; return j; } void quickSort(int vet[],int inicio, int fim) { int j; if(inicio < fim) { j = separa(vet, inicio, fim); quickSort(vet, inicio, j-1); quickSort(vet, j+1, fim); } } void insereHeap(int m, int vet[]) { int f = m + 1; while (f > 1 && vet[f/2] < vet[f]) { int t = vet[f/2]; vet[f/2] = vet[f]; vet[f] = t; f = f/2; } } void sacodeHeap(int m, int v[]) { int t, f = 2; while (f <= m) { if(f < m && v[f] < v[f+1]) ++f; if(v[f/2] >= v[f]) break; t = v[f/2]; v[f/2] = v[f]; v[f] = t; f *= 2; } } void heapSort(int n, int vet[]) { int m; for(m = 1; m < n; m++) insereHeap(m,vet); for(m = n; m > 1; m--) { int t = vet[1]; vet[1] = vet[m]; vet[m] = t; sacodeHeap(m-1,vet); } } int main(void) { clock_t Ticks; Ticks = clock(); int v[10] = {11, 7, 20, 11, 3, 6, 30, 28, 22, 25}; int v2[10] = {11, 7, 20, 11, 3, 6, 30, 28, 22, 25}; int v3[10] = {11, 7, 20, 11, 3, 6, 30, 28, 22, 25}; int v4[10] = {11, 7, 20, 11, 3, 6, 30, 28, 22, 25}; int v5[10] = {11, 7, 20, 11, 3, 6, 30, 28, 22, 25}; int v6[10] = {11, 7, 20, 11, 3, 6, 30, 28, 22, 25}; selectionSort(v, 10); insertionSort(v2, 10); bubbleSort(v3, 10); mergeSort(v4, 0, 10); quickSort(v5, 0, 9); heapSort(10, v6-1); double Tempo = (clock() - Ticks) * 1000.0 / CLOCKS_PER_SEC; printf("Tempo gasto: %g ms.", Tempo); getchar(); return 0; }
C
/* * * FileName : webserver.c * Description : This file contains SW implementation of a HTTP-based webserver that accepts multiple * simultaneous connections * File Author Name: Bhallaji Venkatesan * Tools used : gcc, Sublime Text, Webbrowser (Mozzila Firfox) * References : NETSYS Class Lectures * http://www.binarytides.com/server-client-example-c-sockets-linux/ * http://www.csc.villanova.edu/~mdamian/sockets/echoC.htm * */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netdb.h> #include <signal.h> #include <fcntl.h> #include <sys/time.h> #include <signal.h> /***** MACROS *******/ #define MAX_CONN 100 #define MAX_WSBUFF 1000 #define TX_BYTES 1024 #define CLIENT_MSGSIZE 65536 #define TRUE 1 #define FALSE 0 #define STATUSLENGTH 2000 /**** Global Variables ****/ char *DIR_ROOT = NULL; char PORT_NUM[8]; int sock = 0; int clients[MAX_CONN]; int COUNT = 0; int client_count = 0; int internal_error = 0; /*******Function Implementations***********/ void signal_handler(int signal) { switch (signal) { case SIGINT: close(sock); exit(1); break; case SIGTERM: close(sock); exit(1); break; } } static uint32_t get_sizeof_file (FILE * fileDesc) { uint32_t size; fseek(fileDesc, 0L, SEEK_END); size = ftell(fileDesc); fseek(fileDesc, 0L, SEEK_SET); return size; } char * content_check(char *filetype) { char *type; if((strcmp(filetype,".htm"))==0 || (strcmp(filetype,".html"))==0) type = "text/html"; else if((strcmp(filetype,".jpg"))==0) type = "image/jpeg"; else if(strcmp(filetype,".gif")==0) type = "image/gif"; else if(strcmp(filetype,".txt")==0) type = "text/plain"; else if(strcmp(filetype,".png")==0) type = "image/png"; else if(strcmp(filetype,".css")==0) type = "text/css"; else if(strcmp(filetype,".js")==0) type = "text/javascript"; else type="application/octet-stream"; return type; } int format_extract(char *filetype) { FILE *fp; char wsbuff[MAX_WSBUFF]; unsigned int formatIndex = 0; int file_supported = 0; char formats[20][100]; char *wsconfig = getenv("PWD"); if (wsconfig != NULL) printf("Path to ws.conf: %s \n", wsconfig); fp=fopen(wsconfig,"r"); unsigned int wsconfig_size = get_sizeof_file (fp); while(fgets(wsbuff,wsconfig_size,fp)!=NULL) {//read from the .conf file strcpy(formats[formatIndex],wsbuff); formatIndex++; } int k=0; for(k=0;k<formatIndex+1;k++) { if(strncmp(formats[k],filetype,3)==0) {//check if the file is supported file_supported = 1;//if supported then set file_supported. break; } } fclose(fp); return file_supported; } void wsconf_read() { FILE *fp = NULL; char wsbuff[MAX_WSBUFF]; char *wsconfig = getenv("PWD"); char *temp_buff = NULL; strncat(wsconfig,"/ws.conf", 8); fp=fopen(wsconfig,"r"); if(!fp) { printf("\n Unable to find ws.conf file! Exiting the program \n"); exit(1); } else { uint32_t wsconfig_size = get_sizeof_file (fp); printf("ws.conf size = %d, filename = %s\n", wsconfig_size, wsconfig); while(fgets(wsbuff,wsconfig_size,fp)!=NULL) { /* Parsing ws.conf for finding PORT NUM */ if(strncmp(wsbuff,"Listen",6)==0) { temp_buff=strtok(wsbuff," \t\n"); temp_buff = strtok(NULL, " \t\n"); strcpy(PORT_NUM, temp_buff); printf("PORT NUM %s\n", PORT_NUM); bzero(wsbuff, sizeof(wsbuff)); } /* Parsing ws.conf for finding Root directory */ if(strncmp(wsbuff,"DocumentRoot",12)==0) { temp_buff=strtok(wsbuff," \t\n"); temp_buff = strtok(NULL, " \t\n"); DIR_ROOT=(char*)malloc(100); if(!DIR_ROOT) { internal_error = 1; // Internal Error for HTTP 500 Error Handling break; } strcpy(DIR_ROOT,temp_buff); printf("ROOT DIRECTORY : %s\n",DIR_ROOT); bzero(wsbuff, sizeof(wsbuff)); } } fclose(fp); } } void start_server(int port) { struct sockaddr_in sin; bzero((char *)&sin, sizeof(sin)); sin.sin_family = AF_INET; //set family as the internet family (AF_INET) sin.sin_addr.s_addr = INADDR_ANY; //set any address as the address for the socket sin.sin_port = htons(port); //set the port number to the socket if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) //open socket and check if error occurs { printf("Error in creating socket \n"); exit(1); } int optval = 1; setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval , sizeof(int)); //prevents the "already in use" issue printf("Socket created\n"); if ((bind(sock, (struct sockaddr *)&sin, sizeof(sin))) < 0) //bind socket and check if error occurs { printf("Bind Error : %d\n", bind(sock, (struct sockaddr *)&sin, sizeof(sin))); exit(1); } printf("Socket bound\n"); if(listen(sock, 4) != 0) //listen for incoming requests on the socket we have created { printf("Error in listen\n"); exit(1); } printf("Listening for connections\n"); } void conn_response(int n) { printf("\nEntering Conn Response \n"); char msg_from_client[CLIENT_MSGSIZE], *req_string[3], msg_to_client[TX_BYTES], path[CLIENT_MSGSIZE]; int rcvd, fd, bytes_read; FILE *fp; char status[STATUSLENGTH]; char connection_status[50]; client_count = n; int flag_post=0; printf("\n _________________________________\nclient_count : %d\n",client_count); while(1){ flag_post = 0; // make it zero before every post request bzero(status, sizeof(status)); bzero(msg_from_client, sizeof(msg_from_client)); bzero(path, sizeof(path)); bzero(req_string, sizeof(req_string)); bzero(msg_to_client, sizeof(msg_to_client)); bzero(connection_status, sizeof(connection_status)); memset( (void*)msg_from_client, (int)'\0', CLIENT_MSGSIZE ); rcvd=recv(clients[n], msg_from_client, CLIENT_MSGSIZE, 0); char filename[50] = "Msgstore"; char count_str[50]; sprintf(count_str,"%d", COUNT); strcat(filename, count_str); FILE *fp_storeMsg = fopen(filename, "w"); if (fp_storeMsg != NULL) { fputs(msg_from_client, fp_storeMsg); fclose(fp_storeMsg); } if (!strstr(msg_from_client,"Connection: Keep-alive")) // capturing the last string from the received message { strncpy(connection_status, "Connection: Keep-alive", strlen("Connection: Keep-alive")); } else /* -- If Keep-alive is not found, close the connection --- */ { strncpy(connection_status, "Connection: Close",strlen("Connection: Close")); } bzero(status, sizeof(status)); if (rcvd<0) // receive error fprintf(stderr,("recv() error\n")); else if (rcvd==0) // receive socket closed rcvd = 0; else // message received { if (!strstr(msg_from_client,"Connection: Keep-alive")) // capturing the last string from the received message { strncpy(connection_status, "Connection: Keep-alive", strlen("Connection: Keep-alive")); } else /* -- If Keep-alive is not found, close the connection --- */ { strncpy(connection_status, "Connection: Close",strlen("Connection: Close")); } printf("\n printing msg_from_client %s\n", msg_from_client); printf("Size of rcvd message %ld \n", sizeof(msg_from_client)); // Now breaking the incoming strng into three different paths req_string[0] = strtok (msg_from_client, " \t\n"); if ((strncmp(req_string[0], "GET\0", 4)==0) || (strncmp(req_string[0], "POST\0", 5)==0)) { if (strncmp(req_string[0], "POST\0", 5)==0) { printf("____________________________________________\n"); flag_post = TRUE; } req_string[1] = strtok (NULL, " \t"); req_string[2] = strtok (NULL, " \t\n"); char http_version[8]; if (strncmp(req_string[2], "HTTP/1.1", 8) == 0) strcpy(http_version, "HTTP/1.1"); else strcpy(http_version, "HTTP/1.0"); if(internal_error) { strncat(status,http_version,strlen(http_version)); strncat(status," 500 Internal Server Error:Cannot allocate memory",strlen(" 500 Internal Server Error")); strncat(status,"\n",strlen("\n")); strncat(status,"<html><body>>500 Internal Server Error:Cannot allocate memory",strlen("<body>>400 Bad Request Reason: Invalid HTTP-Version :")); strncat(status,"HTTP",strlen("HTTP")); strncat(status,"</body></html>",strlen("</body></html>")); strncat(status,"\r\n",strlen("\r\n")); printf("%s\n",status); write(clients[n], status, strlen(status)); internal_error = 0; } if ( strncmp( req_string[2], "HTTP/1.0", 8)!=0 && strncmp( req_string[2], "HTTP/1.1", 8)!=0 ) { strncat(status,http_version,strlen(http_version)); strncat(status," 400 Bad Request",strlen(" 400 Bad Request")); strncat(status,"\n",strlen("\n")); strncat(status,"<html><body>>400 Bad Request Reason: Invalid HTTP-Version :",strlen("<body>>400 Bad Request Reason: Invalid HTTP-Version :")); strncat(status,"HTTP",strlen("HTTP")); strncat(status,"</body></html>",strlen("</body></html>")); strncat(status,"\r\n",strlen("\r\n")); printf("%s\n",status); write(clients[n], status, strlen(status)); } else { if ( strncmp(req_string[1], "/\0", 2)==0 ) req_string[1] = "/index.html"; //Because if no file is specified, index.html will be opened by default (like it happens in APACHE... strcpy(path, DIR_ROOT); strcpy(&path[strlen(DIR_ROOT)], req_string[1]); printf("file: %s\n", path); int formatCheck; char *ext = strrchr (path, '.'); if (ext == NULL) { formatCheck = FALSE; } else { formatCheck = format_extract(ext); } char size_array[20]; if (formatCheck == TRUE) { if ( (fd=open(path, O_RDONLY))!=-1 ) //FILE FOUND { fp = fopen(path,"r");; char *checkfileType = content_check(ext); int size= get_sizeof_file(fp); sprintf(size_array,"%d",size); char msg_post[CLIENT_MSGSIZE]; if (flag_post) { COUNT++; printf("coming into post loop\n"); FILE * fp_msgcheck; char * line = NULL; size_t len = 0; ssize_t read; int line_empty = FALSE; fp_msgcheck = fopen(filename, "r"); if (fp_msgcheck == NULL) exit(EXIT_FAILURE); int temp_var = 1; while ((read = getline(&line, &len, fp_msgcheck)) != -1) { if (read == 2 && line_empty == FALSE) { line_empty = TRUE; } if (line_empty == TRUE) { printf(" Retrieved line of length %zu :\n", read); printf(" %s", line); if (temp_var == 1) { temp_var = 0; } else { strncat(msg_post, line, strlen(line)); printf("Coming here!!%s\n", msg_post); } } } printf(" %s\n", msg_post); temp_var = 1; line_empty = FALSE; fclose(fp_msgcheck); remove(filename); if (line) free(line); } char msg[CLIENT_MSGSIZE]; if (flag_post) { strncat(status,"POST ",strlen("POST ")); } strncat(status,http_version,strlen(http_version)); strncat(status," 200 OK",strlen(" 200 OK")); strncat(status,"\n",strlen("\n")); strncat(status,"Content-Type:",strlen("Content-type:")); strncat(status,checkfileType,strlen(checkfileType)); strncat(status,"\n",strlen("\n")); strncat(status,"Content-Length:",strlen("Content-Length:")); strncat(status,size_array,strlen(size_array)); strncat(status,"\n",strlen("\n")); strncat(status,connection_status,strlen(connection_status)); if (flag_post) { strncat(status,"\r\n\r\n",strlen("\r\n\r\n")); sprintf(msg,"<h1>POST DATA</h1><html><body>%s</body></html>\n",msg_post); strncat(status, msg, strlen(msg)); strncat(status,"\r\n",strlen("\r\n")); } else{ strncat(status,"\r\n",strlen("\r\n")); strncat(status,"\r\n",strlen("\r\n")); } printf("printing status update to client %s\n",status); send(clients[n], status, strlen(status), 0); while ( (bytes_read=read(fd, msg_to_client, TX_BYTES))>0 ) write (clients[n], msg_to_client, bytes_read); printf("\n Loaded Index.html \n"); fclose(fp); bzero(msg_post,sizeof(msg_post)); bzero(msg,sizeof(msg)); } else{ // file not found loop strncat(status,http_version,strlen(http_version)); strncat(status," 404 Not Found",strlen(" 404 Not Found")); strncat(status,"\n",strlen("\n")); strncat(status,"Content-Type:",strlen("Content-type:")); strncat(status,"Invalid",strlen("Invalid")); strncat(status,"\n",strlen("\n")); strncat(status,"Content-Length:",strlen("Content-Length:")); strncat(status,"Invalid",strlen("Invalid")); strncat(status,"\n",strlen("\n")); strncat(status,connection_status,strlen(connection_status)); strncat(status,"\r\n",strlen("\r\n")); strncat(status,"\r\n",strlen("\r\n")); strncat(status,"<html><body>404 Not Found: URL does not exist:",strlen("<body>404 Not Found: URL does not exist:")); strncat(status,path,strlen(path)); strncat(status,"</body></html>",strlen("</body></html>")); strncat(status,"\r\n",strlen("\r\n")); printf("%s\n",status); write(clients[n], status, strlen(status)); //FILE NOT FOUND } } else // file not supported { printf("***************************************************\n"); strncat(status,http_version,strlen(http_version)); strncat(status," 501 Not Implemented",strlen(" 501 Not Implemented")); strncat(status,"\n",strlen("\n"));//strncat(status_line,"\r\n",strlen("\r\n")); strncat(status,"Content-Type:",strlen("Content-type:")); strncat(status,"NONE",strlen("NONE")); strncat(status,"\n",strlen("\n")); strncat(status,"Content-Length:",strlen("Content-Length:")); strncat(status,"NONE",strlen("NONE")); strncat(status,"\n",strlen("\n")); strncat(status,connection_status,strlen(connection_status)); strncat(status,"\r\n",strlen("\r\n")); strncat(status,"\r\n",strlen("\r\n")); strncat(status,"<HEAD><TITLE>501 Not Implemented</TITLE></HEAD>",strlen("<HEAD><TITLE>501 Not Implemented</TITLE></HEAD>")); strncat(status,"<body>501 Not Implemented: File format not supported:",strlen("<body>501 Not Implemented: File format not supported:")); strncat(status,http_version,strlen(http_version)); strncat(status,"</body></html>",strlen("</body></html>")); strncat(status,"\r\n",strlen("\r\n")); write(clients[n], status, strlen(status)); //FILE NOT FOUND } } } else {//file not found strncat(status,"HTTP/1.1",strlen("HTTP/1.1")); strncat(status,"\n",strlen("\n")); strncat(status,"Content-Type:",strlen("Content-type:")); strncat(status,"NONE",strlen("NONE")); strncat(status,"\n",strlen("\n")); strncat(status,"Content-Length:",strlen("Content-Length:")); strncat(status,"NONE",strlen("NONE")); strncat(status,"\r\n",strlen("\r\n")); strncat(status,"\r\n",strlen("\r\n")); strncat(status,"<HEAD><TITLE>501 Not Implemented</TITLE></HEAD>",strlen("<HEAD><TITLE>501 Not Implemented</TITLE></HEAD>")); strncat(status,"<body>501 Not Implemented: File format not supported:",strlen("<body>501 Not Implemented: File format not supported:")); strncat(status,"HTTP/1.1",strlen("HTTP/1.1")); strncat(status,"</body></html>",strlen("</body></html>")); strncat(status,"\r\n",strlen("\r\n")); write(clients[n], status, strlen(status)); } } if (!strstr(msg_from_client,"Connection: Keep-alive")) { } else { shutdown (clients[n], SHUT_RDWR); // Send and recv disabled close(clients[n]); clients[n]=-1; exit(0); } } } int main(int argc, char *argv[]) { int conn_count = 0; struct sockaddr_in clientAddr; socklen_t addrlen; struct sigaction custom_signal; custom_signal.sa_handler = signal_handler; if(sigfillset(&custom_signal.sa_mask) == -1) { printf("\nERR:Signal Mask Setting Failed!\n"); return 1; } if(sigaction(SIGINT, &custom_signal, NULL) == -1) { printf("\nERR:Cannot Handle SIGINT!\n"); return 1; } if(sigaction(SIGTERM, &custom_signal, NULL) == -1) { printf("\nERR:Cannot Handle SIGTERM!\n"); return 1; } wsconf_read(); for(int i= 0; i<MAX_CONN; i++) { clients[i] = -1; //Setting all socket values as -1 } int port = atoi(PORT_NUM); if(port < 1024) { printf("\n Chosen Port is invalid (Occupied by system defaults) \n"); exit(1); } start_server(port); while(1) // Server Running forever { addrlen = sizeof(clientAddr); clients[conn_count] = accept (sock, (struct sockaddr *) &clientAddr, &addrlen); printf("%d\n",clients[conn_count]); if(clients[conn_count] < 0) { printf("\n Error in Connection Accept! \n"); } else { if(!fork()) { conn_response(conn_count); } while (clients[conn_count]!=-1) { conn_count = (conn_count+1)%MAX_CONN; } } } }
C
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.c * Author: Nado * * Created on 7. Mai 2017, 16:16 */ #include <stdio.h> #include <stdlib.h> #include "stack.h" /* * */ int main(int argc, char** argv) { // // //TODO achtung , falls zuviele Werte eingebeben werden // intstack_t firststack; // firststack.size = 1000; // stackInit(&firststack); //// // stackGetBack(4,&firststack); //// //// // printf("&d",firststack.stack[10]); // stackPush(&firststack, 100); // stackPush(&firststack, 20); // printf("%d \n", stackTop(&firststack)); // // stackPop(&firststack); // printf("%d", stackTop(&firststack)); // // // // printf("%d",stackGetBack(0,&firststack)); // for(int i = 0; i < 50; i++){ // stackPush(&firststack, i); // } // // stackPrint(&firststack); // intstack_t stack; stackInit(&stack); fprintf(stderr, "%s", "Stack overfloww!\n"); stackPush(&stack, 1); stackPush(&stack, 2); stackPush(&stack, 3); printf("%d \n",!stackIsEmpty(&stack)); // while (!stackIsEmpty(&stack)) // printf("%i\n", stackPop(&stack)); int i = 0; while(i< 100000){ stackPush(&stack,i); i++; } stackPop(&stack); stackPrint(&stack); stackRelease(&stack); stackPop(&stack);stackPop(&stack); stackPop(&stack); return (EXIT_SUCCESS); }
C
// // exercise7_9.c // C-Exercise // // Created by 许浩 on 2020/7/16. // Copyright © 2020 许浩. All rights reserved. // #include "exercise7_9.h" // 使用continue跳过部分循环 int exercise7_9(void){ const float MIN = 0.0f; const float MAX = 100.0f; float score; float total = 0.0f; int n = 0; float min = MAX; float max = MIN; printf("Enter the first score(q to quit):"); while (scanf("%f",&score)==1) { if(score<MIN || score>MAX){ printf("%0.1f is an invalid value. Try again:", score); continue; // 跳转至while循环的测试条件 } printf("Accepting %0.lf:\n", score); min = (score<min)?score:min; max=(score>max)?score:max; total+=score; n++; printf("Enter next score (q to quit):"); } if (n>0) { printf("Average of %d scores is %0.1f.\n",n,total/n); printf("Low = %0.1f, high=%0.1f\n", min,max); }else{ printf("No valid scores were entered.\n"); } return 0; }
C
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <err.h> /* Напишете програма на С, която да работи като обвивка на командата sort тоест вашата програма изпълнява sort като всички подадени параметри се предават на sort. Изхода за грешки по време на изпълнението да отива във файл с име serror.txt */ int main(int argc, char* argv[]) { // int fd1[2]; // fd1[0] is the read end, fd1[1] is the writing end //dup2(old_fd, new_fd) duplicates the functions of old fd to new fd int my_err_file = open("serror.txt", O_RDWR|O_CREAT); dup2(my_err_file, 2); if (argc < 2) { errx(1, "No arguments passed"); } if( execvp("sort", argv) == -1 ) { err(2, "Cant exec sort."); } }
C
#include<stdio.h> #include<stdlib.h> #include<time.h> clock_t start,stop; double duration; void PrintN(int N) { if(N){ PrintN(N-1); printf("%d\n",N); } return; } void PrintN(int N); int main() { int N; scanf("%d",&N); start=clock(); PrintN(N); stop=clock(); duration=((double)(stop-start))/CLK_TCK; printf("%e\n",duration); system("pause"); return 0; }
C
/* * Copyright (c) 2006 Jakub Jermar * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** @addtogroup genericadt * @{ */ /** @file */ #ifndef KERN_HASH_TABLE_H_ #define KERN_HASH_TABLE_H_ #include <adt/list.h> #include <typedefs.h> /** Set of operations for hash table. */ typedef struct { /** Hash function. * * @param key Array of keys needed to compute hash index. All keys must * be passed. * * @return Index into hash table. */ size_t (* hash)(sysarg_t key[]); /** Hash table item comparison function. * * @param key Array of keys that will be compared with item. It is not * necessary to pass all keys. * * @return true if the keys match, false otherwise. */ bool (*compare)(sysarg_t key[], size_t keys, link_t *item); /** Hash table item removal callback. * * @param item Item that was removed from the hash table. */ void (*remove_callback)(link_t *item); } hash_table_operations_t; /** Hash table structure. */ typedef struct { list_t *entry; size_t entries; size_t max_keys; hash_table_operations_t *op; } hash_table_t; #define hash_table_get_instance(item, type, member) \ list_get_instance((item), type, member) extern void hash_table_create(hash_table_t *h, size_t m, size_t max_keys, hash_table_operations_t *op); extern void hash_table_insert(hash_table_t *h, sysarg_t key[], link_t *item); extern link_t *hash_table_find(hash_table_t *h, sysarg_t key[]); extern void hash_table_remove(hash_table_t *h, sysarg_t key[], size_t keys); #endif /** @} */
C
#ifndef SOUND_PLAYER_H #define SOUND_PLAYER_H #include "sound_generator.h" #include "ex2.h" #include "efm32gg.h" /* Waveform to use when playing sound. */ typedef enum SoundType { Saw, Triangle, Square } soundType_t; /* State storing if music should be played or not. */ typedef enum PlayState { Running, Done, Paused } playState_t; /* Stores a song. */ typedef struct Song { uint *song; uint length; uint tempo; bool looping; } song_t; /* Used for playing a sound. */ typedef struct SoundPlayer { song_t *song; playState_t state; uint noteIndex; uint noteCounter; uint notePeriod; soundType_t soundType; uint volume; fp(*soundGen) (fp, uint); // Store sound generation function, so we won't have to look it up during sampling. } soundPlayer_t; /* Used to play mulitple sounds. Should only be one of these in the program. */ typedef struct Audio { soundPlayer_t *sounds; uint soundCount; } audio_t; /* Used to initialize a sound player. Caller is responsible for allocating space. */ void initSoundPlayer(soundPlayer_t * player, song_t * song, soundType_t soundType, uint volume); /* Get next sample from song. */ fp playSong(soundPlayer_t * player, uint time); /* Play songs. Call once per sampling period. Time is a clock variable mesured in sample rate ticks. */ void playAudio(audio_t * audio, uint time); /* Make song start playing from the start. */ void restart(soundPlayer_t * player); #endif
C
#include <stdio.h> #include <stdlib.h> int sommeTableau(int tableau[], int tailleTableau); double moyenneTableau(int tableau[], int tailleTableau); void copie(int tableauOriginal[], int tableauCopie[], int tailleTableau); void maximumTableau(int tableau[], int tailleTableau, int valeurMax); void ordonnerTableau(int tableau[], int tailleTableau); int main() { printf("Hello world!\n"); int tab[5] = {45,12,5,100,5}; int tab2[5] = {0}; printf("somme du tableau = %d\n", sommeTableau(tab, 5)); printf("moyenne du tableau = %f\n", moyenneTableau(tab, 5)); copie(tab, tab2, 5); maximumTableau(tab2, 5, 40); int tableau_desordonee[4] = {15,81,22,13}; ordonnerTableau(tableau_desordonee,4); return 0; } int sommeTableau(int tableau[], int tailleTableau) { int resultat; for(int i = 0; i<tailleTableau; i++) { resultat+=tableau[i]; } return resultat; } double moyenneTableau(int tableau[], int tailleTableau) { int total = 0; for(int i = 0; i<tailleTableau; i++) { total+=tableau[i]; } return total/tailleTableau; } void copie(int tableauOriginal[], int tableauCopie[], int tailleTableau) { for(int i = 0; i<tailleTableau; i++) { tableauCopie[i]+=tableauOriginal[i]; } } void maximumTableau(int tableau[], int tailleTableau, int valeurMax) { for(int i = 0; i < tailleTableau; i++) { if(tableau[i] > valeurMax) tableau[i] = 0; } } void ordonnerTableau(int tableau[], int tailleTableau) { int temp = 0; int j = 1; for(int i = 0; i < tailleTableau; i++) { for(int j = 0; j < tailleTableau; j++) { // A finir temp = tableau[j]; tableau[j] = tableau[i]; tableau[i] = temp; } for(int i = 0; i < tailleTableau; i++) { printf("%d | ", tableau[i]); } }
C
#include <gtest/gtest.h> #include <kmeans/geometry/point.h> TEST(Point, CalculateDistanceSamePoint) { struct KM_Point *point1 = KM_Point_Create(2, NULL); struct KM_Point *point2 = KM_Point_Create(2, NULL); point1->coord[0] = 2; point1->coord[1] = 2; point2->coord[0] = 2; point2->coord[1] = 2; double distance = KM_Point_GetDistance(point1, point2); ASSERT_EQ(distance, 0); KM_Point_Destroy(point1); KM_Point_Destroy(point2); } TEST(Point, CalculateDistance) { struct KM_Point *point1 = KM_Point_Create(2, NULL); struct KM_Point *point2 = KM_Point_Create(2, NULL); point1->coord[0] = 3; point1->coord[1] = 6; point2->coord[0] = 6; point2->coord[1] = 2; double distance = KM_Point_GetDistance(point1, point2); ASSERT_EQ(distance, 5); KM_Point_Destroy(point1); KM_Point_Destroy(point2); } TEST(Point, Clone) { struct KM_Point *point = KM_Point_Create(2, NULL); point->coord[0] = 3; point->coord[1] = 6; struct KM_Point *clone = KM_Point_Clone(point); ASSERT_FALSE(clone->coord == point->coord); for (unsigned int i = 0; i < point->dimensions; ++i) { ASSERT_DOUBLE_EQ(clone->coord[i], point->coord[i]); } KM_Point_Destroy(point); KM_Point_Destroy(clone); } TEST(Point, EqualDifferentDimensions) { struct KM_Point *p1 = KM_Point_Create(3, NULL); struct KM_Point *p2 = KM_Point_Create(2, NULL); ASSERT_FALSE(KM_Point_Equals(p1, p2)); KM_Point_Destroy(p1); KM_Point_Destroy(p2); } TEST(Point, EqualSameDimensions) { struct KM_Point *p1 = KM_Point_Create(2, NULL); struct KM_Point *p2 = KM_Point_Create(2, NULL); ASSERT_TRUE(KM_Point_Equals(p1, p2)); KM_Point_Destroy(p1); KM_Point_Destroy(p2); } TEST(Point, EqualSameCoordinates) { double input[2] = { 1.35, 5.68 }; struct KM_Point *p1 = KM_Point_Create(2, input); struct KM_Point *p2 = KM_Point_Create(2, input); ASSERT_TRUE(KM_Point_Equals(p1, p2)); KM_Point_Destroy(p1); KM_Point_Destroy(p2); } TEST(Point, EqualDifferentCoordinates) { double input1[2] = { 1.35, 5.68 }; double input2[2] = { 1.38, 4.68 }; struct KM_Point *p1 = KM_Point_Create(2, input1); struct KM_Point *p2 = KM_Point_Create(2, input2); ASSERT_FALSE(KM_Point_Equals(p1, p2)); KM_Point_Destroy(p1); KM_Point_Destroy(p2); }
C
//Wildcard(通配符) Matching /* '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). The function prototype should be: bool isMatch(const char *s, const char *p) Some examples: isMatch("aa","a") → false isMatch("aa","aa") → true isMatch("aaa","aa") → false isMatch("aa", "*") → true isMatch("aa", "a*") → true isMatch("ab", "?*") → true isMatch("aab", "c*a*b") → false */ /* 题目的意思是实现通配符?和*字符串匹配 这个题目和之前的10题Regular Expression Matching很相似,之前的那个题目是用动态规划来做的,比较恶心 ------------------------------------------------------------------------------------------------------------ 这个题目的用法是"?"匹配任何字符,那么不和.进行的匹配一样吗 */
C
// Implements a dictionary's functionality using a Hash function // Cheyanna Graham // Aug 2019 #include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include "dictionary.h" // Represents number of buckets in a hash table #define N 26 // Represents a node in a hash table typedef struct node { char word[LENGTH + 1]; struct node *next; } node; // Represents a hash table node *hashtable[N]; // Hashes word to a number between 0 and 25, inclusive, based on its first letter unsigned int hash(const char *word) { return tolower(word[0]) - 'a'; } // Loads dictionary into memory, returning true if successful else false bool load(const char *dictionary) { // Initialize hash table for (int i = 0; i < N; i++) { hashtable[i] = NULL; } // Open dictionary FILE *file = fopen(dictionary, "r"); if (file == NULL) { unload(); return false; } // Buffer for a word char word[LENGTH + 1]; // Insert words into hash table while (fscanf(file, "%s", word) != EOF) { // make new node int index = hash(word); node *new_node = malloc(sizeof(node)); strcpy(new_node->word, word); // Index == NULL if (!hashtable[index]) { new_node->next = NULL; } // Index == NODE, ADD Node & Shift else { new_node->next = hashtable[index]; } hashtable[index] = new_node; } // Close dictionary fclose(file); // Indicate success return true; } // Returns number of words in dictionary if loaded else 0 if not yet loaded unsigned int size(void) { int total = 0; for (int i = 0; i < N; i++) { if (hashtable[i]) { node *curr = hashtable[i]; while (curr) { total ++; curr = curr->next; } } } return total; } // Returns true if word is in dictionary else false bool check(const char *word) { node *curr_node = hashtable[hash(word)]; if (!curr_node) { return false; } int i = 0, word_len = strlen(word); while ( i < word_len) { // if the words don't match, move to the next node if (word_len != strlen(curr_node->word) || tolower(curr_node->word[i]) != tolower(word[i])) { i = 0; curr_node = curr_node->next; // no more nodes if(!curr_node) { return false; } } // the letters do match, compare next letter else { i++; } } return true; } // Unloads dictionary from memory, returning true if successful else false bool unload(void) { for (int i = 0; i < N; i++) { if (hashtable[i]) { node *curr = hashtable[i]; while (curr) { node *next = curr->next; free(curr); curr = next; } } } return true; }
C
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { int A, B, C; scanf("%d", &A); scanf("%d", &B); scanf("%d", &C); if((A==C)||(A==B)||(C==B)) { printf("S"); } else if (((A+B)==C)||((B+C)==A) || ((C+A)==B)) { printf("S"); } else { printf("N"); } return 0; }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<stdlib.h> #include<string.h> // ɾַָĸ char* deleteCharacters(char * str, char * charSet) { int hash[256]; if (NULL == charSet) return str; for (int i = 0; i < 256; i++) hash[i] = 0; for (int i = 0; i < strlen(charSet); i++) hash[charSet[i]] = 1; int currentIndex = 0; for (int i = 0; i < strlen(str); i++) { if (!hash[str[i]]) str[currentIndex++] = str[i]; } str[currentIndex] = '\0'; return str; } int main() { char s[2] = "a"; // Ҫɾĸ char s2[5] = "aca"; // Ŀַ printf("%s\n", deleteCharacters(s2, s)); system("pause"); return 0; }
C
#include "uls.h" void mx_printerr(t_errors errors, char s) { if(errors == INVALID_ARGV) { mx_print_error("uls: illegal option -- -"); mx_print_error("\n"); mx_print_error("usage: uls [-ACSTafhilorstu1] [file ...]"); } else if(errors == INVALID_FLAGS) { mx_print_error("uls: illegal option -- "); mx_printerr_char(s); mx_print_error("\n"); mx_print_error("usage: uls [-ACSTafhilorstu1] [file ...]"); } mx_print_error("\n"); exit(1); }
C
#include <stdio.h> int Fibonacci(int n,int a, int b) { if(n<=2) { printf("%d\n", b); return 1; } else return Fibonacci(n-1, b, a+b); } int main(void) { int n, x; scanf("%d", &n); for(int i=0; i<n; ++i) { scanf("%d", &x); Fibonacci(x, 1, 1); } }
C
/*Reading Map*/ #include<stdio.h> #include<string.h> int main() { FILE *ptr_file; char cfile; /*indexing variable*/ int i = 0;/*keyword_string*/ int j = 0, k = 0;/*ns_list or ew_list*/ int m = 0; /*at_and_string*/ int r = 0, s = 0;/*landmark entrance*/ int u = 0, v = 0;/*landmark boundary*/ /*enable variables*/ int keyword_enable = 1; /*used to check for keyword*/ char keyword_string[50]; /*stores list of street names [index][max string length]*/ char ew_list[100][50]; char ns_list[100][50]; /*store landmark string info[index][max string length]*/ char landmark_names[100][500]; char landmark_entrances[100][500]; char landmark_boundaries[100][500]; /*store landmark entrances and boundaries[index] [Entrance: NS STREET(X), EW STREET(Y), Boundaries: West (X1), East (X2), North (Y1), South (Y2)]*/ int landmark_entrance_coordinates[100][2]; int landmark_boundary_coordinates[100][4]; /*enable variables*/ int name_enable = 1; int entrance_enable = 0; int boundary_enable = 0; /*Store taxi stand street names*/ char taxi_stand_list[10][50]; /*store taxi stand location [Stand Number] [North-South Street (X),East-West Street (Y)]*/ int taxi_stand_coordinates[10][2]; /*enable variables*/ int at_and_enable = 1; char at_and_string[50]; /*check end of lists*/ int eof_ew; int eof_ns; int eof_taxi; /*open file stream*/ ptr_file = fopen("map.txt", "r"); /*Error check*/ if (!ptr_file) return (-1); /*Reading Loop*/ do { /*holds asci character read in the text file*/ cfile = fgetc(ptr_file); /*holds a keyword in string*/ if (keyword_enable == 1 && cfile >= ' ') { keyword_string[i] = cfile; i++; /*disable the keyword checker*/ if (cfile == ':') { keyword_enable = 0; #ifdef DEBUG printf("keyword_string is : %s\n", keyword_string); /*Check value of strcmp*/ printf("strcmp = %d\n", strcmp(keyword_string, "STREETS EAST-WEST:")); printf("strcmp = %d\n", strcmp(keyword_string, "STREETS NORTH-SOUTH:")); printf("strcmp = %d\n", strcmp(keyword_string, "LANDMARKS:")); printf("strcmp = %d\n", strcmp(keyword_string, "TAXI STANDS:")); #endif } } /*set it so the East-West list starts getting filled*/ if (strcmp(keyword_string, "STREETS EAST-WEST:") == 0) { if (cfile != ',' && cfile != '.') { /*First character cannot be space*/ if (k == 0 && cfile > ' ' && cfile != ':') { ew_list[j][k] = cfile; k++; } /*for remaining characters in string*/ else if (k > 0 && cfile >= ' ' && cfile != '.') { ew_list[j][k] = cfile; k++; } } else if (cfile == ',' || cfile == '.') { #ifdef DEBUG printf("%s \n", ew_list[j]); #endif /*move to next index*/ j++; /*reset filling in string*/ k = 0; } if (cfile == '.') eof_ew = j; } /*set it so the North-South list starts getting filled*/ if (strcmp(keyword_string, "STREETS NORTH-SOUTH:") == 0) { if (cfile != ',' && cfile != '.') { /*First character cannot be space*/ if (k == 0 && cfile > ' ' && cfile != ':') { ns_list[j][k] = cfile; k++; } /*for remaining characters in string*/ else if (k > 0 && cfile >= ' ' && cfile != '.') { ns_list[j][k] = cfile; k++; } } else if (cfile == ',' || cfile == '.') { #ifdef DEBUG printf("%s \n", ns_list[j]); #endif /*move to next index*/ j++; /*reset filling in string*/ k = 0; } if (cfile == '.') eof_ns = j; } /*set it so the Landmark list starts getting filled*/ if (strcmp(keyword_string, "LANDMARKS:") == 0) { /*Store Landmark name strings*/ if (name_enable == 1) { if (cfile != ';') { /*First character cannot be space*/ if (k == 0 && cfile > ' ' && cfile != ':') { landmark_names[j][k] = cfile; k++; } /*for remaining characters in string*/ else if (k > 0 && cfile >= ' ' && cfile != '.') { landmark_names[j][k] = cfile; k++; } } else if (cfile == ';') { printf("index : %d \n", j); printf("%s \n", landmark_names[j]); /*move to next index*/ j++; /*reset filling in string*/ k = 0; } } /*Store Landmark Entrances strings*/ if (entrance_enable == 1) { if (strcmp(at_and_string, "AT") == 0) { if (cfile != ',') { /*First character cannot be space*/ if (s == 0 && cfile > ' ' && cfile != ':') { landmark_entrances[r][s] = cfile; s++; } /*for remaining characters in string*/ else if (s > 0 && cfile >= ' ' && cfile != '.') { landmark_entrances[r][s] = cfile; s++; } } } if (strcmp(at_and_string, "AND") == 0) { if (cfile != ',') { /*First character cannot be space*/ if (s == 0 && cfile > ' ' && cfile != ':') { landmark_entrances[r][s] = cfile; s++; } /*for remaining characters in string*/ else if (s > 0 && cfile >= ' ' && cfile != '.') { landmark_entrances[r][s] = cfile; s++; } } } /*Check for AT or AND in text file*/ if ((cfile == 'A' || cfile == 'T' || cfile == 'N' || cfile == 'D') && at_and_enable == 1) { #ifdef DEBUG printf("strcmp AT = %d\n", strcmp(at_and_string, "AT")); printf("strcmp AND = %d\n", strcmp(at_and_string, "AND")); printf("%c \n", cfile); #endif at_and_string[m] = cfile; m++; if (strcmp(at_and_string, "AT") == 0) { printf("%s \n", at_and_string); at_and_enable = 0; } if (strcmp(at_and_string, "AND") == 0) { printf("%s \n", at_and_string); at_and_enable = 0; } } } /*Store Landmark Boundary strings*/ if (boundary_enable == 1) { } if (cfile == ';') { printf("%s \n", landmark_names[j]); /*reset at_and_string*/ m = 0; at_and_enable = 1; memset(at_and_string, 0, 50); } if (cfile == ',' || cfile == '.') { printf("index : %d \n", j); printf("%s \n", landmark_entrances[r]); /*move to next index*/ r++; /*reset filling in string*/ s = 0; /*reset at_and_string*/ m = 0; at_and_enable = 1; memset(at_and_string, 0, 50); } } /*set it so the Taxi Stand list starts getting filled*/ if (strcmp(keyword_string, "TAXI STANDS:") == 0) { if (strcmp(at_and_string, "AT") == 0) { if (cfile != ',') { /*First character cannot be space*/ if (k == 0 && cfile > ' ' && cfile != ':') { taxi_stand_list[j][k] = cfile; k++; } /*for remaining characters in string*/ else if (k > 0 && cfile >= ' ' && cfile != '.') { taxi_stand_list[j][k] = cfile; k++; } } } if (strcmp(at_and_string, "AND") == 0) { if (cfile != ',') { /*First character cannot be space*/ if (k == 0 && cfile > ' ' && cfile != ':') { taxi_stand_list[j][k] = cfile; k++; } /*for remaining characters in string*/ else if (k > 0 && cfile >= ' ' && cfile != '.') { taxi_stand_list[j][k] = cfile; k++; } } } /*Check for AT or AND in text file*/ if ((cfile == 'A' || cfile == 'T' || cfile == 'N' || cfile == 'D') && at_and_enable == 1) { #ifdef DEBUG printf("strcmp AT = %d\n", strcmp(at_and_string, "AT")); printf("strcmp AND = %d\n", strcmp(at_and_string, "AND")); printf("%c \n", cfile); #endif at_and_string[m] = cfile; m++; if (strcmp(at_and_string, "AT") == 0) { printf("%s \n", at_and_string); at_and_enable = 0; } if (strcmp(at_and_string, "AND") == 0) { printf("%s \n", at_and_string); at_and_enable = 0; } } if (cfile == ';') { /*reset at_and_string*/ m = 0; at_and_enable = 1; memset(at_and_string, 0, 50); } if (cfile == ',' || cfile == '.') { printf("index : %d \n", j); printf("%s \n", taxi_stand_list[j]); /*move to next index*/ j++; /*reset filling in string*/ k = 0; /*reset at_and_string*/ m = 0; at_and_enable = 1; memset(at_and_string, 0, 50); } if (cfile == '.') eof_taxi = j; } /*set it so the Parking list starts getting filled*/ if (strcmp(keyword_string, "PARKING:") == 0) { } /*Renable keyword reading, reset keyword_string, reset list indexing*/ if (cfile == '.') { j = 0; k = 0; i = 0; keyword_enable = 1; memset(keyword_string, 0, 50); } /*Exits reading the file once end is reached*/ if (feof(ptr_file)) { break; } } while (1); /*fill in taxi_stand_coordinates*/ for (j = 0; j < eof_taxi; j++) { /*NS Street (X)*/ for (i = 0; i < 100; i++) { if (strcmp(taxi_stand_list[j], ns_list[i]) == 0) { taxi_stand_coordinates[j][0] = i; printf("X coordinate: %d\n", taxi_stand_coordinates[j][0]); break; } } /*EW Street (Y)*/ for (i = 0; i < 100; i++) { if (strcmp(taxi_stand_list[j], ew_list[i]) == 0) { taxi_stand_coordinates[j][1] = i; printf("Y coordinate: %d\n", taxi_stand_coordinates[j][1]); break; } } } /*close file stream*/ fclose(ptr_file); return 0; }
C
#include <stdio.h> #include <locale.h> //быстрая сортировка void qsort(int* arraySize, int start, int finish){ int i=start, j=finish, x=arraySize[(start+finish)/2]; do { while (arraySize[i]<x) i++; while (arraySize[j]<x) j--; if(i<=j){ if(arraySize[i]>arraySize[j]){ int tmp = arraySize[i]; arraySize[i] = arraySize[j]; arraySize[j] = arraySize[tmp]; } i++; j--; } } while (i<=j); (i<finish) ? qsort(arraySize, i, finish) : 0; (start<j) ? qsort(arraySize, start, j) : 0; } int main(){ setlocale(LC_ALL, "Rus"); int n1, n2; puts("Введите размеры массива: "); scanf("%d%d", &n1, &n2); int mas1[n1], mas2[n2]; puts("Введите первый массив: "); for(int i=0;i<n1;i++) scanf("%d", &mas1[i]); puts("Введите второй массив: "); for(int i=0;i<n2;i++) scanf("%d", &mas2[i]); //отсортируем массивы, для быстрого поиска //int a = n1; //qsort(a, mas1[0],mas1[n1-1]); /* for(int i=1;i<n1;i++){ for(int k=0;k<n1-i;k++){ if(mas1[k]<mas1[k+1]){ mas1[k]+=mas1[k+1]; mas1[k+1] = mas1[k]-mas1[k+1]; mas1[k] = mas1[k]-mas1[k+1]; } } } for(int i=0;i<n2;i++){ for(int k=0;i<n2;k++){ if(mas2[k]<mas2[k+1]){ mas2[k]+=mas2[k+1]; mas2[k+1] = mas2[k]-mas2[k+1]; mas2[k] -= mas2[k+1]; } } } */ int max = -99999; for(int i=0;i<n1;i++){ int flag=0; for(int k=0;k<n2;k++){ if(mas1[i]==mas2[k]){ flag=1; } } if(flag!=1){ max= max>mas1[i] ? max : mas1[i]; } } printf("Ответ: %d", max); }
C
/* * memdebug.h * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __MEM_DEBUG_H__ #define __MEM_DEBUG_H__ /** * memdebug_check_overflow() * * This function can be called at any point in the program. It will check if there * was a buffer overflow in any memory block allocated on the heap (with malloc or * calloc). It prints an error message on stderr for any detected overflow. * * * memdebug_check_leak() * * This function should be called at the very end of the program. It checks for * any memory block which was allocated but not freed. It prints an error message * on stderr and then free the leaking memory. This function is already called in * the tranalyzer2 core, you should not call it in plugins. * * * These functions are macro and produce no code if MEMORY_DEBUG != 1. * Therefore, they do not need to be commented in release code. * * * How to use memdebug in a plugin: * - #include "memdebug.h" in the C file of the plugin, * - change MEMORY_DEBUG in tranalyzer.h to enable or disable memory check, * - recompile tranalyzer2 and the plugin; */ #if MEMORY_DEBUG == 1 extern void* memdebug_malloc(size_t size, const char* file, unsigned int line); extern void memdebug_free(void* ptr, const char* file, unsigned int line); extern void* memdebug_calloc(size_t nmemb, size_t size, const char* file, unsigned int line); extern void* memdebug_realloc(void* ptr, size_t size, const char* file, unsigned int line); extern char* memdebug_strdup(const char* s, const char* file, unsigned int line); extern char* memdebug_strndup(const char* s, size_t n, const char* file, unsigned int line); extern void memdebug_check_overflow_int(const char* file, unsigned int line); extern void memdebug_check_leak_int(const char* file, unsigned int line); // overwrite all memory management functions #define malloc(size) memdebug_malloc((size), __FILE__, __LINE__) #define calloc(nmemb, size) memdebug_calloc((nmemb), (size), __FILE__, __LINE__) #define realloc(ptr, size) memdebug_realloc((ptr), (size), __FILE__, __LINE__) #define free(ptr) memdebug_free((ptr), __FILE__, __LINE__) #undef strdup #undef strndup #define strdup(s) memdebug_strdup((s), __FILE__, __LINE__) #define strndup(s, n) memdebug_strndup((s), (n), __FILE__, __LINE__) #define memdebug_check_overflow() memdebug_check_overflow_int(__FILE__, __LINE__) #define memdebug_check_leak() memdebug_check_leak_int(__FILE__, __LINE__) #else // MEMORY_DEBUG != 1 // mem_check functions do nothing in non memory debug mode #define memdebug_check_overflow() #define memdebug_check_leak() #endif // MEMORY_DEBUG #endif // __MEM_DEBUG_H__
C
#include "brainfuck.h" static struct globals* glob_accessor(struct globals* value) { static struct globals* glob = NULL; if (!glob && value) glob = value; return glob; } static struct globals* glob_init() { struct globals* glob = malloc(sizeof(struct globals)); if (!glob) err(1, "glob initialisation"); for (int i = 0; i < 256; ++i) glob->buffer[i] = 0; glob->pointer = 0; glob->stack = vect_create(); return glob_accessor(glob); } struct globals* glob_get() { struct globals* glob = glob_accessor(NULL); if (!glob) glob = glob_init(); return glob; }
C
#include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }*newnode,*temp,*head=NULL; void insertfirst(); void insertmid(); void insertlast(); void display(); int length(); void deletefirst(); void deletemid(); void deletelast(); int main() { printf("\t\t\t\t\t\tCircular Linked List\n"); int choice; while(1) { printf("\n1.Insert First"); printf("\n2.Insert Middle"); printf("\n3.Insert Last"); printf("\n4.Display"); printf("\n5.Delete First"); printf("\n6.Delete Middle"); printf("\n7.Delete End"); printf("\n8.Exit"); printf("\nEnter your choice: "); scanf("%d",&choice); switch(choice) { case 1: insertfirst(); break; case 2: insertmid(); break; case 3: insertlast(); break; case 4: display(); break; case 5: deletefirst(); break; case 6: deletemid(); break; case 7: deletelast(); break; case 8: exit(1); default: printf("\n!!!Enter Valid Choice!!!\n"); } } } int item,pos; void insertfirst() { newnode=(struct node*)malloc(sizeof(struct node)); printf("\nEnter the data to insert: "); scanf("%d",&item); temp=head; newnode->data=item; if(head==NULL) { newnode->next=newnode; head=newnode; printf("\nData inserted successfully\n"); } else { newnode->next=head; while(temp->next!=head) temp=temp->next; head=newnode; temp->next=newnode; printf("\nData inserted successfully\n"); } } void insertmid() { if(head==NULL) printf("\nList is Empty\n"); else if(head->next==head) printf("\nThere is one element in list\n"); else { int i=1; int count=length(); printf("\nEnter the position to insert: "); scanf("%d",&pos); if(pos<=count) { newnode=(struct node*)malloc(sizeof(struct node)); printf("\nEnter the element to insert: "); scanf("%d",&item); temp=head; newnode->data=item; while(i<pos-1) { temp=temp->next; i++; } newnode->next=temp->next; temp->next=newnode; printf("\nData inserted successfully\n"); } else printf("\nEnter valid position to insert!!!\n"); } } int length() { int count=0; temp=head; do { count++; temp=temp->next; }while(temp!=head); return count; } void insertlast() { if(head==NULL) printf("\nlist is Empty\n"); else { newnode=(struct node*)malloc(sizeof(struct node)); printf("\nEnter the element to insert: "); scanf("%d",&item); temp=head; while(temp->next!=head) temp=temp->next; newnode->data=item; newnode->next=head; temp->next=newnode; printf("\nData inserted successfully\n"); } } void display() { if(head==NULL) printf("\nList is Empty\n"); else { temp=head; printf("\nThe List elements are:"); do { printf("\t%d",temp->data); temp=temp->next; }while(temp!=head); } printf("\n"); } void deletefirst() { if(head==NULL) printf("\nList is Empty!!!\n"); else { if(head->next==head) { printf("\nThe deleted element is %d",head->data); free(head); head=NULL; printf("\nThe element is deleted successfully\n"); } else { struct node *temp1=temp=head; printf("\nThe deleted element is %d",temp->data); while(temp1->next!=head) temp1=temp1->next; head=temp->next; free(temp); temp=NULL; temp1->next=head; printf("\nThe element is deleted successfully\n"); } } } void deletemid() { if(head==NULL) printf("\nList is Empty\n"); else if(head->next==head) printf("\nThere is one element in the list"); else { int count=length(); printf("\nEnter the position to delete\t"); scanf("%d",&pos); if(pos<=count) { int i=1; struct node *temp1; temp=temp1=head; while(i<pos) { temp1=temp; temp=temp->next; i++; } printf("\nThe deleted element is %d",temp->data); temp1->next=temp->next; free(temp); temp=NULL; printf("\nThe element is deleted successfully!!!"); } else printf("\nEnter Valid Position"); } } void deletelast() { if(head==NULL) printf("\nList is Empty\n"); else { struct node *temp1=temp=head; while(temp->next!=head) { temp1=temp; temp=temp->next; } printf("\nThe deleted element is %d",temp->data); temp1->next=head; free(temp); temp=NULL; printf("\nThe element is deleted successfully\n"); } }
C
#include "include/Ncurses.h" #include "include/GameObject.h" #include "include/defs.h" #include "include/Matrix22.h" #include "include/Quaternion.h" #include "include/Time.h" #include <math.h> #include "include/Texture.h" #include "include/Panel.h" /** * renders a single fragment to the screen applying all shader functionality * to render directly to the screen, pass the frame buffer as NULL * */ static int renderFragment(FrameBuffer* frameBuffer, TriVert* data); /** * renders a triangle onto the screen * */ static void renderTriangle(TriVert* allVertInfo, Camera* camera, FrameBuffer* buffer, int drawMode, GameObject* object); /** * renders the entire scene * */ static void render(GOList* instance, FrameBuffer* buffer, Camera* cam); /** * renders a game object * */ static void renderObject(GameObject* object, Camera* cam, FrameBuffer* instance, int mode); /** * transforms a vertex from -1 to 1 to proper position on window * */ static Vertex transformVertex(Vertex vertex, int maxx, int maxy, Matrix44* transformationMatrix); /** * finds the max vertex positions of the triagle * */ static void getMinMax(const Vertex* v1, const Vertex* v2, const Vertex* v3, Vector2* xMax, Vector2* yMax); /** * renders a panel to the screen * */ static void renderPanel(FrameBuffer* instance, Panel* panel); //for finding the fps when buffering the frame int renderBufferFPS = 0; int bufferIndex = 0; FrameBuffer* buffers[2]; thread_t renderBuffers; int rendering = 0; int* run; /** * used to double buffer the render process * basically, this thread renders stuff and when it is done, it switches to another buffer and does it again * while the other thread is presenting the rendered information, this thread is writing a new buffer * Why is this an optimization? It actually isnt when dealing with small amounts of objects and triangles, it starts to show how powerful it is when there are many many triangles * In the previous system, we were only drawing the pixels that were written that frame to the screen, that is great, as long as we don't want a background and other stuff * it is also very very slow when objects take up a large part of the screen. * With this solution, the efficiency is only capped by the time it takes to render a buffer, or by the time it takes to present a buffer * this leads to much more consistent fps although slower with low poly * you can think of this as only doing the slower of these two slow processes per frame instead of both of them per frame so it should lead to twice the fps and it will be noticable when there are many models in the game * */ void* BufferRender(void* i){ Instance* instance = (Instance*)i; buffers[0] = instance->mainFrame; buffers[1] = instance->swapFrame; Timer bufferTimer = TimerCreate(); Timer bufferFPSCounter = TimerCreate(); float bufferDelta = 0; while(*run){ //update the timer so I can find how long it took to render the buffer TimerUpdate(&bufferTimer); FrameBufferClear(buffers[bufferIndex ^ 1], BR_COLOR_BUFFER_BIT | BR_DEPTH_BUFFER_BIT, CLEAR_COLOR); //render the frame buffer CameraCalculateViewMatrix(&instance->camera); render(instance->objects, buffers[bufferIndex ^ 1], &instance->camera); TimerUpdate(&bufferFPSCounter); renderBufferFPS = bufferFPSCounter.currentFPS; //render the menus Panel* p = instance->menus; while(p){ renderPanel(buffers[bufferIndex ^ 1], p); p = p->next; } //record the time it took to render the frame in seconds and convert it to milliseconds bufferDelta = TimerUpdate(&bufferTimer); bufferIndex ^= 1; //use the calculated difference in time to adjust frame delay sleep_ms(FRAME_TIME_MS - (bufferDelta * 1000)); } return NULL; } //Vector3 lightPos = {0, 0, 10}; char MainLoop(int* running, Instance* instance, char (*inputCallback)(float, int*)){ run = running; buffers[0] = instance->mainFrame; buffers[1] = instance->swapFrame; //int err = pthread_create(&renderBuffers, NULL, BufferRender, instance); ThreadCreate(&renderBuffers, BufferRender, (void*)instance); Timer mainFps = TimerCreate(); Timer renderTimer = TimerCreate(); float renderDelta = 0; float delta = 0; while(*running){ //lightPos = instance->camera.position; TimerUpdate(&renderTimer); erase(); int startx, starty, sizex, sizey; startx = 0; starty = 0; sizex = (TERMINAL_COLS + 1); sizey = (TERMINAL_LINES + 1); //render the scene FrameBufferRender(buffers, &bufferIndex, startx, starty, sizex, sizey); //output the current frames attron(COLOR_PAIR(WHITE)); //output basic debug info mvprintw(0, 0, "FPS main: %d", mainFps.currentFPS); mvprintw(1, 0, "FPS thread: %d", renderBufferFPS); //collect user input for later use inputCallback(delta, running); //allow user to output text here refresh(); //get the total time to render the frame renderDelta = TimerUpdate(&renderTimer); //update the physics of each and every object GOList* objects = instance->objects; while(objects){ GOUpdatePhysics(objects->object, delta); objects = objects->next; } //update the menus Panel* p = instance->menus; while(p){ //we have found the focused window if(!p->next){ PanelUpdate(p); break; } p = p->next; } //lock framerate sleep_ms(FRAME_TIME_MS - (renderDelta * 1000)); //find the delta value for next frame delta = TimerUpdate(&mainFps); //if its windows 32, I don't have a good way of getting the time yet, so I will just assume the FPS is around 60 and call it good //it wont work most of the time, but it is better than nothing if(instance->paused){ delta = 0; } //sleep_ms(4); //if this thread is reading from the buffer the other is writing to, it is time to mutex lock it, otherwise, it is time to mutex unlock it //pthread_mutex_unlock(renderBuffers); } //pthread_detach(renderBuffers); //I cannot do this in the future, I need to make the render buffer immediately exit when the code gets to here sleep_ms(100); return 0x30; } static void renderPanel(FrameBuffer* buffer, Panel* panel){ char* text = panel->text; char* options = panel->options; //clear all the stuff beneath the panel and draw the border //also draw the characters to the right location for(int i = panel->startx; i < panel->startx + panel->scalex; i++){ for(int j = panel->starty; j < panel->starty + panel->scaley; j++){ if(j > buffer->frameHeight){ break; } char character = ' '; if(j == panel->starty + panel->scaley - 1 || j == panel->starty){ character = '_'; } if(i == panel->startx + panel->scalex - 1 || i == panel->startx){ if(j != panel->starty && j != panel->starty + panel->scaley){ character = '|'; } } buffer->frame[(j * buffer->frameWidth) + i] = (WHITE << 8) | character; } } //draw the prompt text to the buffer int cursx, cursy; cursx = panel->startx + panel->textOffsetX; cursy = panel->starty + panel->textOffsetY; while(*text){ if(cursy > buffer->frameHeight){ break; } if(*text == '~'){ cursx = panel->startx + panel->textOffsetX; cursy ++; text++; continue; } buffer->frame[(cursy * (int)buffer->frameWidth) + cursx] = (panel->textColor << 8) | *text; text ++; cursx ++; } //draw the options to the menu now cursx = panel->startx + panel->textOffsetX; cursy += 2; int currop = 0; while(*options){ if(cursy > buffer->frameHeight){ break; } //if it is the next option, dont render the charcter and just move on if(*options == '~'){ cursx = panel->startx + panel->textOffsetX; cursy ++; options++; currop++; continue; } if(currop == panel->currentOption){ buffer->frame[(cursy * (int)buffer->frameWidth) + cursx] = (panel->selectionColor << 8) | *options; } else{ buffer->frame[(cursy * (int)buffer->frameWidth) + cursx] = (panel->optionColor << 8) | *options; } cursx ++; options ++; } } /** * finds the barry centric coord of the passed triangle * */ static float sign (Vector2* p1, Vector2* p2, Vector2* p3){ return (p1->x - p3->x) * (p2->y - p3->y) - (p2->x - p3->x) * (p1->y - p3->y); } int PointInTriangle (Vector2* pt, Vertex* vert1, Vertex* vert2, Vertex* vert3){ int b1, b2, b3; Vector2 v1Pos = Vec2Create(vert1->position.x, vert1->position.y); Vector2 v2Pos = Vec2Create(vert2->position.x, vert2->position.y); Vector2 v3Pos = Vec2Create(vert3->position.x, vert3->position.y); b1 = sign(pt, &v1Pos, &v1Pos) < 0.0f; b2 = sign(pt, &v2Pos, &v2Pos) < 0.0f; b3 = sign(pt, &v3Pos, &v3Pos) < 0.0f; return ((b1 == b2) && (b2 == b3)); } void render(GOList* objects, FrameBuffer* buffer, Camera* cam){ while(objects){ //render if the object should render if(objects->object->rendering) renderObject(objects->object, cam, buffer, RENDER_TRIANGLE_FILL); //GOUpdatePhysics(objects->object); objects = objects->next; } } static void renderTriangle(TriVert* allVertInfo, Camera* cam, FrameBuffer* buffer, int drawMode, GameObject* object){ //get the position in model view space Vertex v1 = transformVertex(*allVertInfo->v1, buffer->frameWidth, buffer->frameHeight, allVertInfo->finalMatrix); Vertex v2 = transformVertex(*allVertInfo->v2, buffer->frameWidth, buffer->frameHeight, allVertInfo->finalMatrix); Vertex v3 = transformVertex(*allVertInfo->v3, buffer->frameWidth, buffer->frameHeight, allVertInfo->finalMatrix); //get the position in world space /** Vertex worldv1 = transformVertex(*allVertInfo->v1, buffer->frameWidth, buffer->frameHeight, allVertInfo->transformMatrix); Vertex worldv2 = transformVertex(*allVertInfo->v2, buffer->frameWidth, buffer->frameHeight, allVertInfo->transformMatrix); Vertex worldv3 = transformVertex(*allVertInfo->v3, buffer->frameWidth, buffer->frameHeight, allVertInfo->transformMatrix); */ //projection space backface culling if(object->cullBackFaces){ Vector3 bv0 = v1.position; Vector3 bv1 = v2.position; Vector3 bv2 = v3.position; Vector3 U = Vec3Sub(&bv1, &bv0); Vector3 V = Vec3Sub(&bv2, &bv0); Vector3 C = Vec3Cross(&U, &V); if(C.z >= 0){ return; } } //projection space near culling if(v1.position.z < 0 || v2.position.z < 0 || v3.position.z < 0){ return; } //far culling if(v1.position.z > cam->zFar || v2.position.z > cam->zFar || v3.position.z > cam->zFar){ return; } Vector2* texCoord1 = allVertInfo->texCoord1; Vector2* texCoord2 = allVertInfo->texCoord2; Vector2* texCoord3 = allVertInfo->texCoord3; //world normal positions Vector4 n1 = Vec4CreateFromVec3(*allVertInfo->n1); Vector4 n2 = Vec4CreateFromVec3(*allVertInfo->n2); Vector4 n3 = Vec4CreateFromVec3(*allVertInfo->n3); //transform the normals Matrix44Transform(allVertInfo->transformMatrix, &n1, &n1); Matrix44Transform(allVertInfo->transformMatrix, &n2, &n2); Matrix44Transform(allVertInfo->transformMatrix, &n3, &n3); //world vertex positions Vector4 worldv1 = Vec4CreateFromVec3(allVertInfo->v1->position); worldv1.w = 1.0f; Vector4 worldv2 = Vec4CreateFromVec3(allVertInfo->v2->position); worldv2.w = 1.0f; Vector4 worldv3 = Vec4CreateFromVec3(allVertInfo->v3->position); worldv3.w = 1.0f; //transform the vertices Matrix44Transform(allVertInfo->transformMatrix, &worldv1, &worldv1); Matrix44Transform(allVertInfo->transformMatrix, &worldv2, &worldv2); Matrix44Transform(allVertInfo->transformMatrix, &worldv3, &worldv3); switch(drawMode){ case RENDER_POINTS: //probably will never implement this case RENDER_LINES: //probably will never implement this case RENDER_TRIANGLE_FILL: { Vector2 x, y; getMinMax(&v1, &v2, &v3, &x, &y); if(x.x < 0.0f){ x.x = 0.0f; } else if(x.x > buffer->frameWidth){ //return; x.x = buffer->frameWidth; } if(x.y > buffer->frameWidth){ x.y = buffer->frameWidth; } else if(x.y < 0.0f){ //return; x.y = 0.0f; } if(y.x < 0.0f){ y.x = 0.0f; } else if(y.x > buffer->frameHeight){ //return; y.x = buffer->frameHeight; } if(y.y > buffer->frameHeight){ y.y = buffer->frameHeight; } else if(y.y < 0.0f){ //return; y.y = 0.0f; } for(int j = y.x; j <= y.y; j++){ int draw = 0; for(int i = x.x; i < x.y; i++){ float wv1 = ((v2.position.y - v3.position.y) * ((float)i - v3.position.x) + (v3.position.x - v2.position.x) * ((float)j - v3.position.y)) / ((v2.position.y - v3.position.y) * (v1.position.x - v3.position.x) + (v3.position.x - v2.position.x) * (v1.position.y - v3.position.y)); float wv2 = ((v3.position.y - v1.position.y) * ((float)i - v3.position.x) + (v1.position.x - v3.position.x) * ((float)j - v3.position.y)) / ((v2.position.y - v3.position.y) * (v1.position.x - v3.position.x) + (v3.position.x - v2.position.x) * (v1.position.y - v3.position.y)); float wv3 = 1.0f - wv1 - wv2; int one = (wv1 < 0); int two = (wv2 < 0); int three = (wv3 < 0); //is the point in the triangle if((one == two) && (two == three)){ //if(PointInTriangle(&point, v1, v2, v3)){ //check depth information //interpolate across the vertices to find the z position of the fragment //yay time to use some more barycentric interpolation float fragz = (v1.position.z * wv1) + (v2.position.z * wv2) + (v3.position.z * wv3); fragz /= cam->zFar; Vector2 fragTexCoord; fragTexCoord.x = (double)(texCoord1->x * wv1) + (texCoord2->x * wv2) + (texCoord3->x * wv3); fragTexCoord.y = (double)(texCoord1->y * wv1) + (texCoord2->y * wv2) + (texCoord3->y * wv3); Vertex fragPos; fragPos.position.x = i; fragPos.position.y = j; fragPos.position.z = fragz; //calculate fragment normal from other vertex normals Vector3 fragNormal; fragNormal.x = (double)(n1.x * wv1) + (n2.x * wv2) + (n3.x * wv3); fragNormal.y = (double)(n1.y * wv1) + (n2.y * wv2) + (n3.y * wv3); fragNormal.z = (double)(n1.z * wv1) + (n2.z * wv2) + (n3.z * wv3); //get the world position of the fragment Vector3 worldFragPos; worldFragPos.x = (double)(worldv1.x * wv1) + (worldv2.x * wv2) + (worldv3.x * wv3); worldFragPos.y = (double)(worldv1.y * wv1) + (worldv2.y * wv2) + (worldv3.y * wv3); worldFragPos.z = (double)(worldv1.z * wv1) + (worldv2.z * wv2) + (worldv3.z * wv3); TriVert fragVert; fragVert.v1 = &fragPos; fragVert.n2 = &worldFragPos; fragVert.n1 = &fragNormal; fragVert.n3 = &cam->lightPos; fragVert.texCoord1 = &fragTexCoord; fragVert.transformMatrix = allVertInfo->transformMatrix; if(renderFragment(buffer, &fragVert)) draw = 1; } else{ if(draw){ //break; } } } } } } } void renderObject(GameObject* object, Camera* camera, FrameBuffer* buffer, int mode){ //transform verticies to screen coords from (0 to WINDOW_WIDTH)-> (-1 to 1) and (0 to WINDOW_HEIGHT) -> (-1 to 1) Matrix44 transformationMatrix = Matrix44Create(); Vector3 vec; //apply the projection matrix //Matrix44MultMatrix44(&transformationMatrix, &camera->projection, &transformationMatrix); //Matrix44MultMatrix44(&transformationMatrix, &camera->view, &transformationMatrix); //translation vec.x = object->transform.position.x; vec.y = object->transform.position.y; vec.z = object->transform.position.z; Matrix44Translate(&vec, &transformationMatrix, &transformationMatrix); //scale Matrix44 scaleMatrix = Matrix44Create(); vec.x = object->transform.scale.x; vec.y = object->transform.scale.y; vec.z = object->transform.scale.z; Matrix44Scale(&vec, &scaleMatrix, &scaleMatrix); Matrix44 rotationMatrix = Matrix44Create(); vec.x = 1; vec.y = 0; vec.z = 0; Matrix44Rotate(object->transform.rotation.x, &vec, &rotationMatrix, &rotationMatrix); vec.x = 0; vec.y = 1; vec.z = 0; Matrix44Rotate(object->transform.rotation.y, &vec, &rotationMatrix, &rotationMatrix); vec.x = 0; vec.y = 0; vec.z = 1; Matrix44Rotate(object->transform.rotation.z, &vec, &rotationMatrix, &rotationMatrix); Matrix44MultMatrix44(&transformationMatrix, &scaleMatrix, &transformationMatrix); Matrix44MultMatrix44(&transformationMatrix, &rotationMatrix, &transformationMatrix); Matrix44 finalTrans; Matrix44MultMatrix44(&camera->view, &transformationMatrix, &finalTrans); Matrix44MultMatrix44(&camera->projection, &finalTrans, &finalTrans); //bind the texture for the object TextureBind(object->texture); //loop through each of the indices int indCount = object->model->indCount; int* ind = object->model->indices; for(int k = 0; k < indCount; k += 3){ Vertex vert1, vert2, vert3; vert1 = object->model->verts[ind[k + 0]]; vert2 = object->model->verts[ind[k + 1]]; vert3 = object->model->verts[ind[k + 2]]; TriVert allVertInfo; allVertInfo.v1 = &vert1; allVertInfo.v2 = &vert2; allVertInfo.v3 = &vert3; //set the texture coords Vector2 t1 = object->model->texCoords[object->model->texIndices[k + 0]]; Vector2 t2 = object->model->texCoords[object->model->texIndices[k + 1]]; Vector2 t3 = object->model->texCoords[object->model->texIndices[k + 2]]; Vector3 n1 = object->model->normals[object->model->normalIndices[k + 0]]; Vector3 n2 = object->model->normals[object->model->normalIndices[k + 1]]; Vector3 n3 = object->model->normals[object->model->normalIndices[k + 2]]; allVertInfo.texCoord1 = &t1; allVertInfo.texCoord2 = &t2; allVertInfo.texCoord3 = &t3; allVertInfo.n1 = &n1; allVertInfo.n2 = &n2; allVertInfo.n3 = &n3; allVertInfo.transformMatrix = &transformationMatrix; allVertInfo.finalMatrix = &finalTrans; renderTriangle(&allVertInfo, camera, buffer, mode, object); } } static Vertex transformVertex(Vertex vertex, int maxx, int maxy, Matrix44* transformationMatrix){ Vertex ret; Vector4 final; Vector4 prev = Vec4Create(vertex.position.x, vertex.position.y, vertex.position.z, 1); Matrix44Transform(transformationMatrix, &prev, &final); //vertex.position = Matrix22Transform(&finalTransform, &vertex.position); vertex.position.x = final.x / final.z; vertex.position.y = final.y / final.z; float maxDivX = maxx / 2.0f; float maxDivY = maxy / 2.0f; vertex.position.y *= -1; float newx = (maxDivX * vertex.position.x) + maxDivX; float newy = (maxDivY * vertex.position.y) + maxDivY; ret.position.x = newx; ret.position.y = newy; ret.position.z = final.z; return ret; } //char shades[] = {'#', '*', '+', '-', '.', ' '}; char shades[] = {'#', '&', '%', '*', '+', '-', '\'', '.', ' '}; int numShades = 9; static int renderFragment(FrameBuffer* frameBuffer, TriVert* data){ float x, y, z; x = data->v1->position.x; y = data->v1->position.y; z = data->v1->position.z; //should it render at this depth? depthBuffer_t depth = (depthBuffer_t)((float)z * DEPTH_BUFFER_MAX); int index = ((int)frameBuffer->frameWidth * (int)y) + (int)x; if(depth > frameBuffer->depth[index]){ return 0; } //texture calculations double texX, texY; texX = data->texCoord1->x; texY = data->texCoord1->y; //normal data for lighting Vector3 fragNormal; fragNormal.x = data->n1->x; fragNormal.y = data->n1->y; fragNormal.z = data->n1->z; //get the world position of the light Vector3 lightPos = *data->n3; //get the world position of the fragment Vector3 worldPos = *data->n2; //get the position relative to the light Vector3 toLight; toLight = Vec3Sub(&lightPos, &worldPos); //normalize the damn vectors fragNormal = Vec3GetNormalized(&fragNormal); toLight = Vec3GetNormalized(&toLight); //get the brightness based on the dot product float nDot1 = Vec3Dot(&fragNormal, &toLight); float brightness = MAX(nDot1, 0.3); //brightness = 1; //get the color at the relative location on the texture (use the texture coords) color_t color = TextureSample((double)texX * 1, (double)texY * 1); char character = '0'; //invert brightness = 1 - brightness; brightness *= numShades; //brightness = 1; character = shades[(int)brightness]; //scale brighness from 0 to the number of brightness nodes frameBuffer->frame[(int)(frameBuffer->frameWidth * (int)(y) + (int)(x))] = (color << 8) | character; //set new depth frameBuffer->depth[index] = depth; return 1; } static void getMinMax(const Vertex* v1, const Vertex* v2, const Vertex* v3, Vector2* xMax, Vector2* yMax){ float minx, maxx, miny, maxy; minx = (float)MINOF3(v1->position.x, v2->position.x, v3->position.x); maxx = (float)MAXOF3(v1->position.x, v2->position.x, v3->position.x); miny = (float)MINOF3(v1->position.y, v2->position.y, v3->position.y); maxy = (float)MAXOF3(v1->position.y, v2->position.y, v3->position.y); xMax->x = minx; xMax->y = maxx; yMax->x = miny; yMax->y = maxy; }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> int main() { char num1[50],num2[50]; int n1,n2; scanf(" %d",&n1); scanf(" %d",&n2); sprintf(num1,"%d",n1); sprintf(num2,"%d",n2); if(strlen(num1)!=strlen(num2)){ printf("nao e permutacao"); return 0; } for(int i=0;i<strlen(num1);i++) { for(int j=0;j<strlen(num1);j++) { if(i==j)continue; if(num1[i]==num2[j]){ num1[i]=num2[j]='a'; } } } for(int j=0;j<strlen(num1);j++) if(num1[j]!='a') {printf("nao e permutacao"); return 0; } printf("a e permutacao de b"); return 0; }
C
#include <list_link.h> inline void list_init(struct list_link* sent) { sent->prev = sent; sent->next = sent; } inline bool list_empty(struct list_link* sent) { if (sent->prev == sent) { dbg_assert(sent->next == sent); return true; } dbg_assert(sent->next != sent); return false; } inline void list_link(struct list_link* n, struct list_link* prev, struct list_link *next) { n->prev = prev; n->next = next; prev->next = n; next->prev = n; } inline void list_unlink(struct list_link* n) { struct list_link* prev = n->prev; struct list_link* next = n->next; prev->next = next; next->prev = prev; } inline void list_insert_front(struct list_link* sent, struct list_link* n_node) { list_link(n_node, sent, sent->next); } inline void list_remove_front(struct list_link* sent) { list_unlink(sent->next); } inline void list_insert_back(struct list_link* sent, struct list_link* n_node) { list_link(n_node, sent->prev, sent); } inline void list_remove_back(struct list_link* sent) { list_unlink(sent->prev); } inline void list_remove(struct list_link* sent, struct list_link *node) { dbg_assert(sent != node); list_unlink(node); } inline void list_foreach(struct list_link* sent, pf_list_link_process process) { struct list_link* next = sent->next; struct list_link* prev = NULL; while (next != sent) { prev = next; next = next->next; /* we must first move the link to next, then do the processing, because * the process callback may delete the link itself */ process(prev); } } void list_foreach_v(struct list_link* sent, pf_list_link_process_v process_v, void* param) { struct list_link* next = sent->next; struct list_link* prev = NULL; while (next != sent) { prev = next; next = next->next; /* we must first move the link to next, then do the processing, because * the process callback may delete the link itself */ process_v(prev, param); } }
C
#include "functions.h" int fibonacci(int n){ if(n==0) return 0; if(n==1) return 1; int current = 1, previous=0, temp; while(n>=2) { temp= current; current =current + previous; previous =temp; n--; } return current; }
C
#include "grafo.h" #include <stdio.h> #include <stdlib.h> #include "fila.h" #include "lista.h" struct grafo_ { int vertices; int arestas; LISTA* *listas_de_adjascencia; }; GRAFO* grafo_criar(int n) // Cria um grafo com n vértices { GRAFO* g = (GRAFO*) malloc(sizeof(GRAFO)); if(n >= 0 && g != NULL) { g->vertices = n; g->arestas = 0; g->listas_de_adjascencia = (LISTA**) malloc(sizeof(LISTA*) * g->vertices); for(int i = 0; i < g->vertices; i++) // Loop que cria as listas de adjascencia. { g->listas_de_adjascencia[i] = lista_criar(); if(g-> listas_de_adjascencia[i] == NULL) return NULL; } return g; } return NULL; } /* * Função que insere uma aresta no grafo. * Retorna 0 caso a inserção seja realizada sem problema e, caso contsrário, retorna 1; */ int grafo_inserir_aresta(GRAFO* g, int no1, int no2) // Insere uma dada aresta. { if(g != NULL) { if(lista_inserir_fim(g->listas_de_adjascencia[no1], no2)) { g->arestas++; return 1; } if(lista_inserir_fim(g->listas_de_adjascencia[no2], no1)) { g->arestas++; return 1; } return 0; } return 1; } /* * Função que realiza a remoção de um dado elemento no grafo. * Retorna 0 caso a remoção tenha ocorrido sem problemas e, caso contrário, retorna 1; */ int grafo_remover_aresta(GRAFO* g, int no1, int no2) // Remove uma dada aresta. { if(g != NULL) { if(lista_remover(g->listas_de_adjascencia[no1], no2)) return 1; if(lista_remover(g->listas_de_adjascencia[no2], no1)) return 1; return 0; } return 1; } /* * Função que, nesta implementação, substitui as funções de inserção e remoção. * Esta função insere os vértices e as dimensoes de forma que o gráfico representa um tabuleido de dimensão: dimensoes x dimensoes * Cada vértice representa uma posição do tabuleiro, a as arestas representam quais posições estão adjascentes. */ int grafo_montaTabuleiro(GRAFO* tabuleiro, int dimensoes) { if(tabuleiro != NULL) { // Insere as arestas "Horizontais" for(int i = 0; i < dimensoes; i++) { for(int j = 0; j < (dimensoes - 1); j++) { if(grafo_inserir_aresta(tabuleiro, dimensoes*i + j, dimensoes*i + j + 1)) return 0; } } // Insere as arestas Verticais for(int i = 0; i < dimensoes; i++) { for(int j = 0; j < (dimensoes - 1); j ++) { if(grafo_inserir_aresta(tabuleiro, i + j*dimensoes, i + (j+1)*dimensoes)) return 0; } } return 1; } return 0; } void grafo_imprimir(GRAFO* g) // Imprime a lista de adjascência. { if(g != NULL) { for(int i = 0; i < g->vertices; i++) { printf("%d:", i); lista_imprimir(g->listas_de_adjascencia[i]); printf("\n"); } } return; } void grafo_deletar(GRAFO** g) // Apaga o grafo. { if((*g) != NULL) { for(int i = 0; i < (*g)->vertices; i++) lista_apagar(&((*g) -> listas_de_adjascencia[i])); free((*g) -> listas_de_adjascencia); free(*g); g = NULL; } } /* * Função que, dada um grafo G e um vértice deste grafo, gera um vetor que contém as distâncias dos outros vértices * ao vértice fornecido. * * O Algoritmo trata-se de uma Busca em Largura */ int* grafo_wavefront(GRAFO* G, int posicaoFantasma) { if(G != NULL && posicaoFantasma > 0 && posicaoFantasma < G->vertices) { FILA* f = fila_criar(); int vertice; int verticeAdjascente; int* anterior; int* distancias; anterior = (int*) malloc(sizeof(int) * G->vertices); distancias = (int*) malloc(sizeof(int) * G->vertices); // Inicializa o valor do Vetor "distancias": for(int i = 0; i < G->vertices; i++) distancias[i] = -2; distancias[posicaoFantasma] = -1; anterior [posicaoFantasma] = posicaoFantasma; fila_inserir(f, posicaoFantasma); while(!fila_vazia(f)) { vertice = fila_remover(f); verticeAdjascente = lista_primeiro_item(G->listas_de_adjascencia[vertice]); while(verticeAdjascente != ERRO) { if(distancias[verticeAdjascente] == -2) { fila_inserir(f, verticeAdjascente); anterior[verticeAdjascente] = vertice; distancias[verticeAdjascente] = -1; } verticeAdjascente = lista_proximo(G->listas_de_adjascencia[vertice]); } distancias[vertice] = distancias[anterior[vertice]] + 1; } fila_apagar(&f); return distancias; } fprintf(stderr, "Erro ao realizar o algoritmo Wavefront\n"); return NULL; } /* * A função abaixo, dado um grafo G, uma posição desse grafo, e a marcação do grafo por um algoritmo Wavefront, * atualiza a posição fornecida pelo usuário para uma posição que o deixará mais próximo do vértice a partir do qual * o algoritmo Wavefront foi realizado. */ int grafo_atualizaPacman(GRAFO* g, int posicaoPacman, int* distancias) { if(g != NULL && posicaoPacman >= 0 && posicaoPacman < g->vertices) { int menor = lista_primeiro_item(g->listas_de_adjascencia[posicaoPacman]); int aux = menor; while(aux != ERRO) { if(distancias[aux] < distancias[menor]) menor = aux; aux = lista_proximo(g->listas_de_adjascencia[posicaoPacman]); } return(menor); } return -1; }
C
#include "holberton.h" #include <stdio.h> #include <stdarg.h> #include <stdlib.h> /** * get_int - convert integer to string * @list: the character to add to string * @char_count: number of character that stores in buffer. * Return: string */ char *get_int(va_list list, int *char_count) { int num, num_tmp, len = 1, last_digit; char *string = NULL; num = va_arg(list, int); num_tmp = num; /* increase len by 1 if num_tmp is negative */ if (num_tmp < 0) len++; /* loop until num_tmp has only one digit */ while (num_tmp / 10 != 0) { /* increase len by 1 by each time num_tmp divide by 10 */ num_tmp = num_tmp / 10; len++; } *char_count = len; string = malloc(sizeof(char) * len + 1); if (string == NULL) return (NULL); string[len] = '\0'; /* loop until num has only 1 digit by dividing num by 10 in each loop*/ while (num <= -10 || num >= 10) { /* put the last digit of num in string from right to left */ last_digit = ((num % 10) >= 0) ? (num % 10) : -(num % 10); string[len - 1] = last_digit + '0'; /* decrease len by 1 to move index backward */ len--; num = num / 10; } /* for num is (-9) to (-1) */ if (num < 0) { string[0] = '-'; string[1] = -num + '0'; } /* for n is (0) to (9), put num to string*/ else string[0] = num + '0'; return (string); } /** * not_match - return null * @list: not use variable * @char_count: number of character that stores in buffer. * Return: null */ char *not_match(__attribute__((unused))va_list list, int *char_count) { return (NULL); (void) char_count; } /** * get_char - put/add character in buffer * @char_count: number of character that stores in buffer. * @list: the character to add to buffer * Return: buffer */ char *get_char(va_list list, int *char_count) { char *buffer; buffer = malloc(sizeof(char) * 2); if (buffer == NULL) return (NULL); buffer[0] = va_arg(list, int); /* put '\0' at the end of string */ buffer[1] = '\0'; *char_count = 1; return (buffer); } /** * get_string - put/add string in buffer * @char_count: number of character that stores in buffer. * @list: the string to add to buffer * * Return: buffer */ char *get_string(va_list list, int *char_count) { char *tmp = NULL; char *buffer = NULL; int i = 0, len = 0; tmp = va_arg(list, char*); /* if argument is NULL, print (null) */ if (tmp == NULL) tmp = "(null)"; len = _strlen(tmp); buffer = malloc(sizeof(char) * len + 1); if (buffer == NULL) return (NULL); /* copy string to buffer */ while (tmp[i] != '\0') { buffer[i] = tmp[i]; i++; } /* put '\0' at the end of string */ *char_count = len; buffer[i] = '\0'; return (buffer); } /** * get_percent - put/add percent in buffer * @char_count: number of character that stores in buffer. * @list: the percent to add to buffer * Return: buffer */ char *get_percent(__attribute__((unused))va_list list, int *char_count) { char *buffer; buffer = malloc(sizeof(char) * 2); if (buffer == NULL) return (NULL); buffer[0] = '%'; buffer[1] = '\0'; *char_count = 1; return (buffer); }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <sys/wait.h> void func(int signo) { //printf("I'm here\n"); ; } void readDirectoryRecursive(char* directoryPath, int indent){ // opens a directory. Returns a valid pointer if the successfully, NULL otherwise DIR *dirPointer = opendir(directoryPath); if (dirPointer == NULL) { printf("Error opening directory\n"); return; } struct dirent *dirEntry; struct stat inode; char name[1000]; while ((dirEntry = readdir(dirPointer)) != 0) { sprintf(name, "%s/%s", directoryPath, dirEntry->d_name); // sends formatted output to a string(name) / name will be the absolute path to the next file lstat(name, &inode); // get info about the file/folder at the path name // test the type of file if (S_ISDIR(inode.st_mode)){ if(strcmp(dirEntry->d_name, ".") == 0 || strcmp(dirEntry->d_name, "..") == 0) continue; int pid = fork(); struct sigaction new, old; sigset_t smask; // defines signals to block while func() is running // prepare struct sigaction if (sigemptyset(&smask)==-1) // block no signal perror ("sigsetfunctions"); new.sa_handler = func; // function that will be called with the new signal new.sa_mask = smask; new.sa_flags = 0; // usually works switch(pid) { case 0: if(sigaction(SIGUSR1, &new, &old) == -1) perror ("sigaction"); pause(); // wait for signal from parent readDirectoryRecursive(name, indent+2); exit(0); // need to end the child process here, since otherwise it would print the files that are already being printed by the parent default: printf("%*c", indent, ' '); printf("%s %s\n", "dir ", dirEntry->d_name); usleep(10000); kill(pid, SIGUSR1); int* stat_loc; wait(stat_loc); // Waits for the child process to end break; } } else if (S_ISREG(inode.st_mode)){ printf("%*c", indent, ' '); printf("fis "); printf(" %s\n", dirEntry->d_name); } else if (S_ISLNK(inode.st_mode)){ printf("%*c", indent, ' '); printf("lnk "); printf(" %s\n", dirEntry->d_name); } } closedir(dirPointer); return; } int main(int argc, char *argv[], char *envp[]) { char *directoryPath = argv[1]; readDirectoryRecursive(directoryPath, 0); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main(void) { //Описание указателя на целое число int *x; int n,i; printf("Введите размерность массива: "); scanf("%d",&n); //выделение памяти x = (int*)malloc(sizeof(int)*n); for(i=0; i<n; i++) { //вычисление значения элементов массива rand x[i] = rand()%31+20; x[i] = rand()%31-rand()%31; x[i] = rand()%101/(rand()%31+1.); //печать элементов массива printf("%d", x[i]); } //печать элементов массива for(i=0;i<n;i++) printf("%5d",x[i]); //освобождение памяти free(x); printf("\n"); system("pause"); return 0; }
C
#include <libmybox.h> sqlite *db_connect(const char *database) { char *errmsg=NULL; sqlite *db_id=NULL; db_id=sqlite_open(database, 0, &errmsg); if(!db_id) { printf("%s\n",errmsg); free(errmsg); return 0; } return db_id; } void db_clean_buffer(void) { memset(SQL_RESULT->name,0x0,sizeof(SQL_RESULT->name)); memset(SQL_RESULT->value,0x0,sizeof(SQL_RESULT->value)); SQL_NUMROWS=0; } void db_flush(sqlite *db_id) { db_query(db_id,"VACUUM;"); } void db_close(sqlite *db_id) { db_clean_buffer(); db_flush(db_id); sqlite_close(db_id); } int db_callback(void *args,int numrows, char **colresults, char **colnames) { int x=0; for(x=0;x<numrows;x++) { sprintf(SQL_RESULT[SQL_NUMROWS].name,"%s",colnames[x]); sprintf(SQL_RESULT[SQL_NUMROWS].value,"%s",colresults[x]); SQL_NUMROWS++; } return 0; } int db_query(sqlite *db_id,const char *sql) { char *errmsg=NULL; int ret=0; ret=sqlite_exec(db_id, sql, &db_callback, NULL, &errmsg); if(ret==1) { printf("%s\n",errmsg); free(errmsg); return 0; } return 1; } char *db_get_single(sqlite *db_id,const char *sql) { db_query(db_id,sql); return (char *) SQL_RESULT[0].value; }
C
/* 实验8_2 题目: 编写程序,建立一个学生基本信息结构,包括学号、姓名以及语文、数学、英语 3门课程的成绩, 输入 n 个学生的基本信息,写到文本文件 student.txt 中。 再从文件中取出数据,计算每个学生3门课程的总分和平均分(保留2位小数),并将结果输出至屏幕上。 构成: writeData函数功能:打开文件,将输入的基本信息fprintf到文件student.txt(FILENAME)中,关闭文件 calData函数功能:打开文件FILENAME,用结构指针每次读一个结构并计算所需数值输到显示器上,直到structpoint到达文件的末尾(NULL/EOF需执行时再看) 输出结束,关闭文件 可以优化格式 */ #include <stdio.h> #include <stdlib.h> #define FILENAME "student.txt" typedef struct student{ char identity[20]; char name[9]; int chinese; int math; int english; }STUDENT,*STUDENTP; int writeData(void); void calData(int n); int main(){ int n; n = writeData();//n为输入资料的人数,因为下面函数也需要用到 所以作为返回值传回 calData(n); return 0; } int writeData(void){ FILE *fp; int i,n; STUDENT temp; fp = fopen(FILENAME,"w"); if(fp == NULL){ printf("Can't open the file:%s!\n",FILENAME); exit(EXIT_FAILURE); } printf("The number of the student is:"); scanf("%d",&n); for(i = 0; i < n;i++){ scanf("%s%s%d%d%d",temp.identity,temp.name,&temp.chinese,&temp.math,&temp.english); fprintf(fp,"%-20s%-9s%-5d%-5d%-5d\n",temp.identity,temp.name,temp.chinese,temp.math,temp.english); } fclose(fp); printf("The file %s had been made.\n",FILENAME); return n; } void calData(int n){ FILE *fp; int i; STUDENT temp; STUDENTP p; fp = fopen(FILENAME,"r"); p = &temp; for(i = 0;i < n;i++){ double total,ave; fscanf(fp,"%s%s%d%d%d",temp.identity,temp.name,&temp.chinese,&temp.math,&temp.english); total = p -> chinese + p -> math + p -> english; ave = total / 3; printf("Student %9s : total: %3.0lf average: %3.2lf",p->name,total,ave); if(i != n - 1) printf("\n"); } fclose(fp); }
C
// //^ӦĶʱΪ1ͬʱΪ0 /*#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> int main(){ int a, b; unsigned result; printf("please input a:"); scanf("%d", &a); printf("plaese input b:"); scanf("%d", &b); printf("a=%d,b=%d", a, b); result = a^b; printf("\na^b=%u\n", result); system("pause"); return 0; } //ѭλ #define _CRT_SECURE_NO_WARNINGS//ѭ #include<stdio.h> #include<stdlib.h> int left(unsigned value, int n){ unsigned z; z = (value >> (32 - n) | value << n); return z; } int main(){ unsigned a; int n; printf("plaese input a:\n"); scanf("%o", &a); printf("plaese input n:\n"); scanf("%d", &n); printf("the result is %o:\n", left(a, n)); system("pause"); return 0; }*/ #define _CRT_SECURE_NO_WARNINGS//ѭ #include<stdio.h> #include<stdlib.h> int left(unsigned value, int n){ unsigned z; z = (value <<(32 - n) | value >> n); return z; } int main(){ unsigned a; int n; printf("plaese input a:\n"); scanf("%o", &a); printf("plaese input n:\n"); scanf("%d", &n); printf("the result is %o:\n", left(a, n)); system("pause"); return 0; }
C
#include <stdio.h> //1≤N≤10^15 int gcd(int n, int m) { if(n==0)return m; else return gcd(m%n,n); } int fsqrt(int n) { int s; int left=0; int right=n; while(left<=right) { int middle= (left+right)/2; if(middle*middle>n) { right = middle-1; } else { left = middle +1; s= middle; } } return s; } int min(int a, int b) { if(a>b) return b; else return a; } int main() { int N; int i,j,k; scanf("%d",&N); int sum =0; int mod = (1000000000 + 7); for(i=1; i<=N; i++) { int temp_sum =0; int m = min(i*2-1,N); for(j=i; j<=m; j++) //as gcd(a,b)= gcd(a,b-a) { int g = gcd(i,j); int s = fsqrt(g); for(k =1;k<=s;k++) { if(g%k==0) //if k is a divisor of g%k { if((g/k)!=k) //if both the divisors are not equal { temp_sum+=(g/k); } temp_sum+=k; temp_sum%=mod; } } printf("F(%d,%d) = %d\n",i,j,temp_sum); } if(m!=N) { sum+=(N/i-1)*temp_sum; sum %= mod; int temp_sum =0; for(j=(N/i)*i;j<=N;j++) { int g = gcd(i,j); int s = fsqrt(g); for(k =1;k<=s;k++) { if(g%k==0) //if k is a divisor of g%k { if((g/k)!=k) //if both the divisors are not equal { temp_sum+=(g/k); } temp_sum+=k; temp_sum%=mod; } printf("F(%d,%d) = %d\n",i,j,temp_sum); } } sum+=temp_sum; sum %= mod; } else sum +=temp_sum; } printf("%d\n",sum); return 0; }
C
#include <stdio.h> int main(int argc, char const *argv[]){ int lado1, lado2, perimetro, area; scanf("%d\n %d", &lado1, &lado2); perimetro = 2 * (lado1+lado2); area = lado1 * lado2; printf("%d\n%d\n", area, perimetro); return 0; }
C
#include <stdio.h> #include <conio.h> #include <ctype.h> int main () { char str[150]; int i; printf ("Digite a frase desejada.\n"); fgets (str, 150, stdin); for (i = 0; str[i]!='\0'; i++) { if (isalpha(str[i])) { str[i]= tolower(str[i]); } } printf ("A frase, escrita em letras minusculas fica: %s.\n", str); getch (); return 0; }
C
#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int numero =0; int i; char mayores=0; char menores=0; for(i=0;i<10;i++){ //printf("%d",i); printf("Ingrese un numero \n"); scanf("%d",&numero); system("cls"); fflush(stdin); if(numero>0){ mayores++; }if(numero<0){ menores++; } } printf("Los numeros mayores a 0 son: %d \n Los numero menores a 0 son: %d",mayores,menores); return 0; }
C
/* ========================================================================= * * HeapSort * Implémentation ode l'algorithme HeapSort. * ========================================================================= */ #include <stddef.h> #include <stdlib.h> #include "Sort.h" /* ------------------------------------------------------------------------- * * Echange les éléments du tableau array[i] avec array[j] tel que, array[i] <=> array[j] * * PARAMETRES * array Tableau d'entier * i Indice du premier éléments * j Indice du second éléments * ------------------------------------------------------------------------- */ static void swap(int *array, size_t i, size_t j); /* ------------------------------------------------------------------------- * * Retourne le fils gauche du noeud i de l'arbre binaire * * PARAMETRES * i Le noeud i de l'arbre binaire * ------------------------------------------------------------------------- */ static size_t Left(size_t i); /* ------------------------------------------------------------------------- * * Retourne le fils droit du noeud i de l'arbre binaire * * PARAMETRES * i Le noeud i de l'arbre binaire * ------------------------------------------------------------------------- */ static size_t Right(size_t i); /* ------------------------------------------------------------------------- * * Rétablit la propriété des tas(pour tout i, en tenant compte du fait que les * sous-arbres de droite et de gauche sont des tas * * PARAMETRES * array Tableau d'entier * heap_size La taille du tas * ------------------------------------------------------------------------- */ static void Max_Heapify(int *array, size_t i, size_t heap_size); /* ------------------------------------------------------------------------- * * Construit un tas (arbre binaire)à partir du tableau à trier * * PARAMETRES * array Tableau d'entier * length La taille du tableau * ------------------------------------------------------------------------- */ static void Build_Max_Heap(int *array, size_t length); /* ------------------------------------------------------------------------- * * Trie un tableau d'entier. * * PARAMETRES * array Le tableau à trier * length La taille du tableau * ------------------------------------------------------------------------- */ static void HeapSort(int *array, size_t length); static size_t Left(size_t i){ return 2*i; } static size_t Right(size_t i){ return ((2*i)+1); } static void swap(int *array, size_t i, size_t j){ int tmp = array[i]; array[i] = array[j]; array[j] = tmp; } static void Max_Heapify(int *array, size_t i, size_t heap_size){ size_t largest = 0; size_t l = Left(i); size_t r = Right(i); if(l <= heap_size && array[l] > array[i]) largest = l; else largest = i; if(r <= heap_size && array[r] > array[largest]) largest = r; if(largest != i){ swap(array, i, largest); Max_Heapify(array, largest, heap_size); } } static void Build_Max_Heap(int *array, size_t length){ size_t heap_size = length; for(int i = length/2; i >= 0; i--) // int parce que à la fin de la boucle i = -1 Max_Heapify(array, i, heap_size); } static void HeapSort(int *array, size_t length){ Build_Max_Heap(array, length); size_t heap_size = length; for(size_t i = length; i >= 1; i--){ swap(array, i , 0); heap_size--; Max_Heapify(array, 0, heap_size); } } void sort(int* array, size_t length){ if(array == NULL || length == 0) return; HeapSort(array, length-1); }
C
#include "avl.h" #include "testForTask.h" #include <stdio.h> #include <locale.h> #define WRONG_OPTION -1 int main(void) { setlocale(LC_ALL, "rus"); if (!tests()) { printf("Тесты провалены!\n"); return 1; } printf("Тесты пройдены успешно\n"); printf("Набор команд:\n"); printf("0 - Выход\n"); printf("1 - добавить значение по ключу\n"); printf("2 - получить значение по ключу\n"); printf("3 - проверить наличие заданного ключа в словаре\n"); printf("4 - удаление заданного ключа и его значения\n"); int option = -1; Tree* tree = createTree(); while (option != 0) { printf("Введите номер команды: "); if (scanf("%i", &option) == 0) { scanf("%*s"); option = WRONG_OPTION; } switch (option) { case 0: break; case 1: { printf("Введите ключ: "); char key[20] = ""; scanf("%s", key); char value[20] = ""; printf("Введите значение: "); scanf("%s", value); insert(tree, key, value); break; } case 2: { printf("Введите ключ: "); char key[20] = ""; scanf("%s", key); const char* value = getValue(tree, key); if (value == NULL) { printf("Значение по заданному ключу не обнаружено\n"); break; } printf("Значение по заданному ключу: %s\n", value); break; } case 3: { printf("Введите ключ: "); char key[20] = ""; scanf("%s", key); if (checkExist(tree, key)) { printf("Заданный ключ существует\n"); } else { printf("Заданного ключа не обнаружено в словаре\n"); } break; } case 4: { printf("Введите ключ: "); char key[20] = ""; scanf("%s", key); delete(tree, key); printf("Элемент удален\n"); break; } default: printf("Введен неправильный номер команды\n"); break; } } deleteTree(&tree); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_stack_emplace.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: nelson <nelson@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/03/23 17:28:17 by nperrin #+# #+# */ /* Updated: 2017/10/22 20:13:17 by nelson ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include "ft_stack.h" int ft_stack_emplace( t_stack *stack, void *data, void *(*create)(void *, t_error_c **), t_error_c **error_addr) { t_stack_elem *new_elem; if (!(new_elem = (t_stack_elem *)malloc(sizeof(t_stack_elem)))) { if (error_addr) *error_addr = ft_error_bad_alloc(); return (-1); } *error_addr = NULL; new_elem->value = (*create)(data, error_addr); if (!error_addr || *error_addr) { free(new_elem); return (-1); } new_elem->next = stack->top; stack->top = new_elem; stack->size++; return (0); }
C
/************************************************************************* > File Name: bsearch.c > Author: jinshaohui > Mail: jinshaohui789@163.com > Time: 18-10-21 > Desc: ************************************************************************/ #include<stdio.h> #include<stdlib.h> #include<assert.h> /*二分查找算法的变形问题 *1、查找第一个等于给定数值的元素 *2、查找最后一个等于给定数值的元素 *3、查找第一个大于等于给定数值的元素 *4、查找第一个小于等于给定数值的元素 * */ /*1、查找第一个等于给定数值的元素*/ int mybsearch_1(int a[],int size,int value) { int mid = 0; int left = 0; int right = size - 1; while(left <= right) { /*防止size数量太大是,(left + right)数据翻转,导致问题*/ mid = left + ((right - left)>>1); if (a[mid] < value) { left = mid + 1; } else if (a[mid] > value) { right = mid - 1; } else { if ((mid == 0) || (a[mid - 1] != value)) { return mid; } else { right = mid - 1; } } } return -1; } /*2、查找最后一个等于给定数值的元素*/ int mybsearch_2(int a[],int size,int value) { int mid = 0; int left = 0; int right = size - 1; while(left <= right) { /*防止size数量太大是,(left + right)数据翻转,导致问题*/ mid = left + ((right - left)>>1); if (a[mid] < value) { left = mid + 1; } else if (a[mid] > value) { right = mid - 1; } else { if ((mid == (size - 1)) || (a[mid + 1] != value)) { return mid; } else { left = mid + 1; } } } return -1; } /*3、查找第一个大于等于给定数值的元素*/ int mybsearch_3(int a[],int size,int value) { int mid = 0; int left = 0; int right = size - 1; while(left <= right) { /*防止size数量太大是,(left + right)数据翻转,导致问题*/ mid = left + ((right - left)>>1); if (a[mid] < value) { left = mid + 1; } else { /*a[mid] >= value 当mid==0 或者a[mid-1] > value 说明是第一个大于等于value*/ if ((mid == 0) || (a[mid - 1] < value)) { return mid; } else { right = mid - 1; } } } return -1; } /*4、查找第一个小于等于给定数值的元素*/ int mybsearch_4(int a[],int size,int value) { int mid = 0; int left = 0; int right = size - 1; while(left <= right) { /*防止size数量太大是,(left + right)数据翻转,导致问题*/ mid = left + ((right - left)>>1); if (a[mid] > value) { right = mid - 1; } else { /*a[mid] <= value 时,当前mid == size -1 数组中最大的数值; * 或者a[mid + 1] 大于vlaue,就是mid就第一个小于等于value*/ if ((mid == (size - 1)) || (a[mid + 1] > value)) { return mid; } else { left = mid + 1; } } } return -1; } int main() { int a[10] = {5,6,6,9,10,11,11,22,33,33}; int data = 0; int i = 0; int res =0; printf("\r\n"); for(i = 0; i < 10 ; i++) { printf("%d ",a[i]); } printf("\r\n"); printf("\r\n输入一个整数"); scanf("%d",&data); res = mybsearch_1(a,10,data); printf("第一个等于data[%d],下标是%d",data,res); printf("\r\n输入一个整数"); scanf("%d",&data); res = mybsearch_2(a,10,data); printf("最后一个等于data[%d],下标是%d",data,res); printf("\r\n输入一个整数"); scanf("%d",&data); res = mybsearch_2(a,10,data); printf("第一个大于等于data[%d],下标是%d",data,res); printf("\r\n输入一个整数"); scanf("%d",&data); res = mybsearch_2(a,10,data); printf("第一个小等于data[%d],下标是%d",data,res); return; }
C
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int cmp(const void *a, const void *b) { return *(double *)a > *(double *)b ? 1 : -1; } int main() { double s, l, h; double x[4], y[4]; double x1, y1, x2, x3, x4, y2, y3, y4; while (~scanf("%lf%lf%lf%lf%lf%lf%lf%lf", &x1, &y1, &x2, &y2, &x3, &y3, &x4, &y4)) { x[0] = x1; x[1] = x2; x[2] = x3; x[3] = x4; y[0] = y1; y[1] = y2; y[2] = y3; y[3] = y4; qsort(x, 4, sizeof(x[0]), cmp); qsort(y, 4, sizeof(y[0]), cmp); l = fabs(x2 - x1) + fabs(x4 - x3) - (x[3] - x[0]); h = fabs(y2 - y1) + fabs(y4 - y3) - (y[3] - y[0]); s = l * h; if (l <= 0 || h <= 0) //推断不重叠的时候 为零由于题目有要求是精确到两位小数 s = 0.00; printf("%.2lf\n", s); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> void *service; char *auth; int main() { char s[32]; int i; unsigned int dl; // uint8_t unsigned int al; // uint8_t while (1) { s[0] = 0; printf("%p, %p \n", auth, service); fgets(s , 128, stdin); if (s[0] == 0) { s[0] = 0; return (0); } i = 0; char *v = "auth "; while (s[i] == v[i] && i < 5) i++; dl = s[i] > v[i]; al = s[i] < v[i]; if (!al) { i = 0; auth = malloc(4); auth = 0; while (s[i]) i++; if (i <= 30) strncpy(auth, s, 6); } i = 0; char *r = "reset"; while (s[i] == r[i] && i <= 5) i++; dl = s[i] > r[i]; al = s[i] < r[i]; if (!al) free(auth); i = 0; char *b = "service"; while (s[i] == b[i] && i <= 6) i++; dl = s[i] > b[i]; al = s[i] < b[i]; if (!al) service = strdup(s); i = 0; char *l = "login"; while (s[i] == l[i] && i <= 5) i++; dl = s[i] > l[i]; al = s[i] < l[i]; if (!al) { if (!auth[32]) system("/bin/sh"); else fwrite("Password:\n", 1, 10, stdout); } } return (0); }
C
#include <stdio.h> void strRot13(char str[]) { const int shift = 13; for ( int i = 0, ch = str[i]; ch != '\0'; i++, ch = str[i] ) { if ( ch >= 'a' && ch <= 'm' ) { str[i] = ch + shift; } else if ( ch > 'm' && ch <= 'z' ) { str[i] = ch - shift; } else if ( ch >= 'A' && ch <= 'M' ) { str[i] = ch + shift; } else if ( ch > 'M' && ch <= 'Z' ) { str[i] = ch - shift; } } } int main() { char str[] = {'W', 'e', 'l', 'l', ' ', 'd', 'o', 'n', 'e', '!', '\0'}; strRot13(str); printf("%s\n", str); return 0; }
C
#include <stdio.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <omp.h> void swap(int64_t *ptr1, int64_t *ptr2 ){ int64_t temp; temp = *ptr1; *ptr1 = *ptr2; *ptr2 = temp; } int64_t choosePivot(int64_t *a, int64_t lo, int64_t hi){ return ((lo+hi)/2); } int64_t partitionArray(int64_t *a, int64_t lo, int64_t hi){ int64_t pivotIndex, pivotValue, storeIndex; pivotIndex = choosePivot(a, lo, hi); pivotValue = a[pivotIndex]; (void) swap(&a[hi], &a[pivotIndex]); storeIndex = lo; for (int64_t i=lo; i<= hi-1; i++){ if (a[i] < pivotValue){ (void) swap(&a[i], &a[storeIndex]); storeIndex++; } } (void) swap(&a[storeIndex],&a[hi]); return storeIndex; } void Quicksort(int64_t *a, int64_t lo, int64_t hi){ if (lo < hi){ int64_t p = partitionArray(a, lo, hi); #pragma omp task shared(a) firstprivate(lo,p) { (void) Quicksort(a, lo, p-1); } //Left branch (void) Quicksort(a, p+1, hi); //Right branch #pragma omp taskwait } } /* ----------------------------------------------------------------------- Tests the result * ----------------------------------------------------------------------- */ void testit(int64_t *v, int64_t * nelements) { register int k; int not_sorted = 0; for (k = 0; k < (*nelements) - 1; k++) if (v[k] > v[k + 1]) { not_sorted = 1; break; } if (not_sorted) { printf("Array NOT sorted.\n"); exit(1); } // if (not_sorted) // printf("Array NOT sorted.\n"); // else // printf("Array sorted.\n"); } /* ----------------------------------------------------------------------- Sets randomly the values for the array * ----------------------------------------------------------------------- */ void initialize(int64_t *v, int64_t seed, int64_t nelements) { unsigned i; srandom(seed); for(i = 0; i < nelements; i++) v[i] = (int64_t)random(); } int main(int argc, char** argv) { // #pragma omp parallel // { // printf("this\n"); // printf("is\n"); // printf("a test\n"); // } int64_t nelements; int seed; if (argc==1){ nelements = 1000000; seed = 1; } else if (argc==2){ nelements = atoi(argv[1]); seed = 1; }else if (argc==3){ nelements = atoi(argv[1]); seed = atoi(argv[2]); } int64_t a[nelements]; initialize(a,1,nelements); double start_time = omp_get_wtime(); #pragma omp parallel default(none) shared(a, nelements) { #pragma omp single nowait { (void) Quicksort(a,0,nelements-1); } } double time = omp_get_wtime() - start_time; printf("Time taken: %f\n",time); testit(a,&nelements); return 0; }
C
// Program 5 - komunikacja przez netlink //send #include <sys/socket.h> #include <linux/netlink.h> #include <stdio.h> #include <malloc.h> #include <stdio.h> #include <string.h> #include <unistd.h> #define NLINK_MSG_LEN 1024 #define NETLINK_USER 31 int main() { int result; char* received="Hello"; int fd; struct sockaddr_nl src_addr; struct sockaddr_nl dest_addr; struct nlmsghdr *nlh; struct iovec iov; struct msghdr msg; fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_USER); printf("Inside send main\n"); if (fd < 0) { printf("Netlink socket creation failed.\n"); return -1; } memset(&src_addr, 0, sizeof(src_addr)); src_addr.nl_family = AF_NETLINK; //AF_NETLINK socket protocol src_addr.nl_pid = getpid(); //application unique id //src_addr.nl_groups = 0; //send to multicast address 2 result=bind(fd, (struct sockaddr *)&src_addr, sizeof(src_addr)); printf("Result of bind = %i\n", result); nlh=(struct nlmsghdr *) malloc(NLMSG_SPACE(NLINK_MSG_LEN)); memset(nlh, 0, NLMSG_SPACE(NLINK_MSG_LEN)); nlh->nlmsg_len = NLMSG_SPACE(NLINK_MSG_LEN); //netlink message length nlh->nlmsg_pid = getpid(); //src application unique id //nlh->nlmsg_flags = 0; strcpy(NLMSG_DATA(nlh), received); //copy the payload to be sent iov.iov_base = (void *)nlh; //netlink message header base address iov.iov_len = nlh->nlmsg_len; //netlink message length memset(&dest_addr, 0, sizeof(dest_addr)); dest_addr.nl_family = AF_NETLINK; // protocol family dest_addr.nl_pid = 0; //destination process id dest_addr.nl_groups = 0; msg.msg_name = (void *)&dest_addr; msg.msg_namelen = sizeof(dest_addr); msg.msg_iov = &iov; msg.msg_iovlen = 1; printf("Listening to the MCAST address (3): %d\n", dest_addr.nl_groups); while (1) { printf("Try send message %s\n", (char *)NLMSG_DATA(nlh)); result=sendmsg(fd, &msg, 0); printf("Result of sendmsg = %i\n", result); sleep(3); printf("Try receive message\n"); recvmsg(fd, &msg, 0); printf("After receive\n"); printf("Received message: %s\n", (char*)NLMSG_DATA(nlh)); } close(fd); }
C
#include<stdio.h> #include<string.h> int main(void) { int t; char s[1000],p[1000]; scanf("%d",&t); while(t!=0) { scanf("%s",s); p=strrev(s); if(s==p) { printf("YES\n"); } else { printf("NO\n"); } t--; } }
C
/********************************************************** * Author : huang * Creat modified : 2020-07-20 21:29 * Last modified : 2020-07-20 21:29 * Filename : 20_字符数组.c * Description : * *******************************************************/ #include <stdio.h> int main() { //1. C语言没有字符串类型,用字符数组模拟 char a[10]; //2. 字符串一定是字符数组,字符数组不一定是字符串 //3. 如果字符数组是以字符'\0'(等价于数字0)结尾,那么这个字符数组就是字符串 char b[] = {'a', 'b', 'c'}; //字符数组 char c[] = {'a', 'b', 'c', '\0'}; //字符串 char d[] = {'a', 'b', 'c', 0}; //字符串 }
C
#include <stdio.h> int main() { int pinakas[1000], i, c, max, sum; i = 0; while ((c = getchar()) != EOF) { pinakas[i] = c - '0'; i++; } max = pinakas[0] * pinakas[1] * pinakas[2] * pinakas[3] * pinakas[4]; for (i=1; i<=995; i++){ sum = pinakas[i] * pinakas[i+1] * pinakas[i+2] * pinakas[i+3] * pinakas[i+4]; if (sum > max) max = sum; } printf("%d\n", max); }
C
#ifndef COMMON_RESIZABLE_BUFFER_H #define COMMON_RESIZABLE_BUFFER_H #define ERROR -1 #define EXTRA_SPACE 30 #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> typedef struct resizable_buffer{ int size; char *buffer; }resizable_buffer_t; int resizable_buffer_create(resizable_buffer_t *self, int size); void resizable_buffer_destroy(resizable_buffer_t *self); int resizable_buffer_resize(resizable_buffer_t *self, int new_size); /*En caso de no contar con espacio suficiente para guardar la nueva palabra (string) llama a resize con el tamanio nuevo + 1.Luego guarda la palabra*/ int resizable_buffer_save(resizable_buffer_t *self, char *word); /*En caso de no contar con espacio suficiente para guardar los n caracteres de la palabra (word) llama a resize con el tamanio nuevo + 1.Luego guarda los caracteres en el buffer */ int resizable_buffer_n_save(resizable_buffer_t *self, char *word, int n); /*Se utiliza para guardar cadenas de bytes*/ int resizable_buffer_byte_save(resizable_buffer_t *self, char* buf, int size); bool resizable_buffer_is_empty(resizable_buffer_t *self); #endif
C
#include <stdio.h> #include <stdio.h> #define mod 1000000007 int size = 0; void swap(int *a, int *b) { int temp = *b; *b = *a; *a = temp; } void heapify(int array[], int size, int i) { if(size>1) { int largest = i; int l = 2 * i + 1; int r = 2 * i + 2; if (l < size && array[l] > array[largest]) largest = l; if (r < size && array[r] > array[largest]) largest = r; if (largest != i) { swap(&array[i], &array[largest]); heapify(array, size, largest); } } } void insert(int array[], int newNum) { if (size == 0) { array[0] = newNum; size += 1; } else { array[size] = newNum; size += 1; for (int i = size / 2 - 1; i >= 0; i--) { heapify(array, size, i); } } } int main() { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif int m,n; scanf("%d",&m); scanf("%d",&n); int a[m]; int t; for(int i=0;i<m;i++){ scanf("%d",&t); insert(a, t); } int mx=0; for(int i=0;i<n;i++){ mx=(mx+a[0])%mod; a[0]=a[0]/3; heapify(a,m,0); } printf("%d",mx); return 0; }
C
#include <screen.h> #include <stdio.h> #include <stdlib.h> #include <timer.h> #define BUFFER_SIZE 10 * 1024 int main(void) { int err; printf("available resolutions\n"); int resolutions; err = screen_get_supported_resolutions(&resolutions); if (err < 0) return -1; for (int idx = 0; idx < resolutions; idx++) { size_t width, height; screen_get_supported_resolution(idx, &width, &height); printf(" %d x %d\n", width, height); } printf("available colors depths\n"); int pixel_format; err = screen_get_supported_pixel_formats(&pixel_format); if (err < 0) return -1; for (int idx = 0; idx < pixel_format; idx++) { int format; screen_get_supported_pixel_format(idx, &format); size_t bits = screen_get_bits_per_pixel(format); printf(" %d bpp\n", bits); } err = screen_init(BUFFER_SIZE); if (err < 0) { printf("buffer allocation failed\n"); return -1; } printf("screen init\n"); screen_set_brightness(100); size_t width, height; screen_get_resolution(&width, &height); screen_set_frame(0, 0, width, height); screen_fill(0); bool invert = false; for (int i = 0; ; i++) { if (i % 4 == 3) { invert = !invert; if (invert) { screen_invert_on(); } else { screen_invert_off(); } } screen_set_rotation(i % 4); screen_set_frame(10, 20, 30, 30); screen_fill(0xF800); screen_set_frame(88, 20, 30, 30); screen_fill(0); delay_ms(1000); screen_set_frame(10, 20, 30, 30); screen_fill(0); screen_set_frame(88, 20, 30, 30); screen_fill(0x07F0); delay_ms(1000); screen_set_frame(0, 0, width, height); screen_fill(0x0000); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "functions.h" int main(int argc, char** argv) { FILE* fp; fp = fopen("votes.txt","r"); char** nameArray = malloc(10 * sizeof(char *)); //Allocate row pointers int i; for(i =0; i< 10; i++) { nameArray[i] = malloc(25 * sizeof(char)); //Allocate each row separately } for(i=0;i<10;i++) { fgets(nameArray[i], 25, (FILE*)fp); int len = strcspn(nameArray[i], "\r\n"); nameArray[i][len] = 0; } for (i=0; i<10; i++) { printf("Candidate [%d] = %s\n",(i+1),nameArray[i]); } int* votesArray = malloc(10 * sizeof(int)); printf("Submit your vote for candidates 1 through 10 with the appropiate number\t" "followed by enter, type 0 to terminate. All other numbers will be a spoiled vote.\n"); int v; scanf("%d",&v); while (v != 0) { switch (v) { case 1 : votesArray[0]++; break; case 2 : votesArray[1]++; break; case 3 : votesArray[2]++; break; case 4 : votesArray[3]++; break; case 5 : votesArray[4]++; break; case 6 : votesArray[5]++; break; case 7 : votesArray[6]++; break; case 8 : votesArray[7]++; break; case 9 : votesArray[8]++; break; case 10 : votesArray[9]++; break; default : printf("Spoiled vote\n"); break; } scanf("%d",&v); } printf("Unsorted list\n"); for (i=0; i<10; i++) { printf("Candidate [%d], %s = %d votes \n", (i+1), nameArray[i], votesArray[i]); } parallelSortAlpha(0, 9, nameArray, votesArray); fp = fopen("results.txt", "w+"); fprintf(fp, "Sorted Alphabetically\n"); for (i =0; i<10; i++) { fprintf(fp, "%s = %d votes \n", nameArray[i], votesArray[i]); } printf("\n\n"); printf("Sorted Alphabetically\n"); for (i=0; i<10;i++) { printf("%s = %d votes \n", nameArray[i], votesArray[i]);} parallelSortNum(0, 9, nameArray, votesArray); fprintf(fp, "\n\nSorted Numerically\n"); for (i =0; i<10; i++) { fprintf(fp, "%s = %d votes \n", nameArray[i], votesArray[i]); } printf("\n\n"); printf("Sorted Numerically\n"); for (i=0; i<10;i++) { printf("%s = %d votes \n", nameArray[i], votesArray[i]);} for (i =0; i<10; i++) { free(nameArray[i]); } free(nameArray); free(votesArray); close(fp); return 0; }
C
/*swapping without using 3 variable*/ main() { int a,b; printf("Enter two Numbers: "); scanf("%d %d",&a,&b); b=b-a; a=a+b; b=a-b; printf("\nSwapped No. are a=%d & b=%d",a,b);}
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* substr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gabriel <gabriel@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/02/28 12:35:18 by jtoty #+# #+# */ /* Updated: 2021/02/15 18:27:35 by gabriel ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include <unistd.h> #include "../libft.h" #include <stdio.h> #include <string.h> int main_two(void); static void check_substr(char *str, int start, int len) { char *substr; printf("str = '%s'(%ld)\n", str, strlen(str)); if (!(substr = ft_substr(str, start, len))) printf("NULL"); else printf("%s", substr); if (str == substr) printf("\nA new string was not returned"); else free(substr); } int main(int argc, const char *argv[]) { char string[] = "lorem ipsum dolor sit amet"; int arg; alarm(5); if (argc == 1) return (0); else if ((arg = atoi(argv[1])) == 1) check_substr(string, 0, 10); else if (arg == 2) check_substr(string, 7, 10); else if (arg == 3) check_substr(string, 7, 0); else if (arg == 4) check_substr(string, 0, 0); else if (arg == 5) main_two(); else if (arg == 6) { // int iTest = 1; // signal(SIGSEGV, sigsegv); // char * s = ft_substr("tripouille", 0, 42000); // check_substr("tripouille", 0, 122); check_substr("tripouille", 0, 42000); // /* 2 */ mcheck(s, strlen("tripouille") + 1); free(s); showLeaks(); } else if (arg == 7) { check_substr("tripouille", 100, 1); } else if (arg == 8) { check_substr("tripouille", 1, 1); // /* 3 */ check(!strcmp(s, "r")); // /* 4 */ mcheck(s, 2); free(s); showLeaks(); } return (0); } int main_two(void) { char *str = "01234"; size_t size = 10; char *ret = ft_substr(str, 10, size); if (!strncmp(ret, "", 1)) { free(ret); printf("TEST_SUCCESS\n"); return (1); } free(ret); printf("TEST_FAILED\n"); return (0); }
C
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <errno.h> #include <time.h> #include <fcntl.h> #include <strings.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include "utilities.h" #include "packet.h" int main(int argc, char **argv) { if (argc != 13) { printf("usage: trace -a <routetrace port> -b < source hostname> -c <source port>"); printf("-d <destination hostname> -e <destination port> -f <debug option>\n"); exit(1); } char *portStr = NULL; char *sHostName = NULL; char *sPortStr = NULL; char *dHostName = NULL; char *dPortStr = NULL; char *debugStr = NULL; int cmd; while ((cmd = getopt(argc, argv, "a:b:c:d:e:f:")) != -1) { switch(cmd) { case 'a': portStr = optarg; break; case 'b': sHostName = optarg; break; case 'c': sPortStr = optarg; break; case 'd': dHostName = optarg; break; case 'e': dPortStr = optarg; break; case 'f': debugStr = optarg; break; case '?': if (optopt == 'a' || optopt == 'b' || optopt == 'c' || optopt == 'd' || optopt == 'e' || optopt == 'f') fprintf(stderr, "Option -%c requires an argument.\n", optopt); else if (isprint(optopt)) fprintf(stderr, "Unknown option -%c.\n", optopt); else fprintf(stderr, "Unknown option character '\\x%x'.\n", optopt); exit(EXIT_FAILURE); break; default: printf("Unhandled argument: %d\n", cmd); exit(EXIT_FAILURE); } } // DEBUG printf("Port: %s\n", portStr); // Convert program args to values int tracePort = atoi(portStr); int srcPort = atoi(sPortStr); int destPort = atoi(dPortStr); int debug = atoi(debugStr); // Validate the argument values if (tracePort <= 1024 || tracePort >= 65536) ferrorExit("Invalid requester port"); if (srcPort <= 1024 || srcPort >= 65536) ferrorExit("Invalid trace port"); if (destPort <= 1024 || destPort >= 65536) ferrorExit("Invalid trace port"); struct addrinfo thints; bzero(&thints, sizeof(struct addrinfo)); thints.ai_family = AF_INET; thints.ai_socktype = SOCK_DGRAM; thints.ai_flags = AI_PASSIVE; // Get the trace's address info struct addrinfo *traceinfo; int errcode = getaddrinfo(NULL, portStr, &thints, &traceinfo); if (errcode != 0) { fprintf(stderr, "trace getaddrinfo: %s\n", gai_strerror(errcode)); exit(EXIT_FAILURE); } // Loop through all the results of getaddrinfo and try to create a socket for trace int sockfd; struct addrinfo *p; for(p = traceinfo; p != NULL; p = p->ai_next) { // Try to create a new socket sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (sockfd == -1) { perror("Socket error"); continue; } // Try to bind the socket if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { perror("Bind error"); close(sockfd); continue; } break; } if (p == NULL) perrorExit("Send socket creation failed"); else printf("trace socket created.\n"); struct sockaddr_in *tmp = (struct sockaddr_in *)p->ai_addr; unsigned long ipAddr = ntohl(tmp->sin_addr.s_addr); // ------------------------------------------------------------------------ // Setup emul address info struct addrinfo shints; bzero(&shints, sizeof(struct addrinfo)); shints.ai_family = AF_INET; shints.ai_socktype = SOCK_DGRAM; shints.ai_flags = 0; // Get the emul's address info struct addrinfo *srcinfo; errcode = getaddrinfo(sHostName, sPortStr, &shints, &srcinfo); if (errcode != 0) { fprintf(stderr, "emul getaddrinfo: %s\n", gai_strerror(errcode)); exit(EXIT_FAILURE); } // Loop through all the results of getaddrinfo and try to create a socket for emul int ssockfd; struct addrinfo *sp; for(sp = srcinfo; sp != NULL; sp = sp->ai_next) { // Try to create a new socket ssockfd = socket(sp->ai_family, sp->ai_socktype, sp->ai_protocol); if (ssockfd == -1) { perror("Socket error"); continue; } break; } if (sp == NULL) perrorExit("emul socket creation failed"); else printf("emul socket created.\n"); close(ssockfd); tmp = (struct sockaddr_in *)sp->ai_addr; //unsigned long sIpAddr = ntohl(tmp->sin_addr.s_addr); //printf("emul ip %s %lu\n", inet_ntoa(tmp->sin_addr), eIpAddr); //trace packet construction printf("trace packet constructing\n"); struct ip_packet *pkt = NULL; pkt = malloc(sizeof(struct ip_packet)); bzero(pkt, sizeof(struct ip_packet)); struct packet *dpkt = (struct packet *)pkt->payload; dpkt->type = 'T'; dpkt->seq = 0; dpkt->len = (unsigned long) 0; pkt->src = ipAddr; pkt->srcPort = tracePort; pkt->dest = nameToAddr(dHostName); pkt->destPort = destPort; pkt->priority = 0; pkt->length = HEADER_SIZE + 1; struct ip_packet *rpkt = malloc(sizeof(struct ip_packet)); void *msg = malloc(sizeof(struct ip_packet)); char destS[20]; char srcS[20]; while (dpkt->len < 25) { if (debug) { ipULtoStr(pkt->src, srcS); ipULtoStr(pkt->dest, destS); printf("Trace pkt sent - TTL=%lu Src=%s:%u Dest=%s:%u\n", dpkt->len, srcS, pkt->srcPort, destS, pkt->destPort); } sendIpPacketTo(sockfd, pkt, sp->ai_addr); bzero(msg, sizeof(struct ip_packet)); size_t bytesRecvd = recvfrom(sockfd, msg, sizeof(struct ip_packet), 0, NULL, NULL); if (bytesRecvd == -1) { perror("Recvfrom error"); fprintf(stderr, "Failed/incomplete receive: ignoring\n"); continue; } deserializeIpPacket(msg, rpkt); ipULtoStr(rpkt->src, srcS); if (debug) { ipULtoStr(rpkt->dest, destS); printf("Trace pkt recv - TTL=0 Src=%s:%u Dest=%s:%u\n", srcS, rpkt->srcPort, destS, rpkt->destPort); } printf("%s:%u", srcS, rpkt->srcPort); if (rpkt->srcPort == destPort && rpkt->src == nameToAddr(dHostName)) { break; } dpkt->len++; } free(pkt); free(dpkt); }
C
/* Oskar Sobczyk - Problem palaczy tytoniu nr indeksu 281822 18.01.2017 */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <pthread.h> #include <sys/types.h> #include <sys/time.h> #include <sys/stat.h> #include <fcntl.h> #include <semaphore.h> #include <unistd.h> #include <time.h> int main(int argc, char* argv[]) { int items; sem_t *sem_valet, *sem_tobacco, *sem_paper, *sem_matches; sem_valet=sem_open("/sem_valet",0); sem_tobacco=sem_open("/sem_tobacco",0); sem_paper=sem_open("/sem_paper",0); sem_matches=sem_open("/sem_matches",0); srand(time(0)); while(1) { sem_wait(sem_valet); items=(rand()%3); if(items==0) { printf("Lokaj: Wykładam papier i zapałki.\n"); sem_post(sem_tobacco); } else if(items==1) { printf("Lokaj: Wykładam tytoń i zapałki.\n"); sem_post(sem_paper); } else { printf("Lokaj: Wykładam tytoń i papier.\n"); sem_post(sem_matches); } } return 0; }
C
#include "cblas.h" #include "string.h" #include "stdio.h" #include "stdlib.h" #include "math.h" #define MAX(x, y) (x >= y ? x : y) void bias_add(float* in_layer, float* biases, float* result, int shape_b, int shape_h, int shape_w, int shape_d) { cblas_scopy( shape_b * shape_h * shape_w * shape_d, in_layer, 1, result, 1 ); float bias_d[shape_h * shape_w]; for (int i = 0; i < shape_h * shape_w; ++i) { bias_d[i] = 1.0f; } for (int b = 0; b < shape_b; ++b) { float* result_b = result + b * (shape_h * shape_w * shape_d); for (int d = 0; d < shape_d; ++d) { cblas_saxpy( shape_h * shape_w, biases[d], bias_d, 1, result_b + d, shape_d ); } } } void batch_norm(float* in_layer, float* mean, float* variance, float* gamma, float epsilon, float* result, int batch, int oh, int ow, int od) { for (int d = 0; d < od; ++d) { variance[d] = sqrt(variance[d] + epsilon); } for (int b = 0; b < batch; ++b) { for (int i = 0; i < oh; ++i) { for (int j = 0; j < ow; ++j) { for (int d = 0; d < od; ++d) { int ri = i * (ow * od) + j * od + d; result[ri] = ((in_layer[ri] - mean[d]) / variance[d]) * gamma[d]; } } } } } void conv2d(float* in_layer, float* kernel, float* result, int batch, int oh, int ow, int od, int ih, int iw, int ic, int kh, int kw, int sh, int sw) { for (int b = 0; b < batch; ++b) { for (int d = 0; d < od; ++d) { for (int c = 0; c < ic; ++c) { for (int i = 0; i < oh; ++i) { for (int j = 0; j < ow; ++j) { for (int di = 0; di < kh; ++di) { for (int dj = 0; dj < kw; ++dj) { int ri = b * (oh * ow * od) + i * (ow * od) + j * od + d; int ii = b * (ih * iw * ic) + (sh * i + di) * (iw * ic) + (sw * j + dj) * ic + c; int ki = di * (kw * ic * od) + dj * (ic * od) + c * od + d; result[ri] += in_layer[ii] * kernel[ki]; } } } } } } } } void conv2d_arr(float* in_layer_arg, float* kernel_arg, float* result_arg, int batch, int oh, int ow, int od, int ih, int iw, int ic, int kh, int kw, int sh, int sw) { float (*in_layer)[ih][iw][ic] = (float (*)[ih][iw][ic]) in_layer_arg; float (*kernel)[kw][ic][od] = (float (*)[kw][ic][od]) kernel_arg; float (*result)[oh][ow][od] = (float (*)[oh][ow][od]) result_arg; for (int b = 0; b < batch; ++b) { for (int d = 0; d < od; ++d) { for (int c = 0; c < ic; ++c) { for (int i = 0; i < oh; ++i) { for (int j = 0; j < ow; ++j) { for (int di = 0; di < kh; ++di) { for (int dj = 0; dj < kw; ++dj) { result[b][i][j][d] += in_layer[b][sh * i + di][sw * j + dj][c] * kernel[di][dj][c][d]; } } } } } } } } void im2col(float* imb_arg, float* colb_arg, int oh, int ow, int ih, int iw, int ic, int kh, int kw, int sh, int sw) { float (*imb)[iw][ic] = (float (*)[iw][ic]) imb_arg; float (*colb)[ic * kh * kw] = (float (*)[ic * kh * kw]) colb_arg; for (int i = 0; i < oh; ++i) { for (int j = 0; j < ow; ++j) { int patch_i = i * sh; int patch_j = j * sw; for (int c = 0; c < ic; ++c) { int col_i = i * ow + j; int col_j = c * (kh * kw); for (int k = 0; k < kh * kw; ++k) { colb[col_i][col_j + k] = imb[patch_i + k / kw][patch_j + k % kw][c]; } } } } } void conv2d_mul(float* in_layer, float* col, float* kernel_r, float* result, int batch, int oh, int ow, int od, int ih, int iw, int ic, int kh, int kw, int sh, int sw) { for (int b = 0; b < batch; ++b) { float* imb = in_layer + b * (oh * ow * od); float* colb = col + b * ((oh * ow) * (ic * kh * kw)); float* resultb = result + b * (oh * ow * od); im2col(imb, colb, oh, ow, ih, iw, ic, kh, kw, sh, sw); // colb : (oh * ow) X (ic * kh * kw) // kernel_r : (ic * kh * kw) X od cblas_sgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans, (oh * ow), od, (ic * kh * kw), 1, colb, (ic * kh * kw), kernel_r, od, 0, resultb, od ); } } void max_pool2d(float* in_layer, float* result, int batch, int oh, int ow, int od, int ih, int iw, int ic, int kh, int kw, int sh, int sw) { for (int b = 0; b < batch; ++b) { for (int d = 0; d < od; ++d) { for (int i = 0; i < oh; ++i) { for (int j = 0; j < ow; ++j) { int in_i = i * sh; int in_j = j * sw; float imax = in_layer[ b * (ih * iw * ic) + in_i * (iw * ic) + in_j * ic + d ]; for (int di = 0; di < kh; ++di) { for (int dj = 0; dj < kw; ++dj) { int ii = b * (ih * iw * ic) + (in_i + di) * (iw * ic) + (in_j + dj) * ic + d; imax = MAX(imax, in_layer[ii]); } } result[ b * (oh * ow * od) + i * (ow * od) + j * od + d ] = imax; } } } } } void leaky_relu(float* in_layer, float* result, int batch, int oh, int ow, int od) { for (int b = 0; b < batch; ++b) { for (int i = 0; i < oh; ++i) { for (int j = 0; j < ow; ++j) { for (int d = 0; d < od; ++d) { int idx = b * (oh * ow * od) + i * (ow * od) + j * od + d; float t = in_layer[idx]; result[idx] = t < 0 ? 0.1 * t : t; } } } } }
C
// 7-SEG //0000-FFFF include "lpc214x.h" #include "stdint.h" #define IO1 0x10000 #define IO2 0x20000 #define IO3 0x40000 #define IO4 0x80000 #define IOX 0xF0000 #define IOXcl 0xFFFFF int count=0000; unsignedint d1,d2,d3,d4; unsigned char seg[] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x67,0x77,0x7c,0x39,0x5e,0x79,0x71,0x00}; voidinit_gpio() { PINSEL0 = 0x00000000; PINSEL1 = 0x00000000; PINSEL2 = 0x00000000; IO0DIR = 0XFFFFFFFF; IO1DIR = 0XFFFFFFFF; } void delay() { int c = 50000; while(c) c--; } voidshow_disp() { //Digit 1 d1 = count & 0x000F; IO0CLR = IOXcl; IO0SET = seg[d1]; IO1SET = IOX; IO1CLR = IO1; delay(); IO1SET = IOX; //Digit 2 d2 = count & 0x00F0; d2 >>= 4; IO0CLR = IOXcl; IO0SET= seg[d2]; IO1SET = IOX; IO1CLR = IO2; delay(); IO1SET= IOX; //Digit 3 d3 = count & 0x0F00; d3 >>= 8; IO0CLR = IOXcl; IO0SET= seg[d3]; IO1SET = IOX; IO1CLR = IO3; delay(); IO1SET = IOX; //Digit 4 d4 = count & 0xF000; d4>>= 4; IO0CLR = IOXcl; IO0SET = seg[d4]; IO1SET = IOX; IO1CLR = IO4; delay(); IO1SET = IOX; } int main( void ) { init_gpio(); while(1) { show_disp(); count++; count&= 0xFFFF; } }
C
#include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #define SERV_PORT 8888 #define CLIE_PORT 9000 // 广播时客户端端口号需要确定值 #define BROADCAST_IP "172.23.63.255" // ifconfig查看广播地址 int main(int argc, char const *argv[]) { int cfd; struct sockaddr_in clie_addr, serv_addr; char buf[BUFSIZ] = {0}; cfd = socket(AF_INET, SOCK_DGRAM, 0); bzero(&serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(SERV_PORT); serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); bind(cfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)); int flag = 1; setsockopt(cfd, SOL_SOCKET, SO_BROADCAST, &flag, sizeof(flag)); bzero(&clie_addr, sizeof(clie_addr)); clie_addr.sin_family = AF_INET; clie_addr.sin_port = htons(CLIE_PORT); inet_pton(AF_INET, BROADCAST_IP, &clie_addr.sin_addr.s_addr); int i = 0; while (1) { sprintf(buf, "Drink %d water\n", i++); sendto(cfd, buf, strlen(buf), 0, (struct sockaddr *)&clie_addr, sizeof(clie_addr)); sleep(1); } return 0; }
C
#include "zap_tmp.h" int compare(const void* a, const void* b) { if ((*(utmp_t**)a)->ut_time > (*(utmp_t**)b)->ut_time) return 1; else if ((*(utmp_t**)a)->ut_time < (*(utmp_t**)b)->ut_time) return -1; else return 0; } void append_utmp_array(utmp_t* element) { utmp_array[utmp_idx] = (utmp_t*)malloc(UTMPSIZ); memcpy(utmp_array[utmp_idx], element, UTMPSIZ); utmp_idx++; } void get_utmp_array(char* path) { utmp_t utmp_ent; int f; f = open_safe(path, O_RDWR); utmp_idx = 0; while(read(f, &utmp_ent, UTMPSIZ) > 0) { if (is_match(utmp_ent.ut_name, utmp_ent.ut_line, utmp_ent.ut_time)) { if (replace(utmp_ent.ut_name, utmp_ent.ut_line, &utmp_ent.ut_time)) // if replaced utmp_ent append_utmp_array(&utmp_ent); // then write on tmp file else continue; // else write nothing (and do not update latest) } else append_utmp_array(&utmp_ent); // not match -> write original utmp_ent } close(f); } void sort_and_write(char* path) { int tmp_f; tmp_f = open_tmp(); qsort(utmp_array, utmp_idx, sizeof(utmp_t*), compare); for (int i=0; i<utmp_idx; i++) { write(tmp_f, utmp_array[i], UTMPSIZ); free(utmp_array[i]); } close(tmp_f); copy_tmp(path); } void zap_tmp(char* path, char* username, char* username_r, int flag_R) { get_utmp_array(path); sort_and_write(path); update_latest(&latest_user, path, username); update_latest(&latest_user_r, path, username_r); }
C
#include<stdio.h> int main(){ int bubble_num,i ; void sortDisplay(int bubble_set[],int length); printf(":"); scanf("%d",&bubble_num); printf("\n"); int bubble_set[bubble_num]; int length = sizeof(bubble_set)/sizeof(bubble_set[0]); for(i=0;i<=(length-2)/2;i++){ bubble_set[2*i]=2; bubble_set[2*i+1]=1; } printf("ӵijʼ˳Ϊ\n"); sortDisplay(bubble_set,length); printf("\n"); for(i=0;i<length-1;i++){ int j; for(j=0;j<length-1-i;j++){ if(bubble_set[j+1]<bubble_set[j]){ int t=bubble_set[j]; bubble_set[j]=bubble_set[j+1]; bubble_set[j+1]=t; } } } printf("˳Ϊ\n"); sortDisplay(bubble_set,length); return 0; } void sortDisplay(int bubble_set[],int length){ int i; for(i=0;i<length;i++){ // printf("%d ",bubble_set[i]); if(bubble_set[i]==1){ printf(" "); }else{ printf(" ");; } } printf("\n"); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define VERB_PTR 0x6473 #define NOUN_PTR 0x65A9 #define OBJLOC_PTR 0x62f5 #define VERB_NUM 56 #define NOUN_NUM 48 #define VERB_OFFL 0x6400 #define VERB_OFFH 0x6438 typedef struct { char verb[64]; int address; } verb_struct; typedef struct { char noun[64]; int location; } noun_struct; char directions[10][20]={ "north", "south", "east", "west", "northeast", "northwest", "southeast", "southwest", "up", "down" }; typedef struct { int direction; int destination; int blocked:1; } exit_struct; typedef struct { int description; exit_struct exits[10]; } room_struct; verb_struct verbs[255]; noun_struct nouns[255]; char intro[15][255]; int main (void) { FILE *infile; char tokens[512][30], temp[30]; char messages[512][512]; room_struct rooms[512]; unsigned char byte, byte2; int i=0,size=0,ptr=0,lower=0,bracket; int endtok=0,lowtok=0,token=0,j=0; int msgcount=0, roomcount=0, introcount=0; int curexit=0; infile = fopen("XAAN","rb"); if (infile == NULL) { printf("Failed to open file\n"); exit(1); } fseek(infile,0x66e5,SEEK_SET); do { byte=fgetc(infile); if ( (byte != 0x40) && !feof(infile) ) { tokens[i][ptr++]=byte; } else if (!feof(infile)) { tokens[i][ptr++]='\0'; ptr=0; ++i; } } while (!feof(infile)); size=i; printf("Reading Intro\n"); fseek(infile,0x3100,SEEK_SET); endtok=0x0d; do { byte=fgetc(infile); if (byte == endtok) { introcount++; bracket=0; lower=0; } else if (byte < 0x20 || byte > 0x5a) { if (byte < 0x0e) token = byte + 0xa5; else if (byte < 0x20) token = byte + 0xa4; else token = byte - 0x5b; /* look up in dictionary */ if (lower==1) { sprintf(intro[introcount],"%s%c",intro[introcount],tokens[token][0]); } for (i=lower;i<strlen(tokens[token]);i++) { sprintf(intro[introcount],"%s%c",intro[introcount],tolower(tokens[token][i])); } lower=0; } else if (byte == 0x2e || byte == 0x3f || byte == 0x21 || byte == 0x2c || byte == 0x3b || byte == 0x3a) { sprintf(intro[introcount],"%s%c ",intro[introcount],byte); if (byte == 0x2e || byte == 0x3f || byte == 0x21) lower=1; } else if (byte > 0x40 && byte < 0x5b) { if (lower == 1) { token=byte; lower=0; } else { token=tolower(byte); } sprintf(intro[introcount],"%s%c",intro[introcount],token); } else if (byte == 0x23) { lower=1; } else if (byte == 0x2b) { sprintf(intro[introcount],"%s\\n",intro[introcount]); } else { sprintf(intro[introcount],"%s%c",intro[introcount],byte); } } while (ftell(infile) < 0x3249); printf("Reading Messages\n"); fseek(infile,0x3300,SEEK_SET); endtok=0x0d; msgcount=0; do { byte=fgetc(infile); if (byte == endtok) { msgcount++; bracket=0; lower=0; } else if (byte < 0x20 || byte > 0x5a) { if (byte < 0x0e) token = byte + 0xa5; else if (byte < 0x20) token = byte + 0xa4; else token = byte - 0x5b; /* look up in dictionary */ if (lower==1) { sprintf(messages[msgcount],"%s%c",messages[msgcount],tokens[token][0]); } for (i=lower;i<strlen(tokens[token]);i++) { sprintf(messages[msgcount],"%s%c",messages[msgcount],tolower(tokens[token][i])); } lower=0; } else if (byte == 0x2e || byte == 0x3f || byte == 0x21 || byte == 0x2c || byte == 0x3b || byte == 0x3a) { sprintf(messages[msgcount],"%s%c ",messages[msgcount],byte); if (byte == 0x2e || byte == 0x3f || byte == 0x21) lower=1; } else if (byte > 0x40 && byte < 0x5b) { if (lower == 1) { token=byte; lower=0; } else { token=tolower(byte); } sprintf(messages[msgcount],"%s%c",messages[msgcount],token); } else if (byte == 0x23) { lower=1; } else if (byte == 0x2b) { sprintf(messages[msgcount],"%s\\n",messages[msgcount]); } else { sprintf(messages[msgcount],"%s%c",messages[msgcount],byte); } } while (ftell(infile) < 0x5c57); printf("Enumerating rooms\n"); fseek(infile,0x6354,SEEK_SET); roomcount=0x34; do { byte = fgetc(infile); token = byte + 162; rooms[roomcount].description=token; roomcount++; } while (ftell(infile) < 0x6400); roomcount--; printf("Gathering exits\n"); fseek(infile, 0x5c5c, SEEK_SET); i=0x34; curexit=0; for (j=0;j<10;j++) rooms[i].exits[j].destination=0xff; do { unsigned char byte2; byte=fgetc(infile); byte2=fgetc(infile); rooms[i].exits[curexit].direction=byte & 0xf; rooms[i].exits[curexit].destination=byte2; if (byte & 0x40) { rooms[i].exits[curexit].blocked=1; } curexit++; if (byte & 0x80) { i++; for (j=0;j<10;j++) rooms[i].exits[j].destination=0xff; curexit=0; } } while (i < roomcount); printf("%lx\n",ftell(infile)); printf("Gathering Verbs\n"); fseek(infile,VERB_PTR,SEEK_SET); for (i=0; i<VERB_NUM; i++) { int ptr=0, j=0; do { j=fgetc(infile); if (j != '@') verbs[i].verb[ptr++]=j; } while (j != '@'); verbs[i].verb[ptr]='\0'; } // addresses fseek(infile, VERB_OFFL, SEEK_SET); for (i=1; i<VERB_NUM; i++) { verbs[i].address=fgetc(infile); } fseek(infile, VERB_OFFH, SEEK_SET); for (i=1; i<VERB_NUM; i++) { verbs[i].address+=(fgetc(infile)<<8); } verbs[0].address=0; printf("Gathering Nouns\n"); fseek(infile,NOUN_PTR+1,SEEK_SET); for (i=0; i<NOUN_NUM; i++) { int ptr=0, j=0; do { j=fgetc(infile); if (j != '@') nouns[i].noun[ptr++]=j; } while (j != '@'); nouns[i].noun[ptr]='\0'; } printf("Object Locations\n"); fseek(infile,OBJLOC_PTR+1,SEEK_SET); for (i=0; i<NOUN_NUM; i++) { int ptr=0, j=0; j=fgetc(infile); nouns[i].location=j; } printf("\n\nDumping it all:\n"); printf("Intro:\n"); for (i=0; i<=introcount; i++) { printf("%s\n", intro[i]); } // Display messages for (i=0; i<=msgcount; i++) { printf("Message %d: %s\n", i, messages[i]); } // Display rooms for (i=0x34; i<=roomcount; i++) { printf("\nRoom %d: %s\n", i, messages[rooms[i].description]); printf("Exits:\n"); for (j=0; j < 10; j++) { if (rooms[i].exits[j].destination != 0xff) { printf(" %s to %d (%s)", directions[rooms[i].exits[j].direction], rooms[i].exits[j].destination, messages[rooms[rooms[i].exits[j].destination].description]); if (rooms[i].exits[j].blocked) { printf("(blocked)"); } printf("\n"); } } } // Display Verbs for (i=0; i<VERB_NUM; i++) { printf("Verb %d: %s\n address &%04x\n", i, verbs[i].verb, verbs[i].address); } for (i=2; i<NOUN_NUM; i++) { printf("Noun %d: %s\n Starts in: %d (%s)\n", i, nouns[i].noun, nouns[i].location, (nouns[i].location==0)?"inventory": (nouns[i].location==1)?"worn": (nouns[i].location<0x34)?nouns[nouns[i].location].noun: (nouns[i].location>223)?"nowhere": messages[rooms[nouns[i].location].description]); } fclose(infile); return 0; }
C
// // Created by shuttle3468 on 8/2/17. // #include "origin.h" //! **Upper Hull and Lower Hull Algorithm** /*! 1. In case of upper hull formation we move from last element to the first and vice versa for lower hull.\n * * 2. Now we remove those points that are either **anti-clockwise or collinear** because being anticlockwise we are * actually using an interior point in such cases.\n * * 3. After forming the hull remove the **last point** of each list (it's the same as the first point of the other list) */ vector<pair<double,double > > convex_hull(vector<pair<double, double> > points) { int n = points.size(); int counter = 0; vector<pair<double, double> > hull; for (int i = 0; i < n; ++i) { while (counter >= 2 && orientation(hull[counter-2], hull[counter-1], points[i]) != CLOCKWISE) { cout << "popping out\n"; counter--; hull.pop_back(); indices.pop_back(); } hull.pb(points[i]); counter++; indices.pb(i); } cout << "-------------------COUNTER VALUE AFTER LOWER HULL:" << counter <<endl; // Build upper hull for (int i = n-2, t = counter+1; i >= 0; i--) { while (counter >= t && orientation(hull[counter-2], hull[counter-1], points[i]) != CLOCKWISE) { cout << "popping out\n"; counter--; hull.pop_back(); indices.pop_back(); } hull.pb(points[i]); counter++; indices.pb(i); } cout << "-------------------COUNTER VALUE AFTER UPPER HULL:" << counter <<endl; hull.resize(counter-1); return hull; } //! **Complete Execution of Andrews Monotone Chain** /*! 1. Sort the array by their **x-coordinate**. If that's equal then compare y-coordinate this is compared in origin.h * header file.\n * * 2. The next part involves getting upper and lower convex hull\n * * 3. The final set that is formed is just to **remove** any existing duplicate points in the vector */ set<pair<double, double> > execAndrews(vector<pair<double, double> > Points) { cout << "Executing Andrews Algorithm\n---\n"; vector<pair<double, double> > tentative_hull; vector<pair<double, double> > L_upper,L_lower; int len; len = int(Points.size()); /* * Sort the Points By x-coordinate */ sort(Points.begin(),Points.end(),orderedSort); tentative_hull = convex_hull(Points); /* * Final Set of Convex Points */ set<pair<double ,double> > f_convex_hull; int LU_len = tentative_hull.size(); //int LL_len = L_lower.size(); ofstream out_file; out_file.open("output.ch"); out_file << "CH\n"; out_file << len << " " << LU_len << "\n"; cout << "Elements in convex hull:" << LU_len <<endl; for(int i=0;i < len;i++) { out_file << Points[i].first << " " << Points[i].second << " 0\n"; } for(int i=0;i<LU_len;i++) { f_convex_hull.insert(tentative_hull[i]); } indices.erase(indices.begin()); indices.pop_back(); vector<int>::iterator it_set; for(it_set = indices.begin(); it_set!=indices.end(); it_set++) { out_file << *it_set << " "; } out_file << *(indices.end()); out_file.close(); return f_convex_hull; }
C
#include <string.h> #include "memfile.h" #include "util.h" extern const char system_lsp[]; int _stdin_ungetch=0; FILE memp[1]; #if 0 struct __sFILE { unsigned char *_p; /* current position in (some) buffer */ int _r; /* read space left for getc() */ int _w; /* write space left for putc() */ short _flags; /* flags, below; this FILE is free if 0 */ short _file; /* fileno, if Unix descriptor, else -1 */ struct __sbuf _bf; /* the buffer (at least 1 byte, if !NULL) */ int _lbfsize; /* 0 or -_bf._size, for inline putc */ } #endif FILE *mem_fopen(const char *file,const char *mode) { FILE *fp = memp; printf("fopen(%s,%s)\n",file,mode); memset(fp,0,sizeof(FILE)); fp->_p = (unsigned char*) system_lsp; fp->_r = strlen( (char *)fp->_p); fp->_file = 'M'; if(strcmp(file,"system.lsp")!=0) return NULL; return fp; } int mem_fread(char *buf,int size,int n,FILE *fp) { size *= n; printf("fread(%d) %x\n",size,(int)fp); if(fp->_file != 'M') return EOF; if(size > fp->_r) return EOF; char *src = (char *)fp->_p; memcpy(buf,src,size); { fp->_p += size; fp->_r -= size; } return size; } int mem_fclose(FILE *fp) { return 0; } int mem_feof(FILE *fp) { if(fp==stdin) return 0; if(fp->_file != 'M') return EOF; if(fp->_r <= 0) return EOF; return 0; } int stdin_ungetc(c) { _stdin_ungetch = c; return c; } int stdin_getc() { int c; if( _stdin_ungetch ) { c = _stdin_ungetch; _stdin_ungetch = 0; return c; } while(1) { c = user_getc(); if(c!=(-1)) { user_putc(c); if(c==0x0d) user_putc(0x0a); return c; } } } int mem_fgetc(FILE *fp) { if(fp==stdin) return stdin_getc(); if(fp->_file != 'M') return EOF; int c = fp->_p[0]; int size = 1; { fp->_p += size; fp->_r -= size; } // printf("fgetc()=%x %x\n",c,(int)fp); // user_putc(c); return c; } int mem_ungetc(int c,FILE *fp) { if(fp==stdin) return stdin_ungetc(c); if(fp->_file != 'M') return EOF; int size = -1; { fp->_p += size; fp->_r -= size; } // printf("ungetc()=%x %x\n",c,(int)fp); // user_putc("<"); return c; }
C
//Classe: Equipe #include "gerenciaEquipes.h" #include "structs.h" #include "validacoes.h" /* Mtodos */ //Objetivo : Exibir o menu CRUD da classe equipe. //Parmetros: //Retorno : *** void menuEquipeCRUD(char *opcaoUsuario, int *validaInteracao, int *qtdEquipes){ FILE *arqvEquipes; tEquipe tempStruct; arqvEquipes = NULL; do{ //Criar ou abrir arquivo existente if((arqvEquipes = fopen(ARQV_EQUIPES, "r")) == NULL){ if((arqvEquipes = fopen(ARQV_EQUIPES, "wb+")) == NULL){ printf("\n*** FALHA AO CRIAR O ARQUIVO! ***\n\n"); fclose(arqvEquipes); getch(); return; } }else{ if((arqvEquipes = fopen(ARQV_EQUIPES, "rb+")) == NULL){ printf("\n*** FALHA AO ABRIR O ARQUIVO! ***\n\n"); fclose(arqvEquipes); getch(); return; } } //Obtem quantidade de equipes cadastradas *qtdEquipes = 0; fseek(arqvEquipes, 0, SEEK_SET); while(fread(&tempStruct, sizeof(tEquipe), 1, arqvEquipes) == 1){ (*qtdEquipes)++; } //Apresentao do menu system("cls"); printf("*** GERENCIAMENTO DE EQUIPES ***\n"); printf("--------------------------------\n\n"); printf("Qtd. Equipes: %i\n\n", *qtdEquipes); printf("[C] Cadastrar Equipe.\n"); printf("[E] Excluir Equipe.\n"); printf("[X] Voltar ao menu anterior...\n\n"); leValidaOpcao("Qual opcao deseja[C/E/X]? ", opcaoUsuario, "CEX"); switch(*opcaoUsuario){ case 'C': cadastraEquipe(arqvEquipes, qtdEquipes); break; case 'E': excluiEquipe(arqvEquipes, qtdEquipes); break; default: *validaInteracao = 0; } }while(*validaInteracao == 1); } void cadastraEquipe(FILE *arqvEquipes, int *qtdEquipes){ int contQtdEquipes, validaString; char opcaoUsuario; tEquipe *pEquipes, tempEquipe; //Inicializar variaveis pEquipes = NULL; if(*qtdEquipes == 0){ if((pEquipes = (tEquipe*) calloc(1, sizeof(tEquipe))) == NULL){ printf("\n*** FALHA AO ALOCAR MEMORIA! ***\n\n"); exit(EXIT_FAILURE); } }else{ if((pEquipes = (tEquipe*) calloc(*qtdEquipes, sizeof(tEquipe))) == NULL){ printf("\n*** FALHA AO ALOCAR MEMORIA! ***\n\n"); exit(EXIT_FAILURE); }else{ //Aloca os dados em memoria fseek(arqvEquipes, 0, SEEK_SET); contQtdEquipes = 0; while(fread((pEquipes+contQtdEquipes), sizeof(tEquipe), 1, arqvEquipes) == 1){ contQtdEquipes++; } } } //Cadastrar nova equipe do{ system("cls"); printf("*** CADASTRO DE EQUIPES ***\n"); printf("---------------------------\n\n"); //Nome da Equipe do{ validaString = 0; leValidaString("Informe o nome da equipe: ", MSG_ERRO, tempEquipe.nomeEquipe, 0); validaNomeEquipeRepetida(pEquipes, *qtdEquipes, tempEquipe.nomeEquipe, &validaString); if(validaString == 1){ printf("\n*** A equipe %s ja existe! ***\n\n", tempEquipe.nomeEquipe); } }while(validaString == 1); //Sigla do{ validaString = 0; leValidaSigla("Agora, informe a sigla da equipe: ", MSG_ERRO, tempEquipe.siglaEquipe); validaSiglaEquipeRepetida(pEquipes, *qtdEquipes, tempEquipe.siglaEquipe, &validaString); if(validaString == 1){ printf("\n*** A sigla %s ja existe! ***\n\n", tempEquipe.siglaEquipe); } }while(validaString == 1); //Pais de Origem selecionaPais(tempEquipe.paisOrigem); //Gravar dados no arquivo fseek(arqvEquipes, 0, SEEK_END); fwrite(&tempEquipe, sizeof(tEquipe), 1, arqvEquipes); printf("\nGravando dados."); sleep(1); printf("."); sleep(1); printf("."); sleep(1); printf("OK!\n\n"); leValidaOpcao("Deseja cadstrar mais uma equipe[S/N]? ", &opcaoUsuario, "SN"); if(opcaoUsuario == 'S'){ //Incremento da quantidade de equipes (*qtdEquipes)++; } }while(opcaoUsuario == 'S'); //Desalocando free(pEquipes); //Fechando o arquivo fclose(arqvEquipes); } void excluiEquipe(FILE *arqvEquipes, int *qtdEquipes){ int contQtdEquipes, escolhaUsuario; char opcaoUsuario; tEquipe *pEquipes; pEquipes = NULL; //Verifica se h dados para serem excluidos if(*qtdEquipes == 0){ printf("\n*** Nao ha equipes cadastradas! ***\n\n"); getch(); return; }else{ if((pEquipes = (tEquipe*) calloc(*qtdEquipes, sizeof(tEquipe))) == NULL){ printf("\n*** FALHA AO ALOCAR MEMORIA! ***\n\n"); exit(EXIT_FAILURE); } //Aloca os dados em memoria fseek(arqvEquipes, 0, SEEK_SET); contQtdEquipes = 0; while(fread((pEquipes+contQtdEquipes), sizeof(tEquipe), 1, arqvEquipes) == 1){ contQtdEquipes++; } } //Exclui um usurio do{ escolhaUsuario = 0; opcaoUsuario = '\0'; system("cls"); printf("*** EXCLUSAO DE EQUIPES ***\n"); printf("---------------------------\n\n"); printf("+----+---------------+-------+---------------+\n"); printf("| ID | NOME | SIGLA | PAIS |\n"); printf("+----+---------------+-------+---------------+\n"); for(contQtdEquipes = 0; contQtdEquipes < *qtdEquipes; contQtdEquipes++){ printf("|%4i|%15s|%7s|%15s|\n", contQtdEquipes+1, pEquipes[contQtdEquipes].nomeEquipe, pEquipes[contQtdEquipes].siglaEquipe, pEquipes[contQtdEquipes].paisOrigem ); printf("+----+---------------+-------+---------------+\n"); } leValidaInt("\nEscolha uma equipe para ser excluida: ", MSG_ERRO, &escolhaUsuario, 1, contQtdEquipes+1); strcpy(pEquipes[escolhaUsuario-1].nomeEquipe, "\0"); strcpy(pEquipes[escolhaUsuario-1].siglaEquipe, "\0"); strcpy(pEquipes[escolhaUsuario-1].paisOrigem, "\0"); for(contQtdEquipes = 0; contQtdEquipes < *qtdEquipes; contQtdEquipes++){ if(strcmp(pEquipes[contQtdEquipes].nomeEquipe, "\0") == 0){ pEquipes[contQtdEquipes] = pEquipes[contQtdEquipes+1]; } } (*qtdEquipes)--; //Zera os dados no arquivo. fclose(arqvEquipes); if((arqvEquipes = fopen(ARQV_EQUIPES, "wb+")) == NULL){ printf("\n*** FALHA AO ABRIR O ARQUIVO! ***\n\n"); fclose(arqvEquipes); getch(); return; } fseek(arqvEquipes, 0, SEEK_SET); //Regrava os dados sem a posio excluida. fwrite(pEquipes, sizeof(tEquipe), *qtdEquipes, arqvEquipes); printf("\nRegravando dados."); sleep(1); printf("."); sleep(1); printf("."); sleep(1); printf("OK!\n\n"); if(*qtdEquipes > 0){ leValidaOpcao("\nDeseja excluir mais uma equipe[S/N]? ", &opcaoUsuario, "SN"); } }while(opcaoUsuario == 'S'); //Desaloca free(pEquipes); //Fecha o arquivo fclose(arqvEquipes); } /* Funes & Procedimentos da Classe Equipes */ //Objetivo : Validar se h uma string repetida. //Parmetros: void validaNomeEquipeRepetida(tEquipe *pEquipes, int qtdEquipes, char *string, int *validaRepetido){ int contQtd; for(contQtd = 0; contQtd < qtdEquipes; contQtd++){ if(stricmp(string, pEquipes[contQtd].nomeEquipe) == 0){ *validaRepetido = 1; break; } } } //Objetivo : Validar se h uma string repetida. //Parmetros: void validaSiglaEquipeRepetida(tEquipe *pEquipes, int qtdEquipes, char *string, int *validaRepetido){ int contQtd; for(contQtd = 0; contQtd < qtdEquipes; contQtd++){ if(stricmp(string, pEquipes[contQtd].siglaEquipe) == 0){ *validaRepetido = 1; break; } } } //Objetivo : Apresentar paises ao usurio e deixa-lo escolher um. //Parmetros: Referncia ao ponteiro do elemento pais da struct tEquipe. //Retorno : *** void selecionaPais(char *paisOrigem){ int contQtdPaises, qtdPaises, opcaoPais; tPais *pPaises, tempStruct; FILE *arqvPaises; contQtdPaises = 0; qtdPaises = 0; pPaises = NULL; arqvPaises = NULL; //Abrir arquivo if((arqvPaises = fopen(ARQV_PAISES, "r")) == NULL){ if((arqvPaises = fopen(ARQV_PAISES, "w+")) == NULL){ printf("\n*** FALHA AO CRIAR O ARQUIVO! ***\n\n"); fclose(arqvPaises); getch(); return; } }else{ if((arqvPaises = fopen(ARQV_PAISES, "r")) == NULL){ printf("\n*** FALHA AO ABRIR O ARQUIVO! ***\n\n"); fclose(arqvPaises); getch(); return; } } fseek(arqvPaises, 0, SEEK_SET); while(!feof(arqvPaises)){ fscanf(arqvPaises, "%s", &tempStruct.siglaPais); fseek(arqvPaises, (long) sizeof(char), SEEK_CUR); fscanf(arqvPaises, "%s\n", &tempStruct.nomePais); qtdPaises++; } //Insere os dados na memoria if(qtdPaises == 0){ printf("\n*** No h dados no arquivo paises.txt! ***\n\n"); fclose(arqvPaises); return; }else{ if((pPaises = (tPais*) calloc(qtdPaises, sizeof(tPais))) == NULL){ printf("\n*** FALHA AO ALOCAR MEMORIA! ***\n\n"); exit(EXIT_FAILURE); }else{ qtdPaises = 0; fseek(arqvPaises, 0, SEEK_SET); while(!feof(arqvPaises)){ fscanf(arqvPaises, "%s", (pPaises+qtdPaises)->siglaPais); fseek(arqvPaises, (long) sizeof(char), SEEK_CUR); fscanf(arqvPaises, "%s\n", (pPaises+qtdPaises)->nomePais); qtdPaises++; } } } //O usurio seleciona um pais printf("+----+----+---------------+\n"); for(contQtdPaises = 0; contQtdPaises < qtdPaises; contQtdPaises++){ printf("|%4i|%4s|%-15s|\n", contQtdPaises+1, (pPaises+contQtdPaises)->siglaPais, (pPaises+contQtdPaises)->nomePais); } printf("+----+----+---------------+\n"); leValidaInt("\nSelecione um pais[1-10]: ", MSG_ERRO, &opcaoPais, 1, contQtdPaises+1); memcpy(paisOrigem, (pPaises+(opcaoPais-1))->nomePais, sizeof((pPaises+(opcaoPais-1))->nomePais)); free(pPaises); fclose(arqvPaises); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int strongPasswordChecker(char* s) { int longitud = strlen(s); int contain_min =0; int contain_may =0; int contain_num =0; if(longitud<=20 && longitud>=6){ for(int i=0;i<longitud;i++){ if((int)(s[i])>=48 && (int)(s[i])<=57 ){ contain_num = 1; } if((int)(s[i])>=65 && (int)(s[i])<=90){ contain_may = 1; } if((int)(s[i])>=97 && (int)(s[i])<=122){ contain_min = 1; } } if(contain_min && contain_may && contain_num){ printf("\nLa contrasena es aceptada\n"); return 0; }else{ printf("\nLa contrasena es rechazada\n"); if(contain_num==0){ printf("\nLa Contraseña debe contener al menos un numero\n"); } else if(contain_may==0){ printf("\nLa Contraseña debe contener al menos una letra mayuscula\n"); }else if(contain_min==0){ printf("\nLa Contraseña debe contener al menos una letra minuscula\n"); } return -1; } }else{ printf("\nLa contraseña debe tener una longitud entre 6 y 20 caracteres\n"); return -1; } } int main(){ char *pass = "hoLaa1"; strongPasswordChecker(pass); return 0; }
C
// // signal.c // TCP&C-Demo // // Created by sheng wang on 2019/10/22. // Copyright © 2019 feisu. All rights reserved. // #include "unp.h" void read_childpro(int sig) { int status; pid_t id = waitpid(-1, &status, WNOHANG); if (WIFEXITED(status)) { printf("remove proc id:%d \n", id); printf("child send: %d \n", WEXITSTATUS(status)); } } int main() { int pid = fork(); if(pid > 0) { struct sigaction s; memset(&s, 0, sizeof(s)); s.sa_handler = read_childpro; sigfillset(&s.sa_mask); /* 下面这句话去掉,输出如下: remove proc id:69304 child send: 22 End 然后程序结束 下面这句话不注释,输出如下: remove proc id:69297 child send: 22 然后程序会回到之前的被中断的系统调用scanf函数处,等待用户输入,一旦用户输入完毕后,程序才会终止 http://49d2d554.wiz03.com/wapp/pages/view/share/s/19QJlk1ln4BA22s3BC3c9d430od0332DXk8m2UifrV3KVUu0 */ s.sa_flags |= SA_RESTART; assert(sigaction(SIGCHLD, &s, NULL) != 1); } else if(pid == 0) { sleep(3); exit(22); } char str[10]; scanf("%s", str); printf("%s\n", str); puts("End"); return 0; }
C
#include<stdio.h> #include<conio.h> void main() { longint sum=0,i,n; clrscr(); printf("enter the n numbers"); scanf("%ld",&n); for(i=1;i<=n;i++) { sum=n*i; printf("\n 5*%ld=%ld"); } getch(); }
C
#include "stdio.h" #include "stdlib.h" #include "unistd.h" int main(){ pid_t pid=getpid(); pid_t sid = getsid(pid); char data[10]; //Write to /proc/*pid of the program*/fd/0. The fd subdirectory contains the descriptors of all the opened files and file descriptor 0 is the standard input (1 is stdout and 2 is stderr). printf("CT1:\n"); printf("%d\n", sid); scanf("%9s",data); printf("%s\n", data); return 0; }
C
/* ** EPITECH PROJECT, 2019 ** corewar ** File description: ** check_label_two */ #include "asm.h" int is_it_good(label_t *index, char *str) { int compt = 0; while (index != NULL) { if (my_strcmp(index->name, str) == 0) compt = compt + 1; if (compt == 2) return (84); index = index->next; } return (0); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "queue.h" #include "mylib.h" typedef struct q_item *q_item; struct q_item { double item; q_item next; }; struct queue { q_item first; q_item last; int length; }; queue queue_new() { queue result = emalloc(sizeof * result); result->first = NULL; result->last = NULL; result->length = 0; return result; } void enqueue(queue q, double item) { q_item node = emalloc(sizeof * node); node->item = item; node->next = NULL; if (NULL == q->first) { q->first = node; q->first->next = NULL; q->last = q->first; q->length++; } else if (NULL != q->first) { q->last->next = node; q->last = node; q->length++; } } double dequeue(queue q) { q_item node = emalloc(sizeof * node); node = q->first; if (q->length > 0) { q->length--; q->first = node->next; return node->item; } return 0; } void queue_print(queue q) { int i = 0; q_item node = emalloc(sizeof * node); node = q->first; printf("%.2f\n", node->item); for (i = 1; i<q->length; i++){ printf("%.2f\n", node->next->item); node = node->next; } } int queue_size(queue q) { return q->length; } queue queue_free(queue q) { free(q->first); free(q->last); free(q); return q; }
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #define NUM_THREADS 2 typedef struct _thread_data_t { int tid; double stuff; } thread_data_t; void *thr_func(void *arg){ thread_data_t * data = (thread_data_t *)arg; printf("HI id: %d\n", data->tid); pthread_exit(NULL); } int main(void){ pthread_t thr[NUM_THREADS]; int i, rc; thread_data_t thr_data[NUM_THREADS]; for ( i = 0; i < NUM_THREADS; ++i){ thr_data[i].tid = i; if ( ( rc = pthread_create(&thr[i], NULL, thr_func, &thr_data[i]))){ fprintf(stderr, "error: %d\n", rc); return EXIT_FAILURE; } } for ( i = 0; i < NUM_THREADS; ++i){ pthread_join(thr[i],NULL); } return EXIT_SUCCESS; }
C
#include "myMath.h" #include <stdio.h> int main(){ double x; printf("Please inset a real number: "); scanf("%lf", &x); //f(x) = e^x + x^3 − 2 double y = sub(add(Exponent(x), Power(x,3)),2); printf("\nThe value of f(𝑥) = 𝑒^𝑥 + 𝑥^3 − 2 at the point %lf is: %.4lf", x, y); //f(x) = 3x + 2x^2 double y2 = add(mul(x,3),mul(Power(x,2),2)); printf("\nThe value of f(𝑥) = 3𝑥 + 2𝑥^2 at the point %lf is: %.4lf", x, y2); //f(x) = (4x^3)/5 - 2x double y3 = sub(div(mul(Power(x,3),4),5),mul(x,2)); printf("\nThe value of f(𝑥) = (4𝑥^3)/5 - 2𝑥 at the point %lf is: %.4lf\n", x, y3); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "list.h" int main(){ struct node *s = (struct node *)malloc(sizeof(struct node)); //(*(*s).next).i = 'b'; print_list(s); s = insert_front(s,'a'); print_list(s); s = insert_front(s,'b'); print_list(s); s = free_list(s); printf("Pointer to s:[%p]\n",s); print_list(s); return 0; }
C
#include <stdio.h> #include <stdlib.h> #define ERROR 1e8 typedef int ElementType; typedef enum { push, pop, end } Operation; typedef struct StackRecord *Stack; struct StackRecord { int Capacity; /* maximum size of the stack array */ int Top1; /* top pointer for Stack 1 */ int Top2; /* top pointer for Stack 2 */ ElementType *Array; /* space for the two stacks */ }; Stack CreateStack(int MaxElements) { Stack stack = (Stack)malloc(sizeof(struct StackRecord)); stack->Capacity = MaxElements; stack->Array = (ElementType *)malloc(sizeof(ElementType)*MaxElements); stack->Top1 = -1; stack->Top2 = MaxElements; return stack; } int IsEmpty(Stack S, int Stacknum) { if(Stacknum == 1 && S->Top1 == -1)return 1; else if(Stacknum == 2 && S->Top2 == S->Capacity)return 1; else return 0; } int IsFull(Stack S) { if (S->Top2 - S->Top1 == 1)return 1; else return 0; } int Push(ElementType X, Stack S, int Stacknum) { if (IsFull(S))return 0; else if(Stacknum==1){ (S->Array)[++(S->Top1)] = X; return 1; } else if(Stacknum==2){ (S->Array)[--(S->Top2)] = X; return 1; } return 0; } ElementType Top_Pop(Stack S, int Stacknum) { if (IsEmpty(S, Stacknum))return ERROR; else if (Stacknum == 1)return (S->Array)[(S->Top1)--]; else return (S->Array)[(S->Top2)++]; } Operation GetOp() { char *s = (char *)malloc(sizeof(char)); scanf("%s", s); if (strcmp(s, "push")==0)return push; else if (strcmp(s, "pop") == 0)return pop; else if(strcmp(s,"end")==0)return end; } void PrintStack(Stack S, int Stacknum) { int i; if (Stacknum == 1) { for (i = S->Top1; i >=0; i--)printf("%d ", S->Array[i]); printf("\n"); } else { for (i = S->Top2; i < S->Capacity; i++)printf("%d ", S->Array[i]); printf("\n"); } } int main() { int N, Sn, X; Stack S; int done = 0; scanf("%d", &N); S = CreateStack(N); while (!done) { switch (GetOp()) { case push: scanf("%d %d", &Sn, &X); if (!Push(X, S, Sn)) printf("Stack %d is Full!\n", Sn); break; case pop: scanf("%d", &Sn); X = Top_Pop(S, Sn); if (X == ERROR) printf("Stack %d is Empty!\n", Sn); break; case end: PrintStack(S, 1); PrintStack(S, 2); done = 1; break; } } return 0; } /* Your function will be put here */
C
#ifndef UTN_H_INCLUDED #define UTN_H_INCLUDED /// PRINCIPALES /** \brief Obtiene un string * * \param message char* El mensaje a mostrar * \param messageError char* El mensaje de error a mostrar * \param min int El tamao minimo * \param max int El temao maximo * \param tries int* Intentos que tiene el usuario para ingresar el dato correctamente * \param result char* Donde se guardara el string obtenido * \return int (0) si pudo obtenerlo (-1) si no pudo * */ int getString(char* message, char* messageError, int min, int max, int tries, char* result); /** \brief Obtiene un numero entero sin signo * * \param input int* Donde se guardara el int obtenido * \param message char* El mensaje a mostrar * \param messageError char* El mensaje de error * \param minSize int La cantidad minima de digitos a ingresar * \param maxSize int La cantidad maxima de digitos a ingresar * \param min int El numero minimo del rango que se puede ingresar * \param max int El numero maximo del rango que se puede ingresar * \param tries int La cantidad de intentos * \return int (0) si pudo obtenerlo (-1) si no pudo * */ int getUnsignedInt(int* input, char* message, char* messageError, int minSize, int maxSize, int min, int max, int tries); /** \brief Valida numeros enteros sin signo de una cadena * * \param string char* La cadena a validar * \return int (1) si es valida (0) si no lo es * */ int isValidNumber(char* string); /** \brief Obtiene un numero caracter * * \param result char* Donde se guardara el caracter obtenido * \param message char* El mensaje a mostrar * \param messageError char* El mensaje de error * \param tries int La cantidad de intentos * \return int (0) si pudo obtenerlo (-1) si no pudo * */ int getChar(char* result, char* message, char* messageError, int tries); /** \brief Valida caracteres de una cadena * * \param string char* La cadena a validar * \return int (1) si es valida (0) si no lo es * */ int isValidChar(char character); /** \brief Obtiene un texto * * \param input char* Donde se guardara el texto obtenido * \param message char* El mensaje a mostrar * \param messageError char* El mensaje de error * \param minSize int La cantidad minima de digitos a ingresar * \param maxSize int La cantidad maxima de digitos a ingresar * \param tries int La cantidad de intentos * \return int (0) si pudo obtenerlo (-1) si no pudo * */ int getTexto(char* input, char* message, char* messageError, int minSize, int maxSize, int tries); /** \brief Valida texto de una cadena * * \param string char* La cadena a validar * \param int lenght El largo de la cadena * \return int (1) si es valida (0) si no lo es * */ int isValidText(char* string, int lenght); /** \brief Obtiene un alfanumerico * * \param input char* Donde se guardara el alfanumerico obtenido * \param message char* El mensaje a mostrar * \param messageError char* El mensaje de error * \param minSize int La cantidad minima de digitos a ingresar * \param maxSize int La cantidad maxima de digitos a ingresar * \param tries int La cantidad de intentos * \return int (0) si pudo obtenerlo (-1) si no pudo * */ int getAlfanumeric(char* input, char* message, char* messageError, int minSize, int maxSize, int tries); /** \brief Valida alfanumericos de una cadena * * \param string char* La cadena a validar * \param int lenght El largo de la cadena * \return int (1) si es valida (0) si no lo es * */ int isValidAlphanumeric(char* string, int lenght); /// /** \brief Muestra el mensaje que indica que no hay mas intentos disponibles * * \param tries int Si la variable tries de la funcion que la llama es -1, se muestra el mensaje de esta funcion * \return void * */ void showTriesOverMessage(int tries); /** \brief Obtiene una fecha valida * * \param date eDate La fecha a validar * \param minYear int El ao minimo * \param maxYear int El ao maximo * \return int (1) si es valida, (0) si no lo es * */ int getFecha(int day, int month, int year, int minYear, int maxYear); /** \brief Verifica si un ao es bisiesto * * \param year int El ao a verificar * \return int (1) si es, (0) si no lo es * */ int isLeapYear(int year); /** * \brief Solicita un numero de opcion y lo valida * \param int maxOption La opcion maxima que se puede introducir * \return La opcion validada */ int getOption(int); /** * \brief Solicita el numero de opcion de un menu para confirmar los cambios de acuerdo a ese menu * \param int menuOption El numero de la opcion del menu * \return (1) si se confirmaron los cambios, (0) si no se confirmaron * Le paso el numero de la opcion del menu y muestra el mensaje de confirmacion adecuado para la accion que vaya a realizar */ int confirm(int); int utn_getCadena(char *pAux,int limite,int reintentos,char* msj,char*msjError); int getCadena(char* pAux,int limite); int utn_getEntero(int* pEntero,int reintentos,char* msg,char*msgError,int min,int max); int getInt(int* pAux); int isInt(char *pAux); #endif // UTN_H_INCLUDED
C
// 20. Write a program to display // a. Prime numbers between 1 to 100 // b. Armstrong Numbers between 1 to 500s #include<stdio.h> void main() { int i,j,LR,HR; printf("Enter the range "); scanf("%d %d",&LR,&HR); for(i=LR; i<=HR; i++) { for(j=2; j<i;j++) { if(i%j==0) break; } if(j==i) printf("%d\n", i); } }
C
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <stdlib.h> #define PRINT_ERR(mess)(perror(mess);printf("errno=%d\n",errno);exit(-1)) #define FAILE(mess)(fprintf(stdout,"%s:%s\n",mess,strerror(errno))) /*nonblock to read terminal by change terminal file`s block attribute*/ int main(){ int fd; int re; char buf[1024]={0}; fd=open("/dev/tty",O_RDONLY|O_NONBLOCK); if(fd<0) PRINT_ERR("main open"); while((re=read(fd,buf,sizeof(buf)))<0){ if(errno==EAGAIN){ FAILE("try again"); } else PRINT_ERR(" main read"); } write(STDOUT_FILENO,buf,re); return 0; }
C
#include <stdio.h> char* intToRoman(int num) { int roman[13] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; char* res = (char*)malloc(sizeof(char) * 55); int i = 0; while (num != 0) { int j = 0; while (j < 13) { if (num >= roman[j]) { if (j == 1) { sprintf(res + i, "%c", 'C'); i++; sprintf(res + i, "%c", 'M'); } else if (j == 3) { sprintf(res + i, "%c", 'C'); i++; sprintf(res + i, "%c", 'D'); } else if (j == 5) { sprintf(res + i, "%c", 'X'); i++; sprintf(res + i, "%c", 'C'); } else if (j == 7) { sprintf(res + i, "%c", 'X'); i++; sprintf(res + i, "%c", 'L'); } else if (j == 9) { sprintf(res + i, "%c", 'I'); i++; sprintf(res + i, "%c", 'X'); } else if (j == 11) { sprintf(res + i, "%c", 'I'); i++; sprintf(res + i, "%c", 'V'); } else if (j == 0) { sprintf(res + i, "%c", 'M'); } else if (j == 2) { sprintf(res + i, "%c", 'D'); } else if (j == 4) { sprintf(res + i, "%c", 'C'); } else if (j == 6) { sprintf(res + i, "%c", 'L'); } else if (j == 8) { sprintf(res + i, "%c", 'X'); } else if (j == 10) { sprintf(res + i, "%c", 'V'); } else if (j == 12) { sprintf(res + i, "%c", 'I'); } //printf ("%d ", roman[j]); num -= roman[j]; i++; break; //printf ("%d ", num); //break; } j++; } } sprintf(res + i, "%c", '\0'); return res; } /***************************************************************************************************************/ const int values[] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; const char* symbols[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; char* intToRoman(int num) { char* roman = malloc(sizeof(char) * 16); roman[0] = '\0'; for (int i = 0; i < 13; i++) { while (num >= values[i]) { num -= values[i]; strcpy(roman + strlen(roman), symbols[i]); } if (num == 0) { break; } } return roman; } /***************************************************************************************************************/ const char* thousands[] = { "", "M", "MM", "MMM" }; const char* hundreds[] = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" }; const char* tens[] = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" }; const char* ones[] = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" }; char* intToRoman(int num) { char* roman = malloc(sizeof(char) * 16); roman[0] = '\0'; strcpy(roman + strlen(roman), thousands[num / 1000]); strcpy(roman + strlen(roman), hundreds[num % 1000 / 100]); strcpy(roman + strlen(roman), tens[num % 100 / 10]); strcpy(roman + strlen(roman), ones[num % 10]); return roman; } int main() { intToRoman(3); system("pause"); return 0; }
C
#include "history.h" const int HISTORY_AMOUNTS[NUM_HISTORY_COUNTS] = {8, 16, HISTORY_SIZE - 1}; void addHistory( History *history, char currentState ) { int i; unsigned char *irHistory; int historyIndex; irHistory = history->irHistory; currentState = ( currentState ? 1 : 0 ); history->currentBit = ( history->currentBit + 1 ) % 8; if( !history->currentBit ) { history->currentHistory = ( history->currentHistory + 1 ) % HISTORY_SIZE; } for( i = 0; i < NUM_HISTORY_COUNTS; ++i ) { historyIndex = history->currentHistory - HISTORY_AMOUNTS[i]; if( historyIndex < 0 ) { historyIndex += HISTORY_SIZE; } history->historyCount[i] += currentState - ( ( irHistory[historyIndex] >> ( 7 - history->currentBit ) ) & 0x01 ); } irHistory[history->currentHistory] <<= 1; irHistory[history->currentHistory] |= currentState; }
C
/** * uki.c * A micro-wiki for personal stuff. * * @author: Nathan Campos <nathan@innoveworkshop.com> */ #define UKI_DLL_EXPORTS #include "uki.h" #include "fileutils.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #ifdef UNIX #include <stdbool.h> #endif // Private variables. char *wiki_root; bool uki_initialized = false; uki_variable_container configs; uki_variable_container variables; uki_article_container articles; uki_template_container templates; // Private methods. uki_error populate_variable_container(const char *wiki_root, const char *var_fname, uki_variable_container *container); #ifdef WINDOWS /** * DLL main entry point. * * @param hModule Module handler. * @param ul_reason_for_call Reason for calling this DLL. * @param lpReserved Reserved for the future. * @return TRUE if the DLL should load. */ BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } #endif /** * Initializes the wiki. * * @param wiki_path Path to the root of the uki wiki. * @return UKI_OK if the initialization was completed successfully. */ uki_error uki_initialize(const char *wiki_path) { uki_error err; uki_initialized = true; // Copy the wiki root path string. wiki_root = (char*)malloc((strlen(wiki_path) + 1) * sizeof(char)); strcpy(wiki_root, wiki_path); // Populate the variable containers. if ((err = populate_variable_container(wiki_root, UKI_MANIFEST_PATH, &configs)) != UKI_OK) return err; if ((err = populate_variable_container(wiki_root, UKI_VARIABLE_PATH, &variables)) != UKI_OK) return err; // Initialize templating engine and populate the templates container. initialize_templating(&templates, wiki_root); if ((err = populate_templates(&templates)) != UKI_OK) return err; // Initialize and populate the articles container. initialize_articles(&articles, wiki_root); if ((err = populate_articles(&articles)) != UKI_OK) return err; return UKI_OK; } /** * Renders an article from its text contents. * * @param content Content to be rendered. (Reallocated by this function) * @param deepness Article deepness inside the articles folder. * @return UKI_OK if the operation was successful. */ uki_error uki_render_article_from_text(char **content, const int deepness) { return substitute_assets(content, deepness); } /** * Renders a template from its text contents. * * @param content Content to be rendered. (Reallocated by this function) * @param deepness Template deepness inside the templates folder. * @return UKI_OK if the operation was successful. */ uki_error uki_render_template_from_text(char **content, const int deepness) { return substitute_assets(content, deepness); } /** * Renders an article by its index. * * @param rendered Rendered page contents (Allocated by this fuction). * @param index Article index. * @param preview Is this for preview? (Will change the contents of the page) * @return UKI_OK if the operation was successful. */ uki_error uki_render_article(char **rendered, const size_t index, const bool preview) { uki_article_t article; char fpath[UKI_MAX_PATH]; uki_error err; // Get the article. article = uki_article(index); if (article.name == NULL) return UKI_ERROR_INDEX_NOT_FOUND; // Get the file path. if ((err = uki_article_fpath(fpath, article)) != UKI_OK) return err; // Check if there is an article there. if (!file_exists(fpath)) return UKI_ERROR_NOARTICLE; // Slurp file. slurp_file(rendered, fpath); if (rendered == NULL) return UKI_ERROR_PARSING_ARTICLE; // Substitute asset paths if we are in preview mode. if (preview) return uki_render_article_from_text(rendered, article.deepness); return UKI_OK; } /** * Render a wiki page. * * @param rendered Rendered page text (will be allocated by this function). * @param page Relative path to the page (without the extension). * @return UKI_OK if there were no errors. */ uki_error uki_render_page(char **rendered, const char *page) { char article_path[UKI_MAX_PATH]; uki_error err; // Get main template. int idx = find_variable(UKI_VAR_MAIN_TEMPLATE, configs); if (idx < 0) return UKI_ERROR_NOMAINTEMPLATE; // Render template for placing article into. if ((err = render_template(rendered, configs.list[idx].value)) != UKI_OK) return err; // Build article path and render it. pathcat(3, article_path, wiki_root, UKI_ARTICLE_ROOT, page); extcat(article_path, UKI_ARTICLE_EXT); if ((err = render_article_in_template(rendered, article_path)) != UKI_OK) return err; return render_variables(rendered, variables); } /** * Gets the number of available configurations. * * @return Number of available configurations. */ size_t uki_configs_available() { return configs.size; } /** * Gets a uki configuration by its index. * * @param index Configuration index. * @return The variable structure if it was found. NULL otherwise. */ uki_variable_t uki_config(const uint8_t index) { return find_variable_i(index, configs); } /** * Gets the number of available variables. * * @return Number of available variables. */ size_t uki_variables_available() { return variables.size; } /** * Gets a uki variable by its index. * * @param index Variable index. * @return The variable structure if it was found. NULL otherwise. */ uki_variable_t uki_variable(const uint8_t index) { return find_variable_i(index, variables); } /** * Gets the number of available articles. * * @return Number of available articles. */ size_t uki_articles_available() { return articles.size; } /** * Gets a uki article structure by its index. * * @param index Article index. * @param The article structure if it was found. NULL otherwise. */ uki_article_t uki_article(const size_t index) { return find_article_i(index, articles); } /** * Add a new article. * * @param article_path Complete path to the article file. * @return Recently added article. */ uki_article_t uki_add_article(const char *article_path) { return add_article(&articles, article_path); } /** * Gets the number of available templates. * * @return Number of available templates. */ size_t uki_templates_available() { return templates.size; } /** * Gets a uki template structure by its index. * * @param index Template index. * @param The template structure if it was found. NULL otherwise. */ uki_template_t uki_template(const size_t index) { return find_template_i(index, templates); } /** * Add a new template. * * @param template_path Complete path to the template file. * @return Recently added template. */ uki_template_t uki_add_template(const char *template_path) { return add_template(&templates, template_path); } /** * Creates a file path to an article. * * @param fpath Pre-allocated string buffer to store the article file path. * @param article Article structure. * @return UKI_OK if the operation was successful. */ uki_error uki_article_fpath(char *fpath, const uki_article_t article) { // Build article path. pathcat(3, fpath, wiki_root, UKI_ARTICLE_ROOT, article.path); return UKI_OK; } /** * Creates a file path to a template. * * @param fpath Pre-allocated string buffer to store the template file path. * @param template Template structure. * @return UKI_OK if the operation was successful. */ uki_error uki_template_fpath(char *fpath, const uki_template_t template) { // Build template path. pathcat(3, fpath, wiki_root, UKI_TEMPLATE_ROOT, template.path); return UKI_OK; } /** * Gets the path to the articles folder. * * @param fpath Pre-allocated string buffer to store the articles folder path. * @return UKI_OK if the operation was successful. */ uki_error uki_folder_articles(char *fpath) { // Build article path. pathcat(2, fpath, wiki_root, UKI_ARTICLE_ROOT); return UKI_OK; } /** * Gets the path to the templates folder. * * @param fpath Pre-allocated string buffer to store the templates folder path. * @return UKI_OK if the operation was successful. */ uki_error uki_folder_templates(char *fpath) { // Build template path. pathcat(2, fpath, wiki_root, UKI_TEMPLATE_ROOT); return UKI_OK; } /** * Gets a error message beased on a error code from uki. * * @param ecode Error code. * @return Error message. */ const char* uki_error_msg(const uki_error ecode) { switch (ecode) { case UKI_ERROR_NOMANIFEST: return "No manifest file found in the provided path.\n"; case UKI_ERROR_NOVARIABLES: return "No variables file found in the provided path.\n"; case UKI_ERROR_NOARTICLE: return "Article not found.\n"; case UKI_ERROR_NOTEMPLATE: return "Template file not found.\n"; case UKI_ERROR_NOMAINTEMPLATE: return "No 'main_template' variable set in the manifest.\n"; case UKI_ERROR_INDEX_NOT_FOUND: return "Index to template/article not found.\n"; case UKI_ERROR_VARIABLE_NOTFOUND: return "Variable not found.\n"; case UKI_ERROR_BODYVAR_NOTFOUND: return "Body variable not found in the main template.\n"; case UKI_ERROR_PARSING_ARTICLE: return "Error occured while parsing an article.\n"; case UKI_ERROR_PARSING_VARIABLES: return "Error occured while parsing the variables file.\n"; case UKI_ERROR_PARSING_TEMPLATE: return "Error occured while parsing a template file.\n"; case UKI_ERROR_READING_TEMPLATE: return "Error occured while reading a template file.\n"; case UKI_ERROR_DIRLIST_NOTFOUND: return "Couldn't open directory for listing.\n"; case UKI_ERROR_DIRLIST_FILEUNKNOWN: return "Your filesystem doesn't support dirent->d_type. Sorry.\n"; case UKI_ERROR_CONVERSION_AW: return "String conversion from ASCII to Unicode failed\n"; case UKI_ERROR_CONVERSION_WA: return "String conversion from Unicode to ASCII failed\n"; case UKI_ERROR_REGEX_ASSET_IMAGE: return "There was a regex failure while substituting image assets.\n"; case UKI_ERROR: return "General error.\n"; } return "Unknown error.\n"; } /** * Clean up our mess. */ void uki_clean() { if (uki_initialized) { free(wiki_root); free_variables(configs); free_variables(variables); free_articles(articles); free_templates(templates); } } /** * Populates a variable/configuration container. * * @param wiki_root Path to the root of the uki wiki. * @param var_fname Path to the variable/configuration file. * @param container Variable container. * @return UKI_OK if the operation was successful. Respective error * code otherwise. */ uki_error populate_variable_container(const char *wiki_root, const char *var_fname, uki_variable_container *container) { // Get path string length and allocate some memory. size_t path_len = strlen(wiki_root) + strlen(var_fname) + 2; char *var_path = (char*)malloc(path_len * sizeof(char)); // Build the wiki variables file path and check for its existance. pathcat(2, var_path, wiki_root, var_fname); if (!file_exists(var_path)) { free(var_path); return UKI_ERROR_NOVARIABLES; } // Initialize and populate variable container. initialize_variables(container); if (!populate_variables(container, var_path)) { free(var_path); return UKI_ERROR_PARSING_VARIABLES; } free(var_path); return UKI_OK; }
C
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { FILE *f1, *f2; //pointers to two files char buffer[10]; size_t data; //read from file1 the source file f1 = fopen(argv[1], "r"); //test to see if file can be opened or not if(argc <2) { printf("Not enough arguments!"); exit(0); } if(f1 == NULL) { printf("can't open %s file \n", argv[1]); exit(0); } //f2 is the destination file f2 = fopen(argv[2], "w"); printf("\n"); if(f2 == NULL) { printf("can't open %s file \n", argv[2]); exit(0); } //now copy from one file to another //fread takes what we're reading from, the size of how much we're //reading, how many items (size of buffer) and where we're reading from while(0 < (data = fread(buffer,1, 10, f1))) { fwrite(buffer,1, data, f2); // data = fread(f1); } printf("Contents copied to %s", argv[2]); printf("\n"); fclose(f1); fclose(f2); return 0; }
C
#ifndef __LinkedList_C #define __LinkedList_C #include <stdio.h> #include <stdlib.h> #include "linkedList.h" Node *newNode( GraphNode *graphNode ) { Node *newNode = (Node *) malloc( sizeof( Node ) ); newNode->node = graphNode; newNode->next = NULL; newNode->prev = NULL; return newNode; } void append( LinkedList *list, GraphNode *graphNode ) { //insert at the end Node *inNode = newNode( graphNode ); Node *last = list->tail->prev; last->next = inNode; inNode->prev = last; inNode->next = list->tail; list->tail->prev = inNode; } LinkedList *newList() { LinkedList *linkedList = (LinkedList *) malloc( sizeof( LinkedList ) ); linkedList->head = newNode( NULL ); linkedList->tail = newNode( NULL ); linkedList->head->next = linkedList->tail; linkedList->head->prev = NULL; linkedList->tail->prev = linkedList->head; linkedList->tail->next = NULL; return linkedList; } void deleteList( LinkedList *list ) { if ( !list ) return; if ( !list->head || !list->tail ) { free( list ); return; } Node *thisNode = list->head->next; while ( thisNode != list->tail ) { Node *tmp = thisNode->next; free( thisNode ); thisNode = tmp; } free( list->head ); free( list->tail ); list->head = NULL; list->tail = NULL; free( list ); } GraphNode *newGraphNode( int value ) { GraphNode *newNode = (GraphNode *) malloc( sizeof( GraphNode ) ); newNode->value = value; newNode->neighbors = newList(); newNode->marked = 0; return newNode; } GraphNode *find( LinkedList *list, int value ) { Node *found = list->head->next; while ( found->node->value != value ) { found = found->next; } return found->node; } int hasNeighbor( GraphNode *node, int value ) { if ( node->value == value ) return 1; for ( Node *cur = node->neighbors->head->next; cur != node->neighbors->tail; cur = cur->next ) { if ( cur->node->value == value ) return 1; } return 0; } void link( GraphNode *node1, GraphNode *node2 ) { if ( node1 == node2 ) return; if ( !hasNeighbor( node1, node2->value ) && !hasNeighbor( node2, node1->value ) ) { append( node1->neighbors, node2 ); append( node2->neighbors, node1 ); } } void delete( GraphNode *graphNode ) { if ( !graphNode ) return; free( graphNode ); } #endif
C
#include "holberton.h" /* * Function that prints 1 is n is prime * 0 is not prime */ int is_prime_number(int n) { int k; k = n / 2; if (n <= 1) return (0); else return (checkprime(n, k)); } /* * function to check is n given is prime */ int checkprime(int n, int k) { int i = 1; if (k == 1) { i = 1; } else if (n % k == 0) { i = 0; } else { checkprime(n, k - 1); } return (i); }
C
#include "PLL.h" #include "tm4c123gh6pm.h" void DisableInterrupts(void); // Disable interrupts void EnableInterrupts(void); // Enable interrupts void WaitForInterrupt(void); // low power mode void PortA_Init(void); // start sound output void SysInit(void); //initialize SysTick timer void SysLoad(unsigned long period); //Load reload value //############################################################################ unsigned char Index; // 3-bit 16-element sine wave const unsigned char SineWave[16] = {4,5,6,7,7,7,6,5,4,3,2,1,1,1,2,3}; // **************DAC_Init********************* // Initialize 3-bit DAC // Input: none // Output: none void DAC_Init(void){unsigned long volatile delay; SYSCTL_RCGC2_R |= SYSCTL_RCGC2_GPIOB; // activate port B delay = SYSCTL_RCGC2_R; // allow time to finish activating GPIO_PORTB_AMSEL_R &= ~0x07; // no analog GPIO_PORTB_PCTL_R &= ~0x00000FFF; // regular function GPIO_PORTB_DIR_R |= 0x07; // make PB2-0 out GPIO_PORTB_AFSEL_R &= ~0x07; // disable alt funct on PB2-0 GPIO_PORTB_DEN_R |= 0x07; // enable digital I/O on PB2-0 GPIO_PORTB_DR8R_R|=0x07; } // **************DAC_Out********************* // output to DAC // Input: 3-bit data, 0 to 7 // Output: none void DAC_Out(unsigned long data){ GPIO_PORTB_DATA_R = data; } //################################################################################# int main(void){ PLL_Init(); SysInit(); SysLoad(10000); DAC_Init(); // Port B is DAC while(1){ } } void SysLoad(unsigned long period){ NVIC_ST_RELOAD_R = period -1; Index = 0; } void SysInit(void){ NVIC_ST_CTRL_R = 0; NVIC_ST_CURRENT_R = 0; // any write to current clears it NVIC_SYS_PRI3_R = (NVIC_SYS_PRI3_R&0x00FFFFFF)|0x20000000; // priority 1 NVIC_ST_CTRL_R = 0x00000007; // enable with core clock and interrupts } // Interrupt service routine // Executed every 12.5ns*(period) void SysTick_Handler(void){ DAC_Out(SineWave[Index]); Index = (Index+1) & 0x0F; }
C
/* ============================================================================ Name : homework3-2.c Author : Ji Un Song Version : Copyright : Description : ap2.c ============================================================================ */ #include <stdio.h> #include <stdlib.h> int main(void) { printf(" ̸: й : 2019038028 \n\n"); int list[5]; // 5ĭ 迭 int *plist[5]; // 迭 plist[0] = (int*)malloc(sizeof(int)); // plist[0] ּҸ heap printf("list[0] \t =%d\n", list[0]); // list[0] Ÿ ¹(ʱȭ ȵǾ ־ ) printf("address of list \t= %p\n", list); // list[0] ּҸ Ÿ ¹ printf("address of list[0] \t= %p\n", &list[0]); // list[0] ּҸ Ÿ ¹ printf("address of list + 0 \t= %p\n", list + 0); // list[0] Ÿ ¹ printf("address of list + 1 \t= %p\n", list + 1); // list + 1 == list[1] ּҸ Ÿ ¹ printf("address of list + 2 \t= %p\n", list + 2); // list + 2 == list[2] ּҸ Ÿ ¹ printf("address of list + 3 \t= %p\n", list + 3); // list + 3 == list[3] ּҸ Ÿ ¹ printf("address of list + 4 \t= %p\n", list + 4); // list + 4 == list[4] ּҸ Ÿ ¹ printf("address of list[4] \t = %p\n", &list[4]); // list[4] ּҸ Ÿ ¹ free(plist[0]); // Ҵ return 0; // 0 ȯ }
C
/** * COSC 3250 - Project 8 * Test cases for process messages * @authors Danny Hudetz Marty Boehm * Instructor Rubya * TA-BOT:MAILTO daniel.hudetz@marquette.edu martin.boehm@marquette.edu */ #include <xinu.h> /** * testcases - called after initialization completes to test things. */ void receiveMsg(void) { register pcb *currpcb; currpcb = &proctab[currpid[getcpuid()]]; while(1==1){ if(currpcb->msg_var.hasMessage){ kprintf("Message received: %d/r/n", recv()); } } } void receiveMsgNow(void) { register pcb *currpcb; currpcb = &proctab[currpid[getcpuid()]]; while(1==1){ if(currpcb->msg_var.hasMessage){ kprintf("Message received: %d/r/n", recvnow()); } } } void testcases(void) { uchar c; kprintf("===TEST BEGIN===\r\n"); kprintf("0) One SENDNOW()\r\n"); kprintf("1) One sendnow and RECV\r\n"); kprintf("2) sendnow and SEND enqueue test\r\n"); kprintf("3) One sendnow and one RECVNOW\r\n"); // TODO: Test your operating system! c = kgetc(); int result; register pcb *ppcb; register pcb *currpcb; int testpid; int currid; switch (c) { case '0': testpid = create((void *)receiveMsg, INITSTK, PRIORITY_LOW, "RECV", 0); ppcb = &proctab[testpid]; ppcb->core_affinity = 0; result = sendnow(testpid, 0x5); kprintf("Result: %d", result); if((TRUE == ppcb->msg_var.hasMessage) && (0x5 == ppcb->msg_var.msgin)) kprintf("Message correctly sent.\r\n"); else kprintf("Recv process hasMessage == %d, msgin == %d\r\n", ppcb->msg_var.hasMessage, ppcb->msg_var.msgin); kill(testpid); break; case '1': testpid = create((void *)receiveMsg, INITSTK, PRIORITY_LOW, "RECV", 0); ppcb = &proctab[testpid]; ppcb->core_affinity = 0; currid = currpid[getcpuid()]; currpcb = &proctab[currid]; result = sendnow(testpid, 0x5); kprintf("Result: %d\n\r", result); ready(testpid, RESCHED_NO, 0); if((TRUE == ppcb->msg_var.hasMessage) && (0x5 == ppcb->msg_var.msgin)) kprintf("Messages correctly sent.\r\n"); else kprintf("Recv process hasMessage == %d, msgin == %d\r\n", ppcb->msg_var.hasMessage, ppcb->msg_var.msgin); kill(testpid); break; case '2': testpid = create((void *)receiveMsg, INITSTK, PRIORITY_LOW, "RECV", 0); ppcb = &proctab[testpid]; ppcb->core_affinity = 0; currid = currpid[getcpuid()]; currpcb = &proctab[currid]; result = sendnow(testpid, 0x5); kprintf("Result: %d\n\r", result); result = send(testpid, 0x6); kprintf("Result: %d\n\r", result); if((TRUE == ppcb->msg_var.hasMessage) && (0x5 == ppcb->msg_var.msgin) && (currid == ppcb->msg_var.msgqueue) && (currpcb->msg_var.msgout == 0x6)) kprintf("Messages correctly sent.\r\n"); else kprintf("Recv process hasMessage == %d, msgin == %d\r\n", ppcb->msg_var.hasMessage, ppcb->msg_var.msgin); kill(testpid); break; case '3': testpid = create((void *)receiveMsgNow, INITSTK, PRIORITY_LOW, "RECV", 0); ppcb = &proctab[testpid]; ppcb->core_affinity = 0; currid = currpid[getcpuid()]; currpcb = &proctab[currid]; result = sendnow(testpid, 0x5); kprintf("Result: %d\n\r", result); if((TRUE == ppcb->msg_var.hasMessage) && (0x5 == ppcb->msg_var.msgin)) kprintf("Messages correctly sent.\r\n"); else kprintf("Recv process hasMessage == %d, msgin == %d\r\n", ppcb->msg_var.hasMessage, ppcb->msg_var.msgin); kill(testpid); break; default: break; } kprintf("\r\n===TEST END===\r\n"); return; }
C
#include <stdio.h> #include <time.h> #include "gconio.h" const int fogoLargura = 18; const int fogoAltura = 18; void rederizaFogo(int fogotab[]){ int pont = 0; for(int y = 0; y < fogoAltura; y++){ for(int x = 0; x < fogoLargura; x++){ textbackground(fogotab[pont] % 7); printf("%.2d", fogotab[pont]); pont++; textbackground(0); printf(" "); } puts(""); } } void fonteFogo(int fogotab[]){ for(int i = 0; i < fogoLargura; i++){ int ultimoPixel = ((fogoAltura * fogoLargura) - fogoLargura) + i; fogotab[ultimoPixel] = 36; } } void propagarFogo(int fogotab[]){ for(int x = 0; x < fogoAltura; x++){ for(int y = 0; y < fogoLargura; y++){ int point = x + (fogoLargura * y); int pixelBaixo = point + fogoLargura ; int declinio = (rand() % 3) + 1; if(y == fogoAltura - 1){} else if(fogotab[pixelBaixo] == 0){} else{ int oudFogo = fogotab[point]; fogotab[point] = fogotab[pixelBaixo - 1] - declinio; if((fogotab[point] - declinio) < 0){ fogotab[point] = oudFogo; } } } } } int main(){ srand(time(NULL)); int fogoTab[fogoAltura * fogoLargura]; int numeroDePixels = fogoAltura * fogoLargura; for(int i = 0; i < numeroDePixels; i++){ fogoTab[i] = 0; } fonteFogo(fogoTab); for(int i = 0;i < 500; i++){ clrscr(); propagarFogo(fogoTab); rederizaFogo(fogoTab); sleep(1); } }
C
#include <stdio.h> #include <netdb.h> #include <sys/socket.h> #include <sys/utsname.h> main() { //ҪЧ,Ա/etc/hostsû sethostent(1); struct hostent *ent; while(1) { ent = gethostent(); if(!ent) break; printf(":%s:%hhu.%hhu.%hhu.%hhu\n", //printf(":%s:%u.%u.%u.%u\n", ent->h_name, ent->h_addr[0], ent->h_addr[1], ent->h_addr[2], ent->h_addr[3]); } endhostent(); ///////////////////////////////// struct utsname name; uname(&name); printf("%s\n",name.sysname); printf("%s\n",name.nodename); printf("%s\n",name.release); printf("%s\n",name.version); printf("%s\n",name.machine); //printf("%s\n",name.domainname); ////////////////////////////// struct hostent *ipent; ipent=gethostbyname("www.baidu.com"); printf("%s:%hhu.%hhu.%hhu.%hhu\n", ipent->h_name, ipent->h_addr[0], ipent->h_addr[1], ipent->h_addr[2], ipent->h_addr[3]); }
C
#include <stdio.h> #include <sys/types.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <signal.h> #define MAX_INPUT_SIZE 1024 #define MAX_TOKEN_SIZE 64 #define MAX_NUM_TOKENS 64 #define RD_WR 0666 char* server_ip; char* server_port; int server_set; volatile sig_atomic_t keep_going = 1; int curr_back=-1; int no_bgp=0; char **tokenize(char *line) { server_ip="127.0.0.1"; server_port="5000"; server_set=1; char **tokens = (char **)malloc(MAX_NUM_TOKENS * sizeof(char *)); char *token = (char *)malloc(MAX_TOKEN_SIZE * sizeof(char)); int i, tokenIndex = 0, tokenNo = 0; for(i =0; i < strlen(line); i++){ char readChar = line[i]; if (readChar == ' ' || readChar == '\n' || readChar == '\t'){ token[tokenIndex] = '\0'; if (tokenIndex != 0){ tokens[tokenNo] = (char*)malloc(MAX_TOKEN_SIZE*sizeof(char)); strcpy(tokens[tokenNo++], token); tokenIndex = 0; } } else { token[tokenIndex++] = readChar; } } free(token); tokens[tokenNo] = NULL ; return tokens; } void handler(int signo) { keep_going = 0; return; } void main(void) { char line[MAX_INPUT_SIZE]; char **tokens; int i; server_set=0; signal (SIGINT, handler); /* must call waitpid() */ int arg_set=0; int no_tokens=0; while (1) { if(arg_set==0) { printf("Hello>"); bzero(line, MAX_INPUT_SIZE); gets(line); //printf("Got command %s\n", line); line[strlen(line)] = '\n'; //terminate with new line tokens = tokenize(line); //do whatever you want with the commands, here we just print them for(i=0;tokens[i]!=NULL;i++){ //printf("found token %s\n", tokens[i]); } no_tokens=i; if(i==0) { continue; } } // cd if(strcmp(tokens[0],"cd")==0) { if(no_tokens!=2) { printf("Format cd <directory> \n"); } else { int err = chdir(tokens[1]); if(err==-1) { printf("cd: Error in changing directory\n"); } } } //server else if(strcmp(tokens[0],"server")==0) { if(no_tokens!=3) { printf("error:Expected input : server server_IP server_port \n"); } else { free(server_ip); free(server_port); server_ip=malloc(strlen(tokens[1])); server_port=malloc(strlen(tokens[2])); strcpy(server_ip, tokens[1]); strcpy(server_port, tokens[2]); server_set=1; } } // getfl filename else if(strcmp(tokens[0],"getfl")==0) { //printf("yyo\n"); if(no_tokens==2) { if(server_set!=1) { printf("No server details given\n"); } else { int pid=fork(); if(pid<0) printf("%s\n","Error"); if(pid==0) { execl("./get-one-file-sig", "./get-one-file-sig", tokens[1], server_ip, server_port, "display", NULL); exit(0); } waitpid(pid,0,NULL); } } else if((strcmp(tokens[2],">")==0 && no_tokens==4)){ if(server_set!=1) { printf("No server details given\n"); } else { int pid=fork(); if(pid<0) printf("%s\n","Error"); if(pid==0) { int fd; fd = creat( tokens[3], RD_WR ); dup2(fd,1); execl("./get-one-file-sig", "./get-one-file-sig", tokens[1], server_ip, server_port, "display", NULL); exit(0); } waitpid(pid,0,NULL); } } else if(strcmp(tokens[2],"|")!=0 ) { printf("error:Expected input : getfl filename or getfl filename > output gadda \n"); } else { if(server_set!=1) { printf("No server details given\n"); } else { int fd[2]; if(pipe(fd)<0)printf("hugg diya\n"); int pid1=fork(); if(pid1<0) printf("%s\n","Error"); if(pid1==0) { dup2(fd[1],1); close(fd[0]); close(fd[1]); execl("./get-one-file-sig", "./get-one-file-sig", tokens[1], server_ip, server_port, "display", NULL); exit(0); } int pid2=fork(); if(pid2<0) printf("%s\n","Error"); if(pid2==0) { dup2(fd[0],0); close(fd[0]); close(fd[1]); arg_set=1; int i=0; char **temps = (char **)malloc(MAX_NUM_TOKENS * sizeof(char *)); for(i=0;i<no_tokens-3;i++) { temps[i]=(char*)malloc(MAX_TOKEN_SIZE*sizeof(char)); strcpy(temps[i],tokens[i+3]); } for(i=0;i<no_tokens;i++) { free(tokens[i]); } free(tokens); no_tokens=no_tokens-3; tokens=temps; tokens[no_tokens]=NULL; //printf("%s %s\n", tokens[0], tokens[1]); continue; } close(fd[0]); close(fd[1]); waitpid(pid2,0,NULL); waitpid(pid1,0,NULL); } } } //getsq file1 file2 else if(strcmp(tokens[0],"getsq")==0) { if(no_tokens<2) { printf("error:Expected input : getsq file1 file2 ... \n"); } else { if(server_set!=1) { printf("No server details given\n"); } else { int j=0; for(j=0; (j<no_tokens-1) && keep_going;j++) { int pid=fork(); if(pid<0) printf("%s\n","Error"); if(pid==0) { execl("./get-one-file-sig", "./get-one-file-sig", tokens[j+1], server_ip, server_port, "nodisplay", NULL); exit(0); } waitpid(pid,0,NULL); } keep_going=1; } } } //getpl file1 file2 else if(strcmp(tokens[0],"getpl")==0) { if(no_tokens<2) { printf("error:Expected input : getpl file1 file2 ... \n"); } else { if(server_set!=1) { printf("No server details given\n"); } else { int j=0; int * pids = malloc(sizeof(int)*(no_tokens-1)); for(j=0;j<no_tokens-1;j++) { int pid=fork(); pids[j]=pid; if(pid<0) printf("%s\n","Error"); if(pid==0) { execl("./get-one-file-sig", "./get-one-file-sig", tokens[j+1], server_ip, server_port, "nodisplay", NULL); exit(0); } } for(j=0;j<no_tokens-1;j++) { waitpid(pids[j],0,NULL); } } } } //getbg filename else if(strcmp(tokens[0],"getbg")==0) { if(no_tokens!=2) { printf("error:Expected input : getbg filename \n"); } else { if(server_set!=1) { printf("No server details given\n"); } else { int pid=fork(); if(pid<0) printf("%s\n","Error"); if(pid==0) { setpgrp(); //maintan a list of bgproc execl("./get-one-file-sig", "./get-one-file-sig", tokens[1], server_ip, server_port, "nodisplay", NULL); exit(0); } printf("%d %d",curr_back,pid); if(curr_back<0) { curr_back=pid; if(setpgid(pid,0)<0) { printf("Error in background process group"); } } else if(setpgid(pid,curr_back)<0) { curr_back=pid; printf("yoyo\n"); if(setpgid(pid,0)<0) { printf("Error in back 2"); } } printf("pgid - %d",getpgid(pid)); no_bgp++; } } } //exit else if(strcmp(tokens[0],"exit")==0) { kill(-curr_back,SIGTERM); int i=0; printf("no_bgp = %d\n",no_bgp); for(i=0;i<no_bgp;i++) { waitid(-curr_back,0,0); } exit(0); } //others else { // printf("Yoyo\n"); char temp[80]; sprintf(temp,"/bin/%s",tokens[0]); if(access(temp, F_OK)==-1) { if(access(tokens[0], F_OK)==-1) { printf("Command does not exist \n"); } else { int pid=fork(); if(pid<0) printf("%s\n","Error"); if(pid==0) { execv(tokens[0],tokens); exit(0); } waitpid(pid,0,NULL); } } else { int pid=fork(); if(pid<0) printf("%s\n","Error"); if(pid==0) { execv(temp,tokens); exit(0); } waitpid(pid,0,NULL); } } //Reap off background process int a; int status; while(a=waitpid(-1,&status,WNOHANG)>0) { no_bgp--; printf("Background process reaped off with status %d \n",status); } // Freeing the allocated memory for(i=0;tokens[i]!=NULL;i++){ free(tokens[i]); } free(tokens); if(arg_set==1) exit(0); } }
C
// ============================================================================= // // Polonator G.007 Image Processing Software // // Church Lab, Harvard Medical School // Written by Greg Porreca // // Release 1.0 -- 02-12-2008 // // This software may be modified and re-distributed, but this header must appear // at the top of the file. // // ============================================================================= // #include <stdio.h> #include <stdlib.h> #include "Polonator_logger.h" #include "ProcessorParams.h" void ProcessImage_extract(short unsigned int *image, int offset_xcols, int offset_yrows, short unsigned int img_error, FILE *full_pixel_list, int curr_imagenum, int curr_arraynum, int curr_fcnum, short unsigned int *num_beads, short unsigned int *bead_val, unsigned long long int *beadsum) { short unsigned int curr_val; int curr_val2; int f_imagenum, f_arraynum, f_fcnum, f_numobjs; // current vals read from file short int curr_xcol, curr_yrow; int i; char log_string[255]; if(img_error == 1) { sprintf(log_string, "WARNING:\tProcessImage_extract: current image (%d %d %d) has error flag set", curr_imagenum, curr_arraynum, curr_fcnum); p_log(log_string); } // SEEK TO CORRECT PLACE IN full_pixel_list FILE // I.E. THE FIRST BEAD LOCATION FOR THIS // (imagenum, arraynum, fcnum) /* fprintf(stdout, "ProcessImage_extract: seeking to header for correct frame %d %d %d...\n", curr_fcnum, curr_arraynum, curr_imagenum);*/ #ifdef DEBUG1 p_log((char*)"STATUS:\tProcessImage_extract: seeking to correct place in pixel list file"); #endif if(fread(&curr_val2, 4, 1, full_pixel_list) < 1) { p_log_errorno((char*)"ERROR:\tProcessImage_extract read pixel list file failed(1)"); exit(1); } while(curr_val2 != -1) { sprintf(log_string, "curr_val tested != -1; %d", curr_val2); p_log(log_string); if(fread(&curr_val, 4, 1, full_pixel_list) < 1) { p_log_errorno((char*)"ERROR:\tProcessImage_extract: read pixel list file failed(2)"); exit(1); } } #ifdef DEBUG1 p_log((char*)"STATUS:\tProcessImage_extract: read values from pixel list file"); #endif // READ IMAGENUM, ARRAYNUM, FCNUM AND COMPARE TO EXPECTED // REPORT AN ERROR BUT DO NOT ATTEMPT TO CORRECT if(fread(&f_fcnum, 4, 1, full_pixel_list) < 1) { p_log_errorno((char*)"ERROR:\tProcessImage_extract: read pixel list file failed(3)"); exit(1); } if(fread(&f_arraynum, 4, 1, full_pixel_list) < 1) { p_log_errorno((char*)"ERROR:\tProcessImage_extract: read pixel list file failed(4)"); exit(1); } if(fread(&f_imagenum, 4, 1, full_pixel_list) < 1) { p_log_errorno((char*)"ERROR:\tProcessImage_extract: read pixel list file failed(5)"); exit(1); } if(fread(&f_numobjs, 4, 1, full_pixel_list) < 1) { p_log_errorno((char*)"ERROR:\tProcessImage_extract: read pixel list file failed(6)"); exit(1); } if( (f_imagenum != curr_imagenum) || (f_arraynum != curr_arraynum) || (f_fcnum != curr_fcnum)) { sprintf(log_string, "ERROR in ProcessImage_extract; expected image %d %d %d does not match pixel list file: %d %d %d", curr_fcnum, curr_arraynum, curr_imagenum, f_fcnum, f_arraynum, f_imagenum); p_log(log_string); } // THE FLUORESCENCE IMAGE HERE IS MISSING; ADVANCE PIXEL LIST FILE POINTER // THIS WONT WORK SINCE POSITIONS ARE 2 BYTES AND FLAG IS 4 BYTES; LAST FLAG // MUST BE 2 BYTES if(img_error) { #ifdef DEBUG1 p_log((char*)"WARNING:\tProcessImage_extract: fluorescence image is missing; advancing pixel list pointer"); #endif curr_val = 1; while(curr_val!=0) { if(fread(&curr_val, 2, 1, full_pixel_list) < 1) { p_log_errorno((char*)"ERROR:\tProcessImage_extract: read pixel list file failed(7)"); exit(1); } } } // CURRENT IMAGE IS VALID; EXTRACT PIXEL VALS else { #ifdef DEBUG1 sprintf(log_string, "STATUS:\tProcessImage_extract: extracting %d pixel values", f_numobjs); p_log(log_string); #endif *beadsum = 0; for(i=0; i < f_numobjs; i++) { if(fread(&curr_xcol, 2, 1, full_pixel_list) < 1) { p_log_errorno((char*)"ERROR:\tProcessImage_extract: read pixel list file failed(8)"); exit(1); } if(fread(&curr_yrow, 2, 1, full_pixel_list) < 1) { p_log_errorno((char*)"ERROR:\tProcessImage_extract: read pixel list file failed(9)"); exit(1); } // DETERMINE OFFSET X AND Y VALS AND VERIFY THEY ARE WITHIN RANGE // IF NOT, SET PIXEL VALUES TO 0 AS A FLAG (NO BEAD CAN HAVE VALUE OF 0) if( ((curr_xcol + offset_xcols) < 0 ) || ((curr_yrow + offset_yrows) < 0) || ((curr_xcol + offset_xcols) >= NUM_XCOLS) || ((curr_yrow + offset_yrows) >= NUM_YROWS)) { *(bead_val + i) = 0; } else { // ASSIGN CURRENT VAL IN BEAD LIST; IF EXTRACTED VALUE == 0, SET IT // TO 1 SINCE 0 IS NOT IN THE VALID PIXEL DATA RANGE OF THE BASECALLER *(bead_val + i) = *( image + (NUM_XCOLS * (curr_yrow + offset_yrows)) + (curr_xcol + offset_xcols) ); *beadsum += *(bead_val+i); if( *(bead_val + i) == 0 ) { *(bead_val + i) = 1; *(beadsum)++; } } } // end for } // end else *num_beads = f_numobjs; #ifdef DEBUG1 p_log((char*)"STATUS:\tProcessImage_extract: advancing pixel list file pointer"); #endif if(fread(&curr_val, 2, 1, full_pixel_list) < 1) { p_log_errorno((char*)"ERROR:\tProcessImage_extract: read pixel list file failed(10)"); exit(1); } while(curr_val != 0) { sprintf(log_string, "ERROR: curr_val tested != 0; %d", curr_val); p_log(log_string); if( fread(&curr_val, 2, 1, full_pixel_list ) < 1) { p_log_errorno((char*)"ERROR:\tProcessImage_extract: read pixel list file failed(11)"); exit(1); } } }