language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include "includes.h" #include "BswDrv_Debug.h" #include "BswDrv_Usart.h" static __IO uint8_t gPrintBuff[164]; //ij static volatile uint16_t gWrite = 0; int fputc(int ch, FILE *f) #if 0 { usart_data_transmit(USARTX[USARTX_INDEX], (uint8_t)ch); while(RESET == usart_flag_get(USARTX[USARTX_INDEX], USART_FLAG_TBE)); return ch; } #else { if (gWrite < sizeof(gPrintBuff)) { gPrintBuff[gWrite++] = ch; if ('\n' == ch) { BswDrv_UsartSend(DBG_UARTX_INDEX, (void *)gPrintBuff, gWrite); gWrite = 0; } } else { BswDrv_UsartSend(DBG_UARTX_INDEX, (void *)gPrintBuff, sizeof(gPrintBuff)); gWrite = 0; } return ch; } #endif void PrintfData(void *pfunc, uint8_t *pdata, int len) { uint32_t i; printf("call by %s,len=%d,pdata:",(char*)pfunc,len); for(i = 0; i < len; i++) { printf("%02x", pdata[i]); } printf("\n"); }
C
/* ** EPITECH PROJECT, 2020 ** rpg ** File description: ** str to array */ #include "rpg.h" int size_malloc_y(char *str, char sep) { int size_malloc = 0; for (int i = 0; str[i]; i++) { if (str[i] == sep) size_malloc += 1; } return (size_malloc); } char **malloc_array(char *str, char sep) { char **array = malloc(sizeof(char *) * (size_malloc_y(str, sep) + 2)); int j = 0; int y = 0; for (int i = 0; i != my_strlen(str) + 1; i++) { if (str[i] == sep || str[i] == '\0') { array[y] = malloc(sizeof(char) * (j + 1)); j = 0; y += 1; continue; } j += 1; } return (array); } char **str_to_array(char *str, char sep) { char **array = malloc_array(str, sep); int j = 0; int index = 0; for (int i = 0; i != my_strlen(str) + 1; i++) { if (str[i] == ' ' || str[i] == '[' || str[i] == ']') continue; if (str[i] == sep || str[i] == '\0') { array[index][j] = '\0'; index += 1; j = 0; continue; } array[index][j] = str[i]; j += 1; } array[index] = NULL; return (array); }
C
#include <stdio.h> #include <malloc.h> void snt(int n) { long i,kt,nt,s; nt=0; for (s=2;s<=n;s++) { kt=0; for (i=2;i<s;i++) { if (s%i==0) kt=kt+1; } if (kt==0) // { // printf("%d\t",s); nt=nt+1; // } } printf("\nCo %d so nguyen to!",nt); } void main() { long n; printf("Nhap vao N: "); scanf("%d",&n); n=(int*)malloc(n* sizeof(int)); snt(n); free(n); }
C
#ifndef _HELP_H_INCLUDED_ #define _HELP_H_INCLUDED_ char* help_str = "\n" "Usage: lolcat [OPTION]... [FILE]...\n" "\n" "Concatenate FILE(s), or standard input, to standard output.\n" "With no FILE, or when FILE is -, read standard input.\n" "\n" " -F Rainbow frequency (default: 0.1)\n" " -S Rainbow seed, 0 = random (default: 0)\n" " -i Invert fg and bg\n" " -q Continue even if a file couldn\'t be read\n" " -f Force color even when stdout is not a tty and\n" " force usage of high frequency\n" " -h Show this help\n" "\n" "Examples:\n" " lolcat f - g Output f's contents, then stdin, then g's contents.\n" " lolcat Copy standard input to standard output.\n" " fortune | lolcat Display a rainbow cookie.\n" "\n" "Report bugs to https://github.com/IchMageBaume/clolcat/issues>\n" "\n"; #endif
C
/* ************************************************************************** */ /* LE - / */ /* / */ /* check_place_letter.c .:: .:/ . .:: */ /* +:+:+ +: +: +:+:+ */ /* By: jfeve <[email protected]> +:+ +: +: +:+ */ /* #+# #+ #+ #+# */ /* Created: 2017/11/29 17:53:14 by jfeve #+# ## ## #+# */ /* Updated: 2017/11/29 17:53:14 by jfeve ### #+. /#+ ###.fr */ /* / */ /* / */ /* ************************************************************************** */ #include "fillit.h" t_check *check_tetro_init(void) { t_check *check; if (!(check = malloc(sizeof(t_check)))) return (NULL); check->l = 1; check->nb_dpl = 1; return (check); } int check_tetro(char *str, int memo, int diez) { t_check *check; if (!(check = check_tetro_init())) return (0); while (diez != 0 && check->nb_dpl != 0) { check->nb_dpl = 0; check->k = memo - 1; while (str[++check->k] != '\n') if (str[check->k] == '#' && diez--) check->nb_dpl++; check->k = check->k - (check->k - memo) + 5 - 1; while (check->nb_dpl != 0 && diez != 0) { if (str[++check->k] == '#') { while (str[check->k - 1] == '#' && check->k--) check->l++; memo = check->k; break ; } check->nb_dpl--; } } return (diez > 0 ? 0 : check->l); } int check_back_diez_point(char *str) { int i; int diez; int memo; i = -1; diez = 0; memo = -1; if (ft_strstr(str, "#.#") || ft_strstr(str, "#..#")) return (0); if (str[4] != '\n' || str[9] != '\n' || str[14] != '\n' || str[19] != '\n' || str[20] != '\0') return (0); while (str[++i]) { if (memo == -1 && str[i] == '#') memo = i; if ((str[i] != '.') && (str[i] != '#') && (str[i] != '\n')) return (0); if (str[i] == '#') diez++; } if (diez != 4) return (0); i = check_tetro(str, memo, diez); return (i); } t_check *check_init(int nb_tetro) { t_check *check; if (!(check = malloc(sizeof(t_check)))) return (NULL); if (!(check->buf = malloc(sizeof(char *) * (nb_tetro + 1)))) return (NULL); check->i = 0; check->mllc = nb_tetro; check->letter = 65; check->buf[nb_tetro] = NULL; while (check->mllc >= 0) { if (!(check->buf[check->mllc] = malloc(sizeof(char) * 21))) return (NULL); check->buf[check->mllc][20] = '\n'; check->mllc--; } return (check); } char **check_place_letter(int fd, int nb_tetro) { t_check *check; if (!(check = check_init(nb_tetro))) return (NULL); while (check->i != nb_tetro) { check->j = 0; check->len = read(fd, check->buf[check->i], 20); check->buf[check->i][check->len] = '\0'; if ((check->len = check_back_diez_point(check->buf[check->i])) == 0) return (0); if (nb_tetro > 1) { read(fd, &check->c, 1); if (check->c != '\n') return (0); } set_up_left(check->buf[check->i]); while (check->buf[check->i][check->j]) check->j++; check->i++; check->letter++; } return (check->buf); }
C
#include "GameEngine.h" #include "Nokia5110.h" #include "Sprites.h" #include "ADC.h" #include "Sound.h" #include "SwitchLED.h" #include "Random.h" #define MAX_CACTUS 2 #define MAX_VULTURE 1 #define WIN_SCORE 100 unsigned long FrameCount=0; //to anmate enemies while they move unsigned long Distance; // units 0.001 cm unsigned long ADCdata; // 12-bit 0 to 4095 sample unsigned long Score; //game score unsigned long Time; unsigned char CactusDelay; //used to create a delay between spawning of cacti unsigned char VultureDelay; //used to create a delay between spawning of vultures struct GameObject { unsigned int x; // x coordinate unsigned int y; // y coordinate unsigned char active; // 0= not on screen, greater than 0 = on screen }; typedef struct GameObject GType; struct PlayerSprite { GType GObj; const unsigned char *image[2]; // a single pointer to image //no animation used int yspeed; int inAir; //is true if currently jumping, else is 0 unsigned char explode; //explode if > 0 }; typedef struct PlayerSprite PType; struct CactusSprite { GType GObj; const unsigned char *image; // two pointers to images }; typedef struct CactusSprite CType; struct VultureSprite { GType GObj; const unsigned char *image[2]; // a single pointer to image unsigned long xspeed; }; typedef struct VultureSprite VType; PType Player; CType Cacti[MAX_CACTUS]; VType Vultures[MAX_VULTURE]; // Convert a 12-bit binary ADC sample into a 32-bit unsigned // fixed-point distance (resolution 0.001 cm). Calibration // data is gathered using known distances and reading the // ADC value measured on PE1. // Input: sample 12-bit ADC sample // Output: 32-bit distance (resolution 0.001cm) unsigned long ConvertToDistance(unsigned long sample){ // A is slope and B is intercept of calibration graph //For 3 cm long potentiometer with 10 kohm resistance: return ((750*sample) >> 10) + (429 >> 10); //A was found to be 0.7326, right shift by 10 is division by 1024, 750/1024 is approximately 0.7326 //B was found to be 0.4188, right shift by 10 is division by 1024, 429/1024 is approximately 0.4188 //For 3cm long 10 kohm potentiometer, method returns a number betweem 0 and 3000 } // Return a random number, the upper limit is defined in the parameter // This generates a random value for VultureDelay and CactusDelay // Input: upper limit // Output: random number unsigned long RandomDelayGenerator(unsigned long limit){ return ((Random()>>22)%limit); } // Return a random number, the upper limit is defined in the parameter // This generates a height and speed for Vulture // Input: upper limit // Output: random number unsigned long RandomGenerator(unsigned long limit){ return (Random()%limit); } void Game_Init(void){ unsigned char i; Score = 0; Time = 0; Player.GObj.x = 32; Player.GObj.y = 47; Player.image[0] = PlayerDino0; Player.image[1] = PlayerDino1; Player.inAir = 0; Player.yspeed = 0; Player.GObj.active = 1; Player.explode = 0; Player.inAir = 0; VultureDelay = RandomDelayGenerator(80); for(i = 0; i < MAX_VULTURE; i++) { Vultures[i].image[0] = Vulture0; Vultures[i].image[1] = Vulture1; Vultures[i].GObj.active = 0; } CactusDelay = RandomDelayGenerator(60); for(i = 0; i < MAX_CACTUS; i++) { if(i%2 == 0) Cacti[i].image = Cactus0; else Cacti[i].image = Cactus1; Cacti[i].GObj.active = 0; } } // unused utility functions for removing dead objects, // A linked list would be better for large array, but for small sizes this is fine void remove_element_cactus(CType *array, int index, int array_length) { int i; for(i = index; i < array_length - 1; i++) array[i] = array[i + 1]; } void remove_element_vulture(VType *array, int index, int array_length) { int i; for(i = index; i < array_length - 1; i++) array[i] = array[i + 1]; } // checks if player has collided with obstical // Input: none // Output: none void CheckCollision(void){ unsigned char j; if(Player.GObj.active){ for(j = 0; j < MAX_CACTUS; j++){ if((!(((Cacti[j].GObj.x + CACTUSW) < Player.GObj.x) || (Cacti[j].GObj.x > (Player.GObj.x + PLAYERW))) && !((Cacti[j].GObj.y < (Player.GObj.y - PLAYERH)) || ((Cacti[j].GObj.y - CACTUSH) > Player.GObj.y))) && (Cacti[j].GObj.active > 0)){ Player.GObj.active = 0; Player.explode = 1; Failure_LedOn(1000); // 1000 Timer2A periods approximately equal 0.9s Sound_Explosion(); break; } } for(j = 0; j < MAX_VULTURE; j++){ if((!(((Vultures[j].GObj.x+VULTUREW) < Player.GObj.x) || (Vultures[j].GObj.x > (Player.GObj.x + PLAYERW))) && !((Vultures[j].GObj.y < (Player.GObj.y - PLAYERH)) || ((Vultures[j].GObj.y - VULTUREH) > Player.GObj.y))) && (Vultures[j].GObj.active > 0)){ Player.GObj.active = 0; Player.explode = 1; Failure_LedOn(1000); // 1000 Timer2A periods approximately equal 0.9s Sound_Explosion(); break; } } } } // causes player to jump // Input: none // Output: none void Jump(void){ if(Player.inAir == 0){ Player.inAir = 1; Player.yspeed = 6; } } // Spawns a cactus on the right side of screen // Input: none // Output: none void SpawnCactus(void) { int x; if(CactusDelay){ CactusDelay--; return; } CactusDelay = RandomDelayGenerator(60); for(x = 0; x < MAX_CACTUS; x++) { if(!Cacti[x].GObj.active) { Cacti[x].GObj.x = 84-CACTUSW; Cacti[x].GObj.y = 47; Cacti[x].GObj.active = 1; return; } } return; } // Spawns a vulture at random height and speed // Input: none // Output: none void SpawnVulture(void) { int x; if(VultureDelay){ VultureDelay--; return; } VultureDelay = RandomDelayGenerator(80); for(x = 0; x < MAX_VULTURE; x++) { if(!Vultures[x].GObj.active) { Vultures[x].GObj.x = 84-VULTUREW; Vultures[x].GObj.y = 47 - RandomGenerator(15); Vultures[x].xspeed = 1 + RandomGenerator(5); Vultures[x].GObj.active = 1; return; } } return; } //Move player horizontally across the screen //The x co-ordinate of the bottom left corner of the player can move from 0 to 64 on the x axis as the player is 18 pixels wide and the screen is 84 pixels //The ConvertToDistance method in GameEngine.c returns a distance between 0 and 3 cm in units of 0.001 cm (i.e. a number between 0 and 3000 //This distance was matched with pixel location on x axis, for the bottom left corner of player, using raw data from the simulation debugging //The relationship was found to be BottomLeftX = Distance*0.0229 - 1.8 via a linear fit to data //0.0229 was approximated as 22/1024 to get a pixel location accurate to 1 pixel void PlayerMove(void){ Player.GObj.x = (ConvertToDistance(ADC0_In())*22) >> 10; Player.GObj.y -= Player.yspeed; if(Player.inAir > 0) { Player.yspeed -= 1; if(Player.GObj.y >= 47) { Player.inAir = 0; Player.GObj.y = 47; Player.yspeed = 0; } } } //Move all cacti 2 pixels to the left //if cactus reaches left edge of screen then it is deactivated void CactusMove(void){ unsigned char i; for(i=0;i<MAX_CACTUS;i++){ if(Cacti[i].GObj.x > 0){ Cacti[i].GObj.x -= 2; }else{ Cacti[i].GObj.active = 0; } } } //Move all vultures by their speed to the left //if vultures reaches left edge of screen then it is deactivated void VultureMove(void){ unsigned char i; for(i=0;i<MAX_VULTURE;i++){ if(Vultures[i].GObj.x > 0){ Vultures[i].GObj.x -= Vultures[i].xspeed; }else{ Vultures[i].GObj.active = 0; } } } void Move_ActiveObjects(void){ PlayerMove(); CactusMove(); VultureMove(); } void DrawPlayer(void){ if(Player.GObj.active){ Nokia5110_PrintBMP(Player.GObj.x, Player.GObj.y, Player.image[FrameCount], 0); } else if(Player.explode){ Player.explode = 0; Nokia5110_PrintBMP(Player.GObj.x, Player.GObj.y, BigExplosion0, 0); } } void DrawCacti(void){unsigned char i; for(i=0;i<MAX_CACTUS;i++){ if(Cacti[i].GObj.active > 0){ Nokia5110_PrintBMP(Cacti[i].GObj.x, Cacti[i].GObj.y, Cacti[i].image, 0); } } } void DrawVultures(void){unsigned char i; for(i=0;i<MAX_VULTURE;i++){ if(Vultures[i].GObj.active > 0){ Nokia5110_PrintBMP(Vultures[i].GObj.x, Vultures[i].GObj.y, Vultures[i].image[FrameCount], 0); } } } void UpdateScore(void) { Time++; FrameCount = (FrameCount+1)&0x01; if(Time%50) Score++; } void Draw_GameFrame(void){ Nokia5110_ClearBuffer(); SpawnCactus(); SpawnVulture(); DrawPlayer(); DrawCacti(); DrawVultures(); UpdateScore(); Nokia5110_DisplayBuffer(); // draw buffer } //returns 1 if game over; 0 otherwise unsigned char Check_GameOver(void){ if((Score == WIN_SCORE) || (Player.GObj.active == 0)) return 1; return 0; } // Outputes the game over screen void State_GameOver(void){ Nokia5110_Clear(); Nokia5110_SetCursor(1, 0); Nokia5110_OutString("GAME OVER"); Nokia5110_SetCursor(1, 1); if(Score == WIN_SCORE){ Nokia5110_OutString("You Won!"); Nokia5110_SetCursor(1, 2); Nokia5110_OutString("Good job!"); } else{ Nokia5110_OutString("You Lost!"); Nokia5110_SetCursor(1, 2); Nokia5110_OutString("Nice try!"); } Nokia5110_SetCursor(1, 4); Nokia5110_OutString("Score:"); Nokia5110_SetCursor(7, 4); Nokia5110_OutUDec(Score); }
C
#include <stdio.h> #include <stdlib.h> float power(float x, int k); int main(){ printf("Stepenovanje %.2f na %d i rez je: %.2f\n",2.0,3,power(2.0,3)); return EXIT_SUCCESS; } float power(float x,int k){ int i; float result=1; for(i=0;i<k;i++) result*=x; return result; }
C
// // main.c // Sigcomp // // Created by Artem Lenskiy on 15/03/2016. // Copyright © 2016 Artem Lenskiy. All rights reserved. // #include <stdio.h> #include <stdlib.h> #include <math.h> #include <memory.h> #ifndef M_PI #define M_PI 3.14159265358979323846264338327950288 #endif #define BLOCK_SIZE 64 //static const short Qtable[BLOCK_SIZE] = { // 17, 18, 18, 24, 21, 24, 26, 26, // 47, 47, 56, 66, 66, 99, 99, 99, // 99, 99, 99, 99, 99, 99, 99, 99, // 99, 99, 99, 99, 99, 99, 99, 99, // 99, 99, 99, 99, 99, 99, 99, 99, // 99, 99, 99, 99, 99, 99, 99, 99, // 99, 99, 99, 99, 99, 99, 99, 99, // 99, 99, 99, 99, 99, 99, 99, 99 //}; static const short Qtable[BLOCK_SIZE] = {3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 9, 9, 10, 10, 12, 13, 13, 14, 14, 14, 14, 14, 15, 15, 15, 16, 16, 16, 17, 17, 18, 19, 20, 20, 20, 22, 22, 23, 23, 24, 25, 25, 25, 25, 26, 26, 26, 26, 27, 28, 28, 30, 30}; static long current_sample_in = 0; static long current_sample_out = 0; static long total_n_samples = 0; //=============================================================================================================== long readTextFile(char path[], short *samples){ FILE *fd = NULL; fd = fopen(path, "r"); if(fd == NULL){ //the file could be opened. return -1; } while(fscanf(fd, "%hd", samples + total_n_samples++) != EOF); total_n_samples--; fclose(fd); return total_n_samples;} //--------------------------------------------------------------------------------------------------------------- long writeTextFile(char path[], const short *samples, unsigned long length){ FILE *fd = NULL; fd = fopen(path, "w"); if(fd == NULL){ //the file could be opened. return -1; } unsigned long i = 0; while(i < length) fprintf(fd, "%hd\n", *(samples + i++)); fclose(fd); return total_n_samples;} //--------------------------------------------------------------------------------------------------------------- unsigned getBlock(short *samples, short *block){ unsigned n_samples_read = 0; while (n_samples_read < BLOCK_SIZE && current_sample_in < total_n_samples) // replace with memcpy block[n_samples_read++] = samples[current_sample_in++]; return n_samples_read;} //--------------------------------------------------------------------------------------------------------------- unsigned putBlock(short *samples, const short *block){ unsigned n_samples_written = 0; while (n_samples_written < BLOCK_SIZE && current_sample_out < total_n_samples) // replace with memcpy samples[current_sample_out++] = block[n_samples_written++]; return n_samples_written;} //=============================================================================================================== void printBlock(short *block){ unsigned int i = 0; for(;i < BLOCK_SIZE; i++) printf("%hd, ", block[i]); printf("\n"); return;} //=============================================================================================================== void compressRange(short *block, unsigned factor){ unsigned int i = 0; for(;i < BLOCK_SIZE; i++) block[i] = block[i] >> factor; return;} //--------------------------------------------------------------------------------------------------------------- void decompressRange(short *block, unsigned factor){ unsigned int i = 0; for(;i < BLOCK_SIZE; i++) block[i] = block[i] << factor; return;} //=============================================================================================================== //input: f, N; output: F short dct_direct(double *f, double *F ){ double a[BLOCK_SIZE], sum; short i, v; a[0] = sqrt(1.0 / BLOCK_SIZE); // sqrt ( 1.0 / N ); for ( i = 1; i < BLOCK_SIZE; ++i ) a[i] = sqrt(2.0 / BLOCK_SIZE) ; // sqrt ( 2.0 / N ); for ( v = 0; v < BLOCK_SIZE; ++v ) { sum = 0.0; for ( i = 0; i < BLOCK_SIZE; ++i ) { sum += f[i] * cos( (2*i+1) * v * M_PI/(2*BLOCK_SIZE) ); } //for j F[v] = a[v] * sum; } //for v return 1;} //--------------------------------------------------------------------------------------------------------------- //f[i][j] * coef //input: N, F; output f short idct_direct(double *F, double *f ){ double a[BLOCK_SIZE], sum; short i, v; a[0] = sqrt(1.0 / BLOCK_SIZE); for ( i = 1; i < BLOCK_SIZE; ++i ) a[i] = sqrt(2.0 / BLOCK_SIZE); for ( i = 0; i < BLOCK_SIZE; ++i ) { sum = 0.0; for ( v = 0; v < BLOCK_SIZE; ++v ) { sum += a[v]*F[v]*cos( (2*i+1) * v * M_PI/(2*BLOCK_SIZE) ); } //for v f[i] = sum; } //for i return 1; } //--------------------------------------------------------------------------------------------------------------- // change values from short to double and vice versa. short dct (const short *f, short *F ){ double temp_f[BLOCK_SIZE] = {0}, temp_F[BLOCK_SIZE] = {0}; int i; for ( i = 0; i < BLOCK_SIZE; ++i ) temp_f[i] = (double) f[i]; dct_direct (temp_f, temp_F); //DCT operation for ( i = 0; i < BLOCK_SIZE; ++i ) F[i] = (short ) ( floor (temp_F[i] + 0.5) ); //rounding return 1;} //--------------------------------------------------------------------------------------------------------------- // change values from short to doulbe, and vice versa. short idct (const short *F, short *f ){ double temp_f[BLOCK_SIZE] = {0}, temp_F[BLOCK_SIZE] = {0}; int i; for ( i = 0; i < BLOCK_SIZE; ++i ) temp_F[i] = (double) F[i]; idct_direct (temp_F, temp_f ); //IDCT operation for ( i = 0; i < BLOCK_SIZE; ++i ) f[i] = (short ) ( floor (temp_f[i] + 0.5) ); //rounding return 1; } //=============================================================================================================== short sub (const short a, const short b){ return (a - b); } //--------------------------------------------------------------------------------------------------------------- void applyOpBlock(short *block1, const short *block2, short (*op) (short, short)){ unsigned i = 0; for(;i < BLOCK_SIZE; ++i) block1[i] = op(block1[i], block2[i]); } //=============================================================================================================== void quantize_block ( short *p_coef ){ int i; for ( i = 0; i < BLOCK_SIZE; i++ ) p_coef[i] = ( short ) round ( (double)p_coef[i] / Qtable[i] ); } //--------------------------------------------------------------------------------------------------------------- void inverse_quantize_block ( short *p_coef ){ int i; for ( i = 0; i < BLOCK_SIZE; i++ ) p_coef[i] = (short) ( p_coef[i] * Qtable[i] ); } //=============================================================================================================== int main(int argc, const char * argv[]) { char pulse_path[] = "/Users/artemlenskiy/Documents/Research/Matlab/HRVformHWsensor/finger pulse.txt"; char decompressed_path[] = "/Users/artemlenskiy/Documents/Research/Matlab/HRVformHWsensor/finger pulse_.txt"; short *samples = (short *)malloc(1e5 * sizeof(short)); //Allocted memory to store .1 million of samples of size short short *samples_save = (short *)malloc(1e5 * sizeof(short)); //Allocted memory to store .1 million of samples of size short if(readTextFile(pulse_path, samples) < 0){ puts("Couldn't read file"); return -1; } long n_samplesInBlock = 0; short *block = (short *) malloc(BLOCK_SIZE * sizeof(short)); short *tempBlock = (short *) malloc(BLOCK_SIZE * sizeof(short)); short *dctBlock = (short *) malloc(BLOCK_SIZE * sizeof(short)); short *reconBlock = (short *) malloc(BLOCK_SIZE * sizeof(short)); //test coding and decoding do{ n_samplesInBlock = getBlock(samples, block); memcpy(tempBlock, block, BLOCK_SIZE * sizeof(short)); //printBlock(tempBlock); compressRange(tempBlock, 0); dct(tempBlock, dctBlock); quantize_block(dctBlock); //printBlock(dctBlock); inverse_quantize_block(dctBlock); idct(dctBlock, reconBlock); decompressRange(reconBlock, 0); applyOpBlock(block, reconBlock, sub); n_samplesInBlock = putBlock(samples_save, reconBlock); printBlock(block); }while(n_samplesInBlock != 0); if(writeTextFile(decompressed_path, samples_save, total_n_samples) < 0){ puts("Couldn't read file"); return -1; } free(reconBlock); free(dctBlock); free(tempBlock); free(block); free (samples); return 0; }
C
#include<stdio.h> void main() { int r; printf("Enter the number of rows : "); scanf("%d",&r); for(int i=1;i<=r;i++) { for(int j=1;j<=i;j++) { printf("*"); } printf("\n"); } }
C
#ifndef _NOTIFICATION_SERVER_H #define _NOTIFICATION_SERVER_H 1 #include <time.h> #include <sys/types.h> /** @file * A notifications server */ #ifndef MAP_ANONYMOUS /** * MAP_ANONYMOUS is undefined on Mac OS X * but MAP_ANON (which is deprecated by POSIX) is */ #define MAP_ANONYMOUS MAP_ANON #endif /** maximum number of clients */ #define MAX_CLIENTS 10 /** 'reliable' option default */ #define RELIABLE_DEFAULT 1 /** min delay between two checks */ #define WATCH_SLEEP_MIN 2 /** default delay between two checks */ #define WATCH_SLEEP_DEFAULT 10 /** max delay between two checks */ #define WATCH_SLEEP_MAX 60 /** full server error message */ #define NS_ERR_FULL "EServer is full\n" /** exit error message */ #define NS_ERR_EXIT "EServer is shutting down\n" /** general config of notification server */ struct ns_config { /** max number of clients */ int client_max; /** number of files watched by server */ int nb_files; /** path of the socket used to accept clients */ char *s_path; /** pathes of files watched */ char **file; /** flag enabling or disabling reliable mode */ char reliable; /* sockets */ /** file descriptor of server */ int s_socket; /** file descriptors of clients */ int *c_socket; /** one mutex per client fd */ pthread_mutex_t *c_mtx; /* waiting time */ /** minimum interval between two file check */ int w_sleep_min; /** default interval between two file check */ int w_sleep_default; /** maximum interval between two file check */ int w_sleep_max; }; /** * Signal handler to send message * and do some cleaning on exit * @param unused unused variable needed by signal handlers */ void ns_exit(int unused); /** * Send a message to all clients connected * using send_message * @see send_message * @param str message to send * @param len length of the message */ void broadcast(char *str, int len); /** * Send a message to a client. * If client disconnected, remove it from client list (c_socket) * @param s_index index of client in c_socket * @param str message to send * @param len length of message */ void send_message(int s_index, char *str, int len); /** * Send a notify to all clients connected to the server * @param arg path of the file which changed */ void *notify(void *arg); /** * Look for a change in 'ctime' of a file * @param file path of file * @param old_time previous recorded ctime of file (or 0 for initialization) * @return 0 if file did not change or on initialization * 1 if file changed * -1 on error */ int unreliable_watch(char *file, time_t *old_time); /** * Look for a change in hashcode of a file * @param file path of file * @param old_hash previous recorded hashcode of file (or 0 for initialization) * @return 0 if file did not change or on initialization * 1 if file changed * -1 on error */ int reliable_watch(char *file, uint32_t *old_hash); /** * Loop periodicly watching for file change * @param path file to watch * @return NULL on error (never return if success) */ void *watch_file(void *path); /** * Launch a thread for each file in conf using watch_file * @see watch_file * @return number of files which are being watched on success * @return -1 on error */ int nsa(void); /** * Set up the server (socket, bind, ...) and update 'conf' * @return 0 on success * @return -1 on error */ int set_up_server(void); /** * If server is not full, wait for a connexion and update client list in conf * @return 0 on success * @return -1 on error */ int accept_client(void); /** * Parse arguments and update 'conf' with found options * @param argc number of arguments in argv * @param argv arguments to parse * @return 0 on success * @return -1 on error */ int parse_arg(int argc, char **argv); #endif
C
#include <math.h> int falsaposicao (double a, double b, int p, double (*f) (double x), double* r) { int i = 0; double c, fc; double maxerr = 0.5 * pow(10.0, -p); double fb = f(b); do { c = a - ( (f(a)*(b-a)) / (f(b) - f(a)) ); fc = f(c); if (f(c) * fb < 0) { a = c; } else { fb = fc; b = c; } i++; } while (fc >= maxerr); *r = c; return i; } int newtonraphson (double x0, int p, double (*f) (double x), double (*fl) (double x), double* r) { int i= 0; double xi; double maxerr = 0.5 * pow(10.0, -p); do { xi = x0 - f(x0) / fl(x0); x0 = xi; i++; } while (fabs(f(xi)) >= maxerr); *r = xi; return i; }
C
#include "philosophers.h" time_t get_time() { const time_t s_to_ms = 1000000; time_t tmp1; suseconds_t tmp; t_time_sturct tv; if (gettimeofday(&tv, NULL) == -1) return 0; tmp1 = tv.tv_sec - g_tv.tv_sec; tmp = tv.tv_usec - g_tv.tv_usec; if (tmp < 0) { tmp1--; tmp += s_to_ms; } if (tmp1 > 0) tmp += tmp1 * s_to_ms; return (tmp); } char *get_message(char *message, t_philo *philo, size_t *len_of) { size_t len; size_t len_tmp; size_t tmp_len; char *tmp; char *result; len = 6; tmp = ft_itoa((philo->num_of_philo) + 1); tmp_len = ft_strlen(tmp); len += tmp_len; len_tmp = ft_strlen(message); len += len_tmp; result = (char *)malloc(len + 1); int i = 0; int j = 0; while (i < 6) result[i++] = ' '; while (j < (int)tmp_len) result[i++] = tmp[j++]; j = 0; while (j < (int)len_tmp) result[i++] = message[j++]; *len_of = len; free(tmp); return (result); } void print_message(t_philo *philo, char *message, int is_dead) { char *tmp; size_t len; tmp = get_message(message, philo, &len); sem_wait(g_print_sem); ft_putnbr_fd((get_time()) / 1000, 1); write(1, tmp, len); if (!is_dead) sem_post(g_print_sem); free(tmp); } int try_to_take_forks(t_philo *philo) { sem_wait(g_waiter); sem_wait(g_forks_sem); print_message(philo, " has taken a fork\n", 0); sem_wait(g_forks_sem); print_message(philo, " has taken a fork\n", 0); sem_post(g_waiter); return (0); } void put_forks(t_philo *philo) { (void)philo; sem_post(g_forks_sem); usleep(5); sem_post(g_forks_sem); usleep(5); } void philo_death(t_philo *philo) { print_message(philo, " is dead\n", 1); } void thinking(t_philo *philo) { print_message(philo, " is thinking\n", 0); } void sleeping(t_philo *philo) { print_message(philo, " is sleeping\n", 0); my_usleep(philo->input_data->t_to_sleep * 1000); } void eating(t_philo *philo) { try_to_take_forks(philo); print_message(philo, " is eating\n", 0); //sem_wait(philo->life_check_sem); philo->eat_time = get_time() / 1000; my_usleep(philo->input_data->t_to_eat * 1000); philo->eating_counter++; //sem_post(philo->life_check_sem); put_forks(philo); } void *simulation_start(t_philo *philo) { philo->eat_time = get_time() / 1000; pthread_create(&philo->death_thread, NULL, (void * (*)(void *))check_deading, ((void *)(philo))); while (1) { eating(philo); sleeping(philo); thinking(philo); } return (NULL); } int main(int argc, char **argv) { t_input_data input_data; if (gettimeofday(&g_tv, NULL) == -1) { write(1, "some problem with gettimeofday func\n", 37); return (0); } if (argc > 6 || argc < 5) { write(1, "Wrong count of arguments\n", 26); return (0); } else if ((argc == 5 && start(argv, 0, &input_data) == -1) || (argc == 6 && start(argv, 1, &input_data) == -1)) { write(1, "Invalid paramaters\n", 20); return (0); } }
C
#include <stdio.h> //counting the characters in a stream int main() { int ws = 0; int c; while((c = getchar()) != EOF) { if (c == 'w') { ws++; } } printf("the number of ws in the string is %d \n", ws); }
C
#include <stdio.h> #include <string.h> #include "connect.h" #include "http.h" #define N_c 9 #define P_c 1 char test_connection[N_c + P_c][30] = { // negative "incorrect", "1234", "1270013030", "127.0.0.1.3030", "", "127.incorrect.0.0.1:3030", ":", // TODO poprawny adres, ale nie ma pod nim serwera "111.121.34.90:3030", ":3030", "127.0.0.1:", // positive "127.0.0.1:3030" // TODO połączenie ze studentsem // TODO połaczenie z maszyną wirtualną }; #define URL_TESTS_NEG 5 char test_url[URL_TESTS_NEG][30] = { "site/file", "ttp://file", "http//site/file/fle/fiel", "", "http://site" }; void make_connection_test(); void add_status_line_test(); int main(int argc, char *argv[]) { make_connection_test(); // add_status_line_test(); printf("Tests finished\n"); return 0; } void make_connection_test() { // incorrect string format int failed = 0; for (int i=0; i < N_c; i++) { if (make_connection(test_connection[i]) != -1) { printf("make_test_connection() test %d failed\n", i); failed = 1; } } // correct adderss for (int i = N_c; i < N_c + P_c; i++) { if (make_connection(test_connection[i]) == -1) { printf("make_test_connection() test %d failed\n", i); failed = 1; } } if (!failed) printf("make_connection() passed\n"); } //void add_status_line_test() { // http_message message1; // // int failed = 0; // // for (int i = 0; i < URL_TESTS_NEG; i++) { // if (add_status_line(NULL, test_url[i]) == 0) { // printf("make_test_connection() test %d failed\n", i); // failed = 1; // } // } // // char long_url[10040] = "https://"; // // memset(long_url + 8, 'a', 9000); // // long_url[20] = '/'; // // if (add_status_line(&message1, long_url) != 0) { // printf("add_status_line long_url test failed\n"); // failed = 1; // } // // // TODO: // // -incorrect addresses // // -long adderss // // -correct addresses // // if (!failed) printf("add_status_line_test() passed\n"); //}
C
#include "holberton.h" /** * _strlen - returns the lenght of a string * @s: pointer to s * * Return: 0 on success * */ int _strlen(const char *s) { int count = 0; if (s != '\0') { while (*(s + count) != '\0') count++; } return (count); } /** * binary_to_uint - converts a binary number to an unsigned int * @b: pointing to a string of 0 and 1 chars * Return: the converted number, or 0 if there is one or more chars in the * string b that is not 0 or 1 or b is NULL */ unsigned int binary_to_uint(const char *b) { unsigned int number; int i, len, pow_of_2; len = _strlen(b); number = 0; pow_of_2 = 1; if (b == NULL) return (0); for (i = len - 1; i >= 0 ; i--) { if (b[i] != '0' && b[i] != '1') return (0); if (b[i] == '0') number += 0; if (b[i] == '1') number += pow_of_2; pow_of_2 *= 2; } return (number); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #define PATH_MAX 2048 #define LINE_MAX 256 // Q. #define COV_MAX 1024 /** * White-Box Testing : derive tests from the implementation. * * Coverage criteria * 1. Statement coverage * 2. Branch coverage */ void get_c_file_name (char * dst, char * src) { char copied_src[1024] ; strcpy(copied_src, src) ; int src_len = strlen(src) ; int idx = 0 ; char reversed[1024] ; for (int i = src_len - 1; i >= 0; i--) { if (src[i] == '/') break ; reversed[idx++] = src[i] ; } reversed[idx] = 0x0 ; int i ; for (i = 0; i < src_len; i++) { dst[i] = reversed[idx - i - 1] ; } dst[i] = 0x0 ; } int exec_program (char * program, char ** arguments) { pid_t child_pid = fork() ; if (child_pid == 0) { if (execv(program, arguments) == -1) { perror("exec_program: execv") ; exit(1) ; } } else if (child_pid == 0x0) { perror("exec_program: fork") ; exit(1) ; } int exit_code ; wait(&exit_code) ; return exit_code ; } void compile_with_gcc (char * target_path, char * target_path_c) { char * compile_args[] = { "gcc", "--coverage", "-o", target_path, target_path_c, 0x0 } ; if (exec_program("/usr/bin/gcc", compile_args) != 0) { perror("compile_with_gcc: exec_program") ; exit(1) ; } } void run_target(char * target_path, char * input) { char * args[] = { target_path, input, 0x0 } ; if (exec_program(target_path, args) != 0) { perror("run_target: exec_program") ; exit(1) ; } } void run_gcov (char * c_file_name) { char * gcov_args[] = { "gcov", c_file_name, 0x0 } ; if (exec_program("/usr/bin/gcov", gcov_args) != 0) { perror("run_gcov: exec_program") ; exit(1) ; } } int read_gcov_file (int * coverage, char * c_file_name) { char gcov_file[PATH_MAX] ; sprintf(gcov_file, "%s.gcov", c_file_name) ; int cov_idx = 0 ; FILE * fp = fopen(gcov_file, "r") ; if (fp == 0x0) { perror("read_gcov_file: fopen") ; exit(1) ; } char * buf = (char *) malloc(sizeof(char) * LINE_MAX) ; size_t line_max = LINE_MAX ; while(getline(&buf, &line_max, fp) > 0) { char * covered = strtok(buf, ":") ; if (atoi(covered) > 0) { char * line_number = strtok(0x0, ":") ; if (cov_idx != 0 && cov_idx % COV_MAX == 0) { coverage = realloc(coverage, cov_idx + COV_MAX) ; } coverage[cov_idx++] = atoi(line_number) ; #ifdef DEBUG printf("('%s', %d)\n", c_file_name, coverage[cov_idx - 1]) ; #endif } } free(buf) ; fclose(fp) ; return cov_idx ; } void remove_files (char * executable, char * c_file_name) { if (remove(executable) == -1) { perror("remove_files: remove: executable") ; } char gcov_file[PATH_MAX] ; sprintf(gcov_file, "%s.gcov", c_file_name) ; if (remove(gcov_file) == -1) { perror("remove_files: remove: gcov") ; } char gcda_file[PATH_MAX] ; char * ptr = strtok(c_file_name, ".") ; sprintf(gcda_file, "%s.gcda", ptr) ; if (remove(gcda_file) == -1) { perror("remove_files: remove: gcda") ; } char gcno_file[PATH_MAX] ; sprintf(gcno_file, "%s.gcno", ptr) ; if (remove(gcno_file) == -1) { perror("remove_files: remove: gcno") ; } } int main (int argc, char * argv[]) { if (argc < 4) { perror("whitebox_testing: usage: ./whitebox_testing EXECUATBLE_PATH C_FILE_PATH INPUT") ; return 1 ; } char * executable_path = argv[1] ; // TODO. check if the path is valid char * c_file_path = argv[2] ; if (access(c_file_path, R_OK) == -1) { perror("access: readable file does not exist") ; return 1 ; } char * input = argv[3] ; // TODO. if the target program gets more than one arguments char c_file_name[PATH_MAX] ; get_c_file_name(c_file_name, c_file_path) ; compile_with_gcc(executable_path, c_file_path) ; run_target(executable_path, input) ; run_gcov(c_file_name) ; int * coverage = (int *) malloc(sizeof(int) * COV_MAX) ; read_gcov_file(coverage, c_file_name) ; // TODO. w/ coverage ? remove_files(executable_path, c_file_name) ; free(coverage) ; return 0 ; }
C
#include<stdio.h> #include<stdbool.h> int reverseDigits(int num) { bool negativeFlag = false; if(num<0) { negativeFlag = true; num = -num; } static int rev_num = 0; if(num>0) { rev_num = (rev_num*10)+ num%10; reverseDigits(num/10); } return negativeFlag ? -rev_num : rev_num; } int main() { int num = -29813; //reverseDigits(num); printf("%d",reverseDigits(num)); return 0; }
C
//this starts @ end of else in sheet he gave us today fscanf(fin,"%d",&num); //prime read. while(!feof(fin)){ count++; fscanf(fin,"%d",&num); } if (count == 0){ perror("this to say"); exit(-1); } fseek(fin, 0, SEEK_SET); //or rewind(fin); array=(int *) malloc(count * sizeof(int)); array=(int *)calloc(count, sizeof(int)); if(array==NULL) exit(-1); int x; for(x=0;x<count;x++) fscnf(fin,"%d",&array[x]); sort(array, count); fout=fopen("out.txt", "w"); if(fout==NULL) exit(-1); for(x=0;x<count;x++){ fprintf(fout, "%d\n", array[x]); fprintf(stdout, "%d\n", array[x]); } fprintf(stdout, "\n"); fprintf(fout, "\n"); if(array != NULL) free(array); array=NULL; return 0;
C
/* Name: Ricerca di un elemento in vettore Author: Alessandro Condello Date: 01/10/19 08:54 Description: Si scriva una funzione in C, denominata cerca, che ricerchi la presenza di un elemento in un vettore di interi. Il vettore e il valore x da cercare sono varabili globali La funzione deve restituire un valore intero, ed in particolare: se il valore x presente nel vettore, allora la funzione restituisce lindice della posizione alla quale si trova tale valore; se il valore x presente pi volte, si restituisca lindice della prima occorrenza; se il valore x non presente nel vettore, si restituisca -1. */ #include <stdio.h> #define N 5 int vet[N]; int x; void rich(int len_); int ricerca(int len); void rich(int len) { int i; for(i = 0; i < len ; i++) { printf("%d valore: ",i+1); scanf("%d",&vet[i]); } } int ricerca(int len) { int i = 0, trov = 0; do { if ( vet[i] == x ) trov++; else i++; }while(i < len && !trov); if(trov) return i; else return -1; } int main() { rich(N); printf("Incognita: "); scanf("%d",&x); int ris = ricerca(N); if ( ris == -1) printf("Incognita non trovata"); else printf("Incognita trovata a posizione %d",ris); }
C
#include "kernel.h" TKVPageDirectory vmmCreateDirectory() { int i; TKVPageDirectory directory = (TKVPageDirectory)allocPage(); for (i = 0; i < 1024; i++) { directory[i] = 0; } return directory; } TKVPageTable vmmGetOrCreatePageTable(TKVPageDirectory directory, unsigned int prefix, int user) { if (directory[prefix] & 1 > 0) { if (user != 0) { directory[prefix] |= 0x4; } return (TKVPageTable)(directory[prefix] & 0xfffff000); } int i; // Allocate a table on the heap TKVPageTable table = (TKVPageTable)allocPage(); // Clear table for (i = 0; i < 1024; i++) { table[i] = 0; } // Set "present" and "read/write" bits directory[prefix] = ((unsigned int)table) & 0xfffff000 | 0x3 | ((user & 0x1) << 2); return table; } void vmmSetPage(TKVPageTable table, int src, unsigned int dest, int user) { // Set "present" and "read/write" bits table[src] = dest & 0xfffff000 | 0x3 | ((user & 0x1) << 2); } void vmmMapPage(TKVPageDirectory directory, unsigned int src, unsigned int dest, int user) { TKVPageTable table = vmmGetOrCreatePageTable(directory, src >> 22, user); vmmSetPage(table, (src >> 12) & 0x3ff, dest, user); } void vmmSwap(TKVPageDirectory directory) { __asm__ __volatile__ ( "mov %0, %%cr3\n" "mov %%cr0, %%ebx\n" "or $0x80000000, %%ebx\n" "mov %%ebx, %%cr0\n" : : "r" (directory) : "%ebx" ); }
C
#include "types.h" #include "bstrlib.h" #include "ApplicationModel.h" static simpleEvent applicationStartsEvent = 0; void ApplicationModel_WhenApplicationStarts(void(*callback)(void)) { applicationStartsEvent = callback; } int ApplicationModel_Run() { applicationStartsEvent(); return 0; } int ApplicationModel_Divide(const char* dividend, const char* divisor) { return atoi(dividend) / atoi(divisor); } int ApplicationModel_ValidateArguments(const char* divisor, const char* dividend) { return (atoi(dividend) == 0) ? FALSE : TRUE; } int ApplicationModel_CheckArgumentFormat(const char* previouslyEnteredText, const char* newText) { bstring combined = bfromcstr(previouslyEnteredText); bstring new = bfromcstr(newText); bconcat(combined, new); bdestroy(new); int textIsValid = NumberValidator_IsNumber(combined->data); bdestroy(combined); return textIsValid; }
C
#ifndef __RAMP_CNTL_CLA_H__ #define __RAMP_CNTL_CLA_H__ typedef struct { float TargetValue; // Input: Target input int RampDelayMax; // Parameter: Maximum delay rate float RampLowLimit; // Parameter: Minimum limit float RampHighLimit; // Parameter: Maximum limit int RampDelayCount; // Variable: Incremental delay float SetpointValue; // Output: Target output int EqualFlag; // Output: Flag output float Tmp; // Variable: Temp variable } RAMP_CNTL_CLA; #define RAMP_CNTL_CLA_MACRO(v) \ v.Tmp = v.TargetValue - v.SetpointValue; \ /* 0.0000305 is resolution */ \ if ((v.Tmp >= (0.0000305))||(v.Tmp <= (-0.0000305))) \ { \ v.RampDelayCount++ ; \ if (v.RampDelayCount >= v.RampDelayMax) \ { \ if (v.TargetValue >= v.SetpointValue) \ v.SetpointValue += 0.0000305; \ else \ v.SetpointValue -= 0.0000305; \ \ v.SetpointValue=__mminf32(v.SetpointValue,v.RampHighLimit); \ v.SetpointValue=__mmaxf32(v.SetpointValue,v.RampLowLimit); \ v.RampDelayCount = 0; \ \ } \ } \ else \ { \ v.EqualFlag = 1; \ v.SetpointValue=v.TargetValue; \ } #define RAMP_CNTL_CLA_INIT(v) \ v.EqualFlag=0; \ v.RampDelayCount=0; \ v.RampDelayMax=5; \ v.RampHighLimit =1.0; \ v.RampLowLimit = -1.0; \ v.SetpointValue=0; \ v.TargetValue = 0.3; \ #endif // __RMP_CNTL_H__
C
/* * Motor.c * * Created on: Jun 15, 2020 * Author: LeoTheLegion */ #include "Motor.h" void setupMotor(){ pinMode(ENABLE, OUTPUT); pinMode(CONTROL1, OUTPUT); pinMode(CONTROL2, OUTPUT); } /* * percentage = (0-1) */ void forward(float percentage){ setPowerto(percentage); digitalWrite(CONTROL1, HIGH); digitalWrite(CONTROL2, LOW); } /* * percentage = (0-1) */ void backward(float percentage){ setPowerto(percentage); digitalWrite(CONTROL1, LOW); digitalWrite(CONTROL2, HIGH); } void brake(){ analogWrite(ENABLE, 0); digitalWrite(CONTROL1, LOW); digitalWrite(CONTROL2, LOW); } /* * percentage = (0-1) */ void setPowerto(float percentage){ analogWrite(ENABLE, MAXPOWER * percentage); }
C
// ŽŰ (search key) // ׸ ׸ ִ Ű(key) // Ž Ͽ Ǵ ڷ // 迭, ḮƮ, Ʈ, ׷ // Ž:  ڷ ϴ ãƳ // Ž (Sequential search) // Ž ߿ ϰ Ž // ĵ 迭 ó ϳ ˻ϴ // Ƚ // Ž: (n+1)/2 // Ž: n // ð⵵: O(n) int seq_search(int key, int low, int high) { int i; for (i = low; i <= high; i++) if (list[i] == key) return i; // Ž return -1; // Ž } int seq_search2(int key, int low, int high) { int i; list[high + 1] = key; // Ű ã for (i = low; list[i] != key; i++) ; if (i == (high + 1)) return -1; // Ž else return i; // Ž } // Ż⹮ 1, i key ̶ 񱳿µ i key index ϸ鼭
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gmordele <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/02/10 01:24:15 by gmordele #+# #+# */ /* Updated: 2018/03/01 20:29:38 by gmordele ### ########.fr */ /* */ /* ************************************************************************** */ #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include "libft.h" #include "asm.h" static char *new_file_name(char *file_name, t_data *data) { int i; char *ret; i = ft_strlen(file_name); while (file_name[i] != '.' && i > 0) --i; if (!ft_strequ(file_name + i, ".s")) return (NULL); if ((ret = (char *)malloc(ft_strlen(file_name) + 3)) == NULL) err_exit_strerror("malloc()", data); ft_strcpy(ret, file_name); ft_strcpy(ret + i, ".cor"); return (ret); } static void init_data(t_data *data, char *file_name) { (void)data; data->file_name = NULL; data->new_file_name = NULL; data->str = NULL; data->statement_lst = NULL; ft_bzero(&(data->header), sizeof(data->header)); if ((data->file_name = ft_strdup(file_name)) == NULL) err_exit_str("init_data(): ft_strdup() failed", data); if ((data->new_file_name = new_file_name(file_name, data)) == NULL) err_exit_str("bad file name", data); data->header.magic = reverse_endian_int(COREWAR_EXEC_MAGIC); data->row = 1; } void free_data(t_data *data) { if (data->file_name != NULL) free(data->file_name); if (data->new_file_name != NULL) free(data->new_file_name); ft_strdel(&(data->str)); statement_lst_free(data); get_next_line(0, FREE_GNL); } int main(int argc, char **argv) { t_data data; int fd; int fd_write; ft_bzero(&data, sizeof(t_data)); if (argc < 2) err_exit_str("missing argument", &data); init_data(&data, argv[1]); if ((fd = open(argv[1], O_RDONLY)) < 0) err_exit_strerror("open()", &data); get_header(fd, &data); get_statements(fd, &data); get_offsets(&data); get_write_buf(&data); if ((fd_write = open(data.new_file_name, O_WRONLY | O_TRUNC | O_CREAT, 0644)) < 0) err_exit_strerror("open():", &data); write_buf(fd_write, &data); ft_printf("Writing output program to %s\n", data.new_file_name); close(fd); close(fd_write); free_data(&data); return (0); }
C
#include "setting_datastructure.h" extern devicelist* arrayofdevice; //定义写在.c当中,声明写在.h当中 task_node* alloc_node(char *t,char *fr,char* hn,int ts,char*fs,int fdm) { task_node* plinkNode=NULL; plinkNode = (task_node *)malloc(sizeof(task_node)); plinkNode->type=t; plinkNode->filterRules=fr; plinkNode->hostname=hn; plinkNode->timeslice_mins=ts; plinkNode->fixtime_starttime=fs; plinkNode->fixtime_duration_mins=fdm; plinkNode->tasknode_threadID=NULL; plinkNode->tasknode_attr=NULL; plinkNode->ring_buf=NULL; plinkNode->next=NULL; return plinkNode; } void push(task_node *head,char *t,char *fr,char* hn,int ts,char*fs,int fdm) { task_node *current=head; while(current->next!=NULL) { current=current->next; } current->next=(task_node*)malloc(sizeof(task_node)); current->next->type=t; current->next->filterRules=fr; current->next->hostname=hn; current->next->timeslice_mins=ts; current->next->fixtime_starttime=fs; current->next->fixtime_duration_mins=fdm; current->next->tasknode_threadID=NULL; current->next->tasknode_attr=NULL; current->next->ring_buf=NULL; current->next->next=NULL; } void print_list(task_node *head) { task_node* current=head; //while(current!=NULL) //{ printf("%s\n",current->type); printf("%s\n", current->filterRules); printf("%s\n", current->hostname); printf("%d\n", current->timeslice_mins); printf("%s\n", current->fixtime_starttime); printf("%d\n", current->fixtime_duration_mins); printf("@@@@@@@@@@@@@@@@\n"); //} //current=current->next; } void pop(task_node **head) { task_node* next_node = NULL; if(*head==NULL) { return ; } next_node=(*head)->next; free(*head); *head=next_node; } void remove_last(task_node *head) { /* if there is only one item in the list, remove it */ if(head->next==NULL) { free(head); head=NULL;//防止野指针 } task_node * current=head; while (current->next->next != NULL) { //找到倒数第二个节点 current = current->next; } task_node *q; q=current->next; current->next=NULL;//原来的链表到此结束 free(q); } void remove_by_index(task_node** head,int n) { int i=0; task_node *current=*head; task_node *temp_node=NULL; if(n==0) { return pop(head); } for (;i<n-1;i++) { if(current->next==NULL) return ; current=current->next; } temp_node=current->next; current->next=temp_node->next; free(temp_node); }
C
#ifndef HAVE_ORDER_LINK_LIST_H #define HAVE_ORDER_LINK_LIST_H #include "common.h" typedef struct _order_link_list_node_st { void * data; struct _order_link_list_node_st * next; }OrderLinkListNode, * OrderLinkListNodePtr; typedef int(*OrderLinkList_FucPtr_compare)(void* v1, void * v2); typedef void(*OrderLinkList_FucPtr_free_val)(void* val); typedef struct _order_link_list_st { OrderLinkListNode * head; OrderLinkList_FucPtr_compare compare; int len; }*OrderLinkList; OrderLinkList OrderLinkList_init(OrderLinkList_FucPtr_compare compare); Status OrderLinkList_add(OrderLinkList list, void * val); int OrderLinkList_size(OrderLinkList list); void OrderLinkList_destroy(OrderLinkList list, OrderLinkList_FucPtr_free_val fuc); void * OrderLinkList_remove_frist(OrderLinkList list); #endif // !HAVE_ORDER_LINK_LIST_H
C
#include <stdio.h> #include <stdlib.h> struct node { int info; struct node *link; }; struct node *removeValue(struct node *, int); int main() { int n; scanf("%d", &n); struct node *head = (struct node *)malloc(sizeof(struct node)); head->link = NULL; struct node *temp; for (int i = 0; i < n; i++) { int value; scanf("%d", &value); if (i == 0) { head->info = value; temp = head; } else { struct node *new = (struct node *)malloc(sizeof(struct node)); new->info = value; new->link = NULL; temp->link = new; temp = temp->link; } } int k; scanf("%d", &k); head = removeValue(head, k); temp = head; while (temp != NULL) { printf("%d ", temp->info); temp = temp->link; } return 0; } struct node *removeValue(struct node *head, int k) { struct node *temp = head; if (head == NULL) { return NULL; } if (k == 1) { head = head->link; free(temp); return head; } struct node *prev = head; temp = head->link; while (temp != NULL) { if (temp->info == k) { prev->link = temp->link; free(temp); return head; } prev = temp; temp = temp->link; } return head; }
C
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <unistd.h> // This is the pathname to the sysfs file that enables and disables // tracing on the qemu emulator. #define SYS_QEMU_TRACE_STATE "/sys/qemu_trace/state" // This is the pathname to the sysfs file that adds new (address, symbol) // pairs to the trace. #define SYS_QEMU_TRACE_SYMBOL "/sys/qemu_trace/symbol" // The maximum length of a symbol name #define MAX_SYMBOL_NAME_LENGTH (4 * 1024) // Allow space in the buffer for the address plus whitespace. #define MAX_BUF_SIZE (MAX_SYMBOL_NAME_LENGTH + 20) // return 0 on success, or an error if the qemu driver cannot be opened int qemu_start_tracing() { int fd = open(SYS_QEMU_TRACE_STATE, O_WRONLY); if (fd < 0) return fd; write(fd, "1\n", 2); close(fd); return 0; } int qemu_stop_tracing() { int fd = open(SYS_QEMU_TRACE_STATE, O_WRONLY); if (fd < 0) return fd; write(fd, "0\n", 2); close(fd); return 0; } int qemu_add_mapping(unsigned int addr, const char *name) { char buf[MAX_BUF_SIZE]; if (strlen(name) > MAX_SYMBOL_NAME_LENGTH) return EINVAL; int fd = open(SYS_QEMU_TRACE_SYMBOL, O_WRONLY); if (fd < 0) return fd; sprintf(buf, "%x %s\n", addr, name); write(fd, buf, strlen(buf)); close(fd); return 0; } int qemu_remove_mapping(unsigned int addr) { char buf[MAX_BUF_SIZE]; int fd = open(SYS_QEMU_TRACE_SYMBOL, O_WRONLY); if (fd < 0) return fd; sprintf(buf, "%x\n", addr); write(fd, buf, strlen(buf)); close(fd); return 0; }
C
/*** *** Decide whether this program terminates *** If it does, use a model checker to verify a ranking function. *** If it does not, use a model checker to find a non-terminating execution. *** ***/ /** Returns a non-deterministic value */ extern int nd(void); int main() { int x = nd(); while (x <= 10) x = x + 1; return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* init_file_for_visu.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: amartinod <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/04/22 11:57:52 by amartinod #+# #+# */ /* Updated: 2020/05/08 11:42:41 by amartinod ### ########.fr */ /* */ /* ************************************************************************** */ #include "lem_in.h" static void add_link_to_file(t_graph *graph, int fd) { size_t i; t_adj_node *node; i = 0; while (i < graph->size) { node = graph->array[i].head; while (node != NULL) { ft_dprintf(fd, "%zu-%zu\n", i, node->dest); node = node->next; } i++; } } static void add_path_to_file(t_network *net, int fd) { t_path *tmp; size_t i; i = 0; while (i <= net->all_path->end) { tmp = net->all_path->contents[i]; while (tmp != NULL) { ft_dprintf(fd, "%zu ", tmp->vertex); tmp = tmp->next; } ft_dprintf(fd, "\n"); i++; } } void init_file_for_visu(t_graph *graph, t_network *net) { int fd; fd = open("/tmp/visu_lemin.txt", O_RDWR | O_CREAT | O_TRUNC, 0744); if (fd != FAILURE) { if (graph != NULL) add_link_to_file(graph, fd); if (net != NULL) add_path_to_file(net, fd); close(fd); } }
C
#include "cmd_exec.h" #include <assert.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/wait.h> #include <pwd.h> #include <fcntl.h> #include <dirent.h> #include "psplit.h" #include "sign_mgmt.h" /****************************************************************************** * Funciones para la ejecución de comandos internos ******************************************************************************/ int EXIT = 0; int run_exit(char** argv, int argc) { EXIT = 1; return 0; } #define BUFFER_SIZE 300 char buff[BUFFER_SIZE]; int cwd(char** argv, int argc) { char* token = getcwd(buff, BUFFER_SIZE); if (token == NULL) { ERROR("%s\n", strerror(errno)); return -1; } INFO("%s\n", token); return 0; } int run_cd(char** argv, int argc) { if (argc > 2) { ERROR("too many arguments\n"); return 1; } char *dir; if (argc == 1) { char* buf; const int PROMPT_STRING_SIZE = 300; char prompt[PROMPT_STRING_SIZE]; uid_t uid = getuid(); // Obtenemos el uid del usuario // Obtenemos de la entrada del fichero /etc/passwd el directorio home // ¡No liberar la estructura devuelta por getpwuid con free! struct passwd* entry = getpwuid(uid); if (entry == NULL) { ERROR("%s\n", strerror(errno)); return -1; } dir = entry->pw_dir; if (dir == NULL) { ERROR("couldn't locate the home directory\n"); return -1; } } else { if (strcmp(argv[1], "-") == 0) { char* oldPath = getenv("OLDPWD"); if (oldPath == NULL) { ERROR("Variable OLDPWD no definida\n"); return -1; } dir = oldPath; } else { dir = argv[1]; } } char* token = getcwd(buff, BUFFER_SIZE); if (chdir(dir) == -1) { ERROR("%s\n", strerror(errno)); return -1; } if (token != NULL) { TRY(setenv("OLDPWD", token, 1)); } return 0; } static char inter_comms[][15] = {"cwd", "exit", "cd", "psplit", "bjobs"}; static int (*inter_funcs[])(char** argv, int argc) = {cwd, run_exit, run_cd, run_psplit, run_bjobs}; int (*isInter(char *comm))(char **argv, int argc) { if (comm == NULL) return NULL; for (int i = 0; i < sizeof(inter_comms) / sizeof(inter_comms[0]); i++) if (strcmp(inter_comms[i], comm) == 0) return inter_funcs[i]; return NULL; } /****************************************************************************** * Funciones para la ejecución de la línea de órdenes ******************************************************************************/ void exec_cmd(struct execcmd* ecmd) { assert(ecmd->type == EXEC); // Si no hay comando: if (ecmd->argv[0] == NULL) exit(EXIT_SUCCESS); execvp(ecmd->argv[0], ecmd->argv); panic("no se encontró el comando '%s'\n", ecmd->argv[0]); } void run_cmd(struct cmd* cmd) { if (EXIT) return; struct execcmd* ecmd; struct redrcmd* rcmd; struct listcmd* lcmd; struct pipecmd* pcmd; struct backcmd* bcmd; struct subscmd* scmd; int p[2], pid[2]; int fd; DPRINTF(DBG_TRACE, "STR\n"); if (cmd == 0) return; switch (cmd->type) { case EXEC: ecmd = (struct execcmd*)cmd; int (*func)(char** argv, int argc) = isInter(ecmd->argv[0]); if (func != NULL) { (*func)(ecmd->argv, ecmd->argc); } else { if ((pid[0] = fork_or_panic("fork EXEC")) == 0) { exec_cmd(ecmd); } TRY_AND_ACCEPT_ECHILD(waitpid(pid[0], NULL, 0)); } break; case REDR: rcmd = (struct redrcmd*)cmd; TRY(fd = dup(rcmd->fd)); TRY(close(rcmd->fd)); if (open(rcmd->file, rcmd->flags, rcmd->mode) < 0) { fprintf(stderr, "simplesh: Couldn't open file '%s' (%s)\n", rcmd->file, strerror(errno)); } else { run_cmd(rcmd->cmd); TRY(close(rcmd->fd)); } TRY(dup(fd)); TRY(close(fd)); break; case LIST: lcmd = (struct listcmd*)cmd; run_cmd(lcmd->left); run_cmd(lcmd->right); break; case PIPE: pcmd = (struct pipecmd*)cmd; if (pipe(p) < 0) { perror("pipe"); exit(EXIT_FAILURE); } // Ejecución del hijo de la izquierda if ((pid[0] = fork_or_panic("fork PIPE left")) == 0) { TRY(close(STDOUT_FILENO)); TRY(dup(p[1])); TRY(close(p[0])); TRY(close(p[1])); run_cmd(pcmd->left); exit(EXIT_SUCCESS); } // Ejecución del hijo de la derecha if ((pid[1] = fork_or_panic("fork PIPE right")) == 0) { TRY(close(STDIN_FILENO)); TRY(dup(p[0])); TRY(close(p[0])); TRY(close(p[1])); run_cmd(pcmd->right); exit(EXIT_SUCCESS); } TRY(close(p[0])); TRY(close(p[1])); // Esperar a ambos hijos TRY_AND_ACCEPT_ECHILD(waitpid(pid[0], NULL, 0)); TRY_AND_ACCEPT_ECHILD(waitpid(pid[1], NULL, 0)); break; case BACK: bcmd = (struct backcmd*)cmd; if ((pid[0] = fork_back_child()) == 0) { run_cmd(bcmd->cmd); exit(EXIT_SUCCESS); } break; case SUBS: scmd = (struct subscmd*)cmd; if ((pid[0] = fork_subshell("fork SUBS")) == 0) { run_cmd(scmd->cmd); exit(EXIT_SUCCESS); } TRY_AND_ACCEPT_ECHILD(waitpid(pid[0], NULL, 0)); break; case INV: default: panic("%s: estructura `cmd` desconocida\n", __func__); } DPRINTF(DBG_TRACE, "END\n"); } void print_cmd(struct cmd* cmd) { struct execcmd* ecmd; struct redrcmd* rcmd; struct listcmd* lcmd; struct pipecmd* pcmd; struct backcmd* bcmd; struct subscmd* scmd; if (cmd == 0) return; switch (cmd->type) { case EXEC: ecmd = (struct execcmd*)cmd; if (ecmd->argv[0] != 0) printf("fork( exec( %s ) )", ecmd->argv[0]); break; case REDR: rcmd = (struct redrcmd*)cmd; printf("fork( "); if (rcmd->cmd->type == EXEC) printf("exec ( %s )", ((struct execcmd*)rcmd->cmd)->argv[0]); else print_cmd(rcmd->cmd); printf(" )"); break; case LIST: lcmd = (struct listcmd*)cmd; print_cmd(lcmd->left); printf(" ; "); print_cmd(lcmd->right); break; case PIPE: pcmd = (struct pipecmd*)cmd; printf("fork( "); if (pcmd->left->type == EXEC) printf("exec ( %s )", ((struct execcmd*)pcmd->left)->argv[0]); else print_cmd(pcmd->left); printf(" ) => fork( "); if (pcmd->right->type == EXEC) printf("exec ( %s )", ((struct execcmd*)pcmd->right)->argv[0]); else print_cmd(pcmd->right); printf(" )"); break; case BACK: bcmd = (struct backcmd*)cmd; printf("fork( "); if (bcmd->cmd->type == EXEC) printf("exec ( %s )", ((struct execcmd*)bcmd->cmd)->argv[0]); else print_cmd(bcmd->cmd); printf(" )"); break; case SUBS: scmd = (struct subscmd*)cmd; printf("fork( "); print_cmd(scmd->cmd); printf(" )"); break; case INV: default: panic("%s: estructura `cmd` desconocida\n", __func__); } }
C
#include "head.h" #include "kernel_list.h" //定义结构体 struct flight_information{ char number[15]; char begin[20]; char end[20]; char day[30]; char type[5]; char time[20]; int price; struct list_head list; }; //定义用户的结构体 struct user_information{ char user_account[20]; char user_mima[20]; char user_name[10]; char user_age[5]; char user_gender[5]; int user_balance; int vip; char user_buy[50][10]; int user_ticket; struct list_head list; }; //读出文件夹中文件数量 int file_number(struct dirent *ep,DIR *fp) { int i=0; while(1) { ep=readdir(fp); if(ep==NULL) break; i=i+1; } return i; } //将文件夹内文件名存放到数组 void store_array(char data[][20],struct dirent *ep,DIR *fp,int i) { int n; rewinddir(fp); for(n=0;n<=i;n++) { ep=readdir(fp); if(ep==NULL) break; strcpy(data[n],ep->d_name); } } //初始化航班头节点 struct flight_information *init_head(struct flight_information *head) { head=(struct flight_information *)malloc(sizeof(struct flight_information)); INIT_LIST_HEAD(&(head->list)); return head; } //初始化用户的头节点 struct user_information *init_user_head(struct user_information *head2) { head2=(struct user_information *)malloc(sizeof(struct user_information)); INIT_LIST_HEAD(&(head2->list)); return head2; } //欢迎界面 void welcome_jiemian(void) { printf("****************************************\n"); printf(" welcome to flight enquiry system \n"); printf("****************************************\n"); //sleep(5); } //尾插新节点 int add_tail_list(struct flight_information *head,char *number,char *begin,char *end,char *day,char *type,char *time,int price) { struct flight_information *new=NULL; new=(struct flight_information *)malloc(sizeof(struct flight_information)); if(new==NULL) { printf("Failed to create new node!"); return -1; } strcpy(new->number,number); strcpy(new->begin,begin); strcpy(new->end,end); strcpy(new->day,day); strcpy(new->type,type); strcpy(new->time,time); new->price=price; list_add_tail(&(new->list),&(head->list)); return 0; } //尾插用户信息节点 int add_registe_tail(struct user_information *head2,struct user_information *p) { struct user_information *new=NULL; new=(struct user_information *)malloc(sizeof(struct user_information)); if(new==NULL) { printf("Failed to create new node!"); return -1; } strcpy(new->user_account,p->user_account); strcpy(new->user_mima,p->user_mima); strcpy(new->user_name,p->user_name); strcpy(new->user_age,p->user_age); strcpy(new->user_gender,p->user_gender); new->user_balance=p->user_balance; new->vip=p->vip; memcpy(&new->user_buy[0][0],&p->user_buy[0][0],50*10); new->user_ticket=p->user_ticket; list_add_tail(&(new->list),&(head2->list)); return 0; } //显示注册用户的信息 void show_regist_list(struct user_information *head2) { int i,n; struct user_information *p=NULL; list_for_each_entry(p,&(head2->list),list) { printf("%s\n",p->user_account); printf("%s\n",p->user_mima); printf("%s\n",p->user_name); printf("%s\n",p->user_age); printf("%s\n",p->user_gender); printf("%d\n",p->user_balance); i=p->user_ticket; for(n=0;n<i;n++) { printf("%s\n",p->user_buy[n]); } } } //写入数据 int write_data(char data[][20],int n,struct flight_information *head) { struct flight_information *p; p=(struct flight_information *)malloc(sizeof(struct flight_information)); FILE *fp1 = fopen(data[n],"r+"); if(fp1==NULL) { printf("open file error!"); return -1; } char str[50] = {0}; fread(str,10,5,fp1); char seps[] = ","; char *tmp; tmp = strtok(str,seps); strcpy(p->number,tmp); tmp = strtok(NULL,seps); strcpy(p->begin,tmp); tmp = strtok(NULL,seps);; strcpy(p->end,tmp); tmp=strtok(NULL,seps); strcpy(p->day,tmp); tmp = strtok(NULL,seps); strcpy(p->type,tmp); tmp=strtok(NULL,seps); strcpy(p->time,tmp); tmp=strtok(NULL,seps); p->price=atoi(tmp); //尾插到头节点 add_tail_list(head,p->number,p->begin,p->end,p->day,p->type,p->time,p->price); fclose(fp1); free(p); return 0; } //读取文件夹内的内容并赋值给p int read_data(struct flight_information *head,int modify) { int i,n; //打开文件夹 DIR *fp=opendir("./data"); if(fp==NULL) { printf("open dir error!"); return -1; } struct dirent *ep=NULL; //判断文件数量 i=file_number(ep,fp); char data[i][20]; //存储名字 store_array(data,ep,fp,i); if(modify==0) { chdir("./data"); for(n=2;n<i;n++) { write_data(data,n,head); } chdir("../"); } closedir(fp); return 0; } //显示信息 void show_list(struct flight_information *head) { struct flight_information *p=NULL; printf("*****************************************************************************\n"); printf("number begin->end day type time price \n"); list_for_each_entry(p,&(head->list),list) { printf("%s %s->%s %s %s %s %d \n",p->number,p->begin,p->end,p->day,p->type,p->time,p->price); } printf("****************************************************************************\n"); printf("1.User 2.Query 3.Quicky query 4.Administrators 5. closeserver 6.exit\n"); printf("****************************************************************************\n"); } //显示航班 void write_message(struct flight_information *head,int modify) { //读取文件夹内的内容并赋值给p read_data(head,modify); //显示航班信息 show_list(head); } //根据日期,起飞时间,型号查找航班 void query(struct flight_information *head) { int i=0; char buf[20]={0}; printf("Please enter date or departure time or model number:"); scanf("%s",buf); struct flight_information *p = NULL; list_for_each_entry(p,&(head->list),list) { if(strcmp(buf,p->day)==0) { printf("%s %s->%s %s %s %s %d \n",p->number,p->begin,p->end,p->day,p->type,p->time,p->price); i=1; } else if(strcmp(buf,p->begin)==0) { printf("%s %s->%s %s %s %s %d \n",p->number,p->begin,p->end,p->day,p->type,p->time,p->price); i=1; } else if(strcmp(buf,p->type)==0) { printf("%s %s->%s %s %s %s %d \n",p->number,p->begin,p->end,p->day,p->type,p->time,p->price); i=1; } } if(i==0) { printf("No flight information!\n"); } } //快速查询 void quicky_query(struct flight_information *head) { int i=0; char buf[20]={0}; printf("number:"); scanf("%s",buf); struct flight_information *p = NULL; list_for_each_entry(p,&(head->list),list) { if(strcmp(buf,p->number)==0) { printf("%s %s->%s %s %s %s %d \n",p->number,p->begin,p->end,p->day,p->type,p->time,p->price); i=1; } } if(i==0) { printf("No flight information!\n"); } } //判断管理员密码用户名 int judge_admima(int n,char name[][20],char *buf) { chdir("./administrators"); char mima[20]; FILE *fp1 = fopen(name[n],"r+"); if(fp1==NULL) { printf("open file error!"); return -1; } char str[50] = {0}; fread(str,10,5,fp1); char seps[] = ","; char *tmp; tmp = strtok(str,seps); if(strcmp(buf,tmp)==0) { printf("Please input a password:"); scanf("%s",mima); tmp = strtok(NULL,seps); if(strcmp(mima,tmp)==0) { chdir("../"); fclose(fp1); return 1; } else { chdir("../"); fclose(fp1); return -2; } } else { chdir("../"); fclose(fp1); return 0; } } //增加航班 void increase_flights(struct flight_information *head) { char number[15]; char number2[15]; char number3[15]; char begin[20]; char begin2[20]; char end[20]; char end2[20]; char day[30]; char day2[30]; char type[5]; char type2[5]; char time[20]; char time2[20]; int price; int i,n,k,j,m; struct flight_information *p=NULL; while(1) { a:printf("please input flight number or intput 5 exit:"); scanf("%s",number); //判断航班号是否存在 list_for_each_entry(p,&(head->list),list) { if(strcmp(p->number,number)==0) { printf("number is existence!\n"); goto a; } } //判断number格式是否及格 if(strcmp(&number[0],"5")==0) { return; } if(isupper(number[0])==0) { goto a; } i=strlen(number); for(n=1;n<i;n++) { if(isdigit(number[n])==0) { goto a; } } break; } b:printf("please input begin or intput 5 exit:"); scanf("%s",begin); k=strlen(begin); if(strcmp(&begin[0],"5")==0) { return; } for(n=0;n<k;n++) { if(isupper(begin[n])==0) { goto b; } } c:printf("please input end or intput 5 exit:"); scanf("%s",end); j=strlen(end); if(strcmp(&end[0],"5")==0) { return; } for(n=0;n<j;n++) { if(isupper(end[n])==0) { goto c; } } printf("please input day or intput 5 exit:"); scanf("%s",day); if(strcmp(&day[0],"5")==0) { return; } d:printf("please input types or intput 5 exit:"); scanf("%s",type); if(strcmp(&type[0],"5")==0) { return; } m=strlen(type); for(n=0;n<m;n++) { if(isupper(type[n])==0) { goto d; } } printf("please input time or intput 5 exit:"); scanf("%s",time); if(strcmp(&day[0],"5")==0) { return; } printf("please input price:"); scanf("%d",&price); chdir("./data"); strcpy(number2,number); strcpy(number3,number); strcat(number2,","); strcat(number,".txt"); FILE *fp=fopen(number,"w+"); { if(fp==NULL) { printf("open file fail!\n"); return; } } fwrite(number2,strlen(number2),1,fp); strcpy(begin2,begin); strcat(begin,","); fwrite(begin,strlen(begin),1,fp); strcpy(end2,end); strcat(end,","); fwrite(end,strlen(end),1,fp); strcpy(day2,day); strcat(day,","); fwrite(day,strlen(day),1,fp); strcpy(type2,type); strcat(type,","); fwrite(type,strlen(type),1,fp); strcpy(time2,time); strcat(time,","); fwrite(time,strlen(time),1,fp); fprintf(fp,"%d",price); add_tail_list(head,number3,begin2,end2,day2,type2,time2,price); chdir("../"); fclose(fp); } //删除航班 int delete_flights(struct flight_information *head,char *bmp) { struct flight_information *p=NULL; char number[10]; char buf[30]; while(1) { a:printf("please input a flight number or input 5 exit:"); scanf("%s",number); if(strcmp(&number[0],"5")==0) { return 0; } chdir("./data"); list_for_each_entry(p,&(head->list),list) { if(strcmp(p->number,number)==0) { sprintf(buf,"rm %s.txt",p->number); system(buf); list_del(&(p->list)); free(p); chdir("../"); return 1; } } chdir("../"); show_bmp(bmp); goto a; } } //修改用户密码 int change_password(char *buf) { char buf1[20]; char buf2[20]; char mima[20]; char mima2[20]; chdir("./administrators"); sprintf(buf1,"%s.txt",buf); FILE *fd=fopen(buf1,"r+"); printf("inuput your old mima :"); scanf("%s",mima); char str[50] = {0}; char seps[] = ","; fread(str,10,5,fd); char *tmp; tmp = strtok(str,seps); tmp = strtok(NULL,seps); if(strcmp(tmp,mima)==0) { fclose(fd); FILE *fp=fopen(buf1,"w+"); printf("inuput your new mima :"); scanf("%s",mima2); sprintf(buf2,"%s,",buf); fwrite(buf2,strlen(buf2),1,fp); fwrite(mima2,strlen(mima2),1,fp); fclose(fp); chdir("../"); return 1; } printf("mima is error!\n"); chdir("../"); return 0; } //管理员功能界面 void administrators_fun(struct flight_information *head,char *bmp,char *buf,int flag,int connfd) { int i,j,k; char rcv_buf[10]; while(1) { char bmp2[1][10]; strcpy(bmp2[0],"7.bmp"); int n; system("clear"); printf("*******************************************************************\n"); printf("1.Increase flights 2.Delete flights 3.Change Password 4.exit\n"); printf("*******************************************************************\n"); show_bmp(bmp2[0]); if(flag == 0) n=ad_jiemian_touch(); if(flag == 1) { bzero(rcv_buf,10); recv(connfd,rcv_buf,10,0); n = atoi(rcv_buf); } switch(n) { case 1: increase_flights(head); break; case 2: j=delete_flights(head,bmp); if(j==1) printf("delete_flights successful!\n"); break; case 3: change_password(buf); break; case 4: return; default: break; } } } //管理员文档的读取 int administrators(struct flight_information *head,char *bmp,int flag,int connfd) { char buf[20]; char nobuf[10] = "no"; char yesbuf[10] = "yes"; int i,n,j; j=0; //输入账户 printf("Please enter your ad account:"); scanf("%s",buf); //打开文件夹 DIR *fp=opendir("./administrators"); if(fp==NULL) { printf("open dir error!"); return -1; } struct dirent *p=NULL; i=file_number(p,fp); char name[i][20]; //写入数组中 store_array(name,p,fp,i); for(n=2;n<i;n++) { j=j+judge_admima(n,name,buf); } printf("%d",j); if(j==0) { printf("account is error!\n"); if(flag == 1) { send(connfd,nobuf,10,0); } } else if(j==-2) { printf("mima is error!\n"); if(flag == 1) { send(connfd,nobuf,10,0); } } else if(j==1) { //登录成功 if(flag == 1) { int ret = send(connfd,yesbuf,10,0); printf("ret = %d\n",ret); //sleep(1); } printf("succesful landing!\n"); administrators_fun(head,bmp,buf,flag,connfd); } closedir(fp); } //注册功能 int registe(struct user_information *head2,int modify) { int i,n; //数据指针 struct user_information *p=NULL; struct user_information *q=NULL; DIR *fp=opendir("./usr"); { if(fp==NULL) { printf("opendir fail!\n"); return -1; } } struct dirent *ep=NULL; i=file_number(ep,fp); char data[i][20]; store_array(data,ep,fp,i); p=(struct user_information *)malloc(sizeof(struct user_information)); printf("please input your account:"); scanf("%s",p->user_account); if(modify==0) { i=read_user_information(head2,modify); } list_for_each_entry(q,&(head2->list),list) { if(strcmp(q->user_account,p->user_account)==0) { printf("account is existence!\n"); return 0; } } chdir("./usr"); printf("please input your mima:"); scanf("%s",p->user_mima); printf("please input your name:"); scanf("%s",p->user_name); printf("please input your age:"); scanf("%s",p->user_age); printf("please input your gender(man 1 women 2):"); scanf("%s",p->user_gender); p->user_balance=0; p->vip=0; p->user_ticket=0; char buf[20]={0}; char buf1[20]={0}; char buf2[20]={0}; char buf3[20]={0}; char buf4[20]={0}; char buf5[20]={0}; sprintf(buf,"%s.txt",p->user_account); FILE *fd=fopen(buf,"w+"); sprintf(buf1,"%s,",p->user_account); fwrite(buf1,strlen(buf1),1,fd); sprintf(buf2,"%s,",p->user_mima); fwrite(buf2,strlen(buf2),1,fd); sprintf(buf3,"%s,",p->user_name); fwrite(buf3,strlen(buf3),1,fd); sprintf(buf4,"%s,",p->user_age); fwrite(buf4,strlen(buf4),1,fd); sprintf(buf5,"%s,",p->user_gender); fwrite(buf5,strlen(buf5),1,fd); fprintf(fd,"%d,",p->user_balance); fprintf(fd,"%d,",p->vip); add_registe_tail(head2,p); chdir("../"); fclose(fd); return 1; } //写入文件到链表中 int write_user_data(char data[][20],int n,struct user_information *head2) { int i; i=0; struct user_information *p=NULL; p=(struct user_information *)malloc(sizeof(struct user_information)); FILE *fp1 = fopen(data[n],"r+"); if(fp1==NULL) { printf("open file error!"); return -1; } char str[50] = {0}; fread(str,10,5,fp1); char seps[] = ","; char *tmp; tmp = strtok(str,seps); strcpy(p->user_account,tmp); tmp = strtok(NULL,seps); strcpy(p->user_mima,tmp); tmp = strtok(NULL,seps);; strcpy(p->user_name,tmp); tmp=strtok(NULL,seps); strcpy(p->user_age,tmp); tmp = strtok(NULL,seps); strcpy(p->user_gender,tmp); tmp=strtok(NULL,seps); p->user_balance=atoi(tmp); tmp=strtok(NULL,seps); p->vip=atoi(tmp); for(n=0;tmp!=NULL;n++) { tmp=strtok(NULL,seps); if(tmp ==NULL) break; strcpy(p->user_buy[n],tmp); i=n+1; } p->user_ticket = i; add_registe_tail(head2,p); fclose(fp1); } //读取文件夹中的数据并存储到链表中 int read_user_information(struct user_information *head2,int modify) { int i,n; //打开文件夹 DIR *fp=opendir("./usr"); if(fp==NULL) { printf("open dir error!"); return -1; } struct dirent *ep=NULL; //判断文件数量 i=file_number(ep,fp); char data[i][20]; //存储名字 store_array(data,ep,fp,i); chdir("./usr"); if(modify==0) { for(n=2;n<i;n++) { write_user_data(data,n,head2); } } chdir("../"); if(n==2) { printf("No user exists!please registe!\n"); return n; } closedir(fp); } //将数据重新写入到文件中 void write_agin(struct user_information *p,int i) { int k; char buf[20]={0}; char buf1[20]={0}; char buf2[20]={0}; char buf3[20]={0}; char buf4[20]={0}; char buf5[20]={0}; char buf6[50][10]={0}; sprintf(buf,"%s.txt",p->user_account); FILE *fd=fopen(buf,"w+"); { if(fd==NULL) printf("open file fail!\n"); } sprintf(buf1,"%s,",p->user_account); fwrite(buf1,strlen(buf1),1,fd); sprintf(buf2,"%s,",p->user_mima); fwrite(buf2,strlen(buf2),1,fd); printf("%s\n",buf2); sprintf(buf3,"%s,",p->user_name); fwrite(buf3,strlen(buf3),1,fd); sprintf(buf4,"%s,",p->user_age); fwrite(buf4,strlen(buf4),1,fd); sprintf(buf5,"%s,",p->user_gender); fwrite(buf5,strlen(buf5),1,fd); fprintf(fd,"%d,",p->user_balance); fprintf(fd,"%d,",p->vip); for(k=0;k<i;k++) { sprintf(buf6[k],"%s,",p->user_buy[k]); fwrite(buf6[k],strlen(buf6[k]),1,fd); } fclose(fd); } //买票功能 int buy_ticket(struct user_information *p,struct flight_information *head) { int i,n; char ticket[10]; char ticket1[10]; char account[20]; struct flight_information *q=NULL; printf("Please enter the flight number you want to purchase:"); scanf("%s",ticket); i=p->user_ticket; for(n=0;n<i;n++) { if(strcmp(p->user_buy[n],ticket)==0) { printf("ticket has been purchase!\n"); return -1; } } list_for_each_entry(q,&(head->list),list) { if(strcmp(q->number,ticket)==0) { if(p->user_balance > q->price) { chdir("./usr"); strcpy(p->user_buy[i],ticket); if(p->vip==1) { p->user_balance=p->user_balance-(0.8 * q->price); } else { p->user_balance=p->user_balance-q->price; } p->user_ticket=p->user_ticket+1; i=i+1; write_agin(p,i); chdir("../"); return 1; } return -2; } } return 0; } //查询买过的票功能 void query_buy_ticket(struct user_information *p) { int i,n; i=p->user_ticket; for(n=0;n<i;n++) { printf("%s\n",p->user_buy[n]); } } //退票 int exit_ticket(struct user_information *p,struct flight_information *head) { struct flight_information *q=NULL; int i,n,j,price; char ticket[10]; char account[10]; printf("Please enter the tickets you have purchased:"); scanf("%s",ticket); i=p->user_ticket; for(n=0;n<i;n++) { if(strcmp(p->user_buy[n],ticket)==0) { list_for_each_entry(q,&(head->list),list) { if(strcmp(q->number,ticket)==0) price=q->price; } bzero(p->user_buy[n],sizeof(p->user_buy[n])); for(j=n+1;j<i;j++) { strcpy(p->user_buy[n],p->user_buy[j]); n=n+1; } p->user_ticket=p->user_ticket-1; p->user_balance=p->user_balance+0.8 * price; i=i-1; chdir("./usr"); write_agin(p,i); printf("succesful refund!\n"); chdir("../"); return 1; } } printf("refund fail!\n"); return 0; } //改票 int change_ticket(struct user_information *p,struct flight_information *head) { int n,i,price; struct flight_information *q=NULL; struct flight_information *k=NULL; char ticket[10]; char ticket2[10]; char account[10]; printf("Please enter the tickets you have purchased:"); scanf("%s",ticket); i=p->user_ticket; for(n=0;n<i;n++) { if(strcmp(p->user_buy[n],ticket)==0) { printf("Please enter the tickets you want retund:"); scanf("%s",ticket2); list_for_each_entry(k,&(head->list),list) { if(strcmp(k->number,ticket)==0) { price=k->price; } } list_for_each_entry(q,&(head->list),list) { if(strcmp(q->number,ticket2)==0) { if(q->price > price) { if(p->user_balance > (q->price-price)) { p->user_balance=p->user_balance-(q->price-price); } else { return -2; } } strcpy(p->user_buy[n],ticket2); chdir("./usr"); write_agin(p,i); printf("succesful change!\n"); chdir("../"); return 1; } } return 0; } } return -1; } //充值功能 int invest_money(struct user_information *p) { int recharged,i,j; printf("Please enter the amount to be recharged:"); scanf("%d",&recharged); printf("would you like pay 1000 to be vip?yes1 or no2:"); scanf("%d",&i); j=p->user_ticket; if(i==1) { if((p->user_balance+recharged)<1000) { p->user_balance=p->user_balance+recharged; printf("money is not enough!\n"); chdir("./usr"); write_agin(p,j); chdir("../"); return -2; } else if(p->vip==1) { p->user_balance=p->user_balance+recharged; printf("you have been a vip!\n"); chdir("./usr"); write_agin(p,j); chdir("../"); return 0; } else { p->user_balance=p->user_balance+recharged-1000; p->vip=1; chdir("./usr"); write_agin(p,j); printf("Congratulations on becoming VIP!\n"); chdir("../"); return 1; } } else { p->user_balance=p->user_balance+recharged; chdir("./usr"); write_agin(p,j); chdir("../"); return -1; } } //密码修改功能 int modify_mima(struct user_information *p) { int i; char mima[20]; char mima2[20]; printf("Please enter the original password:"); scanf("%s",mima); i=p->user_ticket; if(strcmp(p->user_mima,mima)==0) { printf("Please enter the new password:"); scanf("%s",mima2); strcpy(p->user_mima,mima2); chdir("./usr"); write_agin(p,i); chdir("../"); printf("modify mima successful!\n"); return 1; } else { printf("the original password is fail!\n"); return 0; } } //用户功能 void user_fun(struct user_information *p,struct flight_information *head,char *bmp,int flag,int connfd) { int n,j,i; char buf[10]; while(1) { //显示用户功能界面 char bmp2[1][10]; strcpy(bmp2[0],"6.bmp"); printf("****************************************************************************\n"); printf("1.buy_ticket 2.query_buy_ticket \n"); printf("3.exit_ticket 4.change_ticket \n"); printf("5.exit 6.invest_money 7.modify_mima \n"); printf("****************************************************************************\n"); show_bmp(bmp2[0]); if(flag == 0) { n=user_jiemian_touch(); } if(flag == 1) { bzero(buf,10); recv(connfd,buf,10,0); n = atoi(buf); } switch(n) { case 1: printf("begin buy_ticket!\n"); i=buy_ticket(p,head); if(i==1) printf("buy ticket successful!\n"); if(i==0) show_bmp(bmp); if(i==-2) printf("money not enough!\n"); break; case 2: query_buy_ticket(p); break; case 3: printf("begin exit_ticket!\n"); exit_ticket(p,head); break; case 4: printf("begin change_ticket!\n"); j=change_ticket(p,head); if(j==-1) printf("ticket is not purchase!\n"); if(j==0) printf("ticket is not existence\n"); if(j==-2) printf("money is not enough!\n"); break; case 5: return; case 6: printf("begin invest_money!\n"); invest_money(p); break; case 7: printf("begin modify_mima!\n"); modify_mima(p); break; default: break; } } } //登录 int sign_in(struct user_information *head2,int modify,struct flight_information *head,char *bmp,int flag,int connfd) { int i; //读取文件夹中的数据并存储到链表中 if(modify==0) { i=read_user_information(head2,modify); } if(i==2) { return 0; } char account[20]; char mima[20]; char yesbuf[10] = "yes"; char nobuf[10] = "no"; struct user_information *p=NULL; printf("input your account:"); scanf("%s",account); //判断用户是否已经注册 list_for_each_entry(p,&(head2->list),list) { if(strcmp(p->user_account,account)==0) { printf("please input your mima:"); scanf("%s",mima); if(strcmp(p->user_mima,mima)==0) { printf("landing is succesful!\n"); //登录成功发送消息 if(flag == 1) { send(connfd,yesbuf,10,0); } user_fun(p,head,bmp,flag,connfd); show_regist_list(head2); } else { if(flag == 1) { send(connfd,nobuf,10,0); } return -1; } } } return -2; } int searching_password(struct user_information *head2,int modify) { int i,j; char account[20]; char name[20]; char age[5]; char mima[20]; struct user_information *p=NULL; //读取文件夹中的数据并存储到链表中 if(modify==0) { i=read_user_information(head2,modify); } if(i==2) { return; } printf("intput your account:"); scanf("%s",account); list_for_each_entry(p,&(head2->list),list) { if(strcmp(p->user_account,account)==0) { printf("intput your name:"); scanf("%s",name); if(strcmp(p->user_name,name)==0) { printf("intput your age:"); scanf("%s",age); if(strcmp(p->user_age,age)==0) { j=p->user_ticket; printf("input your new mima:"); scanf("%s",mima); strcpy(p->user_mima,mima); chdir("./usr"); write_agin(p,j); chdir("../"); return 1; } return 0; } return -1; } } return -2; } //用户功能 void user(struct user_information *head2,struct flight_information *head,char *bmp,int flag,int connfd) { char bmp2[10][10]; strcpy(bmp2[0],"5.bmp"); int n,j,k,l,ret; int modify=0; char buf[10]; while(1) { printf("****************************************************************************\n"); printf("1.registe 2.sign_in 3.searching_password 4.exit \n"); printf("****************************************************************************\n"); show_bmp(bmp2[0]); if(flag == 0) n=denglu_jiemian_touch(); if(flag == 1) { bzero(buf,10); recv(connfd,buf,10,0); n = atoi(buf); } switch(n) { case 1: printf("registe is begin!\n"); l=registe(head2,modify); if(l==0) printf("account is existence!\n"); if(l==1) printf("successful regisit!\n"); modify=1; break; case 2: printf("sign_in is begin!\n"); k=sign_in(head2,modify,head,bmp,flag,connfd); modify=1; if(k==-1) printf("mima is error!\n"); if(k==-2) printf("account is error!\n"); break; case 3: printf("searching_password is begin!\n"); j=searching_password(head2,modify); modify=1; if(j==1) printf("searching successful!\n"); if(j==0) printf("age is error!\n"); if(j==-1) printf("name is error!\n"); if(j==-2) printf("account is error!\n"); break; case 4: return; default: break; } } }
C
#include "header.h" #include <stdio.h> int main(int argc, char const *argv[]) { int x,y, i ,j; printf("Input x and y\n"); scanf("%d%d", &x, &y); i = addition(x, y); j = substraction(x, y); printf("%d\n", i); printf("%d\n", j); return 0; }
C
// // scope.c // Heck // // Created by Mashpoe on 7/6/19. // #include <scope.h> #include <function.h> #include <code_impl.h> #include <class.h> #include <print.h> #include <stdio.h> #include "vec.h" heck_name* name_create(heck_code* c, heck_scope* parent, heck_idf_type type) { heck_name* name = malloc(sizeof(heck_name)); heck_add_name(c, name); name->type = type; name->value.class_value = NULL; // will set all fields to NULL name->parent = parent; name->child_scope = NULL; name->flags = 0x0; // set all flags to 0 return name; } heck_scope* scope_create(heck_code* c, heck_scope* parent) { heck_scope* scope = malloc(sizeof(heck_scope)); heck_add_scope(c, scope); scope->names = NULL; //scope->decl_vec = NULL; scope->var_inits = NULL; scope->parent = parent; scope->parent_nmsp = parent->parent_nmsp; scope->parent_class = parent->parent_class; scope->parent_func = parent->parent_func; return scope; } heck_scope* scope_create_global(heck_code* c) { heck_scope* scope = malloc(sizeof(heck_scope)); heck_add_scope(c, scope); scope->names = NULL; //scope->decl_vec = NULL; scope->var_inits = NULL; scope->parent = NULL; scope->parent_nmsp = scope; scope->parent_class = NULL; scope->parent_func = NULL; return scope; } // void free_name_callback(str_entry key, void* value, void* user_ptr) { // heck_name* name = value; // // printf("free %s\n", key->value); // switch(name->type) { // case IDF_VARIABLE: // // TODO: free variable // break; // case IDF_FUNCTION: { // heck_func_list* func_list = &name->value.func_value; // if (func_list->decl_vec != NULL) { // size_t num_decls = vector_size(func_list->decl_vec); // for (size_t i = 0; i < num_decls; ++i) { // free_decl_data(&func_list->decl_vec[i]); // } // vector_free(func_list->decl_vec); // } // if (func_list->def_vec != NULL) { // size_t num_defs = vector_size(func_list->def_vec); // for (size_t i = 0; i < num_defs; ++i) { // func_free(func_list->def_vec[i]); // } // vector_free(func_list->def_vec); // break; // } // } // case IDF_UNDECLARED_CLASS: // case IDF_CLASS: // // TODO: free class // break; // default: // break; // } // } // void scope_free(heck_scope* scope) { // if (scope->names != NULL) { // // free all items in the scope // idf_map_iterate(scope->names, free_name_callback, NULL); // // free the scope itself // idf_map_free(scope->names); // } // if (scope->var_inits != NULL) // vector_free(scope->var_inits); // free(scope); // } // use this function only when parsing a declaration or definition // finds a child of a scope, possibly multiple levels deep. // if the child cannot be found, it may be implicitly declared. // returns null on failure heck_name* scope_get_child(heck_code* c, heck_scope* scope, heck_idf idf) { // the current name as we iterate through the idf heck_name* name; // try to iterate through the tree of names int i = 0; do { if (scope->names == NULL) { scope->names = idf_map_create(); } else if (idf_map_get(scope->names, idf[i], (void*)&name)) { // access modifiers won't matter until resolving if (name->child_scope == NULL) { // return if there are no more children if (idf[++i] == NULL) return name; // we need to create children, check the identifier type first if (name->type == IDF_FUNCTION || name->type == IDF_VARIABLE) return NULL; // create a child, let the loop below do the rest of the work name->child_scope = scope_create(c, scope); scope = name->child_scope; scope->names = idf_map_create(); } else { // there is a child scope, so we can obviously continue scope = name->child_scope; // we can continue checking for children as long as they exist continue; } } // the above continue wasn't reached, so the child doesn't exist // we'll just create one instead for (;;) { name = name_create(c, scope, IDF_UNDECLARED); idf_map_set(scope->names, idf[i], name); if (idf[++i] == NULL) return name; // create a child scope name->child_scope = scope_create(c, scope); scope = name->child_scope; scope->names = idf_map_create(); } // we are done creating children return name; } while (idf[++i] != NULL); // if this is reached, the children were found without implicit declarations return name; } bool name_accessible(const heck_scope* parent, const heck_scope* child, const heck_name* name) { if (name->access == ACCESS_PUBLIC) return true; if (name->type == IDF_CLASS && parent->parent_class == child->parent_class) return true; if (name->access == ACCESS_PRIVATE || name->access == ACCESS_PROTECTED) { //vec_size_t size = vector_size(&((heck_class*)parent->class)->friends); //for (vec_size_t i = 0; i < size; ++i) {} return false; } return false; } heck_name* scope_resolve_idf(const heck_scope* parent, heck_idf idf) { // find the parent of the idf heck_name* name; while (parent->names == NULL || !idf_map_get(parent->names, idf[0], (void*)&name)) { // we have likely reached the global scope if parent->parent == NULL if (parent->parent == NULL) { //printf("not found idf: %i, %s\n", idf[0]->hash, idf[0]->value); return NULL; } parent = parent->parent; // check for the identifier in the parent nmsp } //printf("found idf: %i, %s\n", idf[0]->hash, idf[0]->value); /* we have found the parent of the identifier now find the identifier "children" if they exist */ int i = 1; while (idf[i] != NULL) { // keep track of child's child_scope as the parent of heck_scope* child_scope = name->child_scope; if (child_scope == NULL) return NULL; if (idf_map_get(child_scope->names, idf[i], (void*)&name)) { // TODO: check if private/protected/friend if (!name_accessible(parent, child_scope, name)) return NULL; } else { return NULL; } i++; } return name; } heck_name* scope_resolve_value(heck_code* c, heck_scope* parent, heck_expr_value* value) { switch (value->context) { case CONTEXT_LOCAL: return scope_resolve_idf(parent, value->idf); case CONTEXT_THIS: if (parent->parent_class == NULL || parent->parent_class->child_scope == NULL) return NULL; return scope_resolve_idf(parent->parent_class->child_scope, value->idf); case CONTEXT_GLOBAL: return scope_resolve_idf(c->global, value->idf); } } // helper struct for resolve_name_callback typedef struct resolve_name_data { heck_code* c; bool success; } resolve_name_data; void resolve_name_callback(str_entry key, void* value, void* user_ptr) { heck_name* name = value; resolve_name_data* data = user_ptr; switch (name->type) { case IDF_FUNCTION: { data->success *= func_resolve_name(data->c, name, key); break; } case IDF_UNDECLARED_CLASS: data->success = false; // fallthrough case IDF_CLASS: { data->success *= scope_resolve_names(data->c, name->child_scope); // TODO: resolve operator overloads break; } case IDF_UNDECLARED: { if (name->child_scope != NULL) { data->success *= scope_resolve_names(data->c, name->child_scope); } } } } bool scope_resolve_names(heck_code* c, heck_scope* scope) { if (scope->names == NULL) return true; // nothing to resolve resolve_name_data data = { .c = c, .success = true }; idf_map_iterate(scope->names, resolve_name_callback, (void*)&data); return data.success; } // void scope_add_decl(heck_scope* scope, heck_stmt* decl) { // if (scope->decl_vec == NULL) // scope->decl_vec = vector_create(); // vector_add(&scope->decl_vec, decl); // } // this could be made into a macro as a ternary expression //#define scope_is_class(scope) ((scope)->class == NULL ? false : (scope)->class->child_scope == (scope)) bool scope_is_class(heck_scope* scope) { if (scope->parent_class == NULL) return false; return scope->parent_class->child_scope == scope; } bool scope_var_is_init(heck_scope* scope, heck_name* var_name) { heck_variable* var_value = var_name->value.var_value; if (var_value->value != NULL) return true; do { if (scope->var_inits != NULL) { vec_size_t num_inits = vector_size(scope->var_inits); for (vec_size_t i = 0; i < num_inits; ++i) { if (scope->var_inits[i] == var_value) return true; } } scope = scope->parent; // possibly remove && scope != NULL } while(scope != var_name->parent && scope != NULL); return false; } // TODO: add vtables //bool resolve_scope(heck_scope* scope, heck_scope* global) { // if (scope->decl_vec == NULL) // return true; // // bool result = true; // // vec_size_t size = vector_size(scope->decl_vec); // for (vec_size_t i = 0; i < size; ++i) { // heck_stmt* current = scope->decl_vec[i]; // if (!current->vtable->resolve(current, scope, global)) // result = false; // } // // return result; //} void print_idf_map(str_entry key, void* value, void* user_ptr) { int indent = *(int*)user_ptr; heck_name* name = (heck_name*)value; switch (name->type) { case IDF_FUNCTION: print_func_decls(&name->value.func_value, key->value, indent); print_func_defs(&name->value.func_value, key->value, indent); return; break; case IDF_VARIABLE: print_indent(indent); printf("variable %s\n", key->value); return; break; // TODO: eliminate redundancies case IDF_UNDECLARED_CLASS: // fallthrough TODO: print undeclared case IDF_CLASS: { print_class(name, key->value, indent); break; } default: { for (int i = 0; i < indent; ++i) { printf("\t"); } printf("scope %s {\n", key->value); } } if (name->child_scope != NULL && name->child_scope->names != NULL) { ++indent; idf_map_iterate(name->child_scope->names, print_idf_map, (void*)&indent); --indent; } // closing bracket for (int i = 0; i < indent; ++i) { printf("\t"); } printf("}\n"); } void print_scope(heck_scope* scope, int indent) { if (scope->names != NULL) idf_map_iterate(scope->names, print_idf_map, (void*)&indent); }
C
#include <stdio.h> int main (void) { static int a = 2, b = 4, c = 8; static int *arr1[2] = {&a, &b}; static int *arr2[2] = {&b, &c}; int * (*arr[2]) [2] = {&arr1, &arr2}; printf("%d %d\n", *(*arr[0])[1], *(*(**(arr+1)+1))); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main() { FILE *f; f = fopen("a.txt", "w+"); for (int i = 10; i <= 100; i += 10) { fprintf(f, "%d\n", i); } fclose(f); }
C
/*Faça uma função que inverta dois valores passados como parâmetros para a função. Mostre os valores invertidos antes e após a chamada da função Você deve passar os valores por referência*/ #include<stdio.h> #include<stdlib.h> invert(int *pa,int *pb){ int aux = *pa; *pa=*pb; *pb=aux; } int main () { int a,b; scanf("%d %d",&a,&b); printf("%d %d",a,b); invert(&a,&b); printf("\n %d %d",a,b); return 0; }
C
/* 1742 ϴ Ϸ ߴ. 4 ū ¦ Ȧ Ҽ Ÿ ִ , 8 = 3 + 5. Both 3 and 5 are odd prime numbers. 20 = 3 + 17 = 7 + 13. 42 = 5 + 37 = 11 + 31 = 13 + 29 = 19 + 23. ´ ƴ ʾ ݷʵ ã ߴ. ؾ 鸸 ̸ ¦ ־ Ȧ Ҽ ǥ ִ ˾ƺ ̴. Է 6 ̻ 1000000 ̸ ¦ n Է ־. Ҽ a , b ǥõ n = a + b Ѵ. ׷ "Goldbach's conjecture is wrong." ǥѴ. b - a ִ Ѵ. Է 8 8 = 3 + 5 Է 20 20 = 3 + 17 Է 42 42 = 5 + 37 */ #include <stdio.h> #include <stdlib.h> int main(){ int i,n; int pn(int a){ int j; for(j=(int)sqrt((double)a);j>1;j--){ if(a%j==0) break; } if(j==1) return 1; else return 0; } scanf("%d",&n); for(i=2;i<=n/2;i++){ if(pn(i)&&pn(n-i)){ printf("%d = %d + %d\n",n,i,n-i); break; } } if(i>n/2) printf("Goldbach's conjecture is wrong."); system("pause"); return 0; }
C
// BUBBLE SORT #include <iostream> using namespace std; int main() { int i,t,temp,flag,a[100]; cout<<"Enter the number of elements in the array :"; cin>>t; cout<<"Enter the elements:"<<endl; for(i=0;i<t;i++) { cin>>a[i]; } //IMPLEMENTING BUBBLE SORT do { flag = 0; for(i=0;i<t-1;i++) { if(a[i+1]<a[i]) { temp=a[i]; a[i]=a[i+1]; a[i+1]=temp; flag = 1; } } }while(flag==1); cout<<endl<<"The sorted array is :"<<endl; for(i=0;i<t;i++) { cout<<a[i]<<endl; } return 0; }
C
#include<stdio.h> #define POWER 12.34 int main() { //int a=POWER; printf("%d\n",POWER); //printf("a=%d",a); //printf("%s\n",POWER); //printf("%f\n",POWER); printf("%.1lf",POWER); return 1; }
C
//* Problem: 1097 (Sequence IJ 3) #include <stdio.h> int main(void) { int i, j; for (i = 1; i <= 9; i += 2) { for (j = 0; j < 3; j--) { printf("I=%d J=%d\n", i, j); j += 2; } } return 0; } //or #include <stdio.h> int main(void) { int I, J, Q = 7; for (I = 1; I <= 9; I += 2) { for (J = 0; J < 3; J++) { printf("I=%d J=%d\n", I, Q); Q--; } Q = Q + 5; //after 3 time loop Q value now 4; So add 5 } }
C
#include "directory.h" #include "constants.h" #include "types.h" #include "fat.h" #include "macros.h" #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <string.h> DirectoryEntry deserialize_directory_entry( const unsigned char* serialized_directory_entry ) { const unsigned char fat_entry_buffer[3] = { serialized_directory_entry[DIRECTORY_ENTRY_SIZE_IN_BYTES - 3], serialized_directory_entry[DIRECTORY_ENTRY_SIZE_IN_BYTES - 2], serialized_directory_entry[DIRECTORY_ENTRY_SIZE_IN_BYTES - 1], }; const FatTableEntry fat_table_entry = deserialize_fat_entry(fat_entry_buffer); DirectoryEntry entry = { .first_fat_table_record = fat_table_entry }; strcpy(entry.filename, (char*)serialized_directory_entry); return entry; } DirectoryFile deserialize_directory_file( const unsigned char* serialized_directory_file ) { const unsigned char capacity = (unsigned char)deserialize_fat_entry(&serialized_directory_file[0]); const unsigned char length = (unsigned char)deserialize_fat_entry(&serialized_directory_file[1]); DirectoryFile directory = { .capacity = capacity, .length = length, }; for (size_t i = 0; i < ROOT_DIRECTORY_MAX_FILES; i++) { directory.directory_entries[i] = deserialize_directory_entry(&serialized_directory_file[2 + (i * DIRECTORY_ENTRY_SIZE_IN_BYTES)]); } return directory; } void serialize_directory_entry( const DirectoryEntry* entry, unsigned char* output ) { strcpy((char*)output, entry->filename); unsigned char fat_table_entry_buffer[] = INITIALIZE(3, 0); serialize_fat_entry(entry->first_fat_table_record, fat_table_entry_buffer); output[DIRECTORY_ENTRY_SIZE_IN_BYTES - 3] = fat_table_entry_buffer[0]; output[DIRECTORY_ENTRY_SIZE_IN_BYTES - 2] = fat_table_entry_buffer[1]; output[DIRECTORY_ENTRY_SIZE_IN_BYTES - 1] = fat_table_entry_buffer[2]; } void serialize_directory_file( const DirectoryFile* directory, unsigned char* output ) { unsigned char int_serialization_buffer[] = INITIALIZE(3, 0); serialize_fat_entry(directory->capacity, int_serialization_buffer); output[0] = int_serialization_buffer[0]; serialize_fat_entry(directory->length, int_serialization_buffer); output[1] = int_serialization_buffer[0]; for (size_t i = 0; i < directory->length; i++) { serialize_directory_entry( &directory->directory_entries[i], &output[2 + (i * DIRECTORY_ENTRY_SIZE_IN_BYTES)] ); } } DirectoryFile load_directory_file() { FILE* fp = fopen(DIRECTORY_FILENAME, "rb"); if (fp == NULL) { fprintf( stderr, "Error opening directory file. Try partitioning again.\n" ); exit(errno); } unsigned char buffer[ROOT_DIRECTORY_MAX_FILES * DIRECTORY_ENTRY_SIZE_IN_BYTES + 3 * 2] = { 0 }; fread(buffer, sizeof buffer, 1, fp); fclose(fp); return deserialize_directory_file(buffer); } void persist_directory(const DirectoryFile* directory) { FILE* fp = fopen(DIRECTORY_FILENAME, "w+b"); if (fp == NULL) { fprintf( stderr, "Error opening directory file. Try partitioning again.\n" ); exit(errno); } unsigned char buffer[ROOT_DIRECTORY_MAX_FILES * DIRECTORY_ENTRY_SIZE_IN_BYTES + 3 * 2] = { 0 }; serialize_directory_file(directory, buffer); fwrite(buffer, sizeof buffer, 1, fp); fclose(fp); return; } void insert_directory_entry( DirectoryFile* directory_file, const DirectoryEntry* directory_entries ) { directory_file->directory_entries[directory_file->length++] = *directory_entries; } bool directory_is_full(const DirectoryFile* directory_file) { return directory_file->length == directory_file->capacity; } bool filename_exists_in_directory( const DirectoryFile* directory, const char* filename ) { for (size_t i = 0; i < ROOT_DIRECTORY_MAX_FILES; i++) { if (strcmp(filename, directory->directory_entries[i].filename) == 0) { return true; } } return false; } FatTableEntry get_file_fat_first_entry( const DirectoryFile* directory, const char* filename ) { for (size_t i = 0; i < ROOT_DIRECTORY_MAX_FILES; i++) { if (strcmp(filename, directory->directory_entries[i].filename) == 0) { return directory->directory_entries[i].first_fat_table_record; } } return -1; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef int /*<<< orphan*/ u8 ; typedef int /*<<< orphan*/ u16 ; typedef int /*<<< orphan*/ ostream_t ; typedef int /*<<< orphan*/ istream_t ; typedef scalar_t__ i64 ; typedef int /*<<< orphan*/ FSE_dtable ; /* Variables and functions */ int /*<<< orphan*/ FSE_decode_symbol (int /*<<< orphan*/ const* const,int /*<<< orphan*/ *,int /*<<< orphan*/ const* const,scalar_t__*) ; int /*<<< orphan*/ FSE_init_state (int /*<<< orphan*/ const* const,int /*<<< orphan*/ *,int /*<<< orphan*/ const* const,scalar_t__*) ; int /*<<< orphan*/ FSE_peek_symbol (int /*<<< orphan*/ const* const,int /*<<< orphan*/ ) ; int /*<<< orphan*/ INP_SIZE () ; int /*<<< orphan*/ * IO_get_read_ptr (int /*<<< orphan*/ * const,size_t const) ; size_t IO_istream_len (int /*<<< orphan*/ * const) ; int /*<<< orphan*/ IO_write_byte (int /*<<< orphan*/ * const,int /*<<< orphan*/ ) ; int highest_set_bit (int /*<<< orphan*/ const) ; __attribute__((used)) static size_t FSE_decompress_interleaved2(const FSE_dtable *const dtable, ostream_t *const out, istream_t *const in) { const size_t len = IO_istream_len(in); if (len == 0) { INP_SIZE(); } const u8 *const src = IO_get_read_ptr(in, len); // "Each bitstream must be read backward, that is starting from the end down // to the beginning. Therefore it's necessary to know the size of each // bitstream. // // It's also necessary to know exactly which bit is the latest. This is // detected by a final bit flag : the highest bit of latest byte is a // final-bit-flag. Consequently, a last byte of 0 is not possible. And the // final-bit-flag itself is not part of the useful bitstream. Hence, the // last byte contains between 0 and 7 useful bits." const int padding = 8 - highest_set_bit(src[len - 1]); i64 offset = len * 8 - padding; u16 state1, state2; // "The first state (State1) encodes the even indexed symbols, and the // second (State2) encodes the odd indexes. State1 is initialized first, and // then State2, and they take turns decoding a single symbol and updating // their state." FSE_init_state(dtable, &state1, src, &offset); FSE_init_state(dtable, &state2, src, &offset); // Decode until we overflow the stream // Since we decode in reverse order, overflowing the stream is offset going // negative size_t symbols_written = 0; while (1) { // "The number of symbols to decode is determined by tracking bitStream // overflow condition: If updating state after decoding a symbol would // require more bits than remain in the stream, it is assumed the extra // bits are 0. Then, the symbols for each of the final states are // decoded and the process is complete." IO_write_byte(out, FSE_decode_symbol(dtable, &state1, src, &offset)); symbols_written++; if (offset < 0) { // There's still a symbol to decode in state2 IO_write_byte(out, FSE_peek_symbol(dtable, state2)); symbols_written++; break; } IO_write_byte(out, FSE_decode_symbol(dtable, &state2, src, &offset)); symbols_written++; if (offset < 0) { // There's still a symbol to decode in state1 IO_write_byte(out, FSE_peek_symbol(dtable, state1)); symbols_written++; break; } } return symbols_written; }
C
#include<stdio.h> #define max 50 void insert_sort(int a[],int n) { int i,j,k; for(i=1;i<n;i++) { for(j=i-1;j>=0;j--) if(a[j]<a[i]) break; if(j!=i-1) { int temp=a[i]; for(k=i-1;k>j;k--) a[k+1]=a[k]; a[k+1]=temp; } } } void main() { int i,n; int a[max]; printf("鳤ȣ"); scanf("%d",&n); printf("飺"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("ǰ飺"); for(i=0;i<n;i++) printf("%d ",a[i]); printf("\n"); insert_sort(a,n); printf("飺"); for(i=0;i<n;i++) printf("%d ",a[i]); printf("\n"); }
C
/* Написать программу для перевод символов в верхний регистр. Входные данные: Одни символ в нижнем регистре. Выходные данные: Тот же самый символ, но в верхнем регистре. Подсказки: Обратите внимание на расстояние в таблице ASCII между одинаковыми буквами в разных регистрах. Например, между a и A, или h и H. Sample Input: q Sample Output: Q */ #include <stdio.h> #include <string.h> int main(void) { char str1[2]; fgets(str1, 2, stdin); printf("%c", str1[0]-32); fflush(stdin); return 0; } /* * better code * #include <stdio.h> int main() { char a; scanf("%c", &a); printf("%c", a-32); } */
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <netdb.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <arpa/inet.h> #include "encrypt.h" /*Function to establish connection with server and transfer data */ int transferfunction(char *host, char *port, char *filename) { int sockfdc, numbytesc; char *buf; struct addrinfo hintsc, *servinfoc, *pc; int rvc, result; struct sockaddr_in sa; char s[INET6_ADDRSTRLEN]; FILE *fp; size_t filesize; int count; memset(&hintsc, 0, sizeof hintsc); hintsc.ai_family = AF_UNSPEC; hintsc.ai_socktype = SOCK_STREAM; fp=fopen(filename, "r"); filesize = getfilesize(filename); buf = malloc(100 * sizeof(char)); printf("Beginning Transfer\n"); /* Get linked list of connections from kernel */ if ((rvc = getaddrinfo(host, port, &hintsc, &servinfoc)) != 0) { printf("Getaddrinfo %s\n", gai_strerror(rvc)); return 1; } /* loop through all the results and connect to the first we can */ for(pc = servinfoc; pc != NULL; pc = pc->ai_next) { if ((sockfdc = socket(pc->ai_family, pc->ai_socktype, pc->ai_protocol)) == -1) { perror("client: socket"); continue; } if (connect(sockfdc, pc->ai_addr, pc->ai_addrlen) == -1) { close(sockfdc); perror("client: connect"); continue; } break; } if (pc == NULL) { printf("Client failed to connect\n"); return 2; } inet_ntop(pc->ai_family,&(sa.sin_addr),s, sizeof s); printf("client connecting to %s\n", s); freeaddrinfo(servinfoc); /* Keep sending data as until the end of file */ while( !feof( fp ) ) { /* Attempt to read in 100 bytes: */ count = fread( buf, sizeof( char ), 100, fp ); if( ferror( fp ) ) { perror( "Read error" ); break; } /* Send 100 bytes of data to server */ if (send(sockfdc, buf, count, 0) == -1) { perror("send"); } } printf("Client sent data to server successfully\n"); close(sockfdc); return 0; }
C
/* ** EPITECH PROJECT, 2018 ** lemIPC ** File description: ** commander.c */ #include <stdio.h> #include <memory.h> #include <zconf.h> #include "../../include/lemipc.h" static int count_players(commander_t *cmd) { int count = 0; size_t h = cmd->mem->height; size_t w = cmd->mem->width; for (size_t i = 0 ; i < h * w ; i++) { if (cmd->mem->map[i / h][i % w] == cmd->team_id) count++; } return (count); } /* ** Description: ** This function init the content of the commander struct. */ static int init_commander(lemipc_t *lem, commander_t *commander) { char *str = NULL; commander->mem = lem->mem; commander->shm_id = lem->shm_id; commander->sem_id = lem->sem_id; commander->msg_id = lem->msg_id; commander->tx = rand_nbr(lem->mem->width); commander->ty = rand_nbr(lem->mem->height); commander->team_id = lem->args->team_id; commander->p_count = count_players(commander); commander->game_started = 0; asprintf(&str, "2;%d;1", commander->team_id); send_message(commander->msg_id, LOG_CHANNEL, str); free(str); return (0); } static int commander_actions(commander_t *c) { char *order; update_connections(c); if (find_target(c)) { c->game_started = 1; asprintf(&order, "2;%d;3;%d;%d", c->team_id, c->tx, c->ty); for (int i = 0 ; i < c->p_count ; i++) { send_message(c->msg_id, c->team_id + 1, order); } send_message(c->msg_id, LOG_CHANNEL, order); free(order); } else if (c->game_started && !count_players(c)) return (0); else { c->tx = rand_nbr(c->mem->width); c->ty = rand_nbr(c->mem->height); } return (1); } static void *start_commander(void *arg) { lemipc_t *lem = arg; commander_t cmd; char *str; int still_continue = 1; init_commander(lem, &cmd); while (CONTINUE && still_continue) { if (!commander_actions(&cmd)) still_continue = 0; usleep(100000); } asprintf(&str, "2;%d;2", cmd.team_id); send_message(cmd.msg_id, cmd.team_id + 1, str); send_message(cmd.msg_id, LOG_CHANNEL, str); free(str); return ("OK"); } int create_commander(lemipc_t *lem) { int ret = 0; printf("A Commander has been created\n"); ret = pthread_create(&lem->cmd, NULL, &start_commander, lem); if (ret != 0) perror("pthread_create"); return (ret); }
C
/* -- run -- gcc file.c -o outfile -lm (why using lm when using ceil function.) The median of an array of numbers is the element m of the array such that half the remaining numbers in the array are greater then or equal to m and half are less than or equal to m, if the number of elements in the array is odd. if the number of elements is even, the median is average of the two elements m1 and m2 such that half the remaining elements are greater then or equal to m1 and m2 , and half the elements are less than or equal to m1 and m2. Write a C function that acccepts an array of numbers and returns the median of the numbers in the array. steps-1: get array and count of element in array. step-2: sort step-3: if count == 'odd': get one element at (count + 1)/2 else step-4 step-4: get element at count/2 and (count+1)/2 step-5: calc "mean/avg" of two elements get at step-4 step-6: return val from step-3 or step-5 */ #include <stdio.h> #include <math.h> #include "lib/sorts.h" extern void bubble_sort_with_if_no_match(double [], int); double get_median(double [], int); int is_even(int); #define ARR_SIZE 24 int main(int argc, char const *argv[]) { int i; double arr[] = {21,100,1,2,3,5,6,4,7,8,9,10,11,2,88,13,14,15,16,17,18,19,20,21}; double median; median = get_median(arr, ARR_SIZE); for (i = 0; i < ARR_SIZE; ++i) { printf("%7.2lf", arr[i] ); } printf("\n"); printf("median %.2lf\n", median); // get_median(arr,ARR_SIZE); return 0; } double get_median(double arr[], int arr_size) { // odd number of integers int index1, index2; // bubble_sort_with_if_no_match(arr, arr_size); // insertion_sort(arr, arr_size); selection_sort(arr, arr_size); if (is_even(arr_size) == 0) { index1 = (arr_size/2) - 1; index2 = index1 + 1; return (arr[index1] + arr[index2])/2; } index1 = ((arr_size+1)/2) -1; return arr[index1]; } int is_even(int num) { return num % 2; }
C
int main(){ int n,i,j=0,a[100],b[100],s=0,c[100]={0},e; scanf("%d",&n); for(i=0;i<n;i++){ scanf("%d %d",&a[i],&b[i]); if(a[i]>=90&&a[i]<=140&&b[i]>=60&&b[i]<=90&&i!=n-1){ s++; } else if(a[i]>=90&&a[i]<=140&&b[i]>=60&&b[i]<=90&&i==n-1){ s++; c[j]=s; } else{ c[j]=s; s=0; j++; } } for(i=1;i<=n;i++){ for(j=0;j<n-i;j++){ if(c[j]<c[j+1]){ e=c[j]; c[j]=c[j+1]; c[j+1]=e; } } } printf("%d",c[0]); return 0; }
C
// Name: Olga Rudina // Student Number: // Section:J // Workshop:4 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #define MAXDAYS 10 // Put your code below: int main(void) { int i; int dayNum; int high[MAXDAYS], low[MAXDAYS]; int theHighest = 0; int theLowest = 0; int dayHigh; int dayLow; int flag = 0; double average = 0; printf("---=== IPC Temperature Calculator V2.0 ===---\n"); printf("Please enter the number of days, between 3 and 10, inclusive: "); scanf("%d", &dayNum); while (dayNum < 3 || dayNum > 10) { printf("\nInvalid entry, please enter a number between 3 and 10, inclusive: "); scanf("%d", &dayNum); } printf("\n"); for (i = 0; i < dayNum; i++) { printf("Day %d - High: ", i + 1); scanf("%d", &high[i]); printf("Day %d - Low: ", i + 1); scanf("%d", &low[i]); } printf("\nDay Hi Low\n"); for (i = 0; i < dayNum; i++) { printf("%d %d %d\n", i + 1, high[i], low[i]); if (theHighest < high[i]) { theHighest = high[i]; dayHigh = i + 1; } if (theLowest > low[i]) { theLowest = low[i]; dayLow = i + 1; } } printf("\nThe highest temperature was %d, on day %d\n", theHighest, dayHigh); printf("The lowest temperature was %d, on day %d\n", theLowest, dayLow); printf("\nEnter a number between 1 and 4 to see the average temperature for the entered number of days, enter a negative number to exit: "); scanf("%d", &dayNum); while (flag == 0) { if (dayNum == 0 || dayNum > 4) { printf("\nInvalid entry, please enter a number between 1 and 4, inclusive: "); scanf("%d", &dayNum); } else if (dayNum > 0 && dayNum < 5) { for (i = 0; i < dayNum; i++) { average += (high[i] + low[i]); } printf("\nThe average temperature up to day %d is: %.2f\n", i, average / (i * 2)); average = 0; printf("\nEnter a number between 1 and 4 to see the average temperature for the entered number of days, enter a negative number to exit: "); scanf("%d", &dayNum); } else { printf("\nGoodbye!"); printf("\n"); flag = 1; } } return 0; }
C
/* program cast01.c */ /* demotype casting */ main() { int i = 10; float f = 1.234; printf("%f\n",(float)i/3); printf("%lf\n",(double)f); } 
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <mpi.h> /* @author: Aldo Tali @creds: Senior Computer Engineering Student, Bilkent Uniersity @ID: 21500097 @Course: Parallel Computing - CS426 @Project01: Spring 2019 - Due 10/03/2019 @Section: Part B2 @Desc: Writes a parallell implementation of a program that takes two input file, reads two matrices and computes the multiplication of them. */ int ROW_MAJOR = 0; int COLUMN_MAJOR = 1; void allocate2DArray(int*** array,int dim1,int dim2){ int i; *array = (int **)malloc(dim1 * sizeof(int *)); for (i=0; i<dim1; i++) (*array)[i] = (int *)malloc(dim2 * sizeof(int)); } //Reads a file with a square matrix. Given that the line precedding the matrix //gives the dimension of the respective matrix, it assigns the integers in 2d arrays //accordingly. int readMatrixFromFile(char* fileName,int*** matrix,int major){ FILE *fileToRead = fopen(fileName,"r"); char *line = NULL; char linesplitter[] = "\n"; char spacesplitter[] = " "; ssize_t singleLine; size_t length = 0; int dimension = 0; char* numberStr; char* singleEntry; int number; int i,j; if (fileToRead == NULL){ return -1; }else{ i = -1; while ((singleLine = getline(&line, &length, fileToRead)) != -1) { //get the numbers one by one and put them in the array numberStr = strtok(line, linesplitter); if (numberStr == NULL){ printf("The num: %s\n", line); }else { //printf("'%s'\n", numberStr); For debugging reasons if (dimension == 0){ number = atoi(numberStr); dimension = number; allocate2DArray(matrix,dimension,dimension); } else { j = 0; singleEntry = strtok(numberStr, spacesplitter); while( singleEntry != NULL ) { number = atoi(singleEntry); //printf(" %d",number); if (major == ROW_MAJOR){ (*matrix)[i][j] = number; } else { if (major == COLUMN_MAJOR){ (*matrix)[j][i] = number; } } singleEntry = strtok(NULL, spacesplitter); j++; } //printf("\n"); } } i++; } free(line); fclose(fileToRead); } return dimension; } //prints integer array elements line by line void prettyPrintArray(int size, int* array){ int i; if (size > 0){ for (i = 0; i<size; i++){ printf("%d ",array[i]); } } } //prints integer array elements line by line void prettyPrint2DArray(int dim1,int dim2, int** array){ int i,j; if (dim1 > 0 && dim2>0){ for (i = 0; i<dim1; i++){ prettyPrintArray(dim2,array[i]); printf("\n"); } } } //multplies two matrices. Note operation is in O(n3) int** multiplySquareMatrices(int dim1,int dim2, int** mat1, int** mat2){ int i, j, k; int **result; allocate2DArray(&result,dim1,dim2); for (i = 0; i < dim1;i++){ for (j = 0; j < dim2; j++){ result[i][j] = 0; for (k = 0; k < dim1; k++){ result[i][j] = result[i][j] + mat1[i][k] * mat2[k][j]; } } } return result; } //does vector multiplication of two arrays int multiplyVectors(int dim1,int dim2, int* vec1, int* vec2){ int i, j, k; int result = 0; for (i = 0; i < dim1;i++){ result = result + vec1[i]*vec2[i]; } return result; } //copy array from source to destination (deep copy) void copyArray(int* source, int** dest, int size){ int i; //*dest = (int *)malloc(size * sizeof(int)); for (i = 0; i < size; i++){ (*dest)[i]=source[i]; } } //writes a 2d square matrix to a file void write2DArrayToFile(char* filename, int** arr, int dim){ FILE *f = fopen(filename, "w"); if (f == NULL) { printf("Error opening file!\n"); exit(1); } fprintf(f, "%d\n",dim); int i,j; for (i= 0; i < dim; i++){ for (j = 0; j<dim; j++){ fprintf(f, "%d ",arr[i][j]); } fprintf(f,"\n"); } fclose(f); } int executeMPI(int argc, char** argv){ int ROW_TAG = 0; int COLUMN_TAG = 1; int ARRAY_TAG = 2; int DIM_TAG = 3; int OUTPUT_TAG = 4; int ROW_INDEX_TAG = 5; int COLUMN_INDEX_TAG = 6; MPI_Status status; int **matrix,**matrix2,**result; int dim1,dim2; int noOfProcessors; int processId; int chunks; int i,j,k,counter,rowIndex,columnIndex,singleEntry; MPI_Init(NULL, NULL); MPI_Comm_size(MPI_COMM_WORLD, &noOfProcessors); MPI_Comm_rank(MPI_COMM_WORLD, &processId); if (processId == 0){ dim1 = readMatrixFromFile(argv[1],&matrix,0); if (noOfProcessors == 1){ dim2 = readMatrixFromFile(argv[2],&matrix2,0); result = multiplySquareMatrices(dim2,dim2,matrix,matrix2); }else { dim2 = readMatrixFromFile(argv[2],&matrix2,1); allocate2DArray(&result,dim1,dim2); if (dim1 != dim2){ printf("The matrices given as input are not the same dimension. The behaviour cannoit be predicted\n"); } int matrixrow,matrixcolum,gridIndex,processIdrow,pid; //assumes input is perfect square int procDim = sqrt(noOfProcessors); int noOfGrids = dim1/ procDim; for (processIdrow = 1; processIdrow < procDim*procDim; processIdrow++){ MPI_Send(&dim1, 1, MPI_INT, processIdrow, DIM_TAG,MPI_COMM_WORLD); } for (gridIndex = 0; gridIndex<noOfGrids; gridIndex++){ for (pid = 0; pid < procDim*procDim; pid++){ matrixrow = gridIndex*procDim + pid/procDim; matrixcolum = gridIndex*procDim + pid%procDim; if (pid==0){ }else { MPI_Send(matrix[matrixrow], dim1, MPI_INT,pid , ROW_TAG,MPI_COMM_WORLD); MPI_Send(matrix2[matrixcolum], dim1, MPI_INT,pid , COLUMN_TAG,MPI_COMM_WORLD); } } } int gridDim,resultx,resulty; for (gridDim =0 ; gridDim<noOfGrids; gridDim++){ for (gridIndex =0 ; gridIndex < noOfGrids; gridIndex++){ for (pid = 0; pid < procDim*procDim; pid++){ if (pid == 0){ matrixrow = gridIndex*procDim + pid/procDim; matrixcolum = gridIndex*procDim + pid%procDim; singleEntry = multiplyVectors(dim1,dim1,matrix[matrixrow],matrix2[matrixcolum]); resultx = gridDim* procDim; resulty = gridIndex* procDim; result[resultx][resulty] = singleEntry; }else { MPI_Recv(&rowIndex,1, MPI_INT, pid, ROW_INDEX_TAG, MPI_COMM_WORLD, &status); MPI_Recv(&columnIndex,1, MPI_INT, pid, COLUMN_INDEX_TAG, MPI_COMM_WORLD, &status); MPI_Recv(&singleEntry,1, MPI_INT, pid, OUTPUT_TAG, MPI_COMM_WORLD, &status); resultx = gridDim* procDim + pid/procDim; resulty = gridIndex* procDim + pid%procDim; result[resultx][resulty] = singleEntry; } } } } } write2DArrayToFile(argv[3],result,dim1); }else { //recieve the 2 arrays //get singleEntry //send single entry to master int matrixrow,gridIndex,processIdrow,dim; int **rows; int **columns; //assumes input is perfect square MPI_Recv(&dim, 1, MPI_INT, 0, DIM_TAG, MPI_COMM_WORLD, &status); int procDim = sqrt(noOfProcessors); int noOfGrids = dim/ procDim; allocate2DArray(&rows,noOfGrids,noOfGrids); allocate2DArray(&columns,noOfGrids,noOfGrids); for (gridIndex = 0; gridIndex<noOfGrids; gridIndex++){ MPI_Recv(columns[gridIndex],dim, MPI_INT, 0, ROW_TAG, MPI_COMM_WORLD, &status); copyArray(columns[gridIndex], &rows[gridIndex],dim); MPI_Recv(columns[gridIndex],dim, MPI_INT, 0, COLUMN_TAG, MPI_COMM_WORLD, &status); } for (rowIndex = 0; rowIndex<noOfGrids; rowIndex++){ for (columnIndex = 0; columnIndex<noOfGrids; columnIndex++){ singleEntry = multiplyVectors(dim,dim,rows[rowIndex],columns[columnIndex]); MPI_Send(&rowIndex, 1, MPI_INT, 0, ROW_INDEX_TAG,MPI_COMM_WORLD); MPI_Send(&columnIndex, 1, MPI_INT, 0, COLUMN_INDEX_TAG,MPI_COMM_WORLD); MPI_Send(&singleEntry, 1, MPI_INT, 0, OUTPUT_TAG,MPI_COMM_WORLD); } } } MPI_Finalize(); } int main(int argc, char** argv){ return executeMPI(argc,argv); }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdint.h> #include "game.h" #define assert(condition) ((condition) ? (true) : \ (fprintf(stderr, "Assertion failed! Check test.c.\nLine number: %d: %s\n", __LINE__, #condition), \ abort())) DecisionTreeNode* flattenTree(DecisionTreeNode* root); int main(void) { //PARSE TESTS char data[] = "G G G GARBAGE | 343 | 23 | This is a test"; char data2[] = "MORE GARBAGE | 21 | 84 | More tests"; FILE* fp = fopen("text.txt", "w"); fprintf(fp, "%s\n", data); fprintf(fp, "%s\n", data2); fclose(fp); fp = fopen("text.txt", "r"); Shield* sh = malloc(sizeof(Shield)); Sword* sw = malloc(sizeof(Sword)); ParseShieldInfo(sh, fp); //The following sword and shield should match the stats given assert(strcmp(sh->name, "G G G GARBAGE") == 0); assert(sh->cost == 343); assert(sh->defense == 23); assert(strcmp(sh->description, "This is a test") == 0); ParseSwordInfo(sw, fp); assert(strcmp(sw->name, "MORE GARBAGE") == 0); assert(sw->cost == 21); assert(sw->attack == 84); assert(strcmp(sw->description, "More tests") == 0); free(sh); free(sw); fclose(fp); remove("text.txt"); //BST TESTS //If these fail, you built your tree wrong DecisionTreeNode* root = NULL; root = addNodeToTree(root, root); assert(root == NULL); DecisionTreeNode nodes[3] = { { 100, 500, NULL, NULL, NULL }, {50, 51, NULL, NULL, NULL}, {501, 600, NULL, NULL, NULL} }; root = addNodeToTree(root, &nodes[0]); assert(root == &nodes[0]); root = addNodeToTree(root, &nodes[1]); assert(root == &nodes[0]); assert(root->left == &nodes[1]); root = addNodeToTree(root, &nodes[2]); assert(root == &nodes[0]); assert(root->left == &nodes[1]); assert(root->right == &nodes[2]); //ACTION LIST TESTS //same as BST, but with the list. ActionNode aNodes[2] = { {0, NULL}, {1, NULL} } ; ActionNode* head = NULL; head = addActionToList(head, head); assert(head == NULL); head = addActionToList(head, &aNodes[0]); assert(head == &aNodes[0]); head = addActionToList(head, &aNodes[1]); assert(head == &aNodes[0]); assert(head->next == &aNodes[1]); //FETCH TEST //If this fails, something is likely wrong with your tree. //Debug accordingly. nodes[2].FirstAction = head; Boss b1 = {"Sephiroth", 550, 7500, 7, 250, 6}; ActionNode* t = fetchNewList(&b1, root); assert(t != NULL); assert(t == head); //CONTROL TESTS Boss* b = loadBoss(); Boss b2 = {"Sephiroth", 7500, 7500, 7, 250, 6}; //Makes sure you read in the stats correctly. assert(strcmp(b->name, b2.name) == 0); assert(b->health == b2.health); assert(b->baseDefense == b2.baseDefense); assert(b->baseAttack == b2.baseAttack); assert(b->baseSpeed == b2.baseSpeed); //Tests root of tree to make sure that's right assert(b->root->healthFloor == 4541); assert(b->root->FirstAction->next->decision == 0); //Tests to make sure the tree you built was actually a BST, //and the layout of the BST matches what it should be. //Mainly checks for correct implementation of the load function in //conjunction with addNodeToTree DecisionTreeNode* list = flattenTree(b->root); DecisionTreeNode* next = list->right; DecisionTreeNode* start = list; while(next) { assert(list->healthCeiling < next->healthFloor); assert(list->FirstAction != NULL); list = next; next = next->right; } //FREE TEST (can't really test, but shouldn't seg fault) freeBossTree(b->root); //CLEANUP free(b); while(start) { DecisionTreeNode* t = start; start = start->right; free(t); } printf("Tests passed! Good job!\n"); return 0; } //Neat. Makes a linked list out of a BST. I take no credit for coming up with this. DecisionTreeNode* flattenTree(DecisionTreeNode* root) { DecisionTreeNode* L1 = root->left ? flattenTree(root->left) : NULL; DecisionTreeNode* L2 = root->right ? flattenTree(root->right) : NULL; DecisionTreeNode* L3 = malloc(sizeof(DecisionTreeNode)); memcpy(L3, root, sizeof(DecisionTreeNode)); L3->right = L2; if(!L1) return L3; DecisionTreeNode* cursor = L1; while(cursor->right) cursor = cursor->right; cursor->right = L3; return L1; }
C
#include <stdio.h> #include <openssl/bn.h> void printBN(char * msg, BIGNUM * a){// changes were made here for printing style char * number_str = BN_bn2hex(a); printf("%s%s", msg , number_str); OPENSSL_free(number_str); } int main(){ BN_CTX * ctx = BN_CTX_new(); BIGNUM *n = BN_new(); BIGNUM *d = BN_new(); BIGNUM *m = BN_new();//message BIGNUM *s = BN_new();//signed text BN_hex2bn(&n, "DCBFFE3E51F62E09CE7032E2677A78946A849DC4CDDE3A4D0CB81629242FB1A5"); BN_hex2bn(&d, " 74D806F9F3A62BAE331FFE3F0A68AFE35B3D2E4794148AACBC26AA381CD7D30D"); BN_hex2bn(&m, "49206f776520796f75202432303030"); BN_mod_exp(s, m, d, n, ctx); printBN("signed Message: ", s); printf("\n"); return 0; }
C
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // File name: main.c // Author: Jan K. Schiermer // Created on: 22 Nov 2018 // Description: //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #include <stdio.h> int menu(void); void show_soduko(void); void set_array(void); void solve_soduko(void); int main(void) { int choice; printf("Welcome to the soduko solver\n"); while(choice!=4) { choice=menu(); switch(choice) { case 1: show_soduko(); break; case 2: set_array(); break; case 3: solve_soduko(); break; } } printf("%d",choice); return 0; } int menu(void) { int keypress; printf("Key Function\n"); printf("1) Show soduko\n"); printf("2) Set array\n"); printf("3) Solve soduko\n"); printf("4) Exit\n"); while(1) { scanf("%d",&keypress); switch(keypress) { case 1: return 1; case 2: return 2; case 3: return 3; case 4: return 4; default: printf("Sorry wrong input try again\n"); while((getchar())!='\n'); continue; } } } void show_soduko(void) { } void set_array(void) { } void solve_soduko(void) { }
C
#pragma once #ifdef __cplusplus extern "C" { #endif #include <assert.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define Array(T) \ struct Array { \ T *contents; \ uint32_t size; \ uint32_t capacity; \ void *(*malloc)(size_t); \ void *(*realloc)(void *, size_t); \ void (*free)(void *); \ } #define array_init(self) \ ((self)->size = 0, (self)->capacity = 0, (self)->malloc = malloc, (self)->realloc = realloc, (self)->free = free, (self)->contents = NULL) #define array_new() \ { NULL, 0, 0, malloc, realloc, free } #define array_get(self, index) \ (assert((uint32_t) index < (self)->size), &(self)->contents[index]) #define array_head(self) array_get(self, 0) #define array_last(self) array_get(self, (self)->size - 1) #define array_clear(self) ((self)->size = 0) #define array_delete(self) array__delete((VoidArray *) self) #define array_push(self, element) \ (array__grow((VoidArray *) (self), 1, array__elem_size(self)), (self)->contents[(self)->size++] = (element)) #define array_insert(self, index, element) \ array__splice((VoidArray *) (self), array__elem_size(self), index, 0, 1, &element) #define array_grow_by(self, count) \ (array__grow((VoidArray *) (self), count, array__element_size(self)), \ memset((self)->contents + (self)->size, 0, (count) *array__element_size(self)), \ (self)->size += (count)) // Private typedef Array(void) VoidArray; #define array__elem_size(self) sizeof(*(self)->contents) #define array__malloc(self) (self)->malloc #define array__realloc(self) (self)->realloc #define array__free(self) (self)->free static inline void array__delete(VoidArray *self) { array__free(self)(self->contents); self->contents = NULL; self->size = 0; self->capacity = 0; } static inline void array__reserve(VoidArray *self, size_t element_size, uint32_t new_capacity) { if (new_capacity > self->capacity) { if (self->contents) { self->contents = array__realloc(self)(self->contents, new_capacity * element_size); } else { self->contents = array__malloc(self)(new_capacity * element_size); } self->capacity = new_capacity; } } static inline void array__grow(VoidArray *self, size_t margin, size_t element_size) { size_t new_size = self->size + margin; if (new_size > self->capacity) { size_t new_capacity = self->capacity * 2; if (new_capacity < 8) { new_capacity = 8; } if (new_capacity < new_size) { new_capacity = new_size; } array__reserve(self, element_size, new_capacity); } } static inline void array__splice(VoidArray *self, size_t element_size, uint32_t index, uint32_t old_count, uint32_t new_count, const void *elements) { uint32_t new_size = self->size + new_count - old_count; uint32_t old_end = index + old_count; uint32_t new_end = index + new_count; assert(old_end <= self->size); array__reserve(self, element_size, new_size); char *contents = (char *) self->contents; if (self->size > old_end) { memmove(contents + new_end * element_size, contents + old_end * element_size, (self->size - old_end) * element_size); } if (new_count > 0) { if (elements) { memcpy((contents + index * element_size), elements, new_count * element_size); } else { memset((contents + index * element_size), 0, new_count * element_size); } } self->size += new_count - old_count; } #ifdef __cplusplus } #endif
C
/************************************************************************* > File Name: Linklist.h > Author: kwh > Mail: > Created Time: 2019年07月13日 星期六 21时13分41秒 ************************************************************************/ #ifndef _LINKLIST_H #define _LINKLIST_H #endif #include <stdlib.h> #include <string.h> #include <stdio.h> <<<<<<< HEAD /* //链表结点数据类型 struct LinkNode { void *data; struct LinkNode *next; }; //链表数据类型 struct LList { struct LinkNode header; int size; }; */ typedef void * LinkList; typedef int (*COMPARE) (void *, void *); //typedef void (*FOREACH) (void *) //初始化链表 LinkList Init_LinkList (); //插入结点 void Insert_LinkList (LinkList list, int pos, void *data); //遍历链表 void Foreach_LinkList (LinkList list, void (* myforeach)(void *)); //按位置删除 void RemoveByPos_LinkList (LinkList list, int pos); //按值删除 void RemoveByVal_LinkList (LinkList list, void *data, COMPARE compare); //清空链表 void Clear_LinkList (LinkList); //大小 int Size_LinkList (LinkList list); ======= typedef void * LinkList; typedef int (*COMPARE) (void *, void *); //初始化链表 LinkList Init_LinkList (); //插入结点 void Insert_LinkList (LinkList list, int pos, void *data); //遍历链表 void Foreach_LinkList (LinkList list, void (* myforeach)(void *)); //按位置删除 void RemoveByPos_LinkList (LinkList list, int pos); //按值删除 void RemoveByVal_LinkList (LinkList list, void *data, COMPARE compare); //清空链表 void Clear_LinkList (LinkList); //大小 int Size_LinkList (LinkList list); >>>>>>> first //销毁链表 void Destory_LinkList (LinkList list);
C
#include<stdio.h> int main(){ int k=0, i=0, j=0, tamanho[100000], qtd=0; char lado[100000]; while( scanf("%d %c", &tamanho[i], &lado[i])!= EOF){ k++; i++; } for(i = 0; i < k; i++){ scanf("%d %c", &tamanho[i], &lado[i]); } for(i = 0; i< k; i++){ for(j = 0; j < k; j++){ if(tamanho[i] == tamanho[j]){ if(lado[i] == lado[j]){ qtd++; } } } } printf("%d\n", qtd/2); return 0; }
C
/* ARRAY IMPLMENTATION OF QUEUE */ #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include "queue.h" #define MAX_QUEUE_SIZE 100 size_t top, bot, size; Item array[MAX_QUEUE_SIZE]; void make_empty(){ top = 0; bot = 0; size = 0; } bool is_empty() { if (size == 0) { return true; } else { return false; } } bool is_full() { if (size == MAX_QUEUE_SIZE) { return true; } else { return false; } } void enqueue(Item data) { if (!(is_full())) { array[bot] = data; bot = (bot+1) % MAX_QUEUE_SIZE; size++; } else { printf("Queue is full. Cannot enqueue.\n"); } } Item dequeue() { Item temp = NULL; if (is_empty()) { printf("Nothing to dequeue. Queue is empty.\n"); } else { temp = array[top]; array[top] = NULL; top = (top+1) % MAX_QUEUE_SIZE; } return temp; } Item first() { Item temp = NULL; if (!(is_empty())) { temp = array[top]; } return temp; } Item last() { Item temp = NULL; if (!(is_empty())) { temp = array[bot-1]; } return temp; } int main() { make_empty(); enqueue(45); enqueue(67); enqueue(78); enqueue(34); enqueue(675); enqueue(23); enqueue(756); printf("Dequeue 2 numbers:\n"); printf("%d\n", dequeue()); printf("%d\n", dequeue()); enqueue(42); printf("Dequeue the rest of the numbers on the queue:\n"); Item DQdata = dequeue(); while(DQdata != NULL){ printf("%d\n", DQdata); DQdata = dequeue(); } return 0; }
C
/* linkedlist.c */ #include "linkedlist.h" void insertFirst(struct linkedList * head, int ele){ //create a node struct node *link = (struct node*) malloc (sizeof(struct node)); /* by this you are creating a node whose address is being stored in the link pointer. */ link->element = ele; //point it to old first node link->next = head->first; //point first to new first node head -> first = link; head -> count ++; } //delete first item struct node* deleteFirst(struct linkedList * head){ // exercise to implement this operation. struct node* temp = head->first; head->first = temp->next; temp->next = NULL; head->count --; return temp; } //display the list void printList(struct linkedList* head){ struct node *ptr = head->first; printf("\n[ "); //start from the beginning while(ptr != NULL){ printf("%d, ", ptr->element); ptr = ptr->next; } printf(" ]"); } //search int search(struct linkedList * head, int ele){ struct node *ptr = head->first; int x = 0; while(ptr != NULL){ if(ptr->element==ele){ return x+1; } ptr = ptr->next; x++; } return -1; //return -1 if element is missing } //delete struct node * delete(struct linkedList * head, int ele){ struct node *ptr = head->first; int index = search(head, ele); if(index==-1){ return NULL; //if element does not exist } for(int i= 1; i<index-1 ;i++){ ptr = ptr->next; } struct node *temp = ptr->next; ptr->next = ptr->next->next; temp->next = NULL; return temp; }
C
#include <stdio.h> int main(void) { int a, n, soma = 0, i = 0; scanf("%d %d", &a, &n); if(n <= 0) while(n <= 0) scanf("%d", &n); while(n-- > 0) { soma = soma + (a+i); i++; } printf("%d\n",soma); return 0; }
C
/* * SHT20.c * * Created on: Jul 31, 2016 * Author: matt */ #include "SHT20.h" void sht20_init() { } uint16_t sht20_get_raw_temp() { uint16_t temp; uint8_t crc; twi_read_word_crc(SHT20_ADDRESS, TEMP_HOLD, &temp, &crc); return temp & VALUE_STATUS_MASK; } double sht20_get_temp() { return (double)sht20_get_raw_temp()/0x10000*175.72-46.85; } uint16_t sht20_get_raw_rh() { uint16_t rh; uint8_t crc; twi_read_word_crc(SHT20_ADDRESS, RH_HOLD, &rh, &crc); return rh & VALUE_STATUS_MASK; } double sht20_get_rh() { return (double)sht20_get_raw_rh()/0x10000*125 - 6; } // TODO: Verify that this works void sht20_soft_reset() { twi_write_command(SHT20_ADDRESS, SOFT_RESET_COMMAND); } // TODO: Verify that this works void sht20_change_res(sht20_res_t res) { uint8_t user_reg = twi_read_reg_byte(SHT20_ADDRESS, READ_USER_REG); user_reg &= RES_MASK; switch (res) { case RH_8_T12: user_reg |= RES_RH_8_T_12_BIT; break; case RH_10_T_13: user_reg |= RES_RH_10_T_13_BIT; break; case RH_11_T_11: user_reg |= RES_RH_11_T_11_BIT; break; default: break; } twi_write_byte(SHT20_ADDRESS, WRITE_USER_REG, user_reg); } // TODO: Verify that this works uint8_t sht20_is_low_battery() { return (twi_read_reg_byte(SHT20_ADDRESS, READ_USER_REG) >> LOW_BATT_BIT_POS) & 1; } void sht20_low_power() { }
C
#include<stdio.h> int main() { enum status {pass, fail, atkt}; enum status stud1, stud2, stud3; stud1 = pass; stud2 = fail; stud3 = atkt; printf("%d %d %d",stud1, stud2,stud3); return 0; }
C
#include "stdio.h" #include "stdlib.h" #include "string.h" #include "setjmp.h" #include "signal.h" jmp_buf jmpSigSev; struct sigaction sigActionSegv; void sigSegvHandlerWithJmp(int signal, siginfo_t *si, void *arg) { printf("Caught segfault at address %p\n", si->si_addr); printf("regain control thanks to longjmp\n"); longjmp(jmpSigSev, 1); } void sigSegvHandlerWithoutJmp(int signal, siginfo_t *si, void *arg) { printf("Caught segfault at address %p\n", si->si_addr); exit(1); } void sigSegvHandlerSetWithJmp(void) { memset(&sigActionSegv, 0, sizeof(struct sigaction)); sigemptyset(&(sigActionSegv.sa_mask)); sigActionSegv.sa_sigaction = sigSegvHandlerWithJmp; sigActionSegv.sa_flags = SA_SIGINFO; sigaction(SIGSEGV, &sigActionSegv, NULL); } void sigSegvHandlerSetWithoutJmp(void) { memset(&sigActionSegv, 0, sizeof(struct sigaction)); sigemptyset(&(sigActionSegv.sa_mask)); sigActionSegv.sa_sigaction = sigSegvHandlerWithoutJmp; sigActionSegv.sa_flags = SA_SIGINFO; sigaction(SIGSEGV, &sigActionSegv, NULL); } void withTryCatch() { int* ptr = NULL; // Set the hanlder for sig sev with longjmp sigSegvHandlerSetWithJmp(); // Block protected from sig sev, equivalent to 'try' printf("Entering a block protected from sig sev\n"); switch (setjmp(jmpSigSev)) { case 0: // Trigger a sig sev printf("Trigger sig sev\n"); printf("%d",*ptr); break; // Equivalent to 'catch' case 1: printf("Sig sev has been caught\n"); break; } printf("Exiting the block protected from sig sev\n"); } void withoutTryCatch() { int* ptr = NULL; // Set the hanlder for sig sev without longjmp sigSegvHandlerSetWithoutJmp(); printf("Entering a block not protected from sig sev\n"); printf("Trigger sig sev\n"); // Trigger a sig sev printf("%d",*ptr); // Never reach here printf("Exiting the block not protected from sig sev\n"); } int main() { withTryCatch(); withoutTryCatch(); return 0; }
C
/* Dalam pointer simbol * merujuk pada value Dalam pointer simbol & merujuk pada alamat */ #include <stdio.h> int main(){ int a = 10, b = 20, c; int *pa, *pb; pa = &a, pb = &b; *pa = 15; // Value pada alamat yang ditampung pa (a) akan diubah menjadi 15 c = *pa + *pb; // c diisi dengan penjumlahan dari value yang alamatnya ditampung pa dan pb printf("Hasil a + b : %d\n",c); return 0; }
C
/* Copyright (c) 2011-2012 Hiroshi Tsubokawa See LICENSE and README */ #include "ObjectGroup.h" #include "VolumeAccelerator.h" #include "ObjectInstance.h" #include "PrimitiveSet.h" #include "Accelerator.h" #include "Interval.h" #include "Matrix.h" #include "Array.h" #include "Ray.h" #include "Box.h" #include <stdlib.h> #include <assert.h> #include <stdio.h> #include <float.h> struct ObjectList { struct Array *objects; double bounds[6]; }; static struct ObjectList *obj_list_new(void); static void obj_list_free(struct ObjectList *list); static void obj_list_add(struct ObjectList *list, const struct ObjectInstance *obj); static void object_bounds(const void *prim_set, int prim_id, double *bounds); static int object_ray_intersect(const void *prim_set, int prim_id, const struct Ray *ray, struct Intersection *isect); static int volume_ray_intersect(const void *prim_set, int prim_id, const struct Ray *ray, struct Interval *interval); struct ObjectGroup { struct ObjectList *surface_list; struct ObjectList *volume_list; struct Accelerator *surface_acc; struct VolumeAccelerator *volume_acc; }; struct ObjectGroup *ObjGroupNew(void) { struct ObjectGroup *grp; grp = (struct ObjectGroup *) malloc(sizeof(struct ObjectGroup)); if (grp == NULL) return NULL; grp->surface_list = NULL; grp->volume_list = NULL; grp->surface_acc = NULL; grp->volume_acc = NULL; grp->surface_list = obj_list_new(); if (grp->surface_list == NULL) { ObjGroupFree(grp); return NULL; } grp->volume_list = obj_list_new(); if (grp->volume_list == NULL) { ObjGroupFree(grp); return NULL; } grp->surface_acc = AccNew(ACC_BVH); if (grp->surface_acc == NULL) { ObjGroupFree(grp); return NULL; } grp->volume_acc = VolumeAccNew(VOLACC_BVH); if (grp->volume_acc == NULL) { ObjGroupFree(grp); return NULL; } return grp; } void ObjGroupFree(struct ObjectGroup *grp) { if (grp == NULL) return; obj_list_free(grp->surface_list); obj_list_free(grp->volume_list); AccFree(grp->surface_acc); VolumeAccFree(grp->volume_acc); free(grp); } void ObjGroupAdd(struct ObjectGroup *grp, const struct ObjectInstance *obj) { if (ObjIsSurface(obj)) { struct PrimitiveSet primset; obj_list_add(grp->surface_list, obj); MakePrimitiveSet(&primset, "ObjectInstance:Surface", grp->surface_list->objects->data, grp->surface_list->objects->nelems, grp->surface_list->bounds, object_ray_intersect, object_bounds); AccSetPrimitiveSet(grp->surface_acc, &primset); } else if (ObjIsVolume(obj)) { obj_list_add(grp->volume_list, obj); VolumeAccSetTargetGeometry(grp->volume_acc, grp->volume_list->objects->data, grp->volume_list->objects->nelems, grp->volume_list->bounds, volume_ray_intersect, object_bounds); } else { printf("fatal error: object is neither surface nor volume\n"); abort(); } } const struct Accelerator *ObjGroupGetSurfaceAccelerator(const struct ObjectGroup *grp) { return grp->surface_acc; } const struct VolumeAccelerator *ObjGroupGetVolumeAccelerator(const struct ObjectGroup *grp) { return grp->volume_acc; } static void object_bounds(const void *prim_set, int prim_id, double *bounds) { const struct ObjectInstance **objects = (const struct ObjectInstance **) prim_set; ObjGetBounds(objects[prim_id], bounds); } static int object_ray_intersect(const void *prim_set, int prim_id, const struct Ray *ray, struct Intersection *isect) { const struct ObjectInstance **objects = (const struct ObjectInstance **) prim_set; return ObjIntersect(objects[prim_id], ray, isect); } static int volume_ray_intersect(const void *prim_set, int prim_id, const struct Ray *ray, struct Interval *interval) { const struct ObjectInstance **objects = (const struct ObjectInstance **) prim_set; return ObjVolumeIntersect(objects[prim_id], ray, interval); } static struct ObjectList *obj_list_new(void) { struct ObjectList *list; list = (struct ObjectList *) malloc(sizeof(struct ObjectList)); if (list == NULL) return NULL; list->objects = ArrNew(sizeof(struct ObjectInstance *)); if (list->objects == NULL) { obj_list_free(list); return NULL; } BOX3_SET(list->bounds, FLT_MAX, FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX); return list; } static void obj_list_free(struct ObjectList *list) { if (list == NULL) return; if (list->objects != NULL) ArrFree(list->objects); free(list); } static void obj_list_add(struct ObjectList *list, const struct ObjectInstance *obj) { double bounds[6]; ObjGetBounds(obj, bounds); ArrPushPointer(list->objects, obj); BoxAddBox(list->bounds, bounds); }
C
/* { dg-do run } */ /* { dg-options "-O2 -fdump-tree-strlen" } */ #include "strlenopt.h" char temp[30]; volatile int v; size_t __attribute__ ((noinline, noclone)) f1 (void) { char a[30]; v += 1; memcpy (a, "1234567", 7); memcpy (a + 7, "89abcdefg", 9); memcpy (a + 16, "h", 2); return strlen (a); // This strlen should be optimized into 17. } size_t __attribute__ ((noinline, noclone)) f2 (char *a) { v += 2; memcpy (a, "1234567", 7); memcpy (a + 7, "89abcdefg", 9); memcpy (a + 16, "h", 2); return strlen (a); // This strlen should be optimized into 17. } size_t __attribute__ ((noinline, noclone)) f3 (void) { char a[30]; v += 3; a[0] = '1'; memcpy (a + 1, "2345678", 8); return strlen (a); // This strlen should be optimized into 8. } size_t __attribute__ ((noinline, noclone)) f4 (char *a) { v += 4; a[0] = '1'; memcpy (a + 1, "2345678", 8); return strlen (a); // This strlen should be optimized into 8. } size_t __attribute__ ((noinline, noclone)) f5 (void) { char a[30]; v += 5; a[0] = '1'; a[1] = '2'; a[2] = '3'; memcpy (a + 3, "456", 3); a[6] = '7'; a[7] = 0; return strlen (a); // This strlen should be optimized into 7. } size_t __attribute__ ((noinline, noclone)) f6 (char *a) { v += 6; a[0] = '1'; a[1] = '2'; a[2] = '3'; memcpy (a + 3, "456", 3); a[6] = '7'; a[7] = 0; return strlen (a); // This strlen should be optimized into 7. } size_t __attribute__ ((noinline, noclone)) f7 (void) { char a[30]; v += 7; strcpy (a, "abcde"); int len1 = strlen (a); a[2] = '_'; int len2 = strlen (a); return len1 + len2; // This should be optimized into 10. } size_t __attribute__ ((noinline, noclone)) f8 (char *a) { v += 8; strcpy (a, "abcde"); int len1 = strlen (a); a[2] = '_'; int len2 = strlen (a); return len1 + len2; // This should be optimized into 10. } size_t __attribute__ ((noinline, noclone)) f9 (char b) { char a[30]; v += 9; strcpy (a, "foo.bar"); a[4] = b; a[3] = 0; return strlen (a); // This should be optimized into 3. } size_t __attribute__ ((noinline, noclone)) f10 (char *a, char b) { v += 10; strcpy (a, "foo.bar"); a[4] = b; a[3] = 0; return strlen (a); // This should be optimized into 3. } size_t __attribute__ ((noinline, noclone)) f11 (void) { char a[30]; v += 11; strcpy (temp, "123456"); memcpy (a, temp, 7); return strlen (a); // This should be optimized into 6. } size_t __attribute__ ((noinline, noclone)) f12 (char *a) { v += 12; strcpy (temp, "123456"); memcpy (a, temp, 7); return strlen (a); // This should be optimized into 6. } size_t __attribute__ ((noinline, noclone)) f13 (void) { char a[30]; v += 13; strcpy (temp, "1234567"); memcpy (a, temp, 7); a[7] = 0; return strlen (a); // This should be optimized into 7. } size_t __attribute__ ((noinline, noclone)) f14 (char *a) { v += 14; strcpy (temp, "1234567"); memcpy (a, temp, 7); a[7] = 0; return strlen (a); // This should be optimized into 7. } size_t __attribute__ ((noinline, noclone)) f15 (void) { char a[30]; v += 15; strcpy (temp, "12345679"); memcpy (a, temp, 7); a[7] = 0; return strlen (a); // This should be optimized into 7. } size_t __attribute__ ((noinline, noclone)) f16 (char *a) { v += 16; strcpy (temp, "123456789"); memcpy (a, temp, 7); a[7] = 0; return strlen (a); // This should be optimized into 7. } int main () { char a[30]; if (f1 () != 17 || f2 (a) != 17 || f3 () != 8 || f4 (a) != 8 || f5 () != 7 || f6 (a) != 7 || f7 () != 10 || f8 (a) != 10 || f9 ('_') != 3 || f10 (a, '_') != 3 || f11 () != 6 || f12 (a) != 6 || f13 () != 7 || f14 (a) != 7 || f15 () != 7 || f16 (a) != 7) abort (); return 0; } /* { dg-final { scan-tree-dump-times "strlen \\(" 0 "strlen1" } } */
C
#include <stdio.h> int chercherMin(int *tableau, int taille) { int i; int min; for (i = 0; i < taille; i++) { if (tableau[i] < tableau[min]) min = i; } return min; } int main() { int nbAutos; int listDepart[1001]; int i, j; int min; scanf("%d", &nbAutos); for (i = 0; i < nbAutos; i++) scanf("%d", &listDepart[i]); while /* for (i = 0, j = 0; i < nbAutos; i++) */ /* { */ /* if (listDepart[j] != (i + 1)) */ /* { */ /* while (listDepart[j] != (i + 1)) */ /* { */ /* j++; */ /* } */ /* printf("%d %d\n", listDepart[j - 1], listDepart[j]); */ /* temp = listDepart[j]; */ /* listDepart[j] = listDepart[j - 1]; */ /* listDepart[j - 1] = temp; */ /* j = 0; */ /* i = 0; */ /* } */ /* else */ /* i++; */ /* } */ return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<sys/shm.h> // shared memory #include<sys/sem.h> // semaphore #include<sys/msg.h> // message queue #include<string.h> // memcpy #include "msg.h" int create_msg(void) { key_t key; int msqid; // 获取key值 if((key = ftok(".", 'z')) < 0) { perror("ftok error"); exit(1); } // 创建消息队列 if ((msqid = msgget(key, IPC_CREAT|0777)) == -1) { perror("msgget error"); exit(1); } return msqid; } int read_msg(int msqid, struct msg_form *msg) { msgrcv(msqid, msg, 1, 888, 0); /*读取类型为888的消息*/ printf("read data mtext: %c \n", msg->mtext); return 0; } //int write_msg(int msqid, struct msg_form *msg) int write_msg(int msqid) { struct msg_form msg; msg.mtype = 888; msg.mtext = 'r'; /*发送消息通知服务器读数据*/ msgsnd(msqid, &msg, sizeof(msg.mtext), 0); return 0; } int delete_msg(int msqid) { struct msqid_ds buf2; /*用于删除消息队列*/ msgctl(msqid, IPC_RMID, &buf2); return 0; }
C
#include<stdio.h> void main() {int n,space,row,i,j; scanf("%d",&n); space=n-1; for(row=1;row<=n;row++) {for(i=1;i<=space;i++) {printf(" ");} space--; for(j=1;j<=2*row-1;j++) {printf("*");} printf("\n");} }
C
/* * @Author: cy101 * @Date: 2020-03-09 22:09:06 * @Last Modified by: cyang * @Last Modified time: 2020-03-09 23:01:38 */ #include <stdio.h> int maxProfit(int* prices, int pricesSize){ int sum = 0; for (int i = 0; i < pricesSize-1; ++i) { if (prices[i+1] > prices[i]) { sum += prices[i+1] - prices[i]; } } return sum; } int main(int argc, char const *argv[]) { int prices[] = {7,1,5,3,6,4}; int sum = maxProfit(prices, sizeof(prices)/sizeof(prices[0])); printf("maxProfit = %d\n", sum); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* verify_keys.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cpereira <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/06/22 17:18:27 by cpereira #+# #+# */ /* Updated: 2021/06/27 17:41:19 by cpereira ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" /* teclas especiais */ /* \e[A = CIMA */ /* \e[B = BAIXO */ static void verify_up_down(t_v *all, char *ret) { tputs(restore_cursor, 1, my_termprint); tputs(tgoto(tgetstr("ch", NULL), 0, (int)ft_strlen(all->prompt)), 0, &my_termprint); tputs(tigetstr("ed"), 1, my_termprint); free(all->ret2); if (!ft_strncmp("\e[A", ret, 3)) { if (all->posic_hist > 0) all->posic_hist--; all->ret2 = ft_strdup(all->hist[all->posic_hist]); } if (!ft_strncmp("\e[B", ret, 3)) { all->posic_hist ++; if (all->posic_hist >= all->qtd_hist) all->ret2 = ft_strdup(""); else all->ret2 = ft_strdup(all->hist[all->posic_hist]); } verify_limits(all); all->pos_str = ft_strlen(all->ret2); all->size = ft_strlen(all->ret2); ret[0] = 0; } /* teclas especiais */ /* \e[C = DIREITA */ /* \e[D = ESQUERDA */ /* \e[H = HOME */ /* \e[F = END */ /* \e[ = OUTRAS */ /* ** */ static void verify_left_right(t_v *all, char *ret) { if (!ft_strncmp("\e[C", ret, 3)) { if (all->pos_str < (int)ft_strlen(all->ret2)) all->pos_str++; tputs(tgoto(tgetstr("ch", NULL), 0, all->pos_str + (int)ft_strlen(all->prompt)), 0, &my_termprint); tputs(save_cursor, 1, my_termprint); ret[0] = 0; } if (!ft_strncmp("\e[D", ret, 3)) { if (all->pos_str > 0) all->pos_str--; tputs(tgoto(tgetstr("ch", NULL), 0, all->pos_str + (int)ft_strlen(all->prompt)), 0, &my_termprint); tputs(save_cursor, 1, my_termprint); } } /* teclas especiais */ /* 28 = CTRL - / */ /* 3 = CTRL - C */ /* 4 = CTRL - D */ /* 127 = BACKSPACE */ /* 51 = DELETE */ /* ** */ static void verify_back(t_v *all, char *ret) { if (ret[0] == 127 || (ret[2] == 51 && all->pos_str != (int) ft_strlen(all->ret2))) { if (ret[0] == 127 && all->pos_str > 0) { erase_bksp(all, all->pos_str); all->pos_str--; } if (ret[2] == 51 && all->pos_str >= 0) erase_bksp(all, all->pos_str + 1); ret[0] = 0; tputs(tgoto(tgetstr("ch", NULL), 0, (int)ft_strlen(all->prompt)), 0, &my_termprint); tputs(tigetstr("ed"), 1, my_termprint); all->ret2[ft_strlen(all->ret2)] = '\0'; ft_putstr_fd(all->ret2, 1); tputs(tgoto(tgetstr("ch", NULL), 0, (int)ft_strlen(all->prompt) + all->pos_str), 0, &my_termprint); all->size--; } } static void verify_home_end(t_v *all, char *ret) { if (!ft_strncmp("\e[H", ret, 3)) { all->pos_str = (int)ft_strlen(all->prompt); tputs(tgoto(tgetstr("ch", NULL), 0, all->pos_str), 0, &my_termprint); all->pos_str = 0; } if (!ft_strncmp("\e[F", ret, 3)) { all->pos_str = (int)ft_strlen(all->ret2) + (int)ft_strlen(all->prompt); tputs(tgoto(tgetstr("ch", NULL), 0, all->pos_str), 0, &my_termprint); all->pos_str = ft_strlen(all->ret2); } } int verify_term(t_v *all, char *ret) { verify_left_right(all, ret); if (!ft_strncmp("\e[A", ret, 3) || !ft_strncmp("\e[B", ret, 3)) verify_up_down(all, ret); else { if (ret[0] == 3) { ft_putstr_fd("^C\n", 1); all->pos_str = 0; ft_bzero(all->ret2, ft_strlen(all->ret2)); write_prompt(all); } if (ret[0] == 4 ) { if (ft_strlen(all->ret2) == 0) { tcsetattr(0, TCSANOW, &all->old); bye(all); } } verify_back(all, ret); verify_home_end(all, ret); } return (!ft_isprint(ret[0])); }
C
void acreate() { printf("\nEnter the size of the array elements:\t"); scanf("%d",&n); printf("\nEnter the elements for the array:\n"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } }//end of create() void adisplay() //displaying an array elements { int i; printf("\nThe array elements are:\n"); for(i=0;i<n;i++){ printf("%d\t",a[i]); } }//end of display() void ainsert() //inserting an element in to an array { printf("\nEnter the position for the new element:\t"); scanf("%d",&pos); printf("\nEnter the element to be inserted :\t"); scanf("%d",&val); for(i=n-1;i>=pos;i--) { a[i+1]=a[i]; } a[pos]=val; n=n+1; }//end of insert() void adel() //deleting an array element { printf("\nEnter the position of the element to be deleted:\t"); scanf("%d",&pos); val=a[pos]; for(i=pos;i<n-1;i++) { a[i]=a[i+1]; } n=n-1; printf("\nThe deleted element is =%d",val); }//end of delete() void asearch() //searching an array element { printf("\nEnter the element to be searched:\t"); scanf("%d",&key); for(i=0;i<n;i++) { if(a[i]==key) { printf("\nThe element is present at position %d",i); break; } } if(i==n) { printf("\nThe search is unsuccessful"); } } int slmenu() { int n=0; while(n<1 || n>3) { printf("\n1:At front\n2:At end\n3:At center\nEnter your choice:"); scanf("%d",&n); if(n<1||n>3) { printf("\nWrong choice!!\n"); } return n; } } int slmenu1() { int n=0; while(n<1 || n>5) { printf("\n1:At front\n2:At end\n3:At center\n4:Search and delete\n5:Delete whole list\nEnter your choice:"); scanf("%d",&n); if(n<1||n>5) { printf("\nWrong choice!!\n"); } return n; } } struct node* slcreate(int info) { t=malloc(1*sizeof(node)); if(t!=NULL) { t->info=info; t->next=NULL; } return t; } void slinsert() { printf("\nWhere to insert??\n"); int n,info; n=slmenu(); struct node *x,*p1,*p2; switch(n) { case 1: printf("\nEnter info:"); scanf("%d",&info); x=slcreate(info); x->next=start; start=x; break; case 2: printf("\nEnter info:"); scanf("%d",&info); x=slcreate(info); t=start; if(t==NULL) { x->next=start; start=x; } else { while(t->next!=NULL) t=t->next; t->next=x; } break; case 3: p1=start; p2=start; while(p2!=NULL) { if(p2->next!=NULL && p2->next->next!=NULL) { p2=p2->next->next; p1=p1->next; } else break; } printf("\nEnter info:"); scanf("%d",&info); x=slcreate(info); x->next=p1->next; p1->next=x; break; } printf("\nNode inserted!!\n"); } void sldel() { printf("\nWhere to delete??\n"); int n; int info; n=slmenu1(); node *x,*p1,*p2; switch(n) { case 1: if(start==NULL) { printf("\nNo Node present!!\n"); return; } else { x=start; start=start->next; free(x); } break; case 2: t=start; if(t==NULL) { printf("\nNo Node present!!\n"); return; } else { while(t->next->next!=NULL) t=t->next; x=t->next; t->next=NULL; free(x); } break; case 3: p1=start; p2=start; if(p1==NULL) { printf("\nNo Node present!!\n"); return; } while(p2!=NULL) { if(p2->next!=NULL && p2->next->next!=NULL && p2->next->next->next!=NULL ) { p2=p2->next->next; p1=p1->next; } else break; } x=p1->next; p1->next=p1->next->next; free(x); break; case 4: printf("\nEnter info to search:"); scanf("%d",&info); t=start; if(start->info==info) { printf("\nNode is present!!\n"); start=start->next; free(t); printf("\nNode deleted!!\n"); return; } while(t->next!=NULL) { if(t->next->info==info) { printf("\nNode is present!!\n"); x=t->next; t->next=x->next; free(x); printf("\nNode deleted!!\n"); return; } t=t->next; } printf("\nNode not present!!\n"); return; case 5: t=start; while(t!=NULL) { x=t; t=t->next; free(x); } start=NULL; printf("\nList deleted\n"); return; } printf("\nNode deleted!!\n"); } void sldisplay() { t=start; printf("\n"); while(t!=NULL) { printf("%d -> ",t->info); t=t->next; } } void slsearch() { int info; printf("\nEnter info to search:"); scanf("%d",&info); t=start; while(t!=NULL) { if(t->info==info) { printf("\nNode is present!!\n"); return; } t=t->next; } printf("\nNode is not present!!"); } node* slreverse(node *x) { node *temp; if(x->next==NULL) { start=x; return x; } else { temp=slreverse(x->next); temp->next=x; temp=temp->next; temp->next=NULL; } } void sapush() { if(top==19) { printf("\nStack is full!!\n"); } else { int x; printf("\nEnter element:"); scanf("%d",&x); top++; stack[top]=x; printf("\nElement pushed!!\n"); } } void sapop() { if(top==-1) { printf("\nStack is empty!!Can't pop!!\n"); } else { printf("\nElement popped=%d\n",stack[top]); top--; } } void sadisplay() { if(top==-1) { printf("\nStack is empty!\n"); exit(50); } else {int i; printf("\nStack is....\n"); for(i=top;i>=0;i--) { printf("%d\n",stack[i]); } } } void sasize() { printf("\nSize of stack=%d",top+1); } void sapeek() { if(top==-1) printf("\nStack is empty!!"); else printf("\nElement at top=%d",stack[top]); } void qainsert(int item) { if( qaisFull() ) { printf("Queue Overflow\n"); return; } if( front == -1 ) front=0; rear=rear+1; queue_arr[rear]=item ; } int qadel() { int item; if( qaisEmpty() ) { printf("Queue Underflow\n"); exit(1); } item=queue_arr[front]; front=front+1; return item; } int qapeek() { if( qaisEmpty() ) { printf("Queue Underflow\n"); exit(1); } return queue_arr[front]; } int qaisEmpty() { if( front==-1 || front==rear+1 ) return 1; else return 0; } int qaisFull() { if( rear==MAX-1 ) return 1; else return 0; } void qadisplay() { int i; if ( qaisEmpty() ) { printf("Queue is empty\n"); return; } printf("Queue is :\n\n"); for(i=front;i<=rear;i++) printf("%d ",queue_arr[i]); printf("\n\n"); } void btacreate_tree(struct bnode *root, int tree[], int i) { if(root==NULL) return; if(i*2<=n) { struct bnode* temp1 = (struct bnode*)malloc(sizeof(struct bnode)); temp1->data = tree[i*2]; root->left = temp1; } else root->left=NULL; if(i*2+1<=n) { struct bnode* temp2 = (struct bnode*)malloc(sizeof(struct bnode)); temp2->data = tree[i*2+1]; root->right = temp2; } else root->right=NULL; btacreate_tree(root->left, tree, i*2); btacreate_tree(root->right, tree,i*2+1); } void btainorder(struct bnode* root) { if(root!=NULL) { btainorder(root->left); printf("%d ", root->data); btainorder(root->right); } } void btapreorder(struct bnode* root) { if(root!=NULL) { printf("%d ", root->data); btapreorder(root->left); btapreorder(root->right); } } void btapostorder(struct bnode* root) { if(root!=NULL) { btapostorder(root->left); btapostorder(root->right); printf("%d ", root->data); } } void htsamax_heapify(int *heap, int i) { if(i>n) return; if((2*i+1)<=n) { int large; if(heap[2*i]>heap[2*i+1]) large = heap[2*i]; else large = heap[2*i+1]; if(heap[i]<large) { int temp = heap[i]; heap[i] = large; if(large==heap[2*i]) { heap[2*i] = temp; htsamax_heapify(heap,2*i); } else { heap[2*i+1] = temp; htsamax_heapify(heap,2*i+1); } } } if(2*i<=n && heap[i]<heap[2*i]) { int tem = heap[i]; heap[i] = heap[2*i]; heap[2*i] = tem; htsamax_heapify(heap,2*i); } } void htsabuild_max_heap(int *heap, int i) { if(i==0) return; if((2*i+1)<=n) { int large; if(heap[2*i]>heap[2*i+1]) large = heap[2*i]; else large = heap[2*i+1]; if(heap[i]<large) { int temp = heap[i]; heap[i] = large; if(large==heap[2*i]) { heap[2*i] = temp; htsamax_heapify(heap,2*i); } else { heap[2*i+1] = temp; htsamax_heapify(heap,2*i+1); } } } if(heap[i]<heap[2*i]) { int tem = heap[i]; heap[i] = heap[2*i]; heap[2*i] = tem; htsamax_heapify(heap,2*i); } htsabuild_max_heap(heap, i-1); } void htsamin_heapify(int *heap, int i) { if(i>n) return; if((2*i+1)<=n) { int small; if(heap[2*i]<heap[2*i+1]) small = heap[2*i]; else small = heap[2*i+1]; if(heap[i]>small) { int temp = heap[i]; heap[i] = small; if(small==heap[2*i]) { heap[2*i] = temp; htsamin_heapify(heap,2*i); } else { heap[2*i+1] = temp; htsamin_heapify(heap,2*i+1); } } } if(2*i<=n && heap[i]>heap[2*i]) { int tem = heap[i]; heap[i] = heap[2*i]; heap[2*i] = tem; htsamin_heapify(heap,2*i); } } void htsabuild_min_heap(int *heap, int i) { if(i==0) return; if((2*i+1)<=n) { int small; if(heap[2*i]<heap[2*i+1]) small = heap[2*i]; else small = heap[2*i+1]; if(heap[i]>small) { int temp = heap[i]; heap[i] = small; if(small==heap[2*i]) { heap[2*i] = temp; htsamin_heapify(heap,2*i); } else { heap[2*i+1] = temp; htsamin_heapify(heap,2*i+1); } } } if(2*i<=n && heap[i]>heap[2*i]) { int tem = heap[i]; heap[i] = heap[2*i]; heap[2*i] = tem; htsamin_heapify(heap,2*i); } htsabuild_min_heap(heap, i-1); } void htsaheap_sort(int *heap) { if(n==0) return; htsamax_heapify(heap,1); int temp = heap[1]; heap[1] = heap[n]; heap[n] = temp; n--; htsaheap_sort(heap); } struct avlnode* avlsearch(avlnode* ptr,int skey) { if(!ptr) { printf("Key not found"); return NULL; } if(ptr->info>skey) return avlsearch(ptr->rchild,skey); else if(ptr->info<skey) return avlsearch(ptr->lchild,skey); else return ptr; } void avlpreorder(avlnode * ptr) { if(!ptr) return ; printf("%d ",ptr->info); avlpreorder(ptr->lchild); avlpreorder(ptr->rchild); return; } void avlinorder(avlnode* ptr) { if(!ptr) return ; avlinorder(ptr->lchild); printf("%d ",ptr->info); avlinorder(ptr->rchild); } void avlpostorder(avlnode* ptr) { if(!ptr) return ; avlpostorder(ptr->lchild); avlpostorder(ptr->rchild); printf("%d ",ptr->info); } int avlheightnode(avlnode* ptr,int p) { if(!ptr) return 0; if(ptr->info ==p) { return avlheight(ptr); } } void avlarry(avlnode* root) { if(root!=NULL) { avlarry(root->lchild); ar[i] = root->info; i++; avlarry(root->rchild); } } void avlsucc_prede(avlnode* root, int key) { i = 0; int j; avlarry(root); for(j=0;j<i;j++) { if(ar[j]==key) { if(j>0) printf("Predecessor: %d\n", ar[j-1]); else printf("No Predecessor!!!\n"); if(j<i-1) printf("Successor: %d", ar[j+1]); else printf("No Successor!!!\n"); return; } } if(j==i) printf("Key not Found"); } avlnode * avlinsert(avlnode *T,int x) { if(T==NULL) { T=(struct avlnode*)malloc(sizeof(avlnode)); T->data=x; T->lchild=NULL; T->rchild=NULL; } else if(x > T->data) // insert in right subtree { T->rchild=avlinsert(T->rchild,x); if(avlBF(T)==-2) if(x>T->rchild->data) T=avlRR(T); else T=avlRL(T); } else if(x<T->data) { T->lchild=avlinsert(T->lchild,x); if(avlBF(T)==2) if(x < T->lchild->data) T=avlLL(T); else T=avlLR(T); } T->ht=avlheight(T); return(T); } avlnode * avlDelete(avlnode *T,int x) { struct avlnode *p; if(T==NULL) { printf("\nElement doesn't exist!!\n"); return NULL; } else if(x > T->data) { T->rchild=avlDelete(T->rchild,x); if(avlBF(T)==2) if(avlBF(T->lchild)>=0) T=avlLL(T); else T=avlLR(T); } else if(x<T->data) { T->lchild=avlDelete(T->lchild,x); if(avlBF(T)==-2) //Rebalance during windup if(avlBF(T->rchild)<=0) T=avlRR(T); else T=avlRL(T); } else { //data to be deleted is found if(T->rchild!=NULL) { //delete its inorder succesor p=T->rchild; while(p->lchild!= NULL) p=p->lchild; T->data=p->data; T->rchild=avlDelete(T->rchild,p->data); if(avlBF(T)==2)//Rebalance during windup if(avlBF(T->lchild)>=0) T=avlLL(T); else T=avlLR(T); } else return(T->lchild); } T->ht=avlheight(T); return(T); } int avlheight(avlnode *T) { int lh,rh; if(T==NULL) return(0); if(T->lchild==NULL) lh=0; else lh=1+T->lchild->ht; if(T->rchild==NULL) rh=0; else rh=1+T->rchild->ht; if(lh>rh) return(lh); return(rh); } avlnode * avlrotateright(avlnode *x) { avlnode *y; y=x->lchild; x->lchild=y->rchild; y->rchild=x; x->ht=avlheight(x); y->ht=avlheight(y); return(y); } avlnode * avlrotateleft(avlnode *x) { avlnode *y; y=x->rchild; x->rchild=y->lchild; y->lchild=x; x->ht=avlheight(x); y->ht=avlheight(y); return(y); } avlnode * avlRR(avlnode *T) { T=avlrotateleft(T); return(T); } avlnode * avlLL(avlnode *T) { T=avlrotateright(T); return(T); } avlnode * avlLR(avlnode *T) { T->lchild=avlrotateleft(T->lchild); T=avlrotateright(T); return(T); } avlnode * avlRL(avlnode *T) { T->rchild=avlrotateright(T->rchild); T=avlrotateleft(T); return(T); } int avlBF(avlnode *T) { int lh,rh; if(T==NULL) return(0); if(T->lchild==NULL) lh=0; else lh=1+T->lchild->ht; if(T->rchild==NULL) rh=0; else rh=1+T->rchild->ht; return(lh-rh); } void arr() { int choice; do{ printf("1.Create\n"); printf("2.Display\n"); printf("3.Insert\n"); printf("4.Delete\n"); printf("5.Search\n"); printf("6.quit\n"); printf("\nEnter your choice:\t"); scanf("%d",&choice); switch(choice) { case 1: acreate(); break; case 2: adisplay(); break; case 3: ainsert(); break; case 4: adel(); break; case 5: asearch(); break; case 6: printf("Exiting..."); break; default: printf("\nInvalid choice:\n"); break; } }while(choice!=6); } void singlell() { int ch; while(1) { printf("\nSelect an option:\n1:Insert\n2:Search\n3:Display\n4:Delete\n5:Reverse\n6:Exit\nYour choice:"); scanf("%d",&ch); switch(ch) { case 1: slinsert(); break; case 2: slsearch(); break; case 3: sldisplay(); break; case 4: sldel(); break; case 5: slreverse(start); break; case 6: return ; default: printf("\nWrong choice!!"); } getche(); } } void stacka() { int ch; while(1) { printf("\nSelect an option:\n1:Push\n2:Pop\n3:Size\n4:Peek\n5:Display\n6:Exit\nYour choice:"); scanf("%d",&ch); switch(ch) { case 1:sapush(); break; case 2:sapop(); break; case 3:sasize(); break; case 4:sapeek(); break; case 5:sadisplay(); break; case 6:exit(0); default:printf("\nWrong choice!!\n"); break; } } } void queuea() { int choice,item; while(1) { printf("1.Insert\n"); printf("2.Delete\n"); printf("3.Display element at the front\n"); printf("4.Display all elements of the queue\n"); printf("5.Quit\n"); printf("Enter your choice : "); scanf("%d",&choice); switch(choice) { case 1: printf("Input the element for adding in queue : "); scanf("%d",&item); qainsert(item); break; case 2: item=qadel(); printf("Deleted element is %d\n",item); break; case 3: printf("Element at the front is %d\n",qapeek()); break; case 4: qadisplay(); break; } } } void bintree() { printf("Enter the num of nodes: "); scanf("%d", &n); int tree[n+1]; tree[0] = -1; int i; printf("Enter the tree data\n"); for(i=1;i<n+1;i++) scanf("%d", &tree[i]); struct bnode* root = NULL; if(n!=0) { root = (struct bnode*)malloc(sizeof(struct bnode)); root->data = tree[1]; btacreate_tree(root,tree,1); } int opt; while(1){ printf("Options:\n"); printf("1.Inorder\n2.Preorder\n3.Postorder\n4.Levelorder\n5.Exit\n"); scanf("%d", &opt); if(opt==1){ btainorder(root); printf("\n");} else if(opt==2){ btapreorder(root); printf("\n");} else if(opt==3){ btapostorder(root); printf("\n");} else if(opt==4) { for(i=1;i<n+1;i++) printf("%d ", tree[i]); printf("\n"); } else break; } } void htsa() { int n; printf("\nEnter the Number of elements in heap: "); scanf("%d", &n); int heap[n+1]; heap[0] = -1; int i, opt; for(i=1;i<n+1;i++) scanf("%d", &heap[i]); while(1) { printf("\nOptions:\n"); printf("\n1. Build max heap\n2. Build min heap\n3. Heap sort\n4. Display heap\n5. Exit"); scanf("%d", &opt); switch(opt) { case 1: htsabuild_max_heap(heap, (n+1)/2); break; case 2: htsabuild_min_heap(heap, (n+1)/2); break; case 3: i = n; htsabuild_max_heap(heap, (n+1)/2); htsaheap_sort(heap); n = i; break; case 4: printf("\n"); for(i=1;i<n+1;i++) printf("%d ", heap[i]); printf("\n"); break; case 5: break; } if(opt==5) break; } } void avl() { int choice,key; printf("\n1.Search\n2.Insert\n3.Delete\n4.Preorder\n5.postorder\n6.inorder\n7.height of tree \n8.find Successor and predecessor"); printf("\n9.Height of a node\n10.Quit\n\nEnter your choice:"); scanf("%d",&choice); do{ switch(choice) { case 1: printf("Enter the number you want to search:"); scanf("%d",&key); ptr=avlsearch(root,key); if(ptr) printf("\nKey present"); else printf("\n key not present"); break; case 2: printf("Enter the number you want to insert:"); scanf("%d",&key); root=avlinsert(root,key); break; case 3: printf("Enter the number you want to delete:"); scanf("%d",&key); root=avlDelete(root,key); break; case 4: avlpreorder(root); break; case 5: avlpostorder(root); break; case 6: avlinorder(root); break; case 7: printf("The height of the tree is:%d",avlheight(root)); break; case 8: printf("Enter the node value: "); scanf("%d",&key); avlsucc_prede(root, key); break; case 9: printf("Enter the node value you want to find height of:"); scanf("%d",&key); printf("Height of the node is:%d",avlheightnode(root,key)); break; case 10: printf("Exiting..."); break; default: printf("Enter correct choice\n"); } if(choice!=10) { printf("Enter your choice again:"); scanf("%d",&choice); } }while(choice!=10); } int mins(int x, int y) { return (x<=y)? x : y; } int linsearch(int arr[],int n,int x) { int i; for (i=0; i<n; i++) if (arr[i] == x) return i; return -1; } int binsearch(int arr[],int l,int r,int x) { if (r >= l) { int mid = l + (r - l)/2; if (arr[mid] == x) return mid; if (arr[mid] > x) return binsearch(arr, l, mid-1, x); return binsearch(arr, mid+1, r, x); } return -1; } int fibsearch(int arr[],int x,int n) { int fibMMm2 = 0; int fibMMm1 = 1; int fibM = fibMMm2 + fibMMm1; while (fibM < n) { fibMMm2 = fibMMm1; fibMMm1 = fibM; fibM = fibMMm2 + fibMMm1; } int offset = -1; while (fibM > 1) { int i = mins(offset+fibMMm2, n-1); if (arr[i] < x) { fibM = fibMMm1; fibMMm1 = fibMMm2; fibMMm2 = fibM - fibMMm1; offset = i; } else if (arr[i] > x) { fibM = fibMMm2; fibMMm1 = fibMMm1 - fibMMm2; fibMMm2 = fibM - fibMMm1; } else return i; } if(fibMMm1 && arr[offset+1]==x) return offset+1; return -1; } void srch() { int a[max],n,i,t,k,choice; printf("\nChoices for different type of searching:-"); printf("\n1.LINEAR SEARCH"); printf("\n2.BINARY SEARCH"); printf("\n3.FIBONACCI SEARCH"); printf("\n4.EXIT"); do { printf("\nEnter the choice for searching:-"); scanf("%d",&choice); switch(choice) { case 1:system("cls"); printf("\nLinear Search\n"); printf("\nEnter the no. of elements in array:"); scanf("%d",&n); printf("\nEnter the elements of array:"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("\nEnter the element wanted to be searched in array:"); scanf("%d",&k); t=linsearch(a,n,k); (t == -1)? printf("Element is not present in array") : printf("Element is present at index %d",t); break; case 2:system("cls"); printf("\nBinary Search\n"); printf("\nEnter the no. of elements in array:"); scanf("%d",&n); printf("\nEnter the elements of array:"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("\nEnter the element wanted to be searched in array:"); scanf("%d",&k); t=binsearch(a,0,n-1,k); (t == -1)? printf("Element is not present in array") : printf("Element is present at index %d",t); break; case 3:system("cls"); printf("\nFibonacci Search\n"); printf("\nEnter the no. of elements in array:"); scanf("%d",&n); printf("\nEnter the elements of array(space separated):"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("\nEnter the element wanted to be searched in array:"); scanf("%d",&k); t=fibsearch(a,k,n); (t == -1 )? printf("Element is not present in array") : printf("Element is present at index %d",t); break; case 4:printf("***Program is quiting!!!***\n***Thank-You for using our Program***\n***Have a nice day!!!***\n"); exit(5); default:printf("WRONG CHOICE"); break; } }while(choice>0 && choice<4); return 0; } void soort() { int arr[MAX],temp,i,n,j,k,min; system("cls"); printf("DIFFERENT TYPES OF SORTING\n1.Bubble Sort\n2.Linear sort\n3.Selection Sort\n4.Quick Sort\n5.Merge Sort"); printf("\nEnter Choice:"); int ch; scanf("%d",&ch); switch(ch) { case 1: printf("enter the no.of elements in array\n"); scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&arr[i]); } for(i=0;i<n-1;i++) { for(j=0;j<n-i-1;j++) { if(arr[j]>arr[j+1]) { temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } printf("sorted list is\n"); for(i=0;i<n;i++) printf("%d\n",arr[i]); break; case 2: printf("enter the no.of elements in array\n"); scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&arr[i]); for(i=0;i<n;i++) { k=arr[i]; for(j=i-1;j>=0 && k<arr[j];j--) arr[j+1]=arr[j]; arr[j+1]=k; } printf("sorted list is\n"); for(i=0;i<n;i++) printf("%d\n",arr[i]); break; case 3: printf("enter the no.of elements in array\n"); scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&arr[i]); } for(i=0;i<n-1;i++) { min=i; for(j=i+1;j<n;j++) { if(arr[min]>arr[j]) min=j; } if(i!=min) { temp=arr[i]; arr[i]=arr[min]; arr[min]=temp; } } printf("the sorted order of no. is\n"); for(i=0;i<n;i++) printf("%d\n",arr[i]); printf("\n"); break; case 4: qqsort(); break; case 5: msort(); break; } } void qqsort() { int arr[MAX],n,i; printf("Enter the number of elements : "); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter element %d : ",i+1); scanf("%d",&arr[i]); } quick(arr,0,n-1); printf("Sorted list is :\n"); for(i=0;i<n;i++) printf("%d\n",arr[i]); printf("\n"); } void quick(int arr[],int low,int up) { int pivloc; printf("\n"); if(low>=up) return ; pivloc = part(arr,low,up); quick(arr,low,pivloc-1); quick(arr,pivloc+1,up); } int part(int arr[], int low, int up) { int temp,i,j,pivot; i=low+1; j=up; pivot=arr[low]; while( i <= j ) { while( (arr[i] < pivot) && (i<up) ) i++; while( arr[j] > pivot ) j--; if(i < j) { temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; i++; j--; } else {i++; } } arr[low]=arr[j]; arr[j]=pivot; return j; } void msort() { int arr[MAX],i,n; printf("Enter the number of elements : "); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter element %d : ",i+1); scanf("%d",&arr[i]); } merge_sort(arr,0,n-1); printf("\nSorted list is :\n"); for( i = 0 ; i<n ; i++) printf("%d ", arr[i]); printf("\n"); } void merge_sort(int arr[], int low,int up) { int mid; int temp[MAX]; if(low<up) { mid=(low+up)/2; merge_sort(arr,low,mid); merge_sort(arr,mid+1,up); mergee(arr,temp,low,mid,mid+1,up); copyy(arr,temp,low,up); } } void mergee(int arr[], int temp[],int low1, int up1, int low2, int up2 ) { int i=low1; int j=low2; int k=low1; while((i<=up1 )&& (j<=up2 )) { if( arr[i] <= arr[j] ) temp[k++]=arr[i++]; else temp[k++]=arr[j++]; } while(i<=up1) temp[k++]=arr[i++]; while(j<=up2) temp[k++]=arr[j++]; } void copyy(int arr[], int temp[], int low,int up) { int i; for(i=low;i<up;i++) arr[i]=temp[i]; } void bstree() { struct bstnode* root=NULL,*ptr; int choice,key; printf("1.Search\n2.Insert\n3.Delete\n4.Preorder\n5.postorder\n6.inorder\n7.height of tree \n8.find Successor and predecessor"); printf("\n9.height of a node\n10.Quit\n\nEnter your choice:"); scanf("%d",&choice); do{ switch(choice) { case 1: printf("\nEnter the number you want to search:"); scanf("%d",&key); ptr=bstsearch(root,key); if(ptr) printf("\nKey present"); else printf("\n key not present"); break; case 2: printf("Enter the number you want to insert:"); scanf("%d",&key); root=bstinsert(root,key); break; case 3: printf("Enter the number you want to delete:"); scanf("%d",&key); root=bstdel(root,key); break; case 4: bstpreorder(root); break; case 5: bstpostorder(root); break; case 6: bstinorder(root); break; case 7: printf("The height of the tree is:%d",bstheight(root)); break; case 8: printf("Enter the node value: "); scanf("%d",&key); bstsucc_prede(root, key); break; case 9: printf("Enter the node value you want to find height of:"); scanf("%d",&key); printf("Height of the node is:%d",bstheightnode(root,key)); break; case 10: printf("Exiting..."); break; default: printf("Enter correct choice\n"); } if(choice!=10) { printf("Enter your choice again:"); scanf("%d",&choice); } }while(choice!=10); } bstnode* bstsearch(bstnode* ptr,int skey) { if(!ptr) { printf("Key not found"); return NULL; } if(ptr->info>skey) return bstsearch(ptr->rchild,skey); else if(ptr->info<skey) return bstsearch(ptr->lchild,skey); else return ptr; } bstnode* bstinsert(bstnode* ptr,int ikey) { if(ptr==NULL) { bstnode* temp=(bstnode*)malloc(sizeof(bstnode)); temp->info=ikey; temp->rchild=NULL; temp->lchild=NULL; return temp; } if(ptr->info<ikey) ptr->rchild=bstinsert(ptr->rchild,ikey); else if(ptr->info>ikey) ptr->lchild=bstinsert(ptr->lchild,ikey); else printf("Duplicate key\n"); return ptr; } void bstpreorder(bstnode * ptr) { if(!ptr) return ; printf("%d ",ptr->info); bstpreorder(ptr->lchild); bstpreorder(ptr->rchild); return; } void bstinorder(bstnode* ptr) { if(!ptr) return ; bstinorder(ptr->lchild); printf("%d ",ptr->info); bstinorder(ptr->rchild); } void bstpostorder(bstnode* ptr) { if(!ptr) return ; bstpostorder(ptr->lchild); bstpostorder(ptr->rchild); printf("%d ",ptr->info); } int bstheight(bstnode *ptr) { if(!ptr) return 0; int x=bstheight(ptr->lchild); int y=bstheight(ptr->rchild); if(x>y) return x+1; else return y+1; } bstnode* bstdel(bstnode* ptr,int dkey) { if(ptr==NULL) { printf("Key not found\n"); return NULL; } if(ptr->info>dkey) return bstdel(ptr->rchild,dkey); else if(ptr->info<dkey) return bstdel(ptr->lchild,dkey); else { if(ptr->rchild && ptr->lchild) { bstnode* succ=ptr->rchild; while(succ->lchild) succ=succ->lchild; ptr->info=succ->info; ptr->rchild=bstdel(succ->rchild,succ->info); } else { bstnode* tmp=ptr; if(ptr->lchild!=NULL) ptr=ptr->lchild; else if(ptr->rchild) ptr=ptr->rchild; else ptr=NULL; free(tmp); } } return ptr; } int bstheightnode(bstnode* ptr,int p) { if(!ptr) return 0; if(ptr->info ==p) { return bstheight(ptr); } } void bstarry(bstnode* root) { if(root!=NULL) { bstarry(root->lchild); ar[i] = root->info; i++; bstarry(root->rchild); } } void bstsucc_prede(bstnode* root, int key) { i = 0; int j; bstarry(root); for(j=0;j<i;j++) { if(ar[j]==key) { if(j>0) printf("Predecessor: %d\n", ar[j-1]); else printf("No Predecessor!!!\n"); if(j<i-1) printf("Successor: %d", ar[j+1]); else printf("No Successor!!!\n"); return; } } if(j==i) printf("Key not Found"); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> char shellcode[] = "\xeb\xfe"; int main(int argc, char *argv[]){ void (*f)(); char x[4]; memcpy(x, shellcode, sizeof(shellcode)); f = (void (*)()) x; f(); return 0; }
C
#include<stdio.h> #include<stdlib.h> void strToInts(char *ipAdd, int* iArr )//ipַתͣ洢iArr { char temp[4] = {0}; char *p = ipAdd; int i =0; int j= 0; while (*p != '\0')//ǰ'.'ַָת { if (*p != '.') { temp [j] = *p; j++; ++p; } else { iArr[i] = atoi(temp); memset(temp,0,sizeof(temp)); j = 0; i++; ++p; } } iArr[i] = atoi(temp);//һַת } int IsSameSubNetwork(char * pcIp1, char * pcIp2, char * pcSubNetworkMask) { /*ʵֹ*/ int i = 0; int Ip1[4]={0}; int Ip2[4] = {0}; int mask[4] ={0}; strToInts(pcIp1, Ip1); strToInts(pcIp2, Ip2); strToInts(pcSubNetworkMask, mask); for (; i < 4; ++i) { if ((Ip1[i]&mask[i]) != (Ip2[i] &mask[i]))//вͬģIpַͬһ { return 0; } } return 1; } int main() { printf("%d",IsSameSubNetwork("192.168.0.1", "192.168.0.254", "255.255.255.0")); system("pause"); return 0; }
C
#include "types.h" //////////////////////////////////////////////////////////////////////////////// //! //! \brief compare two char arrays //! //! \param aStr1 - pointer data array of chars //! \param aStr2 - pointer data array of chars //! //! \return TRUE if arrays are equals //! FALSE if arrays are not equals //! //////////////////////////////////////////////////////////////////////////////// BOOL strCompare(UINT8 aStr1[],UINT8 aStr2[]); //////////////////////////////////////////////////////////////////////////////// //! //! \brief convert UINT32 value to byte array UINT8 //! //! \param iValue - integer value //! \param acByteArray - pointer data array of bytes //! //////////////////////////////////////////////////////////////////////////////// void myitoa(UINT32 iValue, UINT8* acByteArray); //////////////////////////////////////////////////////////////////////////////// //! //! \brief set all values of byte array UINT8 to '\0' //! //! \param acByteArray - pointer data array of bytes //! \param sLength - length of array of bytes //! //////////////////////////////////////////////////////////////////////////////// void clearByteArray(UINT8* acByteArray, UINT16 sLength); //////////////////////////////////////////////////////////////////////////////// //! //! \brief convert UINT16 to byte array UINT8 //! //! \param aByteArr - pointer data array of bytes //! \param sNum - UINT16 number to convert //! //////////////////////////////////////////////////////////////////////////////// void ConvertShortToByteArray(UINT16 sNum, UINT8 *aByteArr); //////////////////////////////////////////////////////////////////////////////// //! //! \brief convert UINT32 to byte array UINT8 //! //! \param aByteArr - pointer data array of bytes //! \param sNum - UINT32 number to convert //! //////////////////////////////////////////////////////////////////////////////// void ConvertIntToByteArray(UINT32 sNum, UINT8 *aByteArr); //////////////////////////////////////////////////////////////////////////////// //! //! \brief convert byte array UINT8 to UINT32 //! //! \param aByteArr - pointer data array of bytes //! //////////////////////////////////////////////////////////////////////////////// UINT32 ConvertByteArrayToInt(UINT8 *aByteArr); //////////////////////////////////////////////////////////////////////////////// //! //! \brief convert byte array UINT8 to UINT16 //! //! \param aByteArr - pointer data array of bytes //! //////////////////////////////////////////////////////////////////////////////// UINT16 ConvertByteArrayToShort(UINT8 *aByteArr); //////////////////////////////////////////////////////////////////////////////// //! //! \brief convert int array UINT32 to byie attay UINT8 //! //! \param aByteArr - pointer data array of bytes //! //////////////////////////////////////////////////////////////////////////////// void ConvertIntArrayToByteArray(UINT32 *aIntArray, UINT16 sIntArrLen, UINT8 *aByteArr); BOOL IsArrayContainsElement(UINT32 *aIntArray, UINT16 sIntArrLen, UINT32 iElement); UINT16 GetEntryNumOfArrayElement(UINT32 *aIntArray, UINT16 sIntArrLen, UINT32 iElement); void WriteOneByteArrayToAnother(UINT8 *aOneArray, UINT8 *aTwoArray, UINT16 sArrLen); UINT16 rot16(UINT16 x); UINT32 rot32(UINT32 x); BOOL isNumericChar(UINT8 x); UINT32 ConvertStrToInt(UINT8 *str); void convertHexToStr(UINT32 iValue, UINT8* acByteArray, UINT8 cByteAmt); BOOL IsArrCmp(UINT8 *arr1, UINT8 *arr2, UINT16 sLength);
C
/* * Copyright (C) 2017-2019 Alibaba Group Holding Limited */ /****************************************************************************** * @file csi_kernel.h * @brief header file for kernel definition * @version V1.0 * @date 02. June 2017 ******************************************************************************/ #ifndef _CSI_KERNEL_ #define _CSI_KERNEL_ #include <stdint.h> #include <errno.h> #ifdef __cplusplus extern "C" { #endif /* =================================================================================== */ /* Enumerations, structures, defines */ /* =================================================================================== */ /// Status code values returned by CSI-kernel functions. 0 - success, negative represents error code ,see errno.h typedef int32_t k_status_t; /// Kernel scheduler state. typedef enum { KSCHED_ST_INACTIVE = 0, ///< Inactive: The kernel is not ready yet. csi_kernel_init needs to be executed successfully. KSCHED_ST_READY = 1, ///< Ready: The kernel is not yet running. csi_kernel_start transfers the kernel to the running state. KSCHED_ST_RUNNING = 2, ///< Running: The kernel is initialized and running. KSCHED_ST_LOCKED = 3, ///< Locked: The kernel was locked with csi_kernel_sched_lock. The functions csi_kernel_sched_unlock or csi_kernel_sched_restore_lock unlocks it. KSCHED_ST_SUSPEND = 4, ///< Suspended: The kernel was suspended using csi_kernel_sched_suspend. The function csi_kernel_sched_resume returns to normal operation KSCHED_ST_ERROR = 5 ///< Error: An error occurred. } k_sched_stat_t; /// task state. typedef enum { KTASK_ST_INACTIVE = 0, ///< Inactive. KTASK_ST_READY = 1, ///< Ready. KTASK_ST_RUNNING = 2, ///< Running. KTASK_ST_BLOCKED = 3, ///< Blocked. KTASK_ST_TERMINATED = 4, ///< Terminated. KTASK_ST_ERROR = 5 ///< Error: An error occurred. } k_task_stat_t; /// timer state. typedef enum { KTIMER_ST_INACTIVE = 0, ///< not running KTIMER_ST_ACTIVE = 1, ///< running } k_timer_stat_t; /// Timer type. typedef enum { KTIMER_TYPE_ONCE = 0, ///< One-shot timer. KTIMER_TYPE_PERIODIC = 1 ///< Repeating timer. } k_timer_type_t; /// event option. typedef enum { KEVENT_OPT_SET_ANY = 0, ///< Check any bit in flags to be 1. KEVENT_OPT_SET_ALL = 1, ///< Check all bits in flags to be 1. KEVENT_OPT_CLR_ANY = 2, ///< Check any bit in flags to be 0. KEVENT_OPT_CLR_ALL = 3 ///< Check all bits in flags to be 0. } k_event_opt_t; /// Priority definition. typedef enum { KPRIO_IDLE = 0, ///< priority: idle (lowest) KPRIO_LOW0 , ///< priority: low KPRIO_LOW1 , ///< priority: low + 1 KPRIO_LOW2 , ///< priority: low + 2 KPRIO_LOW3 , ///< priority: low + 3 KPRIO_LOW4 , ///< priority: low + 4 KPRIO_LOW5 , ///< priority: low + 5 KPRIO_LOW6 , ///< priority: low + 6 KPRIO_LOW7 , ///< priority: low + 7 KPRIO_NORMAL_BELOW0 , ///< priority: below normal KPRIO_NORMAL_BELOW1 , ///< priority: below normal + 1 KPRIO_NORMAL_BELOW2 , ///< priority: below normal + 2 KPRIO_NORMAL_BELOW3 , ///< priority: below normal + 3 KPRIO_NORMAL_BELOW4 , ///< priority: below normal + 4 KPRIO_NORMAL_BELOW5 , ///< priority: below normal + 5 KPRIO_NORMAL_BELOW6 , ///< priority: below normal + 6 KPRIO_NORMAL_BELOW7 , ///< priority: below normal + 7 KPRIO_NORMAL , ///< priority: normal (default) KPRIO_NORMAL1 , ///< priority: normal + 1 KPRIO_NORMAL2 , ///< priority: normal + 2 KPRIO_NORMAL3 , ///< priority: normal + 3 KPRIO_NORMAL4 , ///< priority: normal + 4 KPRIO_NORMAL5 , ///< priority: normal + 5 KPRIO_NORMAL6 , ///< priority: normal + 6 KPRIO_NORMAL7 , ///< priority: normal + 7 KPRIO_NORMAL_ABOVE0 , ///< priority: above normal + 1 KPRIO_NORMAL_ABOVE1 , ///< priority: above normal + 2 KPRIO_NORMAL_ABOVE2 , ///< priority: above normal + 3 KPRIO_NORMAL_ABOVE3 , ///< priority: above normal + 4 KPRIO_NORMAL_ABOVE4 , ///< priority: above normal + 5 KPRIO_NORMAL_ABOVE5 , ///< priority: above normal + 6 KPRIO_NORMAL_ABOVE6 , ///< priority: above normal + 7 KPRIO_NORMAL_ABOVE7 , ///< priority: above normal + 8 KPRIO_HIGH0 , ///< priority: high KPRIO_HIGH1 , ///< priority: high + 1 KPRIO_HIGH2 , ///< priority: high + 2 KPRIO_HIGH3 , ///< priority: high + 3 KPRIO_HIGH4 , ///< priority: high + 4 KPRIO_HIGH5 , ///< priority: high + 5 KPRIO_HIGH6 , ///< priority: high + 6 KPRIO_HIGH7 , ///< priority: high + 7 KPRIO_REALTIME0 , ///< priority: realtime + 1 KPRIO_REALTIME1 , ///< priority: realtime + 2 KPRIO_REALTIME2 , ///< priority: realtime + 3 KPRIO_REALTIME3 , ///< priority: realtime + 4 KPRIO_REALTIME4 , ///< priority: realtime + 5 KPRIO_REALTIME5 , ///< priority: realtime + 6 KPRIO_REALTIME6 , ///< priority: realtime + 7 KPRIO_REALTIME7 , ///< priority: realtime + 8 KPRIO_ISR , ///< priority: Reserved for ISR deferred thread KPRIO_ERROR ///< Illegal priority } k_priority_t; /// Entry point of a task. typedef void (*k_task_entry_t)(void *arg); /// Entry point of a timer call back function. typedef void (*k_timer_cb_t)(void *arg); /// \details Task handle identifies the task. typedef void *k_task_handle_t; /// \details Timer handle identifies the timer. typedef void *k_timer_handle_t; /// \details Event Flags handle identifies the event flags. typedef void *k_event_handle_t; /// \details Mutex handle identifies the mutex. typedef void *k_mutex_handle_t; /// \details Semaphore handle identifies the semaphore. typedef void *k_sem_handle_t; /// \details Memory Pool handle identifies the memory pool. typedef void *k_mpool_handle_t; /// \details Message Queue handle identifies the message queue. typedef void *k_msgq_handle_t; /* =================================================================================== */ /* Kernel Management Functions */ /* =================================================================================== */ /// Initialize the Kernel. Before it is successfully executed, no RTOS function should be called /// \return execution status code. \ref k_status_t k_status_t csi_kernel_init(void); /// Start the kernel .It will not return to its calling function in case of success /// \return execution status code. \ref k_status_t k_status_t csi_kernel_start(void); /// Get the current kernel state. /// \return current kernel state \ref k_sched_stat_t . k_sched_stat_t csi_kernel_get_stat(void); /* =================================================================================== */ /* scheduler Management Functions */ /* =================================================================================== */ /// Lock the scheduler. /// \return previous lock state (1 - locked, 0 - not locked, error code if negative). int32_t csi_kernel_sched_lock(void); /// Unlock the scheduler. /// \return previous lock state (1 - locked, 0 - not locked, error code if negative). int32_t csi_kernel_sched_unlock(void); /// Restore the scheduler lock state. /// \param[in] lock lock state obtained by \ref csi_kernel_sched_lock or \ref csi_kernel_sched_unlock. /// \return new lock state (1 - locked, 0 - not locked, error code if negative). int32_t csi_kernel_sched_restore_lock(int32_t lock); /// Suspend the scheduler. /// \return time in ticks, for how long the system can sleep or power-down. uint32_t csi_kernel_sched_suspend(void); /// Resume the scheduler. /// \param[in] sleep_ticks time in ticks for how long the system was in sleep or power-down mode. void csi_kernel_sched_resume(uint32_t sleep_ticks); /* =================================================================================== */ /* Task Management Functions */ /* =================================================================================== */ /// Create a task and add it to Active Tasks. /// \param[in] task task function. /// \param[in] name the name of task. /// \param[in] arg pointer that is passed to the task function as start argument. /// \param[in] prio task priority. /// \param[in] time_quanta the amount of time (in clock ticks) for the time quanta when round robin is enabled,if Zero, then use FIFO sched /// \param[in] stack stack base. /// \param[in] stack_size stack size. /// \param[in] task_handle reference to a task handle. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_task_new(k_task_entry_t task, const char *name, void *arg, k_priority_t prio, uint32_t time_quanta, void *stack, uint32_t stack_size, k_task_handle_t *task_handle); /// Delete a task. /// \param[in] task_handle task handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_task_del(k_task_handle_t task_handle); /// Return the task handle of the current running task. /// \return task handle for reference by other functions or NULL in case of error. k_task_handle_t csi_kernel_task_get_cur(void); /// Get current task state of a task. /// \param[in] task_handle task handle to operate. /// \return current task state of the specified task. k_task_stat_t csi_kernel_task_get_stat(k_task_handle_t task_handle); /// Change priority of a task. /// \param[in] task_handle task handle to operate. /// \param[in] priority new priority value for the task function. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_task_set_prio(k_task_handle_t task_handle, k_priority_t priority); /// Get current priority of a task. /// \param[in] task_handle task handle to operate. /// \return current priority value of the specified task.negative indicates error code. k_priority_t csi_kernel_task_get_prio(k_task_handle_t task_handle); /// Get name of a task. /// \param[in] task_handle task handle to operate. /// \return name of the task. const char *csi_kernel_task_get_name(k_task_handle_t task_handle); /// Suspend execution of a task. /// \param[in] task_handle task handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_task_suspend(k_task_handle_t task_handle); /// Resume execution of a task. /// \param[in] task_handle task handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_task_resume(k_task_handle_t task_handle); /// Terminate execution of a task. /// \param[in] task_handle task handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_task_terminate(k_task_handle_t task_handle); /// Exit from the calling task. /// \return none void csi_kernel_task_exit(void); /// Pass control to next task that is in state \b READY. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_task_yield(void); /// Get number of active tasks. /// \return number of active tasks. uint32_t csi_kernel_task_get_count(void); /// Get stack size of a task. /// \param[in] task_handle task handle to operate. /// \return stack size in bytes. uint32_t csi_kernel_task_get_stack_size(k_task_handle_t task_handle); /// Get available stack space of a thread based on stack watermark recording during execution. /// \param[in] task_handle task handle to operate. /// \return remaining stack space in bytes. uint32_t csi_kernel_task_get_stack_space(k_task_handle_t task_handle); /// Enumerate active tasks. /// \param[out] task_array pointer to array for retrieving task handles. /// \param[in] array_items maximum number of items in array for retrieving task handles. /// \return number of enumerated tasks. uint32_t csi_kernel_task_list(k_task_handle_t *task_array, uint32_t array_items); /// System enter interrupt status. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_intrpt_enter(void); /// System exit interrupt status. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_intrpt_exit(void); /* =================================================================================== */ /* Generic time Functions */ /* =================================================================================== */ /// Waits for a time period specified in kernel ticks. /// \param[in] ticks time ticks value /// \return execution status code. \ref k_status_t k_status_t csi_kernel_delay(uint32_t ticks); /// Waits until an absolute time (specified in kernel ticks) is reached. /// \param[in] ticks absolute time in ticks /// \return execution status code. \ref k_status_t k_status_t csi_kernel_delay_until(uint64_t ticks); /// Convert kernel ticks to ms. /// \param[in] ticks ticks which will be converted to ms /// \return the ms of the ticks. uint64_t csi_kernel_tick2ms(uint32_t ticks); /// Convert ms to kernel ticks. /// \param[in] ms ms which will be converted to ticks /// \return the ticks of the ms. uint64_t csi_kernel_ms2tick(uint32_t ms); /// Waits for a time period specified in ms. /// \param[in] ms time to be delayed in ms /// \return execution status code. \ref k_status_t k_status_t csi_kernel_delay_ms(uint32_t ms); /// Get kernel ticks. /// \return kernel ticks number uint64_t csi_kernel_get_ticks(void); /// Get the RTOS kernel tick frequency. /// \return frequency of the kernel tick. uint32_t csi_kernel_get_tick_freq(void); /// Get the RTOS kernel system timer frequency. /// \return frequency of the system timer. uint32_t csi_kernel_get_systimer_freq(void); /* =================================================================================== */ /* Timer Management Functions */ /* =================================================================================== */ /// Create and Initialize a timer. /// \param[in] func start address of a timer call back function. /// \param[in] type time type, \ref k_timer_type_t. /// \param[in] arg argument to the timer call back function. /// \return timer handle for reference by other functions or NULL in case of error. k_timer_handle_t csi_kernel_timer_new(k_timer_cb_t func, k_timer_type_t type, void *arg); /// Delete a timer. /// \param[in] timer_handle timer handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_timer_del(k_timer_handle_t timer_handle); /// Start or restart a timer. /// \param[in] timer_handle timer handle to operate. /// \param[in] ticks time out value in ticks /// \return execution status code. \ref k_status_t k_status_t csi_kernel_timer_start(k_timer_handle_t timer_handle, uint32_t ticks); /// Stop a timer. /// \param[in] timer_handle timer handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_timer_stop(k_timer_handle_t timer_handle); /// Check if a timer is running. /// \param[in] timer_handle timer handle to operate. /// \return \ref k_timer_stat_t. k_timer_stat_t csi_kernel_timer_get_stat(k_timer_handle_t timer_handle); /* =================================================================================== */ /* Event Management Functions */ /* =================================================================================== */ /// Create and Initialize an Event Flags object. /// \return event flags handle for reference by other functions or NULL in case of error. k_event_handle_t csi_kernel_event_new(void); /// Delete an Event Flags object. /// \param[in] ev_handle event flags handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_event_del(k_event_handle_t ev_handle); /// Set the specified Event Flags. /// \param[in] ev_handle event flags handle to operate. /// \param[in] flags specifies the flags that shall be set. /// \param[out] ret_flags The value of the event after setting. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_event_set(k_event_handle_t ev_handle, uint32_t flags, uint32_t *ret_flags); /// Clear the specified Event Flags. /// \param[in] ev_handle event flags handle to operate. /// \param[in] flags specifies the flags that shall be clear. /// \param[out] ret_flags event flags before clearing. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_event_clear(k_event_handle_t ev_handle, uint32_t flags, uint32_t *ret_flags); /// Get the current Event Flags. This function allows the user to know “Who did it!” /// \param[in] ev_handle event flags handle to operate. /// \param[out] ret_flags The value of the current event. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_event_get(k_event_handle_t ev_handle, uint32_t *ret_flags); /// Wait for one or more Event Flags to become signaled. /// \param[in] ev_handle event flags handle to operate. /// \param[in] flags specifies the flags to wait for. /// \param[in] options specifies flags options, \ref k_event_opt_t. /// \param[in] clr_on_exit 1 - event flags will be cleared before exit, otherwise event flags are not altered /// \param[out] actl_flags The value of the event at the time either the bits being waited for became set, or the block time expired. /// \param[in] timeout time out value in ticks if > 0, 0 in case of no time-out, negative in case of wait forever /// \return execution status code. \ref k_status_t k_status_t csi_kernel_event_wait(k_event_handle_t ev_handle, uint32_t flags, k_event_opt_t options, uint8_t clr_on_exit, uint32_t *actl_flags, int32_t timeout); /* =================================================================================== */ /* Mutex Management Functions */ /* =================================================================================== */ /// Create and Initialize a Mutex object. /// \return mutex handle for reference by other functions or NULL in case of error. k_mutex_handle_t csi_kernel_mutex_new(void); /// Delete a Mutex object. /// \param[in] mutex_handle mutex handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_mutex_del(k_mutex_handle_t mutex_handle); /// Acquire a Mutex or timeout if it is locked. /// \param[in] mutex_handle mutex handle to operate. /// \param[in] timeout time out value in ticks if > 0, 0 in case of no time-out, negative in case of wait forever /// \return execution status code. \ref k_status_t k_status_t csi_kernel_mutex_lock(k_mutex_handle_t mutex_handle, int32_t timeout); /// Release a Mutex that was acquired by \ref csi_kernel_mutex_new. /// \param[in] mutex_handle mutex handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_mutex_unlock(k_mutex_handle_t mutex_handle); /// Get Thread which owns a Mutex object. /// \param[in] mutex_handle mutex handle to operate. /// \return task handle or NULL when mutex was not acquired. k_task_handle_t csi_kernel_mutex_get_owner(k_mutex_handle_t mutex_handle); /* =================================================================================== */ /* Semaphore Management Functions */ /* =================================================================================== */ /// Create and Initialize a Semaphore object. /// \param[in] max_count maximum number of available tokens. /// \param[in] initial_count initial number of available tokens. /// \return semaphore handle for reference by other functions or NULL in case of error. k_sem_handle_t csi_kernel_sem_new(int32_t max_count, int32_t initial_count); /// Delete a Semaphore object. /// \param[in] sem_handle semaphore handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_sem_del(k_sem_handle_t sem_handle); /// Acquire a Semaphore token or timeout if no tokens are available. /// \param[in] sem_handle semaphore handle to operate. /// \param[in] timeout time out value in ticks if > 0, 0 in case of no time-out, negative in case of wait forever /// \return execution status code. \ref k_status_t k_status_t csi_kernel_sem_wait(k_sem_handle_t sem_handle, int32_t timeout); /// Release a Semaphore token that was acquired by \ref csi_kernel_sem_wait. /// \param[in] sem_handle semaphore handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_sem_post(k_sem_handle_t sem_handle); /// Get current Semaphore token count. /// \param[in] sem_handle semaphore handle to operate. /// \return number of tokens available. negative indicates error code. int32_t csi_kernel_sem_get_count(k_sem_handle_t sem_handle); /* =================================================================================== */ /* Memory Pool Management Functions */ /* =================================================================================== */ /// Create and Initialize a Memory Pool object. /// \param[in] p_addr memory block base address. /// \param[in] block_count maximum number of memory blocks in memory pool. /// \param[in] block_size memory block size in bytes. /// \return memory pool handle for reference by other functions or NULL in case of error. k_mpool_handle_t csi_kernel_mpool_new(void *p_addr, int32_t block_count, int32_t block_size); /// Delete a Memory Pool object. /// \param[in] mp_handle memory pool handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_mpool_del(k_mpool_handle_t mp_handle); /// Allocate a memory block from a Memory Pool. /// \param[in] mp_handle memory pool handle to operate. /// \param[in] timeout time out value in ticks if > 0, 0 in case of no time-out, negative in case of wait forever /// \return address of the allocated memory block or NULL in case of no memory is available. void *csi_kernel_mpool_alloc(k_mpool_handle_t mp_handle, int32_t timeout); /// Return an allocated memory block back to a Memory Pool. /// \param[in] mp_handle memory pool handle to operate. /// \param[in] block address of the allocated memory block to be returned to the memory pool. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_mpool_free(k_mpool_handle_t mp_handle, void *block); /// Get number of memory blocks used in a Memory Pool. /// \param[in] mp_handle memory pool handle to operate. /// \return number of memory blocks used. negative indicates error code. int32_t csi_kernel_mpool_get_count(k_mpool_handle_t mp_handle); /// Get maximum number of memory blocks in a Memory Pool. /// \param[in] mp_handle memory pool handle to operate. /// \return maximum number of memory blocks. uint32_t csi_kernel_mpool_get_capacity(k_mpool_handle_t mp_handle); /// Get memory block size in a Memory Pool. /// \param[in] mp_handle memory pool handle to operate. /// \return memory block size in bytes. uint32_t csi_kernel_mpool_get_block_size(k_mpool_handle_t mp_handle); /* =================================================================================== */ /* Message Queue Management Functions */ /* =================================================================================== */ /// Create and Initialize a Message Queue object. /// \param[in] msg_count maximum number of messages in queue. /// \param[in] msg_size maximum message size in bytes. /// \return message queue handle for reference by other functions or NULL in case of error. k_msgq_handle_t csi_kernel_msgq_new(int32_t msg_count, int32_t msg_size); /// Delete a Message Queue object. /// \param[in] mq_handle message queue handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_msgq_del(k_msgq_handle_t mq_handle); /// Put a Message into a Queue or timeout if Queue is full. /// \param[in] mq_handle message queue handle to operate. /// \param[in] msg_ptr pointer to buffer with message to put into a queue. /// \param[in] front_or_back specify this msg to be put to front or back. 1 - front, 0 -back /// \param[in] timeout time out value in ticks if > 0, 0 in case of no time-out, negative in case of wait forever /// \return execution status code. \ref k_status_t k_status_t csi_kernel_msgq_put(k_msgq_handle_t mq_handle, const void *msg_ptr, uint8_t front_or_back, int32_t timeout); /// Get a Message from a Queue or timeout if Queue is empty. /// \param[in] mq_handle message queue handle to operate. /// \param[out] msg_ptr pointer to buffer for message to get from a queue. /// \param[in] timeout time out value in ticks if > 0, 0 in case of no time-out, negative in case of wait forever /// \return execution status code. \ref k_status_t k_status_t csi_kernel_msgq_get(k_msgq_handle_t mq_handle, void *msg_ptr, int32_t timeout); /// Get number of queued messages in a message queue. /// \param[in] mq_handle message queue handle to operate. /// \return number of queued messages.negative indicates error code. int32_t csi_kernel_msgq_get_count(k_msgq_handle_t mq_handle); /// Get maximum number of messages in a message queue. /// \param[in] mq_handle message queue handle to operate. /// \return maximum number of messages. uint32_t csi_kernel_msgq_get_capacity(k_msgq_handle_t mq_handle); /// Get maximum message size in a message queue. /// \param[in] mq_handle message queue handle to operate. /// \return maximum message size in bytes. uint32_t csi_kernel_msgq_get_msg_size(k_msgq_handle_t mq_handle); /// Reset a Message Queue to initial empty state. /// \param[in] mq_handle message queue handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_msgq_flush(k_msgq_handle_t mq_handle); /* =================================================================================== */ /* Heap Management Functions */ /* =================================================================================== */ /// Allocates size bytes and returns a pointer to the allocated memory. /// \param[in] size Allocates size bytes. /// \param[in] caller the function who call this interface or NULL. /// \return a pointer to the allocated memory. void *csi_kernel_malloc(int32_t size, void *caller); /// Frees the memory space pointed to by ptr /// \param[in] ptr a pointer to memory block, return by csi_kernel_malloc or csi_kernel_realloc. /// \param[in] caller the function who call this interface or NULL. /// \return void void csi_kernel_free(void *ptr, void *caller); /// Changes the size of the memory block pointed to by ptr to size bytes /// \param[in] ptr a pointer to memory block, return by csi_kernel_malloc or csi_kernel_realloc. /// \param[in] size Allocates size bytes. /// \param[in] caller the function who call this interface or NULL. /// \return a pointer to the allocated memory. void *csi_kernel_realloc(void *ptr, int32_t size, void *caller); /// Get csi memory used info. /// \param[out] total the total memory can be use. /// \param[out] used the used memory by malloc. /// \param[out] free the free memory can be use. /// \param[out] peak the peak memory used. /// \return execution status code. \ref k_status_t. k_status_t csi_kernel_get_mminfo(int32_t *total, int32_t *used, int32_t *free, int32_t *peak); /// Dump csi memory . /// \param void /// \return execution status code. \ref k_status_t. k_status_t csi_kernel_mm_dump(void); #ifdef __cplusplus } #endif #endif // _CSI_KERNEL_
C
#include<stdio.h> #include<conio.h> void main() { int number,sum=0,count=1; do { printf("Enter a number : \n"); scanf("%d",&number); sum=sum+number; count++; }while(count<=5); printf("Print the result : %d \n",sum); getch(); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc,char *argv[]) { char s[] = " hello|world|do|you|work"; char *sep = "|"; char *p; // printf("%s\n",strtok(s,sep)); strtok(s,sep); while((p = strtok(NULL,sep))) { printf("%s\n",p); } return 0; }
C
/* * main.c * * Created on: 09/05/2013 * Author: masc */ #include <stdio.h> int main(void) { char c = 'D'; while (c < 'L') { if (!(c % 2)) c++; else c += 5; printf("%c", c); } return 0; }
C
/***************************************************************************** * Copyright (C) Krutika Sanjay Anasane [email protected] * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. *****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include "maths.h" #include <math.h> #include <sys/types.h> /* for open() */ #include <sys/stat.h> /* for open() */ #include <fcntl.h> /* for open() */ #include <unistd.h> /* for read() */ #include <errno.h> enum function{EXP, ABS, ROUND, ISNAN, ISINF, ISFINITE, GREATER, GREATEREQUAL, LESS, LESSEQUAL, SINX, COSX, TANX, ASIN, ACOS, ATAN, SQRT, CUBEROOT, CEIL, FLOOR}; /* Struct contains integer representing function to used; float, double, long double, represents input value to function written for float, double, long double data type respectively. */ typedef struct data { int testno; float x; double y; long double z; }data; /* Floating point values should not be compared using either the == or != operators. Most floating point values have no exact binary representation and have a limited precision i.e cannot be precisely represented using binary floating point numbers. */ /* fltcmpf, fltcmp, fltcmpl compares two float, double, long double values and return 1 if they are equal and 0 if they are not. Two numbers with value +Infinity or -Infinity can't be compared directly; these function returns non zero value if both arguments are +infinity or -infinity and 0 if not. Similarly these functions handle nan cases. */ int fltcmpf(float x, float y); int fltcmpf(float x, float y) { if((x - y) <= (PRECISION_F * y) || (x - y) >= (PRECISION_F * y)) return 1; else if(x == INFINITY && y == INFINITY) return 2; else if(x == -INFINITY && y == -INFINITY) return 3; else if(x != x && y != y) return 4; else return 0; } int fltcmp(double x, double y); int fltcmp(double x, double y) { if((x - y) <= (PRECISION_F * y) || (x - y) >= (PRECISION_F * y)) return 1; else if(x == INFINITY && y == INFINITY) return 2; else if(x == -INFINITY && y == -INFINITY) return 3; else if(x != x && y != y) return 4; else return 0; } int fltcmpl(long double x, long double y); int fltcmpl(long double x, long double y) { if((x - y) <= (PRECISION_F * y) || (x - y) >= (PRECISION_F * y)) return 1; else if(x == INFINITY && y == INFINITY) return 2; else if(x == -INFINITY && y == -INFINITY) return 3; else if(x != x && y != y) return 4; else return 0; } /* test code log float = 23455 */ int main(int argc, char *argv[]) { FILE *fp; int i = 0; float t, m; double a, b; long double p, q; data arr[MAX]; if (argc != 2){ printf("usage: ./test1 <filename>\n" ); perror("failed\n"); return errno; } fp = fopen(argv[1], "r"); if (fp == NULL) { perror("bad address\n"); return errno; } while(fscanf(fp, "%d", &arr[i].testno) != -1) { switch(arr[i].testno) { case EXP: printf("-------------------------------\nCASE 0 : Exponential function\n"); fscanf(fp, "%f%lf%Lf", &arr[i].x, &arr[i].y, &arr[i].z); t = expof(arr[i].x); m = expf(arr[i].x); a = expo(arr[i].y); b = exp(arr[i].y); p = expol(arr[i].z); q = expl(arr[i].z); if(fltcmpf(t, m) && fltcmp(a, b) && fltcmpl(p, q)) printf("Pass\n-------------------------------\n\n"); else printf("Fail\n-------------------------------\n\n"); break; case ABS: printf("-------------------------------\nCASE 1 : Absolute value function\n"); fscanf(fp, "%f%lf%Lf", &arr[i].x, &arr[i].y, &arr[i].z); t = fabsolutef(arr[i].x); m = fabsf(arr[i].x); a = fabsolute(arr[i].y); b = fabs(arr[i].y); p = fabsolutel(arr[i].z); q = fabsl(arr[i].z); if(fltcmpf(t, m) && fltcmp(a, b) && fltcmpl(p, q)) printf("Pass\n-------------------------------\n\n"); else printf("Fail\n-------------------------------\n\n"); break; case ROUND: printf("-------------------------------\nCASE 2 : Round function\n"); fscanf(fp, "%f%lf%Lf", &arr[i].x, &arr[i].y, &arr[i].z); t = roundf(arr[i].x); m = rndf(arr[i].x); a = round(arr[i].y); b = rnd(arr[i].y); p = roundl(arr[i].z); q = rndl(arr[i].z); if(fltcmpf(t, m) && fltcmp(a, b) && fltcmpl(p, q)) printf("Pass\n-------------------------------\n\n"); else printf("Fail\n-------------------------------\n\n"); break; case ISNAN: printf("-------------------------------\nCASE 3 : Isnan function\n"); fscanf(fp, "%f%lf%Lf", &arr[i].x, &arr[i].y, &arr[i].z); t = isnan(arr[i].x); m = issnanf(arr[i].x); a = isnan(arr[i].y); b = issnan(arr[i].y); p = isnan(arr[i].z); q = issnanl(arr[i].z); if(fltcmpf(t, m) && fltcmp(a, b) && fltcmpl(p, q)) printf("Pass\n-------------------------------\n\n"); else printf("Fail\n-------------------------------\n\n"); break; case ISINF: printf("-------------------------------\nCASE 4 : Isinf function\n"); fscanf(fp, "%f%lf%Lf", &arr[i].x, &arr[i].y, &arr[i].z); t = isinf(arr[i].x); m = issinff(arr[i].x); a = isinf(arr[i].y); b = issinf(arr[i].y); p = isinf(arr[i].z); q = issinfl(arr[i].z); if(fltcmpf(t, m) && fltcmp(a, b) && fltcmpl(p, q)) printf("Pass\n-------------------------------\n\n"); else printf("Fail\n-------------------------------\n\n"); break; case ISFINITE: printf("-------------------------------\nCASE 5 : Isfinite function\n"); fscanf(fp, "%f%lf%Lf", &arr[i].x, &arr[i].y, &arr[i].z); t = isfinite(arr[i].x); m = issfinitef(arr[i].x); a = isfinite(arr[i].y); b = issfinite(arr[i].y); p = isfinite(arr[i].z); q = issfinitel(arr[i].z); if(fltcmpf(t, m) && fltcmp(a, b) && fltcmpl(p, q)) printf("Pass\n-------------------------------\n\n"); else printf("Fail\n-------------------------------\n\n"); break; case GREATER: printf("-------------------------------\nCASE 6 : Isgreater function\n"); fscanf(fp, "%f", &arr[i].x); t = isgreater(arr[i].x, 123.456); m = isgrt(arr[i].x, 123.456); if(fltcmpf(t, m)) printf("Pass\n-------------------------------\n\n"); else printf("Fail\n-------------------------------\n\n"); break; case GREATEREQUAL: printf("-------------------------------\nCASE 7 : Isgreaterequal function\n"); fscanf(fp, "%f", &arr[i].x); t = isgreaterequal(arr[i].x, 123.456); m = isgrteq(arr[i].x, 123.456); if(fltcmpf(t, m)) printf("Pass\n-------------------------------\n\n"); else printf("Fail\n-------------------------------\n\n"); break; case LESS: printf("-------------------------------\nCASE 8 : Isless function\n"); fscanf(fp, "%f", &arr[i].x); t = isless(arr[i].x, 123.456); m = isls(arr[i].x, 123.456); if(fltcmpf(t, m)) printf("Pass\n-------------------------------\n\n"); else printf("Fail\n-------------------------------\n\n"); break; case LESSEQUAL: printf("-------------------------------\nCASE 9 : Islessequal function\n"); fscanf(fp, "%f", &arr[i].x); t = islessequal(arr[i].x, 123.456); m = islseq(arr[i].x, 123.456); if(fltcmpf(t, m)) printf("Pass\n-------------------------------\n\n"); else printf("Fail\n-------------------------------\n\n"); break; case SINX: printf("-------------------------------\nCASE 10 : Sine function\n"); fscanf(fp, "%f%lf%Lf", &arr[i].x, &arr[i].y, &arr[i].z); t = sinf(arr[i].x); m = sinef(arr[i].x); a = sin(arr[i].y); b = sine(arr[i].y); p = sinl(arr[i].z); q = sinel(arr[i].z); if(fltcmpf(t, m) && fltcmp(a, b) && fltcmpl(p, q)) printf("Pass\n-------------------------------\n\n"); else printf("Fail\n-------------------------------\n\n"); break; case COSX: printf("-------------------------------\nCASE 11 : Cosine function\n"); fscanf(fp, "%f%lf%Lf", &arr[i].x, &arr[i].y, &arr[i].z); t = cosf(arr[i].x); m = cosinef(arr[i].x); a = cos(arr[i].y); b = cosine(arr[i].y); p = cosl(arr[i].z); q = cosinel(arr[i].z); if(fltcmpf(t, m) && fltcmp(a, b) && fltcmpl(p, q)) printf("Pass\n-------------------------------\n\n"); else printf("Fail\n-------------------------------\n\n"); break; case TANX: printf("-------------------------------\nCASE 12 : Tangent function\n"); fscanf(fp, "%f%lf%Lf", &arr[i].x, &arr[i].y, &arr[i].z); t = tanf(arr[i].x); m = tangentf(arr[i].x); a = tan(arr[i].y); b = tangent(arr[i].y); p = tanl(arr[i].z); q = tangentl(arr[i].z); if(fltcmpf(t, m) && fltcmp(a, b) && fltcmpl(p, q)) printf("Pass\n-------------------------------\n\n"); else printf("Fail\n-------------------------------\n\n"); break; case ASIN: printf("-------------------------------\nCASE 13 : Sine inverse function\n"); fscanf(fp, "%f%lf%Lf", &arr[i].x, &arr[i].y, &arr[i].z); t = asinf(arr[i].x); m = asinxf(arr[i].x); a = asin(arr[i].y); b = asinx(arr[i].y); p = asinl(arr[i].z); q = asinxl(arr[i].z); if(fltcmpf(t, m) && fltcmp(a, b) && fltcmpl(p, q)) printf("Pass\n-------------------------------\n\n"); else printf("Fail\n-------------------------------\n\n"); break; case ACOS: printf("-------------------------------\nCASE 14 : Cosine inverse function\n"); fscanf(fp, "%f%lf%Lf", &arr[i].x, &arr[i].y, &arr[i].z); t = acosf(arr[i].x); m = acosxf(arr[i].x); a = acos(arr[i].y); b = acosx(arr[i].y); p = acosl(arr[i].z); q = acosxl(arr[i].z); if(fltcmpf(t, m) && fltcmp(a, b) && fltcmpl(p, q)) printf("Pass\n-------------------------------\n\n"); else printf("Fail\n-------------------------------\n\n"); break; case ATAN: printf("-------------------------------\nCASE 15 : Tan inverse function\n"); fscanf(fp, "%f%lf%Lf", &arr[i].x, &arr[i].y, &arr[i].z); t = atanf(arr[i].x); m = atanxf(arr[i].x); a = atan(arr[i].y); b = atanx(arr[i].y); p = atanl(arr[i].z); q = atanxl(arr[i].z); if(fltcmpf(t, m) && fltcmp(a, b) && fltcmpl(p, q)) printf("Pass\n-------------------------------\n\n"); else printf("Fail\n-------------------------------\n\n"); break; case SQRT: printf("-------------------------------\nCASE 16 : Square root function\n"); fscanf(fp, "%f%lf%Lf", &arr[i].x, &arr[i].y, &arr[i].z); t = sqrtf(arr[i].x); m = squrtf(arr[i].x); a = sqrt(arr[i].y); b = squrt(arr[i].y); p = sqrtl(arr[i].z); q = squrtl(arr[i].z); if(fltcmpf(t, m) && fltcmp(a, b) && fltcmpl(p, q)) printf("Pass\n-------------------------------\n\n"); else printf("Fail\n-------------------------------\n\n"); break; case CUBEROOT: printf("-------------------------------\nCASE 17 : Cube root function\n"); fscanf(fp, "%f%lf%Lf", &arr[i].x, &arr[i].y, &arr[i].z); t = cbrtf(arr[i].x); m = cubrtf(arr[i].x); a = cbrt(arr[i].y); b = cubrt(arr[i].y); p = cbrtl(arr[i].z); q = cubrtl(arr[i].z); if(fltcmpf(t, m) && fltcmp(a, b) && fltcmpl(p, q)) printf("Pass\n-------------------------------\n\n"); else printf("Fail\n-------------------------------\n\n"); break; case CEIL: printf("-------------------------------\nCASE 18 : Ceiling function\n"); fscanf(fp, "%f%lf%Lf", &arr[i].x, &arr[i].y, &arr[i].z); t = ceilf(arr[i].x); m = ceilngf(arr[i].x); a = ceil(arr[i].y); b = ceilng(arr[i].y); p = ceill(arr[i].z); q = ceilngl(arr[i].z); if(fltcmpf(t, m) && fltcmp(a, b) && fltcmpl(p, q)) printf("Pass\n-------------------------------\n\n"); else printf("Fail\n-------------------------------\n\n"); break; case FLOOR: printf("-------------------------------\nCASE 19 : Floor function\n"); fscanf(fp, "%f%lf%Lf", &arr[i].x, &arr[i].y, &arr[i].z); t = floorf(arr[i].x); m = flrf(arr[i].x); a = floor(arr[i].y); b = flr(arr[i].y); p = floorl(arr[i].z); q = flrl(arr[i].z); if(fltcmpf(t, m) && fltcmp(a, b) && fltcmpl(p, q)) printf("Pass\n-------------------------------\n\n"); else printf("Fail\n-------------------------------\n\n"); break; default : break; } i++; } }
C
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../struct.h" extern s_global *g_global; void init_history(void) { char *home = getenv("HOME"); char *buf = malloc(sizeof (char) * (strlen(home) + 15)); strcpy(buf, home); strcat(buf, "/.42sh_history"); g_global->hist_file = buf; FILE *file = fopen(buf, "r"); g_global->hist_arr = calloc(200, sizeof (char *)); g_global->hist_ind = -1; if (file) { size_t len = 0; for (int i = 0; i < 200; i++) { getline(&g_global->hist_arr[i], &len, file); g_global->hist_arr[i][strlen(g_global->hist_arr[i]) - 1] = '\0'; } fclose(file); } else { for (int i = 0; i < 200; i++) g_global->hist_arr[i] = calloc(10, sizeof (char)); } } void free_history(void) { for (int i = 0; i < 200; i++) { free(g_global->hist_arr[i]); } free(g_global->hist_arr); } void write_history(void) { FILE *file = fopen(g_global->hist_file, "w"); for (int i = 0; i < 200; i++) { fputs(g_global->hist_arr[i], file); fputc('\n', file); } fclose(file); } void add_to_hist(char *buf) { if (strcmp(buf, g_global->hist_arr[0]) == 0) return; char *tmp = calloc(strlen(buf) + 1, sizeof (char)); strcpy(tmp, buf); free(g_global->hist_arr[199]); memmove(g_global->hist_arr + 1, g_global->hist_arr, sizeof (char *) * 199); g_global->hist_arr[0] = tmp; } char *get_history_ln(void) { if (g_global->hist_ind == -1) return ""; return g_global->hist_arr[g_global->hist_ind]; }
C
// COA-602 Tarea 9 Ejercicio 3 // Fecha de creacion: 10-Marzo-2020 /********************************************************************************************************************************* Lea una lista de salarios entre 5000 y 20000 de tamaño n < 30. Luego, clasifique la lista en tres estratos. 5000-10000, 10000-15000 y 15000-20000. Defina intervalos abiertos por la derecha. Para cada estrato, realice un conteo de salarios en cada estrato. Grafique un histograma con frecuencias relativas. Calcule las medias por estrato. Elabore una función f1, para leer la dimensión de la lista; una función f2 para leer los elementos de la lista; una función f3, para clasificar, y una función f4 para imprimir los resultados. Las funciones debe llamarse del el main(). **********************************************************************************************************************************/ #include <stdio.h> int f1(void); void f2(int n, int lista[]); void f3(int n, int lista[], int resultados[]); void f4(int n, int resultados[]); int main() { int n = f1(); int salarios[n]; int resultados[3] = {0}; f2(n, salarios); f3(n, salarios, resultados); f4(n, resultados); return 0; } int f1(void) { int n, fin; fin = 0; while (!fin) { printf("Ingresar tamaño de lista de salarios:\t"); scanf("%d", &n); if (n > 0) if (n < 30) { fin = 1; break; } printf("Tamaño invalido. Intente de nuevo.\n"); } return n; } void f2(int n, int lista[]) { int i, temp; for (i = 0; i < n; i++) { printf("\tIngresar salario %2d:\t", i + 1); scanf("%d", &temp); lista[i] = temp; } } void f3(int n, int lista[], int resultados[]) { int i; for (i = 0; i < n; i++) { if (lista[i] >= 5000) if (lista[i] < 10000) resultados[0]++; if (lista[i] >= 10000) if (lista[i] < 15000) resultados[1]++; if (lista[i] >= 15000) if (lista[i] < 20000) resultados[2]++; } } void f4(int n, int resultados[]) { int i, j; printf("\n"); for (i = 0; i < 3; i++) { switch (i) { case 0: printf(" [5000-10000)"); break; case 1: printf("[10000-15000)"); break; case 2: printf("[15000-20000)"); break; default: break; } printf("%3d:\t", resultados[i]); for (j = 1; j <= resultados[i]; j++) printf("*"); printf("\n"); } printf("\n"); }
C
#include <stdio.h> #include <libavformat/avformat.h> #include <libavcodec/avcodec.h> //////////////////////////////////////////////////////////////////////////////////////////////// // The following is a heap/priority queue -> https://en.wikipedia.org/wiki/Heap_(data_structure) // implementation where the data stored is AVFrame pointers and the order of the nodes is // determined by a comparison function passed to the constructor avframe_heap_create. // // As written this is a min heap. Will order items from min to max, and top of the heap // will always be the AVFrame with the minimum either coded_picture_number or display_picture_number // // This allows us to reorder frames on decode (presentation->coded order) with flexibility and also // without assuming an underlying // frame GOP structure. Extracting the min element from the heap is a cost of O(log n) n being the // maximum number of reference pictures in the underlying coded stream. We define a max capacity for the heap // but we are unlikely to ever get there. // #define MAX_REFERENCE_FRAMES 1000 typedef struct { AVFrame *q[MAX_REFERENCE_FRAMES]; int n; // elements in the queue int (* cmp)(AVFrame *, AVFrame *); } avframe_heap_t; int avframe_heap_parent(int n) { if (n==1) return -1; else return n/2; } int avframe_heap_young_child(int n) { return 2*n; } void avframe_heap_swap(avframe_heap_t *h, int a, int b) { AVFrame *tmp = h->q[a]; h->q[a] = h->q[b]; h->q[b] = tmp; } void avframe_heap_bubble_up( avframe_heap_t *h, int p ) { if( avframe_heap_parent(p) == -1 ) return; //heap root if( h->cmp( h->q[avframe_heap_parent(p)], h->q[p]) >= 0 ) { avframe_heap_swap(h, p, avframe_heap_parent(p)); avframe_heap_bubble_up(h, avframe_heap_parent(p)); } } void avframe_heap_insert( avframe_heap_t *h, AVFrame *f ) { if( h->n >= MAX_REFERENCE_FRAMES ) return; else { h->n += 1; h->q[h->n] = f; avframe_heap_bubble_up(h, h->n); } } // >0 if a>b // ==0 if a==b // <0 if a<b int avframe_heap_cmp_coded(AVFrame *a, AVFrame *b) { return a->coded_picture_number - b->coded_picture_number; } int avframe_heap_cmp_display(AVFrame *a, AVFrame *b) { return a->display_picture_number - b->display_picture_number; } avframe_heap_t *avframe_heap_create(int (* cmp)(AVFrame *, AVFrame *)) { avframe_heap_t *r = malloc(sizeof(avframe_heap_t)); r->n = 0; if(!cmp) r->cmp = avframe_heap_cmp_display; else r->cmp = cmp; return r; } void avframe_heap_destroy(avframe_heap_t *h) { free(h); } AVFrame *avframe_heap_peek_min( avframe_heap_t *h ) { if(h->n>0) { return h->q[1]; } else { return 0; } } void avframe_heap_bubble_down( avframe_heap_t *h, int p ) { int c,i,min_index; c = avframe_heap_young_child(p); min_index = p; // figure out which one of the two children, if any is the minimum if( c<=h->n && h->cmp( h->q[c], h->q[c+1] )<=0 && h->cmp( h->q[c], h->q[p] )<=0 ) { min_index = c; } else if( c+1 <= h->n && h->cmp( h->q[c+1], h->q[c] )<=0 && h->cmp( h->q[c+1], h->q[p] )<=0 ) { min_index = c+1; } if( min_index!=p) { avframe_heap_swap(h, p, min_index ); avframe_heap_bubble_down(h, min_index); } } AVFrame *avframe_heap_get_min( avframe_heap_t *h ) { AVFrame *min = NULL; if(h->n>0) { min = h->q[1]; h->q[1] = h->q[h->n]; h->n--; avframe_heap_bubble_down(h,1); } return min; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// // AVFormat/AVCodec routines follow // // // typedef struct { AVFormatContext *inctx; AVFormatContext *outctx; AVCodecContext *dec_ctx; AVCodecContext *enc_ctx; int vidstream_idx; } app_ctx_t; #define APPERROR -1 //////////////////////////////////////////////////////////////////////////////////////////////////////////// // open input file, setup decoder. Will pick the first video stream available on input // static int open_input(app_ctx_t *ctx, const char *fname) { int ret; unsigned int i; // open input AVFormatContext ctx->inctx = NULL; if ((ret=avformat_open_input(&(ctx->inctx), fname, NULL, NULL)) < 0){ fprintf(stderr, "avformat_open_input failed\n"); return ret; } // find streams in input if ((ret=avformat_find_stream_info(ctx->inctx, NULL)) < 0) { fprintf(stderr, "avformat_find_stream info failed\n"); return ret; } // setup decoder for the first video stream in input if any AVStream *vidstream = NULL; for( i=0; i< ctx->inctx->nb_streams; i++ ) { AVStream *st = ctx->inctx->streams[i]; if( st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ){ vidstream = st; ctx->vidstream_idx = st->index; break; } } if (!vidstream) { fprintf(stderr, "couldn't find video stream in input\n"); return APPERROR; } // find decoder AVCodec *dec = avcodec_find_decoder(vidstream->codecpar->codec_id); if(!dec) { fprintf(stderr, "failed to find decoder\n"); return APPERROR; } // create context for decoder AVCodecContext *codec_ctx = avcodec_alloc_context3(dec); if(!codec_ctx) { fprintf(stderr, "couldn't allocate codec context\n"); return APPERROR; } // copy parameters from stream onto codec context. potentially copies SPS and PPS from mp4 ret = avcodec_parameters_to_context(codec_ctx, vidstream->codecpar); if(ret<0) { fprintf(stderr, "failed to copy decoder pars from stream to codec\n"); return APPERROR; } // open decoder codec_ctx->framerate = av_guess_frame_rate( ctx->inctx, vidstream, NULL ); ret = avcodec_open2(codec_ctx, dec, NULL); if(ret<0) { fprintf(stderr, "couldn't open decoder\n"); return APPERROR; } ctx->dec_ctx = codec_ctx; // show input format av_dump_format(ctx->inctx, 0, fname, 0); return 0; } //////////////////////////////////////////////////////////////////////////////////////////////////////////// // open output file and setup y4m muxer. assumes only one video stream // static int open_output(app_ctx_t *ctx, const char *fname) { ctx->outctx = NULL; AVCodec *encoder; int ret; AVStream *out_stream; // allocates output format based on extension of file 'fname' avformat_alloc_output_context2(&ctx->outctx, NULL, NULL, fname); if(!ctx->outctx) { fprintf(stderr, "couldn't open output context\n"); return APPERROR; } out_stream = avformat_new_stream(ctx->outctx, NULL); if(!out_stream) { fprintf(stderr, "can't allocation output stream\n"); return APPERROR; } // allocate output stream for video of AV_CODEC_ID_WRAPPED_AVFRAME type encoder = avcodec_find_encoder(AV_CODEC_ID_WRAPPED_AVFRAME); if(!encoder) { fprintf(stderr, "couldn't allocate encoder\n"); return APPERROR; } // allocate encoder context ctx->enc_ctx = avcodec_alloc_context3(encoder); if(!ctx->enc_ctx) { fprintf(stderr,"couldn't allocate encoder context\n"); return APPERROR; } // we use the same format from the input ctx->enc_ctx->height = ctx->dec_ctx->height; ctx->enc_ctx->width = ctx->dec_ctx->width; ctx->enc_ctx->sample_aspect_ratio = ctx->dec_ctx->sample_aspect_ratio; ctx->enc_ctx->pix_fmt = encoder->pix_fmts ? encoder->pix_fmts[0] : ctx->dec_ctx->pix_fmt; ctx->enc_ctx->time_base = av_inv_q(ctx->dec_ctx->framerate); // open the actual codec ret = avcodec_open2(ctx->enc_ctx, encoder, NULL); if(ret<0) { fprintf(stderr, "couldn't open video encoder\n"); return ret; } // update parameters from encoder context to output stream ret = avcodec_parameters_from_context(out_stream->codecpar, ctx->enc_ctx); if(ret<0) { fprintf(stderr,"couldn't copy pars from encoder context to stream\n"); return ret; } out_stream->time_base = ctx->enc_ctx->time_base; // show input format av_dump_format(ctx->outctx, 0, fname, 1); // open output file ret = avio_open(&ctx->outctx->pb, fname, AVIO_FLAG_WRITE ); if(ret<0) { fprintf(stderr, "couldn't open file for writing\n"); return ret; } // write header ret = avformat_write_header(ctx->outctx, NULL); if( ret<0 ) { fprintf(stderr, "coudln't write output header\n"); return ret; } return 0; } /////////////////////////////////////////////////////////////////////////////////////// // writes video frame to output muxer // static int write_frame(app_ctx_t *ctx, AVFrame *frame) { AVPacket enc_packet; int got_frame; int ret; enc_packet.data = NULL; enc_packet.size = 0; av_init_packet(&enc_packet); ret = avcodec_encode_video2(ctx->enc_ctx, &enc_packet, frame, &got_frame); if(ret<0) return ret; // and mux int stream_index = 0; // we only have one output stream by design enc_packet.stream_index = stream_index; av_packet_rescale_ts(&enc_packet, ctx->enc_ctx->time_base, ctx->outctx->streams[stream_index]->time_base ); ret = av_interleaved_write_frame(ctx->outctx, &enc_packet); return ret; } /////////////////////////////////// // avframe_heap testing routines // AVFrame *test_alloc(int n) { AVFrame *r = av_frame_alloc(); r->coded_picture_number = n; r->display_picture_number = n; return r; } void avframe_heap_testing() { avframe_heap_t *h = avframe_heap_create(NULL); avframe_heap_insert(h, test_alloc(3)); avframe_heap_insert(h, test_alloc(4)); avframe_heap_insert(h, test_alloc(9)); avframe_heap_insert(h, test_alloc(7)); avframe_heap_insert(h, test_alloc(84)); avframe_heap_insert(h, test_alloc(1)); avframe_heap_insert(h, test_alloc(7)); avframe_heap_insert(h, test_alloc(16)); AVFrame *f; while(avframe_heap_peek_min(h)) { f = avframe_heap_get_min(h); printf("%d\n", f->coded_picture_number); av_frame_free(&f); } avframe_heap_destroy(h); } /////////////////////////////////////////// // main // // use debug flag to enable testing. It will exercise the heap testing routines. Also outputs // use coded_order=1 to output coded order [default] // int main(int argc, char *argv[]) { int ret; char *urlout = "file:out.y4m"; char *url; int debug = 0; if(argc==1) { printf("Usage: y4mcreator [file:input.mp4 | url] [out.y4m]\n"); return 0; } else if(argc==2) { url = argv[1]; } else if (argc==3) { url = argv[1]; urlout = argv[2]; } else if (argc==4) { url = argv[1]; urlout = argv[2]; debug = 1; } app_ctx_t ctx; AVPacket packet = { .data=NULL, .size = 0 }; unsigned int sidx; enum AVMediaType type; int isframe=0; AVFrame *frame=NULL; if(debug) avframe_heap_testing(); if(open_input(&ctx, url)<0) { fprintf(stderr, "failed to open input\n"); return APPERROR; } if(open_output(&ctx, urlout)<0) { fprintf(stderr, "failed to open output\n"); return APPERROR; } int i =0; int coded_order = 1; // switch to display either coded order or display order int nextidx = 0; // AVFrame heap creation avframe_heap_t *frame_heap = avframe_heap_create(coded_order ? avframe_heap_cmp_coded : avframe_heap_cmp_display ); // main loop while(1) { // read data from demuxer if ((ret = av_read_frame(ctx.inctx, &packet))<0 ) break; sidx = packet.stream_index; type = ctx.inctx->streams[sidx]->codecpar->codec_type; // allocate AVFrame frame = av_frame_alloc(); if(!frame) { ret = AVERROR(ENOMEM); break; } // only deal with selected video track on input if( type==AVMEDIA_TYPE_VIDEO && sidx==ctx.vidstream_idx ) { // decode video ret= avcodec_decode_video2( ctx.dec_ctx, frame, &isframe, &packet); if(ret<0) { av_frame_free(&frame); fprintf(stderr, "couldn't decode frame %d", i); break; } // if frame was decoded push it onto the heap if(isframe) { frame->width = ctx.enc_ctx->width; frame->height = ctx.enc_ctx->height; frame->format = ctx.enc_ctx->pix_fmt; frame->display_picture_number = nextidx; avframe_heap_insert( frame_heap, frame ); } else { av_frame_free(&frame); } // At this poing we have buffered frames into the heap. The frame on top of the heap // is the one with the minimum coded_picture_number or display_picture_number. // We know what the next frame to be written is, nextidx, so we just have keep checking // the top of the heap for consecutive indexes. A top of the heap number that is higher // than nextidx implies we are still waiting for the frame to passed down from the decode // functions. // // Note we are still using the heap for presentation order when it's not necessary. It does // however allows us to have the same code flow for both if we funnel everything through the heap. while(1) { AVFrame *m = avframe_heap_peek_min(frame_heap); if(m) { int minidx = coded_order ? m->coded_picture_number : m->display_picture_number; if(minidx == nextidx) { avframe_heap_get_min(frame_heap); // pop top of the heap. Frame already in m from calling avframe_heap_peek_min() m->pts = nextidx*1001; ret = write_frame(&ctx, m ); if(ret<0) { fprintf(stderr,"write frame %d failed\n", i); av_frame_free(&m); break; } if(debug) printf("%d ", minidx); nextidx++; av_frame_free(&m); } else { break; } } else { break; } } av_packet_unref(&packet); i++; } } avframe_heap_destroy(frame_heap); av_write_trailer(ctx.outctx); avcodec_free_context(&ctx.dec_ctx); avcodec_free_context(&ctx.enc_ctx); avformat_close_input(&ctx.inctx); avformat_free_context(ctx.outctx); return ret ? 1 : 0; }
C
#include "GL\glut.h" #include <math.h> GLdouble dvect[] = {0.25, 0.5, 0.0}; GLint circle_points = 100; const float PI=3.1415926; GLfloat xangle = 0; void vertexRender() { static GLfloat data[] = { 5, 5, 5, 1, 0, 1, 5, 5, -5, 0, 1, 1, -5, 5, -5, 1, 1, 1, -5, 5, 5, 1, 0, 1, 5, -5, 5, 0, 1, 1, -5, -5, 5, 1, 1, 1, -5, -5, -5, 1, 0, 1, 5, -5, -5, 0, 1, 1 }; static GLubyte index0[] = { 0,1,2, 0,2,3, 0,7,1, 0,4,7, 1,7,6, 1,6,2, 2,6,5, 2,3,5, 0,5,4, 0,3,5, 5,6,7, 4,5,7 }; glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 6*sizeof(GLfloat), data); glColorPointer(3, GL_FLOAT, 6*sizeof(GLfloat), &data[3]); glDrawElements(GL_TRIANGLES, sizeof(index0), GL_UNSIGNED_BYTE, index0); } void display(void) { int i; float center=0.5; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); xangle+=2.0; glRotatef(xangle,0,0,0); glLineWidth(1); // glColor3f(1.0, 1.0, 0.0); glBegin(GL_LINE_LOOP); glVertex2f(0.25,0.25); glVertex2f(0.75,0.25); glVertex2f(0.75,0.75); glVertex2f(0.25,0.75); glEnd(); //Բ glColor3f(1.0, 0.0, 0.0); glBegin(GL_LINE_LOOP); for(i=0;i<circle_points;i++){ GLdouble angle = 2*PI*i/circle_points; glVertex2f(center+cos(angle)*0.5, center+sin(angle)*0.5); } glEnd(); // vertexRender(); printf("loop\n"); glFlush(); } void setup() { glClearColor(0.0f, 0.0f, 1.0f, 1.0f); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-10.0, 10.0, -10.0, 10.0, -111.0, 111.0); } int main() { glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutCreateWindow("Simple"); glutPositionWindow(100,100); glutDisplayFunc(display); setup(); glutMainLoop(); return 0; }
C
#include "holberton.h" /** * create_file - Create a file * @filename: file name * @text_content: content of file * Return: 1 or -1 */ int create_file(const char *filename, char *text_content) { int fd, i = 0, w; if (filename == NULL) return (-1); fd = open(filename, O_RDWR | O_CREAT | O_TRUNC, 0600); if (fd == -1) return (-1); if (text_content == NULL) return (1); while (text_content[i]) i++; w = write(fd, text_content, i); if (w == -1 || w != i) return (-1); return (1); }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <getopt.h> #include <sys/types.h> #include <sys/stat.h> #include "parse.h" /* filearg - for reading a list of things, either from a string (i.e., * command-line argument) or from a file. Returns a semicolon-separated * list. * Its arguments are: * arg - either the list itself, or "file=filename" which has it * space, length - if the list is in a file, space to read it into. * If no space is provided (space=NULL, length=0), it allocates * it as needed. */ /* semicolonize - only set up temporary outposts */ void semicolonize(char *space) { while (*space) { if (isspace(*space)) { /* duh? */ if (*(space+1)) *space = ';'; else *space = '\0'; } ++space; } } char * filetoarg(char *file, char *space, size_t length) { FILE *fp; int actual; struct stat statbuf; if (!(fp = fopen(file, "r"))) { perror(file); return NULL; } if (!space || !length) { if (fstat(fileno(fp), &statbuf) >= 0) { length = statbuf.st_size; } else { /* ummm */ length = BUFSIZ; } space = (char *)malloc(length+1); if (!space) return NULL; } actual = fread((void *)space, 1, length, fp); space[actual] = '\0'; fclose(fp); semicolonize(space); return space; } char * filearg(char *arg, char *space, int length) { char *value; char *const tokens[] = { "file", NULL }; while (*arg != '\0') { switch (getsubopt(&arg, tokens, &value)) { case 0: if (value == NULL) { fprintf(stderr, "Mising filename\n"); return NULL; } else return filetoarg(value, space, length); default: return value; } } } #ifdef TEST main(int argc, char **argv) { int c; int i; char aspace[20]; char bspace[30]; char cspace[40]; while ((c = getopt(argc, argv, "a:b:c:d:")) >= 0) { switch (c) { case 'a': printf("a arg: %s\n", optarg); printf("\t%s\n", filearg(optarg, aspace, 20)); break; case 'b': printf("b arg: %s\n", optarg); printf("\t%s\n", filearg(optarg, bspace, 30)); break; case 'c': printf("c arg: %s\n", optarg); printf("\t%s\n", filearg(optarg, cspace, 40)); break; case 'd': printf("d arg: %s\n", optarg); printf("\t%s\n", filearg(optarg, NULL, 0)); break; default: printf("unknown arg: %s\n", optarg); break; } } for (i=optind; i < argc; ++i) { printf("other arg: %s\n", argv[i]); } } #endif
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "automata.h" #include "parametros.h" int main(int argc, char** argv) { struct parametros_t parametros; unsigned int cant_celdas; unsigned char regla; char* nombre_arch_entrada; char* nombre_arch_salida; FILE* archivo_entrada; FILE* archivo_salida; if (cargar_parametros(&parametros, argc, argv)) return 1; if (validar_parametros(&parametros)) return 1; if (parametros.informacion) return 0; // Obtengo los parametros de entrada. regla = atoi(parametros.regla); cant_celdas = atoi(parametros.celdas); nombre_arch_entrada = parametros.arch_entrada; nombre_arch_salida = parametros.arch_salida; // Creo e inicializo la matriz unsigned char matriz [cant_celdas][cant_celdas]; inicializar_matriz(matriz,cant_celdas,cant_celdas); //Escribo el estado inicial en la primera fila de la matriz unsigned int i = 0; archivo_entrada = fopen(nombre_arch_entrada, "r"); while (!feof(archivo_entrada)) { if(i >= cant_celdas){ fprintf(stderr,"ERROR: la cantidad de celdas del archivo no coincide con el parametro pasado. \n"); return 0; } int valor; fscanf(archivo_entrada, "%1d", &valor); matriz[0][i] = (unsigned char) valor; i++; } fclose(archivo_entrada); int version; while(1){ printf("Ingrese un 0 para la version normal con archivos de salida, o 1 para la version por terminal: \n"); scanf("%d",&version); if (version == 1 || version == 0){ break; } fprintf(stderr,"Entrada no valida. Intentelo nuevamente. \n"); } if (version == 1){ // Version de terminal: permite determinar un paso variable para completar la matriz. int iteraciones = 0; int sumatoria = 0; while(sumatoria < (cant_celdas - 1)){ printf("Iteraciones realizadas hasta el momento: %d \n", sumatoria); printf("Ingrese la cantidad_celdas de iteraciones a realizar: \n"); scanf("%d",&iteraciones); if (iteraciones < 1){ fprintf(stderr, "Numero invalido, se realizara una iteracion. \n"); iteraciones = 1; } if(iteraciones > (cant_celdas - 1 - sumatoria)){ fprintf(stderr, "Se realizaran todas las iteraciones restantes. \n"); iteraciones = cant_celdas - 1 - sumatoria; } unsigned int fila; for (fila = 0; fila < iteraciones; fila++){ calcular_prox_fila(matriz, fila + sumatoria, regla, cant_celdas); imprimir_fila_matriz(matriz, fila + sumatoria, cant_celdas, stdout); } sumatoria += iteraciones; } return 0; } if (version == 0){ // Version normal con archivos de salida. //Se popula la matriz segun la regla dada. unsigned int fila; for (fila = 0; fila < (cant_celdas - 1); fila++){ calcular_prox_fila(matriz, fila, regla, cant_celdas); } char* arch_salida_pbm = strcat(nombre_arch_salida, ".pbm"); archivo_salida = fopen(arch_salida_pbm, "wb"); fprintf(archivo_salida, "P1\n"); fprintf(archivo_salida, "# Esto es una matriz completa\n"); fprintf(archivo_salida, "%d %d\n",cant_celdas*4,cant_celdas*4); imprimir_matriz_amplificada(matriz,cant_celdas,cant_celdas,archivo_salida); fclose(archivo_salida); return 0; } fprintf(stderr,"Error: no se ejecuto ninguna version. \n"); return 0; }
C
/* * Delta programming language */ #include "delta/delta.h" #include <math.h> /** * @category modules/core/math * * @brief Find lowest value. * @syntax number min ( array values ) * @syntax number min ( number value1 , number value2 [, number value3... ] ) * * If the first and only parameter is an array, min() returns the lowest value in that array. If at * least two parameters are provided, min() returns the smallest of these values. * * @param values An array containing the values. * @return min() returns the numerically lowest of the parameter values. * @see max * @see count */ DELTA_FUNCTION(min) { if(DELTA_ARG0->type == DELTA_TYPE_ARRAY) { struct DeltaArray *array = &DELTA_ARG0->value.array; struct DeltaArrayValue *e = array->head; double lowest = delta_cast_number(e->value); e = e->next; int i; for(i = 1; i < array->elements; ++i, e = e->next) { double arg = delta_cast_number(e->value); if(arg < lowest) lowest = arg; } DELTA_RETURN_NUMBER(lowest); } double lowest = delta_cast_number(DELTA_ARG0); int i; for(i = 1; i < DELTA_ARGS; ++i) { double arg = delta_cast_number(DELTA_ARG(i)); if(arg < lowest) lowest = arg; } DELTA_RETURN_NUMBER(lowest); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printf.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: budelphi <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/25 11:35:38 by budelphi #+# #+# */ /* Updated: 2020/11/25 12:11:48 by budelphi ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdarg.h> int ft_init_struct(t_printf *t_flags) { t_flags->flags = 0; t_flags->width = 0; t_flags->precision = 0; t_flags->type = '\0'; return (0); } int ft_treat_param(char **format, va_list *vl) { t_printf t_flags; int res; res = 0; (*format)++; ft_init_struct(&t_flags); ft_parse_struct(format, vl, &t_flags); res += ft_print_param(&t_flags, vl); return (res); } int ft_printf_body(char **format, va_list *vl, int res) { while (**format != '\0') { if (**format != '%') { res += ft_putchar(**format); (*format)++; } else res += ft_treat_param(format, &vl); if (res == -1) return (res); } return (res); } int ft_printf(const char *format, ...) { va_list vl; int res; if (!format) return (-1); res = 0; va_start(vl, format); res = ft_printf_body((char **)&format, &vl, res); va_end(vl); return (res); }
C
/* * Tema 2 ASC * 2018 Spring * Catalin Olaru / Vlad Spoiala */ #include "utils.h" /* * Add your unoptimized implementation here */ double* my_solver(int N, double *A) { printf("NEOPT SOLVER\n"); double *C = calloc(2 * N * N, sizeof(double)); int i, j, k; for (i = 0; i < N; i++) { for (j = i; j < N; j++) { for (k = 0; k < N; k++) { C[2 * (i * N + j)] += A[2 * (i * N + k)] * A[2 * (j * N + k)] - A[2 * (i * N + k) + 1] * A[2 * (j * N + k) + 1]; C[2 * (i * N + j) + 1] += A[2 * (i * N + k)] * A[2 * (j * N + k) + 1] + A[2 * (i * N + k) + 1] * A[2 * (j * N + k)]; } } } return C; }
C
#include <stdlib.h> #include "CUnit/CUnit.h" #include "CUnit/Basic.h" #include "student_code.h" int init_suite(void) {return 0;} int clean_suite(void) {return 0;} void get_bit_test(void){ unsigned int a = 59; CU_ASSERT_EQUAL(get_bit(a, 0), '1'); CU_ASSERT_EQUAL(get_bit(a, 7), '0'); } void set_bit_test(void){ unsigned int a = 0; a = set_bit(a, 3, 1); CU_ASSERT_EQUAL(a, 8); a = set_bit(a, 3, 0); CU_ASSERT_EQUAL(a, 0); a = set_bit(a, 0, 1); CU_ASSERT_EQUAL(a, 1); a = set_bit(a, 0, 0); CU_ASSERT_EQUAL(a, 0); } void get_3_leftmost_bit_test(void){ unsigned int a = 139; unsigned char b = get_3_leftmost_bit(a); CU_ASSERT_EQUAL(b, 0); a = 4294967295; b = get_3_leftmost_bit(a); CU_ASSERT_EQUAL(b, 15); } void get_4_rightmost_bit_test(void){ unsigned int a = 139; unsigned char b = get_4_rightmost_bit(a); CU_ASSERT_EQUAL(b, 11); a = 4294967295; b = get_4_rightmost_bit(a); CU_ASSERT_EQUAL(b, 15); } void unset_first_bit_test(void){ unsigned int a = 39; a = unset_first_bit(a); CU_ASSERT_EQUAL(a, 7); a = unset_first_bit(a); CU_ASSERT_EQUAL(a, 3); a = unset_first_bit(a); CU_ASSERT_EQUAL(a, 1); } void cycle_bits_test(void){ unsigned int a = 1; a = cycle_bits(a, 2); CU_ASSERT_EQUAL(a, 4); a = cycle_bits(a, 3); CU_ASSERT_EQUAL(a, 32); } int main(int argc, const char *argv[]){ CU_pSuite pSuite = NULL; //initiation du registre de test de CUnit if(CUE_SUCCESS != CU_initialize_registry() ) return CU_get_error(); //ajoute une suite au registre pSuite = CU_add_suite("Test Unitaires Bitwise", init_suite, clean_suite); if(NULL == pSuite){ CU_cleanup_registry(); return CU_get_error(); } //ajoute les tests à la suite if ((NULL == CU_add_test(pSuite, "get_bit", get_bit_test)) || (NULL == CU_add_test(pSuite, "set_bit", set_bit_test)) || (NULL == CU_add_test(pSuite, "get_3_leftmost", get_3_leftmost_bit_test)) || (NULL == CU_add_test(pSuite, "get_4_rightmost_bit", get_4_rightmost_bit_test)) || (NULL == CU_add_test(pSuite, "unset_first_bit", unset_first_bit_test)) || (NULL == CU_add_test(pSuite, "cycle_bits", cycle_bits_test)) ){ CU_cleanup_registry(); return CU_get_error(); } //CU_console_run_tests(); CU_basic_set_mode(CU_BRM_VERBOSE); CU_basic_run_tests(); printf("\n"); CU_basic_show_failures(CU_get_failure_list()); printf("\n\n"); //nettoie le registre et return CU_cleanup_registry(); return CU_get_error(); }
C
/******************************* getch() Reproduce effect of getch() function on Linux. Entering Parameters: none Returned value: none *******************************/ int getch(void) { struct termios oldt, newt; int ch; tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~( ICANON | ECHO); tcsetattr( STDIN_FILENO, TCSANOW, &newt ); ch = getchar(); tcsetattr( STDIN_FILENO, TCSANOW, &oldt ); return ch; } /************************************** save() Save the data of every moves, picking them from the list, and save them in a binary file, so that you can load them later Entering Parameters: pedine: The structs containing all chess data board: bidimensional array of struct puntators, with all the information about the chessboard and the position of every chess name1: player 1 name's name 2: player 2 name's player: current player numero_celle: numebr of moves done up to this point testa: puntator to the head of the list Returned value: none *****************************************/ void save(pedina *pedine, pedina *board[8][8], char *name1, char *name2, int player, int numero_celle, struct mossa *testa) { struct mossa *tmp, *tmpUltimo, *mosseArray; salvataggio saveStruct; FILE *saveFile; char fileName[101], deb[51]; int n, l, p, i; mosseArray=(struct mossa*)malloc(sizeof(struct mossa)*numero_celle); clear(); printf("~~~SAVE GAME~~~\n"); printf("Insert file name. Be sure it doesn't already" "exist, or it will be overwrited!\n"); scanf("%s%*c", fileName); /*saving player*/ saveStruct.player = player; /*saving numero_celle*/ saveStruct.numero_celle = numero_celle; /*saving players names*/ for(i=0; i<31; i++) { saveStruct.name1[i] = name1[i]; } for(i=0; i<31; i++) { saveStruct.name2[i] = name2[i]; } /*saving board*/ for(n=0; n<8; n++) { for(l=0; l<8; l++) { for(p=0; p<33; p++) { if(board[n][l] == pedine+p) { sprintf(deb, "(%d-%d)%c --> pedine[%d]", l, n, board[n][l]->tipo, p); debug(deb); saveStruct.board[n][l] = p; p=33; } } } } /*reaching the last element of the list*/ tmpUltimo = testa; while(tmpUltimo->prev!=NULL) { tmpUltimo = tmpUltimo->prev; } /*----Now I save data in the file----*/ saveFile = fopen(fileName, "w"); fwrite(&saveStruct, sizeof(salvataggio), 1, saveFile); tmp = tmpUltimo; for(i=0; i<numero_celle; i++) { sprintf(deb, "giocatore: %s\n", (tmp->player==0)?name1:name2); debug(deb); sprintf(deb, "mossa: %s\n", tmp->coordinate); debug(deb); sprintf(deb, "durata: %.2lf secs\n", tmp->durata_mossa); debug(deb); fwrite(tmp, sizeof(struct mossa), 1, saveFile); tmp = tmp->next; } fclose(saveFile); } /************************************ load() Load the data of a previous game, taking them from a file previously saved. Entering parameters: pedine: The structs containing all chess data board: bidimensional array of struct puntators, with all the information about the chessboard and the position of every chess name1: player 1 name's name 2: player 2 name's player: current player numero_celle: numebr of moves done up to this point Returned value: testa: the head of the list *************************************/ struct mossa *load(pedina *pedine, pedina *board[8][8], char *name1, char *name2, char *name, int *player, int *numero_celle) { FILE *saveFile; char fileName[51], deb[51]; salvataggio saveStruct; struct mossa *mossaTmp, *tmp1, *tmp2, *testa; testa = NULL; int n, l, p, i; clear(); printf("~~~LOAD GAME~~~\n"); do { printf("Write the file-name to load, it must be in the" "game folder\n"); scanf("%s%*c", fileName); saveFile = fopen(fileName, "r"); if(!saveFile) { printf("Error, are you sure that the file " "exist?\n"); } } while(!saveFile); fread(&saveStruct, sizeof(salvataggio), 1, saveFile); /*loading current player*/ *player = saveStruct.player; /*loading numero_celle*/ *numero_celle = saveStruct.numero_celle; /*loading player names*/ for(i=0; i<31; i++) { name1[i] = saveStruct.name1[i]; } for(i=0; i<31; i++) { name2[i] = saveStruct.name2[i]; } /*linking board to pedine*/ for(n=0; n<8; n++) { for(l=0; l<8; l++) { p = saveStruct.board[n][l]; board[n][l] = &pedine[p]; } } /*making list from array*/ debug("Inizio a prendere la lista"); for(i=0; i<*numero_celle; i++) { tmp1=(struct mossa*)malloc(sizeof(struct mossa)); fread(tmp1, sizeof(struct mossa), 1, saveFile); sprintf(deb, "giocatore: %s\n", (tmp1->player==0)?name1:name2); debug(deb); sprintf(deb, "mossa: %s\n", tmp1->coordinate); debug(deb); sprintf(deb, "durata: %.2lf secs\n", tmp1->durata_mossa); debug(deb); tmp1->next=testa; tmp1->prev=NULL; if(testa!=NULL) { testa->prev=tmp1; } testa=tmp1; } debug("Lista caricata"); name = (*player==0)?name1:name2; printf("Loading done, now players are:\n%s and %s\n",name1, name2); printf("It's %s turn!\n", name); printf("[Press a key to continue]"); getch(); return testa; }
C
/* Вариант 9 Фамилия спортсмена Вид спорта Количество медалей Расположить в алфавитном порядке записи с ненулевым количеством медалей */ #include <stdio.h> #include <stdlib.h> #include <string.h> struct athlet { char surname[50]; char sport[50]; int countMedals; }; int main(int argc, char **argv) { int count; printf("Введите кол-во спортсменов:"); scanf("%d", &count); struct athlet athlets[count]; for (int i = 0; i < count; i++) { printf("Введите Фамилию:"); scanf("%s", athlets[i].surname); printf("Введите вид спорта:"); scanf("%s", athlets[i].sport); printf("Введите количество медалей:"); scanf("%d", &athlets[i].countMedals); } printf("\n"); for (int i = 0; i < count; i++) { printf("Фамилия спортсмена:%s\n", athlets[i].surname); printf("Вид спорта:%s\n", athlets[i].sport); printf("Количество медалей:%d\n", athlets[i].countMedals); } }
C
#include <pwd.h> #include <readline/readline.h> #include <readline/history.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <unistd.h> #include "shell_fct.h" //sudo apt-get install libreadline-dev int main(int argc, char** argv) { int ret = MYSHELL_CMD_OK; char* readlineptr; struct passwd* infos; char str[1024]; char hostname[256]; char workingdirectory[256]; while(ret != MYSHELL_FCT_EXIT) { //Get your session info infos=getpwuid(getuid()); gethostname(hostname, 256); getcwd(workingdirectory, 256); //Print it to the console sprintf(str, "\n{myshell}%s@%s:%s$ ", infos->pw_name, hostname, workingdirectory); //Read command typed by user readlineptr = readline(str); //If a command is typed if(strlen(readlineptr) != 0){ //Add this command to command history add_history(readlineptr); //The command is processed cmd *command = malloc(sizeof(cmd)); parseMembers(readlineptr,command); printCmd(command); //Then the command is executed ret = exec_command(command); //If an error occurs a message is displayed if(ret == -1){ printf("ERROR : \"%s\" is not a valid command or a valid executable",command->initCmd); } //Free memory freeCmd(command); free(command); } free(readlineptr); } return 0; }
C
#include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }*head=NULL; struct node *current=NULL; // Creating a linked List in C //Use a function called create to create a list void create() { struct node *newnode, *current; newnode=(struct node*)malloc(sizeof(struct node)); newnode->next=NULL; if(head==NULL) { head=newnode; current=newnode; } else { current->next=newnode; current=newnode; } } //Function to insert a new element //Insert at the begining void insertFirst() { struct node *newnode; newnode=(struct node*)malloc(sizeof(struct node)); newnode->next=NULL; if(head==NULL) { head=newnode; current=newnode; } else { current->next=head; head=newnode; } } //Inserting at last void insertAtLast() { struct node *newnode, *current; newnode=(struct node*)malloc(sizeof(struct node)); newnode->next=NULL; if(head==NULL) { head=newnode; current=newnode; } else { current->next=newnode; current=newnode; } } // Inserting in the middle void mid_insert() { struct node *newnode, *temp, *temp2; int position=3; newnode = (struct node*)malloc(sizeof(struct node)); newnode->next = NULL; if(head == NULL) { head = newnode; current = newnode; } else { temp=head; int i; for(i=1; i<position; i++) temp = temp->next; temp2 = temp->next; temp->next = newnode; } newnode->next=temp2; } int main(){ printf("Welcome to Linked List implementation in C"); printf("\n============================================\n"); printf("Please choose from the below choices:\n"); //Complete the Main please return 0; }
C
// Converts a person's full name into initials. // Usage: ./initials #include <stdio.h> #include <cs50.h> #include <string.h> #include <ctype.h> void to_initials(); int main(void) { printf("What is your full name?\n"); string name = get_string(); to_initials(name); } void to_initials(string s) { int length = strlen(s); char prev_char = 0; for (int i = 0; i < length; i++) { if (isalpha(prev_char) == false) { if (isupper(s[i])) { printf("%c", s[i]); } else if (islower(s[i])) { printf("%c", s[i] - 32); } } prev_char = s[i]; } printf("\n"); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_inputrc.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: abaurens <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/02 14:25:04 by abaurens #+# #+# */ /* Updated: 2019/10/14 16:57:01 by abaurens ### ########.fr */ /* */ /* ************************************************************************** */ #define FT_DISABLE_WARNINGS #include <stdio.h> #include <stdlib.h> #include "ftreadline/keys.h" #include "ftreadline/ft_inputrc.h" #include "ftio.h" /* ** static char tree_add(t_tree *node, register const char *nodes, t_fkey func) ** { ** register size_t i; ** t_tree *new; ** ** i = 0; ** new = NULL; ** if (!*nodes) ** { ** node->f = func; ** return (0); ** } ** while (!new && i < node->ncnt) ** if (node->nexts[i++]->c == *nodes) ** new = node->nexts[i - 1]; ** ft_printf(" adding '%c' after '%#R'\n", *nodes, node->c); ** if (!new) ** { ** ft_printf(" '%c' doesn't exist yet. allocating memory...\n", ** *nodes); ** if (!(new = malloc(sizeof(t_tree)))) ** return (-1); ** new->f = 0x0; ** new->ncnt = 0; ** new->c = *nodes; ** node->nexts[node->ncnt++] = new; ** } ** return (tree_add(new, nodes + 1, func)); ** } ** ** static char build_input_tree(t_tree *root) ** { ** int i; ** ** i = 0; ** while (g_tb[i].keycode) ** { ** ft_printf("adding '%s'\n", g_tb[i].keycode); ** if (tree_add(root, g_tb[i].keycode, g_tb[i].func)) ** return (1); ** ++i; ** } ** return (0); ** } */ void print_tree(const t_tree_ *cur, int j) { int i; i = 0; ft_printf("%*s'%R': ", j, "", cur->c); if (cur->nln) ft_printf("[%d](", cur->nln); else ft_printf("%s()\n", cur->funcname); while (cur->nxt[i]) { ft_printf("'%c'%s", cur->nxt[i]->c, cur->nxt[i + 1] ? ", " : ")\n"); ++i; } i = 0; while (cur->nxt[i]) print_tree(cur->nxt[i++], j + 2); } /* **t = &g_test; **ft_printf("'%R'(%d) : ('%c', '%c')\n", t->c, t->nln, ** t->nxt[0]->c, t->nxt[1]->c); **t = t->nxt[0]; **ft_printf("'%R' : [%d]('%c', '%c', '%c', '%c', '%c', '%c')\n", t->c, t->nln, ** t->nxt[0]->c, t->nxt[1]->c, t->nxt[2]->c, ** t->nxt[3]->c, t->nxt[4]->c, t->nxt[5]->c); **t = g_test.nxt[1]; **ft_printf("'%R' : [%d]('%c', '%c', '%c', '%c', '%c', '%c')\n", t->c, t->nln, ** t->nxt[0]->c, t->nxt[1]->c, t->nxt[2]->c, ** t->nxt[3]->c, t->nxt[4]->c, t->nxt[5]->c); */ t_tree *get_input_tree(void) { print_tree(&g_test, 0); return (0x0); }
C
/* Based on PSFEx.h by peter melchior */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include "psfex.h" #include "poly.h" static const double INTERPFAC = 4.0; static const double IINTERPFAC = 0.25; struct psfex *psfex_new(long *masksize, // [MASK_DIM] long poldeg, double *contextoffset, // [POLY_DIM] double *contextscale, // [POLY_DIM] double psf_samp) { struct psfex *self; int i; long deg[POLY_MAXDIM], group[POLY_MAXDIM]; if ((self = calloc(1, sizeof(struct psfex))) == NULL) { fprintf(stderr,"Failed to allocate struct psfex\n"); exit(1); } self->maskcomp = NULL; // copy masksize memcpy(self->masksize, masksize, MASK_DIM * sizeof(long)); // copy contextoffset memcpy(self->contextoffset, contextoffset, POLY_DIM * sizeof(double)); // copy contextscale memcpy(self->contextscale, contextscale, POLY_DIM * sizeof(double)); self->masknpix = self->masksize[0] * self->masksize[1]; // set up poly struct for (i=0;i<POLY_DIM;i++) { group[i] = 1; } deg[0] = poldeg; self->poly = poly_init(group, POLY_DIM, deg, POLY_NGROUP); self->pixstep = 1./psf_samp; // allocate memory for mask ... if ((self->maskcomp = (double *) calloc(self->masknpix * self->masksize[2], sizeof(double))) == NULL) { self=psfex_free(self); fprintf(stderr,"Failed to allocate maskcomp\n"); exit(1); } // and set the reconstruction size, using psf sampling factor. Make sure it's odd self->reconsize[0] = (long) ceil((float) self->masksize[0] * (float) psf_samp); if ((self->reconsize[0] % 2) == 0) { self->reconsize[0]++; } self->reconsize[1] = (long) ceil((float) self->masksize[1] * (float) psf_samp); if ((self->reconsize[1] % 2) == 0) { self->reconsize[1]++; } return self; } struct psfex *psfex_free(struct psfex *self) { if (self) { if (self->maskcomp) { free(self->maskcomp); self->maskcomp = NULL; } poly_end(self->poly); free(self); } return self; } void psfex_write(const struct psfex *self, FILE* stream) { fprintf(stream,"masksize[0]: %ld\n", self->masksize[0]); fprintf(stream,"masksize[1]: %ld\n", self->masksize[1]); fprintf(stream,"masksize[2]: %ld\n", self->masksize[2]); fprintf(stream,"reconsize[0]: %ld\n", self->reconsize[0]); fprintf(stream,"reconsize[1]: %ld\n", self->reconsize[1]); fprintf(stream,"contextoffset[0]: %lf\n", self->contextoffset[0]); fprintf(stream,"contextoffset[1]: %lf\n", self->contextoffset[1]); fprintf(stream,"contextscale[0]: %lf\n", self->contextscale[0]); fprintf(stream,"contextscale[1]: %lf\n", self->contextscale[1]); fprintf(stream,"pixstep: %lf\n", self->pixstep); } struct psfex_image *psfex_image_new(long nrow, long ncol) { return _psfex_image_new(nrow, ncol, 1); } struct psfex_image *_psfex_image_new(long nrow, long ncol, int alloc_data) { struct psfex_image *self=calloc(1, sizeof(struct psfex_image)); if (!self) { fprintf(stderr,"Could not allocate struct psfex_image\n"); exit(1); } self->size=nrow*ncol; self->nrow=nrow; self->ncol=ncol; self->rows = calloc(self->nrow,sizeof(double *)); if (!self->rows) { fprintf(stderr,"could not allocate %ld image rows\n", self->nrow); exit(1); } if (alloc_data) { self->rows[0]=calloc(self->size,sizeof(double)); if (self->rows[0]==NULL) { fprintf(stderr,"could not allocate image of dimensions [%lu,%lu]\n", nrow,ncol); exit(1); } for(long i = 1; i < self->nrow; i++) { self->rows[i] = self->rows[i-1] + self->ncol; } self->is_owner=1; } else { self->rows[0] = NULL; self->is_owner=0; } return self; } struct psfex_image *psfex_image_free(struct psfex_image *self) { if (self) { if (self->rows) { if (self->rows[0]) { free(self->rows[0]); } self->rows[0]=NULL; free(self->rows); self->rows=NULL; } free(self); self=NULL; } return self; } void get_center(long nrow, long ncol, double row, double col, double pixstep, double *rowcen, double *colcen) { double drow, dcol; // this follows the new calculation in _psfex_rec_fill, in turn // following SExtractor dcol = col - (long) (col+0.5); drow = row - (long) (row+0.5); *colcen = (double) (ncol/2) + dcol; *rowcen = (double) (nrow/2) + drow; } /* repurposed from sextractor image.c */ /* *%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% * * This file part of: SExtractor * * Copyright: (C) 1993-2010 Emmanuel Bertin -- IAP/CNRS/UPMC * * License: GNU General Public License * * SExtractor 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 3 of the License, or * (at your option) any later version. * SExtractor 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 SExtractor. If not, see <http://www.gnu.org/licenses/>. * * Last modified: 19/10/2010 * *%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ static int _psfex_vignet_resample(double *pix1, int w1, int h1, double *pix2, int w2, int h2, double dx, double dy, double step2) { double *mask,*maskt, xc1,xc2,yc1,yc2, xs1,ys1, x1,y1, x,y, dxm,dym, val, norm, *pix12, *pixin,*pixin0, *pixout,*pixout0; int i,j,k,n,t, *start,*startt, *nmask,*nmaskt, ixs2,iys2, ix2,iy2, dix2,diy2, nx2,ny2, iys1a, ny1, hmw,hmh, ix,iy, ix1,iy1; /* Initialize destination buffer to zero */ memset(pix2, 0, w2*h2*sizeof(double)); xc1 = (double)(w1/2); /* Im1 center x-coord*/ xc2 = (double)(w2/2); /* Im2 center x-coord*/ xs1 = xc1 + dx - xc2*step2; /* Im1 start x-coord */ if ((int)xs1 >= w1) return -1; ixs2 = 0; /* Int part of Im2 start x-coord */ if (xs1<0.0) { dix2 = (int)(1-xs1/step2); /*-- Simply leave here if the images do not overlap in x */ if (dix2 >= w2) return -1; ixs2 += dix2; xs1 += dix2*step2; } nx2 = (int)((w1-1-xs1)/step2+1);/* nb of interpolated Im2 pixels along x */ if (nx2>(ix2=w2-ixs2)) nx2 = ix2; if (nx2<=0) return -1; yc1 = (double)(h1/2); /* Im1 center y-coord */ yc2 = (double)(h2/2); /* Im2 center y-coord */ ys1 = yc1 + dy - yc2*step2; /* Im1 start y-coord */ if ((int)ys1 >= h1) return -1; iys2 = 0; /* Int part of Im2 start y-coord */ if (ys1<0.0) { diy2 = (int)(1-ys1/step2); /*-- Simply leave here if the images do not overlap in y */ if (diy2 >= h2) return -1; iys2 += diy2; ys1 += diy2*step2; } ny2 = (int)((h1-1-ys1)/step2+1);/* nb of interpolated Im2 pixels along y */ if (ny2>(iy2=h2-iys2)) ny2 = iy2; if (ny2<=0) return -1; /* Set the yrange for the x-resampling with some margin for interpolation */ iys1a = (int)ys1; /* Int part of Im1 start y-coord with margin */ hmh = INTERPW/2 - 1; /* Interpolant start */ if (iys1a<0 || ((iys1a -= hmh)< 0)) iys1a = 0; ny1 = (int)(ys1+ny2*step2)+INTERPW-hmh; /* Interpolated Im1 y size */ if (ny1>h1) /* with margin */ ny1 = h1; /* Express everything relative to the effective Im1 start (with margin) */ ny1 -= iys1a; ys1 -= (double)iys1a; /* Allocate interpolant stuff for the x direction */ if ((mask = (double *) malloc(sizeof(double) * nx2 * INTERPW)) == NULL) /* Interpolation masks */ return -1; if ((nmask = (int *) malloc(sizeof(int) * nx2)) == NULL) /* Interpolation mask sizes */ return -1; if ((start = (int *) malloc(sizeof(int) * nx2)) == NULL) /* Int part of Im1 conv starts */ return -1; /* Compute the local interpolant and data starting points in x */ hmw = INTERPW/2 - 1; x1 = xs1; maskt = mask; nmaskt = nmask; startt = start; for (j=nx2; j--; x1+=step2) { ix = (ix1=(int)x1) - hmw; dxm = ix1 - x1 - hmw; /* starting point in the interpolation func */ if (ix < 0) { n = INTERPW+ix; dxm -= (double)ix; ix = 0; } else n = INTERPW; if (n>(t=w1-ix)) n=t; *(startt++) = ix; *(nmaskt++) = n; norm = 0.0; for (x=dxm, i=n; i--; x+=1.0) norm += (*(maskt++) = INTERPF(x)); norm = norm>0.0? 1.0/norm : 1.0; maskt -= n; for (i=n; i--;) *(maskt++) *= norm; } if ((pix12 = (double *) calloc(nx2*ny1, sizeof(double))) == NULL) { /* Intermediary frame-buffer */ return -1; } /* Make the interpolation in x (this includes transposition) */ pixin0 = pix1+iys1a*w1; pixout0 = pix12; for (k=ny1; k--; pixin0+=w1, pixout0++) { maskt = mask; nmaskt = nmask; startt = start; pixout = pixout0; for (j=nx2; j--; pixout+=ny1) { pixin = pixin0+*(startt++); val = 0.0; for (i=*(nmaskt++); i--;) val += *(maskt++)**(pixin++); *pixout = val; } } /* Reallocate interpolant stuff for the y direction */ if ((mask = (double *) realloc(mask, sizeof(double) * ny2 * INTERPW)) == NULL) { /* Interpolation masks */ return -1; } if ((nmask = (int *) realloc(nmask, sizeof(int) * ny2)) == NULL) { /* Interpolation mask sizes */ return -1; } if ((start = (int *) realloc(start, sizeof(int) * ny2)) == NULL) { /* Int part of Im1 conv starts */ return -1; } /* Compute the local interpolant and data starting points in y */ hmh = INTERPW/2 - 1; y1 = ys1; maskt = mask; nmaskt = nmask; startt = start; for (j=ny2; j--; y1+=step2) { iy = (iy1=(int)y1) - hmh; dym = iy1 - y1 - hmh; /* starting point in the interpolation func */ if (iy < 0) { n = INTERPW+iy; dym -= (double)iy; iy = 0; } else n = INTERPW; if (n>(t=ny1-iy)) n=t; *(startt++) = iy; *(nmaskt++) = n; norm = 0.0; for (y=dym, i=n; i--; y+=1.0) norm += (*(maskt++) = INTERPF(y)); norm = norm>0.0? 1.0/norm : 1.0; maskt -= n; for (i=n; i--;) *(maskt++) *= norm; } /* Make the interpolation in y and transpose once again */ pixin0 = pix12; pixout0 = pix2+ixs2+iys2*w2; for (k=nx2; k--; pixin0+=ny1, pixout0++) { maskt = mask; nmaskt = nmask; startt = start; pixout = pixout0; for (j=ny2; j--; pixout+=w2) { pixin = pixin0+*(startt++); val = 0.0; for (i=*(nmaskt++); i--;) val += *(maskt++)**(pixin++); *pixout = val; } } /* Free memory */ free(pix12); free(mask); free(nmask); free(start); return 0; } void _psfex_rec_fill(const struct psfex *self, double row, double col, double *data) { double pos[POLY_DIM]; double *basis=NULL, fac; double *ppc=NULL, *pl=NULL; int i,n,p; double *maskloc=NULL; double dcol,drow; //double sum; if ((maskloc = (double *) calloc(self->masknpix, sizeof(double))) == NULL) { fprintf(stderr,"Could not allocate maskloc\n"); exit(1); } pos[0] = col; pos[1] = row; for (i=0;i<POLY_DIM;i++) { pos[i] = (pos[i] - self->contextoffset[i])/self->contextscale[i]; } poly_func(self->poly, pos); basis = self->poly->basis; ppc = self->maskcomp; for (n=PSFEX_NCOMP(self); n--; ) { pl = maskloc; fac = *(basis++); for (p=PSFEX_SIZE(self); p--;) *(pl++) += fac**(ppc++); } // following sextractor where deltax = mx - ix // mx is the center // ix is the integer (floor) center of the stamp // this does not follow sextractor which has an extra -1 because YOLO // (Note that this shifts the cutout in the postage stamp; get_center() // tells you where the center actually is. Also note that using the // -1 gives boundary problems on the reconstructed postage stamp, // which is why it has been removed for 0.3.1 -- ESR dcol = col - (long) (col+0.5); drow = row - (long) (row+0.5); _psfex_vignet_resample(maskloc, self->masksize[0], self->masksize[1], data, self->reconsize[0], self->reconsize[1], -dcol*self->pixstep, -drow*self->pixstep, self->pixstep); // NOTE: this is not normalized to match SExtractor fits at the moment... // This will be updated when/if SExtractor is updated... free(maskloc); } double *psfex_recp(const struct psfex *self, double row, double col, long *nrow, long *ncol) { // this is the size of the reconstructed image (*nrow) = RECON_NROW(self); (*ncol) = RECON_NCOL(self); long npix=(*nrow)*(*ncol); double *data=calloc(npix, sizeof(double)); if (!data) { fprintf(stderr,"could not allocate %ld doubles\n", npix); exit(1); } _psfex_rec_fill(self, row, col, data); return data; } struct psfex_image *psfex_rec_image(const struct psfex *self, double row, double col) { long nrow=0, ncol=0; double *data=psfex_recp(self, row, col, &nrow, &ncol); // 0 means don't allocate the data struct psfex_image *im=_psfex_image_new(nrow, ncol, 0); im->rows[0] = data; for(long i = 1; i < im->nrow; i++) { im->rows[i] = im->rows[i-1] + im->ncol; } im->is_owner=1; return im; }