language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* author: Tony Lai */ /* EXERCISE 2-6~8 */ #include <stdio.h> #include <string.h> #define MAXLINE 15 /* A SMALL NUMBER FOR TESTING */ int c, i, lim, stop, n; enum boolean {NO, YES}; char s[] = "hellosdgngfrh"; char s1[] = "g"; char *test; int o; int atoi(char a[]); unsigned setbits( unsigned x, int p, int n, unsigned y ); unsigned rightrot( unsigned x, int n ); unsigned bitcount( unsigned x); int main(){ for( int i=0 ; i!=81 ; printf("%d*%d=%2d %c", (i/9+1), (i%9+1), (i/9+1)*(i%9+1), (i%9+1)==9?'\n':'\t' ) , i++); return 0; } /* PRTLINE: PRINT OUT LAST ARRAY LINE, SKIP INPUT BEYOND MAXLINE */ int atoi(char a[]){ int i = 0; int dec = 0; int n = 0; while(i<2){ if(a[i]<='9'&&a[i]>='0') n = a[i]-'0'; else if(a[i]<='F'&&a[i]>='A') n = 10+ (a[i]-'A'); else if(a[i]<='f'&&a[i]>='a') n = 10+ (a[i]-'a'); dec = 16*dec + n; i++; } return dec; } unsigned setbits( unsigned x, int p, int n, unsigned y ){ return (x>>(p-n) & ~(~0<<n)) | (y & (~0<<n)); } unsigned rightrot( unsigned x, int n ){ unsigned test; int length = 0; int i = 0; test = x; test = test | ~0; while(test != 0){ test = (test >> 1); length++; } while(i < n){ x = (x>>1) | (x << (length-1)) ; i++; } return x; } unsigned bitcount( unsigned x){ int b; for (b=0 ; x!=0 ; x &= (x-1)){ b++; } return b; }
C
HTML file : <html> <body> <form action="slip22_2.php" method="get"> <center> <table> <tr><td>Enter 1st String : </td><td><input type="text" name="str1"></td></tr> <tr><td>Enter 2nd String : </td><td><input type="text" name="str2"></td></tr> <tr><td>Enter String To Replace : </td><td><input type="text" name="str3"></td></tr> <tr><td>Occurance</td><td><input type="radio" name="ch" value=1></td></tr> <tr><td>Replace</td><td><input type="radio" name="ch" value=2></td></tr> <tr><td></td><td><input type="submit" value=Next></td></tr> </table> </center> </form> </body> </html> --------------------------------------------------- PHP file : <?php $str1 = $_GET['str1']; $str2 = $_GET['str2']; $str3 = $_GET['str3']; $ch = $_GET['ch']; echo "First String is = $str1.<br><br>"; echo "second String is = ".$str2."<br><br>"; echo "String for Replace is = ".$str3."<br><br>"; If(strlen($str1)>strlen($str2)) { switch($ch) { case 1 : $pos = strpos($str1,$str2); if($pos != 0) echo "string '$str2' Not present at the start of '$str1'.<br>"; else echo "string '$str2' present at the start of '$str1'.<br>"; break; case 2 : $str4 = str_replace($str2,$str3,$str1); echo "After replacing string $str4"; break; } } else { switch($ch) { case 1 : $pos = strpos($str2,$str1); if($pos != 0) echo "string '$str1' Not present at the start of '$str2'.<br>"; else echo "string '$str1' present at the start of '$str2'.<br>"; break; case 2 : $str4 = str_replace($str1,$str3,$str2); echo "After replacing string $str4"; break; } } ?>
C
#include<stdio.h> #include<ctype.h> int main() { int a; printf("Enter a character \n"); scanf("%[^\n]",&a); if (isalpha(a)) { printf("the entered character is an alphabet \n"); if (islower(a)) { printf("the entered character is a lowercase alphabet \n"); } else { printf("the entered character is a lowercase alphabet \n"); } } else if(isspace(a)) { printf("the entered character is a space"); } else if(ispunct(a)) { printf("the entered character is a punctuation"); } else if(isdigit(a)) { printf("the entered character is a number"); } return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <semaphore.h> #include "unistd.h" #define N 10 //número de usuários #define CARTAS 20 //quantidade de cartas na mochila void * f_usuario(void *arg); void * f_pombo(void *arg); sem_t pombo; sem_t cartas; sem_t local; sem_t voar; int cards = 0; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; int main(int argc, char **argv){ sem_init(&pombo, 0, 1); //Como se fosse o lock de uso do pombo sem_init(&cartas, 0, CARTAS); sem_init(&voar, 0, 0); int i; pthread_t usuario[N]; int *id; for(i = 0; i < N; i++){ id = (int *) malloc(sizeof(int)); *id = i; pthread_create(&(usuario[i]),NULL,f_usuario, (void *) (id)); } pthread_t pombo; id = (int *) malloc(sizeof(int)); *id = 0; pthread_create(&(pombo),NULL,f_pombo, (void*) (id)); pthread_join(pombo,NULL); } void * f_pombo(void *arg){ int j; while(1){ sem_wait(&voar); sem_wait(&pombo); printf("Viajando para B\n"); sleep(2); printf("Chegou, entregando cartas\n"); cards = 0; for(j = 0;j < CARTAS; j++){ sem_post(&cartas); } sleep(2); printf("Viajando para A\n"); sleep(2); printf("Chegou em A\n"); sem_post(&pombo); //Inicialmente está em A, aguardar/dorme a mochila ficar cheia (20 cartas) //Leva as cartas para B e volta para A //Acordar os usuários } } void * f_usuario(void *arg){ int n = *((int *) arg); while(1){ //Escreve uma carta //usuarios podem escrever cartas mesmo se o pombo nao estiver presente printf("Pessoa %d screvendo carta\n", n); sleep(1); printf("Carta da pessoa %d escrita\n", n); sem_wait(&cartas); //ver se bolsa esta cheia sem_wait(&pombo); //ver se ninguem esta colocando nada no pombo ou ele esta em outro lugar pthread_mutex_lock(&lock); //talvez eu nao precise desse lock cards++; printf("Carta da pessoa %d colocada na mochila, total = %d\n", n, cards); pthread_mutex_unlock(&lock); if(cards == CARTAS){ printf("Mochila cheia, pombo vai voar!\n"); sem_post(&voar); //acorda o pombo } sem_post(&pombo); //libera o pombo //Caso o pombo não esteja em A ou a mochila estiver cheia, então dorme //Posta sua carta na mochila do pombo //Caso a mochila fique cheia, acorda o ṕombo } }
C
#include <stdio.h> #include <stdlib.h> #define rows_length 750 int main() { FILE* tp; int i = 0; int males = 0, females = 0, mr = 0, fr = 0, amage = 0, afage = 0, hage = 0, amweig = 0, afweig = 0, yage, obesep = 0, obesem = 0, obesef = 0; int mbm1, mbm2, mbm3, ambm1 = 0, ambm2 = 0, ambm3 = 0, fbm1, fbm2, fbm3, afbm1 = 0, afbm2 = 0, afbm3 = 0, aagemn = 0, aagefn = 0; int averagebmim=0, averagebmif=0; int below30fem=0,below30mal=0,above60fem=0,above60mal=0,between30and60fem=0,between30and60mal=0; float rate, mbmi, ambmi = 0, fbmi, afbmi = 0; char gender[rows_length]; int age[rows_length]; float height[rows_length]; float weight[rows_length]; char result[rows_length]; int zip[rows_length]; char dataToBeRead[50]; tp = fopen("Data.txt", "r"); //check file open successfully or not if (tp == 0) { printf("error\n"); exit(1); } else { while (fgets(dataToBeRead, 50, tp) != NULL) { sscanf(dataToBeRead, "%c %d %f %f %c %d", &gender[i], &age[i],&height[i], &weight[i], &result[i], &zip[i]); i++; } yage = age[0]; for (int j = 0; j < i; j++) { if (gender[j] == 'M') //check gender { males++; //numbers of males if (result[j] == '+') { mr++; //male result amage = amage + age[j]; amweig = amweig + weight[j]; mbmi = (weight[j] / (height[j]*height[j])) * 703; ambmi = ambmi + mbmi; if (mbmi >= 30) { obesem++; } if(age[j]>=80&&mbmi>=30) { obesep++; } if (age[j] < 30) { mbm1 = (weight[j] / (height[j]*height[j])) * 703; ambm1 = ambm1 + mbm1; below30mal++; } if (age[j] >= 30 && age[j] <= 60) { mbm2 = (weight[j] / (height[j]*height[j])) * 703; ambm2 = ambm2 + mbm2; between30and60mal++; } if (age[j] > 60) { mbm3 = (weight[j] / (height[j]*height[j])) * 703; ambm3 = ambm3 + mbm3; above60mal++; } } else { aagemn = aagemn + age[j]; } } if (gender[j] == 'F') { females++; if (result[j] == '+') { fr++; afage = afage + age[j]; afweig = afweig + weight[j]; fbmi = (weight[j] / (height[j]*height[j])) * 703; afbmi = afbmi + fbmi; if (fbmi >= 30) { obesef++; } if(age[j]>=80&&fbmi>=30) { obesep++; } if (age[j] < 30) { fbm1 = (weight[j] / (height[j]*height[j])) * 703; afbm1 = afbm1 + fbm1; below30fem++; } if (age[j] >= 30 && age[j] <= 60) { fbm2 = (weight[j] / (height[j]*height[j])) * 703; afbm2 = afbm2 + fbm2; between30and60fem++; } if (age[j] > 60) { fbm3 = (weight[j] / (height[j]*height[j])) * 703; afbm3 = afbm3 + fbm3; above60fem++; } } else { aagefn = aagefn + age[j]; } } if (result[j] == '+') { if (age[j] > hage) { hage = age[j]; } if (age[j] <= yage) { yage = age[j]; } } } float a; a = males + females; float b; b = mr + fr; rate = b / a; if(mr!=0) { amage = amage / mr; amweig = amweig / mr; averagebmim = ambmi / mr; } if (fr!=0) { afage = afage / fr; afweig = afweig / fr; averagebmif = afbmi / fr; } if(aagemn!=0) { aagemn = aagemn / (males - mr); } if(aagefn!=0) { aagefn = aagefn / (females - fr); } if(below30mal!=0) { ambm1 = ambm1/below30mal; } if(between30and60mal!=0) { ambm2 = ambm2 / between30and60mal; } if(above60mal!=0) { ambm3 = ambm3 / above60mal; } if(below30fem!=0) { afbm1 = afbm1 / below30fem; } if(between30and60fem!=0) { afbm2 = afbm2 / between30and60fem; } if(above60fem!=0) { afbm3 = afbm3 / above60fem; } printf ("1.How many males have been tested and how many of them tested positive?\n"); printf(" Total males tested is: %d\n", males); printf(" Total males tested positive is: %d\n\n", mr); printf ("2.How many females have been tested and how many of them tested positive?\n"); printf(" Total females tested is : %d\n", females); printf(" Total females tested positive is: %d\n\n", fr); printf ("3.What is the average age of the males who tested positive?\n"); printf(" Average age of males who testes positive is: %d\n\n", amage); printf ("4.What is the average age of the females who tested positive?\n"); printf(" Average age of females who testes positive is: %d\n\n", afage); printf("5. What is the oldest age of a person who tested positive?\n"); printf(" Oldest age of person who tested positive is: %d\n\n", hage); printf ("5.What is the youngest age of a person who tested positive?\n"); printf(" Youngest age of person who tested positive is: %d\n\n", yage); printf ("7.Compare the average age of the males who tested positive to the average age of the males who didnot test positive.\n"); printf(" Average age of male who tested positive is: %d\n", amage); printf(" Average age of male who didnot test positive is: %d\n\n", aagemn); printf ("8.Compare the average age of the females who tested positive to the average age of the females who did not test positive.\n"); printf(" Average age of females who tested positive is: %d\n", afage); printf(" Average age of females who didnot test positive is: %d\n\n", aagefn); printf ("9.What's the average weight of the males who tested positive?\n"); printf(" Average weight of the male who tested positive is: %d\n\n", amweig); printf ("10.What's the average weight of the females who tested positive?\n"); printf(" Average weight of the females who tested positive is: %d\n\n", afweig); printf ("11.Determine the average BMI for the males who tested positive.\n"); printf(" Average BMI for male is: %d\n\n", averagebmim); printf ("12.Determine the average BMI for the females who tested positive.\n"); printf(" Average BMI for females is: %d\n\n", averagebmif); printf ("13.Determine how many of the males who tested positive are obese.\n"); printf(" Obese males are: %d\n\n", obesem); printf ("14.Determine how many of the females who tested positive are obese.\n"); printf(" Obese females are: %d\n\n", obesef); printf ("15.Determine how many people who are 80 or older who tested positive are obese.\n"); printf(" persons who are 80 or older who tested positive are obese are: %d\n\n", obesep); printf ("16.Determine what the average BMI is for males who tested positive in the following three groups: under 30, between 30-60, and over 60.\n"); printf(" Under 30 is: %d\n", ambm1); printf(" Between 30 and 60 is: %d\n", ambm2); printf(" Above 60 is: %d\n\n", ambm3); printf ("17.Determine what the average BMI is for females who tested positive in the following three groups: under 30, between 30-60, and over 60.\n"); printf(" Under 30 is: %d\n", afbm1); printf(" Between 30 and 60 is: %d\n", afbm2); printf(" Above 60 is: %d\n\n", afbm3); printf ("18.What is the average rate of infection for all of the people who were tested?\n"); printf(" Average rate is: %f\n", rate); } fclose(tp); return 0; }
C
/* * Copyright (c) 2010 Luca Abeni * * This is free software; see gpl-3.0.txt */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include "int_coding.h" #include "payload.h" #include "config.h" #include "dechunkiser_iface.h" enum pt { raw, avf, udp, rtp, }; struct dechunkiser_ctx { int fd; enum pt payload_type; }; static struct dechunkiser_ctx *raw_open(const char *fname, const char *config) { struct dechunkiser_ctx *res; struct tag *cfg_tags; res = malloc(sizeof(struct dechunkiser_ctx)); if (res == NULL) { return NULL; } res->fd = 1; res->payload_type = raw; if (fname) { #ifndef _WIN32 res->fd = open(fname, O_WRONLY | O_CREAT, S_IROTH | S_IWUSR | S_IRUSR); #else res->fd = open(fname, O_WRONLY | O_CREAT); #endif if (res->fd < 0) { res->fd = 1; } } cfg_tags = config_parse(config); if (cfg_tags) { const char *pt; pt = config_value_str(cfg_tags, "payload"); if (pt) { if (!strcmp(pt, "avf")) { res->payload_type = avf; } else if (!strcmp(pt, "udp")) { res->payload_type = udp; } else if (!strcmp(pt, "rtp")) { res->payload_type = rtp; } } } free(cfg_tags); return res; } static void raw_write(struct dechunkiser_ctx *o, int id, uint8_t *data, int size) { int offset; if (o->payload_type == avf) { int header_size; int frames; int i; uint8_t codec; if (data[0] == 0) { fprintf(stderr, "Error! Strange chunk: %x!!!\n", codec); return; } else if (data[0] < 127) { int width, height, frame_rate_n, frame_rate_d; header_size = VIDEO_PAYLOAD_HEADER_SIZE; video_payload_header_parse(data, &codec, &width, &height, &frame_rate_n, &frame_rate_d); // dprintf("Frame size: %dx%d -- Frame rate: %d / %d\n", width, height, frame_rate_n, frame_rate_d); } else { uint8_t channels; int sample_rate, frame_size; header_size = AUDIO_PAYLOAD_HEADER_SIZE; audio_payload_header_parse(data, &codec, &channels, &sample_rate, &frame_size); // dprintf("Frame size: %d Sample rate: %d Channels: %d\n", frame_size, sample_rate, channels); } frames = data[header_size - 1]; for (i = 0; i < frames; i++) { int frame_size; int64_t pts, dts; frame_header_parse(data, &frame_size, &pts, &dts); // dprintf("Frame %d has size %d\n", i, frame_size); } offset = header_size + frames * FRAME_HEADER_SIZE; } else if (o->payload_type == udp) { offset = UDP_CHUNK_HEADER_SIZE; } else if (o->payload_type == rtp) { offset = UDP_CHUNK_HEADER_SIZE + 12; } else { offset = 0; } write(o->fd, data + offset, size - offset); } static void raw_close(struct dechunkiser_ctx *s) { close(s->fd); free(s); } struct dechunkiser_iface out_raw = { .open = raw_open, .write = raw_write, .close = raw_close, };
C
#include "stm32f10x.h" //使用STM32标准函数库需要添加此头文件 #include "stdio.h" #include "stdout_USART.h" void ADC_RCC_Init(void) { RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_ADC1 , ENABLE ); //使能ADC1 通道时钟 RCC_ADCCLKConfig(RCC_PCLK2_Div6); //设置ADC 分频因子6,72M/6=12,ADC 最大时间不能超过14M } void ADC_GPIO_Init(void) { GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Pin =GPIO_Pin_1;//PA1 作为模拟通道输入引脚 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;//模拟输入 GPIO_Init(GPIOA, &GPIO_InitStructure); //初始化GPIOA1 } void ADC_Mode_Config(void) { ADC_InitTypeDef ADC_InitStructure; ADC_DeInit(ADC1); //复位ADC1 ADC_InitStructure.ADC_Mode = ADC_Mode_Independent; //ADC 独立模式 ADC_InitStructure.ADC_ScanConvMode = DISABLE; //单通道模式 ADC_InitStructure.ADC_ContinuousConvMode = DISABLE; //单次转换模式 ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;//转换由软件而不是外部触发启动 ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right; //ADC 数据右对齐 ADC_InitStructure.ADC_NbrOfChannel = 1; //顺序进行规则转换的ADC 通道的数目 ADC_Init(ADC1, &ADC_InitStructure); //根据指定的参数初始化外设ADCx ADC_Cmd(ADC1, ENABLE); //使能指定的ADC1 ADC_ResetCalibration(ADC1); //开启复位校准 while(ADC_GetResetCalibrationStatus(ADC1)); //等待复位校准结束 ADC_StartCalibration(ADC1); //开启AD 校准 while(ADC_GetCalibrationStatus(ADC1)); //等待校准结束 } uint16_t Get_Adc(uint8_t ch) { //设置指定ADC 的规则组通道,设置它们的转化顺序和采样时间 ADC_RegularChannelConfig(ADC1, ch, 1, ADC_SampleTime_239Cycles5 );//通道1,规则采样顺序值为1,采样时间为239.5 周期 ADC_SoftwareStartConvCmd(ADC1, ENABLE); //使能指定的ADC1 的软件转换功能 while(!ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC ));//等待转换结束 return ADC_GetConversionValue(ADC1); //返回最近一次ADC1 规则组的转换结果 } void ADC_Inti() { ADC_RCC_Init(); // 初始化RCC ADC_GPIO_Init(); // 初始化GPIO ADC_Mode_Config(); // 初始化ADC模式 } int main(void) { uint16_t adcx;float real_v; stdout_init(); // 初始化printf()函数 while(1){ ADC_Inti(); // ADC初始化 adcx = Get_Adc(1); // 获得AD数据 real_v=(float)adcx*(2.5/4096); // 转换成真实电压值 printf("get value of adc is :%d\r\n",adcx); printf("real v is :%f\r\n",real_v); } }
C
#include <stdio.h> int main() { int grid[3][3]; int row,col; /* initialize the array */ for(row=0;row<3;row++) for(col=0;col<3;col++) grid[row][col] = 0; grid[1][1] = 1; /* display the grid */ for(row=0;row<3;row++) { for(col=0;col<3;col++) printf("%d ",grid[row][col]); putchar('\n'); } return(0); }
C
#include<stdio.h> int main() { int a; printf("enter number:"); scanf("%x",&a); a=(a<<24 & 0xFF000000)| (a>>24 & 0x000000FF)| (a<<8 & 0x00FF0000)| (a>>8 & 0x0000FF00); printf("%x\n",a); }
C
/****************************************************************************** * Filename : wd_outer.c * Developer : Eyal Weizman * Last Update : 2019-05-18 * Description : source file for the outer WD process. *******************************************************************************/ #define _POSIX_C_SOURCE 200112L /* struct sigaction */ #include <assert.h> /* assert */ #ifndef NDEBUG #include <stdio.h> /* printf */ #endif #include "./scheduler/scheduler.h" #include "wd_shared.h" /******************************* MACROS ***************************************/ #define UNUSED(x) ((void) x) /************************** internal functions ********************************/ static void InitWD(com_pack_t *wd_pack); /****************************************************************************** * main *******************************************************************************/ int main(int argc, char *const argv[]) { /* create a pack of arguments via stack allocation */ com_pack_t com_pack = {0}; UNUSED(argc); #ifndef NDEBUG printf("\n *** WD: IM ALIVE!!!***\n\n"); printf("WD pid is: %d\n", getpid()); #endif com_pack.argv = argv; InitWD(&com_pack); /* main loop - can be stopped by SIGUSR2 */ MainLoop(&com_pack); /* free resources */ SchedulerDestroyWrapper(); #ifndef NDEBUG printf("\n ***WD is dead ***\n\n"); #endif return (0); } /************************** InitWD ********************************************/ static void InitWD(com_pack_t *com_pack) { assert(com_pack); /* at this point, the parent process is necessarily the app */ com_pack->other_proc_pid = getppid(); /* define the behaviour when SIGUSR1/SIGUSR2 are received */ com_pack->sig_1.sa_handler = SigHandZeroCounter; sigaction(SIGUSR1, &(com_pack->sig_1), NULL); com_pack->sig_2.sa_handler = SigHandStopMainLoop; sigaction(SIGUSR2, &(com_pack->sig_2), NULL); /* set mask */ sigemptyset(&(com_pack->mask)); sigaddset(&(com_pack->mask), SIGUSR1); /* set the app name (from argv[0]) in who_to_revive */ com_pack->who_to_revive = com_pack->argv[0]; /* create scheduler & load it with tasks */ InitScheduler(com_pack); }
C
#include <stdio.h> int insert_num(int a[],int size,int num,int ind) { int n1,n2; size++; if(ind>=0&&ind<size) { n2=size-1; for(n1=size;n1>ind;n1--) { a[n1]=a[n2]; --n2; } a[ind]=num; } else { printf("\nEnter the correct index...."); return 0; } return size; } int main(void) { int a[20],size,num,ind,i,num2; printf("Enter the size of the array...."); scanf("%d",&size); printf("\nEnter the elements in the array...."); for(i=0;i<size;i++) { scanf("%d",&a[i]); } printf("\nEnter the number to be inserted...."); scanf("%d",&num); printf("\nEnter the index...."); scanf("%d",&ind); num2=insert_num(a,size,num,ind); printf("\n"); for(i=0;i<num2;i++) { printf("%d\t",a[i]); } return 0; }
C
//==================================================================== // 工学部「情報環境実験1」(富永) 例題 // 多倍長整数の計算 除算と応用 //-------------------------------------------------------------------- // BigNum BigNumDiv.c // ライブラリ // Linux GCC 4.4 //-------------------------------------------------------------------- // 富永研究室 tominaga 富永浩之 // 2015.05.20 v3.0 //==================================================================== //==================================================================== // s15t200 高松太郎 // 2017.00.00 v3.0 //==================================================================== //==================================================================== // 前処理 //==================================================================== //-------------------------------------------------------------------- // ヘッダ指定 //-------------------------------------------------------------------- #include <stdio.h> #include "BigNumLib.h" //==================================================================== // 関数定義(除算) //==================================================================== //-------------------------------------------------------------------- // 多倍長整数の除算(整商と剰余) //-------------------------------------------------------------------- Bool bignum_div(BigNum b1, BigNum b2, BigNum *b3, BigNum *b4) { // return bignum_div3(b1, b2, b3, b4); return bignum_div4(b1, b2, b3, b4); } //-------------------------------------------------------------------- // 多倍長÷多倍長=単倍長‥多倍長 (減算法) //-------------------------------------------------------------------- Bool bignum_div0(BigNum b1, BigNum b2, int *a3, BigNum *b4) { //---- 初期処理 if ( bignum_zero(b2) ) { return FALSE; } // 計算不可の除外 *a3 = 0; // 整商の初期化(減算の反復回数) *b4 = b1; // 剰余の初期化(減算の最終結果) //---- 除算処理 // b2×a3 ≦ b1 < b2×(a3+1) となるa3を減算法で求める while ( *a3 < RAD ) { if ( bignum_cmp(*b4, b2) < 0 ) { break; } // 除数と剰余の比較 bignum_sub(*b4, b2, b4); // 剰余からの減算 (*a3)++; // 整商の増分 } // 以下でもよい // if ( ! bignum_sub(*b4, b2, t) ) { break; } // *b4 = t; (*a3)++; //---- 事後処理 if ( *a3 >= RAD ) { return FALSE; } // 範囲超過 return bignum_normal(b4); // 正常に処理完了 // 減算法は非効率なので、二分法で効率化する } //-------------------------------------------------------------------- // 多倍長÷多倍長=単倍長‥多倍長 (二分法) //-------------------------------------------------------------------- Bool bignum_div1(BigNum b1, BigNum b2, int *a3, BigNum *b4) { //---- 局所宣言 int low = 0; // 下端値 int hig = RAD; // 上端値 BigNum val; // 乗算値 int cmp; // 比較結果 //---- 事前処理 if ( bignum_zero(b2) ) { return FALSE; } // 除数が0なら計算不可 //---- 二分法の適用 while ( hig - low > 1 ) { // hig‐low=1 は事後処理に *a3 = (low+hig)/2; // 中央値(切捨であることに注意) val = b2; // bignum_scl(&val, *a3); // 仮の整商で乗算 cmp = bignum_cmp(b1, val); // 比較結果 if ( cmp <= 0 ) { hig = *a3; } else { low = *a3; } } // b2×a3=val ≦ b1 < b2×(a3+1) となるa3を二分法で求める //---- 結果の調整と吟味 if ( bignum_cmp(b1, val) < 0 ) { (*a3)--; } // 整商は切捨値 bignum_scl(&b2, *a3); // 乗算値の再計算 return bignum_sub(b1, b2, b4); // 剰余の計算 } //-------------------------------------------------------------------- // 多倍長÷単倍長=多倍長‥単倍長 (商立法) //-------------------------------------------------------------------- Bool bignum_div2(BigNum b1, int a2, BigNum *b3, int *a4) { //---- 局所宣言 int k; // 反復変数 //---- 初期処理 if ( a2 == 0 ) { return FALSE; } // 計算不可の除外 bignum_init(b3, 0, 0); // 整商の初期化 *a4 = 0; // 剰余の初期化 //---- 除算処理 for ( k = b1.nsz-1; k >= 0; k-- ) { // 上位節から計算 *a4 *= RAD; *a4 += b1.node[k]; // 一時的な被除数(繰下りを含む) b3->node[k] = *a4 / a2; // 整商の節値 *a4 %= a2; // 剰余の更新 } //---- 事後処理 return bignum_normal(b3); // 節数と桁数の格納 } //------------------------------------------------------------------- // 多倍長÷多倍長=多倍長‥多倍長 (商立法) //-------------------------------------------------------------------- Bool bignum_div3(BigNum b1, BigNum b2, BigNum *b3, BigNum *b4) { //---- 局所宣言 int nsz; // 節数 int a3; // 整商の節値 int k; // 反復変数 //---- 事前処理 if ( bignum_zero(b2) ) { return FALSE; } // 計算不可の除外 bignum_init(b3, 0, 0); // 整商の初期化(0) nsz = b1.nsz - b2.nsz +1; // 節数の差(整商の節数) if ( nsz < 0 ) { *b4 = b1; return TRUE; } // 整商が0のとき終了 *b4 = b1; // bignum_shift(b4, -nsz); // 剰余の初期化 //---- 除算処理 for ( k = nsz-1; k >= 0; k-- ) { bignum_shift(b4, 1); // 剰余の候補のRAD倍(左移動) bignum_inc(b4, b1.node[k], 0); // 部分節との加算 bignum_div1(*b4, b2, &a3, b4); // b4とb2に除算による剰余の更新 b3->node[k] = a3; // 整商を節値の格納 } //---- 事後処理 return bignum_normal(b3); } //-------------------------------------------------------------------- // 多倍長÷多倍長=多倍長‥多倍長 (二分法) //-------------------------------------------------------------------- Bool bignum_div4(BigNum b1, BigNum b2, BigNum *b3, BigNum *b4) { //---- 局所宣言 BigNum low; // 下端 BigNum hig; // 上端 BigNum m0, m1; // 中央 BigNum v0, v1; // 計算値(除数と仮整商の積) int nsz; // 上端の節数 int cmp; // 大小比較の結果 //---- 初期処理 if ( bignum_zero(b2) ) { return FALSE; } nsz = b1.nsz - b2.nsz +1; // 上端の節数 if ( nsz <= 0 ) { *b4 = b1; bignum_init(b3, 0, 0); return TRUE; } bignum_init(&low, 0, 0); // 下端の初期化(0) bignum_init(&hig, 1, nsz); // 上端の初期化(節移動) while ( TRUE ) { //-- 中央値m0と累乗値v0の計算 bignum_add(low, hig, &m0); bignum_half(&m0); bignum_mlt(b2, m0, &v0); //-- 中央値の増分m1と累乗値v1の計算 m1 = m0; bignum_inc(&m1, 1, 0); bignum_mlt(b2, m1, &v1); //-- 計算の終了判定と範囲の更新 if ( bignum_within(v0, b1, v1) ) { break; } if ( bignum_cmp(v0, b1) <= 0 ) { low = m0; } else { hig = m0; } } //---- 事後処理 *b3 = m0; return bignum_sub(b1, v0, b4); } //-------------------------------------------------------------------- // 多倍長整数の半分 //-------------------------------------------------------------------- Bool bignum_half(BigNum *b0) { //---- 局所宣言 int r; // 剰余 int k; // 反復変数 //---- 計算処理(ビット演算の利用) for ( k = b0->nsz -1; k >= 0; k-- ) { // 上位節から r = b0->node[k] & 1; // 奇偶 b0->node[k] >>= 1; // 半分 if ( r == 1 && k >= 1 ) { b0->node[k-1] += RAD; // 桁送り } } //---- 事後処理 return bignum_normal(b0); // 節数と桁数の格納 } //==================================================================== // 関数定義 累乗根 //==================================================================== //-------------------------------------------------------------------- // 二分法による平方根の切捨整数値 //-------------------------------------------------------------------- Bool bignum_sqrt(BigNum b1, BigNum *b0) { return bignum_plrt(b1, 2, b0); } //-------------------------------------------------------------------- // 二分法による累乗根の切捨整数値 //-------------------------------------------------------------------- Bool bignum_plrt(BigNum b1, int e, BigNum *b0) { //---- 局所宣言 BigNum low; // 下端 BigNum hig; // 上端 BigNum m0, m1; // 中央 BigNum v0, v1; // 累乗値 int nsz; // // b0^e ≦ b1 < (b0+1)^e となるb0を二分法で求める // 比較が面倒なので、m0 と m1=m0+1 を用意して、 // m0^e ≦ b1 < m1^e を終了条件にして反復処理を行う // 不等号を調整すれば、m1で切上整数値が求められる //---- 初期処理 nsz = b1.nsz/e +1; // higの節数 bignum_init(&low, 0, 0); // lowを最下端0に初期化 bignum_init(&hig, 1, nsz); // higを最上端に初期化 //---- 二分法の計算処理 while ( TRUE ) { //-- 中央値m0と累乗値v0の計算 bignum_add(low, hig, &m0); bignum_half(&m0); bignum_pow(m0, e, &v0); //-- 中央値の増分m1と累乗値v1の計算 m1 = m0; bignum_inc(&m1, 1, 0); bignum_pow(m1, e, &v1); //-- 計算の終了判定と範囲の更新 if ( bignum_within(v0, b1, v1) ) { break; } if ( bignum_cmp(v0, b1) <= 0 ) { low = m0; } else { hig = m0; } } //---- 事後処理 *b0 = m0; // 中央値m0を結果b0に格納 return bignum_normal(b0); // 正常に処理完了 } //==================================================================== // 関数定義(最大公約数) //==================================================================== //-------------------------------------------------------------------- // 最大公約数 //-------------------------------------------------------------------- Bool bignum_gcd(BigNum b1, BigNum b2, BigNum *b0) { // return bignum_gcd1(b1, b2, b0); return bignum_gcd2(b1, b2, b0); } //-------------------------------------------------------------------- // ブレントの算法による最大公約数 //-------------------------------------------------------------------- Bool bignum_gcd1(BigNum b1, BigNum b2, BigNum *b0) { //---- 局所宣言 int e; // 2の指数 int cmp; // 比較結果 //---- 事前処理 while ( b1.node[0] %2 == 0 && b2.node[0] %2 == 0 ) { bignum_half(&b1); bignum_half(&b2); e++; // ともに偶数なら割り続ける } //---- 計算処理 while ( 1 ) { //-- ともに奇数になるまで2で割っておく while ( b1.node[0] %2 == 0 ) { bignum_half(&b1); } while ( b2.node[0] %2 == 0 ) { bignum_half(&b2); } //-- 相等なら終了、そうでなければ大きい方から小さい方を引いて更新 cmp = bignum_cmp(b1, b2); if ( cmp == 0 ) { *b0 = b1; break; } if ( cmp > 0 ) { bignum_sub(b1, b2, &b1); } if ( cmp < 0 ) { bignum_sub(b2, b1, &b2); } } //---- 事後処理 while ( e-- > 0 ) { bignum_scl(b0, 2); } // 指数分だけ2を乗算 return TRUE; // 正常に処理完了 } //-------------------------------------------------------------------- // ユークリッドの互除法による最大公約数 //-------------------------------------------------------------------- Bool bignum_gcd2(BigNum b1, BigNum b2, BigNum *b0) { //---- 局所宣言 BigNum t; // 除算における整商の捨値 //---- 計算処理 while ( ! bignum_zero(b2) ) { bignum_div(b1, b2, &t, &b1); t = b1; b1 = b2; b2 = t; } //---- 返却処理 *b0 = b1; return TRUE; // 正常に処理完了 }
C
/* * Trabajo.h * * Created on: 3 may. 2021 * Author: Julian Leandro Nieva 1C */ #ifndef TRABAJO_H_ #define TRABAJO_H_ #define MAX_TRABAJOS 10 #include "Fecha.h" #define IS_EMPTY 0 #define NOT_EMPTY 1 typedef struct { int id; int idMascota;//fk int idServicio;//fk int idVeterinario;//fk eFecha fecha; int isEmpty; }eTrabajo; /** * @fn void InicializarTrabajos(eTrabajo[]) * @brief Incizalizo los trabajos para que esten vacios * * @param listaTrabajos[] Array de trabajos */ void InicializarTrabajos(eTrabajo[],int); /** * @fn int BuscarLibre(eTrabajo[]) * @brief Buusco un espacio libre en el array * * @param listaTrabajos[] Array de trabajos * @return Retorna la posicion donde se encuetra libre */ int BuscarLibre(eTrabajo[],int); /** * @fn int DarDeBajaDeTrabajo(eTrabajo[]) * @brief Dar de baja un trabajo * * @param listadoTrabajos[] array de trabajos * @return Retorna un valor dependiendo de lo que sucedio dentro de la funcion */ int DarDeBajaDeTrabajo(eTrabajo[],int); /** * @fn int BuscarId(eTrabajo[], int) * @brief Busca el id de un trabajo * * @param listadoTrabajos[] Array de trabajos * @param id Id que se le pasa mediante parametros para realizar la busqueda * @param tam Tamao del array * @return Devuelve la posicion del array donde se encuentra el trabajo */ int BuscarId(eTrabajo[], int,int); #endif /* TRABAJO_H_ */
C
/* 軭 */ #include "bootpack.h" void init_palette(void) { static unsigned char table_rgb[16 * 3] = { 0x00, 0x00, 0x00, /* 0:\ */ 0xff, 0x00, 0x00, /* 1: */ 0x00, 0xff, 0x00, /* 2: */ 0xff, 0xff, 0x00, /* 3: */ 0x00, 0x00, 0xff, /* 4: */ 0xff, 0x00, 0xff, /* 5: */ 0x00, 0xff, 0xff, /* 6:dz */ 0xff, 0xff, 0xff, /* 7: */ 0xc6, 0xc6, 0xc6, /* 8: */ 0x84, 0x00, 0x00, /* 9: */ 0x00, 0x84, 0x00, /* 10:v */ 0x84, 0x84, 0x00, /* 11: */ 0x00, 0x00, 0x84, /* 12: */ 0x84, 0x00, 0x84, /* 13: */ 0x00, 0x84, 0x84, /* 14:dz */ 0x84, 0x84, 0x84 /* 15: */ };/* Cеstatic char ֻݣ൱ڻеDBָ*/ unsigned char table2[216 * 3]; int r, g, b; set_palette(0, 15, table_rgb); for (b = 0; b < 6; b++) { for (g = 0; g < 6; g++) { for (r = 0; r < 6; r++) { table2[(r + g * 6 + b * 36) * 3 + 0] = r * 51; table2[(r + g * 6 + b * 36) * 3 + 1] = g * 51; table2[(r + g * 6 + b * 36) * 3 + 2] = b * 51; } } } set_palette(16, 231, table2); return; } void set_palette(int start, int end, unsigned char *rgb) { int i, eflags; eflags = io_load_eflags(); /* ¼жɱ־ֵ */ io_cli(); /* жɱ־Ϊ0ֹж*/ io_out8(0x03c8, start); for (i = start; i <= end; i++) { io_out8(0x03c9, rgb[0] / 4); io_out8(0x03c9, rgb[1] / 4); io_out8(0x03c9, rgb[2] / 4); rgb += 3; } io_store_eflags(eflags); /* ԭжɱ־ */ return; } void boxfill8(unsigned char *vram, int xsize, unsigned char c, int x0, int y0, int x1, int y1) { int x, y; for (y = y0; y <= y1; y++) { for (x = x0; x <= x1; x++) vram[y * xsize + x] = c; } return; } void init_screen8(char *vram, int x, int y) { boxfill8(vram, x, COL8_008484, 0, 0, x - 1, y - 29); set_picture(vram, x, y); boxfill8(vram, x, COL8_C6C6C6, 0, y - 28, x - 1, y - 28); boxfill8(vram, x, COL8_FFFFFF, 0, y - 27, x - 1, y - 27); boxfill8(vram, x, COL8_C6C6C6, 0, y - 26, x - 1, y - 1); boxfill8(vram, x, COL8_FFFFFF, 3, y - 24, 59, y - 24); boxfill8(vram, x, COL8_FFFFFF, 2, y - 24, 2, y - 4); boxfill8(vram, x, COL8_848484, 3, y - 4, 59, y - 4); boxfill8(vram, x, COL8_848484, 59, y - 23, 59, y - 5); boxfill8(vram, x, COL8_000000, 2, y - 3, 59, y - 3); boxfill8(vram, x, COL8_000000, 60, y - 24, 60, y - 3); putfonts8_asc(vram, x, 11, y - 22 , COL8_840084, "˵"); return; } void putfont8(char *vram, int xsize, int x, int y, char c, char *font) { int i; char *p, d /* data */; for (i = 0; i < 16; i++) { p = vram + (y + i) * xsize + x; d = font[i]; if ((d & 0x80) != 0) { p[0] = c; } if ((d & 0x40) != 0) { p[1] = c; } if ((d & 0x20) != 0) { p[2] = c; } if ((d & 0x10) != 0) { p[3] = c; } if ((d & 0x08) != 0) { p[4] = c; } if ((d & 0x04) != 0) { p[5] = c; } if ((d & 0x02) != 0) { p[6] = c; } if ((d & 0x01) != 0) { p[7] = c; } } return; } void putfont8_ch(char *vram, int xsize, int x, int y, char c, char *font) { int i; char *p, d; for (i = 0; i < 16; i++) { p = vram + (y + i) * xsize + x; d = font[i * 2]; if ((d & 0x80) != 0) p[0] = c; if ((d & 0x40) != 0) p[1] = c; if ((d & 0x20) != 0) p[2] = c; if ((d & 0x10) != 0) p[3] = c; if ((d & 0x08) != 0) p[4] = c; if ((d & 0x04) != 0) p[5] = c; if ((d & 0x02) != 0) p[6] = c; if ((d & 0x01) != 0) p[7] = c; } return; } void putfonts8_asc(char *vram, int xsize, int x, int y, char c, unsigned char *s) { extern char hankaku[4096]; struct TASK *task = task_now(); char *nihongo = (char *) *((int *) 0x0fe8), *font; int k, t; if (task->langmode == 0) { for (; *s != 0x00; s++) { putfont8(vram, xsize, x, y, c, hankaku + *s * 16); x += 8; } } if (task->langmode == 1) { for (; *s != 0x00; s++) { if (task->langbyte1 == 0) { if ((0x81 <= *s && *s <= 0x9f) || (0xe0 <= *s && *s <= 0xfc)) { task->langbyte1 = *s; } else { putfont8(vram, xsize, x, y, c, nihongo + *s * 16); } } else { if (0x81 <= task->langbyte1 && task->langbyte1 <= 0x9f) { k = (task->langbyte1 - 0x81) * 2; } else { k = (task->langbyte1 - 0xe0) * 2 + 62; } if (0x40 <= *s && *s <= 0x7e) { t = *s - 0x40; } else if (0x80 <= *s && *s <= 0x9e) { t = *s - 0x80 + 63; } else { t = *s - 0x9f; k++; } task->langbyte1 = 0; font = nihongo + 256 * 16 + (k * 94 + t) * 32; putfont8(vram, xsize, x - 8, y, c, font ); /* */ putfont8(vram, xsize, x , y, c, font + 16); /* E */ } x += 8; } } if (task->langmode == 2) { for (; *s != 0x00; s++) { if (task->langbyte1 == 0) { if (0x81 <= *s && *s <= 0xfe) { task->langbyte1 = *s; } else { putfont8(vram, xsize, x, y, c, nihongo + *s * 16); } } else { k = task->langbyte1 - 0xa1; t = *s - 0xa1; task->langbyte1 = 0; font = nihongo + 256 * 16 + (k * 94 + t) * 32; putfont8(vram, xsize, x - 8, y, c, font ); /* */ putfont8(vram, xsize, x , y, c, font + 16); /* E */ } x += 8; } } if (task->langmode == 3) { for (; *s != 0x00; s++) { if (task->langbyte1 == 0) { if (*s >= 0xa0) { task->langbyte1 = *s; } else { putfont8(vram, xsize, x, y, c, hankaku + *s * 16); } } else { k = task->langbyte1 - 0xa0; t = *s - 0xa0; task->langbyte1 = 0; font = nihongo + ((k - 1) * 94 + (t - 1)) * 32; putfont8_ch(vram, xsize, x - 8, y, c, font); putfont8_ch(vram, xsize, x, y, c, font + 1); } x += 8; } } return; } void init_mouse_cursor8(char *mouse, char bc) /* ״ 16x16 */ { static char cursor[16][16] = { "**************..", "*OOOOOOOOOOO*...", "*OOOOOOOOOO*....", "*OOOOOOOOO*.....", "*OOOOOOOO*......", "*OOOOOOO*.......", "*OOOOOOO*.......", "*OOOOOOOO*......", "*OOOO**OOO*.....", "*OOO*..*OOO*....", "*OO*....*OOO*...", "*O*......*OOO*..", "**........*OOO*.", "*..........*OOO*", "............*OO*", ".............***" }; int x, y; for (y = 0; y < 16; y++) { for (x = 0; x < 16; x++) { if (cursor[y][x] == '*') { mouse[y * 16 + x] = COL8_000000; } if (cursor[y][x] == 'O') { mouse[y * 16 + x] = COL8_FFFFFF; } if (cursor[y][x] == '.') { mouse[y * 16 + x] = bc; } } } return; } void putblock8_8(char *vram, int vxsize, int pxsize, int pysize, int px0, int py0, char *buf, int bxsize) { int x, y; for (y = 0; y < pysize; y++) { for (x = 0; x < pxsize; x++) { vram[(py0 + y) * vxsize + (px0 + x)] = buf[y * bxsize + x]; } } return; } //start_status_switch()лͼstartťʾ״̬ void start_status_switch(unsigned int status,struct SHEET *sht){ unsigned char *vram; int xsize, ysize; vram = sht->buf, xsize = sht->bxsize, ysize = sht->bysize; int color=COL8_FF0000; if(status == 0){ //startťδ boxfill8(vram, xsize, COL8_FFFFFF, 3, ysize - 24, 59, ysize - 24); boxfill8(vram, xsize, COL8_FFFFFF, 2, ysize - 24, 2, ysize - 4); boxfill8(vram, xsize, COL8_848484, 3, ysize - 4, 59, ysize - 4); boxfill8(vram, xsize, COL8_848484, 59, ysize - 23, 59, ysize - 5); boxfill8(vram, xsize, COL8_000000, 2, ysize - 3, 59, ysize - 3); boxfill8(vram, xsize, COL8_000000, 60, ysize - 24, 60, ysize - 3); color = COL8_840084; } else{ //startť boxfill8(vram, xsize, COL8_000000, 3, ysize - 24, 59, ysize - 24); boxfill8(vram, xsize, COL8_000000, 2, ysize - 24, 2, ysize - 4); boxfill8(vram, xsize, COL8_848484, 3, ysize - 23, 59, ysize - 23); boxfill8(vram, xsize, COL8_848484, 3, ysize - 23, 3, ysize - 5); boxfill8(vram, xsize, COL8_FFFFFF, 2, ysize - 3, 59, ysize - 3); boxfill8(vram, xsize, COL8_FFFFFF, 60, ysize - 24, 60, ysize - 3); color = COL8_000000; } putfonts8_asc(vram, xsize, 11, ysize - 22, color, "˵"); sheet_refresh(sht, 1, ysize - 25, 61, ysize - 2); } void init_menu(struct SHEET *sht){ unsigned char *vram; int xsize, ysize, yskip; vram = sht->buf; xsize = sht->bxsize, ysize = sht->bysize; yskip = ysize / 6; boxfill8(vram, xsize, COL8_C6C6C6, 0, 0, xsize - 1, ysize - 1); //ɫ //boxfill8(vram, xsize, COL8_848484, 1, 1, xsize - 2, yskip-1); //߿ boxfill8(vram, xsize, COL8_000000, 0, 0, xsize - 1, 0); boxfill8(vram, xsize, COL8_000000, 0, 0, 0, ysize - 1); boxfill8(vram, xsize, COL8_000000, 0, ysize - 1, xsize - 1, ysize - 1); boxfill8(vram, xsize, COL8_000000, xsize-1, 0, xsize - 1, ysize - 1); //˵ѡ boxfill8(vram, xsize, COL8_000000, 0, 1 * yskip, xsize - 1, 1 * yskip); boxfill8(vram, xsize, COL8_000000, 0, 2 * yskip, xsize - 1, 2 * yskip); boxfill8(vram, xsize, COL8_000000, 0, 3 * yskip, xsize - 1, 3 * yskip); boxfill8(vram, xsize, COL8_000000, 0, 4 * yskip, xsize - 1, 4 * yskip); boxfill8(vram, xsize, COL8_000000, 0, 5 * yskip, xsize - 1, 5 * yskip); putfonts8_asc(vram, xsize, 8, 7, COL8_000000, "Ϣ"); putfonts8_asc(vram, xsize, 8, 7 + yskip * 1, COL8_000000, "̨"); putfonts8_asc(vram, xsize, 8, 7 + yskip * 2, COL8_000000, "Ϸ"); putfonts8_asc(vram, xsize, 8, 7 + yskip * 3, COL8_000000, "ļ"); putfonts8_asc(vram, xsize, 8, 7 + yskip * 4, COL8_000000, ""); putfonts8_asc(vram, xsize, 8, 7 + yskip * 5, COL8_000000, "ػ"); sheet_refresh(sht, 0, 0, xsize - 1, ysize - 1); } struct SHEET *init_fileManager(struct SHTCTL *shtctl){ struct SHEET *sht_fm = sheet_alloc(shtctl); struct MEMMAN *memman = (struct MEMMAN *) MEMMAN_ADDR; unsigned char *buf_fm = (unsigned char *) memman_alloc_4k(memman, 780 * 500); struct FILEINFO *finfo = (struct FILEINFO *) (ADR_DISKIMG + 0x002600); int i, j, line = 0; char s[50]; unsigned short year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0; sheet_setbuf(sht_fm, buf_fm, 780, 500, -1); /* Ϊͼû */ sht_fm->flags |= 0x40; //˵ѡ make_window8(sht_fm->buf, sht_fm->bxsize, sht_fm->bysize, "ļ", 1); boxfill8(buf_fm, sht_fm->bxsize, COL8_FFFFFF, 6, 27, sht_fm->bxsize - 6, sht_fm->bysize - 6); for(i = 0; i < 49; i++){ s[i] = 0; } for (i = 0; i < 224; i++) { if (finfo[i].name[0] == 0x00) { break; } if (finfo[i].name[0] != 0xe5) { if ((finfo[i].type & 0x18) == 0) { //ת ڡʱ year = (finfo[i].date >> 9) + 1980; month = (finfo[i].date >> 5) & 15; day = finfo[i].date & 31; hour = finfo[i].time >> 11; minute = (finfo[i].time >> 5) & 63, second = (finfo[i].time & 31) * 2; sprintf(s, "filename.ext %7d byte %4d/%02d/%02d %02d:%02d:%02d", finfo[i].size, year, month, day, hour, minute, second); for (j = 0; j < 8; j++) { s[j] = finfo[i].name[j]; } s[ 9] = finfo[i].ext[0]; s[10] = finfo[i].ext[1]; s[11] = finfo[i].ext[2]; if(line > 26){ putfonts8_asc_sht(sht_fm, 6 + (sht_fm->bxsize / 2), (line - 27) * 16 + 27, COL8_000000, COL8_FFFFFF, s, 45); } else{ putfonts8_asc_sht(sht_fm, 6, line * 16 + 27, COL8_000000, COL8_FFFFFF, s, 45); } line++; } } } return sht_fm; } int set_picture(unsigned char *vram, int x, int y) { int i, j, x0, y0, fsize, info[4]; unsigned char *filebuf, r, g, b; struct RGB *picbuf; struct MEMMAN *memman = (struct MEMMAN *) MEMMAN_ADDR; struct BOOTINFO *binfo = (struct BOOTINFO *) ADR_BOOTINFO; struct FILEINFO *finfo; struct DLL_STRPICENV *env; int *fat; fat = (int *) memman_alloc_4k(memman, 4 * 2880); file_readfat(fat, (unsigned char *) (ADR_DISKIMG + 0x000200)); finfo = file_search("image.jpg", (struct FILEINFO *) (ADR_DISKIMG + 0x002600), 224); if (finfo == 0 || (finfo->type & 0x18) != 0) { boxfill8(vram, x, COL8_FF0000, 100, 100, 300, 400); return -1; } fsize = finfo->size; filebuf = (unsigned char *) memman_alloc_4k(memman, fsize); filebuf = file_loadfile2(finfo->clustno, &fsize, fat); env = (struct DLL_STRPICENV *) memman_alloc_4k(memman, sizeof(struct DLL_STRPICENV)); if(info_JPEG(env, info, fsize, filebuf) == 0){ return -1; // jpegļ } picbuf = (struct RGB *) memman_alloc_4k(memman, info[2] * info[3] * sizeof(struct RGB)); decode0_JPEG(env, fsize, filebuf, 4, (unsigned char *) picbuf, 0); x0 = (int) ((x - info[2]) / 2); y0 = (int) ((y - info[3]) / 2); for (i = 0; i < info[3]; i++) { for (j = 0; j < info[2]; j++) { r = picbuf[i * info[2] + j].r; g = picbuf[i * info[2] + j].g; b = picbuf[i * info[2] + j].b; vram[(y0 + i) * x + (x0 + j)] =(unsigned char) rgb2pal(r, g, b, j, i, binfo->vmode); } } memman_free_4k(memman, (int) filebuf, fsize); memman_free_4k(memman, (int) picbuf , info[2] * info[3] * sizeof(struct RGB)); memman_free_4k(memman, (int) env , sizeof(struct DLL_STRPICENV)); memman_free_4k(memman, (int) fat, 4 * 2880); return 0; } unsigned char rgb2pal(int r, int g, int b, int x, int y, int cb) { if (cb == 8) { static int table[4] = { 3, 1, 0, 2 }; int i; x &= 1; /* жż */ y &= 1; i = table[x + y * 2]; /* мɫij */ r = (r * 21) / 256; /* Ϊ0~20*/ g = (g * 21) / 256; b = (b * 21) / 256; r = (r + i) / 4; /* Ϊ0~5 */ g = (g + i) / 4; b = (b + i) / 4; return((unsigned char) (16 + r + g * 6 + b * 36)); } else { return((unsigned char) (((r << 8) & 0xf800) | ((g << 3) & 0x07e0) | (b >> 3))); } }
C
#include <stdio.h> #include <stdlib.h> void main() { int a=86; int b=21; printf("%d \n",a/b); float c=86.0; float d=21.0; printf("%f \n",c/d); }
C
#include<stdio.h> #include<stdlib.h> int main(){ FILE *fp=fopen("./0.bin","rb"); fseek(fp,0,SEEK_END); int dat_size = ftell(fp)/sizeof(short); fseek(fp,0,SEEK_SET); unsigned short *dat; dat = (unsigned short *)malloc(dat_size*sizeof(short)); fread(dat,sizeof(short),dat_size,fp); for(int idy = 0; idy<3; idy++){ for(int idx = 0; idx<3; idx++){ printf("%d ",dat[idy*3+idx]); } printf("\n"); } return 0; }
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*/ WPACKET ; typedef int /*<<< orphan*/ BIGNUM ; /* Variables and functions */ int BN_bn2binpad (int /*<<< orphan*/ const*,unsigned char*,int) ; scalar_t__ BN_is_negative (int /*<<< orphan*/ const*) ; int BN_num_bits (int /*<<< orphan*/ const*) ; int /*<<< orphan*/ ID_INTEGER ; int /*<<< orphan*/ WPACKET_allocate_bytes (int /*<<< orphan*/ *,size_t,unsigned char**) ; int /*<<< orphan*/ WPACKET_close (int /*<<< orphan*/ *) ; int /*<<< orphan*/ WPACKET_put_bytes_u8 (int /*<<< orphan*/ *,int /*<<< orphan*/ ) ; int /*<<< orphan*/ WPACKET_start_sub_packet (int /*<<< orphan*/ *) ; int /*<<< orphan*/ encode_der_length (int /*<<< orphan*/ *,size_t) ; int encode_der_integer(WPACKET *pkt, const BIGNUM *n) { unsigned char *bnbytes; size_t cont_len; if (BN_is_negative(n)) return 0; /* * Calculate the ASN.1 INTEGER DER content length for n. * This is the number of whole bytes required to represent n (i.e. rounded * down), plus one. * If n is zero then the content is a single zero byte (length = 1). * If the number of bits of n is a multiple of 8 then an extra zero padding * byte is included to ensure that the value is still treated as positive * in the INTEGER two's complement representation. */ cont_len = BN_num_bits(n) / 8 + 1; if (!WPACKET_start_sub_packet(pkt) || !WPACKET_put_bytes_u8(pkt, ID_INTEGER) || !encode_der_length(pkt, cont_len) || !WPACKET_allocate_bytes(pkt, cont_len, &bnbytes) || !WPACKET_close(pkt)) return 0; if (bnbytes != NULL && BN_bn2binpad(n, bnbytes, (int)cont_len) != (int)cont_len) return 0; return 1; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <assert.h> #include <syslog.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/sem.h> int ReservarMemoriaComp(int n); void* MapearMemoriaComp(int n); int CrearSemaforos(int n, short* vals); void BorrarSemaforos(int id); void BloquearSemaforo(int id, int i); void DesbloquearSemaforo(int id, int i); void entraMujer(); void saleMujer(); void entraHombre(); void saleHombre(); typedef struct{ char buf[50]; int sema; int limite; int usando; enum { usandoH, usandoM, usandoVacio }cartel; enum { colaH, colaM, colaVacio }cola; } variable; enum { SEM_USERP_1, SEM_USERH_2, SEM_USERM_3 }; union semun { int val; struct semid_ds* buf; unsigned short* array; struct seminfo* __buf; }; void entraMujer(){ sleep(1); printf("Entrando Mujer al SSHH...\n"); } void saleMujer(){ printf("Saliendo Mujer del SSHH...\n"); } void entraHombre(){ sleep(1); printf("Entrando Hombre al SSHH...\n"); } void saleHombre(){ printf("Saliendo Hombre del SSHH...\n"); } int ReservarMemoriaComp(int n) { return shmget(IPC_PRIVATE, n*sizeof(variable), IPC_CREAT | SHM_R | SHM_W); } void* MapearMemoriaComp(int id) { void* addr; addr = shmat(id, NULL, 0); shmctl(id, IPC_RMID, NULL); return addr; } int CrearSemaforos(int n, short* vals) { union semun arg; int id; id=semget(IPC_PRIVATE, n, SHM_R | SHM_W); arg.array=vals; semctl(id, 0, SETALL, arg); return id; } void BorrarSemaforos(int id) { if(semctl(id, 0, IPC_RMID, NULL)==-1) { perror("Error liberando semáforo!"); exit(EXIT_FAILURE); } } void BloquearSemaforo(int id, int i) { struct sembuf sb; sb.sem_num = i; sb.sem_op=-1; sb.sem_flg=SEM_UNDO; semop(id,&sb,1); } void DesbloquearSemaforo(int id, int i) { struct sembuf sb; sb.sem_num = i; sb.sem_op = 1; sb.sem_flg = SEM_UNDO; semop(id, &sb, 1); } int main(int argc, char* argv[]) { variable *var; int idShMem; int idSem; short vals[3]; int miSem; int tuSem; int suSem; if(argc<2) { puts("Bienvenido a Proyecto Final!"); idShMem = ReservarMemoriaComp(1); var = (variable*) MapearMemoriaComp(idShMem); vals[SEM_USERP_1]=0; vals[SEM_USERH_2]=0; vals[SEM_USERM_3]=0; idSem=CrearSemaforos(3,vals); var->sema = idSem; var->limite = 2; var->cartel = usandoVacio; var->usando = 0; miSem = SEM_USERP_1; tuSem = SEM_USERH_2; suSem = SEM_USERM_3; printf("Proceso Principal respeta el orden de la cola. El id de la memoria compartida es: %d\n",idShMem); char colaSH[] = {"MMMHMMHM"}; int i; for (i = 0; i < sizeof(colaSH); i++) printf("%c ", colaSH[i]); printf("=> "); printf("\n"); fflush(stdout); printf("Limite del SSHH : %i\n",var->limite ); if(var->cartel == 2) printf("Estado del cartel : vacio\n"); printf("Esperando en cola al proceso H de control de Hombres...\n"); BloquearSemaforo(idSem, miSem); printf("Esperando en cola al proceso M de control de Mujeres...\n"); BloquearSemaforo(idSem, miSem); printf("Semaforos sincronizados...\n\n"); for(i = sizeof(colaSH); i >=0 ; i--) { if(colaSH[i]=='H'){ DesbloquearSemaforo(idSem,tuSem); entraHombre(); saleHombre(); } if(colaSH[i]=='M'){ DesbloquearSemaforo(idSem,suSem); entraMujer(); saleMujer(); } } printf("Cola vacia... Fin del proceso...\n"); } else { if(strcmp("H", argv[2])==0){ idShMem = atoi(argv[1]); var = (variable *) MapearMemoriaComp(idShMem); idSem = var->sema; miSem = SEM_USERH_2; tuSem = SEM_USERP_1; puts("Eres el proceso H. Avisando al proceso Principal..."); DesbloquearSemaforo(idSem, tuSem); for (;;){ BloquearSemaforo(idSem, miSem); entraHombre(); saleHombre(); DesbloquearSemaforo(idSem,tuSem); } } if(strcmp("M", argv[2])==0){ idShMem = atoi(argv[1]); var = (variable *) MapearMemoriaComp(idShMem); idSem = var->sema; miSem = SEM_USERM_3; tuSem = SEM_USERP_1; puts("Eres el proceso M. Avisando al proceso Principal..."); DesbloquearSemaforo(idSem, tuSem); for (;;){ BloquearSemaforo(idSem, miSem); entraMujer(); saleMujer(); DesbloquearSemaforo(idSem,tuSem); } } } /* if(miSem == SEM_USERP_1) BorrarSemaforos(idSem); */ }
C
#include "isr.h" /** init_isr * Initialize the exception interrupts */ void init_isr() { void *isrs[ISR_NUM] = { &isr0, &isr1, &isr2, &isr3, &isr4, &isr5, &isr6, &isr7, &isr8, &isr9, &isr10, &isr11, &isr12, &isr13, &isr14, &isr15, &isr16, &isr17, &isr18, &isr19, &isr20, &isr21, &isr22, &isr23, &isr24, &isr25, &isr26, &isr27, &isr29, &isr30, &isr31 }; for (int32_t i = 0; i < ISR_NUM; i++) set_idt_gate(i, (uint32_t)isrs[i], 0x08, 0x8E); global_log(INFO, "Initialized Exception Interrupts"); } /** interrupt_handler * 'catches' all the interrupt and handle them. */ void isr_handler(regs_t *regs) { if (regs->interrupt_num < ISR_NUM) { int8_t int_num[3] = { 0 }; itoa(regs->interrupt_num, int_num, 10); print(int_num); while(1); } }
C
/* * vasprintf.h * * Created on: 9 May 2017 * Author: egriffiths */ #ifndef LIBLIMESUITE_SRCMW_VASPRINTF_H_ #define LIBLIMESUITE_SRCMW_VASPRINTF_H_ #define _GNU_SOURCE #define __CRT__NO_INLINE #include <stdio.h> #include <stdlib.h> #include <stdarg.h> int my_vasprintf(char ** __restrict__ ret, const char * __restrict__ format, va_list ap) { int len; /* Get Length */ len = _vsnprintf(NULL,0,format,ap); if (len < 0) return -1; /* +1 for \0 terminator. */ *ret = (char *) malloc(len + 1); /* Check malloc fail*/ if (!*ret) return -1; /* Write String */ _vsnprintf(*ret,len+1,format,ap); /* Terminate explicitly */ (*ret)[len] = '\0'; return len; } #endif /* LIBLIMESUITE_SRCMW_VASPRINTF_H_ */
C
/* Minimum for spectrum chi2. Each phase needs a minimum to include a total systematic uncertainty for flux measurement. The best fit point is sin_2_theta = 0.310, ms12 = 4.8e-5. Weiran, Mar. 27, 2018. */ #include "../chi2SK.h" #include "TH2D.h" #include <iostream> #include "TMinuit.h" #include <sstream> #include <fstream> #include <string> #include <iomanip> #include "TMath.h" #include "TFile.h" using namespace std; chi2SK chi; double sin_2_theta = 0.310, ms = 4.8e-5; void fcn(int &npar, double* gin, double &f, double* par, int iflag); int main() { chi.SetupParameter(sin_2_theta, ms); TMinuit minuit(2); int ierflg; minuit.mnparm(0,"B8flux",5.25e6,0.2e6,0,0,ierflg); minuit.mnparm(1,"hepflux",8e3, 16e3, 0,8e4, ierflg); minuit.SetFCN(fcn); minuit.SetErrorDef(1); double arglist[10]; arglist[0] = 1e5; minuit.mnexcm("MIGRAD",arglist,0,ierflg); double chi2 = 0; double edm, errdef; int nvpar, nparx, icstat; minuit.mnstat(chi2, edm, errdef, nvpar, nparx, icstat); cout << "Chi2: " << chi2 << endl; double B8flux, B8err, hepflux, heperr; minuit.GetParameter(0,B8flux, B8err); minuit.GetParameter(1,hepflux, heperr); double chi2spec = chi2 - pow((B8flux-5.25e6)/0.2e6,2) - pow((hepflux-8e3)/16e3,2); cout << "Chi2 without constraint: " << chi2spec << endl; return 0; } void fcn(int &npar, double* gin, double &f, double* par, int iflag) { double chi2 = 0; chi2 += chi.chi2spec(par[0], par[1]); chi2 += pow((par[0]-5.25e6)/0.2e6,2); chi2 += pow((par[1]-8e3)/16e3,2); f = chi2; }
C
/** * @file hds_error.h * @brief This file defines error codes which will be used throughout hds. * @author Tej */ #ifndef HDS_ERROR_H_ #define HDS_ERROR_H_ #ifndef HDS_DTYPES_H_ #include "hds_dtypes.h" #endif /** * @enum error_codes_t * @brief Defines error codes */ typedef enum { HDS_ERR_HDS_STATE_INIT = 2, /**< Error in initializing hds_state */ HDS_ERR_NO_CONFIG_FILE, /**< Configuration file is missing */ HDS_ERR_CONFIG_ABORT, /**< Fatal error in accessing configuration file */ HDS_ERR_INIT_UI , /**< Error initializing UI */ HDS_ERR_WINDOW_SIZE_TOO_SHORT, /**< UI error: window size specified is too short */ HDS_ERR_NO_COLOR, /**< UI Error: curses does not have support for colors */ HDS_ERR_COLOR_INIT_FAILED,/**< UI Error: Failed to activate color mode*/ HDS_ERR_CDK_CONSOLE_DRAW,/**< Error drawing console window */ HDS_ERR_WINDOW_CONFIG_MISMATCH,/**< UI Error: config mismatch in specified windows's sizes */ HDS_ERR_DRAW_WINDOWS,/**< Error in drawing windows*/ HDS_ERR_THREAD_INIT, /**< Error in thread creation*/ HDS_ERR_TIME_READ, HDS_ERR_FILE_IO, HDS_ERR_NO_MEM, HDS_ERR_MEM_FAULT, HDS_ERR_NO_SUCH_ELEMENT, HDS_ERR_INVALID_PROCESS, HDS_ERR_NO_RESOURCE, HDS_ERR_GENERIC /** Generic error: not sure what it is, but it's fishy anyway*/ } error_codes_t; /** * @enum log_level_t * @brief Defines logging levels. */ typedef enum { LOG_DEBUG, /**< The message is for debugging purposes. */ LOG_WARN, /**< The message is a warning */ LOG_ERROR /**< The message is an error */ } log_level_t; #endif /* HDS_ERROR_H_ */
C
#include <assert.h> #include <getopt.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <db/common/dberror.h> #include <db/common/try.h> #include <db/server/server.h> #define PORT 5000 #define BACKLOG 16 #define NTHREADS 16 #define DBDIR "db" struct server_options server_options = { .sopt_port = PORT, .sopt_backlog = BACKLOG, .sopt_nthreads = NTHREADS, .sopt_dbdir = DBDIR, }; const char *short_options = "h"; const struct option long_options[] = { {"help", no_argument, NULL, 'h'}, {"port", required_argument, &server_options.sopt_port, 0}, {"backlog", required_argument, &server_options.sopt_backlog, 0}, {"nthreads", required_argument, &server_options.sopt_nthreads, 0}, {"dbdir", required_argument, NULL, 0}, {NULL, 0, NULL, 0} }; static int parse_options(int argc, char **argv) { while (1) { int option_index; int c = getopt_long(argc, argv, short_options, long_options, &option_index); if (c == -1) { break; } switch (c) { case 0: if (optarg) { if (strcmp(long_options[option_index].name, "dbdir") == 0) { strcpy(server_options.sopt_dbdir, optarg); } else { *(long_options[option_index].flag) = atoi(optarg); } } break; case 'h': printf("Usage: %s\n", argv[0]); printf("--help -h\n"); printf("--port P [default=%d]\n", PORT); printf("--backlog B [default=%d]\n", BACKLOG); printf("--nthreads T [default=%d]\n", NTHREADS); printf("--dbdir dir [default=%s]\n", DBDIR); return 1; } } printf("port: %d, backlog: %d, nthreads: %d, dbdir: %s\n", server_options.sopt_port, server_options.sopt_backlog, server_options.sopt_nthreads, server_options.sopt_dbdir); return 0; } int main(int argc, char **argv) { if (parse_options(argc, argv) != 0) { return 0; } int result; struct server *s; TRYNULL(result, DBENOMEM, s, server_create(&server_options), done); TRY(result, server_start(s), cleanup_server); cleanup_server: server_destroy(s); done: return result; }
C
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int i; printf("SSAAP -> Small and Simple Application Arguments Printer\n\n"); for(i = 0; i < argc; i++) { printf("%d: \"%s\"", i, argv[i]); } printf("\n\n"); printf("(c) 2013"); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "alloc.h" #include "statemachine.h" #include "literal.h" char *SVM_TypeToStr(val_t dval) { doubleunion_t val; static char tmp[64]; val.d = dval; switch (val.p.type) { case TYPE_NUMBER: return "number"; case TYPE_OBJECT: return "object"; case TYPE_UNDEFINED: return "undefined"; case TYPE_FUNCTION: return "function"; case TYPE_CDECL_FUNCTION: return "cdecl_function"; case TYPE_STRING: return "string"; case TYPE_ARRAY: return "array"; case TYPE_BYTE_ARRAY: return "byte_array"; default: sprintf(tmp, "(bad type code %d)", val.p.type); return (char*)tmp; } } void SVM_FreeObject(SVMObject *ob) { if (ob->fields) MEM_free(ob->fields); if (ob->names) MEM_free(ob->names); MEM_free(ob); } int SVM_FindField(SimpleVM *vm, val_t val, char *field) { SVMObject *ob = CAST_OBJECT(val); if (!ob) { return -1; } int i; if (!ob->names) { return -1; } for (i=0; i<ob->totfield; i++) { char *name = LT_GetStr(&vm->literals, ob->names[i]); if (!strcmp(name, field)) { return i; } } return -1; } int SVM_FindFieldI(SimpleVM *vm, val_t val, int field) { SVMObject *ob = CAST_OBJECT(val); if (!ob) { return -1; } int i; if (!ob->names) { return -1; } for (i=0; i<ob->totfield; i++) { if (ob->names[i] == field) return i; } return -1; } val_t SVM_MakeObject(SimpleVM *vm, int type) { SVMObject *ob = MEM_calloc(sizeof(*ob)); LinkNode *node = MEM_malloc(sizeof(*node)); ob->type = TYPE_OBJECT; node->value = ob; List_Append(&vm->objects, node); return SVM_Obj2Val(ob); } static void svm_obj_ensuresize(SimpleVM *vm, SVMObject *ob, int size) { if (size >= ob->size) { int newsize = (size+1)*2; int *newnames = MEM_malloc(sizeof(*newnames)*newsize); val_t *newfields = MEM_malloc(sizeof(*newfields)*newsize); if (ob->fields) { memcpy(newfields, ob->fields, sizeof(*ob->fields)*ob->size); memcpy(newnames, ob->names, sizeof(*ob->names)*ob->size); MEM_free(ob->fields); MEM_free(ob->names); } ob->size = newsize; ob->names = newnames; ob->fields = newfields; } } void SVM_SetFieldI(SimpleVM *vm, val_t dval, int name, val_t setval) { doubleunion_t val = VAL2UNION(dval); SVMObject *ob = CAST_OBJECT(val); if (!ob) { //XXX raise an error return; } if (val.p.type != TYPE_OBJECT) { fprintf(stderr, "Error: not an object!\n"); return; } int i = SVM_FindFieldI(vm, SVM_Obj2Val(ob), name); if (i < 0) { svm_obj_ensuresize(vm, ob, ob->totfield+1); ob->names[ob->totfield++] = name; i = SVM_FindFieldI(vm, SVM_Obj2Val(ob), name); } ob->fields[i] = setval; } void SVM_SetField(SimpleVM *vm, val_t dval, char *name, val_t setval) { doubleunion_t val = VAL2UNION(dval); SVMObject *ob = CAST_OBJECT(val); if (!ob) { //XXX raise an error return; } if (val.p.type != TYPE_OBJECT) { fprintf(stderr, "Error: not an object!\n"); return; } int i = SVM_FindField(vm, SVM_Obj2Val(ob), name); if (i < 0) { svm_obj_ensuresize(vm, ob, ob->totfield+1); ob->names[ob->totfield++] = LT_GetStrLit(&vm->literals, name); i = SVM_FindField(vm, SVM_Obj2Val(ob), name); } ob->fields[i] = setval; } val_t SVM_MakeNativeFunc(SimpleVM *vm, c_callback func) { doubleunion_t val; val.p.type = TYPE_CDECL_FUNCTION; val.p.ptr = (uintptr_t)func; return val.d; } val_t SVM_GetField(SimpleVM *vm, val_t val, char *name) { SVMObject *ob = CAST_OBJECT(val); if (!val) { return JS_UNDEFINED; //XXX raise error. . .handle primitive types? auto-boxing? or not? } int i = SVM_FindField(vm, SVM_Obj2Val(ob), name); if (i >= 0) { return ob->fields[i]; } return JS_UNDEFINED; } val_t SVM_GetFieldI(SimpleVM *vm, val_t val, int name) { SVMObject *ob = CAST_OBJECT(val); if (!val) { return JS_UNDEFINED; //XXX raise error. . .handle primitive types? auto-boxing? or not? } int i = SVM_FindFieldI(vm, SVM_Obj2Val(ob), name); if (i >= 0) { return ob->fields[i]; } return JS_UNDEFINED; } val_t SVM_SimpleObjCopy(SimpleVM *vm, val_t scope) { SVMObject *ob = SVM_Val2Obj(scope); val_t scope2 = SVM_MakeObject(vm, TYPE_OBJECT); int i; for (i=0; i<ob->totfield; i++) { SVM_SetFieldI(vm, scope2, ob->names[i], ob->fields[i]); } return scope2; }
C
#include<stdio.h> #include<conio.h> void main() { int n1,n2,minmul; printf("enter numbers"); scanf("%d %d",&n1,&n2); minmul=(n1>n2)?n1:n2; while(1) { if(minmul%n1==0 && minmul%n2==0) { printf(%d %d %d",n1,n2,minmul); break; } ++minmul; } getch(); }
C
#ifndef _PUMPS_H_ #define _PUMPS_H_ #include <Arduino.h> #include "timer.h" typedef enum pumps_state { PUMP_IDLE, PUMP_ACTIVE, PUMP_STOPPED } pumps_state; typedef struct pumps { int pin; unsigned long timeout_time; pumps_state state; timer pump_timer; } pumps; /* ---------------------------- PROTOTYPES ----------------------------- */ pumps new_pump ( int pin ); void start_pump ( pumps *pump, unsigned long ms); void stop_pump ( pumps *pump ); void reset_pump ( pumps *pump ); void stop_pump_after_timeout ( pumps *pump, unsigned long ms ); /* --------------------------- DEFINITIONS ----------------------------- */ pumps new_pump (int pin) { pumps p; p.pin = pin; p.state = PUMP_IDLE; p.timeout_time = 0; p.pump_timer = new_timer(); digitalWrite(pin, LOW); return p; } void start_pump (pumps *pump, unsigned long ms) { switch (pump->state) { case PUMP_IDLE: case PUMP_STOPPED: pump->state = PUMP_ACTIVE; pump->timeout_time = ms; start_timer(&(pump->pump_timer)); digitalWrite(pump->pin, HIGH); break; case PUMP_ACTIVE: break; default: // TODO: ... break; } } void stop_pump (pumps *pump) { switch (pump->state) { case PUMP_IDLE: case PUMP_STOPPED: break; case PUMP_ACTIVE: pump->state = PUMP_STOPPED; stop_timer(&(pump->pump_timer)); digitalWrite(pump->pin, LOW); break; default: // TODO: ... break; } } void reset_pump (pumps *pump) { switch (pump->state) { case PUMP_IDLE: break; case PUMP_STOPPED: case PUMP_ACTIVE: pump->state = PUMP_IDLE; pump->timeout_time = 0; reset_timer(&(pump->pump_timer)); digitalWrite(pump->pin, LOW); break; default: // TODO: ... break; } } void stop_pump_after_timeout ( pumps *pump ) { if (pump->state == PUMP_ACTIVE) { if (wait(&(pump->pump_timer), pump->timeout_time)) { stop_pump(pump); } } } #endif
C
#include <stdio.h> int main() { int i; double now, sum = 0; for(i = 0; i < 12; ++i) { scanf("%lf", &now); sum += now; } printf("$%.2lf\n", sum/12); return 0; }
C
int main(){ int n,m[1000],i; scanf("%d",&n); char a[1000][256]; for(i=0;i<n;i++){ scanf("%s",a[i]); m[i]=strlen(a[i]);} for(i=0;i<n;i++) {for(int j=0;j<m[i];j++){ if(a[i][j]=='T') a[i][j]='A'; else if(a[i][j]=='A') a[i][j]='T'; else if(a[i][j]=='C') a[i][j]='G'; else if(a[i][j]=='G') a[i][j]='C';} printf("%s\n",a[i]);} return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> // жǷཻԼ㽻: list1:1 2 3 4 5 6 7 8 9, list2:12 13ӵlist1һ // 1. һwhileһforȾཻ //2.ijȣd=L1-L2, dȣȻͬʱֵͬ¼λã˵ཻ typedef struct student{ int num; struct student* pnext; }stud,*pstud; void list_tail_insert(pstud*,pstud*,int); void list_print(pstud); void list_count_node(pstud phead,int* ); void list_judge_intersect(pstud,pstud); void main(int argc,char* argv[]) { pstud pcur1,phead1,ptail1,phead2,ptail2; int i,k; phead1 = NULL; ptail1 = NULL; phead2 = NULL; ptail2 = NULL; while(scanf("%d",&i) != EOF) { list_tail_insert(&phead1,&ptail1,i); } printf("the first list is:\n"); list_print(phead1); while(scanf("%d",&i) != EOF) { list_tail_insert(&phead2,&ptail2,i); } // һӵһ pcur1=phead1; pcur1=pcur1->pnext->pnext; ptail2->pnext=pcur1; ptail2=ptail1; printf("the second list is:\n"); list_print(phead2); list_judge_intersect(phead1,phead2); } // β巨 void list_tail_insert(pstud* phead,pstud* ptail,int num) { pstud pcur; pcur=(pstud)malloc(sizeof(stud)); pcur->num= num; pcur->pnext=NULL; if(*ptail==NULL) //˵ԭǿսڵ㣬Ľڵǵһڵ { *phead=pcur; *ptail=pcur; }else{ (*ptail)->pnext=pcur; // ԭβڵpnextָڵIJĽڵ (*ptail)=pcur;// ǰڵβ } } // ӡ void list_print(pstud phead) { pstud pcur; pcur= phead; while(pcur!=NULL) { printf("%3d",pcur->num); pcur=pcur->pnext; } printf("\n"); } // жٸڵ void list_count_node(pstud phead,int* k) { pstud pcur; pcur=phead; (*k)=0; while(pcur != NULL) { pcur=pcur->pnext; (*k)++; } } //жǷཻཻڵ void list_judge_intersect(pstud phead1,pstud phead2) { int i,d,L1,L2; pstud pcur1,pcur2; pcur1=phead1; pcur2=phead2; list_count_node(phead1,&L1); list_count_node(phead2,&L2); d=abs(L1-L2); if(L1>L2) { for(i=0;i<d;i++) { pcur1=pcur1->pnext; } }else { for(i=0;i<d;i++) { pcur2=pcur2->pnext; } } while(pcur1->pnext != NULL) { pcur1=pcur1->pnext; pcur2=pcur2->pnext; if(pcur1==pcur2) { printf("the two lists intersect!\n"); printf("the intersection is:%d\n",pcur1->num); break; } } }
C
#include <stdio.h> #include <fcntl.h> #include "get_next_line.h" int main(int argc, char **argv) { int fd; int ret; char *line; size_t i; if (argc <= 1) fd = 0; else fd = open(argv[1], O_RDONLY); i = 0; while ((ret = get_next_line(fd, &line)) > 0) { printf("|%s|\n", line); free(line); i++; } printf("last ret %d\n", ret); close(fd); return 0; }
C
#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int i,diem[20],n; printf("nhap so mon(ko qua 20):\n"); scanf("%d",&n); for(i=0;i<n;i++){ printf("diem mon thu %d:",i+1); scanf("%d",&diem[i]); } xh(diem,n); return 0; } int xh(int diem[],int n){ int i; float tb,sum=0; for(i=0;i<n;i++){ sum+= diem[i]; } tb=sum/n; printf("Diem trung binh la:%.2f",tb); if(tb<5){ printf("\nHoc sinh:Yeu"); } if(tb>=5 && tb<=7){ printf("\nHoc sinh: Kha"); } if(tb>7 && tb<10){ printf("\nhoc sinh:Gioi"); } }
C
#include <stdio.h> #define SIZE 7 int graph[SIZE][SIZE] = { {999, 6, 5, 5, 999, 999, 999}, {999, 999, 999, 999, -1, 999, 999}, {999, -2, 999, 999, 1, 999, 999}, {999, 999, -2, 999, 999, -1, 999}, {999, 999, 999, 999, 999, 999, 3}, {999, 999, 999, 999, 999, 999, 3}, {999, 999, 999, 999, 999, 999, 999} }; void BF(int n, int v, int finish); void printPath(int path[], int start, int finish); int main(){ int start,finish; printf("Put start: "); scanf("%d", &start); printf("Put finish: "); scanf("%d", &finish); BF(SIZE, start, finish); } void BF(int n, int v, int finish){ int i, j, u, k, dis[SIZE], path[SIZE], flag; for(i=0; i<n; i++){ dis[i] = graph[v][i]; path[i] = v; } for(i=2; i<=SIZE-1; i++){ for(u=0; u<SIZE; u++){ flag = -1; if(u == v) continue; else{ for(j=0; j<SIZE; j++){ if(graph[j][u] != 999) flag = 1; } } if(flag == 1){ for(k=0; k<SIZE; k++){ if(dis[u] > dis[k] + graph[k][u] && k != u){ dis[u] = dis[k] + graph[k][u]; path[u] = k; } } } } } printf("cost: %d", dis[finish]); printf("\n"); printPath(path, v, finish); } void printPath(int path[], int start, int finish){ int temp[SIZE], count = 0 ,i; while(finish != start){ temp[count++] = finish; finish = path[finish]; } temp[count] = start; for(i=count; i>0; i--){ printf("%d -> ", temp[i]); } printf("%d", temp[0]); printf("\n"); }
C
#include "set.h" #include "uarray.h" #include <stdio.h> #include <stdlib.h> #include <stdlib.h> //#include "bitpack.h" #include "ummem.c" #include "umop.c" #include "assert.h" void check_newfree(); void check_length(); void check_storeload(); int main(int argc, char* argv[]){ /*if(argc != 2){ fprintf(stderr, "Not correct number of files\n"); exit(1); } */ FILE * input = fopen(argv[1], "r"); UM_run(input); (void) argc; (void) argv; return 0; } void check_newfree(){ create_segment(1, 0x1); uint64_t * segment = UArray_at(seg_array, 1); assert(segment != NULL); free_segment(0x1); } void check_length(){ create_segment(5, 0x1); int length = *(int*)UArray_at(Seg_Length_Array, 1); printf("%d\n", length); assert(length == 5); } void check_storeload(){ create_segment(1, 0x1); create_segment(5, 0x2); create_segment(10, 0x3); store_word(0x1, 0, 0x1); store_word(0x2, 4, 0x10); store_word(0x3, 4, 0x100); uint64_t a = load_word(1, 0); uint64_t b = load_word(2, 4); uint64_t c = load_word(3, 4); assert(a == 0x1 && b == 0x10 && c == 0x100); }
C
#include "svdpi.h" #include "veriuser.h" /* * 2-state bit selects */ void bitsel_2state_test(svBitVecVal *val, int bi) { svBit sb; sb = svGetBitselBit(val, bi); io_printf("2-state val[%d]=%d\n", bi, sb); /* now zero the bit */ svPutBitselBit(val, bi, 0); /* one some bits */ svPutBitselBit(val, 20, 1); svPutBitselBit(val, 35, 1); sb = svGetBitselBit(val, bi); io_printf("2-state val[%d]=%d\n", bi, sb); } /* * 4-state bit selects */ void bitsel_4state_test(svLogicVecVal *val, int bi) { svLogic slb; slb = svGetBitselLogic(val, bi); io_printf("4-state val[%d]=%d\n", bi, slb); /* now zero the bit */ svPutBitselLogic(val, bi, 0); /* one some bits */ svPutBitselLogic(val, 20, 1); svPutBitselLogic(val, 35, 1); slb = svGetBitselLogic(val, bi); io_printf("4-state val[%d]=%d\n", bi, slb); } /* * 2-state part selects */ void partsel_2state_test(svBitVecVal *val, svBitVecVal *in) { svBitVecVal val2; svGetPartselBit(val, in, 0, 16); val2 = 0xffffffff; svPutPartselBit(val, val2, 20, 8); } /* * 4-state part selects */ void partsel_4state_test(svLogicVecVal *val, svLogicVecVal *in) { svLogicVecVal val2; svGetPartselLogic(val, in, 0, 16); val2.aval = 0xffffffff; val2.bval = 0x0; svPutPartselLogic(val, val2, 20, 8); }
C
#include <stdio.h> #include <string.h> struct student { char name[15]; int age; float mark; }; void read_data(struct student arr[], int n); void print_data(struct student arr[], int n); int read_data_w_ptr(struct student* stru_ptr); int main(void) { struct student class[10]; printf("Welcome!!\n"); for (int i = 0; i < 5; i++) { read_data(class, i); // read_data_w_ptr(&class[i]) == read_data_w_ptr(class + i) } for (int j = 0; j < 5; j++) { print_data(class, j); } } void read_data(struct student arr[], int n) { printf("Record: %d\n", n); printf("\tName: "); fgets(arr[n].name, 15, stdin); arr[n].name[strlen(arr[n].name) - 1] = '\0'; printf("\tAge: "); scanf("%d", &arr[n].age); printf("\tMark:"); scanf("%f", &arr[n].mark); getchar(); } void print_data(struct student arr[], int n) { printf("Name: %s\n", arr[n].name); printf("Age: %d\n", arr[n].age); printf("Mark: %g\n", arr[n].mark); } int read_data_w_ptr(struct student* stru_ptr) { printf("Name: "); gets(stru_ptr->name); printf("Age: "); scanf("%d", &stru_ptr->age); printf("Mark: "); scanf("%f", &stru_ptr->mark); getchar(); //Clean the buffer! return 1; //Used for checking! }
C
/* * ===================================================================================== * * Filename: ex6.c * * Description: * * Version: 1.0 * Created: 06/03/2013 10:25:11 AM * Revision: none * Compiler: gcc * * Author: Eli Gundry * * ===================================================================================== */ #include <stdio.h> int main(int argc, const char *argv[]) { int distance = 100; float power = 2.345f; double super_power = 56789.4532; char initial = 'D'; char first_name[] = "Eli"; char last_name[] = "Gundry"; printf("You are %d miles away!\n", distance); printf("You have %f levels of power!\n", power); printf("You have %f awsome super powers!\n", super_power); printf("I have the initial %c!\n", initial); printf("I have the first name of %s!\n", first_name); printf("I am of the house %s!\n", last_name); printf("My whole name is %s %c. %s!\n", first_name, initial, last_name); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <pthread.h> #include "../src/z_circular_buffer/z_circular_buffer.h" #define LOOP_COUNT ( 4096 << 10 ) #define PRODUCER_THREAD_NUM 1 #define CONSUMER_THREAD_NUM 1 #define PERF_TRHEAD_NUM 1 #define TOTAL_THREAD_NUM ( PRODUCER_THREAD_NUM + \ CONSUMER_THREAD_NUM + \ PERF_TRHEAD_NUM) char *produce_data = "Produce,dataextrabytes"; char consume_buffer[20]; struct thread_arg { int i; struct z_cirbuf *cb; }; void * produce_thread_fn(void *arg) { printf("Produce thread created\n"); int i = ((struct thread_arg *)arg)->i; uint32_t size = strlen(produce_data); struct z_cirbuf *cb = ((struct thread_arg *)arg)->cb; while(1) { z_cirbuf_produce(cb, (void *)produce_data, size); //i--; } return NULL; } void * consume_thread_fn(void *arg) { printf("Consume thread created\n"); int i = ((struct thread_arg *)arg)->i; uint32_t size = strlen(produce_data); struct z_cirbuf *cb = ((struct thread_arg *)arg)->cb; while(1) { z_cirbuf_consume(cb, (void *)consume_buffer, size); //i--; } return NULL; } void * perf_thread_fn(void *arg) { printf("Perf thread created\n"); uint64_t old_write = 0; uint64_t new_write = 0; uint64_t old_read = 0; uint64_t new_read = 0; struct z_cirbuf *cb = (struct z_cirbuf *)arg; while(1) { pthread_spin_lock(&cb->lock); new_write = cb->stat.w_bytes; new_read = cb->stat.r_bytes; pthread_spin_unlock(&cb->lock); printf("write rate: %d bytes/sec\n", (new_write - old_write)); printf("read rate: %d bytes/sec\n", (new_read - old_read)); old_write = new_write; old_read = new_read; sleep(1); } return NULL; } int main() { pthread_t pids[TOTAL_THREAD_NUM]; struct z_cirbuf *cb = z_cirbuf_create(4096); struct thread_arg prod_arg = {.i = LOOP_COUNT, .cb = cb}; struct thread_arg cons_arg = {.i = LOOP_COUNT, .cb = cb}; if (cb == NULL) { fprintf(stderr, "circular buffer create failed\n"); exit(0); } int i; for(i = 0; i < PRODUCER_THREAD_NUM; i++) { pthread_create(&pids[i], NULL, produce_thread_fn, (void *)&prod_arg); } for(i = 0; i < CONSUMER_THREAD_NUM; i++) { pthread_create(&pids[PRODUCER_THREAD_NUM + i], NULL, consume_thread_fn, (void *)&cons_arg); } pthread_create(&pids[PRODUCER_THREAD_NUM + CONSUMER_THREAD_NUM], NULL, perf_thread_fn, (void *)cb); for(i = 0; i < TOTAL_THREAD_NUM; i++) { pthread_join(pids[i], NULL); } printf("Text: %s\n", consume_buffer); printf("Total write bytes: %ld\n", cb->stat.w_bytes); printf("Total read bytes: %ld\n", cb->stat.r_bytes); printf("Total times of full: %ld\n", cb->stat.nr_full); printf("Total times of empty: %ld\n", cb->stat.nr_empty); z_cirbuf_destroy(cb); return 0; }
C
#include <stdio.h> #include <string.h> void main(){ int a[3]; int x; a = [1 || 0,1 && 0,!0]; for(x=2;x>-1;x--){ printf("%d \t",a[x]); } return; }
C
#include "/players/stark/defs.h" inherit "/room/room.c"; int snake; reset(arg) { snake = 0; if (arg) return; set_light(1); short_desc="A dimly lit forest"; long_desc= " Light pours down from the heavens above. A slit in the green \n"+ "fabric of trees flows above the stream. You stand on a log that \n"+ "connects two sides of a stream. A worn path leads southward but is \n"+ "blocked by vines to the north. The stream below pushes east, fighting \n"+ "and grinding away at the pebbles and sand.\n"; items=({ "water", "Rushing water creates a stream below", "vines", "Vines climb up the trees and droop down from their branches", "light", "Light and sky mirror the stream below", "sky", "Light and sky mirror the stream below", "slit", "A rip in the ever present forest ceiling", "fabric", "Ever present and light oppressive; the green fabric of the tree branches", "stream", "Water rushes down just below the log, you could 'hop' down into it", "ceiling", "The branches of the trees saturate the sky above", "forest", "A forest of thriving trees and other vegetation", "trees", "Strong trees rise high to a ceiling of branches", "vegetation", "Bushes, ferns and grasses carpet the floor", "vines", "Vines climb up the trees and droop down from their branches", "carpet", "The undergrowth is so lush that it creates a carpet of green", "path", "The log connects to a path north and south" }); dest_dir=({ "/players/stark/forest/forest2","south" }); } init() { ::init(); add_action("search","search"); add_action("hop","hop"); } search(str) { if(str == "vines" || str == "vine"){ if(snake){ write("You search the vines and and find nothing.\n"); return 1;} write("You search the vines and find a snake!\n"); move_object(clone_object("/players/stark/forest/mon/snake3.c"),this_object()); snake = 1; return 1;} write("You search around and find you can 'hop' down to the stream below.\n"); return 1; } hop(str) { write("You hop down to the stream below.\n"); this_player()->move_player("into the forest#/players/stark/forest/forest4"); return 1; }
C
#include "FIT_RANGE.h" #include "stdio.h" #ifndef XES #ifdef GSM #include "../../interface/intergsm.h" #else #include "../../interface/interface.h" /* C++ class header */ #endif #endif #ifndef _DATATYPE_H #define _DATATYPE_H #include "../../include/datatype.h" #endif /*--------------------------------------------- * Describe Procedure & Function * This is FIT_RANGE_data.c *---------------------------------------------*/ StrlSampleIndex ADD_INDEX_SIZE(char *str) { VrSampleRange data; /*char indx[80]="0";*/ sscanf(str, "%lld %lu",&data.index, &data.size); data.index=data.index + data.size; /*sprintf(indx, "%lld",data.index);*/ return lld2str(data.index); } void ADD_INDEX_SIZENEW(StrlSampleIndex indx, char *str) { VrSampleRange data; sscanf(str, "%lld %lu",&data.index, &data.size); data.index=data.index + data.size; sprintf(&indx, "%lld",data.index); #ifdef DEBUG printf("ADD_INDEX_SIZENEW => [%s] %s\n",str,&indx); #endif } /* void ADD_INDEX_SIZEVR(VrSampleIndex* indx, VrSampleRange str) { *indx=str.index+str.size; } */ int GET_SIZE(StrlSampleRange str) { int data; sscanf(str, "%d %d",&data, &data); return data; } /* int GET_SIZEVR(VrSampleRange str) { return str.size; } */ StrlSampleIndex GETINDEX(char *str) { VrSampleRange data; /*char indx[80]="0";*/ sscanf(str, "%lld %lu",&data.index, &data.size); /*sprintf(indx, "%lld",data.index);*/ return lld2str(data.index); } void GETINDEXNEW(StrlSampleIndex indx, char *str) { VrSampleRange data; sscanf(str, "%lld %lu",&data.index, &data.size); sprintf(&indx, "%lld",data.index); } /* void GETINDEXVR(VrSampleIndex* indx, VrSampleRange str) { *indx=str.index; } */ int SUBTRACT_A_B(StrlSampleIndex a,StrlSampleIndex b) { long long x,y; x=str2lld(a); y=str2lld(b); #ifdef DEBUG printf("[1]SUBTRACT_A_B => %s - %s\n",a,b); #endif return (int) x-y; } /* int SUBTRACT_A_BVR(VrSampleIndex a,VrSampleIndex b) { return a-b; } */ int ROUNDOWN_SIZE(int x,UnsignedInt y) { return x=((x/y)*y); } /* int ROUNDUP_REQUESTSIZE(int x,UnsignedInt y) { return x=(((x + y - 1)/y ) * (y)); } */ StrlSampleRange SET_SAMPLERANGE(StrlSampleIndex y,int z) { VrSampleRange data; /*char str[80]="0";*/ data.index=str2lld(y); data.size=z; /*sprintf(str, "%lld %lu",data.index, data.size);*/ return SRange2str(data); } void SET_SAMPLERANGENEW(StrlSampleIndex str,StrlSampleIndex y,int z) { VrSampleRange data; data.index=str2lld(y); data.size=z; sprintf(&str, "%lld %lu",data.index, data.size); #ifdef DEBUG printf("[1]SET_SAMPLERANGENEW => %lld %lu = %s(strl)\n",y,z,&str); #endif } /* void SET_SAMPLERANGEVR(VrSampleIndex* str,VrSampleIndex y,int z) { str->index=y;str->size=z; } */ StrlSampleRange DOWNCASTS(StrlSampleRange s,char *r) { #ifndef XES /*char str[80]="0"; VrSampleRange data=InterDowncast(str2SRange(s),r); sprintf(str, "%lld %lu",data.index, data.size); #ifdef DEBUG printf("[1]DOWNCASTS =>%s: [%s]\n",r,s); #endif return str;*/ return SRange2str(InterDowncast(str2SRange(s),r)); #endif } StrlSampleRange FORECASTS(StrlSampleRange s,char *r) { #ifndef XES /* char str[80]="0"; VrSampleRange data=InterForecast(str2SRange(s),r); sprintf(str, "%lld %lu",data.index, data.size); #ifdef DEBUG printf("[1]FORECASTS =>%s: [%s]\n",r,s); #endif return str; */ return SRange2str(InterForecast(str2SRange(s),r)); #endif } void DOWNCASTSNEW(StrlSampleRange str,StrlSampleRange s,char *r) { #ifndef XES InterDowncastNew(&str,str2SRange(s),r); #endif } void FORECASTSNEW(StrlSampleRange str,StrlSampleRange s,char *r) { #ifndef XES InterForecastNew(&str,str2SRange(s),r); #endif } /* void DOWNCASTSVR(VrSampleRange* str,VrSampleRange s,char *r) { #ifndef XES InterDowncastVr(str,s,r); #endif } void FORECASTSVR(VrSampleRange* str,VrSampleRange s,char *r) { #ifndef XES InterForecastVr(str,s,r); #endif } */ /* int REAL_MARK_DATA(StrlSampleIndex p_wp,int req,int dm,StrlSampleRange range,char *r) { VrSampleIndex x=str2lld(p_wp); VrSampleRange rg=str2SRange(range); return InterStrlmarkData(x,req,dm,rg,r); } */ int REAL_FIT_RANGE(StrlSampleIndex p_wp,int req,StrlSampleRange range,char *r) { #ifndef XES VrSampleIndex x=str2lld(p_wp); VrSampleRange rg=str2SRange(range); #ifdef DEBUG printf("[1]REAL_FIT_RANGE => index %s, requestsize %d\n",p_wp,req); #endif return InterStrlFitRange(x,req,rg,r); #endif } /* int REAL_FIT_RANGEVR(VrSampleIndex p_wp,int req,VrSampleRange range,char *r) { #ifndef XES return InterStrlFitRange(p_wp,req,range,r); #endif } */ int GETMAXOUTSIZE(char *r) { #ifndef XES return InterGetMaxOutSize(r); #endif } int error_exit(int x) { fprintf(stderr,"impossible case\n"); exit(x); }
C
#include"defs.h" int isWindow (double firstPacketWindowTime, double packetWindowTime , double windowLength){ double tFinal; tFinal = firstPacketWindowTime + windowLength; if (packetWindowTime <= tFinal) return 0; else return 1; }
C
#include <stdio.h> int main() { int a; float b; char c; char d[255]; // printf("address of a: %p\n",&a); // printf("address of b: %p\n",&b); // printf("address of c: %p\n",&c); // printf("address of d: %p\n",d); //printf("Please give a character: "); //scanf("%c", &c); //printf("The character you input: %c\n",c); //printf("please give an intger:"); //scanf("%d", &a);// & means to get the ram address of a //printf("Please give a floating-point number: "); //scanf("%f", &b); // //printf("Your input integer,floating-point number, and character: %d, %f, %c\n", a,b,c); printf("Please give a string: "); //scanf("%s", &d); scanf("%[^\n]", &d);// [^] means not, so [^\n] means not "new line symbol". or read until "\n" printf("Your input string: %s\n", d); return 0; }
C
#include <stdio.h> void josephusHelper(int n); void josephus(int n, int arr[], int max); void shift(int n, int arr[], int index); int main() { int a; printf("How many soldiers are there: "); scanf("%d", &a); josephusHelper(a); return 0; } void josephusHelper(int n) { int arr[n]; for (int i = 0; i < n; i++) { arr[i] = i + 1; } josephus(n, arr, n); } void josephus(int n, int arr[], int max) { if (n == 1) { printf("Soldier %d survived. \n", arr[0]); int j = 1, k = 0; while ((j <= max) && (k < n)) { if (j == arr[k]) { printf("|"); k++; } else { printf(" "); } j++; } printf("\n"); return; } else { for (int i = 0; i < n; i++) { if (i == n - 1) { printf("Soldier %d killed soldier %d. \n", arr[i], arr[0]); shift(n--, arr, 0); } else { printf("Soldier %d killed soldier %d. \n", arr[i], arr[i + 1]); shift(n--, arr, i + 1); } int j = 1, k = 0; while ((j <= max) && (k < n)) { if (j == arr[k]) { printf("|"); k++; } else { printf(" "); } j++; } printf("\n"); } josephus(n, arr, max); } } void shift(int n, int arr[], int index) { for (int i = index; i < n - 1; i++) { arr[i] = arr[i + 1]; } }
C
#ifndef STRING_INTERNING #define STRING_INTERNING struct _string { size_t len; const char *str; }; static struct _string *table = NULL; const char *str_intern_slice(const char *str, size_t len) { struct _string *s; if (table == NULL) goto push; for (int i = 0; i < buf_len(table); i++) { s = table + i; if (s->len == len && strncmp(s->str, str, len) == 0) return s->str; } push: str = strndup(str, len); buf_push(table, ((struct _string) {len, str})); return str; } const char *str_intern(const char *str) { return str_intern_slice(str, strlen(str)); } void str_test() { const char *px, *py, *pz; char x[] = "hello"; char y[] = "hello"; char z[] = "hello!"; assert(x != y); px = str_intern(x); py = str_intern(y); assert(px == py); pz = str_intern(z); assert(pz != px); } #endif
C
/*********************************************************************************/ /* Course: Advanced Programming for Physics (2020-2021) */ /*********************************************************************************/ /* The program numerically computes the integral of the following function: */ /* */ /* f(x) = 4.0 / (1 + x*x) */ /* */ /* from 0 to 1. The value of the intergral is pi. */ /* This is the parallel implementation. */ /* */ /* Compile the code: */ /* $ gcc -Wall -Wextra -fopenmp pi_parallel.c -o pi_parallel -lm */ /* */ /* Run the code: */ /* $ time ./pi_parallel <number of OpenMP threads> */ /* */ /* Author: David Goz - [email protected] */ /* */ /* Assigned tasks: */ /* - parallelize the code targeting the for loop over the steps */ /* of the integral. Check the result, and then measure the */ /* time-to-solution (this can be done smoothly using the Unix */ /* 'time' command). Does it scale linearly with the number of */ /* OpenMP threads? Any difference in changing the scheduling */ /* policy of the for loop? Why? */ /*********************************************************************************/ #include "my_omp_header.h" /* number of steps */ unsigned long int num_steps = 1000000000; typedef double MyFloat; int main (int argc, char *argv[]) { if (argc < 2) { printf("\n\t USAGE: <executable> <number of OpenMP threads> \n\n"); return -1; } const int num_threads = atoi(argv[1]); MyFloat step = 1.0/(MyFloat) num_steps; /* accumulator. OMP initiliazes it at zero since a sum reduction will be performed */ MyFloat sum; #pragma omp parallel default(none) shared(step,sum,num_steps) num_threads(num_threads) { # pragma omp single nowait { /* get the number of active omp threads */ printf("\n\t Active OpenMP threads: %d \n", omp_get_num_threads()); } /* omp single nowait */ # pragma omp for reduction(+:sum) schedule(static) nowait for (unsigned long int i=1 ; i<=num_steps ; i++) { const MyFloat x = (i - 0.5) * step; sum += (1.0 / (1.0 + (x * x))); } /* omp for nowait */ } /* omp parallel region */ const MyFloat my_pi = (4.0 * step * sum); printf("\n\t pi with %ld steps is %lf [PI: %lf]\n\n", num_steps, my_pi, M_PI); return 0; }
C
// Exercise 3 from chapter 6 // This program receives two integers from the user and shows the result of dividing the first by the second. #include<stdio.h> int main( void ) { int num1, num2; printf( "Enter two integer numbers separated by a blank space:\n" ); scanf( "%i %i", &num1, &num2 ); if( num2 == 0 ) { printf( "Division by zero not supported.\n" ); } else { printf( "%i / %i = %.3f .\n", num1, num2, ( (double)num1 / num2 ) ); } return 0; }
C
//Функция strlen видит начало Си-строки и начинает сначала считать количество //символов (байтов, отводимых под каждый символ), этот процесс выполняется //до тех пор, пока не будет достигнут завершающий нулевой символ //#include "../libft.h" //#include "stdafx.h" //Для работы с VS12 C++11 //#include <stdio.h> //#include <cstdlib> //Для работы с функцией system("pause") int ft_strlen(char *str) { int i; i = 0; while (str[i]) ++i; return (i); } /* void main() { char buffer1[13] = "DWgaOtP12df0"; int n = ft_strlen(buffer1); printf("The number of characters is: '%d'.\n", n); //system("pause"); } */
C
#include <stdio.h> int main(void) { int ary[10] = { 31,41,59,26,53,58,97,23,84 }; printf("בւȌԁF"); for (int i = 0;i < 10;i++) { printf(" %d", ary[i]); } printf("\n"); int tmp = 0; for (int i = 0;i < 9;i++) { for (int n = 0;n < 9 - i;n++) { if (ary[n] > ary[n + 1]) { tmp = ary[n]; ary[n] = ary[n + 1]; ary[n + 1] = tmp; } } } printf("בւ̏ԁF"); for (int i = 0;i < 10;i++) { printf(" %d", ary[i]); } return 0; }
C
/* File Name: : main.c Device : PIC32MM0256GPM048 Compiler : XC32 2.05 MPLAB : MPLAB X 4.15 Created by : http://strefapic.blogspot.com */ #include <xc.h> #include "mcc_generated_files/mcc.h" #include <stdio.h> #include <stdlib.h> #include <stdint.h> /*dyrektywy do uint8_t itp*/ #include "delay.h" #define LED1_TOG PORTA ^= (1<<_PORTA_RA3_POSITION) /*zmienia stan bitu na przeciwny*/ void main(void) { /*initialize the device*/ SYSTEM_Initialize(); /*ustawia zegar i wszystkie inne duperele potrzebne do startu procka, zrobimy to w przyjazany sposb w MCC*/ /*ustawienia pinu RA3 do pracy jako wyjscie cyfrowe*/ /*odlaczenie RA3 od zegara RC mamy w pliku mcc.c sekcja dotyczaca rejestru FOSCSEL , #pragma config OSCIOFNC = OFF*/ ANSELAbits.ANSA3 = 0; /*odlaczamy pin RA3 od sekcji analogowej*/ TRISAbits.TRISA3 = 0; /*ustawiamy kierunek pinu RA3 jako wyjscie*/ /*od tego momentu RA3 jest normalnym wyjsciem cyfrowym huraaa...*/ while (1) { if(!Timer1_Programowy) { Timer1_Programowy = 10 ; /*Timer1 sprzetowy x Timer1_Programowy = 100ms x 10 = 1 s*/ LED1_TOG ; /*zmieniaj stan wyjscia na przeciwny i mrugamy sobie LED-em*/ } } }
C
#include<stdio.h> #include<conio.h> main() { int i,len,n; char a[110][110]; scanf("%d",&n); for(i=0;i<n;i++) scanf("%s",&a[i]); for(i=0;i<n;i++) { len=strlen(a[i]); if(len>10) { printf("%c%d%c",a[i][0],(len-2),a[i][len-1]); } else printf("%s",a[i]); printf("\n"); } getch(); }
C
/****************************************************************************** * Student Name : Brearne Gibson * RMIT Student ID : s3496168 * * Startup code provided by Paul Miller for use in "Programming in C", * Assignment 2, study period 2, 2020. *****************************************************************************/ #include "array_list.h" #include <assert.h> /** * create appropriate functions for managing the array list here **/ /* struct word make_word(char *word) { struct word *new; assert(word); new = malloc(sizeof(struct word)); strcpy(new->text, word); }*/
C
/*! \file main.c * * Author: Javier Montenegro (https://javiermontenegro.github.io/) * Details: program file for methods implementation. */ #include "common.h" extern void client(const char* hostname, const unsigned int port, char *username); int main(int argc, char *argv[]) { //TODO: use getopt char ipaddr[INET_ADDRSTRLEN]; unsigned int port = 0; if(argc < 3) { printf("Client usage: chatclient <desired_username> <server_ip>:<server_port>\n"); return 0; } sscanf(argv[2], "%[^:]:%u", ipaddr, &port); if(port == 0) port = DEFAULT_SERVER_PORT; client(ipaddr, port, argv[1]); }
C
/* UNIX "timer" driver for NOS, for reckoning time and delivering timer events * when NOS is hosted locally on a UNIX machine. * * Copyright 2017 Jeremy Cooper, KE6JJJ. * * Timer devices are traditionally interrupt driven in NOS. But since * this is a UNIX driver there are no interrupts to receive. Instead, we will * simulate interrupt-like behavior with a thread that sleeps until a timer * "tick" has elapsed. It will then wake up the "timer" NOS process, simulating * a PC hardware tick. * * The thread will interface with the rest of the NOS code entirely through * the "Tick" global variable and the ksignal() calls. It will treat the * "disable()" and "restore()" interrupt blocking methods as a lock * barrier. */ #include "top.h" #ifndef UNIX #error "This file should only be built on POSIX/UNIX systems." #endif #include <sys/time.h> #include <pthread.h> #include <time.h> #include <unistd.h> #include "global.h" #include "core/proc.h" #include "core/timer.h" #include "unix/timer_unix.h" #include "unix/nosunix.h" static void *timer_proc(void *dummy); /* The global timer ticking thread */ static pthread_t g_timer_thread; /* Startup time */ static struct timeval g_start_time; /* The global timer tick count */ int Tick; /* Initialize the timer tick thread */ int unix_timer_start(void) { gettimeofday(&g_start_time, NULL); return pthread_create(&g_timer_thread, NULL, timer_proc, NULL); } /* Stop timer tick thread */ int unix_timer_stop(void) { void *dummy; pthread_cancel(g_timer_thread); return pthread_join(g_timer_thread, &dummy); } int32 msclock(void) { struct timeval now; int64_t duration_u; gettimeofday(&now, NULL); duration_u = ((int64_t)(now.tv_sec - g_start_time.tv_sec)) * 1000000; duration_u += (now.tv_usec - g_start_time.tv_usec); return duration_u / 1000; } int32 secclock(void) { return msclock() / 1000; } int32 rdclock(void) { return msclock() / MSPTICK; } static void * timer_proc(void *dummy) { struct timeval last, next, now; int64_t duration_u; gettimeofday(&last, NULL); for (;;) { next.tv_usec = last.tv_usec + MSPTICK * 1000; next.tv_sec = last.tv_sec; if (next.tv_usec > 1000000) { next.tv_sec++; next.tv_usec -= 1000000; } do { gettimeofday(&now, NULL); duration_u = (next.tv_sec - now.tv_sec) * 1000000; duration_u += (next.tv_usec - now.tv_usec); if (duration_u > 0) usleep(duration_u); } while (duration_u > 0); interrupt_enter(); Tick++; ksignal(&Tick,1); interrupt_leave(); last.tv_sec = next.tv_sec; last.tv_usec = next.tv_usec; } return NULL; }
C
/////////////////////////////////////////////////////////////////////////////////// // The MIT License (MIT) // // Copyright (c) 2017 Tarek Sherif // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. /////////////////////////////////////////////////////////////////////////////////// #include <math.h> #include "math.h" static vec3 tempVec3; static mat4 tempMat4; void math_setVec3(vec3 v, float x, float y, float z) { v[0] = x; v[1] = y; v[2] = z; } float math_dotVec3(vec3 v1, vec3 v2) { return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2]; } float math_lengthVec3(vec3 v) { return sqrt(math_dotVec3(v, v)); } void math_scaleVec3(vec3 v, float s) { v[0] *= s; v[1] *= s; v[2] *= s; } void math_normalizeVec3(vec3 v) { float l = math_lengthVec3(v); v[0] /= l; v[1] /= l; v[2] /= l; } void math_addVec3(vec3 out, vec3 v1, vec3 v2) { out[0] = v1[0] + v2[0]; out[1] = v1[1] + v2[1]; out[2] = v1[2] + v2[2]; } void math_subVec3(vec3 out, vec3 v1, vec3 v2) { out[0] = v1[0] - v2[0]; out[1] = v1[1] - v2[1]; out[2] = v1[2] - v2[2]; } void math_crossVec3(vec3 out, vec3 v1, vec3 v2) { tempVec3[0] = v1[1] * v2[2] - v1[2] * v2[1]; tempVec3[1] = v1[2] * v2[0] - v1[0] * v2[2]; tempVec3[2] = v1[0] * v2[1] - v1[1] * v2[0]; out[0] = tempVec3[0]; out[1] = tempVec3[1]; out[2] = tempVec3[2]; } void math_identityMat4(mat4 m) { m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[5] = 1; m[6] = 0; m[7] = 0; m[8] = 0; m[9] = 0; m[10] = 1; m[11] = 0; m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1; } void math_translationMat4(mat4 m, float x, float y, float z) { m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[5] = 1; m[6] = 0; m[7] = 0; m[8] = 0; m[9] = 0; m[10] = 1; m[11] = 0; m[12] = x; m[13] = y; m[14] = z; m[15] = 1; } void math_scalingMat4(mat4 m, float x, float y, float z) { m[0] = x; m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[5] = y; m[6] = 0; m[7] = 0; m[8] = 0; m[9] = 0; m[10] = z; m[11] = 0; m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1; } void math_rotationXMat4(mat4 m, float theta) { float sine = sin(theta); float cosine = cos(theta); m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[5] = cosine; m[6] = sine; m[7] = 0; m[8] = 0; m[9] = -sine; m[10] = cosine; m[11] = 0; m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1; } void math_rotationYMat4(mat4 m, float theta) { float sine = sin(theta); float cosine = cos(theta); m[0] = cosine; m[1] = 0; m[2] = -sine; m[3] = 0; m[4] = 0; m[5] = 1; m[6] = 0; m[7] = 0; m[8] = sine; m[9] = 0; m[10] = cosine; m[11] = 0; m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1; } void math_rotationZMat4(mat4 m, float theta) { float sine = sin(theta); float cosine = cos(theta); m[0] = cosine; m[1] = sine; m[2] = 0; m[3] = 0; m[4] = -sine; m[5] = cosine; m[6] = 0; m[7] = 0; m[8] = 0; m[9] = 0; m[10] = 1; m[11] = 0; m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1; } void math_multiplyMat4(mat4 result, mat4 m1, mat4 m2) { int row, col, i; int result_index, m1_index, m2_index; float val; for (col = 0; col < 4; col++) { for (row = 0; row < 4; row++) { result_index = col * 4 + row; val = 0; for (i = 0; i < 4; i++) { m1_index = i * 4 + row; m2_index = col * 4 + i; val += m1[m1_index] * m2[m2_index]; } tempMat4[result_index] = val; } } for (i = 0; i < 16; i++) { result[i] = tempMat4[i]; } } void math_mat4TransformVec3(vec3 out, mat4 m, vec3 v) { tempVec3[0] = v[0] * m[0] + v[1] * m[4] + v[2] * m[8] + m[12]; tempVec3[1] = v[0] * m[1] + v[1] * m[5] + v[2] * m[9] + m[13]; tempVec3[2] = v[0] * m[2] + v[1] * m[6] + v[2] * m[10] + m[14]; out[0] = tempVec3[0]; out[1] = tempVec3[1]; out[2] = tempVec3[2]; } void math_transposeMat4(mat4 result, mat4 m) { int row, col; int index1, index2; for (col = 0; col < 4; col++) { for (row = col; row < 4; row++) { index1 = col * 4 + row; index2 = row * 4 + col; result[index1] = m[index2]; result[index2] = m[index1]; } } } float math_detMat4(mat4 m) { float m0 = m[0]; float m1 = m[1]; float m2 = m[2]; float m3 = m[3]; float m4 = m[4]; float m5 = m[5]; float m6 = m[6]; float m7 = m[7]; float m8 = m[8]; float m9 = m[9]; float m10 = m[10]; float m11 = m[11]; float m12 = m[12]; float m13 = m[13]; float m14 = m[14]; float m15 = m[15]; return m0 * m5 * m10 * m15 + m0 * m9 * m14 * m7 + m0 * m13 * m6 * m11 + m4 * m1 * m14 * m11 + m4 * m9 * m2 * m15 + m4 * m13 * m10 * m3 + m8 * m1 * m6 * m15 + m8 * m5 * m14 * m3 + m8 * m13 * m2 * m7 + m12 * m1 * m10 * m7 + m12 * m5 * m2 * m11 + m12 * m9 * m6 * m3 - m0 * m5 * m14 * m11 - m0 * m9 * m6 * m15 - m0 * m13 * m10 * m7 - m4 * m1 * m10 * m15 - m4 * m9 * m14 * m3 - m4 * m13 * m2 * m11 - m8 * m1 * m14 * m7 - m8 * m5 * m2 * m15 - m8 * m13 * m6 * m3 - m12 * m1 * m6 * m11 - m12 * m5 * m10 * m3 - m12 * m9 * m2 * m7; } void math_invertMat4(mat4 result, mat4 m) { float m0 = m[0]; float m1 = m[1]; float m2 = m[2]; float m3 = m[3]; float m4 = m[4]; float m5 = m[5]; float m6 = m[6]; float m7 = m[7]; float m8 = m[8]; float m9 = m[9]; float m10 = m[10]; float m11 = m[11]; float m12 = m[12]; float m13 = m[13]; float m14 = m[14]; float m15 = m[15]; float det = math_detMat4(m); result[0] = (m5 * m10 * m15 - m5 * m11 * m14 - m9 * m6 * m15 + m9 * m7 * m14 + m13 * m6 * m11 - m13 * m7 * m10) / det; result[1] = (-m1 * m10 * m15 + m1 * m11 * m14 + m9 * m2 * m15 - m9 * m3 * m14 - m13 * m2 * m11 + m13 * m3 * m10) / det; result[2] = (m1 * m6 * m15 - m1 * m7 * m14 - m5 * m2 * m15 + m5 * m3 * m14 + m13 * m2 * m7 - m13 * m3 * m6) / det; result[3] = (-m1 * m6 * m11 + m1 * m7 * m10 + m5 * m2 * m11 - m5 * m3 * m10 - m9 * m2 * m7 + m9 * m3 * m6) / det; result[4] = (-m4 * m10 * m15 + m4 * m11 * m14 + m8 * m6 * m15 - m8 * m7 * m14 - m12 * m6 * m11 + m12 * m7 * m10) / det; result[5] = (m0 * m10 * m15 - m0 * m11 * m14 - m8 * m2 * m15 + m8 * m3 * m14 + m12 * m2 * m11 - m12 * m3 * m10) / det; result[6] = (-m0 * m6 * m15 + m0 * m7 * m14 + m4 * m2 * m15 - m4 * m3 * m14 - m12 * m2 * m7 + m12 * m3 * m6) / det; result[7] = (m0 * m6 * m11 - m0 * m7 * m10 - m4 * m2 * m11 + m4 * m3 * m10 + m8 * m2 * m7 - m8 * m3 * m6) / det; result[8] = (m4 * m9 * m15 - m4 * m11 * m13 - m8 * m5 * m15 + m8 * m7 * m13 + m12 * m5 * m11 - m12 * m7 * m9) / det; result[9] = (-m0 * m9 * m15 + m0 * m11 * m13 + m8 * m1 * m15 - m8 * m3 * m13 - m12 * m1 * m11 + m12 * m3 * m9) / det; result[10] = (m0 * m5 * m15 - m0 * m7 * m13 - m4 * m1 * m15 + m4 * m3 * m13 + m12 * m1 * m7 - m12 * m3 * m5) / det; result[11] = (-m0 * m5 * m11 + m0 * m7 * m9 + m4 * m1 * m11 - m4 * m3 * m9 - m8 * m1 * m7 + m8 * m3 * m5) / det; result[12] = (-m4 * m9 * m14 + m4 * m10 * m13 + m8 * m5 * m14 - m8 * m6 * m13 - m12 * m5 * m10 + m12 * m6 * m9) / det; result[13] = (m0 * m9 * m14 - m0 * m10 * m13 - m8 * m1 * m14 + m8 * m2 * m13 + m12 * m1 * m10 - m12 * m2 * m9) / det; result[14] = (-m0 * m5 * m14 + m0 * m6 * m13 + m4 * m1 * m14 - m4 * m2 * m13 - m12 * m1 * m6 + m12 * m2 * m5) / det; result[15] = (m0 * m5 * m10 - m0 * m6 * m9 - m4 * m1 * m10 + m4 * m2 * m9 + m8 * m1 * m6 - m8 * m2 * m5) / det; } void math_lookAtMat4(mat4 m, vec3 eye, vec3 at, vec3 up) { float xaxis[3]; float yaxis[3]; float zaxis[3]; math_subVec3(zaxis, eye, at); math_normalizeVec3(zaxis); math_crossVec3(xaxis, up, zaxis); math_normalizeVec3(xaxis); math_crossVec3(yaxis, zaxis, xaxis); math_normalizeVec3(yaxis); m[0] = xaxis[0]; m[1] = yaxis[0]; m[2] = zaxis[0]; m[3] = 0; m[4] = xaxis[1]; m[5] = yaxis[1]; m[6] = zaxis[1]; m[7] = 0; m[8] = xaxis[2]; m[9] = yaxis[2]; m[10] = zaxis[2]; m[11] = 0; m[12] = -math_dotVec3(eye, xaxis); m[13] = -math_dotVec3(eye, yaxis); m[14] = -math_dotVec3(eye, zaxis); m[15] = 1; } void math_orthoMat4(mat4 m, float left, float right, float bottom, float top, float near, float far) { m[0] = 2 / (right - left); m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[5] = 2 / (top - bottom); m[6] = 0; m[7] = 0; m[8] = 0; m[9] = 0; m[10] = -2 / (far - near); m[11] = 0; m[12] = - (right + left) / (right - left); m[13] = - (top + bottom) / (top - bottom); m[14] = - (far + near) / (far - near); m[15] = 1; } void math_perspectiveMat4(mat4 m, float yfov, float aspect, float near, float far) { float top = near * tan(yfov / 2); float right = top * aspect; m[0] = near / right; m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[5] = near / top; m[6] = 0; m[7] = 0; m[8] = 0; m[9] = 0; m[10] = -(far + near) / (far - near); m[11] = -1; m[12] = 0; m[13] = 0; m[14] = -2 * far * near / (far - near); m[15] = 0; }
C
/* ** EPITECH PROJECT, 2020 ** dele.c ** File description: ** myftp */ #include "myftp.h" #include <fcntl.h> void dele(char *file, client_t *client, server_t server) { if (!client->is_connected) return (send_message("530 Need connection\r\n", client->socket)); if (!file) return (send_message("501 DELE takes a file as \ parameter\r\n", client->socket)); if (open(file, O_RDONLY) == -1) return (send_message("550 file not found\r\n", client->socket)); if (remove(file) == 0) send_message(command_array[5].message, client->socket); else send_message("500 An error occured with the DELE \ command\r\n", client->socket); }
C
#include "intro_state.h" #include "util.h" void play_intro_state() { WINDOW *intro = newwin(0, 0, 0, 0); // window's background color wbkgd(intro, COLOR_PAIR(7)); // fake loading :) print_in_middle(intro, "loading..."); wrefresh(intro); // play some useless animation loading_animation(intro, 1); // splash screen (animated) wattron(intro, COLOR_PAIR(15)); print_splash_screen(intro, 1); wattroff(intro, COLOR_PAIR(15)); // loading complete print_in_middle(intro, "Press any key to continue..."); // play some random terminal sound when ready beep(); // waiting for the 'any' key to be pressed :)) getch(); // destroy state destroy_intro(intro); } void destroy_intro(WINDOW *intro) { wrefresh(intro); delwin(intro); endwin(); }
C
/** @file circle.c - same as line modulo 360. Etienne Démoulin - 2020. this object has 1 inlet and 2 outlets it responds to ints and floats in inlet. output a line in the first outlet / bang when done in the second outlet. @ingroup demoul */ #include "ext.h" // you must include this - it contains the external object's link to available Max functions #include "ext_obex.h" // this is required for all objects using the newer style for writing objects. #include <stdlib.h> #include <stdio.h> #include <string.h> #include <limits.h> #include <errno.h> #include <time.h> #include <unistd.h> #include <fcntl.h> #include <assert.h> #include <string> #include <vector> #include <map> #include <iostream> #include <fstream> #include <sstream> #ifdef __APPLE__ #include <Carbon/Carbon.h> #include <unistd.h> #endif #ifdef WIN32 #ifndef NAN static const unsigned long __nan[2] = {0xffffffff, 0x7fffffff}; #define NAN (*(const float *) __nan) #endif #endif typedef struct _plussz { // defines our object's internal variables for each instance in a patch t_object p_ob; // object header - ALL objects MUST begin with this... double p_time; double p_dep; double p_inc; double p_arr; long p_step; long i; //PNPP double p_cur; void *p_outlet; // 2nd output. Bang when done void *p_outlet2; //1rst output. Line out. void *m_clock; } t_plussz; // these are prototypes for the methods that are defined below void plussz_assist(t_plussz *x, void *b, long m, long a, char *s); //help function void plussz_free(t_plussz *x); //destructor void *plussz_new(t_symbol *s, long argc, t_atom *argv); //squelette void plussz_float(t_plussz *x, double f); //when float called void plussz_task(t_plussz *x); //clocker. void plussz_int(t_plussz *x, long n); //when int called t_class *plussz_class; // global pointer to the object class - so max can reference the object //-------------------------------------------------------------------------- void ext_main(void *r) { t_class *c; c = class_new("circle", (method)plussz_new, (method)plussz_free, (long)sizeof(t_plussz), 0L, A_GIMME, 0); // class_new() loads our external's class into Max's memory so it can be used in a patch // plussz_new = object creation method defined below class_addmethod(c, (method)plussz_float, "float", A_FLOAT, 0); class_addmethod(c, (method)plussz_int, "int", A_LONG, 0); class_addmethod(c, (method)plussz_assist, "assist", A_CANT, 0); // (optional) assistance method needs to be declared like this class_register(CLASS_BOX, c); plussz_class = c; } //-------------------------------------------------------------------------- void *plussz_new(t_symbol *s, long argc, t_atom *argv) // argc = number of arguments // argv list of arguments. { //Verifications. t_plussz *x = NULL; long time; if (argc != 1) //check there is 1 argument. { post("circle <time to reach>"); return NULL; } time = atom_getfloat(argv); //check argument > 0. if (time < 0) { post("circle <time to reach>"); post("<time to reach> > 0"); return NULL; } x = (t_plussz *)object_alloc(plussz_class); // create a new instance of this object x->p_outlet = floatout(x); // Create 2nd outlet. x->p_outlet2 = floatout(x); // Create 1rst outlet. //Define time and steps. x->p_time = time; x->p_step = x->p_time/20; //Define loop variables. x->p_cur = 0; x->i = 0; x->m_clock = clock_new((t_plussz *)x, (method)plussz_task); //define clock. return(x); // return a reference to the object instance } //-------------------------------------------------------------------------- void plussz_assist(t_plussz *x, void *b, long m, long a, char *s) // 4 final arguments are always the same for the assistance method { if (m == ASSIST_INLET) { // Inlets switch (a) { case 0: sprintf(s, "(number) destination to reach"); break; } } else { // Outlets switch (a) { case 0: sprintf(s, "(float) Line out"); break; case 1: sprintf(s, "(bang) when done"); break; } } } void plussz_task(t_plussz *x) //clocker { x->p_cur+=x->p_inc; outlet_float(x->p_outlet2, fmod(x->p_cur,360)); if (x->i < x->p_step) { x->i+=1; clock_fdelay(x->m_clock, 20.); } else { outlet_float(x->p_outlet2, x->p_arr); outlet_bang(x->p_outlet); x->p_dep = x->p_arr; clock_unset(x->m_clock); //post("la clock est stop"); } } void plussz_free(t_plussz *x) //destructor { object_free(x->m_clock); } void plussz_float(t_plussz *x, double f) //when float called. { if (f <= 360 & f >= 0) //check incoming value. { x->i=0; x->p_arr = f; x->p_dep = x->p_cur; if (fabs(x->p_arr-x->p_dep) < 180) //case 1. distance < 180. { x->p_inc = (x->p_arr-x->p_dep)/x->p_step; x->p_cur = x->p_dep; clock_fdelay(x->m_clock, 0L); //post("step %.2f",n); } else if (x->p_arr-x->p_dep < 0) //case 2. distance > 180 and positive increment. { x->p_inc = ((x->p_arr-x->p_dep)+360)/x->p_step; x->p_cur = x->p_dep; clock_fdelay(x->m_clock, 0L); } else //case 3. Distance > 180 and negative increment. { x->p_inc = ((x->p_arr-x->p_dep)-360)/x->p_step; x->p_cur = x->p_dep+360; clock_fdelay(x->m_clock, 0L); } } else { post("FORBIDDEN, you should stay on range [0;360]"); outlet_bang(x->p_outlet); } } void plussz_int(t_plussz *x, long n) //when inc called, convert to float. { double f = n; plussz_float(x,f); }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include "hash.h" unsigned int hash(char *s){ unsigned int h; unsigned char *p; h=0; for(p=(unsigned char *)s;*p!='\0';p++) h= MULTIPLIER *h + *p; return h%HASH_SIZE; } PROG_CELL lookup(char *s){ int index = hash(s); while (table[index] != NULL) { if (table[index]->chave) { return table[index]; } index ++; index %= HASH_SIZE; } return NULL; } void insert(char *s, int value){ int index; index = hash(s); PROG_CELL p; p=(PROG_CELL)malloc(sizeof(struct list)); p->chave= s; p->elem = value; p->next = table[index]; table[index] = p; } void init_table(){ int index; for(index=0;index<HASH_SIZE;index++) table[index]=NULL; } int getValofCell(PROG_CELL p){ return p->elem; } char* getNameofCell(PROG_CELL p){ return p->chave; }
C
//基础函数库:直线 实现 //========================= //------------------------------------------------------------------------------- #include <stdio.h> #include <math.h> #include "line.h" #include "graph.h" #include "window.h" #include "calc.h" static int __graph_line_calc_center(struct graph_line *cthis) //维护中心点信息 { return 0; } //构造函数 void graph_line_init(struct graph_line * cthis,struct point pstart,struct point pend) { graph_init(&(cthis->graph)); //调用父类的构造函数 //覆写父类的虚函数 (cthis->graph).draw = graph_line_draw; (cthis->graph).is_cross = graph_line_is_cross; (cthis->graph).move = graph_line_move; (cthis->graph).rot = graph_line_rot; (cthis->graph).resize = graph_line_resize; (cthis->graph).get_center = graph_line_get_center; (cthis->graph).deepcopy = graph_line_deepcopy; (cthis->graph).draw_tag = graph_line_draw_tag; (cthis->graph).get_tag = graph_line_get_tag; //构建子类的函数指针 cthis->insert = graph_line_insert; cthis->del = graph_line_del; cthis->get_child = graph_line_get_child; cthis->get_parent = graph_line_get_parent; cthis->get_child_count = graph_line_get_child_count; //数据初始化 cthis->pstart = pstart; cthis->pend = pend; return; } //析构函数 void graph_line_exit(struct graph_line * cthis) { return; } //获得新对象 struct graph_line * graph_line_new(struct point pstart,struct point pend) { struct graph_line * cthis = malloc(sizeof(struct graph_line)); if(!cthis) return NULL; graph_line_init(cthis,pstart,pend); return cthis; } //删除对象 void graph_line_delete(struct graph_line * cthis) { free(cthis); return; } //------------------------------------------------------------------------------- //继承自graph的方法实现:调用父对象函数 int graph_line_insert(struct graph_line *cthis,struct graph_line *item) { return graph_insert((struct graph *)cthis,(struct graph *)item); } //删除子元 int graph_line_del(struct graph_line *cthis,int item_id) { return graph_del((struct graph *)cthis,item_id); } //返回子元序列 struct graph** graph_line_get_child(struct graph_line *cthis) { return graph_get_child((struct graph *)cthis); } //返回父元 struct graph* graph_line_get_parent(struct graph_line *cthis) { return graph_get_parent((struct graph *)cthis); } //返回子代数量 int graph_line_get_child_count(struct graph_line *cthis) { return graph_get_child_count((struct graph *)cthis); } //------------------------------------------------------------------------------- //实现的虚函数 int graph_line_draw(struct graph * cthis, struct window * draw_object) { //从接口恢复对象 struct graph_line *cthis_tf = (struct graph_line *)cthis; //画线 draw_object->draw_line(draw_object,cthis_tf->pstart,cthis_tf->pend); return 0; } //TODO: int graph_line_is_cross(struct graph *cthis, struct point point) { struct graph_line *cthis_tf = (struct graph_line *)cthis; return 0; } int graph_line_move(struct graph *cthis,struct point base,struct point vector) { struct graph_line *cthis_tf = (struct graph_line *)cthis; //计算相对位移 (cthis_tf->pstart).x += vector.x; (cthis_tf->pend).x += vector.x; (cthis_tf->pstart).y += vector.y; (cthis_tf->pend).y += vector.y; return 0; } int graph_line_rot(struct graph *cthis,struct point base,float angle) { struct graph_line *cthis_tf = (struct graph_line *)cthis; (cthis_tf->pstart).x = (int)(base.x + ((cthis_tf->pstart).x - base.x)*cos(angle) - ((cthis_tf->pstart).y - base.y ) * sin(angle)); (cthis_tf->pstart).y = (int)(base.y + ((cthis_tf->pstart).x - base.x)*sin(angle) - ((cthis_tf->pstart).y - base.y ) * cos(angle)); (cthis_tf->pend).x = (int)(base.x + ((cthis_tf->pend).x - base.x)*cos(angle) - ((cthis_tf->pend).y - base.y ) * sin(angle)); (cthis_tf->pend).y = (int)(base.y + ((cthis_tf->pend).x - base.x)*sin(angle) - ((cthis_tf->pend).y - base.y ) * cos(angle)); return 0; } int graph_line_resize(struct graph *cthis,struct point base,float rate) { struct graph_line *cthis_tf = (struct graph_line *)cthis; cthis_tf->pstart = calc_scale(cthis_tf->pstart,base,rate); cthis_tf->pend = calc_scale(cthis_tf->pend,base,rate); return 0; } struct point graph_line_get_center(struct graph *cthis) { struct graph_line *cthis_tf = (struct graph_line *)cthis; return calc_center(cthis_tf->pstart,cthis_tf->pend); } struct graph *graph_line_deepcopy(struct graph *cthis) { struct graph_line *cthis_tf = (struct graph_line *)cthis; return (struct graph *)graph_line_new(cthis_tf->pstart,cthis_tf->pend); } int graph_line_draw_tag(struct graph *cthis,struct window * draw_object) { struct graph_line *cthis_tf = (struct graph_line *)cthis; char tags[100]; sprintf(tags,"L(%d)",cthis->object_id); window_draw_tag(draw_object,cthis_tf->pstart,tags); return 0; } int graph_line_get_tag(struct graph *cthis, struct graph_description *out_info, char *out_info_str) { return 0; }
C
//recursive fibonacci variant - tail recursion #include <stdio.h> int fibonacciTR( int , int , int ); int main( void ) { int term = 5; printf( "fibonacci(%d) = %d" , term , fibonacciTR( term , 0 , 1 ) ); //only in c++ you can supply default argument return 0; } int fibonacciTR( int n , int a , int b ) { if ( n == 0 ){ return a; }else if ( n == 1 ){ return b; }else{ return fibonacciTR( n - 1 , b , b + a ); //simply give value b to 'a' and b + a to 'b' in the header } }
C
/* ClockIt TEXT. A modification by Dave Parker to ClockIt written by Nathan Seidle at Spark Fun Electronics A basic alarm clock that uses a 4 digit 7-segment display. Includes alarm and snooze. Alarm will turn back on after 9 minutes if alarm is not disengaged. To switch to text display, press and hold DOWN then press and hold SNOOZE for two seconds. Repeat to go back to regular display mode. The other modification is to dim the display at 7PM and brighten the display at 7AM. Alarm is through a piezo buzzer. Three input buttons (up/down/snooze) 1 slide switch (engage/disengage alarm) Display is with PWM of segments - no current limiting resistors! Uses external 16MHz clock as time base. Set fuses: avrdude -p m168 -P lpt1 -c stk200 -U lfuse:w:0xE6:m program hex: avrdude -p m168 -P lpt1 -c stk200 -U flash:w:clockit-text.hex or: make make program (you may need to alter the makefile for your programmer) */ #define NORMAL_TIME #include <stdio.h> #include <avr/io.h> #include <avr/interrupt.h> #include <avr/pgmspace.h> #include <string.h> #define sbi(port, pin) ((port) |= (uint8_t)(1 << pin)) #define cbi(port, pin) ((port) &= (uint8_t)~(1 << pin)) #define FOSC 16000000 //16MHz internal osc #define STATUS_LED 5 //PORTB #define TRUE 1 #define FALSE 0 #define SEG_A PORTC3 #define SEG_B PORTC5 #define SEG_C PORTC2 #define SEG_D PORTD2 #define SEG_E PORTC0 #define SEG_F PORTC1 #define DIG_1 PORTD0 #define DIG_2 PORTD1 #define DIG_3 PORTD4 #define DIG_4 PORTD6 #define DP PORTD5 #define COL PORTD3 #define BUT_UP PORTB5 #define BUT_DOWN PORTB4 #define BUT_SNOOZE PORTD7 #define BUT_ALARM PORTB0 #define BUZZ1 PORTB1 #define BUZZ2 PORTB2 #define AM 1 #define PM 2 #define BRIGHT 50 #define DIM 1 #define DIM_BEFORE_HOUR 7 #define BRIGHT_AFTER_HOUR 7 enum { SHOW_TIME, SET_TIME, SHOW_ALARM, SET_ALARM } program_state = SHOW_TIME; //Declare functions //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void ioinit (void); void delay_ms(uint16_t x); // general purpose delay void delay_us(uint16_t x); void siren(void); void display_number(uint8_t number, uint8_t digit); void display_time(uint16_t time_on); void display_alarm_time(uint16_t time_on); void clear_display(void); void check_buttons(void); void check_alarm(void); void update_time_str(void); uint8_t append_str(char *dest, char *source); uint8_t append_str_P(char *dest, char *source); void display_time_str(uint16_t time_on); void display_character(uint8_t character, uint8_t position); //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //Declare global variables //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= uint8_t hours, minutes, seconds, ampm, flip; uint8_t hours_alarm, minutes_alarm, seconds_alarm, ampm_alarm, flip_alarm; uint8_t hours_alarm_snooze, minutes_alarm_snooze, seconds_alarm_snooze, ampm_alarm_snooze; uint8_t alarm_going; uint8_t snooze; char time_str[30]; uint8_t time_str_display_index = 0; uint8_t scroll_count = 0; uint8_t show_time_str = FALSE; uint8_t bright_level = BRIGHT; //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= const char num_string_0[] PROGMEM = "Zero"; const char num_string_1[] PROGMEM = "One"; const char num_string_2[] PROGMEM = "Two"; const char num_string_3[] PROGMEM = "Three"; const char num_string_4[] PROGMEM = "Four"; const char num_string_5[] PROGMEM = "Five"; const char num_string_6[] PROGMEM = "Six"; const char num_string_7[] PROGMEM = "Seven"; const char num_string_8[] PROGMEM = "Eight"; const char num_string_9[] PROGMEM = "Nine"; const char num_string_10[] PROGMEM = "Ten"; const char num_string_11[] PROGMEM = "Eleven"; const char num_string_12[] PROGMEM = "Twelve"; const char num_string_13[] PROGMEM = "Thirteen"; const char num_string_14[] PROGMEM = "Fourteen"; const char num_string_15[] PROGMEM = "Fifteen"; const char num_string_16[] PROGMEM = "Sixteen"; const char num_string_17[] PROGMEM = "Seventeen"; const char num_string_18[] PROGMEM = "Eighteen"; const char num_string_19[] PROGMEM = "Nineteen"; const char *const num_table[] PROGMEM = { num_string_0, num_string_1, num_string_2, num_string_3, num_string_4, num_string_5, num_string_6, num_string_7, num_string_8, num_string_9, num_string_10, num_string_11, num_string_12, num_string_13, num_string_14, num_string_15, num_string_16, num_string_17, num_string_18, num_string_19, }; const char tens_string_0[] PROGMEM = "Oh"; const char tens_string_10[] PROGMEM = "Ten"; const char tens_string_20[] PROGMEM = "Twenty"; const char tens_string_30[] PROGMEM = "Thirty"; const char tens_string_40[] PROGMEM = "Forty"; const char tens_string_50[] PROGMEM = "Fifty"; const char *const tens_table[] PROGMEM = { tens_string_0, tens_string_10, tens_string_20, tens_string_30, tens_string_40, tens_string_50, }; // 7-Segment display IDs referenced below // // - A - // | | // F B // |-G-| // E C // | | // - D - [0] <- decimal char const CHARACTERS[] PROGMEM = { //0bD0BGACFE 0b00111111, // A 0b10010111, // b 0b10001011, // C 0b10110101, // d 0b10011011, // E 0b00011011, // F 0b10001111, // G 0b00110111, // h 0b00000011, // i 0b10100101, // J 0b00011111, // k 0b10000011, // L 0b10101010, // M 0b00101111, // N 0b10010101, // O 0b00111011, // P 0b00111110, // q 0b00001011, // r 0b00010110, // s 0b10010011, // t 0b10100111, // U 0b10100010, // v 0b10001101, // w 0b10011000, // x 0b10110110, // Y 0b00110001, // z }; const char DIGITS[] PROGMEM = { //0bD0BGACFE 0b10101111, // 0 0b00100100, // 1 0b10111001, // 2 0b10111100, // 3 0b00110110, // 4 0b10011110, // 5 0b10011111, // 6 0b00101100, // 7 0b10111111, // 8 0b10111110, // 9 }; const char PUNCTUATION[] PROGMEM = { //0bD0BGACFE 0b00010000, // - 0b00100000, // ' }; ISR (TIMER1_OVF_vect) { //Prescalar of 1024 //Clock = 16MHz //15,625 clicks per second //64us per click TCNT1 = 49911; //65536 - 15,625 = 49,911 - Preload timer 1 for 49,911 clicks. Should be 1s per ISR call //Debug with faster time! //TCNT1 = 63581; //65536 - 1,953 = 63581 - Preload timer 1 for 63581 clicks. // Should be 0.125s per ISR call - 8 times faster than normal time flip_alarm = 1; if(flip == 0) flip = 1; else flip = 0; seconds++; if(seconds == 60) { seconds = 0; minutes++; if(minutes == 60) { minutes = 0; hours++; if(hours == 12) { if(ampm == AM) ampm = PM; else ampm = AM; } if(hours == 13) hours = 1; } update_time_str(); } if (program_state != SET_TIME) { bright_level = (((hours < DIM_BEFORE_HOUR || hours == 12) && ampm == AM) || \ (hours > BRIGHT_AFTER_HOUR && hours !=12 && ampm == PM)) ? DIM : BRIGHT; } } ISR (TIMER2_OVF_vect) { if (program_state == SHOW_TIME && show_time_str == TRUE) { display_time_str(10); } else { display_time(10); //Display current time for 1ms } if (scroll_count == 10) { scroll_count = 0; time_str_display_index++; if (strlen(time_str) - time_str_display_index < 4) { time_str_display_index = 0; } } else { scroll_count++; } } void update_time_str(void) { uint8_t index = 0; char *spacer = " "; char *space = " "; index += append_str(time_str + index, spacer) - 1; index += append_str_P(time_str + index, (char*)pgm_read_word(&(num_table[hours]))) - 1; index += append_str(time_str + index, space) - 1; if (minutes == 0) { index += append_str(time_str + index, "O'Clock") - 1; } else if (minutes >= 10 && minutes <= 19) { index += append_str_P(time_str + index, (char*)pgm_read_word(&(num_table[minutes]))) - 1; } else { uint8_t tens = minutes / 10; uint8_t ones = minutes % 10; index += append_str_P(time_str + index, (char*)pgm_read_word(&(tens_table[tens]))) - 1; if(ones != 0) { index += append_str(time_str + index, "-") - 1; index += append_str_P(time_str + index, (char*)pgm_read_word(&(num_table[ones]))) - 1; } } if (ampm == AM) { index += append_str(time_str + index, " AM") - 1; } else { index += append_str(time_str + index, " PM") - 1; } index += append_str(time_str + index, spacer) - 1; time_str_display_index = 0; } uint8_t append_str(char *dest, char *source) { uint8_t index = 0; char temp_char; do { temp_char = source[index]; dest[index] = temp_char; index++; } while (temp_char != 0); return index; } uint8_t append_str_P(char *dest, char *source) { uint8_t index = 0; char temp_char; do { temp_char = (char)pgm_read_byte(source + index); dest[index] = temp_char; index++; } while (temp_char != 0); return index; } int main (void) { ioinit(); //Boot up defaults hours = 12; minutes = 00; seconds = 00; ampm = PM; hours_alarm = 10; minutes_alarm = 00; seconds_alarm = 00; ampm_alarm = AM; hours_alarm_snooze = 12; minutes_alarm_snooze = 00; seconds_alarm_snooze = 00; ampm_alarm_snooze = AM; alarm_going = FALSE; snooze = FALSE; update_time_str(); sei(); //Enable interrupts siren(); //Make some noise at power up while(1) { check_buttons(); //See if we need to set the time or snooze check_alarm(); //See if the current time is equal to the alarm time } return(0); } //Check to see if the time is equal to the alarm time void check_alarm(void) { //Check wether the alarm slide switch is on or off if( (PINB & (1<<BUT_ALARM)) != 0) { if (alarm_going == FALSE) { //Check to see if the time equals the alarm time if( (hours == hours_alarm) && (minutes == minutes_alarm) && \ (seconds == seconds_alarm) && (ampm == ampm_alarm) && (snooze == FALSE) ) { //Set it off! alarm_going = TRUE; } //Check to see if we need to set off the alarm again after a ~9 minute snooze if( (hours == hours_alarm_snooze) && (minutes == minutes_alarm_snooze) && \ (seconds == seconds_alarm_snooze) && (ampm == ampm_alarm_snooze) && (snooze == TRUE) ) { //Set it off! alarm_going = TRUE; } } } else alarm_going = FALSE; } //Checks buttons for system settings void check_buttons(void) { uint8_t i; uint8_t sling_shot = 0; uint8_t minute_change = 1; uint8_t previous_button = 0; //If the user hits snooze while alarm is going off, record time so that we can set off alarm again in 9 minutes if ( (PIND & (1<<BUT_SNOOZE)) == 0 && alarm_going == TRUE) { alarm_going = FALSE; //Turn off alarm snooze = TRUE; //But remember that we are in snooze mode, alarm needs to go off again in a few minutes seconds_alarm_snooze = 0; minutes_alarm_snooze = minutes + 9; //Snooze to 9 minutes from now hours_alarm_snooze = hours; ampm_alarm_snooze = ampm; if(minutes_alarm_snooze > 59) { minutes_alarm_snooze -= 60; hours_alarm_snooze++; if(hours_alarm_snooze == 12) { if(ampm_alarm_snooze == AM) ampm_alarm_snooze = PM; else ampm_alarm_snooze = AM; } if(hours_alarm_snooze == 13) hours_alarm_snooze = 1; } } // toggle time display if ((PINB & (1<<BUT_DOWN)) == 0 && (PIND & (1<<BUT_SNOOZE)) == 0) { delay_ms(2000); if ((PINB & (1<<BUT_DOWN)) == 0 && (PIND & (1<<BUT_SNOOZE)) == 0) { show_time_str = (show_time_str == TRUE) ? FALSE : TRUE; while((PIND & (1<<BUT_SNOOZE)) == 0) ; //Wait for you to release button } } //Check for set time if ( (PINB & ((1<<BUT_UP)|(1<<BUT_DOWN))) == 0) { delay_ms(2000); if ( (PINB & ((1<<BUT_UP)|(1<<BUT_DOWN))) == 0) { //You've been holding up and down for 2 seconds //Set time! program_state = SET_TIME; //siren(); //Make some noise to show that you're setting the time while( (PINB & ((1<<BUT_UP)|(1<<BUT_DOWN))) == 0) //Wait for you to stop pressing the buttons display_time(1000); //Display current time for 1000ms while(1) { if ( (PIND & (1<<BUT_SNOOZE)) == 0) //All done! { TIMSK2 = (1<<TOIE2); //Re-enable the timer 2 interrupt for(i = 0 ; i < 3 ; i++) { display_time(250); //Display current time for 100ms clear_display(); delay_ms(250); } while((PIND & (1<<BUT_SNOOZE)) == 0) ; //Wait for you to release button update_time_str(); program_state = SHOW_TIME; break; } if ( (PINB & (1<<BUT_UP)) == 0) { //Ramp minutes faster if we are holding the button //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= if(previous_button == BUT_UP) sling_shot++; else { sling_shot = 0; minute_change = 1; } previous_button = BUT_UP; if (sling_shot > 5) { minute_change++; if(minute_change > 30) minute_change = 30; sling_shot = 0; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= minutes += minute_change; if (minutes > 59) { minutes -= 60; hours++; if(hours == 13) hours = 1; if(hours == 12) { if(ampm == AM) ampm = PM; else ampm = AM; } } delay_ms(100); } else if ( (PINB & (1<<BUT_DOWN)) == 0) { //Ramp minutes faster if we are holding the button //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= if(previous_button == BUT_DOWN) sling_shot++; else { sling_shot = 0; minute_change = 1; } previous_button = BUT_DOWN; if (sling_shot > 5) { minute_change++; if(minute_change > 30) minute_change = 30; sling_shot = 0; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= minutes -= minute_change; if(minutes > 60) { minutes = 59; hours--; if(hours == 0) hours = 12; if(hours == 11) { if(ampm == AM) ampm = PM; else ampm = AM; } } delay_ms(100); } else { previous_button = 0; } //clear_display(); //Blink display //delay_ms(100); } } } //Check for set alarm if ( (PIND & (1<<BUT_SNOOZE)) == 0) { TIMSK2 = 0; display_alarm_time(2000); if ( (PIND & (1<<BUT_SNOOZE)) == 0) { //You've been holding snooze for 2 seconds //Set alarm time! //Disable the regular display clock interrupt TIMSK2 = 0; while( (PIND & (1<<BUT_SNOOZE)) == 0) //Wait for you to stop pressing the buttons { clear_display(); delay_ms(250); display_alarm_time(250); //Display current time for 1000ms } while(1) { display_alarm_time(100); //Display current time for 100ms if ( (PIND & (1<<BUT_SNOOZE)) == 0) //All done! { for(i = 0 ; i < 4 ; i++) { display_alarm_time(250); //Display current time for 100ms clear_display(); delay_ms(250); } while((PIND & (1<<BUT_SNOOZE)) == 0) ; //Wait for you to release button TIMSK2 = (1<<TOIE2); //Re-enable the timer 2 interrupt break; } if ( (PINB & (1<<BUT_UP)) == 0) { //Ramp minutes faster if we are holding the button //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= if(previous_button == BUT_UP) sling_shot++; else { sling_shot = 0; minute_change = 1; } previous_button = BUT_UP; if (sling_shot > 5) { minute_change++; if(minute_change > 30) minute_change = 30; sling_shot = 0; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= minutes_alarm += minute_change; if (minutes_alarm > 59) { minutes_alarm -= 60; hours_alarm++; if(hours_alarm == 13) hours_alarm = 1; if(hours_alarm == 12) { if(ampm_alarm == AM) ampm_alarm = PM; else ampm_alarm = AM; } } //delay_ms(100); } else if ( (PINB & (1<<BUT_DOWN)) == 0) { //Ramp minutes faster if we are holding the button //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= if(previous_button == BUT_DOWN) sling_shot++; else { sling_shot = 0; minute_change = 1; } previous_button = BUT_DOWN; if (sling_shot > 5) { minute_change++; if(minute_change > 30) minute_change = 30; sling_shot = 0; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= minutes_alarm -= minute_change; if(minutes_alarm > 60) { minutes_alarm = 59; hours_alarm--; if(hours_alarm == 0) hours_alarm = 12; if(hours_alarm == 11) { if(ampm_alarm == AM) ampm_alarm = PM; else ampm_alarm = AM; } } //delay_ms(100); } else { previous_button = 0; } //clear_display(); //Blink display //delay_ms(100); } } else TIMSK2 = (1<<TOIE2); //Re-enable the timer 2 interrupt } } void clear_display(void) { PORTC = 0; PORTD &= 0b10000000; } void display_number(uint8_t number, uint8_t digit) { //Set the digit PORTD |= (1<<DIG_1)|(1<<DIG_2)|(1<<DIG_3)|(1<<DIG_4)|(1<<COL); switch(digit) { case 1: PORTD &= ~(1<<DIG_1);//Select Digit 1 break; case 2: PORTD &= ~(1<<DIG_2);//Select Digit 2 break; case 3: PORTD &= ~(1<<DIG_3);//Select Digit 3 break; case 4: PORTD &= ~(1<<DIG_4);//Select Digit 4 break; case 5: PORTD &= ~(1<<COL);//Select Digit COL break; default: break; } PORTC = 0; //Clear all segments PORTD &= ~((1<<2)|(1<<5)); //Clear D segment and decimal point switch(number) { case 0: PORTC |= 0b00101111; //Segments A, B, C, D, E, F PORTD |= 0b00000100; break; case 1: PORTC |= 0b00100100; //Segments B, C //PORTD |= 0b00000000; break; case 2: PORTC |= 0b00111001; //Segments A, B, D, E, G PORTD |= 0b00000100; break; case 3: PORTC |= 0b00111100; //Segments ABCDG PORTD |= 0b00000100; break; case 4: PORTC |= 0b00110110; //Segments BCGF PORTD |= 0b00000000; break; case 5: PORTC |= 0b00011110; //Segments AFGCD PORTD |= 0b00000100; break; case 6: PORTC |= 0b00011111; //Segments AFGDCE PORTD |= 0b00000100; break; case 7: PORTC |= 0b00101100; //Segments ABC PORTD |= 0b00000000; break; case 8: PORTC |= 0b00111111; //Segments ABCDEFG PORTD |= 0b00000100; break; case 9: PORTC |= 0b00111110; //Segments ABCDFG PORTD |= 0b00000100; break; case 10: //Colon PORTC |= 0b00101000; //Segments AB //PORTD |= 0b00000000; break; case 11: //Alarm dot PORTD |= 0b00100000; break; case 12: //AM dot PORTC |= 0b00000100; //Segments C break; default: PORTC = 0; break; } } //Displays current time //Brightness level is an amount of time the LEDs will be in - 200us is pretty dim but visible. //Amount of time during display is around : [ BRIGHT_LEVEL(us) * 5 + 10ms ] * 10 //Roughly 11ms * 10 = 110ms //Time on is in (ms) void display_time(uint16_t time_on) { for(uint16_t j = 0 ; j < time_on ; j++) { #ifdef NORMAL_TIME //Display normal hh:mm time if(hours > 9) { display_number(hours / 10, 1); //Post to digit 1 delay_us(bright_level); } display_number(hours % 10, 2); //Post to digit 2 delay_us(bright_level); display_number(minutes / 10, 3); //Post to digit 3 delay_us(bright_level); display_number(minutes % 10, 4); //Post to digit 4 delay_us(bright_level); #else //During debug, display mm:ss display_number(minutes / 10, 1); delay_us(bright_level); display_number(minutes % 10, 2); delay_us(bright_level); display_number(seconds / 10, 3); delay_us(bright_level); display_number(seconds % 10, 4); delay_us(bright_level); #endif //Check whether it is AM or PM and turn on dot if(ampm == AM) { display_number(12, 5); //Turn on dot on digit 3 delay_us(bright_level); } //Flash colon for each second if(flip == 0 && program_state == SHOW_TIME) { display_number(255, 5); //Post to digit COL } else { display_number(10, 5); //Post to digit COL } delay_us(bright_level); //Indicate wether the alarm is on or off if( (PINB & (1<<BUT_ALARM)) != 0) { display_number(11, 4); //Turn on dot on digit 4 delay_us(bright_level); //If the alarm slide is on, and alarm_going is true, make noise! if(alarm_going == TRUE && flip_alarm == 1) { clear_display(); siren(); flip_alarm = 0; } } else { snooze = FALSE; //If the alarm switch is turned off, this resets the ~9 minute addtional snooze timer hours_alarm_snooze = 88; //Set these values high, so that normal time cannot hit the snooze time accidentally minutes_alarm_snooze = 88; seconds_alarm_snooze = 88; } clear_display(); delay_us(bright_level); } } //Displays current alarm time //Brightness level is an amount of time the LEDs will be in - 200us is pretty dim but visible. //Amount of time during display is around : [ BRIGHT_LEVEL(us) * 5 + 10ms ] * 10 //Roughly 11ms * 10 = 110ms //Time on is in (ms) void display_alarm_time(uint16_t time_on) { for(uint16_t j = 0 ; j < time_on ; j++) { //Display normal hh:mm time if(hours_alarm > 9) { display_number(hours_alarm / 10, 1); //Post to digit 1 delay_us(bright_level); } display_number(hours_alarm % 10, 2); //Post to digit 2 delay_us(bright_level); display_number(minutes_alarm / 10, 3); //Post to digit 3 delay_us(bright_level); display_number(minutes_alarm % 10, 4); //Post to digit 4 delay_us(bright_level); //During debug, display mm:ss /*display_number(minutes_alarm / 10, 1); delay_us(bright_level); display_number(minutes_alarm % 10, 2); delay_us(bright_level); display_number(seconds_alarm / 10, 3); delay_us(bright_level); display_number(seconds_alarm % 10, 4); delay_us(bright_level); display_number(10, 5); //Display colon delay_us(bright_level);*/ //Check whether it is AM or PM and turn on dot if(ampm_alarm == AM) { display_number(12, 5); //Turn on dot on digit 3 delay_us(bright_level); } display_number(10, 5); //Post to digit COL delay_us(bright_level); clear_display(); delay_ms(1); } } void display_time_str(uint16_t time_on) { for(uint16_t j = 0 ; j < time_on ; j++) { display_character(time_str[time_str_display_index], 1); delay_us(bright_level); display_character(time_str[time_str_display_index + 1], 2); delay_us(bright_level); display_character(time_str[time_str_display_index + 2], 3); delay_us(bright_level); display_character(time_str[time_str_display_index + 3], 4); delay_us(bright_level); //Indicate wether the alarm is on or off if( (PINB & (1<<BUT_ALARM)) != 0) { display_number(11, 4); //Turn on dot on digit 4 delay_us(bright_level); //If the alarm slide is on, and alarm_going is true, make noise! if(alarm_going == TRUE && flip_alarm == 1) { clear_display(); siren(); flip_alarm = 0; } } else { snooze = FALSE; //If the alarm switch is turned off, this resets the ~9 minute addtional snooze timer hours_alarm_snooze = 88; //Set these values high, so that normal time cannot hit the snooze time accidentally minutes_alarm_snooze = 88; seconds_alarm_snooze = 88; } clear_display(); delay_us(bright_level); } } void display_character(uint8_t character, uint8_t position) { //Set the digit PORTD |= (1<<DIG_1)|(1<<DIG_2)|(1<<DIG_3)|(1<<DIG_4)|(1<<COL); switch(position) { case 1: PORTD &= ~(1<<DIG_1);//Select Digit 1 break; case 2: PORTD &= ~(1<<DIG_2);//Select Digit 2 break; case 3: PORTD &= ~(1<<DIG_3);//Select Digit 3 break; case 4: PORTD &= ~(1<<DIG_4);//Select Digit 4 break; case 5: PORTD &= ~(1<<COL);//Select Digit COL break; default: break; } PORTC = 0; //Clear all segments PORTD &= ~((1<<2)|(1<<5)); //Clear D segment and decimal point const char* base_address; if (character >= 'A' && character <= 'Z') { base_address = CHARACTERS - 'A'; } else if (character >= 'a' && character <= 'z') { base_address = CHARACTERS - 'a'; } else if (character >= '0' && character <= '9') { base_address = DIGITS - '0'; } else if (character == '-') { base_address = PUNCTUATION - character; } else if (character == '\'') { base_address = PUNCTUATION - character + 1; } else { return; } uint8_t character_bitmap = pgm_read_byte(base_address + character); PORTC |= character_bitmap; if (character_bitmap >> 7) { PORTD |= 0b00000100; } } //Make noise for time_on in (ms) void siren(void) { for(int i = 0 ; i < 500 ; i++) { cbi(PORTB, BUZZ1); sbi(PORTB, BUZZ2); delay_us(300); sbi(PORTB, BUZZ1); cbi(PORTB, BUZZ2); delay_us(300); } cbi(PORTB, BUZZ1); cbi(PORTB, BUZZ2); delay_ms(50); for(int i = 0 ; i < 500 ; i++) { cbi(PORTB, BUZZ1); sbi(PORTB, BUZZ2); delay_us(300); sbi(PORTB, BUZZ1); cbi(PORTB, BUZZ2); delay_us(300); } cbi(PORTB, BUZZ1); cbi(PORTB, BUZZ2); } void ioinit(void) { //1 = output, 0 = input DDRB = 0b11111111 & ~((1<<BUT_UP)|(1<<BUT_DOWN)|(1<<BUT_ALARM)); //Up, Down, Alarm switch DDRC = 0b11111111; DDRD = 0b11111111 & ~(1<<BUT_SNOOZE); //Snooze button PORTB = (1<<BUT_UP)|(1<<BUT_DOWN)|(1<<BUT_ALARM); //Enable pull-ups on these pins PORTD = (1<<BUT_SNOOZE); //Enable pull-up on snooze button PORTC = 0; //Init Timer0 for delay_us TCCR0B = (1<<CS01); //Set Prescaler to clk/8 : 1click = 0.5us(assume we are running at external 16MHz). CS01=1 //Init Timer1 for second counting TCCR1B = (1<<CS12)|(1<<CS10); //Set prescaler to clk/1024 :1click = 64us (assume we are running at 16MHz) TIMSK1 = (1<<TOIE1); //Enable overflow interrupts TCNT1 = 49911; //65536 - 15,625 = 49,911 - Preload timer 1 for 49,911 clicks. Should be 1s per ISR call //Init Timer2 for updating the display via interrupts TCCR2B = (1<<CS22)|(1<<CS21)|(1<<CS20); //Set prescalar to clk/1024 : 1 click = 64us (assume 16MHz) TIMSK2 = (1<<TOIE2); //TCNT2 should overflow every 16.384 ms (256 * 64us) } //General short delays void delay_ms(uint16_t x) { for (; x > 0 ; x--) { delay_us(250); delay_us(250); delay_us(250); delay_us(250); } } //General short delays void delay_us(uint16_t x) { x *= 2; //Correction for 16MHz while(x > 256) { TIFR0 = (1<<TOV0); //Clear any interrupt flags on Timer2 TCNT0 = 0; //256 - 125 = 131 : Preload timer 2 for x clicks. Should be 1us per click while( (TIFR0 & (1<<TOV0)) == 0); x -= 256; } TIFR0 = (1<<TOV0); //Clear any interrupt flags on Timer2 TCNT0 = 256 - x; //256 - 125 = 131 : Preload timer 2 for x clicks. Should be 1us per click while( (TIFR0 & (1<<TOV0)) == 0); }
C
#include "holberton.h" /** * _strspn - function that gets the length of a prefix substring. * @s: prefix string * @accept: returns number of bytes * Return: Always 0. */ unsigned int _strspn(char *s, char *accept) { unsigned int b, a = 0; while (s[a]) { b = 0; while (accept[b] && s[a] != accept[b]) b++; if (accept[b] == 0) return (a); a++; } return (a); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* int_handle_2.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: selbert <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/25 13:23:27 by selbert #+# #+# */ /* Updated: 2021/09/25 13:23:29 by selbert ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" int check_zero(int t, t_flag flag) { int words; char *out; words = 0; out = ft_itoa(t); if (t == 0 && (flag.pres_num == 0 || flag.after_dot == 0) && flag.pres == 1) { if (flag.left == 1 && flag.after_dot < 0) { write(1, out, ft_strlen(out)); words += ft_strlen(out); } if (flag.after_dot < 0 ) flag.before_dot = flag.before_dot - ft_strlen(out); words = ft_write(flag.before_dot, words, 1); if (flag.right == 1 && flag.after_dot < 0) { write(1, out, ft_strlen(out)); words += ft_strlen(out); } free(out); return (words); } free(out); return (-1); } int pls_work(t_flag flag, char *out) { int words; words = 0; if (flag.left == 1 && flag.pres == 1 && flag.int_minus == 1 && flag.zero == 0) { if (flag.zeros >= 0) { flag.spaces--; flag.zeros++; } words++; ft_putchar_fd('-', 1); while (flag.zeros-- > 0) { words++; ft_putchar_fd('0', 1); } write(1, out, ft_strlen(out)); words += (int)ft_strlen(out); words = ft_write(flag.spaces, words, 1); } return (words); } int words1(t_flag flag, int width, char *out) { int words; words = 0; if (flag.left == 1 && flag.pres == 0 && flag.zero == 0) { if (flag.int_minus == 1) { ft_putchar_fd('-', 1); words++; } write(1, out, ft_strlen(out)); words += (int)ft_strlen(out); while (flag.before_dot-- - width > 0) { ft_putchar_fd(' ', 1); words++; } } return (words); }
C
/** * @file Login.h * @author your name ([email protected]) * @brief Header file of login * @version 0.1 * @date 2021-04-07 * * @copyright Copyright (c) 2021 * */ /** * @brief User created header file * */ #include "HeaderFile.h" /** * @brief function for updating login details * */ int login(); /** * @brief function for checking login details * * @param username variable used to store username * @param password variable used to store password * @return true * @return false */ char user[](char usr[100],pwd[100]);
C
//Program to implement queue using two stacks #include <stdio.h> #define max 4 int stack1[max]; int stack2[max]; int top1 = -1; int top2 = -1; int gt; //Function to push the element into the stack1 void push1(int element){ if(top1==max-1){ printf("overflow"); }else{ stack1[++top1] = element; } gt = top1; return; } //Function to push the element into the stack2 void push2(int element){ if(top2==max-1){ printf("overflow"); }else{ stack2[++top2] = element; } return; } //Function to pop the element from the stack1 int pop1(){ int item; if(top1==-1){ printf("underflow"); return -1; }else{ item = stack1[top1--]; return item; } } int pop2(){ int item; if(top2==-1){ printf("underflow"); return -1; }else{ item = stack2[top2--]; return item; } } //Function to implement enqueue void insert(int element){ push1(element); } //Function to implement dequeue int delete(){ int element,i,lastElement; if(top2==-1){ if(top1==-1){ printf("Q is empty"); return -1; }else{ for(i=0;i<=gt;i++){ element = pop1(); push2(element); } } } lastElement = pop2(); return lastElement; } int main(){ insert(1); insert(2); insert(3); insert(4); int first = delete(); int second = delete(); int third = delete(); int fourth = delete(); printf("%d\n",first);//1 printf("%d\n",second);//2 printf("%d\n",third);//3 printf("%d\n",fourth); //4 }
C
/* * 1-19.c * * Created on: Sep 24, 2009 * Author: Abhijith */ #include<stdio.h> #define MAXLENGTH 1000 int getline(char line[], int lim); void reverse(char string[], char rev[]); int main() { char line[MAXLENGTH], rev[MAXLENGTH]; int len; while ((len = getline(line, MAXLENGTH)) > 0) { reverse(line, rev); printf("%s\n", rev); } return 0; } int getline(char string[], int lim) { int c, i; for ( i =0; (c = getchar()) != EOF && c != '\n' && c < lim - 1; ) string[i++] = c; if ( c == '\n') string[i++] = '\n'; string[i] = '\0'; return i; } void reverse(char string[], char reverse[]) { /* * 1. Traverse 'string' until null is reached * 2. Travel back until start, populating 'reverse' * 3. Insert a '\0' to terminate 'reverse' */ int i, j; for (i = 0; string[i] != '\0'; ++i) ; for ( j = 0; i > 0; ) reverse[j++] = string[--i]; reverse[j] = '\0'; }
C
/* Program name: Discount.c Author: Atish Jain Task: Calcualte Discount and Final amount */ # include <stdio.h> main() { int sales,dis,famt; sales=dis=famt=0; printf("Enter Sales Amount....:"); scanf("%d",&sales); if(sales>=25000) dis=sales*10/100; else dis=sales*5/100; famt=sales-dis; printf("\nDiscount is:%d",dis); printf("\nFinal Amount is:%d",famt); printf("\n"); }
C
/* ** Program-chaining function for Commodore platforms. ** ** This copy of the cc65 system library function makes smaller code by using ** Contiki's Personal File System (instead of POSIX) functions. ** ** 2016-03-16, Greg King ** ** This function exploits the program-chaining feature in CBM BASIC's ROM. ** ** CC65's CBM programs have a BASIC program stub. We start those programs by ** RUNning that stub; it SYSes to the Machine Language code. Normally, after ** the ML code exits, the BASIC ROM continues running the stub. But, it has ** no more statements; so, the program stops. ** ** This function puts the desired program's name and device number into a LOAD ** statement. Then, it points BASIC to that statement, so that the ROM will run ** that statement after this program quits. The ROM will load the next program, ** and will execute it (because the LOAD will be seen in a running program). */ #include <unistd.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <device.h> #include "cfs.h" /* The struct below is a line of BASIC code. It sits in the LOWCODE segment ** to make sure that it won't be hidden by a ROM when BASIC is re-enabled. ** The line is: ** 0 CLR:LOAD""+"" ,01 ** After this function has written into the line, it might look like this: ** 0 CLR:LOAD""+"program name" ,08 ** ** When BASIC's LOAD command asks the Kernal to load a file, it gives the ** Kernal a pointer to a file-name string. CC65's CBM programs use that ** pointer to give a copy of the program's name to main()'s argv[0] parameter. ** But, when BASIC uses a string literal that is in a program, it points ** directly to that literal -- in the models that don't use banked RAM ** (Pet/CBM, VIC-20, and 64). The literal is overwritten by the next program ** that is loaded. So, argv[0] would point to machine code. String operations ** create a new result string -- even when that operation changes nothing. The ** result is put in the string space at the top of BASIC's memory. So, the ""+ ** in this BASIC line guarantees that argv[0] will get a name from a safe place. */ #pragma data-name(push, "LOWCODE") static struct line { const char end_of_line; /* fake previous line */ const struct line* const next; const unsigned line_num; const char CLR_token, colon, LOAD_token, quotes[2], add_token, quote; char name[21]; const char comma; char unit[3]; } basic = { '\0', &basic + 1, /* high byte of link must be non-zero */ 0, 0x9C, ':', 0x93, "\"\"", 0xAA, '\"', "\" ", /* format: "123:1234567890123456\"" */ ',', "01" }; #pragma data-name(pop) /* These values are platform-specific. */ extern const void* vartab; /* points to BASIC program variables */ #pragma zpsym("vartab") extern const void* memsize; /* points to top of BASIC RAM */ #pragma zpsym("memsize") extern const struct line* txtptr; /* points to BASIC code */ #pragma zpsym("txtptr") extern char basbuf[]; /* BASIC's input buffer */ extern void basbuf_len[]; #pragma zpsym("basbuf_len") int __fastcall__ exec(const char *progname, const char *cmdline) { static int fd; static unsigned char dv, n; /* Exclude devices that can't load files. */ /* (Use hand optimization, to make smaller code.) */ dv = getcurrentdevice(); if(dv < 8 && __AX__ != 1 || __AX__ > 30) { return _mappederrno(9); /* illegal device number */ } utoa(dv, basic.unit, 10); /* Tape files can be openned only once; skip this test for the Datasette. */ if(dv != 1) { /* Don't try to run a program that can't be found. */ fd = cfs_open(progname, CFS_READ); if(fd < 0) { return -1; } cfs_close(fd); } n = 0; do { if((basic.name[n] = progname[n]) == '\0') { break; } } while(++n < 20); /* truncate long names */ basic.name[n] = '\"'; /* This next part isn't needed by machines that put ** BASIC source and variables in different RAM banks. */ #if !defined(__C128__) /* cc65 program loads might extend beyond the end of the RAM that is allowed ** for BASIC. Then, the LOAD statement would complain that it is "out of ** memory". Some pointers that say where to put BASIC program variables ** must be changed, so that we do not get that error. One pointer is ** changed here; a BASIC CLR statement changes the others. Some space is ** needed for the file-name string. Subtracting an entire RAM page allows ** better optimization of this expression. */ vartab = (char*)memsize - 0x0100; #endif /* Build the next program's argument list. */ basbuf[0] = 0x8F; /* REM token */ basbuf[1] = '\0'; if(cmdline != NULL) { strncat(basbuf, cmdline, (size_t)basbuf_len - 2); } /* Tell the ROM where to find that BASIC program. */ txtptr = &basic; /* (The return code, in ST [status], will be destroyed by LOAD. ** So, don't bother to set it here.) */ exit(__AX__); }
C
/* In our program's we'll need to make decisions. One of the easiest ways to do this in C is to use the "if statement". Here we provide a condition that the run time evaluates. If the condition is satisfied and evaluates to true, then the block of code associated with the statement is executed. If not, then the block is skipped. The basic syntax is as follows: if (expression) { // statement to be executed if expression is true. (the body) } // code execution resumes here If you have a single lined statement to execute after the if statement. The curly braces ca be omitted. For example: if (variable == true) printf("It's true!") Some coding styles do mandate that curly braces should ALWAYS be used (such as 1TBS) so use at your own discresion. Just remember that, if your single lined if statement grows in future, you'll need to add the curly braces to stop bugs! In addition to if statements, we have if-else statements! These dictate that, if the boolean condition in the if statement is not satisfied, then the code contained in the body of the else statement should be executed instead! It looks something like this: if(expression) { // statements to execute if above expression is satisfied. } else { // statements to be executed if the if statement evaluates to false. } */ #include <stdio.h> int main(void) { // No code here. Example is theory. printf("Hello World"); }
C
#include <stdio.h> #include <math.h> int isPrime(int n){ int i=2; int ret = 1; if(n<2) return 0; if(n==2) return 1; while(i<=(int)sqrt((double)n) && ret){ ret = !(n%i==0); i++; } return ret; } int main(){ unsigned long sum=0; int i; for(i=2; i<2000000; i++) sum += (isPrime(i)) ? i : 0; printf("%lu", sum); return 0; }
C
#include <stdlib.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <stdio.h> #include <ctype.h> #include <dirent.h> #include <sys/stat.h> #include <sys/types.h> #include <pthread.h> #include <errno.h> #include <math.h> #define BUFSIZE 256 pthread_t allThreads[100]; //stores the handles of all threads int tracker = -1; //tracks the total number of files/directories and threads at the same time pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; int dirTracker = -1; int threadTracker = -1; struct wordnode { char* name; int totalCount; double probability; struct wordnode *nextWord; }; struct filenode{ char* name; struct filenode *nextFile; struct wordnode *headWord; int wordcount; // pthread_t thread; int index; // int* trackerPtr; }; struct dirnode { char* name; }; struct filenode* headFile; struct filenode* prevFile; struct filenode files[100]; //stores the nodes of files struct dirnode directory[100]; //stores the nodes of directories /* function to swap data of two nodes a and b*/ void swap(struct filenode *a, struct filenode *b) { char* tempname = a->name; struct wordnode *tempheadWord = a->headWord; int tempwordcount = a->wordcount; a->name = b->name; a->headWord = b->headWord; a->wordcount = b->wordcount; b->name = tempname; b->headWord = tempheadWord; b->wordcount = tempwordcount; } void sortWordsInFile() { int swapped, i; struct filenode *ptr1; struct filenode *lptr = NULL; struct filenode *start = headFile; /* Checking for empty list */ if (start == NULL) return; do { swapped = 0; ptr1 = start; while (ptr1->nextFile != lptr) { if(ptr1->wordcount > ptr1->nextFile->wordcount) { swap(ptr1, ptr1->nextFile); swapped = 1; } ptr1 = ptr1->nextFile; } lptr = ptr1; } while (swapped); } void printFileArr() { int i = 0; struct filenode* fileTracker; fileTracker = headFile; while(fileTracker != NULL) { printf("%s ---> ", fileTracker->name); fileTracker = fileTracker->nextFile; if(fileTracker == NULL) break; } printf("NULL\n"); fileTracker = headFile; while(fileTracker != NULL) { printf("Words in %s: \n", fileTracker->name); struct wordnode *storetemphead = fileTracker->headWord; while(storetemphead != NULL) { printf("%s ---> ", storetemphead->name); storetemphead = storetemphead->nextWord; if(storetemphead == NULL) break; } printf("NULL\n"); fileTracker = fileTracker->nextFile; if(fileTracker == NULL) break; } } /*void findMeanDistribution() { struct filenode* fileTracker; struct wordnode* meanTracker; struct wordnode* wordTracker; fileTracker = headFile; while(fileTracker != NULL) { // for each file, compare every word in the file with every word in the mean distribution wordTracker = fileTracker->headWord; while(wordTracker != NULL) { if(meanhead == NULL) { meanhead = (struct wordnode*) malloc(sizeof(struct wordnode)); strcpy(meanhead->name, wordTracker->name); meanhead->probability = wordTracker->probability; meanTracker->nextWord = NULL; meanTracker = meanhead; } else { while(meanTracker != NULL) { if(strcmp(meanTracker->name, wordTracker->name) == 0) { meanTracker->probability = meanTracker->probability + wordTracker->probability; meanTracker->probability = meanTracker->probability/2; } meanTracker = meanTracker->nextWord; } } wordTracker = wordTracker->nextWord; if(wordTracker == NULL) break; } fileTracker = fileTracker->nextFile; if(fileTracker == NULL) break; } } */ void outputJensenShannon() { // for each file, compare it with every file after it struct filenode* fileTracker = headFile; while(fileTracker != NULL) { // loop for each file // printf("entered first loop\n"); printf("First file: %s\n", fileTracker->name); struct filenode* compareFile = fileTracker; struct filenode* secondaryFileTracker = compareFile->nextFile; // printf("secondary file assigned is first loop\n"); //comparing the file with every other file that comes after it in linked list while(secondaryFileTracker != NULL) { // loop to compare with files after it // printf("entered second loop\n"); // fill the linked list of mean distribution with first file printf("Second file: %s\n", secondaryFileTracker->name); struct wordnode* meanhead = (struct wordnode* ) malloc(sizeof(struct wordnode)); struct wordnode* meanTracker = meanhead; struct wordnode* compareTracker = fileTracker->headWord; while(compareTracker != NULL) { // printf( // printf("entered third loop\n"); meanTracker->name = (char *) malloc(sizeof(char*) * (int) strlen(compareTracker->name)); strcpy(meanTracker->name, compareTracker->name); printf("Word added to mean distribution list: %s\n", meanTracker->name); // printf("copied name in third loop\n"); meanTracker->probability = compareTracker->probability; if(compareTracker->nextWord == NULL) { // printf meanTracker->nextWord = NULL; break; } meanTracker->nextWord = (struct wordnode* ) malloc(sizeof(struct wordnode)); // printf("next assigned in third loop\n"); meanTracker = meanTracker->nextWord; compareTracker = compareTracker->nextWord; // printf("loop next roung in third loop\n"); } //Time to compare the two files now and update mean distribution linked list compareTracker = secondaryFileTracker->headWord; meanTracker = meanhead; // compare each word in the second file while(compareTracker != NULL) { // printf("entered third loop (b) \n"); // with each word in the first file while(meanTracker != NULL) { // printf("entered fourth loop\n"); // printf("mean tracker null? %d\n", meanTracker // if(meanTracker->name != NULL) // printf("Comparing %s and %s\n", meanTracker->name, compareTracker->name); if(meanTracker->name != NULL && strcmp(meanTracker->name, compareTracker->name) == 0) { // printf("same name\n"); // printf("%s and %s are same\n", meanTracker->name, compareTracker->name); meanTracker->probability = meanTracker->probability + compareTracker->probability; meanTracker->probability = meanTracker->probability/2; meanTracker = meanhead; break; } else if(meanTracker->nextWord == NULL) { // printf("adding at end\n"); meanTracker->nextWord = (struct wordnode* ) malloc(sizeof(struct wordnode)); meanTracker->nextWord->name = (char *) malloc(sizeof(char *) * (int) strlen(compareTracker->name)); strcpy(meanTracker->nextWord->name, compareTracker->name); meanTracker->probability = compareTracker->probability/2; // printf("%s was added at the end\n", meanTracker->nextWord->name); meanTracker->nextWord->nextWord = NULL; // printf("all right\n"); meanTracker = meanhead; break; } meanTracker = meanTracker->nextWord; } compareTracker = compareTracker->nextWord; } //find kld for first file compareTracker = fileTracker->headWord; double kld1 = 0.0; meanTracker = meanhead; while(compareTracker != NULL) { // printf("calculating kld1\n"); while(meanTracker != NULL) { if(strcmp(compareTracker->name, meanTracker->name) == 0) { kld1 += ((compareTracker->probability) * log(compareTracker->probability/meanTracker->probability)); break; } meanTracker = meanTracker->nextWord; } compareTracker = compareTracker->nextWord; } //find kld for second file compareTracker = secondaryFileTracker->headWord; double kld2 = 0.0; meanTracker = meanhead; while(compareTracker != NULL) { while(meanTracker != NULL) { if(strcmp(compareTracker->name, meanTracker->name) == 0) { kld1 += ((compareTracker->probability) * log(compareTracker->probability/meanTracker->probability)); break; } meanTracker = meanTracker->nextWord; } compareTracker = compareTracker->nextWord; } //find jensen shennon and output double jsd = (kld1 + kld2)/2; if(jsd <= 0.1) { printf("\033[0;31m"); printf("%f \"%s\" and \"%s\"\n", jsd, fileTracker->name, secondaryFileTracker->name); } else if(jsd > 0.1 && jsd <= 0.15) { printf("\033[0;33m"); printf("%f \"%s\" and \"%s\"\n", jsd, fileTracker->name, secondaryFileTracker->name); } else if(jsd > 0.15 && jsd <= 0.2) { printf("\033[0;32m"); printf("%f \"%s\" and \"%s\"\n", jsd, fileTracker->name, secondaryFileTracker->name); } else if(jsd > 0.2 && jsd <= 0.25) { printf("\033[0;36m"); printf("%f \"%s\" and \"%s\"\n", jsd, fileTracker->name, secondaryFileTracker->name); } else if(jsd > 0.25 && jsd <= 0.3) { printf("\033[0;34m"); printf("%f \"%s\" and \"%s\"\n", jsd, fileTracker->name, secondaryFileTracker->name); } else { printf("\033[0m"); printf("%f \"%s\" and \"%s\"\n", jsd, fileTracker->name, secondaryFileTracker->name); } secondaryFileTracker = secondaryFileTracker->nextFile; if(secondaryFileTracker == NULL) break; } fileTracker = fileTracker->nextFile; if(fileTracker == NULL) break; } } void *grow(struct filenode smt[100], int* capacityPTR) { //update capacity printf("growing\n"); return NULL; } void* handleFile(void* kmt) { pthread_mutex_lock(&lock); int numLoop = 0; struct filenode * funcArgs = (struct filenode *) kmt; char* name = funcArgs->name; printf("\n\n"); printf("inspecting %s\n", name); int fd = open(name, O_RDONLY); if (fd < 0) { perror(name); exit(EXIT_FAILURE); } char buf[BUFSIZE]; int bytes, pos; int filesize = 0; struct stat st; stat(name, &st); filesize = (int) st.st_size; char* buffer = (char *) malloc(sizeof(char) * filesize); char* buffercopy = (char *) malloc(sizeof(char) * filesize); bytes = read(fd, buffer, filesize); if(bytes < 0) printf("error\n"); buffercopy = strcpy(buffercopy, buffer); char* token = strtok(buffercopy, " \n\t\v\f\r"); int totalwords = 0; while(token != NULL) { totalwords++; token = strtok(NULL, " \n\t\r\v\f"); } funcArgs->wordcount = totalwords; token = strtok(buffer, " \n\t\v\f\r"); printf("total words in token: %d\n", totalwords); while(token != NULL) { if(funcArgs->headWord == NULL) { struct wordnode* storetemp = (struct wordnode* ) malloc(sizeof(struct wordnode)); storetemp->name = token; storetemp->totalCount = 1; storetemp->probability = (double) 1/(double) totalwords; storetemp->nextWord = NULL; funcArgs->headWord = storetemp; token = strtok(NULL, " \n\t\r\v\f"); continue; } struct wordnode* track; track = funcArgs->headWord; int found = 0; struct wordnode* tempNode = (struct wordnode*) malloc(sizeof(struct wordnode)); tempNode->name = token; tempNode->totalCount = 1; tempNode->probability = (double) 1/(double) totalwords; tempNode->nextWord = NULL; while(track->nextWord != NULL) { if(strcmp(track->name, token) == 0) { track->totalCount = track->totalCount + 1; track->probability = (double) track->totalCount/(double) totalwords; found = 1; break; } track = track->nextWord; if(track->nextWord == NULL) { if(strcmp(track->name, token) == 0) { track->totalCount = track->totalCount + 1; track->probability = (double) track->totalCount/(double) totalwords; found = 1; // break; } } } if(found != 1) { track->nextWord = tempNode; } token = strtok(NULL, " \n\t\r\v\f"); } struct wordnode* track; track = funcArgs->headWord; printf("File: %s\n", name); while(track != NULL) { printf("|_ Word: %s | Count: %d | Probability: %f _| ---> ", track->name, track->totalCount, track->probability); track = track->nextWord; } printf("NULL\n"); close(fd); pthread_mutex_unlock(&lock); } void* handleDir(void* kmt) { struct filenode * funcArgs = (struct filenode *) kmt; int numLoop = 0; char* name = funcArgs->name; printf("Handling: %s\n", name); printf("%s was added at %d\n", name, funcArgs->index); DIR *dirp = opendir(name); if(dirp != NULL) { struct dirent *dp; while((dp = readdir(dirp))) { if(dp->d_type == DT_REG) { pthread_mutex_lock(&lock); threadTracker++; tracker++; int totalLen = strlen(name) + 2 + strlen(dp->d_name); char* tempName = (char *) malloc(sizeof(char *) * totalLen); strcpy(tempName, name); strcat(tempName, "/"); strcat(tempName, dp->d_name); struct filenode* newNode = (struct filenode*) malloc(sizeof(struct filenode)); if(headFile == NULL) { newNode->name = (char *) malloc(sizeof(char *) * totalLen); strcpy(newNode->name, tempName); newNode->index = tracker; headFile = newNode; prevFile = newNode; } else { newNode->name = (char *) malloc(sizeof(char *) * totalLen); strcpy(newNode->name, tempName); newNode->index = tracker; prevFile->nextFile = newNode; prevFile = newNode; } /* files[tracker].name = (char *) malloc(sizeof(char *) * totalLen); strcpy(files[tracker].name, tempName); files[tracker].index = tracker; if(tracker != 0) files[tracker - 1].nextFile = &(files[tracker]); */ // files[tracker].trackerPtr = &tracker; pthread_create(allThreads+threadTracker, NULL, handleFile, newNode); printf("thread number %ld added to arr\n", *(allThreads+threadTracker)); pthread_mutex_unlock(&lock); } else if(dp->d_type == DT_DIR && strcmp(".", dp->d_name) != 0 && strcmp("..", dp->d_name) != 0) { pthread_mutex_lock(&lock); threadTracker++; dirTracker++; int totalLen = strlen(name) + 2 + strlen(dp->d_name); char* tempName = (char *) malloc(sizeof(char *) * totalLen); strcpy(tempName, name); strcat(tempName, "/"); strcat(tempName, dp->d_name); directory[dirTracker].name = (char *) malloc(sizeof(char *) * totalLen); strcpy(directory[dirTracker].name, tempName); pthread_create(allThreads+threadTracker, NULL, handleDir, &(directory[dirTracker])); printf("thread number %ld added to arr\n", *(allThreads+threadTracker)); pthread_mutex_unlock(&lock); } } } printf("handled: %s\n", name); closedir(dirp); } int main(int argc, char** argv) { if(argc != 2) { printf("Usage: %s file\n", argv[0]); exit(EXIT_FAILURE); } int capacity = 100; int* capacityPTR = &capacity; DIR *dirp = opendir(argv[1]); struct dirent *dp; if(dirp) { while((dp = readdir(dirp))) { /*if(tracker >= capacity) { grow(arr, capacityPTR); } */ if(dp->d_type == DT_REG) { pthread_mutex_lock(&lock); threadTracker++; tracker++; printf("Got a file: %s\n", dp->d_name); int totalLen = 9; totalLen += strlen(dp->d_name); char* tempName = (char *) malloc(sizeof(char *) * totalLen); tempName[0] = '.'; tempName[1] = '/'; strcat(tempName, argv[1]); strcat(tempName, "/"); strcat(tempName, dp->d_name); struct filenode* newNode = (struct filenode*) malloc(sizeof(struct filenode)); if(headFile == NULL) { newNode->name = (char *) malloc(sizeof(char *) * totalLen); strcpy(newNode->name, tempName); newNode->index = tracker; headFile = newNode; prevFile = newNode; } else { newNode->name = (char *) malloc(sizeof(char *) * totalLen); strcpy(newNode->name, tempName); newNode->index = tracker; prevFile->nextFile = newNode; prevFile = newNode; } // files[tracker].name = (char *) malloc(sizeof(char *) * totalLen); // strcpy(files[tracker].name, tempName); // files[tracker].index = tracker; // if(tracker != 0) // files[tracker - 1].nextFile = &(files[tracker]); // files[tracker].trackerPtr = &tracker; pthread_create(allThreads+threadTracker, NULL, handleFile, newNode); printf("thread number %ld added to arr\n", *(allThreads+threadTracker)); pthread_mutex_unlock(&lock); } else if(dp->d_type == DT_DIR && strcmp(".", dp->d_name) != 0 && strcmp("..", dp->d_name) != 0) { pthread_mutex_lock(&lock); threadTracker++; dirTracker++; printf("Got a dir: %s\n", dp->d_name); int totalLen = 9; totalLen += strlen(dp->d_name); char* tempName = (char *) malloc(sizeof(char *) * totalLen); tempName[0] = '.'; tempName[1] = '/'; strcat(tempName, argv[1]); strcat(tempName, "/"); strcat(tempName, dp->d_name); directory[dirTracker].name = (char *) malloc(sizeof(char *) * totalLen); strcpy(directory[dirTracker].name, tempName); pthread_create(allThreads+threadTracker, NULL, handleDir, &(directory[dirTracker])); printf("thread number %ld added to arr\n", *(allThreads+threadTracker)); pthread_mutex_unlock(&lock); } } } else if(ENOENT == errno) { printf("%s does not exist.\n", argv[1]); return EXIT_FAILURE; } else { printf("Opendir failed to open %s.\n", argv[1]); return EXIT_FAILURE; } int i = 0; for (i = 0; i <= threadTracker; ++i) { printf("Joining: %ld\n", allThreads[i]); pthread_join(allThreads[i], NULL); } printf("Threads: %d\n", threadTracker); printf("Directories: %d\n", dirTracker); printf("Files: %d\n", tracker); //printFileArr(); printf("Sorting files\n"); sortWordsInFile(); printf("Outputing jsd\n"); printFileArr(); outputJensenShannon(); closedir(dirp); return EXIT_SUCCESS; }
C
#include <stdio.h> int main(){ float a = 0, b = 0, c = 0, d = 0; scanf("%f %f %f %f", &a, &b, &c, &d); float x = 0; if(a <= b){ if(b > c){ x = (a + b + d) / 3; if(x >= 7){ printf("Aprovado com %.1f\n",x); }else{ printf("Final com %.1f\n",x); } }else{ x = (a + c + d) / 3; if(x >= 7){ printf("Aprovado com %.1f\n",x); }else{ printf("Final com %.1f\n",x); } } }else if(b >= c){ if(a >= c){ x = (b + a + d) / 3; if(x >= 7){ printf("Aprovado com %.1f\n",x); }else{ printf("Final com %.1f\n",x); } }else{ x = (b + c + d) / 3; if(x >= 7){ printf("Aprovado com %.1f\n",x); }else{ printf("Final com %.1f\n",x); } } }else if(c >= a){ if(a >= b){ x = (c + a + d) / 3; if(x >= 7){ printf("Aprovado com %.1f\n",x); }else{ printf("Final com %.1f\n",x); } }else{ x = (c + b + d) / 3; if(x >= 7){ printf("Aprovado com %.1f\n",x); }else{ printf("Final com %.1f\n",x); } } } }
C
#include <stdlib.h> #include <string.h> #include "files.h" #include "io.h" void add_to_file(FILE *file, char *string) { int exit_code = OK; char *word; while (!read_string(&word, file)) { read_string(&word, file); if (!strcmp(word, string)) exit_code = 1; free(word); } if (!exit_code) fprintf(file, "%s\n", string); } size_t file_size(FILE *file) { fseek(file, 0, SEEK_END); size_t size = ftell(file); fseek(file, 0, SEEK_SET); return size; }
C
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <limits.h> #include <pthread.h> #include <string.h> int producers; int consumers; int buff_size; int min_line_length; int max_work_time; int search_mode; int info_mode; char **buffer; pthread_mutex_t *buff_mutex; pthread_mutex_t prod_mutex; pthread_mutex_t cons_mutex; pthread_cond_t w_cond; pthread_cond_t r_cond; pthread_t *prod_thread; pthread_t *cons_thread; FILE *file; char * file_name; int last_prod_index = 0; int last_cons_index = 0; int is_writing_done = 0; void signal_processing(int signo); void init(char **argv) { producers = atoi(argv[1]); consumers = atoi(argv[2]); buff_size = atoi(argv[3]); // *buffer size file_name = argv[4]; min_line_length = atoi(argv[5]); // string minimum length search_mode = atoi(argv[6]); info_mode = atoi(argv[7]); max_work_time = atoi(argv[8]); // 0 - until file reading is finished or sig ctrl+c, 0< - secs signal(SIGINT, signal_processing); if (max_work_time > 0) signal(SIGALRM, signal_processing); if ((file = fopen(file_name, "r")) == NULL) {perror(file_name); exit(EXIT_FAILURE);} buffer = malloc((size_t) buff_size * sizeof(char *)); buff_mutex = malloc((buff_size) * sizeof(pthread_mutex_t)); for (int i = 0; i < buff_size; ++i){ pthread_mutex_init(&buff_mutex[i], NULL); buffer[i] = NULL; } pthread_mutex_init(&prod_mutex, NULL); pthread_mutex_init(&cons_mutex, NULL); pthread_cond_init(&w_cond, NULL); pthread_cond_init(&r_cond, NULL); } void finito_bonito() { if (file) fclose(file); for (int i = 0; i < buff_size; i++){ if (buffer[i]) free(buffer[i]); pthread_mutex_destroy(&buff_mutex[i]); } free(buffer); free(buff_mutex); pthread_mutex_destroy(&prod_mutex); pthread_mutex_destroy(&cons_mutex); pthread_cond_destroy(&w_cond); pthread_cond_destroy(&r_cond); } void signal_processing(int signo) { fprintf(stderr,"Sig: %d received. Stoping the program.\n", signo); for (int i = 0; i < producers; i++) pthread_cancel(prod_thread[i]); for (int i = 0; i < consumers; i++) pthread_cancel(cons_thread[i]); finito_bonito(); exit(EXIT_SUCCESS); } void *producer(void *pVoid) { int index; char line[LINE_MAX]; while (fgets(line, LINE_MAX, file) != NULL) { if(info_mode) fprintf(stderr, "P: %ld reading a line.\n", (long) pthread_self()); pthread_mutex_lock(&prod_mutex); while (buffer[last_prod_index] != NULL) pthread_cond_wait(&w_cond, &prod_mutex); index = last_prod_index; if(info_mode) fprintf(stderr, "P: %ld reading buff index (%d).\n", (long) pthread_self(), index); last_prod_index = (last_prod_index + 1) % buff_size; pthread_mutex_lock(&buff_mutex[index]); buffer[index] = malloc((strlen(line) + 1) * sizeof(char)); strcpy(buffer[index], line); if(info_mode) fprintf(stderr, "P: %ld line copied to buffer at index (%d).\n", (long) pthread_self(), index); pthread_cond_broadcast(&r_cond); pthread_mutex_unlock(&buff_mutex[index]); pthread_mutex_unlock(&prod_mutex); } if(info_mode) fprintf(stderr, "P: %ld the job is done.\n", (long) pthread_self()); return NULL; } void *consumer(void *pVoid) { char *line; int index; while (1) { pthread_mutex_lock(&cons_mutex); while (buffer[last_cons_index] == NULL) { if (is_writing_done) { pthread_mutex_unlock(&cons_mutex); if(info_mode) fprintf(stderr, "C: %ld the job is done. \n", (long) pthread_self()); return NULL; } pthread_cond_wait(&r_cond, &cons_mutex); } index = last_cons_index; if(info_mode) fprintf(stderr, "C: %ld reading buff index (%d).\n", (long) pthread_self(), index); last_cons_index = (last_cons_index + 1) % buff_size; pthread_mutex_lock(&buff_mutex[index]); pthread_mutex_unlock(&cons_mutex); line = buffer[index]; buffer[index] = NULL; if(info_mode) fprintf(stderr, "C: %ld taking line from buffer at index (%d).\n", (long) pthread_self(), index); pthread_cond_broadcast(&w_cond); pthread_mutex_unlock(&buff_mutex[index]); if(strlen(line) > min_line_length){ if(info_mode) fprintf(stderr, "C: %ld there is appropriate line with length %d %c %d.\n", (long) pthread_self(), (int) strlen(line), search_mode == 1 ? '>' : search_mode == -1 ? '<' : '=', min_line_length); fprintf(stderr, "%ld - \t%d\t- %s", (long) pthread_self(), index, line); } free(line); usleep(10); } } void start_threads() { prod_thread = malloc(producers * sizeof(pthread_t)); cons_thread = malloc(consumers * sizeof(pthread_t)); for (int i = 0; i < producers; i++) pthread_create(&prod_thread[i], NULL, producer, NULL); for (int i = 0; i < consumers; i++) pthread_create(&cons_thread[i], NULL, consumer, NULL); if (max_work_time > 0) alarm((unsigned int) max_work_time); for (int p = 0; p < producers; ++p) pthread_join(prod_thread[p], NULL); is_writing_done = 1; pthread_cond_broadcast(&r_cond); for (int k = 0; k < consumers; ++k) pthread_join(cons_thread[k], NULL); } int main(int argc, char **argv) { if (argc < 9){ fprintf(stderr, "Arguments goes: [producers] [consumers] [buff_size] [file_name] [min_line_length] [search_mode] [info_mode] [exec_max_time]"); exit(EXIT_FAILURE); } init(argv); start_threads(); // and wait for them finito_bonito(); return 0; }
C
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <netdb.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <signal.h> #include <time.h> FILE *dbg; int sockfd, visItsockfd[1024], address_len; socklen_t visIt_address_len; struct sockaddr_in address, visIt_address; char buf[512], visbuf[512]; char *buffer; ssize_t readlen; //static const int signum=SIGRTMIN+1; struct sigevent sigevent; int iter = 0; void handler(int signum) { printf("Hi I am handler\n"); if((readlen=(recv(visItsockfd[iter], buffer, 512, 0)))> 0) { // buf[readlen]='\0'; printf("%s\n", buffer); } } /* * Main program * * No Arguments * * // * Visualization site address * */ int main(int argc, char **argv) { // ***************** Variable Declaration ***** int flag=1, result; if(argc < 3) { printf("Missing argument \nUsage: ./server <total report time (in seconds)> <report frequency>"); exit(1); } int t_time = atoi(argv[1]); int wait = atoi(argv[2]); int numps = 1; // Create an endpoint for communication if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("server: socket error "); exit(1); } flag = 1; result = setsockopt(sockfd, /* socket affected */ IPPROTO_TCP, /* set option at TCP level */ TCP_NODELAY, /* name of option */ (char *) &flag, /* the cast is historical cruft */ sizeof(int)); /* length of option value */ //if (result < 0) //... handle the error ... // Fill socket structure with host information memset(&address, 0, sizeof(address)); address.sin_family = AF_INET; address.sin_port = htons(6666); //6633 if hop address.sin_addr.s_addr = INADDR_ANY; if (bind(sockfd, (struct sockaddr *) &address, sizeof(address)) == -1) { perror("server: bind error "); exit(1); } if (listen(sockfd, 5) == -1) { perror("server: listen error "); exit(1); } // signal(SIGIO, handler); visIt_address_len = sizeof(visIt_address); buffer = (char *)malloc(512*sizeof(char)); printf("waiting %d\n", iter); if ((visItsockfd[iter] = accept(sockfd, (struct sockaddr *) &visIt_address, &visIt_address_len)) == -1) { perror("server: accept error "); exit(1); } printf("client connected %d\n", visItsockfd[iter]); /* if((readlen=(recv(visItsockfd[iter], buffer, 512, 0)))> 0) printf("%s\n", buffer); if (readlen < 0) perror("Server recv error"); */ //sleep(180); const char *string[] = {"Hello", "Byebye"}; int i=-1, numbytes; time_t startTime = time(NULL); while(1) { if (time(NULL) - startTime < t_time) { //sleep(5); printf("\nSending %s to %d\n", string[0], visItsockfd[iter]); strcpy(buffer, string[0]); int len = strlen(buffer); buffer[len]='%'; //\n'; //if((numbytes = write(visItsockfd[iter], buffer, len+1)) <= 0) if((numbytes = send(visItsockfd[0], buffer, len+1, 0)) <= 0) perror("Server send error"); printf("\nSent %d %d bytes\n", len, numbytes); } else { printf("\nSending %s to %d\n", string[1], visItsockfd[iter]); strcpy(buffer, string[1]); int len = strlen(buffer); buffer[len]='%'; //\n'; //if((numbytes = write(visItsockfd[iter], buffer, len+1)) <= 0) if((numbytes = send(visItsockfd[0], buffer, len+1, 0)) <= 0) perror("Server send error"); printf("\nSent %d %d bytes\n", len, numbytes); break; } sleep(wait); } // Close connection close(sockfd); close(visItsockfd[iter]); return 0; }
C
//Bora Mutluoglu | bmutluog | 1564633 | cs12b | March 17, 2018 | //Dictionary.c implementation using hash tables instead of previously //used ADT/Linked Lists/BST implementations. #include<stdio.h> #include<stdlib.h> #include<string.h> #include<assert.h> #include"Dictionary.h" // private types, hash functions given by professor------------------------------- const int tableSize = 101; // rotate_left() // rotate the bits in an unsigned int unsigned int rotate_left(unsigned int value, int shift) { int sizeInBits = 8*sizeof(unsigned int); shift = shift & (sizeInBits - 1); if ( shift == 0 ) return value; return (value << shift) | (value >> (sizeInBits - shift)); } // pre_hash() // turn a string into an unsigned int unsigned int pre_hash(char* input) { unsigned int result = 0xBAE86554; while (*input) { result ^= *input++; result = rotate_left(result, 5); } return result; } // hash() // turns a string into an int in the range 0 to tableSize-1 int hash(char* key){ return pre_hash(key)%tableSize; } //private types------------------------------------------------------------------ // NodeObj typedef struct NodeObj{ char* key; char* value; struct NodeObj* next; } NodeObj; // Node typedef NodeObj* Node; // newNode() // constructor of the Node type Node newNode(char* k, char* v) { Node N = malloc(sizeof(NodeObj)); assert(N!= NULL); //allocate memory for the respective keys and values N->key = calloc(strlen(k)+1, sizeof(char)); N->value = calloc(strlen(v)+1, sizeof(char)); strcpy(N->key, k); strcpy(N->value, v); N->next = NULL; return(N); } // freeNode() // destructor for the Node type void freeNode(Node* pN){ if(pN != NULL && *pN != NULL){ Node N = *pN; free(N->key); free(N->value); free(*pN); *pN = NULL; } } // DictionaryObj typedef struct DictionaryObj{ Node* table; int numItems; }DictionaryObj; //find, used to find a key referene Node find(Dictionary D, char* k){ Node N = D->table[hash(k)]; while(N != NULL && strcmp(N->key, k) != 0) { N = N->next; } return N; } //recursively deletes and frees the nodes void deleteAll(Node N){ if( N != NULL ){ deleteAll(N->next); freeNode(&N); } } // public types --------------------------------------------------------------- // newDictionary() // constructor for the Dictionary type Dictionary newDictionary(void){ Dictionary D = malloc(sizeof(DictionaryObj)); assert(D != NULL); D->table = calloc(tableSize, sizeof(Node*)); D->numItems = 0; return D; } // freeDictionary() // destructor for the Dictionary type void freeDictionary(Dictionary* pD){ Dictionary D = *pD; if( pD != NULL && D != NULL ){ if(!isEmpty(D)){ makeEmpty(D); } for(int i = 0; i < tableSize; i++){ Node N = D->table[i]; while(N != NULL){ free(N); N = N->next; } free(D->table[i]); D->table[i] = NULL; } free(*pD); *pD = NULL; } } // isEmpty() // returns 1 (true) if S is empty, 0 (false) otherwise // pre: none int isEmpty(Dictionary D){ if( D == NULL){ fprintf(stderr, "Dictionary Error: calling isEmpty() on a NULL Dictionary reference\n"); exit(EXIT_FAILURE); } if (D->numItems == 0){ return 1; }else{ return 0; } } // size() // returns the number of (key, value) pairs in D // pre: none int size(Dictionary D){ if( D == NULL){ fprintf(stderr, "Dictionary Error: calling size() on a NULL Dictionary reference\n"); exit(EXIT_FAILURE); } return D->numItems; } // lookup() // returns the value v such that (k, v) is in D, or returns NULL if no // such value v exists. // pre: none char* lookup(Dictionary D, char* k){ if( D == NULL){ fprintf(stderr, "Dictionary Error: calling lookup() on a NULL Dictionary reference\n"); exit(EXIT_FAILURE); } Node N = find(D, k); if(N != NULL){ return N->value; }else{ return NULL; } } // insert() // inserts new (key,value) pair into D // pre: lookup(D, k)==NULL void insert(Dictionary D, char* k, char* v){ if( D==NULL ){ fprintf(stderr, "Dictionary Error: calling insert() on a NULL Dictionary reference\n"); exit(EXIT_FAILURE); } if( D->numItems > 0 && lookup(D, k) != NULL){ fprintf(stderr, "Dictionary Error: cannot insert duplicate keys."); exit(EXIT_FAILURE); } else if(D->table[hash(k)] == NULL){ Node N = newNode(k, v); D->table[hash(k)] = N; D->numItems++; } else{ Node N = D->table[hash(k)]; while(N->next != NULL){ N = N->next; } N->next = newNode(k,v); D->numItems++; } } // delete() // deletes pair with the key k // pre: lookup(D, k)!=NULL void delete(Dictionary D, char* k){ if( D == NULL ){ fprintf(stderr, "Dictionary Error: calling delete() on a NULL Dictionary reference\n"); exit(EXIT_FAILURE); } if( D->numItems == 0 ){ fprintf(stderr, "Dictionary Error: calling delete() on an empty Dictionary\n"); exit(EXIT_FAILURE); } Node N = find(D, k); if(D->table[hash(k)] != NULL && D->table[hash(k)]->next == NULL){ freeNode(&N); D->table[hash(k)] = NULL; D->numItems--; } else if(lookup(D,k) != NULL && N == D->table[hash(k)]){ D->table[hash(k)] = N->next; freeNode(&N); D->numItems--; } else{ Node N = D->table[hash(k)]; while(N->next != NULL && strcmp(N->next->key, k) != 0) { N = N->next; } Node P = N; P->next = N->next; freeNode(&N); D->numItems--; } } // makeEmpty() // re-sets D to the empty state. // pre: none void makeEmpty(Dictionary D){ if( D == NULL ){ fprintf(stderr, "Dictionary Error: calling makeEmpty() on a NULL Dictionary reference\n"); exit(EXIT_FAILURE); } for(int i = 0; i < tableSize; i++){ deleteAll(D->table[i]); D->table[i] = NULL; } D->numItems = 0; } // printDictionary() // pre: none // prints a text representation of D to the file pointed to by out void printDictionary(FILE* out, Dictionary D){ if( D == NULL ){ fprintf(stderr, "Dictionary Error: calling printDictionary() on a NULL Dictionary reference\n"); exit(EXIT_FAILURE); } Node N; for(int i = 0; i < tableSize; i++){ N = D->table[i]; while(N != NULL){ fprintf(out, "%s %s \n" , N->key, N->value); N = N->next; } } }
C
typedef struct { school data; struct node * right, * left; }node ; //insert void insert(node ** tree, school val) { node *temp = NULL; if(!(*tree)) { temp = (node *)malloc(sizeof(node)); temp->left = temp->right = NULL; temp->data = val; *tree = temp; return; } if(val.code < (*tree)->data.code) { insert(&(*tree)->left, val); } else if(val.code > (*tree)->data.code) { insert(&(*tree)->right, val); } } void print_preorder(node * tree) { if (tree) { printschool(tree); print_preorder(tree->left); print_preorder(tree->right); } } void print_inorder(node * tree) { if (tree) { print_inorder(tree->left); printschool(tree); print_inorder(tree->right); } } void print_postorder(node * tree) { if (tree) { print_postorder(tree->left); print_postorder(tree->right); printschool(tree); } } void printschool(node * tree) { printf("\nCode:%d\n",tree->data.code); printf("Ballot Boxes: %d\n",tree->data.cantboxes); } //delete whole tree void deltree(node * tree) { if (tree) { deltree(tree->left); deltree(tree->right); free(tree); } } //search a school and returns it node* search(node ** tree, school val) { if(!(*tree)) { return NULL; } if(val.code < (*tree)->data.code) { search(&((*tree)->left), val); } else if(val.code > (*tree)->data.code) { search(&((*tree)->right), val); } else if(val.code == (*tree)->data.code) { return *tree; } }
C
#include <linux/module.h> #include <linux/fs.h> #include <linux/poll.h> #include <linux/errno.h> #include <linux/debugfs.h> #include <linux/jiffies.h> #include <linux/semaphore.h> #define EUDYPTULA_ID "123456789012\n" #define EUDYPTULA_ID_SIZE 13 /* EUDYPTULA_ID length */ MODULE_LICENSE("GPL"); MODULE_AUTHOR("EK"); MODULE_DESCRIPTION("Eudyptula Challenge Task 8 - Debugfs module"); static DEFINE_SEMAPHORE(foo_sem); static char foo_data[PAGE_SIZE]; static int foo_len; static struct dentry *eudy; static ssize_t foo_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { int retval = -EINVAL; if (*ppos != 0) return 0; down(&foo_sem); if (!copy_to_user(buf, foo_data, foo_len)) { *ppos += count; retval = count; } up(&foo_sem); return retval; } static ssize_t foo_write(struct file *file, char const __user *buf, size_t count, loff_t *ppos) { int retval = -EINVAL; if (count >= PAGE_SIZE) return -EINVAL; down(&foo_sem); if (copy_from_user(foo_data, buf, count)) { foo_len = 0; } else { foo_len = count; retval = count; } up(&foo_sem); return retval; } static const struct file_operations foo_fops = { .owner = THIS_MODULE, .read = foo_read, .write = foo_write }; static ssize_t id_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { char *hello_str = EUDYPTULA_ID; if (*ppos != 0) return 0; if ((count < EUDYPTULA_ID_SIZE) || (copy_to_user(buf, hello_str, EUDYPTULA_ID_SIZE))) return -EINVAL; *ppos += count; return count; } static ssize_t id_write(struct file *file, char const __user *buf, size_t count, loff_t *ppos) { char *hello_str = EUDYPTULA_ID; char input[EUDYPTULA_ID_SIZE]; if ((count != EUDYPTULA_ID_SIZE) || (copy_from_user(input, buf, EUDYPTULA_ID_SIZE)) || (strncmp(hello_str, input, EUDYPTULA_ID_SIZE))) return -EINVAL; else return count; } static const struct file_operations id_fops = { .owner = THIS_MODULE, .read = id_read, .write = id_write }; static int __init hello_init(void) { eudy = debugfs_create_dir("eudyptula", NULL); if (!eudy) goto fail; if (!debugfs_create_file("foo", 0644, eudy, NULL, &foo_fops)) goto fail; if (!debugfs_create_u32("jiffies", 0444, eudy, (u32*)&jiffies)) goto fail; if (!debugfs_create_file("id", 0666, eudy, NULL, &id_fops)) goto fail; pr_debug("Hello World!\n"); foo_len = 0; return 0; fail: pr_alert("Could not create devices"); return -ENODEV; } static void __exit hello_exit(void) { debugfs_remove_recursive(eudy); } module_init(hello_init); module_exit(hello_exit);
C
/** * *leet - function that encodes a string into 1337 * @str: string for encryption * Return: string encrypted */ char *leet(char *str) { char letter_lower[6] = {'a', 'e', 'o', 't', 'l'}; char letter_uper[6] = {'A', 'E', 'O', 'T', 'L'}; char code[6] = {'4', '3', '0', '7', '1'}; int i, j; for (i = 0; str[i] != '\0'; i++) { for (j = 0; j < 6; j++) { if (str[i] == letter_lower[j] || str[i] == letter_uper[j]) { str[i] = code[j]; } } } return (str); }
C
#include "header.h" static gboolean change_password_and_all_encryption(const gchar* old_pwd_entry, const gchar* new_pwd_entry); /* We call init_option_window() when our program is starting to load option window with references to Glade file. */ gboolean init_option_window() { GtkBuilder *builder; GError *err=NULL; /* use GtkBuilder to build our interface from the XML file */ builder = gtk_builder_new (); if (gtk_builder_add_from_file (builder, UI_GLADE_FILE, &err) == 0) { error_message (err->message); g_error_free (err); return FALSE; } /* get the widgets which will be referenced in callbacks */ optionwindow->window = GTK_WIDGET (gtk_builder_get_object (builder, "option_window")); optionwindow->old_entry = GTK_WIDGET (gtk_builder_get_object (builder, "option_old_entry")); optionwindow->new_entry = GTK_WIDGET (gtk_builder_get_object (builder, "option_new_entry")); optionwindow->confirm_entry = GTK_WIDGET (gtk_builder_get_object (builder, "option_confirm_entry")); gtk_builder_connect_signals (builder, optionwindow); g_object_unref(G_OBJECT(builder)); return TRUE; } /* Callback for Ok button in option window */ void on_option_ok_button_clicked() { const gchar *new_pwd_entry, *confirm_pwd_entry, *old_pwd_entry, *old_pwd_in_passwordwindow; /*read text entry*/ old_pwd_in_passwordwindow = gtk_entry_get_text(GTK_ENTRY(passwordwindow->text_entry)); old_pwd_entry = gtk_entry_get_text(GTK_ENTRY(optionwindow->old_entry)); new_pwd_entry = gtk_entry_get_text(GTK_ENTRY(optionwindow->new_entry)); confirm_pwd_entry = gtk_entry_get_text(GTK_ENTRY(optionwindow->confirm_entry)); /*make sure text entry is not empty*/ if(strcmp(new_pwd_entry,"") && strcmp(confirm_pwd_entry,"") && strcmp(old_pwd_entry, "")) { /*make sure entered old password same with current password*/ if(!strcmp(old_pwd_entry, old_pwd_in_passwordwindow)) { /*make sure new password and confirmed password is same*/ if(!strcmp(new_pwd_entry, confirm_pwd_entry)) { if(change_password_and_all_encryption(old_pwd_entry,new_pwd_entry) == FALSE) { error_message("failed to change password"); gtk_main_quit(); } else { notification_message("Password Changed! Restart application!"); gtk_main_quit(); } } else error_message("new password and confirm password field must be same"); } else error_message("wrong password!"); } else error_message("Field can not empty"); } /* Callback for Cancel button in option window */ void on_option_cancel_button_clicked() { /*open main menu window only*/ Bitwise WindowSwitcherFlag; f_status_window = FALSE; f_mainmenu_window = TRUE; WindowSwitcher(WindowSwitcherFlag); } static gboolean change_password_and_all_encryption(const gchar* old_pwd_entry, const gchar* new_pwd_entry) { int i=0; char hashed[(SHA256_DIGEST_LENGTH*2)+1]; //~ uintmax_t ACCN; gchar ACCNstr[32]; //~ ACCN = get_ACCN(ACCNstr); get_ACCN(ACCNstr); /*=================*/ /*hash new password*/ /*=================*/ passwordhashing(hashed, new_pwd_entry, ACCNstr); /*==================*/ /*change key wrapper*/ /*==================*/ unsigned char aes_key[KEY_LEN_BYTE]; memset(aes_key,0,KEY_LEN_BYTE); getTransKey(aes_key, old_pwd_entry, ACCNstr, FALSE); unsigned char KeyEncryptionKey[KEY_LEN_BYTE]; unsigned char wrapped_key[KEY_LEN_BYTE+8]; /* derive key from password + ACCN */ if(derive_key(KeyEncryptionKey, new_pwd_entry, ACCNstr, 10000) == FALSE) { error_message("KEK derivation error"); return FALSE; } #ifdef DEBUG_MODE print_array_inHex("derived key:", KeyEncryptionKey, KEY_LEN_BYTE); #endif /* wrap key using KEK */ if(wrap_aes_key(wrapped_key, KeyEncryptionKey, aes_key) == FALSE) { error_message("error wrapping key"); return FALSE; } #ifdef DEBUG_MODE print_array_inHex("wrapped key:", wrapped_key, KEY_LEN_BYTE+8); #endif /*====================*/ /*change encrypted log*/ /*====================*/ int logged_transaction = logNum(); if(logged_transaction) { int logLen; unsigned char oldLogKey[32]; memset(oldLogKey,0,32); unsigned char newLogKey[32]; memset(newLogKey,0,32); unsigned char logToWrite[logged_transaction][48]; memset(logToWrite,0,sizeof(logToWrite)); if(derive_key(oldLogKey, old_pwd_entry, ACCNstr, 9000)==FALSE) { error_message("error deriving old log key"); return FALSE; } if(derive_key(newLogKey, new_pwd_entry, ACCNstr, 9000)==FALSE) { error_message("error deriving new log key"); return FALSE; } for(i=1;i<=logged_transaction;i++) { unsigned char fromDB[96]; memset(fromDB,0,96); logLen = read_log_blob(fromDB,i); if(logLen == 96) { unsigned char fromDBbyte[48]; memset(fromDBbyte,0,48); hexstrToBinArr(fromDBbyte,(gchar*)fromDB,48); unsigned char logDecrypted[32]; memset(logDecrypted,0,32); unsigned char IV[16]; memset(IV,0,16); memcpy(IV, fromDBbyte+32, 16); aes256cbc(logDecrypted, fromDBbyte, oldLogKey, IV, "DECRYPT"); unsigned char logEncrypted[32]; memset(logEncrypted,0,32); unsigned char newIV[16]; //, iv_dec[AES_BLOCK_SIZE]; RAND_bytes(newIV, 16); memcpy((logToWrite[i-1])+32,newIV,16); aes256cbc(logEncrypted, logDecrypted, newLogKey, newIV, "ENCRYPT"); memcpy(logToWrite[i-1],logEncrypted,32); #ifdef DEBUG_MODE print_array_inHex("old log:", fromDBbyte, 48); print_array_inHex("new log:", logToWrite[i-1], 48); #endif } else return FALSE; } /*=================*/ /* Write log to DB */ /*=================*/ for(i=0;i<logged_transaction;i++) { int j = 0; char logToWriteInStr[97]; memset(logToWriteInStr,0,97); //NULL in index 96 for(j = 0; j<48; j++) { sprintf(&logToWriteInStr[j*2], "%02X", logToWrite[i][j]); } #ifdef DEBUG_MODE printf("new log %d: %s\n",i+1,logToWriteInStr); #endif update_encrypted_log(logToWriteInStr, i+1); } } /*=======================================*/ /* Write trans key to config (in Base64) */ /*=======================================*/ char *wrapped_base64 = base64(wrapped_key, KEY_LEN_BYTE+8); printf("wrapped key to write: %s\n\n",wrapped_base64); write_string_to_config(wrapped_base64,"security.transaction"); /*=================================*/ /* Write hashed password to config */ /*=================================*/ write_string_to_config(hashed,"application.Pwd"); return TRUE; }
C
#include <stdio.h> #define NUMBER 5 // 对元素个数为n的int型数组v进行倒序排列 void rev_intary(int v[], int n) { int temp; for (int i = 0; i < n / 2; ++i) { temp = v[i]; v[i] = v[n - i - 1]; v[n - i - 1] = temp; } } int main(void) { int i; int vx[NUMBER]; for (i = 0; i < NUMBER; ++i) { printf("vx[%d]: ", i); scanf("%d", &vx[i]); } rev_intary(vx, NUMBER); puts("倒序为:"); for (i = 0; i < NUMBER; ++i) { printf("%d ", vx[i]); } printf("\n"); return 0; }
C
#include <linux/sort.h> #include <linux/slab.h> /*sort utilization from highest to lowest*/ static int util_sort(const void* l, const void* r){ struct subtask sub1=*(struct subtask*)(l); struct subtask sub2=*(struct subtask*)(r); if(sub1->utilization>sub2->utilization) return -1; else if(sub1->utilization<sub2->utilization) return 1; else return 0; } /*sort relative ddl from earliest to latest, so get priority from highest to lowest*/ static int ddl_sort(const void* l, const void* r){ struct subtask sub1=*(struct subtask*)(l); struct subtask sub2=*(struct subtask*)(r); if(sub1->relative_ddl<sub2->relative_ddl) return -1; else if(sub1->relative_ddl>sub2->relative_ddl) return 1; else return 0; } void initALL(void){ int i,j; int index=0; struct task* taskNow; struct subtask* subtaskNow; int cpuLoad[num_core]={0,0,0,0}; int cpuCount[num_core]={0,0,0,0}; ktime_t total_exec_time; for (i=0;i<num_task;i++){ taskNow=tasks[i]; total_exec_time=0; for (j=0;j<tasks[i]->num;j++){ subtaskNow= taskNow->subtask_list[j]; subtaskNow->parent=taskNow; total_exec_time=total_exec_time+subtaskNow->execution_time; subtaskNow->cumul_exec_time=total_exec_time; subtaskNow->hr_timer=kmalloc(sizeof(struct hrtimer),GFP_KERNEL); subtasks[index]=subtaskNow; index+=1; } tasks[i]->execution_time=total_exec_time; for (j=0;j<tasks[i]->num;j++){ taskNow->subtask_list[j]->relative_ddl=(taskNow->period)*(taskNow->subtask_list[j]->cumul_exec_time)/tasks[i]->execution_time; } } //todo: sort subtask based on utilization from largest to smallest sort((void*)subtasks,num_subtask,sizeof(struct subtask*),&util_sort,NULL); for (i=0;i<num_subtask;i++){ for(j=0;j<num_core;j++){ if(cpuLoad[j]+subtasks[i]->utilization<100){ cpuLoad[j]+=subtasks[i]->utilization; subtasks[i]->core=j; cpuCount[j]+=1; subtasks[i]->flag=TRUE; break; } } //if the subtask can't fit into any core, assign it to core 3 and mark it as being not assumed to be schedulable.. if(subtasks[i]->core<0){ cpuLoad[3]+=subtasks[i]->utilization; subtasks[i]->core=3; cpuCount[3]+=1; subtasks[i]->flag=FALSE; } } for (i=0;i<num_core;i++){ cores[i]->num=cpuCount[i]; //todo: sort subtask based on relative ddl from earliest to latest sort((void*)(cores[i]->subtask_list),cpuCount[i],sizeof(struct subtask*),&ddl_sort,NULL); for(j=0;j<cpuCount[i];j++){ subtaskNow=cores[i]->subtask_list[j]; subtaskNow->priority=HIGHEST_PRIORITY-(j*2+10); } } }
C
/* 線形リストの利用例 */ #include <stdio.h> #include "Member.h" #include "LinkedList.h" /* メニュー */ typedef enum { TERMINATE, INS_FRONT, INS_REAR, RMV_FRONT, RMV_REAR, PRINT_CRNT, RMV_CRNT, SRCH_NO, SRCH_NAME, PRINT_ALL, CLEAR } Menu; /* メニュー選択 */ Menu SelectMenu(void) { int i, ch; char *mstring[] = { "先頭にノードを挿入", "末尾にノードを挿入", "先頭のノードを削除", "末尾のノードを削除", "着目ノードを表示", "着目ノードを削除", "番号で探索", "氏名で探索", "全ノードを表示", "全ノードを削除" }; do { for (i = TERMINATE; i < CLEAR; i++) { printf("(%2d)%-18.18s ", i + 1, mstring[i]); if ((i % 3) == 2)/* iは0から始まるから、余りが2=改行して4つ目 */ putchar('\n'); } printf("( 0)終了 :"); scanf("%d", &ch); } while (ch < TERMINATE || ch > CLEAR); return (Menu)ch; } /* メイン */ int main(void) { Menu menu; List list; Initialize(&list); /* 線形リストの初期化 */ do { Member x; switch (menu = SelectMenu()){ /* 先頭にノードを挿入 */ case INS_FRONT: x = ScanMember("先頭に挿入", MEMBER_NO | MEMBER_NAME); InsertFront(&list, &x); break; /* 末尾にノードを挿入 */ case INS_REAR: x = ScanMember("末尾に挿入", MEMBER_NO | MEMBER_NAME); InsertRear(&list, &x); break; /* 先頭ノードを削除 */ case RMV_FRONT: RemoveFront(&list); break; /* 末尾ノードを削除 */ case RMV_REAR: RemoveRear(&list); break; /* 着目ノードのデータを表示 */ case PRINT_CRNT: PrintLnCurrent(&list); break; /* 着目ノードを削除 */ case RMV_CRNT: RemoveCurrent(&list); break; /* 番号による探索 */ case SRCH_NO: x = ScanMember("探索", MEMBER_NO); if (Search(&list, &x, MemberNoCmp) != NULL) PrintLnCurrent(&list); else puts("その番号のデータはありません。"); break; /* 氏名による探索 */ case SRCH_NAME: x = ScanMember("探索", MEMBER_NAME); if (Search(&list, &x, MemberNameCmp) != NULL) PrintLnCurrent(&list); else puts("その名前のデータはありません。"); break; /* 全ノードのデータを表示 */ case PRINT_ALL: Print(&list); break; /* 全ノードを削除 */ case CLEAR: Clear(&list); break; default: break; } } while (menu != TERMINATE); Terminate(&list); return 0; }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #include <errno.h> #include "chop_line.h" #include "list.h" void watchBgProcesses(list_t* bg_pids_list){ struct list_node_t* node = bg_pids_list->head; while(node != NULL){ int status = 0; int pid = node->val; node = node->next; //If waitpid returns 0, no children have changed state and the status variable is meaningless if(waitpid(pid, &status, WNOHANG) == 0) continue; if(WIFEXITED(status)){ list_remove_val(bg_pids_list, pid); } //else, not the process hasn't ended yet } } void cleanup(list_t* bg_pids_list){ if(bg_pids_list->size == 0) exit(0); //Wait for all background processes to finish while(bg_pids_list->size > 0){ watchBgProcesses(bg_pids_list); } exit(0); } char* getRawCmd(list_t* bg_pids_list){ size_t buff_size = 256; size_t char_index = 0; char *buffer = (char *) malloc(buff_size); char c; while((c = getchar()) != '\n'){ if(c == EOF) cleanup(bg_pids_list); buffer[char_index] = c; char_index++; if(char_index >= buff_size){ buff_size *= 2; buffer = (char *) realloc(buffer, buff_size); } } buffer[char_index] = '\0'; return buffer; } //Returns 0 on success int executeCmd(char *argv[], int is_background, list_t* bg_pids_list){ //Exit if(strcmp(argv[0], "exit") == 0){ cleanup(bg_pids_list); } //Fork returns zero in child int pid = fork(); if(pid){ int status; if(is_background){ list_insert_val(bg_pids_list, pid); } else{ waitpid(pid, &status, 0); } } else{ if(execvp(argv[0], argv) == -1){ int errsv = errno; printf("execvp(): %s\n", strerror(errsv)); fflush(stdout); return 1; } } return 0; } int main(int argc, char *argv[]){ list_t* bg_pids_list = list_create(); while(1){ watchBgProcesses(bg_pids_list); printf("mysh: "); fflush(stdout); char* raw_cmd = getRawCmd(bg_pids_list); chopped_line_t* chop_cmd = get_chopped_line(raw_cmd); free(raw_cmd); //No command was entered if(chop_cmd->num_tokens < 1) continue; int i; int cmd_valid = 1; int is_background = 0; char* args[chop_cmd->num_tokens + 1]; int arg_index = 0; for(i = 0; i < chop_cmd->num_tokens; i++){ char* curr_token = chop_cmd->tokens[i]; //strcmp returns 0 if strings are equal if(strcmp(curr_token, "&") != 0){ args[arg_index] = curr_token; arg_index++; } else if(i != (chop_cmd->num_tokens - 1)){ //& is not the last token, error printf("Operator & must appear at end of command line"); fflush(stdout); cmd_valid = 0; break; } else{ is_background = 1; } } free_chopped_line(chop_cmd); if(!cmd_valid) { continue; } args[arg_index] = NULL; if(executeCmd(args, is_background, bg_pids_list) != 0) return 1; fflush(stdout); } return 0; }
C
/* Cell Plan Kyle George 1-15-2020 */ #include <stdio.h> //Calculate a rate given an amount of data and an amount of time. double calculateRateOfUse(int days, int amount) { return (double)amount/(double)days; } //Executable Code int main(void) { //Variable Definitions int totalGigs = 0; //Amount of data the user can use int currentDay = 0; //Number of days since the start of the period (1-30) int usedGigs = 0; //Amount of data already used //Gather Input from user printf("Enter Total GB in your plan: "); scanf("%d", &totalGigs); printf("Enter GB Used in since the start of the period: "); scanf("%d", &usedGigs); printf("Enter days since start of period: "); scanf("%d", &currentDay); //Calculate values used in program double usedRate = calculateRateOfUse(currentDay, usedGigs); double desiredRate = calculateRateOfUse(30, totalGigs); double changedRate = calculateRateOfUse(30 - currentDay, totalGigs-usedGigs); //Display to user. Display differs if the user's rate is above, at, or below what it should be. printf("\n%d days used. %d days remaining.\nAverage daily use %.2f GB/Day\n\n", currentDay, 30-currentDay, usedRate); if(usedRate > desiredRate) { //Execute if the user is using too much data. int excededData = usedRate * 30 - totalGigs; //Calculate the amount by which the user would excede the data cap. printf("You are EXCEDING your average daily use (%.2f).\n", desiredRate); printf("Continuing this usage, you'll exceed your data plan by %d GB.\n", excededData); printf("\n"); printf("To stay below you data plan, use no more than %.2f GB/day.\n", changedRate); } else if (usedRate < desiredRate) { //Execute if the user is using less data than available. int remainingData = totalGigs - usedRate * 30; //Calculate the amount of data the user will have at the end of period. printf("You are UNDER your average daily use (%.2f).\n", desiredRate); printf("Continuing this usage, you'll have %d GB extra data.\n", (int)(totalGigs-usedRate*30)); printf("**Remaining data does not carry over into the next period.**\n"); printf("\nYou may continue to use %.2f GB/day and remain under your limit.\n", changedRate); } else { //Execute if the user is using exactly the correct amount of data. printf("You are EQUAL TO your average daily use (%.2f).\n", desiredRate); printf("Continuing at this usage, you will use all available data\n"); } return 0; } /* Tested Data Sets Inputs: (Total = 15, Used = 13 Days = 10) Expected Outputs: (Avg Daily = 1.3, Excess GB = 24, Future Rate = 0.1) Outputs: (Avg Daily = 1.30, Excess GB = 24, Future Rate = 0.10) Inputs: (Total = 35, Used = 5, Days = 17) Expected Outputs: (Avg Daily = .29, Remaining GB = 26, Future Rate = 2.31) Outputs: (Avg Daily = .29, Remaining GB = 26, Future Rate = 2.31) Inputs: (Total = 10, Used = 5, Days = 15) Expected Outputs: (Avg Daily = .33, Remaining GB = 0, Future Rate = .33) Outputs: (Avg Daily = .33, Remaining GB = 0, Future Rate = .33) Test data sets were gathered via calculations done by my own calculator. */
C
#define UNUSED(x) x __attribute__ ((unused)) #include <string.h> #include <unistd.h> #include <sys/wait.h> #include "interface.h" #include "lib/lib.h" // Storing executable path char exec_path[1024]; size_t exec_path_len; int load_commands(char UNUSED(*dir_name)) { if(!getcwd(exec_path, 1024)) { printf("Error getting current working directory\n"); return -1; } exec_path_len = strlen(exec_path); exec_path[exec_path_len++] = '/'; return 0; } void unload_commands() { } int _exec(int argc, char *argv[]); Command getfunc(char *name) { strcpy(exec_path+exec_path_len, name); if(access(exec_path, X_OK) == -1) // Checking file existence & X permissions return exec_func; return _exec; } // Execute ./argv[0] int _exec(int argc __attribute__((unused)), char *argv[]) { strcpy(exec_path+exec_path_len, argv[0]); argv[0]=exec_path; return execv(argv[0], argv); }
C
#include <unistd.h> #include <stdio.h> #include <string.h> #include <stdlib.h> int main() { int pipe_fd[2]; pid_t pid; int ret = 0; char r_buf[4]; char w_buf[4]; ret = pipe(pipe_fd); if (ret < 0) printf("pipe fail\n"); memset(r_buf, 0, sizeof(r_buf)); memset(w_buf, 0, sizeof(w_buf)); pid = fork(); if (pid == 0) { close(pipe_fd[0]); close(pipe_fd[1]); sleep(10); exit(0); } else if (pid > 0) { sleep(1); //wait child close pipe close(pipe_fd[0]); strcpy(w_buf, "111"); ret = write(pipe_fd[1], w_buf, 4); if (ret < 0) printf("write fail\n"); else printf("the bytes write to pipe is %d\n", ret); close(pipe_fd[1]); } else { printf("fork fail\n"); } return 0; } /* *对管道写规则验证:写端对读端存在依赖性 *只用在管道的读端存在时,向管道中写入数据才有意义,否则向管道中写入数据的进程将收到SIFPIPE信号,应用程序可以处理该信号,也可以忽略(默认动作是应用程序终止) */
C
#include<stdio.h> #include<malloc.h> struct node { int data; struct node *next; }*head=NULL,*current,*first=NULL,*temp,*temp1,*ptr,*ptr1,*rslt=NULL,*rslt1,*rslt2,*p,*q,*r; int w; void result(int m,int n) { int z,a,b,d; z=n+m; if(rslt==NULL) { rslt1=(struct node*)malloc(sizeof(struct node)); rslt1->data=(z%10); rslt1->next=NULL; rslt=rslt1; b=z/10; } else { rslt2=(struct node*)malloc(sizeof(struct node)); rslt2->data=(z%10)+b; rslt2->next=NULL; rslt2->next=rslt1; rslt1=rslt2; b=z/10; w=b; } } main() { int c,ctr1=0,ctr2=0,x=0,count1=1,count2=1; while(1) { printf("\nMENU"); printf("\n1.Push the first number"); printf("\n2.Push the second number"); printf("\n3.Display the entered elements"); printf("\n4.Result"); printf("\nPlease enter your choice-:"); scanf("%d",&c); if(c==1) { if(head==NULL) { current=(struct node*)malloc(sizeof(struct node)); printf("\nEnter 1st digit-:"); scanf("%d",&current->data); current->next=NULL; head=current; } else { ptr=(struct node*)malloc(sizeof(struct node)); printf("\nEnter next digit-:"); scanf("%d",&ptr->data); ptr->next=NULL; ptr->next=current; current=ptr; } p=current; while(p->next!=NULL) { p=p->next; count1++; } } if(c==2) { if(first==NULL) { temp=(struct node*)malloc(sizeof(struct node)); printf("\nEnter 1st element"); scanf("%d",&temp->data); temp->next=NULL; first=temp; } else { ptr1=(struct node*)malloc(sizeof(struct node)); printf("\nEnter next element"); scanf("%d",&ptr1->data); ptr1->next=NULL; ptr1->next=temp; temp=ptr1; } p=temp; while(p->next!=NULL) { p=p->next; count2++; } } if(c==3) { int j; count1--; printf("\nThe 1st number is-:"); while(count1!=0) { j=0; count1--; q=current; while(j!=count1) { q=q->next; j++; } printf("\t%d",q->data); } int k; count2--; printf("\nThe 2nd number is-:"); while(count2!=0) { k=0; count2--; q=temp; while(k!=count2) { q=q->next; k++; } printf("\t%d",q->data); } } if(c==4) { while(ptr!=NULL&&ptr1!=NULL) { result(ptr->data,ptr1->data); ptr=ptr->next; ptr1=ptr1->next; x++; } if(ctr1=ctr2) result(head->data,first->data); else if(ctr1>ctr2) { while(x!=ctr1) { result(ptr->data,0); x++; } } else if(ctr2>ctr1) { while(x!=ctr2) { result(0,ptr1->data); x++; } } printf("\t%d",w); while(rslt1!=NULL) { printf("\t%d",rslt1->data); rslt1=rslt1->next; } return; } } }
C
#include "server.h" Graph* initialise(int size) { // Create a graph Graph* g = (Graph *)malloc(sizeof(Graph)); g->n = size; g->graph = malloc(size * sizeof(Node)); // Initialise each node to NULL for (int i = 0; i < size; i ++) { g->graph[i].head = NULL; g->graph[i].prev = 0; g->graph[i].dist = INT_MAX; } return g; } Head insert(Head head, int id, int weight) { // Create node with id and weight Node* new = malloc(sizeof(Node)); new->id = id; new->weight = weight; new->next = NULL; new->dist = INT_MAX; new->prev = 0; // Setting to 0 as nodes start from 1, 0 indicates no previous node in the path // If that particular list is empty if (head.head == NULL) { head.head = new; } else { Node* temp = head.head; while (temp->next != NULL) { temp = temp->next; } // Now at last node, next node will be new node temp->next = new; } return head; } Graph* file(void) { // Read data from file FILE* fp; fp = fopen("test.txt", "r"); // If file pointer is null, return if (fp == NULL) { return NULL; } size_t size = 100; // Create string to display char* test = malloc(100 * sizeof(char)); int x; x = getline(&test, &size, fp); // Here test is first line, which is number of vertices in graph Graph* g = initialise(atoi(test) + 1); // Adding 1 so can refer with vertex ids instead of converting to indices // Iterate through all connections from a given vertix while (x = getline(&test, &size, fp) != -1) { // First token received is the one all have connections to (reversing edges) char* token = strtok(test, " "); int node = atoi(token); int weight; int vertex; // Now for every given vertex, need to iterate to get pairs of connecting vertex and corresponding weight while (token != NULL) { // Get vertex token token = strtok(NULL, " "); // Just check for if token is NULL if (token == NULL) { break; } vertex = atoi(token); // Get weight token token = strtok(NULL, " "); // Just check for if token is NULL if (token == NULL) { break; } weight = atoi(token); // Inserting to graph g->graph[vertex] = insert(g->graph[vertex], node, weight); } } return g; } void display(Graph* g) { // Temp to traverse through each list Node* temp; printf("Length: %d\n", g->n); for (int i = 1; i < g->n; i ++) { printf("\nHead: %d ", i); temp = g->graph[i].head; if (temp == NULL) { printf("No outgoing connections"); } else { while (temp != NULL) { printf("Vertex: %d Weight: %d ", temp->id, temp->weight); temp = temp->next; } } } printf("\n"); } Heap* create_heap(int size) { // Create heap Heap* h = (Heap* )malloc(sizeof(Heap)); // Assign size h->n = size - 1; // Allocate memory for array h->heap = malloc((h->n + 1) * sizeof(Node)); // As all distances are infinity, order does not matter in heap for (int i = 0; i < h->n; i ++) { // Assigning the id h->heap[i].id = i + 1; // Assigning the distance h->heap[i].dist = INT_MAX; // Assigning the previous vertex in the path h->heap[i].prev = 0; } return h; } Heap* delete(Heap* h, int* del) { *del = h->heap[0].id; // Copy next element to previous element for (int i = 0; i < (h->n - 1); i ++) { h->heap[i] = h->heap[i + 1]; } // Update length h->n --; return h; } Heap* update(Heap* h) { // Sort based on dist // Implemented using bubble sort for ease of coding Node temp;// Temp node for swapping for (int i = 0; i < h->n - 1; i ++) { int swaps = 0; for (int j = 0; j < (h->n - i - 1); j ++) { if (h->heap[j].dist > h->heap[j + 1].dist) { temp = h->heap[j]; h->heap[j] = h->heap[j + 1]; h->heap[j + 1] = temp; swaps ++; } } if (swaps == 0) { break; } } return h; } Paths* initialise_paths(int size) { Paths* p = malloc(sizeof(Paths)); // Number of vertices p->n = size; p->paths = malloc(p->n * sizeof(Path)); for (int i = 0; i < p->n; i ++) { p->paths[i].dist = 0; p->paths[i].head = malloc(sizeof(Node)); p->paths[i].head->id = i + 1; } return p; } Heap* dist_update(Heap* h, int id, int dist) { // Search for node in heap for (int i = 0; i < h->n; i ++) { if (h->heap[i].id == id) { h->heap[i].dist = dist; break; } } h = update(h); return h; } Graph* Dijkstra(Graph* g, Heap* h) { // Source vertex is vertex with greatest id int source = g->n - 1; // Update dist of source vertex to 0, initially it is the last element in the heap h->heap[h->n - 1].dist = 0; g->graph[h->heap[h->n - 1].id].dist = 0; // Update heap to reflect this h = update(h); // List of vertices whose shortest path has been found int v[g->n]; for (int i = 1; i < g->n; i ++) { v[i] = 0; } // Update that source vertex's shortest path has been found v[g->n - 1] = 1; // Node which has been removed from heap int del; Node* n; // Iterate through all vertices for (int i = 1; i < (g->n - 1); i ++) { // Get element at start of priority queue h = delete(h, &del); // Mark vertix as visited v[del] = 1; // Temp variable to get outgoing connections Node* temp = g->graph[del].head; while (temp != NULL) { if ((g->graph[del].dist + temp->weight) < (g->graph[temp->id].dist)) { // Update dist g->graph[temp->id].dist = g->graph[del].dist + temp->weight; // Update dist in heap h = dist_update(h, temp->id, g->graph[temp->id].dist); // Update previous vertex g->graph[temp->id].prev = del; } temp = temp->next; } } return g; } Node* insert_path(Node* head, int id) { // Create node to be added Node* new = malloc(sizeof(Node)); new->id = id; new->next = NULL; // If first node if (head == NULL) { head = new; } else { // Temp node for traversal Node* temp = head; while(temp->next != NULL) { temp = temp->next; } temp->next = new; } return head; } int* reset(int* arr, int size) { for (int i = 1; i < size; i ++) { arr[i] = 0; } return arr; } void get_paths(Graph* g) { Paths* p = malloc(sizeof(Paths)); p->paths = malloc((g->n - 1) * sizeof(Node)); // Source int source = g->n - 1; int* arr = malloc(source * sizeof(int)); // Initialise paths with first node as the node itself (only those that have paths) for (int i = 1; i < source; i ++) { // If a path exists, add to paths array if (g->graph[i].prev != 0) { Node* new = malloc(sizeof(Node)); new->id = i; new->next = NULL; p->paths[i].head = new; } else { p->paths[i].head = NULL; } } // Iterate over and add path for (int i = 1; i < source; i ++) { // Keeps track of prev element int prev = g->graph[i].prev; arr = reset(arr, source); int j = 0; // If it has a path if (prev != 0) { while (prev != source) { arr[j] = prev; j ++; // Go back to previous node prev = g->graph[prev].prev; } arr[j] = prev; } int k = 0; while (k <= j && (arr[j] == source)) { p->paths[i].head = insert_path(p->paths[i].head, arr[k]); k ++; } } // Print paths // Temp variable for traversal Node* temp; for (int i = 1; i < source; i ++) { temp = p->paths[i].head; if (temp == NULL) { printf("%d NO PATH\n", i); } else { printf("%d ", i); while (temp != NULL) { printf("%d ", temp->id); temp = temp->next; } printf("%d\n", g->graph[i].dist); } } }
C
//Program to contruct a BST from given preorder traversal //This is the recursive approach //It uses min_int max_int approach to construct the tree in O(n) time //Assumption is made that all elements are distinct #include <stdio.h> #include <stdlib.h> #define LARGE 10000 struct Node{ int data; struct Node *lc; struct Node *rc; }; struct Node *new_node(int data){ struct Node *new = (struct Node *)malloc(sizeof(struct Node)); new->data = data; new->lc = NULL; new->rc = NULL; return new; } struct Node *Construct_BST(int pre_order[] , int *preindex , int key , int min , int max , int size){ //Base Case for resursion if(*preindex>=size){ return NULL; } struct Node *root = NULL; if(key>min && key<max){ root = new_node(key); *preindex = *preindex + 1; if(*preindex<size){ //To build left_subtree root->lc = Construct_BST(pre_order , preindex , pre_order[*preindex] , min , key , size); //To build right_subtree root->rc = Construct_BST(pre_order , preindex , pre_order[*preindex] , key , max , size); } } return root; } struct Node *construct_tree(int pre[] , int size){ int preind = 0; return Construct_BST(pre , &preind , pre[0] , 0 , 10000 , size); } void inorder_traversal(struct Node *node){ if(node){ inorder_traversal(node->lc); printf("%d " , node->data); inorder_traversal(node->rc); }//printf("\n"); } int main(){ int n, size; scanf("%d" , &n); int pre_order[LARGE]; size = n; for(int i = 0; i<n; i++){ scanf("%d" , &pre_order[i]); } int pre_index = 0; struct Node *temp = Construct_BST(pre_order , &pre_index , pre_order[0] , 0 , 10000 , n); //struct Node *head = construct_tree(pre_order , n);//Here we sre taking min as 0 and max as 10000 inorder_traversal(temp); return 0; }
C
/* * Funo : Programa com a fuo dizer se uma gangorra esta ou no equlibrada, levando em considerao o comprimento das extremidades e o peso das pessoas. * Autores: Denilson Higino da Silva | RGM: 36712 Fernando Oliveira de Lima | RGM: 36716 * Data : 07/05/2017 ________________________________________________________________________________________*/ #include<stdio.h> int main() { /*============================DECLARAO DAS VARIAVEIS==========================*/ float C1,C2, //C1 = Comprimento esquerdo | C2 = Comprimento direito P1,P2, //P1 = Peso do lado esquerdo | P2 = Peso do lado direito LADO1,LADO2; //LADO1 = Lado esquerdo | LADO2 = lado direito /*============================ENTRADA DOS DADOS===================================*/ printf("Veja se a existe um equilibrio entre os dois lados de uma gangorra\n\n"); printf("\tENTRADA DOS EXTREMOS E OS PESOS\n"); //ENTRADA DE DADOS DO LADO ESQUERDO DA GANGORRA printf("\n\t\tLADO ESQUERDO\n"); printf("Comprimento (deve ser entre 10 e 100)\n"); printf("--> "); do{ //Verificao da entrada do comprimento scanf("%f",&C1); if((C1 < 10) || (C1>100)){ printf("Comprimento invalido\n"); printf("Digite outro: "); } }while((C1 < 10) || (C1>100)); printf("\nPeso da pessoa sentada nesse extremo\n"); printf("(peso entre 10 e 100)\n"); printf("--> "); do{ //Verificao da entrada do peso scanf("%f",&P1); if((P1 < 10) || (P1>100)){ printf("Peso invalido\n"); printf("Digite outro: "); } }while((P1 < 10) || (P1>100)); LADO1 = C1*P1;//Colocando peso em funo do comprimento //para obter o valor resultante do lado esquedo. //------------------------------------------------------------------- //ENTRADA DE DADOS DO LADO DIREITO DA GANGORRA printf("\t\tLADO DIREITO\n"); printf("Comprimento (deve ser entre 10 e 100)\n"); printf("--> "); do{ //Verificao da entrada do comprimento scanf("%f",&C2); if((C2 < 10) || (C2>100)){ printf("Comprimento invalido\n"); printf("Digite outro: "); } }while((C2 < 10) || (C2>100)); printf("\nPeso da pessoa sentada nesse extremo\n"); printf("(peso entre 10 e 100)\n"); printf("--> "); do{ //Verificao da entrada do peso scanf("%f",&P2); if((P2 < 10) || (P2>100)){ printf("Peso invalido\n"); printf("Digite outro: "); } }while((P2 < 10) || (P2>100)); LADO2 = C2*P2;//Colocando peso em funo do comprimento //para obter o valor resultante do lado direito. //------------------------------------------------------------------------------------- /*============================SAIDA DOS DADOS=====================================*/ //Verificao do equilibrido da gangorra if(LADO1==LADO2){ printf("\n--> 0 "); }else if(LADO1>LADO2){ printf("\n--> -1"); }else{ printf("\n--> 1"); } return 0; }
C
#include "utils.h" #include <API.h> //#include <ctype.h> #include <string.h> // // Updates the given variable with the current time in microseconds, // and returns the time difference in seconds. // float timeUpdate(unsigned long *microTime) { unsigned long newMicroTime = micros(); float change = (newMicroTime - *microTime) / 1000000.0f; *microTime = newMicroTime; return change; } int signOf(int x) { return (x > 0) - (x < 0); } bool stringStartsWith(char const *pre, char const *string) { size_t stringLength = strlen(string); size_t preLength = strlen(pre); if (stringLength < preLength) { return false; } else { return strncmp(pre, string, preLength) == 0; } } //http://stackoverflow.com/questions/4392665/converting-string-to-float-without-atof-in-c // And, using atof makes the linker complain about _sbrk not defined, so the lazy way is to write custom atof: float stringToFloat(const char* string) { float rez = 0, factor = 1; if (*string == '-') { string++; factor = -1; } for (int pointSeen = 0; *string; string++) { if (*string == '.') { pointSeen = 1; continue; } int digit = *string - '0'; if (digit >= 0 && digit <= 9) { if (pointSeen) { factor /= 10.0f; } rez = rez * 10.0f + (float)digit; } } return rez * factor; }; #if 0 bool stringCaseInsensitiveStartsWith(char const *pre, char const *string) { size_t stringLength = strlen(string); size_t preLength = strlen(string); if (stringLength < preLength) { return false; } else { return stringCaseInsensitiveCompare(pre, string, preLength) == 0; } } // TODO: test this int stringCaseInsensitiveCompare(char const *a, char const *b, size_t maxCount) { for (size_t i; i < maxCount; a++, b++, i++) { int d = tolower(*a) - tolower(*b); if (d != 0 || !*a) { return d; } } return 0; } #endif
C
#ifndef __MATHCONSTANT_H__ #define __MATHCONSTANT_H__ #ifdef _MSC_VER #define _USE_MATH_DEFINES #endif #include "math.h" #include "stdlib.h" // Constants for numerical routines // #define TINY 1.0e-30 // A small number #define ITMAX 200 // Maximum number of iterations #define EPS 3.0e-7 // Relative accuracy #define ZEPS 3.0e-10 // Precision around zero #define FPMIN 1.0e-30 // Number near the smallest representable number #define FPMAX 1.0e+100 // Number near the largest representable number #define TOL 1.0e-6 // Zero SVD values below this #define GOLD 0.61803399 // Golden ratio #define CGOLD 0.38196601 // Complement of golden ratio inline double square(double a) { return a * a; } inline double sign(double a, double b) { return b >= 0 ? fabs(a) : -fabs(a); } inline double min(double a, double b) { return a < b ? a : b; } inline double max(double a, double b) { return a > b ? a : b; } inline int square(int a) { return a * a; } inline int sign(int a, int b) { return b >= 0 ? abs(a) : -abs(a); } inline int min(int a, int b) { return a < b ? a : b; } inline int max(int a, int b) { return a > b ? a : b; } #endif
C
#include <stdio.h> main() { int i; for (i = 1; i <= 4; i++) { printf("programacao\n"); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_vector_concat.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: abrabant <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/22 19:20:53 by abrabant #+# #+# */ /* Updated: 2021/04/13 16:19:34 by abrabant ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft/cstring.h" #include "libft/vector.h" #include "libft/internal/vector_int.h" t_vector ft_vector_concat(t_vector a1, t_vector a2) { t_vector_int *new; new = (t_vector_int *)ft_vector_new(((t_vector_int *)a1)->capacity + ((t_vector_int *)a2)->capacity); if (new == NULL) { return (NULL); } new->length = ((t_vector_int *)a1)->length + ((t_vector_int *)a2)->length; ft_memcpy(new->vector, ((t_vector_int *)a1)->vector, sizeof(*new->vector) * ((t_vector_int *)a1)->length); ft_memcpy(new->vector + ((t_vector_int *)a1)->length, ((t_vector_int *)a2)->vector, sizeof(*new->vector) * ((t_vector_int *)a2)->length); return (new); }
C
#include "tests.h" int main(void) { TArray *arr = tarray_new(sizeof(s32)); for (s32 i = 0; i < 100; ++i) { tarray_push(arr, i); } ASSERT(arr->size == 100); for (s32 i = 0; i < 100; ++i) { tarray_pop(arr); } ASSERT(arr->size == 0); for (s32 i = 0; i < 100; ++i) { tarray_push(arr, i); } tarray_erase(arr, 99); ASSERT(arr->size == 99); tarray_erase(arr, 0); ASSERT(arr->size == 98); tarray_erase(arr, 10); ASSERT(arr->size == 97); tarray_delete(arr); return 0; }
C
/*4.2 cwiczenia podpunktn 9 */ #include <LPC21xx.H> #include <stdio.h> #define MILI 4615 #define LED0_bm 0x10000 //16 bit ma wartosc 1 /*Funkcja odpowiedzialna za opoznienie dla mojego kompilatora 1 ms to 4615 iteracji*/ void Delay(int iHowLong){ unsigned long int uiIntCounter; char cCharIncrementation; for(uiIntCounter=0; uiIntCounter<(iHowLong*MILI);uiIntCounter++){ cCharIncrementation++; } } int main(){ while(1){ Delay(50); IO1SET = LED0_bm; Delay(50); IO1CLR = LED0_bm; } }
C
#include<time.h> #include<stdio.h> #include<stdlib.h> #define N 10 void Merge(int *a,int *L,int leftCount,int *R,int rightCount) { int i,j,k; i = 0; j = 0; k =0; while(i<leftCount && j< rightCount) { if(L[i] < R[j]) a[k++] = L[i++]; else a[k++] = R[j++]; } while(i < leftCount) a[k++] = L[i++]; while(j < rightCount) a[k++] = R[j++]; } void MergeSort(int *a,int n) { int mid,i, *L, *R; if(n < 2) return; mid = n/2; L = (int*)malloc(mid*sizeof(int)); R = (int*)malloc((n- mid)*sizeof(int)); for(i = 0;i<mid;i++) L[i] = a[i]; for(i = mid;i<n;i++) R[i-mid] = a[i]; MergeSort(L,mid); MergeSort(R,n-mid); Merge(a,L,mid,R,n-mid); free(L); free(R); } int main() { int a[N] = {0}; int i; int t=0; int v=0; srand(time(NULL)); for(t=0;t<N;t++) { v=rand()%100; a[t]=v; printf("%d\n",a[t]); } printf("\n"); MergeSort(a,N); for(i = 0;i<N;i++) { printf("%d\n",a[i]); } return 0; }
C
#include "lib_ccx.h" #include "ccx_common_option.h" #include "dvb_subtitle_decoder.h" #include "utility.h" #include <stdbool.h> #ifdef WIN32 #include "..\\win_iconv\\iconv.h" #else #include "iconv.h" #endif //Prints a string to a file pointer, escaping XML special chars //Works with UTF-8 void EPG_fprintxml(FILE *f, char *string) { char *p = string; char *start = p; while(*p!='\0') { switch(*p) { case '<': fwrite(start, 1, p-start, f); fprintf(f, "&lt;"); start = p+1; break; case '>': fwrite(start, 1, p-start, f); fprintf(f, "&gt;"); start = p+1; break; case '"': fwrite(start, 1, p-start, f); fprintf(f, "&quot;"); start = p+1; break; case '&': fwrite(start, 1, p-start, f); fprintf(f, "&amp;"); start = p+1; break; case '\'': fwrite(start, 1, p-start, f); fprintf(f, "&apos;"); start = p+1; break; } p++; } fwrite(start, 1, p-start, f); } // Fills given string with given (event.*_time_string) ATSC time converted to XMLTV style time string void EPG_ATSC_calc_time(char *output, uint32_t time) { struct tm timeinfo; timeinfo.tm_year = 1980-1900; timeinfo.tm_mon = 0; timeinfo.tm_mday = 6; timeinfo.tm_sec = 0+time; timeinfo.tm_min = 0; timeinfo.tm_hour = 0; timeinfo.tm_isdst = -1; mktime(&timeinfo); sprintf(output, "%02d%02d%02d%02d%02d%02d +0000", timeinfo.tm_year+1900, timeinfo.tm_mon+1, timeinfo.tm_mday, timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec); } // Fills event.start_time_string in XMLTV format with passed DVB time void EPG_DVB_calc_start_time(struct EPG_event *event, uint64_t time) { uint64_t mjd = time>>24; event->start_time_string[0]='\0'; if (mjd > 0) { long y,m,d ,k; // algo: ETSI EN 300 468 - ANNEX C y = (long) ((mjd - 15078.2) / 365.25); m = (long) ((mjd - 14956.1 - (long)(y * 365.25) ) / 30.6001); d = (long) (mjd - 14956 - (long)(y * 365.25) - (long)(m * 30.6001)); k = (m == 14 || m == 15) ? 1 : 0; y = y + k + 1900; m = m - 1 - k*12; sprintf(event->start_time_string, "%02ld%02ld%02ld%06"PRIu64 "+0000",y,m,d,time&0xffffff); } } // Fills event.end_time_string in XMLTV with passed DVB time + duration void EPG_DVB_calc_end_time(struct EPG_event *event, uint64_t time, uint32_t duration) { uint64_t mjd = time>>24; event->end_time_string[0]='\0'; if (mjd > 0) { long y,m,d ,k; struct tm timeinfo; // algo: ETSI EN 300 468 - ANNEX C y = (long) ((mjd - 15078.2) / 365.25); m = (long) ((mjd - 14956.1 - (long)(y * 365.25) ) / 30.6001); d = (long) (mjd - 14956 - (long)(y * 365.25) - (long)(m * 30.6001)); k = (m == 14 || m == 15) ? 1 : 0; y = y + k + 1900; m = m - 1 - k*12; timeinfo.tm_year = y-1900; timeinfo.tm_mon = m-1; timeinfo.tm_mday = d; timeinfo.tm_sec = (time&0x0f) + (10*((time&0xf0)>>4)) + (duration&0x0f) + (10*((duration&0xf0)>>4)); timeinfo.tm_min = ((time&0x0f00)>>8) + (10*((time&0xf000)>>4)>>8) + ((duration&0x0f00)>>8) + (10*((duration&0xf000)>>4)>>8); timeinfo.tm_hour = ((time&0x0f0000)>>16) + (10*((time&0xf00000)>>4)>>16) + ((duration&0x0f0000)>>16) + (10*((duration&0xf00000)>>4)>>16); timeinfo.tm_isdst = -1; mktime(&timeinfo); sprintf(event->end_time_string, "%02d%02d%02d%02d%02d%02d +0000", timeinfo.tm_year+1900, timeinfo.tm_mon+1, timeinfo.tm_mday, timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec); } } // returns english string description of the passed DVB category ID char *EPG_DVB_content_type_to_string(uint8_t cat) { struct table { uint8_t cat; char *name; }; struct table t[] = { {0x00, "reserved"}, { 0x10, "movie/drama (general)" }, { 0x11, "detective/thriller" }, { 0x12, "adventure/western/war" }, { 0x13, "science fiction/fantasy/horror" },{ 0x14, "comedy" }, { 0x15, "soap/melodram/folkloric" }, { 0x16, "romance" }, { 0x17, "serious/classical/religious/historical movie/drama" }, { 0x18, "adult movie/drama" }, { 0x1E, "reserved" }, { 0x1F, "user defined" }, { 0x20, "news/current affairs (general)" }, { 0x21, "news/weather report" }, { 0x22, "news magazine" }, { 0x23, "documentary" }, { 0x24, "discussion/interview/debate" }, { 0x2E, "reserved" }, { 0x2F, "user defined" }, { 0x30, "show/game show (general)" }, { 0x31, "game show/quiz/contest" }, { 0x32, "variety show" }, { 0x33, "talk show" }, { 0x3E, "reserved" }, { 0x3F, "user defined" }, { 0x40, "sports (general)" }, { 0x41, "special events" }, { 0x42, "sports magazine" }, { 0x43, "football/soccer" }, { 0x44, "tennis/squash" }, { 0x45, "team sports" }, { 0x46, "athletics" }, { 0x47, "motor sport" }, { 0x48, "water sport" }, { 0x49, "winter sport" }, { 0x4A, "equestrian" }, { 0x4B, "martial sports" }, { 0x4E, "reserved" }, { 0x4F, "user defined" }, { 0x50, "childrens's/youth program (general)" }, { 0x51, "pre-school children's program" }, { 0x52, "entertainment (6-14 year old)" }, { 0x53, "entertainment (10-16 year old)" }, { 0x54, "information/education/school program" }, { 0x55, "cartoon/puppets" }, { 0x5E, "reserved" }, { 0x5F, "user defined" }, { 0x60, "music/ballet/dance (general)" }, { 0x61, "rock/pop" }, { 0x62, "serious music/classic music" }, { 0x63, "folk/traditional music" }, { 0x64, "jazz" }, { 0x65, "musical/opera" }, { 0x66, "ballet" }, { 0x6E, "reserved" }, { 0x6F, "user defined" }, { 0x70, "arts/culture (without music, general)" },{ 0x71, "performing arts" }, { 0x72, "fine arts" }, { 0x73, "religion" }, { 0x74, "popular culture/traditional arts" }, { 0x75, "literature" }, { 0x76, "film/cinema" }, { 0x77, "experimental film/video" }, { 0x78, "broadcasting/press" }, { 0x79, "new media" }, { 0x7A, "arts/culture magazine" }, { 0x7B, "fashion" }, { 0x7E, "reserved" }, { 0x7F, "user defined" }, { 0x80, "social/political issues/economics (general)" }, { 0x81, "magazines/reports/documentary" }, { 0x82, "economics/social advisory" }, { 0x83, "remarkable people" }, { 0x8E, "reserved" }, { 0x8F, "user defined" }, { 0x90, "education/science/factual topics (general)" }, { 0x91, "nature/animals/environment" }, { 0x92, "technology/natural science" }, { 0x93, "medicine/physiology/psychology" }, { 0x94, "foreign countries/expeditions" }, { 0x95, "social/spiritual science" }, { 0x96, "further education" }, { 0x97, "languages" }, { 0x9E, "reserved" }, { 0x9F, "user defined" }, { 0xA0, "leisure hobbies (general)" }, { 0xA1, "tourism/travel" }, { 0xA2, "handicraft" }, { 0xA3, "motoring" }, { 0xA4, "fitness & health" }, { 0xA5, "cooking" }, { 0xA6, "advertisement/shopping" }, { 0xA7, "gardening" }, { 0xAE, "reserved" }, { 0xAF, "user defined" }, { 0xB0, "original language" }, { 0xB1, "black & white" }, { 0xB2, "unpublished" }, { 0xB3, "live broadcast" }, { 0xBE, "reserved" }, { 0xBF, "user defined" }, { 0xEF, "reserved" }, { 0xFF, "user defined" }, {0x00, NULL}, }; struct table *p = t; while(p->name!=NULL) { if(cat==p->cat) return p->name; p++; } return "undefined content"; } // Prints given event to already opened XMLTV file. void EPG_print_event(struct EPG_event *event, uint32_t channel, FILE *f) { int i; fprintf(f, " <program "); fprintf(f, "start=\""); fprintf(f, "%s", event->start_time_string); fprintf(f, "\" "); fprintf(f, "stop=\""); fprintf(f, "%s", event->end_time_string); fprintf(f, "\" "); fprintf(f, "channel=\"%i\">\n", channel); if(event->has_simple) { fprintf(f, " <title lang=\"%s\">", event->ISO_639_language_code); EPG_fprintxml(f, event->event_name); fprintf(f, "</title>\n"); fprintf(f, " <sub-title lang=\"%s\">", event->ISO_639_language_code); EPG_fprintxml(f, event->text); fprintf(f, "</sub-title>\n"); } if(event->extended_text!=NULL) { fprintf(f, " <desc lang=\"%s\">", event->extended_ISO_639_language_code); EPG_fprintxml(f, event->extended_text); fprintf(f, "</desc>\n"); } for(i=0; i<event->num_ratings; i++) if(event->ratings[i].age>0 && event->ratings[i].age<0x10) fprintf(f, " <rating system=\"dvb:%s\">%i</rating>\n", event->ratings[i].country_code, event->ratings[i].age+3); for(i=0; i<event->num_categories; i++) { fprintf(f, " <category lang=\"en\">"); EPG_fprintxml(f, EPG_DVB_content_type_to_string(event->categories[i])); fprintf(f, "</category>\n"); } fprintf(f, " <ts-meta-id>%i</ts-meta-id>\n", event->id); fprintf(f, " </program>\n"); } void EPG_output_net(struct lib_ccx_ctx *ctx) { int i; unsigned j; struct EPG_event *event; /* TODO: don't remove untill someone fixes segfault with -xmltv 2 */ if (ctx->demux_ctx == NULL) return; if (ctx->demux_ctx->nb_program == 0) return; for (i = 0; i < ctx->demux_ctx->nb_program; i++) { if (ctx->demux_ctx->pinfo[i].program_number == ccx_options.demux_cfg.ts_forced_program) break; } if (i == ctx->demux_ctx->nb_program) return; for (j = 0; j < ctx->eit_programs[i].array_len; j++) { event = &(ctx->eit_programs[i].epg_events[j]); if (event->live_output == true) continue; event->live_output = true; char *category = NULL; if (event->num_categories > 0) category = EPG_DVB_content_type_to_string(event->categories[0]); net_send_epg( event->start_time_string, event->end_time_string, event->event_name, event->extended_text, event->ISO_639_language_code, category ); } } // Creates fills and closes a new XMLTV file for live mode output. // File should include only events not previously output. void EPG_output_live(struct lib_ccx_ctx *ctx) { int c=false, i, j; FILE *f; char *filename, *finalfilename; for(i=0; i < ctx->demux_ctx->nb_program; i++) { for(j=0; j<ctx->eit_programs[i].array_len; j++) if(ctx->eit_programs[i].epg_events[j].live_output==false) { c=true; } } if(!c) return; filename = malloc(strlen(ctx->basefilename)+30); sprintf(filename, "%s_%i.xml.part", ctx->basefilename, ctx->epg_last_live_output); f = fopen(filename, "w"); fprintf(f, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE tv SYSTEM \"xmltv.dtd\">\n\n<tv>\n"); for(i=0; i < ctx->demux_ctx->nb_program; i++) { fprintf(f, " <channel id=\"%i\">\n", ctx->demux_ctx->pinfo[i].program_number); fprintf(f, " <display-name>%i</display-name>\n", ctx->demux_ctx->pinfo[i].program_number); fprintf(f, " </channel>\n"); } for(i=0; i < ctx->demux_ctx->nb_program; i++) { for(j=0; j<ctx->eit_programs[i].array_len; j++) if(ctx->eit_programs[i].epg_events[j].live_output==false) { ctx->eit_programs[i].epg_events[j].live_output=true; EPG_print_event(&ctx->eit_programs[i].epg_events[j], ctx->demux_ctx->pinfo[i].program_number, f); } } fprintf(f, "</tv>"); fclose(f); finalfilename = malloc(strlen(filename)+30); memcpy(finalfilename, filename, strlen(filename)-5); finalfilename[strlen(filename)-5]='\0'; rename(filename, finalfilename); free(filename); free(finalfilename); } // Creates fills and closes a new XMLTV file for full output mode. // File should include all events in memory. void EPG_output(struct lib_ccx_ctx *ctx) { FILE *f; char *filename; int i,j, ce; filename = malloc(strlen(ctx->basefilename) + 9); if(filename == NULL) return; memcpy(filename, ctx->basefilename, strlen(ctx->basefilename)+1); strcat(filename, "_epg.xml"); f = fopen(filename, "w"); if(!f) { dbg_print (CCX_DMT_GENERIC_NOTICES, "\rUnable to open %s\n", filename); freep(&filename); return; } freep(&filename); fprintf(f, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE tv SYSTEM \"xmltv.dtd\">\n\n<tv>\n"); for(i=0; i<ctx->demux_ctx->nb_program; i++) { fprintf(f, " <channel id=\"%i\">\n", ctx->demux_ctx->pinfo[i].program_number); fprintf(f, " <display-name>"); if(ctx->demux_ctx->pinfo[i].name[0] != '\0') EPG_fprintxml(f, ctx->demux_ctx->pinfo[i].name); else fprintf(f, "%i\n", ctx->demux_ctx->pinfo[i].program_number); fprintf(f, "</display-name>\n"); fprintf(f, " </channel>\n"); } if(ccx_options.xmltvonlycurrent==0) { // print all events for(i=0; i<ctx->demux_ctx->nb_program; i++) { for(j=0; j<ctx->eit_programs[i].array_len; j++) EPG_print_event(&ctx->eit_programs[i].epg_events[j], ctx->demux_ctx->pinfo[i].program_number, f); } if(ctx->demux_ctx->nb_program==0) //Stream has no PMT, fall back to unordered events for(j=0; j<ctx->eit_programs[TS_PMT_MAP_SIZE].array_len; j++) EPG_print_event(&ctx->eit_programs[TS_PMT_MAP_SIZE].epg_events[j], ctx->eit_programs[TS_PMT_MAP_SIZE].epg_events[j].service_id, f); } else { // print current events only for(i=0; i<ctx->demux_ctx->nb_program; i++) { ce = ctx->eit_current_events[i]; for(j=0; j<ctx->eit_programs[i].array_len; j++) { if(ce==ctx->eit_programs[i].epg_events[j].id) EPG_print_event(&ctx->eit_programs[i].epg_events[j], ctx->demux_ctx->pinfo[i].program_number, f); } } } fprintf(f, "</tv>"); fclose(f); } // Free all memory allocated for given event void EPG_free_event(struct EPG_event *event) { if(event->has_simple) { free(event->event_name); free(event->text); } if(event->extended_text!=NULL) free(event->extended_text); if(event->num_ratings>0) free(event->ratings); if(event->num_categories>0) free(event->categories); } //compare 2 events. Return false if they are different. int EPG_event_cmp(struct EPG_event *e1, struct EPG_event *e2) { if(e1->id != e2->id || (strcmp(e1->start_time_string, e2->start_time_string)!=0) || (strcmp(e1->end_time_string, e2->end_time_string)!=0)) return false; // could add full checking of strings here if desired. return true; } // Add given event to array of events. // Return FALSE if nothing changed, TRUE if this is a new or updated event. int EPG_add_event(struct lib_ccx_ctx *ctx, int32_t pmt_map, struct EPG_event *event) { int isnew=true, j; for(j=0; j<ctx->eit_programs[pmt_map].array_len; j++) { if(ctx->eit_programs[pmt_map].epg_events[j].id==event->id) { if(EPG_event_cmp(event, &ctx->eit_programs[pmt_map].epg_events[j])) return false; //event already in array, nothing to do else { //event with this id is already in the array but something has changed. Update it. event->count=ctx->eit_programs[pmt_map].epg_events[j].count; EPG_free_event(&ctx->eit_programs[pmt_map].epg_events[j]); memcpy(&ctx->eit_programs[pmt_map].epg_events[j], event, sizeof(struct EPG_event)); return true; } } } // id not in array. Add new event; event->count=0; memcpy(&ctx->eit_programs[pmt_map].epg_events[ctx->eit_programs[pmt_map].array_len], event, sizeof(struct EPG_event)); ctx->eit_programs[pmt_map].array_len++; return true; } //EN 300 468 V1.3.1 (1998-02) //6.2.4 Content descriptor void EPG_decode_content_descriptor(uint8_t *offset, uint32_t descriptor_length, struct EPG_event *event) { int i; int num_items = descriptor_length/2; if(num_items == 0) { dbg_print (CCX_DMT_GENERIC_NOTICES, "\rWarning: Invalid EIT content_descriptor length detected.\n"); return; } event->categories = malloc(1*num_items); event->num_categories = num_items; for(i=0; i<num_items; i++) { event->categories[i] = offset[0]; offset+=2; } } //EN 300 468 V1.3.1 (1998-02) //6.2.20 Parental rating descripto void EPG_decode_parental_rating_descriptor(uint8_t *offset, uint32_t descriptor_length, struct EPG_event *event) { int i; int num_items = descriptor_length/4; struct EPG_rating *ratings; if(num_items == 0) { dbg_print (CCX_DMT_GENERIC_NOTICES, "\rWarning: Invalid EIT parental_rating length detected.\n"); return; } event->ratings = malloc(sizeof(struct EPG_rating)*num_items); ratings = event->ratings; event->num_ratings = num_items; for(i=0; i<descriptor_length/4; i++) { ratings[i].country_code[0] = offset[0]; ratings[i].country_code[1] = offset[1]; ratings[i].country_code[2] = offset[2]; ratings[i].country_code[3] = '\0'; if(offset[3] == 0x00 || offset[3] >=0x10) ratings[i].age = 0; else ratings[i].age = offset[3]; offset+=4; } } // an ugly function to convert from dvb codepages to UTF-8859-9 using iconv // returns a null terminated UTF8-strings // EN 300 468 V1.7.1 (2006-05) // A.2 Selection of Character table char* EPG_DVB_decode_string(uint8_t *in, size_t size) { uint8_t *out; uint16_t decode_buffer_size = (size*4)+1; uint8_t *decode_buffer = malloc(decode_buffer_size); char *dp = &decode_buffer[0]; size_t obl=decode_buffer_size; uint16_t osize=0; iconv_t cd=(iconv_t)(-1); int skipiconv = false; int ret=-1; int x; if(size==0) { // 0 length strings are valid decode_buffer[0]='\0'; return decode_buffer; } if(in[0]>=0x20) { skipiconv=true; } else if(in[0]==0x01) { size--; in++; cd = iconv_open("UTF-8", "ISO8859-5"); //tested } else if(in[0]==0x02) { size--; in++; cd = iconv_open("UTF-8", "ISO8859-6"); } else if(in[0]==0x03) { size--; in++; cd = iconv_open("UTF-8", "ISO8859-7"); } else if(in[0]==0x04) { size--; in++; cd = iconv_open("UTF-8", "ISO8859-8"); } else if(in[0]==0x05) { size--; in++; cd = iconv_open("UTF-8", "ISO8859-9"); } else if(in[0]==0x06) { size--; in++; cd = iconv_open("UTF-8", "ISO8859-10"); } else if(in[0]==0x07) { size--; in++; cd = iconv_open("UTF-8", "ISO8859-11"); } else if(in[0]==0x08) { size--; in++; cd = iconv_open("UTF-8", "ISO8859-12"); //This doesn't even exist? } else if(in[0]==0x09) { size--; in++; cd = iconv_open("UTF-8", "ISO8859-13"); } else if(in[0]==0x0a) { size--; in++; cd = iconv_open("UTF-8", "ISO8859-14"); } else if(in[0]==0x0b) { size--; in++; cd = iconv_open("UTF-8", "ISO8859-15"); //tested, german } else if(in[0]==0x10) { char from[14]; uint16_t cpn = (in[1] << 8) | in[2]; size-=3; in+=3; snprintf(from, sizeof(from), "ISO8859-%d", cpn); cd = iconv_open("UTF-8", from); } else if(in[0]==0x11) { size--; in++; cd = iconv_open("UTF-8", "ISO-10646/UTF8"); } else if(in[0]==0x12) { size--; in++; cd = iconv_open("UTF-8", "KS_C_5601-1987"); } else if(in[0]==0x13) { size--; in++; cd = iconv_open("UTF-8", "GB2312"); } else if(in[0]==0x14) { size--; in++; cd = iconv_open("UTF-8", "BIG-5"); } else if(in[0]==0x15) { size--; in++; cd = iconv_open("UTF-8", "UTF-8"); } else { dbg_print (CCX_DMT_GENERIC_NOTICES, "\rWarning: EPG_DVB_decode_string(): Reserved encoding detected: %02x.\n", in[0]); size--; in++; cd = iconv_open("UTF-8", "ISO8859-9"); } if((long)cd != -1 && !skipiconv) { ret = iconv(cd, (char **)&in, &size, &dp, &obl); obl=decode_buffer_size-obl; decode_buffer[obl]=0x00; } else { uint16_t newsize=0; if(!skipiconv) dbg_print (CCX_DMT_GENERIC_NOTICES, "\rWarning: EPG_DVB_decode_string(): Failed to convert codepage.\n"); /* http://dvbstreamer.sourcearchive.com/documentation/2.1.0-2/dvbtext_8c_source.html libiconv doesn't support ISO 6937, but glibc does?! so fall back to ISO8859-1 and strip out the non spacing diacritical mark/graphical characters etc. ALSO: http://lists.gnu.org/archive/html/bug-gnu-libiconv/2009-09/msg00000.html */ for(x=0; x<size; x++) { if(in[x]<=(uint8_t)127) { decode_buffer[newsize]=in[x]; newsize++; } } size=newsize; decode_buffer[size]=0x00; } osize=strlen(decode_buffer); out = malloc(osize+1); memcpy(out, decode_buffer, osize); out[osize]=0x00; free(decode_buffer); if (cd != (iconv_t)-1) iconv_close(cd); return out; } //EN 300 468 V1.3.1 (1998-02) //6.2.27 Short event descriptor void EPG_decode_short_event_descriptor(uint8_t *offset, uint32_t descriptor_length, struct EPG_event *event) { uint8_t text_length; uint8_t event_name_length; event->has_simple=true; event->ISO_639_language_code[0] = offset[0]; event->ISO_639_language_code[1] = offset[1]; event->ISO_639_language_code[2] = offset[2]; event->ISO_639_language_code[3] = 0x00; event_name_length = offset[3]; if(event_name_length+4>descriptor_length) { dbg_print (CCX_DMT_GENERIC_NOTICES, "\rWarning: Invalid short_event_descriptor size detected.\n"); return; } event->event_name = EPG_DVB_decode_string(&offset[4], event_name_length); text_length = offset[4+event_name_length]; if(text_length+event_name_length+4>descriptor_length) { dbg_print (CCX_DMT_GENERIC_NOTICES, "\rWarning: Invalid short_event_descriptor size detected.\n"); return; } event->text = EPG_DVB_decode_string(&offset[5+event_name_length], text_length); } //EN 300 468 V1.3.1 (1998-02) //6.2.9 Extended event descriptor void EPG_decode_extended_event_descriptor(uint8_t *offset, uint32_t descriptor_length, struct EPG_event *event) { uint8_t descriptor_number=offset[0]>>4; uint8_t last_descriptor_number=(offset[0]&0x0f); uint32_t text_length; uint32_t oldlen=0; uint8_t length_of_items = offset[4]; event->extended_ISO_639_language_code[0] = offset[1]; event->extended_ISO_639_language_code[1] = offset[2]; event->extended_ISO_639_language_code[2] = offset[3]; event->extended_ISO_639_language_code[3] = 0x00; offset=offset+length_of_items+5; if(length_of_items>descriptor_length-5) { dbg_print (CCX_DMT_GENERIC_NOTICES, "\rWarning: Invalid extended_event_descriptor size detected.\n"); return; } text_length = offset[0]; if(text_length>descriptor_length-5-length_of_items-1) { dbg_print (CCX_DMT_GENERIC_NOTICES, "\rWarning: Invalid extended_event_text_length size detected.\n"); return; } //TODO: can this leak memory with a malformed descriptor? if(descriptor_number>0) { if(offset[1]<0x20) { offset++; text_length--; } uint8_t *net = malloc(strlen(event->extended_text)+text_length+1); oldlen=strlen(event->extended_text); memcpy(net, event->extended_text, strlen(event->extended_text)); free(event->extended_text); event->extended_text=net; } else event->extended_text = malloc(text_length+1); memcpy(&event->extended_text[oldlen], &offset[1], text_length); event->extended_text[oldlen + text_length] = '\0'; if(descriptor_number==last_descriptor_number) { uint8_t *old = event->extended_text; event->extended_text = EPG_DVB_decode_string(event->extended_text, strlen(event->extended_text)); free(old); } } // decode an ATSC multiple_string // extremely basic implementation // only handles single segment, single language ANSI string! void EPG_ATSC_decode_multiple_string(uint8_t *offset, uint32_t length, struct EPG_event *event) { uint8_t number_strings; int i, j; char ISO_639_language_code[4]; uint8_t *offset_end = offset + length; #define CHECK_OFFSET(val) if(offset + val < offset_end) return CHECK_OFFSET(1); number_strings = offset[0]; offset++; for(i=0; i<number_strings; i++) { uint8_t number_segments; CHECK_OFFSET(4); number_segments = offset[3]; ISO_639_language_code[0] = offset[0]; ISO_639_language_code[1] = offset[1]; ISO_639_language_code[2] = offset[2]; ISO_639_language_code[3] = 0x00; offset+=4; for (j=0; j< number_segments; j++) { uint8_t compression_type; uint8_t mode; uint8_t number_bytes; CHECK_OFFSET(3); compression_type = offset[0]; mode = offset[1]; number_bytes = offset[2]; offset+=3; if(mode==0 && compression_type==0 && j==0) { CHECK_OFFSET(number_bytes); event->has_simple=true; event->ISO_639_language_code[0]=ISO_639_language_code[0]; event->ISO_639_language_code[1]=ISO_639_language_code[1]; event->ISO_639_language_code[2]=ISO_639_language_code[2]; event->ISO_639_language_code[3]=0x00; event->event_name = malloc(number_bytes+1); memcpy(event->event_name, &offset[0], number_bytes); event->event_name[number_bytes]='\0'; event->text = malloc(number_bytes+1); memcpy(event->text, &offset[0], number_bytes); event->text[number_bytes]='\0'; } else { dbg_print (CCX_DMT_GENERIC_NOTICES, "\rWarning: Unsupported ATSC multiple_string encoding detected!.\n"); } offset+=number_bytes; } } #undef CHECK_OFFSET } // decode ATSC EIT table. void EPG_ATSC_decode_EIT(struct lib_ccx_ctx *ctx, uint8_t *payload_start, uint32_t size) { uint8_t table_id; struct EPG_event event; uint8_t num_events_in_section; uint8_t *offset; int hasnew=false; int i, j; uint16_t source_id; int32_t pmt_map = -1; if (size < 11) return; table_id = payload_start[0]; source_id = ((payload_start[3]) << 8) | payload_start[4]; event.has_simple=false; event.extended_text=NULL; event.num_ratings=0; event.num_categories=0; event.live_output=false; for (i = 0; i < ctx->demux_ctx->nb_program; i++) { if (ctx->demux_ctx->pinfo[i].program_number == ctx->ATSC_source_pg_map[source_id]) pmt_map=i; } //Don't know how to store EPG until we know the programs. Ignore it. if(pmt_map==-1) pmt_map=TS_PMT_MAP_SIZE; num_events_in_section = payload_start[9]; #define CHECK_OFFSET(val) if(offset + val < (payload_start + size) ) return offset=&payload_start[10]; for(j = 0; j < num_events_in_section && offset < payload_start + size; j++) { uint16_t descriptors_loop_length; uint8_t title_length, emt_location; uint32_t length_in_seconds, start_time, full_id; uint16_t event_id; CHECK_OFFSET(10); event_id = ((offset[0]&0x3F) << 8) | offset[1]; full_id = (source_id << 16) | event_id; event.id=full_id; event.service_id=source_id; start_time = (offset[2] << 24) | (offset[3] << 16) | (offset[4] << 8)| (offset[5] << 0); EPG_ATSC_calc_time(event.start_time_string, start_time); emt_location = (offset[6]&0x30)>>4; length_in_seconds = (((offset[6]&0x0F) << 16) | (offset[7] << 8) | (offset[8] << 0)); EPG_ATSC_calc_time(event.end_time_string, start_time+length_in_seconds); title_length = offset[9]; //XXX cant decode data more then size of payload CHECK_OFFSET(11 + title_length); EPG_ATSC_decode_multiple_string(&offset[10], title_length, &event); descriptors_loop_length = ((offset[10+title_length] & 0x0f) << 8) | offset[10+title_length+1]; hasnew |= EPG_add_event(ctx, pmt_map, &event); offset += 12 + descriptors_loop_length + title_length; } if((ccx_options.xmltv==1 || ccx_options.xmltv==3) && ccx_options.xmltvoutputinterval==0 && hasnew) EPG_output(ctx); #undef CHECK_OFFSET } // decode ATSC VCT table. void EPG_ATSC_decode_VCT(struct lib_ccx_ctx *ctx, uint8_t *payload_start, uint32_t size) { uint8_t table_id; uint8_t num_channels_in_section; uint8_t *offset; int i; if (size <= 10) return; table_id = payload_start[0]; num_channels_in_section = payload_start[9]; offset = &payload_start[10]; for (i=0; i< num_channels_in_section; i++) { char short_name[7*2]; uint16_t program_number; uint16_t source_id; uint16_t descriptors_loop_length; if(offset + 31 > payload_start+size) break; program_number = offset[24]<<8 | offset[25]; source_id = offset[28]<<8 | offset[29]; descriptors_loop_length = ((offset[30] & 0x03) << 8) | offset[31]; memcpy(short_name, &offset[0], 7*2); offset += 32 + descriptors_loop_length; ctx->ATSC_source_pg_map[source_id]=program_number; } } void EPG_DVB_decode_EIT(struct lib_ccx_ctx *ctx, uint8_t *payload_start, uint32_t size) { uint8_t table_id; //uint8_t section_syntax_indicator = (0xf1&0x80)>>7; uint16_t section_length; uint16_t service_id; int32_t pmt_map = -1; int i; int hasnew = false; struct EPG_event event; uint8_t section_number; uint8_t last_section_number; uint8_t segment_last_section_number; uint32_t events_length; uint8_t *offset; uint32_t remaining; if(size < 13) return; table_id = payload_start[0]; //section_syntax_indicator = (0xf1&0x80)>>7; section_length = (payload_start[1]&0x0F)<<8 | payload_start[2]; service_id = (payload_start[3] << 8) | payload_start[4]; section_number = payload_start[6]; last_section_number = payload_start[7]; segment_last_section_number = payload_start[12]; events_length = section_length - 11; offset = payload_start; remaining = events_length; for (i = 0; i < ctx->demux_ctx->nb_program; i++) { if (ctx->demux_ctx->pinfo[i].program_number == service_id) pmt_map = i; } //For any service we don't have an PMT for (yet), store it in the special last array pos. if(pmt_map == -1) pmt_map = TS_PMT_MAP_SIZE; if(events_length > size-14) { dbg_print (CCX_DMT_GENERIC_NOTICES, "\rWarning: Invalid EIT packet size detected.\n"); //XXX hack to override segfault, we should concat packets instead return; } while(remaining > 4) { uint16_t descriptors_loop_length; uint8_t *descp; uint32_t duration; uint64_t start_time; event.id = (offset[14] << 8) | offset[15]; event.has_simple = false; event.extended_text = NULL; event.num_ratings = 0; event.num_categories = 0; event.live_output = false; event.service_id = service_id; //40 bits start_time = ((uint64_t)offset[16] << 32) | ((uint64_t)offset[17] << 24) | ((uint64_t)offset[18] << 16) | ((uint64_t)offset[19] << 8)| ((uint64_t)offset[20] << 0); EPG_DVB_calc_start_time(&event, start_time); //24 bits duration = (offset[21] << 16 ) | (offset[22] << 8 ) | (offset[23] << 0 ); EPG_DVB_calc_end_time(&event, start_time, duration); event.running_status = (offset[24] & 0xE0) >> 5; event.free_ca_mode = (offset[24] & 0x10) >> 4; //12 bits descriptors_loop_length = ((offset[24] & 0x0f) << 8) | offset[25]; descp = &offset[26]; if(descriptors_loop_length > remaining-16) { dbg_print (CCX_DMT_GENERIC_NOTICES, "\rWarning: Invalid EIT descriptors_loop_length detected.\n"); return; } while(descp<&(offset[26])+descriptors_loop_length) { if(descp+descp[1]+2>payload_start+size) { dbg_print (CCX_DMT_GENERIC_NOTICES, "\rWarning: Invalid EIT descriptor_loop_length detected.\n"); EPG_free_event(&event); return; } if(descp[0]==0x4d) EPG_decode_short_event_descriptor(descp+2, descp[1], &event); if(descp[0]==0x4e) EPG_decode_extended_event_descriptor(descp+2, descp[1], &event); if(descp[0]==0x54) EPG_decode_content_descriptor(descp+2, descp[1], &event); if(descp[0]==0x55) EPG_decode_parental_rating_descriptor(descp+2, descp[1], &event); if(descp[1]+2==0) { dbg_print (CCX_DMT_GENERIC_NOTICES, "\rWarning: Invalid EIT descriptor_length detected.\n"); return; } descp=descp+(descp[1]+2); } remaining = remaining - (descriptors_loop_length + 12); offset = offset + descriptors_loop_length + 12; hasnew |= EPG_add_event(ctx, pmt_map, &event); if(hasnew && section_number==0 && table_id==0x4e) ctx->eit_current_events[pmt_map]=event.id; } if((ccx_options.xmltv==1 || ccx_options.xmltv==3) && ccx_options.xmltvoutputinterval==0 && hasnew) EPG_output(ctx); } //handle outputing to xml files void EPG_handle_output(struct lib_ccx_ctx *ctx) { int cur_sec = (int) ((ctx->demux_ctx->global_timestamp - ctx->demux_ctx->min_global_timestamp) / 1000); if(ccx_options.xmltv==1 || ccx_options.xmltv==3) { //full outout if(ccx_options.xmltvoutputinterval!=0 && cur_sec>ctx->epg_last_output+ccx_options.xmltvliveinterval) { ctx->epg_last_output=cur_sec; EPG_output(ctx); } } if(ccx_options.xmltv==2 || ccx_options.xmltv==3 || ccx_options.send_to_srv) { //live output if(cur_sec>ctx->epg_last_live_output+ccx_options.xmltvliveinterval) { ctx->epg_last_live_output=cur_sec; if (ccx_options.send_to_srv) EPG_output_net(ctx); else EPG_output_live(ctx); } } } //determine table type and call the correct function to handle it void EPG_parse_table(struct lib_ccx_ctx *ctx, uint8_t *b, uint32_t size) { uint8_t pointer_field = b[0]; uint8_t *payload_start; uint8_t table_id; //XXX hack, should accumulate data if(pointer_field + 2 > size) { return; } payload_start = &b[pointer_field + 1]; table_id = payload_start[0]; switch (table_id) { case 0x0cb: EPG_ATSC_decode_EIT(ctx, payload_start, size - (payload_start - b)); break; case 0xc8: EPG_ATSC_decode_VCT(ctx, payload_start, size - (payload_start - b)); break; default: if (table_id>=0x4e && table_id<=0x6f) EPG_DVB_decode_EIT(ctx, payload_start, size - (payload_start - b)); break; } EPG_handle_output(ctx); } // reconstructs DVB EIT and ATSC tables void parse_EPG_packet(struct lib_ccx_ctx *ctx) { unsigned char *payload_start = tspacket + 4; unsigned payload_length = 188 - 4; unsigned transport_error_indicator = (tspacket[1]&0x80)>>7; unsigned payload_start_indicator = (tspacket[1]&0x40)>>6; // unsigned transport_priority = (tspacket[1]&0x20)>>5; unsigned pid = (((tspacket[1] & 0x1F) << 8) | tspacket[2]) & 0x1FFF; // unsigned transport_scrambling_control = (tspacket[3]&0xC0)>>6; unsigned adaptation_field_control = (tspacket[3]&0x30)>>4; unsigned ccounter = tspacket[3] & 0xF; unsigned adaptation_field_length = 0; int buffer_map = 0xfff; if ( adaptation_field_control & 2 ) { adaptation_field_length = tspacket[4]; payload_start = payload_start + adaptation_field_length + 1; payload_length = tspacket+188-payload_start; } if((pid!=0x12 && pid!=0x1ffb && pid<0x1000) || pid==0x1fff) return; if(pid!=0x12) buffer_map = pid-0x1000; if(payload_start_indicator) { if(ctx->epg_buffers[buffer_map].ccounter>0) { ctx->epg_buffers[buffer_map].ccounter=0; EPG_parse_table(ctx, ctx->epg_buffers[buffer_map].buffer, ctx->epg_buffers[buffer_map].buffer_length); } ctx->epg_buffers[buffer_map].prev_ccounter = ccounter; if(ctx->epg_buffers[buffer_map].buffer!=NULL) free(ctx->epg_buffers[buffer_map].buffer); else { // must be first EIT packet } ctx->epg_buffers[buffer_map].buffer = (uint8_t *)malloc(payload_length); memcpy(ctx->epg_buffers[buffer_map].buffer, payload_start, payload_length); ctx->epg_buffers[buffer_map].buffer_length=payload_length; ctx->epg_buffers[buffer_map].ccounter++; } else if(ccounter==ctx->epg_buffers[buffer_map].prev_ccounter+1 || (ctx->epg_buffers[buffer_map].prev_ccounter==0x0f && ccounter==0)) { ctx->epg_buffers[buffer_map].prev_ccounter = ccounter; ctx->epg_buffers[buffer_map].buffer = (uint8_t *)realloc(ctx->epg_buffers[buffer_map].buffer, ctx->epg_buffers[buffer_map].buffer_length+payload_length); memcpy(ctx->epg_buffers[buffer_map].buffer+ctx->epg_buffers[buffer_map].buffer_length, payload_start, payload_length); ctx->epg_buffers[buffer_map].ccounter++; ctx->epg_buffers[buffer_map].buffer_length+=payload_length; } else { dbg_print (CCX_DMT_GENERIC_NOTICES, "\rWarning: Out of order EPG packets detected.\n"); } } // Free all memory used for EPG parsing void EPG_free(struct lib_ccx_ctx *ctx) { if(ctx->epg_inited) { if(ccx_options.xmltv==2 || ccx_options.xmltv==3 || ccx_options.send_to_srv) { if (ccx_options.send_to_srv) EPG_output_net(ctx); else EPG_output_live(ctx); } } free(ctx->epg_buffers); free(ctx->eit_programs); free(ctx->eit_current_events); free(ctx->ATSC_source_pg_map); }