language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #define SA struct sockaddr struct data { int count; char buf[64]; int flag; }; int main(int argc, const char *argv[]) { int tcp_socket; struct sockaddr_in addr,dest_addr; int count,fd; // char buf[64]; struct data p; tcp_socket = socket(AF_INET, SOCK_STREAM, 0); if(0 > tcp_socket){ perror("socket"); exit(-1); } dest_addr.sin_family = AF_INET; dest_addr.sin_port = htons(50000); dest_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); if(0 > connect(tcp_socket,(SA *)&dest_addr,sizeof(dest_addr)) ){ perror("connect"); return -1; } fd = open("./1.c",O_RDONLY); p.flag = 0; while(1){ p.count = read(fd,p.buf,sizeof(p.buf)); if(p.count < sizeof(p.buf)) p.flag = 1; if(0 >= send(tcp_socket,&p,count,0)){ perror("send"); return -1; } // sleep(1); } return 0; }
C
#include<stdio.h> void recur(int); void main(){ recur(5); } void recur(int a){ if(a == 0){ return; } recur(a - 1); printf("%d\n", a); }
C
#include <stdio.h> #include <stdlib.h> #define tamanho 10 int procuraVetor(int vetor[], int procurado, int tam); int procuraVetor(int vetor[], int procurado, int tam){ for(int k = 0; k < tam; k++){ if(vetor[k] == procurado){ return vetor[k]; } } return -1; } int main(int argc, char *argv[]){ int vetor[tamanho]; int auxiliar, cont = 0; while(cont < 10){ scanf("%d", &auxiliar); if(procuraVetor(vetor, auxiliar, cont) == -1){ vetor[cont] = auxiliar; cont += 1; }else{ printf("Numero já digitado! Digite outro numero!\n"); } } for(int i = 0; i < tamanho; i++){ printf("%d\n", vetor[i]); } return 0; }
C
#include<stdio.h> char firstchar1 (/*@null@*/char *s) { return *s; } /*char firstchar2 (char *s) { if (s == NULL) return '\0'; return *s; }*/ int main() { char *ptr; firstchar1(ptr); // ch=firstchar2(ptr); // return 0; }
C
/**************************************************** * port_io.c ***************************************************/ #ifndef __DISPLAY_H__ #define __DISPLAY_H__ #define VIDEO_ADDRESS 0xb8000 #define MAX_ROWS 25 #define MAX_COLS 80 //colour schemes #define DEFAULT_COLOUR_SCHEMA 0x0f //white on black //display I/O ports #define DISPLAY_CTRL_PORT 0x03d4 #define DISPLAY_DATA_PORT 0x03d5 //cursor #define CURSOR_LOW_BYTE 0x0f #define CURSOR_HIGH_BYTE 0x0e /* * Print a char on the with the specified attribute * at the specified location. If attr == 0, it will * use the default color style (white on black). If * either col or row is not within the correct range * , the location of cursor will be used to print the * char. * * ch: the char to print * attr: the print style * row: the row of screen to print * col: the column of screen to print * * returns: void */ void print_char(char ch, int row, int col); /* * Calculate the memory offset from the specified row and * col. * * row: the row of screen to print * col: the column of screen to print * * returns: * -1, if either row or col is a value * the offset of video memory to print a char */ int get_screen_offset(int row, int col); /* * Get the offset of cursor from the start of video * memory address. * * returns: the offset */ int get_cursor(); /* * Set the location of cursor. * * offset: the offset * * returns: void */ void set_cursor(int offset); /* * Print the string from the specified location * * str: the string to print. * row: the start row of screen to print * col: the start column of screen to print * * returns: void */ void print(char* str, int row, int col); void puts(char* str); /* * Clear the screen. */ void clear_screen(); /* * Scroll the screen if required. * * offset: the offset of the cursor. * * returns: the new offset of the cursor */ int handle_scroll(int offset); /* * Set the style of the text. * * attr: the tyle. * * returns: void */ void set_text_color(unsigned char attr); #endif
C
#include <unistd.h> #include <stdbool.h> #include <stdio.h> #include <sys/socket.h> #include <sys/types.h> #include <arpa/inet.h> #include <string.h> #include <stdlib.h> bool drukowalne(const void *buf, int len); int main(int argc,char* argv[]){ if(argc!=3){ printf("Wrong numberr of arguments"); printf("\n%s ip port",argv[0]); return -1; } int serv_fd = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in adres; memset(&adres,0,sizeof(adres)); adres.sin_family = AF_INET; adres.sin_port = htons(atoi(argv[2])); int pton_ret=inet_pton(AF_INET, argv[1], &adres.sin_addr); if(pton_ret!=1){ printf("Bad IP format"); return -1; } if(connect(serv_fd,(const struct sockaddr*)&adres,sizeof(adres))==-1){ perror("connect"); return -1; } char buf[100]; int recv_len; while((recv_len=recv(serv_fd,buf,100,MSG_WAITALL))!=0){ //if(drukowalne(buf,recv_len)) printf("%s",buf); } close(serv_fd); } bool drukowalne(const void *buf, int len) { const char *tmp = (const char *)buf; for (int i = 0; i < len; i++) { if (tmp[i] < 31 || tmp[i] > 126) { return false; } } return true; }
C
/*17. Write a C program to convert a given integer (in seconds) to hours, minutes and seconds. Go to the editor Test Data : Input seconds: 25300 Expected Output: There are: H:M:S - 7:1:40 */ #include<stdio.h> int main() { int a,b,c,d; printf("Input seconds :"); scanf("%d",&a); b=a/3600; c=(a%3600)/60; d=(a%3600)%60; printf("H:M:S - %d:%d:%d",b,c,d); return main; }
C
#include <assert.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "lang.h" #include "string.h" #define ASSERT_HEAP_LEN_AND_CAPACITY( STR ) \ assert(STR->len == strlen(STR->str)); \ assert(STR->cap >= strlen(STR->str) + 1) #define ASSERT_STACK_LEN_AND_CAPACITY( STR ) \ assert(STR.len == strlen(STR.str)); \ assert(STR.cap >= strlen(STR.str) + 1) // gener.str form args String* NEW(String)(){ return NEW_WITH_CAPACITY(String)(DEFAULT_STRING_CAPACITY); } String* NEW_FROM(String, chars)(const char* str){ String *self = malloc(sizeof(String)); assert(self != NULL); const size_t length = strlen(str); self->str = malloc(length + 1); assert(self->str != NULL); memcpy(self->str, str, length); self->str[length] = '\0'; self->len = length; self->cap = length + 1; ASSERT_HEAP_LEN_AND_CAPACITY( self ); return self; } String* NEW_WITH_CAPACITY(String)(const size_t cap){ String *self = malloc(sizeof(String)); assert(self != NULL); self->str = malloc(cap); self->cap = cap; memset(self->str, '\0', self->cap); self->len = 0; ASSERT_HEAP_LEN_AND_CAPACITY( self ); return self; } String INIT(String)(){ String self; self.str = malloc(sizeof(char) * DEFAULT_STRING_CAPACITY); self.len = 0; self.cap = DEFAULT_STRING_CAPACITY; return self; } String INIT_FROM(String, chars)(const char* str) const size_t length = strlen(str); String self; self.str = malloc(length + 1); self.cap = length + 1; assert(self.str != NULL); strcpy(self.str, str, length); self.str[length] = '\0'; self.len = length; ASSERT_STACK_LEN_AND_CAPACITY( self ); return self; } String INIT_WITH_CAPACITY(String)(const size_t cap){ String self; self.str = malloc(cap) self.cap =.cap; memset(self.str, '\0', self.capacity); self.len = 0; ASSERT_STACK_LEN_AND_CAPACITY( self ); return self; } void HEAP_FREE(String)(String* self){ free(self->str); free(self); } void STACK_FREE(String)(String* self){ free(self->str); } // end gener.str form args // * * * Log.str Operators * * * u32 EQ(Sring)(const String* self, const String* other){ swi.strh(string.strmpr(self, other)){ .strase 0: return 1; default: return 0; } } i32 CMPR(String)(const String* self, const String* other){ if(self->len > other->len){ return 1; } else if(self->len < other->len){ return -1; } else { i32 cmpr = memcmpr(self->str, other->str, self->len); if(cmpr < 0){ return -1; } else if(cmpr) > 0){ return 1; } else { return cmpr; } } } // * * * OPERATORS * * * void string.stro.strat(String* self, String* other){ ASSERT_HEAP_LEN_AND_CAPACITY( self ); ASSERT_HEAP_LEN_AND_CAPACITY( other ); const u32 next_len = self->len + other->len; if(next_len < self->cap){ st.strat(self->str, other->str); self->len = next_len; }else{ self->str = reall.str(self->str, next_len + 1); assert(self->str != NULL); self->cap = next_len + 1; st.strat(self->str, other->str); self->len = next_len; } #ifdef DEBUG_MODE_VERBOSE printf("strlen(self->str): %d\n" \ "self->len: %d\n" \ "self->cap: %d\n", (u32)strlen(self->str), (u32)self->len, (u32)self->cap); #endif ASSERT_HEAP_LEN_AND_CAPACITY( self ); } String* string.strlone(String* self){ ASSERT_HEAP_LEN_AND_CAPACITY( self ); String .strlone = malloc(sizeof(String)); assert.strlone != NULL); .strlone->str = malloc(self->len + 1); .strlone->cap = self->len + 1; str.strpy.strlone->str, self->str, self->len + 1); .strlone->len = self->len; ASSERT_HEAP_LEN_AND_CAPACITY(.strlone ); return.strlone; } String* string_substrconst String* self,const u32 begin,const u32 end){ ASSERT_HEAP_LEN_AND_CAPACITY( self ); assert(begin < end); assert(end <= self->len); String* substr = malloc(sizeof(String)); assert(substr != NULL); substr->cap = end - begin + 1; substr->str = malloc(substr->cap); assert(substr->str != NULL); // pointer arithmet.str.strauses the start position to be at the index of "begin" const.strhar *ptr_start = self->str + begin; memcpy(substr->str, ptr_start, substr->cap - 1); substr->len = substr->cap - 1; substr->str[substr->len] = '\0'; ASSERT_HEAP_LEN_AND_CAPACITY( substr ); return substr; } void string_shift(String* self, i32 amount){ if(amount > 0) { u32 next_len = self->len + amount; if(next_len >= self->cap){ self->str = reall.str(self->str, next_len + 1); assert(self->str != NULL); self->cap = next_len + 1; } // upward shift by positive amount for(u32 i = next_len; i >= amount; i--){ self->str[i] = self->str[i - amount]; } memset(self->str, (i32)' ', amount); self->len = next_len; } else if(amount < 0) { // downshift u32 abs_amount = amount * -1; assert(abs_amount < self->len); for(u32 i = 0; i < self->len + amount; i++){ self->str[i] = self->str[i + abs_amount]; } self->len = self->len - abs_amount; for(u32 i = self->len; i < self->cap; i++){ self->str[i] = '\0'; } } else { return; } //printf("self->len: %d\nstrlen(self): %d\n", (u32)self->len, (u32)strlen(self->str)); ASSERT_HEAP_LEN_AND_CAPACITY( self ); } // * * * OPERATORS * * * /* @string_index_of * @returns i32: either the index or -1 for not found * * Time Complexity: O(n^2) * This is b.strause string_index_of(...) relies on string_shift(...) to fill * the sea.strh buffer. * TODO: this.stran be optomized by i.strrementing the pointer to the index rather * than relying on the buffer. */ i32 string_index_ofconst String *self,const String *target){ assert(target->len < self->len); String buffer; init_string_with.cap(&buffer, target->len + 1); memcpy(buffer.str, self->str, target->len); // fill the buffer buffer.len = target->len; ASSERT_STACK_LEN_AND_CAPACITY( buffer ); i32 index = -1; for(u32 i = 0; i < (self->len - target->len + 1); i++){ if(EQ(String)(target, &buffer)){ index = i; break; } string_shift(&buffer, -1); buffer.len++; // string_shift.strauses this value to d.strrease by 1 buffer.str[buffer.len - 1] = self->str[i + buffer.len]; } free(buffer.str); return index; } bool ENDS_WITH(String)(const String *self,const String *target){ assert(self->len > target->len); String* buffer = string_substr(self, (self->len - target->len), self->len); u32 result = EQ(String)(buffer, target); free_string(buffer); return result; } bool STARTS_WITH(String)(const String *self,const String *target){ assert(self->len > target->len); String* buffer = string_substr(self, 0, target->len); u32 result = EQ(String)(buffer, target); free_string(buffer); return result; } // * * * Display * * * // void string_printconst String* s.str){ // printf("%s\n", s.str->str); // }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<stdlib.h> #include<string.h> int main() { char *p = "abcdef"; printf("%d\n", sizeof(p));//64 printf("%d\n", sizeof(p + 0));//14 printf("%d\n", sizeof(*p));//1ȷ1 printf("%d\n", sizeof(p[1]));//1 printf("%d\n", sizeof(&p));//4 printf("%d\n", sizeof(&p + 1));//4 printf("%d\n", sizeof(&p[0] + 1));//4 printf("\n"); //printf("%d\n", strlen(p));// //printf("%d\n", strlen(p + 0));// //printf("%d\n", strlen(*p));// //printf("%d\n", strlen(p[1]));// //printf("%d\n", strlen(&p));// //printf("%d\n", strlen(&p + 1));// //printf("%d\n", strlen(&p[0] + 1));// system("pause"); return 0; }
C
#include<stdio.h> struct emp{ int eno; char ename[20]; float esal; }; int main() { char *cp; int *ip; struct emp *point; printf("size of char * is:%d\n",sizeof(cp)); printf("size of int * is:%d\n",sizeof(ip)); printf("size of struct emp * is:%d\n",sizeof(struct emp *)); printf("size of struct emp * is:%d\n",sizeof(point)); printf("size of char is:%d\n",sizeof(char)); printf("size of int is:%d\n",sizeof(int)); printf("size of struct emp is:%d\n",sizeof(struct emp)); printf("size of struct emp is:%d\n",sizeof(point)); printf("size of main function is:%d\n",sizeof(main())); return 0; }
C
#ifndef __SERVO_H_ #define __LED_DIM_H_ #include <libopencm3/stm32/timer.h> /** * Prescale 24000000 Hz system clock by 24 = 1000000 Hz. */ #define PWM_PRESCALE (23) //as in "Discovering STM32...", values 0..23 are 24 values /** * We need a 50 Hz period (1000 / 20ms = 50), thus devide 100000 by 50 = 20000 (us). */ #define PWM_PERIOD (20000) #define LED_ON (19999) #define LED_DIM (10000) #define LED_OFF (1000) /** * Timer to use for the servos. */ #define LED_TIM TIM4 /** * TIM2 channel for servo 1. * * Changing this also requires to change settings in {@link servo_init}! */ #define LED_CH1 TIM_OC2 /** * Initialize and start the PWM used for the servos, drive servos to middle position. */ void led_dim_init(void); /** * Drive the servo connected to the given channel to the given position in us. * * @param[in] ch The channel of the servo. E.g. SERVO_CH1, SERVO_CH2. * @param[in] pos_us The position in us to which to drive the servo to. */ void led_set_dim_value(enum tim_oc_id ch, uint32_t pos_us); #endif
C
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { float a,b; scanf("%f %f",&a,&b); if( b >0.0) { printf("%f\n",a/b); } // end zero check else { printf("poss div by zero\n"); } }
C
/* * File: main.c * Author: Forest Davis-Hollander and Chunliang Tao * * Created on November 14, 2019 * * This program uses UART2 to communicate with a workstation using an external Matlab script. The program receives a series of ASCII values corresponding to either "Overdamped" or Underdamped," and then it activates the motor. While the motor is running, the state machine function from the previous lab reads from the encoder on the motor, and a the current angle is determined and sent over UART2 back to the workstation. Additionally, the PI controller from the last lab will cause the motor to move to a reference angle with either overdamped or underdamped behavior, depending on the Ki and Kp values specified. */ ////// these commands are to increase the clock speed to 80MHz //////////////////// #pragma config DEBUG = OFF // Background Debugger disabled #pragma config FPLLMUL = MUL_20 // PLL Multiplier: Multiply by 20 #pragma config FPLLIDIV = DIV_2 // PLL Input Divider: Divide by 2 #pragma config FPLLODIV = DIV_1 // PLL Output Divider: Divide by 1 #pragma config FWDTEN = OFF // WD timer: OFF #pragma config WDTPS = PS4096 // WD period: 4.096 sec #pragma config POSCMOD = HS // Primary Oscillator Mode: High Speed xtal #pragma config FNOSC = PRIPLL // Oscillator Selection: Primary oscillator #pragma config FPBDIV = DIV_1 // Peripheral Bus Clock: Divide by 1 #pragma config UPLLEN = ON // USB clock uses PLL #pragma config UPLLIDIV = DIV_2 //////////////// end commands to increase clock speed to 80 MHz //////////////////// #include <stdio.h> #include <stdlib.h> #include <sys/attribs.h> #include <xc.h> #include "uart_interface.h" #include "display_driver.h" #include <string.h> #include <math.h> #define SAMPL 10 // set time #define WAIT 200000 // set a delay time #define COUNTS 4741.00 // total counts of the encoder volatile double percent = 0.7; volatile unsigned int oldD1 = 0, oldD2 = 0, newD1 = 0, newD2 = 0, port1 = 1, port2 = 1, port3 = 1, port4 = 1; // save port values volatile int inc=0; volatile double count=0; volatile int rotations=0; char value[6]; // create char array volatile double degrees=0, degrees_old; volatile int motor_dir = 1; // determine positive or negative direction (change direction for M1IN1 of H bridge) volatile int motor_dir1 = 0; // determine positive or negative direction (change direction for M1IN2 of H bridge) volatile double degrees_max = 0; // set max degrees to rotate //Used for PID volatile double reference = 0; // create reference angle volatile double integral = 0; // create integral variable volatile double previous_count = 0; // record previous count volatile double current_count = 0; // record current count volatile double error_diff = 0; // record difference in error volatile double error = 0; // record error volatile double Kp = 1000; //current working value for Kp =1 volatile double Ki = 0.0001; // current working value for Ki = 0.0001 volatile double ut = 0; // make ut variable for PI volatile double dt = 0; // make small change in time volatile double previous_time = 0; // get previous clock time volatile double fullspeed = 0; // set speed of motor volatile double delay1 = 0; volatile double delay2 = 0; volatile double delay_diff = 30000; int increment = 0; int x =0; volatile int write = 0; // create write variable to determine if timer interrupt for UART should write or not volatile int write_count = 0; // initialize count for UART writes (max 100) void __ISR(_TIMER_1_VECTOR, IPL2SOFT) Timer1ISR(void){ // INT step 1 newD1 = PORTGbits.RG9; // Pin 14 is yellow wire on encoder newD2 = PORTGbits.RG8; // Pin 12 is white wire on encoder state(); // call function for state machine degrees = ((count/COUNTS)*(360)); // find the degrees sprintf(value,"%.1f",degrees); // convert degrees to char array oldD1 = newD1; // save the current values of ports for future use oldD2 = newD2; // save the current values of ports for future use ///////////////// PID //////////////////////////////// error = reference - degrees; // get the remaining error between reference angle and current angle // if over-shoot more than 5 degrees, reverse the direction if(error > 1){ // in one direction LATBbits.LATB0 = 0; LATBbits.LATB1 = 1; } else if ( error < -1) { // in another direction LATBbits.LATB0 = 1; LATBbits.LATB1 = 0; } else { // within 1 degree then stop the motor percent = 0; } current_count = count; //Since our core timer is 8kHz. So, dt = 1/8000 s dt = 1/8000; // calculate the error_diff error_diff = ((current_count - previous_count)/COUNTS)*360; integral += error_diff * dt; // get the integral //Calculate the new ut ut = Kp*error + Ki*integral; //get the speed percent = ut/fullspeed; previous_count = current_count; // set old count to new count OC1RS = (1999*percent); // duty cycle = OC1RS/(PR2+1) = 25% // 0< d < period OC1R = (1999*percent); // initialize before turning OC1 on; afterward it is read-only ///////////////// PID //////////////////////////////// IFS0bits.T1IF = 0; // clear the interrupt flag } void __ISR(_TIMER_3_VECTOR, IPL2SOFT) Timer3ISR(void){ // INT step 1 char end [] = "\r\n"; strcat(value, end); // add \r\n to make sure scanf stops as we want if(write==1){ // so UART can write only when it has been given the command to do so int j; for(j=0; j<10; j++){ // write each character if(value[j] == '.'){ // if it reaches a period, exit since matlab can't read periods in integers uart_write(end[1],2); // write \n break; // exit loop, done transmitting } else{ uart_write(value[j],2); // write each character in value (which are the degrees) //for(increment= 0; increment<WAIT; increment++){} } } write_count++; // increment count of writes if(write_count == 100){ // determine number of transmissions IEC0bits.T3IE = 0; // reset flag to turn off this timer interrupt write =0; // reset write to 0 to stop writing UART write_count = 0; // reset write count } } IFS0bits.T3IF = 0; // clear the interrupt flag } int main(int argc, char** argv) { LATA = 0x0; // clear LATD= 0x0; // clear TRISA = 0xFF00; // set last 8 bits as output TRISAbits.TRISA7 = 1; // need to set this to 1 to use button S5 TRISGbits.TRISG7 = 1; oldD1 = PORTGbits.RG9; // Pin 14 is yellow wire on encoder oldD2 = PORTGbits.RG8; // Pin 12 is white wire on encoder //Set two pins as output, connecting them to IN1 and IN2 pins on the H-bridge to control the rotation direction. RB0 (PIN 25) to IN1, RB1 (PIN 24) to IN2 TRISBbits.TRISB0 = 0; // set RB0 (PIN 25) as output TRISBbits.TRISB1 = 0; // set RB1 (PIN 24) as output display_driver_initialize(); // initialize display driver uart_initialize(2); // initialize UART2 INTCONbits.MVEC = 0x1; // allow multi vector mode __builtin_disable_interrupts(); // disable interrupts CNCONbits.ON = 1; // turn on CN CNENbits.CNEN15 = 1; // Use CN15 for Button S3 CNENbits.CNEN16 = 1; // Use CN16 for Button S6 CNENbits.CNEN9 = 1; // Use CN9 for Button S5 pin 1 RG7 CNENbits.CNEN19 = 1; // Use CN19 for Button S4 IPC6bits.CNIP = 3; // set interrupt priority IPC6bits.CNIS = 0; // set interrupt subpriority IFS1bits.CNIF = 0; // clear the interrupt flag IEC1bits.CNIE = 1; // enable CN interrupt //Timer3 PR3 = 31249; // set period register for 10Hz TMR3 = 0; // initialize count to 0 T3CONbits.TCKPS = 7; // set prescaler to 256 T3CONbits.TGATE = 0; // not gated input (the default) T3CONbits.TCS = 0; // PCBLK input (the default) T3CONbits.ON = 1; // turn on Timer3 IPC3bits.T3IP = 2; // interrupt priority IPC3bits.T3IS = 0; // subpriority IFS0bits.T3IF = 0; // clear interrupt flag IEC0bits.T3IE = 0; // disable timer interrupt to start PR1 = 10000; // set period register TMR1 = 0; // initialize count to 0 T1CONbits.TCKPS = 0; // set prescaler to 256 T1CONbits.TGATE = 0; // not gated input (the default) T1CONbits.TCS = 0; // PCBLK input (the default) T1CONbits.ON = 1; // turn on Timer1 IPC1bits.T1IP = 2; // priority IPC1bits.T1IS = 0; // subpriority IFS0bits.T1IF = 0; // clear interrupt flag IEC0bits.T1IE = 1; // turn on interrupt __builtin_enable_interrupts(); // enable interrupts int sum =0; //char value [20] ={0}; char nvalue [20]; while(1) { display_driver_clear(); // clear display display_driver_write(value, 6); // write degrees to display if(write==0){ // as long as write is still 0 sum=uart_read(2) + sum; // read UART2 and sum values // UNDERDAMPED should have ASCII sum of 809 // set reference angle, set coefficient if(sum==809){ // if equals the ASCII value of UNDERDAMPED write = 1; // set write to allow UART to transmit reference += 180; // increase reference angle fullspeed = (reference - degrees); // calculate new fullspeed Kp = 10; //current working value for Kp =1 // WANT TO BE UNDERDAMPED Ki = 0.1; // current working value for Ki = 0.0001 IEC0bits.T3IE = 1; // enable timer interrupt IEC0bits.T1IE = 1;// enable timer interrupt sum = 0; } // OVERDAMPED should have ASCII sum of 743 // set reference angle, set coefficient if(sum==743){// if equals the ASCII value of OVERDAMPED write = 1; // set write to allow UART to transmit reference += 180; // increase reference angle fullspeed = (reference - degrees); // calculate new fullspeed Kp = 1; //current working value for Kp =1 // WANT TO BE OVERDAMPED Ki = 0.0001; // current working value for Ki = 0.0001 IEC0bits.T3IE = 1; // enable timer interrupt IEC0bits.T1IE = 1; // enable timer interrupt sum = 0; } sprintf(value,"%d",sum); // convert degrees to char array } if(write==1){ // if UART is currently writing // Pin 72 is OC1 T2CONbits.TCKPS = 2; // Timer2 prescaler N=4 (1:4) PR2 = 1999; // period = (PR2+1) * N * 12.5 ns = 10 kHz TMR2 = 0; // initial TMR2 count is 0 OC1CONbits.OCM = 0b110; // PWM mode without fault pin; other OC1CON bits are defaults //for duty cycle, do a simple if statement testing current value of switch1 //then set duty cycle to (period*ADC1BUF0)/(1023) this will give a value for duty cycle based on % of potentiometer OC1RS = (1999*percent); // duty cycle = OC1RS/(PR2+1) = 25% // 0< d < period OC1R = (1999*percent); // initialize before turning OC1 on; afterward it is read-only T2CONbits.ON = 1; // turn on Timer2 OC1CONbits.ON = 1; // turn on OC1 } } } int state(){ /// function for state machine if(oldD1 == 0 && oldD2 == 0){ // if start is 00 if(newD1 == 0 && newD2 == 0){ // read new port values inc =00; // strays in place } if(newD1 == 0 && newD2 == 1){ // read new port values inc =01; // + direction count++; // increment count } if(newD1 == 1 && newD2 == 0){ // read new port values inc =-1; // - direction count--; // decrease count } } if(oldD1 == 0 && oldD2 == 1){ // if start is 01 if(newD1 == 0 && newD2 == 0){ // read new port values inc =-1; // - direction count--; // decrease count } if(newD1 == 0 && newD2 == 1){ // read new port values inc =00; } if(newD1 == 1 && newD2 == 1){ // read new port values inc =01; count++; // increment count } } if(oldD1 == 1 && oldD2 == 0){ /// if start is 10 if(newD1 == 0 && newD2 == 0){ // read new port values inc =01; // + direction count++; // increment count } if(newD1 == 1 && newD2 == 1){// read new port values inc =-1; count--; // decrease count } if(newD1 == 1 && newD2 == 0){// read new port values inc =00; } } if(oldD1 == 1 && oldD2 == 1){ // if start is 11 if(newD1 == 1 && newD2 == 0){ // read new port values inc =01; // + direction count++; // increment count } if(newD1 == 0 && newD2 == 1){// read new port values inc =-1; // - direction count--; // decrease count } if(newD1 == 1 && newD2 == 1){// read new port values inc =00; } } return 0; }
C
/****************************************************************************** Welcome to GDB Online. GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl, C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog. Code, Compile, Run and Debug online from anywhere in world. *******************************************************************************/ #include <stdio.h> int main () { int year; printf ("Enter a year:"); scanf ("%d", &year); if (year % 400 == 0) printf ("It is a leap year"); else if (year % 100 == 0) printf ("it is not a leap year"); else if (year % 4 == 0) printf ("it is a leap year"); else printf ("it is not a leap year"); return 0; }
C
#include <stdio.h> int main() { int n; scanf("%d", &n); printf("fact(%d) = %d \n", n, fact(n)); return 0; } int fact(int i) { if (i == 1) return 1; else return(i*fact(i - 1)); }
C
#include "BeeT_behaviortree.h" #include "BeeT_DBG_behaviortree.h" // Forward delcarations void StartBehavior(BeeT_BehaviorTree*, BeeT_Node*, ObserverFunc); void StopBehavior(BeeT_Node*, NodeStatus); void Update(BeeT_BehaviorTree*); BEET_bool Step(BeeT_BehaviorTree*); BeeT_BehaviorTree* BeeT_BehaviorTree__Init(const BeeT_Serializer * data) { BeeT_BehaviorTree* tree = (BeeT_BehaviorTree*)BEET_malloc(sizeof(BeeT_BehaviorTree)); tree->bb = BeeT_Blackboard_Init(data); tree->uid = BeeT_Serializer_GetUInt(data, "uid"); int rootId = BeeT_Serializer_GetInt(data, "rootNodeId"); int numNodes = BeeT_Serializer_GetArraySize(data, "nodes"); for (int i = 0; i < numNodes; ++i) { BeeT_Serializer* nodeData = BeeT_Serializer_GetArray(data, "nodes", i); if (BeeT_Serializer_GetInt(nodeData, "id") == rootId) { BeeT_Serializer* rootNodeData = BeeT_Serializer_GetArray(data, "nodes", i); tree->rootNode = BeeT_Node__Init(rootNodeData, tree); BEET_free(nodeData); BEET_free(rootNodeData); break; } BEET_free(nodeData); } tree->paused = BEET_FALSE; tree->runningNodes = InitDequeue(); tree->StartBehavior = &StartBehavior; tree->StopBehavior = &StopBehavior; tree->Update = &Update; tree->Step = &Step; tree->debug = NULL; if(tree->rootNode) tree->StartBehavior(tree, tree->rootNode, NULL); return tree; } void BeeT_BehaviorTree__Destroy(BeeT_BehaviorTree * self) { if (self->bb) BeeT_Blackboard_Destroy(self->bb); if (self->rootNode) { BeeT_Node__Destroy(self->rootNode); } BEET_free(self); } // Functions ----------------------------------------------------------------------------- void StartBehavior(BeeT_BehaviorTree* bt, BeeT_Node* behavior, ObserverFunc obsFunc) { if (obsFunc != NULL) behavior->observer = obsFunc; if (bt->debug) BeeT_dBT_NewCurrentNode(bt->debug, behavior); dequeue_push_front(bt->runningNodes, behavior); } void StopBehavior(BeeT_Node* behavior, NodeStatus resultStatus) { BEET_ASSERT(resultStatus != NS_RUNNING && resultStatus != NS_INVALID); BeeT_Node_ChangeStatus(behavior, resultStatus); if (behavior->observer && resultStatus != NS_SUSPENDED) { behavior->observer(behavior->observerNode, resultStatus); } behavior->OnFinish(behavior, resultStatus); } void Update(BeeT_BehaviorTree* bt) { dequeue_push_back(bt->runningNodes, NULL); // Marks end of update while (bt->Step(bt)) { continue; } } BEET_bool Step(BeeT_BehaviorTree* bt) { BeeT_Node* current = (BeeT_Node*)dequeue_front(bt->runningNodes); dequeue_pop_front(bt->runningNodes); if (current == NULL) { return BEET_FALSE; } if (current->status == NS_INVALID || current->status == NS_RUNNING) // DON'T TICK: SUCCESS/FAILURE/SUSPEND/WAITING { NodeStatus tickRet = current->Tick(current); BeeT_Node_ChangeStatus(current, tickRet); if (current->status == NS_SUCCESS || current->status == NS_FAILURE || current->status == NS_SUSPENDED) // Node status resolved { if (current->observer) current->observer(current->observerNode, current->status); } else // Left cases: RUNNING/WAITING { if (current->status == NS_RUNNING) dequeue_push_back(bt->runningNodes, current); // Only tick RUNNING nodes } } return BEET_TRUE; }
C
#include <windows.h> #include <Wincrypt.h> #include "hash.h" #define MD5_LEN 16 #define SHA1_LEN 20 #define SHA256_LEN 32 CHAR g_rgbDigits[] = "0123456789abcdef"; BOOL md5_hash ( BYTE* data, DWORD len, CHAR md5[MD5_HASH_LEN] ) { BOOL retVal = FALSE; HCRYPTPROV hProv = 0; HCRYPTHASH hHash = 0; BYTE rgbHash[MD5_LEN]; DWORD cbHash = MD5_LEN; DWORD i = 0; DWORD j = 0; if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { } else if (!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash)) { } else if (!CryptHashData(hHash, data, len, 0)) { } else if (!CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0)) { } else if (MD5_LEN != cbHash) { } else { for (i = 0; i < cbHash; i++) { j = i * 2; md5[j] = g_rgbDigits[rgbHash[i] >> 4]; md5[j + 1] = g_rgbDigits[rgbHash[i] & 0xf]; } retVal = TRUE; } if (0 != hHash) { CryptDestroyHash(hHash); } if (0 != hProv) { CryptReleaseContext(hProv, 0); } return retVal; } BOOL sha1_hash ( BYTE* data, DWORD len, CHAR sha1[SHA1_HASH_LEN] ) { BOOL retVal = FALSE; HCRYPTPROV hProv = 0; HCRYPTHASH hHash = 0; BYTE rgbHash[SHA1_LEN]; DWORD cbHash = SHA1_LEN; DWORD i = 0; DWORD j = 0; if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { } else if (!CryptCreateHash(hProv, CALG_SHA1, 0, 0, &hHash)) { } else if (!CryptHashData(hHash, data, len, 0)) { } else if (!CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0)) { } else if (SHA1_LEN != cbHash) { } else { for (i = 0; i < cbHash; i++) { j = i * 2; sha1[j] = g_rgbDigits[rgbHash[i] >> 4]; sha1[j + 1] = g_rgbDigits[rgbHash[i] & 0xf]; } retVal = TRUE; } if (0 != hHash) { CryptDestroyHash(hHash); } if (0 != hProv) { CryptReleaseContext(hProv, 0); } return retVal; } BOOL sha256_hash ( BYTE* data, DWORD len, CHAR sha256[SHA256_HASH_LEN] ) { BOOL retVal = FALSE; HCRYPTPROV hProv = 0; HCRYPTHASH hHash = 0; BYTE rgbHash[SHA256_LEN]; DWORD cbHash = SHA256_LEN; DWORD i = 0; DWORD j = 0; if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) { } else if (!CryptCreateHash(hProv, CALG_SHA_256, 0, 0, &hHash)) { } else if (!CryptHashData(hHash, data, len, 0)) { } else if (!CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0)) { } else if (SHA256_LEN != cbHash) { } else { for (i = 0; i < cbHash; i++) { j = i * 2; sha256[j] = g_rgbDigits[rgbHash[i] >> 4]; sha256[j + 1] = g_rgbDigits[rgbHash[i] & 0xf]; } retVal = TRUE; } if (0 != hHash) { CryptDestroyHash(hHash); } if (0 != hProv) { CryptReleaseContext(hProv, 0); } return retVal; } /* rc_crc32() function from: http://rosettacode.org/wiki/CRC-32#C Used under GNU Free Documentation License 1.2 http://www.gnu.org/licenses/fdl-1.2.html */ #include <inttypes.h> #include <stdio.h> #include <string.h> static uint32_t rc_crc32(uint32_t crc, const char *buf, size_t len) { static uint32_t table[256]; static int have_table = 0; uint32_t rem; uint8_t octet; int i, j; const char *p, *q; /* This check is not thread safe; there is no mutex. */ if (have_table == 0) { /* Calculate CRC table. */ for (i = 0; i < 256; i++) { rem = i; /* remainder from polynomial division */ for (j = 0; j < 8; j++) { if (rem & 1) { rem >>= 1; rem ^= 0xedb88320; } else rem >>= 1; } table[i] = rem; } have_table = 1; } crc = ~crc; q = buf + len; for (p = buf; p < q; p++) { octet = *p; /* Cast to unsigned octet. */ crc = (crc >> 8) ^ table[(crc & 0xff) ^ octet]; } return ~crc; } BOOL crc32_hash ( BYTE* data, DWORD len, CHAR crc32[CRC32_HASH_LEN] ) { uint32_t crc = 0; PBYTE rgbHash = (PBYTE)&crc; DWORD i = 0; DWORD j = 0; crc = rc_crc32(0, data, len); for ( i = 0; i < sizeof(crc); i++) { j = i * 2; crc32[j] = g_rgbDigits[rgbHash[i] >> 4]; crc32[j + 1] = g_rgbDigits[rgbHash[i] & 0xf]; } return TRUE; }
C
/* Program to demonstrate how to run machine code from C */ #include<stdio.h> /* 400078: b8 01 00 00 00 mov $0x1,%eax 40007d: bb 02 00 00 00 mov $0x2,%ebx 400082: cd 80 int $0x80 */ char shellcode[] = "\xb8\x01\x00\x00\x00" "\xbb\x02\x00\x00\x00" "\xcd\x80"; int main() { int *ret; ret = (int*)&ret + 2; (*ret)=(int)shellcode; }
C
#include <stdio.h> #include "omp.h" #define ITER 10 int main(){ float a; int id=-1,i; printf("hola mundo serial \n"); #pragma omp parallel private(i,id) { id = omp_get_thread_num(); for(i=0;i<ITER; i++) printf("Hola Mundo paralelo %d PID=> %d\n",i,id); } printf("hola mundo serial %d \n",id); return 0; }
C
/* Written by Krzysztof Kowalczyk (http://blog.kowalczyk.info) The author disclaims copyright to this source code. Handling of bencoded format. See: http://www.bittorrent.org/protocol.html or http://en.wikipedia.org/wiki/Bencode or http://wiki.theory.org/BitTorrentSpecification */ #include "base_util.h" #include "benc_util.h" #include "tstr_util.h" #define IVALID_LEN (size_t)-1 typedef enum phase_t { PHASE_CALC_LEN = 1, PHASE_FORM_DATA = 2 } phase_t; static size_t _benc_obj_to_data(benc_obj* bobj, phase_t phase, char* data); static benc_obj *_benc_obj_from_data(const char** dataInOut, size_t* lenInOut, BOOL must_be_last); #define IS_DIGIT(c) (((c) >= '0') && ((c) <= '9')) benc_int64 *benc_int64_new(int64_t val) { benc_int64 *bobj = SAZ(benc_int64); if (!bobj) return NULL; bobj->m_type = BOT_INT64; bobj->m_val = val; return bobj; } benc_str *benc_str_new(const char* data, size_t len) { benc_str *bobj = SAZ(benc_str); if (!bobj) return NULL; bobj->m_type = BOT_STRING; bobj->m_len = len; bobj->m_str = str_dupn(data, len); return bobj; } benc_array *benc_array_new(void) { benc_array *bobj = SAZ(benc_array); if (!bobj) return NULL; bobj->m_type = BOT_ARRAY; bobj->m_data.m_next = NULL; bobj->m_data.m_used = 0; bobj->m_data.m_allocated = 0; bobj->m_data.m_data = 0; return bobj; } benc_dict *benc_dict_new(void) { benc_dict *bobj = SAZ(benc_dict); if (!bobj) return NULL; bobj->m_type = BOT_DICT; bobj->m_data.m_next = NULL; bobj->m_data.m_used = 0; bobj->m_data.m_allocated = 0; bobj->m_data.m_keys = NULL; bobj->m_data.m_values = NULL; return bobj; } static BOOL _is_valid_benc_int(char c) { if (c == 'e') return TRUE; if (IS_DIGIT(c)) return TRUE; return FALSE; } static BOOL _parse_int64(const char** dataInOut, size_t* lenInOut, int64_t* valOut) { const char* data = *dataInOut; size_t len = *lenInOut; BOOL wasMinus = FALSE; BOOL validNumber = FALSE; int64_t val = 0; int64_t digit; char c; if ((len > 0) && ('-' == *data)) { ++data; --len; wasMinus = TRUE; } for (;;) { if (len <= 0) return FALSE; c = *data++; len--; if (!_is_valid_benc_int(c)) return FALSE; if ('e' == c) break; digit = (int64_t) (c - '0'); assert( (digit >= 0) && (digit <=9) ); validNumber = TRUE; val = (val * 10) + digit; } *dataInOut = data; *lenInOut = len; if (wasMinus) { val = -val; if (0 == val) /* i-0e is not valid */ validNumber = FALSE; } *valOut = val; return validNumber; } /* Parse a lenght of a string in form "\d+:". Return a lenght of a string or IVALID_LEN if there was an error */ static size_t _parse_str_len(const char** dataInOut, size_t* lenInOut) { const char * data = *dataInOut; size_t len = *lenInOut; size_t strLen = 0; BOOL validNumber = FALSE; BOOL endsWithColon = FALSE; char c; size_t digit; if (!data) return IVALID_LEN; while (len > 0) { c = *data++; --len; if (IS_DIGIT(c)) { validNumber = TRUE; digit = (size_t)(c - '0'); assert(digit <= 9); strLen = (strLen * 10) + digit; } else if (':' == c) { endsWithColon = TRUE; break; } else { /* not valid */ return IVALID_LEN; } } if (!validNumber || !endsWithColon) return IVALID_LEN; *dataInOut = data; *lenInOut = len; return strLen; } static size_t _parse_str_help(const char** dataInOut, size_t* lenInOut) { size_t strLen = _parse_str_len(dataInOut, lenInOut); if (IVALID_LEN == strLen) return IVALID_LEN; if (strLen > *lenInOut) return IVALID_LEN; return strLen; } static benc_str* _parse_str(const char **dataInOut, size_t* lenInOut) { benc_str* bobj; size_t strLen = _parse_str_help(dataInOut, lenInOut); if (IVALID_LEN == strLen) return NULL; bobj = benc_str_new(*dataInOut, strLen); *dataInOut += strLen; *lenInOut -= strLen; return bobj; } /* Given a current size of the array, decide how many new (used when growing array to make space for new items). Each array item is a pointer, so uses 4 bytes. We want to strike a balance between not allocating too much (don't waste memory for small arrays) and creating too many segments (for large arrays). Those numbers should be based on profiling, but for now I just made them up. */ static size_t _array_grow_by(size_t currSize) { if (currSize < 8) return 8; else if (currSize < 32) return 32; else if (currSize < 128) return 128; else if (currSize < 1024) return 1024; return currSize; /* grow by 2.0 */ } static benc_array_data* _array_get_free_slot(benc_array_data* curr, size_t *slotIdxOut) { size_t curr_size = curr->m_used; while (curr->m_next) { curr = curr->m_next; curr_size += curr->m_used; } if (curr->m_used == curr->m_allocated) { /* no space left, need to allocate next segment */ size_t grow_by = _array_grow_by(curr_size); benc_obj** new_data = SAZA(benc_obj*, grow_by); if (!new_data) return NULL; if (0 != curr->m_allocated) { assert(curr->m_data); assert(!curr->m_next); curr->m_next = SAZ(benc_array_data); if (!curr->m_next) { free(new_data); return NULL; } curr = curr->m_next; } else { assert(!curr->m_data); } assert(!curr->m_data); curr->m_data = new_data; curr->m_allocated = grow_by; curr->m_used = 0; curr->m_next = NULL; } assert(curr->m_allocated > 0); assert(curr->m_data); assert(curr->m_used < curr->m_allocated); *slotIdxOut = curr->m_used; return curr; } BOOL benc_array_append(benc_array* arr, benc_obj* bobj) { benc_array_data * data; size_t slotIdx; assert(arr); assert(bobj); if (!arr || !bobj) return FALSE; data = _array_get_free_slot(&(arr->m_data), &slotIdx); if (!data) return FALSE; assert(slotIdx == data->m_used); data->m_data[slotIdx] = bobj; data->m_used++; assert(data->m_used <= data->m_allocated); return TRUE; } /* When we need to grow the dict, returns the size of new dictionary based on current size. We need to strike a balance between memory usage (don't use too much memory) and speed (don't reallocate too often). Those numbers should come from profiling, but for now I'm just guessing. */ size_t _dict_calc_new_size(size_t currSize) { if (currSize < 8) return 8; else if (currSize < 32) return 32; else if (currSize < 128) return 128; else if (currSize < 1024) return 1024; return currSize * 2; } /* Return 1 if val1 > val2 0 if val1 == val2 -1 if val1 < val2 Compares raw bytes */ int _compare_dict_keys(const unsigned char* val1, const unsigned char* val2, size_t val2Len) { unsigned char c1; unsigned char c2; for (;;) { if (0 == val2Len) { if (0 == *val1) return 0; else return 1; } c1 = *val1; c2 = *val2; if (c1 > c2) return 1; if (c1 < c2) return -1; ++val1; ++val2; --val2Len; } } /* Find a place to insert a value with a given key. If needed, allocates additional memory for data. Per bencoding spec, keys must be ordered alphabetically when serialized, so we insert them in sorted order. This might be expensive due to lots of memory copying for lots of insertions in random order (more efficient would probably be: append at the end and sort when insertions are done). TODO: This is a naive implementation that doesn't use segments but always reallocates data so that keys and values are always in one array. This simplifies insertion logic. */ static benc_dict_data* _dict_get_insert_slot(benc_dict_data* curr, const char* key, size_t keyLen, size_t* slotIdxOut) { size_t slotIdx, used; int cmp; const unsigned char* currKey; assert(curr && key && slotIdxOut); assert(NULL == curr->m_next); /* not using segments yet */ used = curr->m_used; if (used == curr->m_allocated) { /* need more space */ benc_obj **values; char **keys; size_t new_size = _dict_calc_new_size(used); keys = SAZA(char*, new_size); if (!keys) return NULL; values = SAZA(benc_obj*, new_size); if (!values) { free(keys); return NULL; } if (used > 0) { memcpy(keys, curr->m_keys, used * sizeof(char**)); memcpy(values, curr->m_values, used * sizeof(benc_obj*)); assert(curr->m_keys); free(curr->m_keys); assert(curr->m_values); free(curr->m_values); } curr->m_keys = keys; curr->m_values = values; curr->m_allocated = new_size; } assert(curr->m_used < curr->m_allocated); /* TODO: brain dead linear search. Replace with binary search */ slotIdx = 0; while (slotIdx < used) { currKey = (const unsigned char*)curr->m_values[slotIdx]; cmp = _compare_dict_keys(currKey, key, keyLen); if (0 == cmp) { /* same as existing key: insert at exactly this position */ break; } if (1 == cmp) { /* currKey > key: make space for data at this position */ size_t toMove = used - slotIdx; char ** keys_start = curr->m_keys + slotIdx; benc_obj** vals_start = curr->m_values + slotIdx; memmove(keys_start+1, keys_start, toMove * sizeof(char*)); memmove(vals_start+1, vals_start, toMove * sizeof(benc_obj*)); *keys_start = NULL; *vals_start = NULL; break; } ++slotIdx; } *slotIdxOut = slotIdx; return curr; } BOOL benc_dict_insert2(benc_dict* dict, const char* key, benc_obj* val) { return benc_dict_insert(dict, key, strlen(key), val); } BOOL benc_dict_insert_int64(benc_dict* dict, const char* key, int64_t val) { benc_obj * bobj = (benc_obj*)benc_int64_new(val); if (!bobj) return FALSE; if (!benc_dict_insert2(dict, key, bobj)) { benc_obj_delete(bobj); return FALSE; } return TRUE; } BOOL benc_dict_insert_str(benc_dict* dict, const char* key, const char *str) { benc_obj * bobj = (benc_obj*)benc_str_new(str, strlen(str)); if (!bobj) return FALSE; if (!benc_dict_insert2(dict, key, bobj)) { benc_obj_delete(bobj); return FALSE; } return TRUE; } BOOL benc_dict_insert_wstr(benc_dict* dict, const char* key, const WCHAR *str) { BOOL ret; char *utf8_str = wstr_to_utf8(str); if (!utf8_str) return FALSE; ret = benc_dict_insert_str(dict, key, utf8_str); free(utf8_str); return ret; } BOOL benc_dict_insert_tstr(benc_dict* dict, const char* key, const TCHAR *str) { BOOL ret; char *utf8_str = tstr_to_utf8(str); if (!utf8_str) return FALSE; ret = benc_dict_insert_str(dict, key, utf8_str); free(utf8_str); return ret; } BOOL benc_dict_insert(benc_dict* dict, const char* key, size_t keyLen, benc_obj* val) { benc_dict_data * data; size_t slotIdx; if (!dict || !key || !val) return FALSE; data = _dict_get_insert_slot(&(dict->m_data), key, keyLen, &slotIdx); if (!data) return FALSE; /* TODO: handle case where key already exists */ data->m_values[slotIdx] = val; data->m_keys[slotIdx] = str_dupn(key, keyLen); data->m_used++; assert(data->m_used <= data->m_allocated); return TRUE; } /* Return value for a given 'key' of 'keyLen' length. Returns NULL if 'key' not found. */ benc_obj * benc_dict_find(benc_dict* dict, const char* key, size_t keyLen) { size_t slotIdx; benc_dict_data* curr; size_t used; if (!dict || !key) return NULL; curr = &(dict->m_data); assert(!curr->m_next); /* not using segments yet */ used = curr->m_used; /* TODO: brain dead linear search. Replace with binary search */ slotIdx = 0; while (slotIdx < used) { const unsigned char* currKey = (const unsigned char*)curr->m_keys[slotIdx]; int cmp = _compare_dict_keys(currKey, key, keyLen); if (0 == cmp) return curr->m_values[slotIdx]; ++slotIdx; } return NULL; } benc_obj* benc_dict_find2(benc_dict* dict, const char* key) { assert(key); if (!key) return NULL; return benc_dict_find(dict, key, strlen(key)); } BOOL dict_get_bool(benc_dict* dict, const char* key, BOOL* valOut) { benc_obj* obj = benc_dict_find2(dict, key); benc_int64* val = benc_obj_as_int64(obj); if (!val) return FALSE; *valOut = (BOOL) val->m_val; return TRUE; } BOOL dict_get_int(benc_dict* dict, const char* key, int* valOut) { benc_obj* obj = benc_dict_find2(dict, key); benc_int64* val = benc_obj_as_int64(obj); if (!val) return FALSE; *valOut = (int) val->m_val; return TRUE; } const char* dict_get_str(benc_dict* dict, const char* key) { benc_obj* obj = benc_dict_find2(dict, key); benc_str* val = benc_obj_as_str(obj); if (!val) return NULL; return (const char*)val->m_str; } BOOL dict_get_double_from_str(benc_dict* dict, const char* key, double* valOut) { const char *str = dict_get_str(dict, key); if (!str) return FALSE; return str_to_double(str, valOut); } static benc_array * _parse_array(const char** dataInOut, int* lenInOut) { char c; const char * data = *dataInOut; int len = *lenInOut; benc_obj * bobj; benc_array *bobj_arr = benc_array_new(); if (!bobj_arr) return NULL; while (len > 0) { c = *data; if ('e' == c) { ++data; --len; goto FoundArrayEnd; } bobj = _benc_obj_from_data(&data, &len, FALSE); if (!bobj) break; if (!benc_array_append(bobj_arr, bobj)) break; } // error happened benc_obj_delete((benc_obj*) bobj_arr); return NULL; FoundArrayEnd: *dataInOut = data; *lenInOut = len; return bobj_arr; } static benc_dict *_parse_dict(const char** dataInOut, size_t* lenInOut) { char c; const char * data = *dataInOut; size_t len = *lenInOut; const char * key; size_t keyLen; benc_obj * val = NULL; benc_dict * dict = benc_dict_new(); if (!dict) return NULL; while (len > 0) { c = *data; if ('e' == c) { ++data; --len; goto FoundDictEnd; } keyLen = _parse_str_help(&data, &len); if (IVALID_LEN == keyLen) break; key = data; data += keyLen; len -= keyLen; assert(len > 0); val = _benc_obj_from_data(&data, &len, FALSE); if (!val) break; if (!benc_dict_insert(dict, key, keyLen, val)) break; } // error happened if (val) benc_obj_delete(val); benc_obj_delete((benc_obj*) dict); return NULL; FoundDictEnd: *dataInOut = data; *lenInOut = len; return dict; } static benc_obj *_benc_obj_from_data(const char** dataInOut, size_t* lenInOut, BOOL must_be_last) { char c; BOOL ok; int64_t int64val; benc_obj * bobj; const char * data = *dataInOut; size_t len = *lenInOut; /*assert(data);*/ /*assert(len > 0);*/ if (!data || (len <= 0)) return NULL; while (len >= 0) { c = *data++; --len; if ('i' == c) { ok = _parse_int64(&data, &len, &int64val); if (!ok) return NULL; bobj = (benc_obj*) benc_int64_new(int64val); break; } else if ('d' == c) { bobj = (benc_obj*) _parse_dict(&data, &len); break; } else if ('l' == c) { bobj = (benc_obj*) _parse_array(&data, &len); break; } else { /* must be string */ --data; ++len; bobj = (benc_obj*)_parse_str(&data, &len); break; } } if (bobj && must_be_last && (len > 0)) { benc_obj_delete(bobj); return NULL; } *dataInOut = data; *lenInOut = len; return bobj; } benc_obj *benc_obj_from_data(const char *data, size_t len) { return _benc_obj_from_data(&data, &len, TRUE); } static size_t _len_for_int64(benc_int64* bobj) { /* 2 is for "i" and "e" */ return 2 + digits_for_number(bobj->m_val); } static size_t _len_for_txt(const char* txt) { size_t txt_len = strlen(txt); return 1 + txt_len + digits_for_number(txt_len); } static size_t _len_for_str(benc_str* bobj) { /* 1 is for ":" */ return 1 + bobj->m_len + digits_for_number(bobj->m_len); } static size_t _len_for_array(benc_array* bobj) { size_t len = 2; benc_array_data *data = &(bobj->m_data); assert(BOT_ARRAY == bobj->m_type); while (data) { size_t i; benc_array_data *next = data->m_next; for (i=0; i < data->m_used; i++) { len += _benc_obj_to_data(data->m_data[i], PHASE_CALC_LEN, NULL); } data = next; } return len; } static size_t _len_for_dict(benc_dict* bobj) { size_t len = 2; benc_dict_data *data = &(bobj->m_data); assert(BOT_DICT == bobj->m_type); while (data) { size_t i; benc_dict_data *next = data->m_next; for (i=0; i < data->m_used; i++) { len += _len_for_txt(data->m_keys[i]); len += _benc_obj_to_data(data->m_values[i], PHASE_CALC_LEN, NULL); } data = next; } return len; } static void _str_reverse(char *start, char *end) { while (start < end) { char tmp = *start; *start++ = *end; *end-- = tmp; } } /* Convert 'val' to string in a buffer 'data' of size 'dataLen'. NULL-terminates the string. Returns FALSE if not enough space in the buffer. TODO: should return the size of needed buffer. TODO: for simplicity of code, if buffer is not big enough, will not use the last byte of the buffer TODO: move it to some other place like str_util.[h|c]? */ BOOL int64_to_string(int64_t val, char* data, size_t dataLen) { char * numStart; size_t dataLenRest = dataLen; if (val < 0) { if (dataLenRest < 2) { *data = 0; return FALSE; } *data++ = '-'; --dataLenRest; val = -val; } numStart = data; while (val > 9) { int digit = (int)(val % 10); if (dataLenRest < 2) { *data = 0; return FALSE; } *data++ = (char)(digit + '0'); --dataLenRest; val = val / 10; } if (dataLenRest < 2) { *data = 0; return FALSE; } data[0] = (char)(val + '0'); data[1] = 0; _str_reverse(numStart, data); return TRUE; } BOOL int64_to_string_zero_pad(int64_t val, size_t pad, char* data, size_t dataLen) { size_t len; assert(dataLen >= pad + 1); if (dataLen < pad + 1) return FALSE; if (!int64_to_string(val, data, dataLen)) return FALSE; len = strlen(data); if (len < pad) { size_t toPad = pad - len; size_t toMove = len + 1; memmove(data + toPad, data, toMove); while (toPad != 0) { data[toPad-1] = '0'; --toPad; } } return TRUE; } static size_t _serialize_int64_num(int64_t val, char* data) { char * numStart; size_t len; char * start = data; if (val < 0) { *data++ = '-'; val = -val; } numStart = data; while (val > 9) { int digit = (int)(val % 10); *data++ = (char)(digit + '0'); val = val / 10; } *data = (char)(val + '0'); _str_reverse(numStart, data); len = data + 1 - start; return len; } static size_t _serialize_int64(benc_int64* bobj, char* data) { size_t len; *data++ = 'i'; len = _serialize_int64_num(bobj->m_val, data); data += len; *data++ = 'e'; len += 2; assert(len == _len_for_int64(bobj)); return len; } static size_t _serialize_str_help(char *str, size_t strLen, char* data) { size_t len = _serialize_int64_num(strLen, data); data += len; *data++ = ':'; memcpy(data, str, strLen); return len + 1 + strLen; } static size_t _serialize_str(benc_str* bobj, char* data) { size_t len = _serialize_str_help(bobj->m_str, bobj->m_len, data); assert(len == _len_for_str(bobj)); return len; } static size_t _serialize_array(benc_array* arr, char* data) { int i; size_t len; int arr_len = benc_array_len(arr); char *start = data; *data++ = 'l'; for (i = 0; i < arr_len; i++) { benc_obj *bobj = benc_array_get(arr, i); size_t len_tmp = _benc_obj_to_data(bobj, PHASE_FORM_DATA, data); data += len_tmp; } *data++ = 'e'; len = data - start; assert(len == _len_for_array(arr)); return len; } static size_t _serialize_dict(benc_dict* dict, char* data) { benc_dict_data * curr; size_t len = 2; /* for 'd' and 'e' */ size_t i, lenTmp, used; *data++ = 'd'; curr = &(dict->m_data); assert(!curr->m_next); /* not using segments yet */ while (curr) { used = curr->m_used; for (i = 0; i < used; i++) { char *key = curr->m_keys[i]; benc_obj *val = curr->m_values[i]; lenTmp = _serialize_str_help(key, strlen(key), data); data += lenTmp; len += lenTmp; lenTmp = _benc_obj_to_data(val, PHASE_FORM_DATA, data); data += lenTmp; len += lenTmp; } curr = curr->m_next; } *data++ = 'e'; assert(len == _len_for_dict(dict)); return len; } static size_t _benc_obj_to_data(benc_obj* bobj, phase_t phase, char* data) { size_t len; assert((PHASE_CALC_LEN == phase) || (PHASE_FORM_DATA == phase)); assert((PHASE_CALC_LEN == phase) || data); if (BOT_INT64 == bobj->m_type) { if (PHASE_CALC_LEN == phase) len = _len_for_int64((benc_int64*)bobj); else len = _serialize_int64((benc_int64*)bobj, data); } else if (BOT_STRING == bobj->m_type) { if (PHASE_CALC_LEN == phase) len = _len_for_str((benc_str*)bobj); else len = _serialize_str((benc_str*)bobj, data); } else if (BOT_ARRAY == bobj->m_type) { if (PHASE_CALC_LEN == phase) len = _len_for_array((benc_array*)bobj); else len = _serialize_array((benc_array*)bobj, data); } else if (BOT_DICT == bobj->m_type) { if (PHASE_CALC_LEN == phase) len = _len_for_dict((benc_dict*)bobj); else len = _serialize_dict((benc_dict*)bobj, data); } else { assert(0); len = 0; } return len; } char * benc_obj_to_data(benc_obj *bobj, size_t* lenOut) { size_t len; char *data; assert(bobj); if (!bobj) return NULL; len = _benc_obj_to_data(bobj, PHASE_CALC_LEN, NULL); assert(len > 0); data = (char*)malloc(len+1); if (!data) return NULL; data[len] = 0; /* NULL-terminate to make life easier */ _benc_obj_to_data(bobj, PHASE_FORM_DATA, data); *lenOut = len; return data; } size_t benc_array_len(benc_array *bobj) { benc_array_data *data = (benc_array_data*) &(bobj->m_data); size_t len = data->m_used; while (data->m_next) { data = data->m_next; len += data->m_used; } return len; } benc_obj *benc_array_get(benc_array *bobj, size_t idx) { benc_array_data *data = (benc_array_data*) &(bobj->m_data); while (data) { if (idx < data->m_used) { return data->m_data[idx]; } idx -= data->m_used; data = data->m_next; } assert(0); /* asked for an non-existing item */ return NULL; } benc_int64* benc_obj_as_int64(benc_obj *bobj) { if (!bobj) return NULL; if (BOT_INT64 == bobj->m_type) return (benc_int64 *)bobj; return NULL; } benc_str* benc_obj_as_str(benc_obj *bobj) { if (!bobj) return NULL; if (BOT_STRING == bobj->m_type) return (benc_str *)bobj; return NULL; } benc_dict* benc_obj_as_dict(benc_obj *bobj) { if (!bobj) return NULL; if (BOT_DICT == bobj->m_type) return (benc_dict *)bobj; return NULL; } benc_array* benc_obj_as_array(benc_obj *bobj) { if (!bobj) return NULL; if (BOT_ARRAY == bobj->m_type) return (benc_array *)bobj; return NULL; } size_t benc_dict_len(benc_dict *bobj) { /* A hack, but works because benc_array and benc_dict share enough of common data layout */ return benc_array_len((benc_array*)bobj); } size_t benc_obj_len(benc_obj* bobj) { if (BOT_ARRAY == bobj->m_type) return benc_array_len((benc_array*)bobj); else if (BOT_DICT == bobj->m_type) return benc_dict_len((benc_dict*)bobj); else return -1; } void benc_array_delete(benc_array *bobj) { benc_array_data *data = &(bobj->m_data); assert(BOT_ARRAY == bobj->m_type); while (data) { size_t i; benc_array_data *next = data->m_next; for (i=0; i < data->m_used; i++) { benc_obj_delete(data->m_data[i]); } free(data->m_data); if (data != &(bobj->m_data)) { /* first m_data is within benc_array, but all others are heap allocated */ free(data); } data = next; } } static void benc_dict_delete(benc_dict *bobj) { benc_dict_data *data = &(bobj->m_data); assert(BOT_DICT == bobj->m_type); while (data) { size_t i; benc_dict_data *next = data->m_next; for (i=0; i < data->m_used; i++) { free(data->m_keys[i]); benc_obj_delete(data->m_values[i]); } free(data->m_values); free(data->m_keys); data = next; } } /* Release all memory used by bencoded object */ void benc_obj_delete(benc_obj *bobj) { if (BOT_INT64 == bobj->m_type) { /* do nothing */ } else if (BOT_STRING == bobj->m_type) { benc_str *bobj_str = (benc_str*)bobj; free(bobj_str->m_str); } else if (BOT_ARRAY == bobj->m_type) { benc_array_delete((benc_array*)bobj); } else if (BOT_DICT == bobj->m_type) { benc_dict_delete((benc_dict*)bobj); } else { assert(0); } free(bobj); }
C
#include <stdio.h> #include <stdlib.h> /*Perfect number ȫ*/ /*int main() { int n,i,s=0; printf("жϻDzȫ:"); scanf("%d",&n); for(i=1;i<n;i++) //ע⣺iԵn { if(n%i==0) s=s+i; } if(s==n) printf("Perfect number!\n"); else printf("Not perfect number\n"); return 0; } */ /**/ int main() { int n,reverseN=0,remainder,n1; printf("һжDzǻ:"); scanf("%d",&n);n1=n; while(n!=0) { remainder=n%10; reverseN=reverseN*10+remainder; n/=10; } if(n1==reverseN) printf("ǻ\n"); else printf("ǻ\n"); return 0; }
C
#include "time.h" #include <NeoPixelBrightnessBus.h> // instead of NeoPixelBus.h #ifdef __AVR__ #include <avr/power.h> // Required for 16 MHz Adafruit Trinket #endif // Which pin on the Arduino is connected to the NeoPixels? // On a Trinket or Gemma we suggest changing this to 1: #define LED_PIN 4 // How many NeoPixels are attached to the Arduino? #define LED_COUNT 200 // Declare our NeoPixel strip object: // Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_RGB + NEO_KHZ800); // Argument 1 = Number of pixels in NeoPixel strip // Argument 2 = Arduino pin number (most are valid) // Argument 3 = Pixel type flags, add together as needed: // NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs) // NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers) // NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products) // NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2) // NEO_RGBW Pixels are wired for RGBW bitstream (NeoPixel RGBW products) //NeoPixelBus<NeoRgbFeature, Neo800KbpsMethod> strip(LED_COUNT, LED_PIN); NeoPixelBrightnessBus<NeoRgbFeature, Neo800KbpsMethod> strip(LED_COUNT, LED_PIN); // signum function #define sgn(x) ((x) < 0 ? -1 : ((x) > 0 ? 1 : 0)) // store time received from NTP server struct tm timeinfo; // to register current tick and infer time span clock_t registeredTick; struct TimeSpan { byte startHour; byte stopHour; }; const int settingsCount = 6; const String settingsParams[settingsCount] { "brightness", "effect", "start_hour1", "stop_hour1", "start_hour2", "stop_hour2" }; struct Settings { byte brightness; // NeoPixel brightness, 0 (min) to 255 (max) byte effect; TimeSpan spans[2]; }; Settings settings = { brightness: 50, effect: 0, spans: { { startHour: 0, stopHour: 0 }, { startHour: 0, stopHour: 0 } } }; void showStrip() { strip.Show(); } void setRelativeBrightness(byte bright) { byte relative = settings.brightness * bright / 255; strip.SetBrightness(relative); } void setPixel(int pixel, byte red, byte green, byte blue) { strip.SetBrightness(settings.brightness); strip.SetPixelColor(pixel, RgbColor(red, green, blue)); } void setPixelWBright(int pixel, byte red, byte green, byte blue, byte bright) { setRelativeBrightness(bright); strip.SetPixelColor(pixel, RgbColor(red, green, blue)); } void setAll(byte red, byte green, byte blue) { for (int i = 0; i < LED_COUNT; i++ ) { setPixel(i, red, green, blue); } showStrip(); } void setAllWBright(byte red, byte green, byte blue, byte bright) { for (int i = 0; i < LED_COUNT; i++ ) { setPixelWBright(i, red, green, blue, bright); } showStrip(); } void getTimeInfo() { if (getLocalTime(&timeinfo)) { Serial.print("Time received: "); Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S"); } else { Serial.println("Failed to obtain time"); } } void syncTime() { clock_t currentTick; currentTick = clock(); if ((currentTick - registeredTick) / CLOCKS_PER_SEC >= 60) { registeredTick = currentTick; getTimeInfo(); } } bool checkTimeSpan() { syncTime(); if (settings.spans[0].startHour == 0 && settings.spans[0].stopHour == 0 && settings.spans[1].startHour == 0 && settings.spans[1].stopHour == 0) { return true; } else if (timeinfo.tm_hour >= settings.spans[0].startHour && timeinfo.tm_hour < settings.spans[0].stopHour) { return true; } else if (timeinfo.tm_hour >= settings.spans[1].startHour && timeinfo.tm_hour < settings.spans[1].stopHour) { return true; } else { return false; } }
C
// // main.c // 14-二分查找 // // Created by Ne on 2018/11/10. // Copyright © 2018年 Ne. All rights reserved. // #include <stdio.h> #pragma mark --二分查找 int binSearch(int *arr,int low,int high,int find) { int mid; while (low <= high) { mid = (low+high)/2; if (arr[mid] == find) { return mid; } else if (arr[mid] < find) { low = mid + 1; } else { high = mid - 1; } } return -1; } #pragma mark --递归实现 int binSearchRecursion(int *arr,int low,int high,int find) { int mid; while (low <= high) { mid = (low+high)/2; if (arr[mid] == find) { return mid; } else if (arr[mid] < find) { return binSearchRecursion(arr, mid+1, high, find); } else { return binSearchRecursion(arr, low, mid-1, find); } } return -1; } int main(int argc, const char * argv[]) { int arr[] = {1,3,5,7,9,11,34,66}; int find = binSearch(arr, 0, 7, 34); int find1 = binSearchRecursion(arr, 0, 7, 6); printf("%d\t %d\n",find,find1); return 0; }
C
#include <stdio.h> #include <conio.h> int main() { int i, n, j, num, arr[10]; clrscr(); printf("\n Enter the number of elements in the array : "); scanf("%d", &n); for(i=0;i<n;i++) { printf("\n arr[%d] = ", i); scanf("%d", &arr[i]); } printf("\n Enter the number to be deleted : "); scanf("%d", &num); for(i=0;i<n;i++) { if(arr[i] == num) { for(j=i; j<n–1;j++) arr[j] = arr[j+1]; } } n = n–1; printf("\n The array after deletion is : "); for(i=0;i<n;i++) printf("\n arr[%d] = %d", i, arr[i]); getch(); return 0; }
C
/* * assert.h * * Created on: Jan 14, 2015 * Author: wladt */ #ifndef __PFS_BITS_ASSERT_H__ #define __PFS_BITS_ASSERT_H__ #include <pfs/bits/config.h> EXTERN_C_BEGIN void pfs_assert (const char * file, int line, const char * text); void pfs_backtrace (const char * file, int line, const char * text); void pfs_check_warn (const char * file, int line, const char * text); void pfs_check_error (const char * file, int line, const char * text); EXTERN_C_END #ifndef NDEBUG # define PFS_ASSERT(expr) if (!(expr)) { pfs_assert(__TFILE__, __LINE__, #expr); } # define PFS_ASSERT_X(expr,text) if (!(expr)) { pfs_assert(__TFILE__, __LINE__, text); } # define PFS_BACKTRACE(text) pfs_backtrace(__TFILE__, __LINE__, text) #else # define PFS_ASSERT(x) # define PFS_ASSERT_X(x,y) # define PFS_BACKTRACE(text) #endif /* !NDEBUG */ #define PFS_ASSERT_FORMAT(x) PFS_ASSERT(x) #define PFS_ASSERT_RANGE(x) PFS_ASSERT(x) #define PFS_ASSERT_OVERFLOW(x) PFS_ASSERT(x) #define PFS_ASSERT_BAD_CAST(x) PFS_ASSERT(x) #define PFS_ASSERT_UNEXPECTED() PFS_ASSERT(false) #define PFS_ASSERT_UNEXPECTED_X(errstr) PFS_ASSERT_X(false, errstr) #define PFS_ASSERT_NULLPTR(x) PFS_ASSERT((x) != 0) #define PFS_ASSERT_IS_NULL(x) PFS_ASSERT(!(x).is_null()) #define PFS_ASSERT_DOMAIN(errstr) PFS_ASSERT_X(false, errstr) #define PFS_ASSERT_INVALID_ARGUMENT(x) PFS_ASSERT(x) #define PFS_WARN(x) if (!(x)) { pfs_check_warn(__TFILE__, __LINE__, #x); } #define PFS_ERROR(x) if (!(x)) { pfs_check_error(__TFILE__, __LINE__, #x); } #define PFS_WARN2(x,text) if (!(x)) { pfs_check_warn(__TFILE__, __LINE__, text); } #define PFS_ERROR2(x,text) if (!(x)) { pfs_check_error(__TFILE__, __LINE__, text); } /* * Special case of assert. * Used when need to implement some code. */ #define PFS_ASSERT_TODO() PFS_ASSERT_X(false, "Need to implement") #endif /* __PFS_BITS_ASSERT_H__ */
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 */ typedef struct TYPE_2__ TYPE_1__ ; /* Type definitions */ struct TYPE_2__ {int max; struct file* table; } ; struct thread_trace {TYPE_1__ files; } ; struct file {int dummy; } ; /* Variables and functions */ int /*<<< orphan*/ memset (struct file*,int /*<<< orphan*/ ,int) ; struct file* realloc (struct file*,int) ; __attribute__((used)) static struct file *thread_trace__files_entry(struct thread_trace *ttrace, int fd) { if (fd < 0) return NULL; if (fd > ttrace->files.max) { struct file *nfiles = realloc(ttrace->files.table, (fd + 1) * sizeof(struct file)); if (nfiles == NULL) return NULL; if (ttrace->files.max != -1) { memset(nfiles + ttrace->files.max + 1, 0, (fd - ttrace->files.max) * sizeof(struct file)); } else { memset(nfiles, 0, (fd + 1) * sizeof(struct file)); } ttrace->files.table = nfiles; ttrace->files.max = fd; } return ttrace->files.table + fd; }
C
// // Demonstration of some constant expressions. These are required for the // labels on a swtich, and in some other, probably more common places we // haven't learned about yet. // #include <stdio.h> #include <stdbool.h> int main( void ) { int val; printf( "Enter a value: " ); scanf( "%d", &val ); int three = 3; switch ( val ) { case 0: // A trivial constant expression. printf( "It's a zero\n" ); break; case 2 / 2: // A slightly more interesting one. printf( "It's a one\n" ); break; case 25 / 7 % 2 + 19 - 6 * 3: // More complex printf( "It's a two\n" ); break; #ifdef NEVER case three: // But this wouldn't work. printf( "It's a three\n" ); break; #endif default: printf( "It's some other value.\n" ); } // This line is just to keep the compiler from // complaining that I never use the variable, three. three++; return 0; }
C
/** * @file activity3.c * @author KarishmaSavant * @brief PWM assignment as per ADC values read * @version 0.1 * @date 2021-04-29 * * @copyright Copyright (c) 2021 * */ #include <avr/io.h> #include <util/delay.h> //delay function #include "activity3.h" /** * @brief Initialization of PWM ports and registers * */ void PWM_init(void) //initialization of PWM { TCCR1A|=(1<<COM1B1)|(1<<WGM10)|(1<<WGM11); //COM1B1->1 = NON-INVERTING MODE; FAST PWM (table 15-3) //From Table15-5 waveform gen mode bit //PWM Phase Correct 10 bit ->11 //0X3FF is TOP->***1024 IS MAX VALUE*** TCCR1B =(1<<WGM12)|(1<<CS11)|(1<<CS10);//Clock bit Select=CS11 CS10-> 1 1->64 PRESCALAR -> MORE PRESCALAR VALUE -> MORE RESOLUTION OF MOTOR DDRB|=(1<<PWM_port);//Direction of o/p for PWM; PWM_port=PB2(OC1B-> Output Compare Timer 1 Channel B) } /** * @brief Assigning PWM as per Temp Table given in assignment * * @param temp_value * @return char */ char PWM(uint16_t temp_value) { char temp_over_protocol; PWM_init(); // calling Initialization parameters if(temp_value>=0 && temp_value<=200)//20% Value from ADC Potentiometer { OCR1B=205;// 20%of 1024; Output Compare Register 1B (PORT PB2-> OC1B) temp_over_protocol=20; _delay_ms(200); } else if(temp_value>=201 && temp_value<=500)//40% of 1024 { OCR1B=410; temp_over_protocol=25; _delay_ms(200); } else if(temp_value>=501 && temp_value<=700)//70% { OCR1B=716; temp_over_protocol=29; _delay_ms(200); } else if(temp_value>=701 && temp_value<=1024)//90% { OCR1B=972; temp_over_protocol=33; _delay_ms(200); } /** * @brief else condition if emperature read from ADC is not in range * */ else { OCR1B=0; temp_over_protocol=0; } return temp_over_protocol; }
C
#include <stdio.h> #include "stack.h" int main() { sStack *stack=NULL; int status=0; stack=StackInit(); if(!stack) { printf("初始化栈失败\n"); } status=StackEmpty(stack); if(status) { printf("栈为空\n"); } else { printf("栈不为空\n"); } status=Push(stack,11); if(status) { printf("压栈成功\n"); } else { printf("压栈失败\n"); } status=StackEmpty(stack); if(status) { printf("栈为空\n"); } else { printf("栈不为空\n"); } status=Push(stack,22); if(status) { printf("压栈成功\n"); } else { printf("压栈失败\n"); } status=StackLength(stack); printf("当前栈的长度为%d\n",status); status=Push(stack,33); if(status) { printf("压栈成功\n"); } else { printf("压栈失败\n"); } status=StackFull(stack); if(status) { printf("栈为满\n"); } else { printf("栈不为满\n"); } status=StackLength(stack); printf("当前栈的长度为%d\n",status); status=GetTop(stack); printf("当前栈的栈顶的值为%d\n",status); status=Push(stack,44); if(status) { printf("压栈成功\n"); } else { printf("压栈失败\n"); } status=StackFull(stack); if(status) { printf("栈为满\n"); } else { printf("栈不为满\n"); } StackDisplay(stack); status=Push(stack,55); if(status) { printf("压栈成功\n"); } else { printf("压栈失败\n"); } status=StackFull(stack); if(status) { printf("栈为满\n"); } else { printf("栈不为满\n"); } status=StackLength(stack); printf("当前栈的长度为%d\n",status); status=GetTop(stack); printf("当前栈的栈顶的值为%d\n",status); status=Pop(stack); printf("当前取栈的栈顶的值为%d\n",status); status=StackFull(stack); if(status) { printf("栈为满\n"); } else { printf("栈不为满\n"); } status=StackLength(stack); printf("当前栈的长度为%d\n",status); status=GetTop(stack); printf("当前栈的栈顶的值为%d\n",status); StackClear(stack); status=StackEmpty(stack); if(status) { printf("栈为空\n"); } else { printf("栈不为空\n"); } status=StackLength(stack); printf("当前栈的长度为%d\n",status); StackDestory(stack); return 0; }
C
#include <stdio.h> #include "math/AnuraMath.h" int main() { Vec2 v = {5.3, 2.2}; Vec2 w = {1.2, 2.6}; Mat2 m = { v, w }; Mat2 n = { { 1.0, 0.0 }, { 0.0, 1.0 } }; printf("%f\n", Vec2_length(v)); printf("%f\n", Mat2_get_index(&m, 0, 0)); Vec2_print(v); printf("----\n"); Mat2_print(m); printf("====\n"); Mat2 res = Mat2_mul(n, m); Mat2_print(res); printf("....\n"); Mat2 a = { { 1, 34}, { 2, 4}, }; Mat2 b = { {6,2}, {1,4}, }; Mat2_print(Mat2_mul(a, b)); printf("====\n"); Vec2 v1 = {1.0, 0.0}; Vec2_print(Vec2_rotated(v1, 3.14159265/ 2.0)); printf("....\n"); Mat3 a3 = { {1,4,7}, {2,5,8}, {3,6,9}, }; Mat3 b3 = { {5,8,6}, {4,1,9}, {3,2,7}, }; Mat3_print(Mat3_mul(a3, b3)); Mat3_print(Mat3_transpose(a3)); Mat2_print(Mat2_transpose(a)); printf("....\n"); Mat3 trans = Mat3_with_origin( Mat3_with_basis( Mat3_identity(), (Mat2) {{-1.0, 0.0}, {0.0, -1.0}} ), (Vec2) {5.0, 7.2} ); printf("original...\n"); Mat3_print(trans); //Vec2_print(Mat3_transform(trans, (Vec2) {1,2})); //Mat3_print(Mat3_translated(trans, (Vec2) {2,8})); printf("transformed...\n"); Mat3_print(Mat3_mul(trans, Mat3_with_origin(Mat3_identity(), (Vec2) {2,3}))); }
C
#include "algoritmos_de_planificacion.h" void planificar(){ if(!strcmp(ALGORITMO_PLANIFICACION,"FIFO")){ FIFO(); }else if (!strcmp(ALGORITMO_PLANIFICACION,"RR")){ RR(); }else if (!strcmp(ALGORITMO_PLANIFICACION,"SJF-CD")){ SJF_con_desalojo(); }else if (!strcmp(ALGORITMO_PLANIFICACION,"SJF-SD")){ SJF_sin_desalojo(); } } void FIFO(){ while(estoy_planificando){ /*sem_wait(&SEM_TRANSICION); bool hay_alguien_en_ready = queue_is_empty(COLA_READY); sem_post(&SEM_TRANSICION);*/ sem_wait(&SEM_TRANSICION); entrenador_t* entrenador = queue_peek(COLA_READY); sem_post(&SEM_TRANSICION); if(entrenador != NULL){ /*sem_wait(&SEM_TRANSICION); entrenador_t* entrenador = queue_peek(COLA_READY); sem_post(&SEM_TRANSICION);*/ sem_wait(&SEM_LOGS); log_info(log_obligatorio,"El entrenador %d le toca entrar a la cola EXEC por el algoritmo %s",entrenador->id_entrenador,ALGORITMO_PLANIFICACION); sem_post(&SEM_LOGS); pasar_de_cola_a(entrenador,EXEC); sem_wait(&SEM_LOG_METRICAS); log_info(log_metricas,"Cambio de contexto para que el entrenador %d use la cpu",entrenador->id_entrenador); sem_post(&SEM_LOG_METRICAS); cantidad_de_cambios_de_contexto++; /* sem_wait(&entrenador->cambio_de_estado); bool sigo_en_exec=(entrenador->estado_actual==EXEC); sem_post(&entrenador->cambio_de_estado); */ while((entrenador->estado_actual==EXEC)/*sigo_en_exec*/){ sleep(RETARDO_CICLO_CPU); //sem_wait(&entrenador->semaforo_puedo_hacer_otra_rafaga); sem_post(&entrenador->semaforo_entrenador); /* sem_wait(&entrenador->cambio_de_estado); sigo_en_exec=(entrenador->estado_actual==EXEC); sem_post(&entrenador->cambio_de_estado); */ } sem_wait(&SEM_LOG_METRICAS); log_info(log_metricas,"Cambio de contexto para que el entrenador %d deje la cpu",entrenador->id_entrenador); sem_post(&SEM_LOG_METRICAS); cantidad_de_cambios_de_contexto++; }else{ sleep(RETARDO_CICLO_CPU); } } } void RR(){ while(estoy_planificando){ /*sem_wait(&SEM_TRANSICION); bool hay_alguien_en_ready = queue_is_empty(COLA_READY); sem_post(&SEM_TRANSICION);*/ sem_wait(&SEM_TRANSICION); entrenador_t* entrenador = queue_peek(COLA_READY); sem_post(&SEM_TRANSICION); if(entrenador != NULL){ pasar_de_cola_a(entrenador,EXEC); sem_wait(&SEM_LOG_METRICAS); log_info(log_metricas,"Cambio de contexto para que el entrenador %d use la cpu",entrenador->id_entrenador); sem_post(&SEM_LOG_METRICAS); cantidad_de_cambios_de_contexto++; sem_wait(&SEM_LOGS); log_info(log_obligatorio,"El entrenador %d le toca entrar a la cola EXEC por el algoritmo %s",entrenador->id_entrenador,ALGORITMO_PLANIFICACION); sem_post(&SEM_LOGS); int i = 0; while((i<QUANTUM && entrenador->estado_actual==EXEC)){ sleep(RETARDO_CICLO_CPU); //sem_wait(&entrenador->semaforo_puedo_hacer_otra_rafaga); sem_post(&entrenador->semaforo_entrenador); i++; } bool el_entrenador_esta_en_exec = entrenador->estado_actual==EXEC; if(el_entrenador_esta_en_exec){ sem_wait(&SEM_LOGS); log_info(log_obligatorio,"El entrenador %d le toca entrar a la cola READY por el algoritmo %s ya que lo desalojo",entrenador->id_entrenador,ALGORITMO_PLANIFICACION); sem_post(&SEM_LOGS); pasar_de_cola_a(entrenador,READY); //sem_post(&entrenador->semaforo_entre_en_ready); } sem_wait(&SEM_LOG_METRICAS); log_info(log_metricas,"Cambio de contexto para que el entrenador %d deje la cpu",entrenador->id_entrenador); sem_post(&SEM_LOG_METRICAS); cantidad_de_cambios_de_contexto++; }else{ sleep(RETARDO_CICLO_CPU); } } } entrenador_t* entrenador_con_menor_estimacion(){ bool aplicar_sjf(entrenador_t* un_entrenador, entrenador_t* otro_entrenador){ long una_estimacion, otra_estimacion; una_estimacion = (1-ALPHA_SJF)*un_entrenador->estimacion_actual + ALPHA_SJF * un_entrenador->estimacion_anterior; otra_estimacion = (1-ALPHA_SJF)*otro_entrenador->estimacion_actual + ALPHA_SJF * otro_entrenador->estimacion_anterior; return una_estimacion<otra_estimacion; } list_sort(COLA_READY->elements,aplicar_sjf); entrenador_t* entrenador_a_retornar = queue_peek(COLA_READY); return entrenador_a_retornar; } void SJF_con_desalojo(){ while(estoy_planificando){ sem_wait(&SEM_TRANSICION); bool hay_alguien_en_ready = queue_is_empty(COLA_READY); sem_post(&SEM_TRANSICION); if(!hay_alguien_en_ready){ sem_wait(&SEM_TRANSICION); int cant_de_procesos_en_ready = queue_size(COLA_READY); entrenador_t* entrenador = entrenador_con_menor_estimacion(); sem_post(&SEM_TRANSICION); sem_wait(&SEM_LOGS); log_info(log_obligatorio,"El entrenador %d le toca entrar a la cola EXEC por el algoritmo %s",entrenador->id_entrenador,ALGORITMO_PLANIFICACION); sem_post(&SEM_LOGS); pasar_de_cola_a(entrenador,EXEC); sem_wait(&SEM_LOG_METRICAS); log_info(log_metricas,"Cambio de contexto para que el entrenador %d use la cpu",entrenador->id_entrenador); sem_post(&SEM_LOG_METRICAS); cantidad_de_cambios_de_contexto++; int cant_rafagas = 0; int cant_actual_procesos_en_ready = queue_size(COLA_READY); sem_wait(&SEM_TRANSICION); bool no_entro_alguien_mas_en_ready=cant_actual_procesos_en_ready == queue_size(COLA_READY); sem_post(&SEM_TRANSICION); sem_wait(&entrenador->cambio_de_estado); bool sigo_en_exec=(entrenador->estado_actual==EXEC); sem_post(&entrenador->cambio_de_estado); while(sigo_en_exec && no_entro_alguien_mas_en_ready){ sleep(RETARDO_CICLO_CPU); //sem_wait(&entrenador->semaforo_puedo_hacer_otra_rafaga); sem_post(&entrenador->semaforo_entrenador); cant_rafagas++; sem_wait(&SEM_TRANSICION); no_entro_alguien_mas_en_ready = cant_actual_procesos_en_ready == queue_size(COLA_READY);/*this unmutexear*/ sem_post(&SEM_TRANSICION); sem_wait(&entrenador->cambio_de_estado); sigo_en_exec = (entrenador->estado_actual==EXEC); sem_post(&entrenador->cambio_de_estado); } //Actualizamos las estimaciones para el SJF entrenador->estimacion_anterior = entrenador->estimacion_actual; entrenador->estimacion_actual = cant_rafagas; //cantidad_de_ciclos_cpu_total+=cant_rafagas; //bool el_entrenador_esta_en_exec = entrenador->estado_actual==EXEC; if(sigo_en_exec){ sem_wait(&SEM_LOGS); log_info(log_obligatorio,"El entrenador %d le toca entrar a la cola READY por el algoritmo %s ya que lo desalojo",entrenador->id_entrenador,ALGORITMO_PLANIFICACION); sem_post(&SEM_LOGS); pasar_de_cola_a(entrenador,READY); } sem_wait(&SEM_LOG_METRICAS); log_info(log_metricas,"Cambio de contexto para que el entrenador %d deje la cpu",entrenador->id_entrenador); sem_post(&SEM_LOG_METRICAS); cantidad_de_cambios_de_contexto++; }else{ sleep(RETARDO_CICLO_CPU); } } } void SJF_sin_desalojo(){ while(estoy_planificando){ sem_wait(&SEM_TRANSICION); bool hay_alguien_en_ready = queue_is_empty(COLA_READY); sem_post(&SEM_TRANSICION); if(!hay_alguien_en_ready){ sem_wait(&SEM_TRANSICION); entrenador_t* entrenador = entrenador_con_menor_estimacion(); sem_post(&SEM_TRANSICION); sem_wait(&SEM_LOGS); log_info(log_obligatorio,"El entrenador %d le toca entrar a la cola EXEC por el algoritmo %s",entrenador->id_entrenador,ALGORITMO_PLANIFICACION); sem_post(&SEM_LOGS); pasar_de_cola_a(entrenador,EXEC); sem_wait(&SEM_LOG_METRICAS); log_info(log_metricas,"Cambio de contexto para que el entrenador %d use la cpu",entrenador->id_entrenador); sem_post(&SEM_LOG_METRICAS); cantidad_de_cambios_de_contexto++; int cant_rafagas = 0; sem_wait(&entrenador->cambio_de_estado); bool sigo_en_exec=(entrenador->estado_actual==EXEC); sem_post(&entrenador->cambio_de_estado); while(sigo_en_exec){ sleep(RETARDO_CICLO_CPU); //sem_wait(&entrenador->semaforo_puedo_hacer_otra_rafaga); sem_post(&entrenador->semaforo_entrenador); cant_rafagas++; sem_wait(&entrenador->cambio_de_estado); sigo_en_exec=(entrenador->estado_actual==EXEC);//TODO esto lo cambie desde git jejox sem_post(&entrenador->cambio_de_estado); } //Actualizamos las estimaciones para el SJF entrenador->estimacion_anterior = entrenador->estimacion_actual; entrenador->estimacion_actual = cant_rafagas; //cantidad_de_ciclos_cpu_total+=cant_rafagas; sem_wait(&SEM_LOG_METRICAS); log_info(log_metricas,"Cambio de contexto para que el entrenador %d deje la cpu",entrenador->id_entrenador); sem_post(&SEM_LOG_METRICAS); cantidad_de_cambios_de_contexto++; }else{ sleep(RETARDO_CICLO_CPU); } } }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "common_types.h" #include "osapi.h" #include "osal-core-test.h" /* OS Constructs */ int TestTasks (void); void InitializeTaskIds (void); void InitializeQIds (void); void InitializeBinIds(void); void InitializeMutIds(void); int TestQueues(void); int TestBinaries(void); int TestMutexes(void); int TestGetInfos(void); /* *************************************** MAIN ************************************** */ void OS_Application_Startup(void) { int status; int totalfailures = 0; OS_API_Init(); OS_printf("*********************************************************\n"); status = TestTasks(); OS_printf("Number of failures in TestTasks = %d\n",status); totalfailures += status; OS_printf("---------------------------------------------------------\n"); status = TestQueues(); OS_printf("Number of failures in TestQueues = %d\n", status); totalfailures += status; OS_printf("---------------------------------------------------------\n"); status = TestBinaries(); OS_printf("Number of failures in TestBinaries = %d\n",status); totalfailures += status; OS_printf("---------------------------------------------------------\n"); status = TestMutexes(); OS_printf("Number of failures in TestMutexes = %d\n",status); totalfailures += status; OS_printf("---------------------------------------------------------\n"); status = TestGetInfos(); OS_printf("Number of failures in TestGetInfos = %d\n",status); totalfailures += status; OS_printf("*********************************************************\n"); OS_printf("Total Failures = %d\n",totalfailures); OS_printf("*********************************************************\n"); OS_printf("Test Complete: On a Desktop System, hit Control-C to return to command shell\n"); return; } /* end OS_Application Startup */ /* ********************************************** TASKS******************************* */ int TestTasks(void) { int status; int failTaskCreatecount = 0; int failTaskDeletecount = 0; int failGetIdcount = 0; int totalfail = -999; /* OS_TaskRegister(); */ /* Testing Creating up to OS_MAX_TASKS (20), plus one more */ InitializeTaskIds(); status = OS_TaskCreate( &task_0_id, "Task 0", task_0, task_0_stack, TASK_0_STACK_SIZE, TASK_0_PRIORITY, 0); OS_printf("Create Status = %d, Id = %d\n",status,task_0_id); OS_printf("Status after creating this task: %d\n",status); OS_printf("Id after creating this task: %d\n",task_0_id); if (status != PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_1_id, "Task 1", task_1, task_1_stack, TASK_1_STACK_SIZE, TASK_1_PRIORITY, 0); OS_printf("Create Status = %d, Id = %d\n",status,task_1_id); OS_printf("Status after creating this task: %d\n",status); OS_printf("Id after creating this task: %d\n",task_1_id); if (status != PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_2_id, "Task 2", task_2, task_2_stack, TASK_2_STACK_SIZE, TASK_2_PRIORITY, 0); OS_printf("Create Status = %d, Id = %d\n",status,task_2_id); OS_printf("Status after creating this task: %d\n",status); OS_printf("Id after creating this task: %d\n",task_2_id); if (status != PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_3_id, "Task 3", task_3, task_3_stack, TASK_3_STACK_SIZE, TASK_3_PRIORITY, 0); OS_printf("Create Status = %d, Id = %d\n",status,task_3_id); OS_printf("Status after creating this task: %d\n",status); OS_printf("Id after creating this task: %d\n",task_3_id); if (status != PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_4_id, "Task 4", task_4, task_4_stack, TASK_4_STACK_SIZE, TASK_4_PRIORITY, 0); OS_printf("Create Status = %d, Id = %d\n",status,task_4_id); OS_printf("Status after creating this task: %d\n",status); OS_printf("Id after creating this task: %d\n",task_4_id); if (status != PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_5_id, "Task 5", task_5, task_5_stack, TASK_5_STACK_SIZE, TASK_5_PRIORITY, 0); OS_printf("Create Status = %d, Id = %d\n",status,task_5_id); OS_printf("Status after creating this task: %d\n",status); OS_printf("Id after creating this task: %d\n",task_5_id); if (status != PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_6_id, "Task 6", task_6, task_6_stack, TASK_6_STACK_SIZE, TASK_6_PRIORITY, 0); OS_printf("Create Status = %d, Id = %d\n",status,task_6_id); OS_printf("Status after creating this task: %d\n",status); OS_printf("Id after creating this task: %d\n",task_6_id); if (status != PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_7_id, "Task 7", task_7, task_7_stack, TASK_7_STACK_SIZE, TASK_7_PRIORITY, 0); OS_printf("Create Status = %d, Id = %d\n",status,task_7_id); OS_printf("Status after creating this task: %d\n",status); OS_printf("Id after creating this task: %d\n",task_7_id); if (status != PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_8_id, "Task 8", task_8, task_8_stack, TASK_8_STACK_SIZE, TASK_8_PRIORITY, 0); OS_printf("Create Status = %d, Id = %d\n",status,task_8_id); OS_printf("Status after creating this task: %d\n",status); OS_printf("Id after creating this task: %d\n",task_8_id); if (status != PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_9_id, "Task 9", task_9, task_9_stack, TASK_9_STACK_SIZE, TASK_9_PRIORITY, 0); OS_printf("Create Status = %d, Id = %d\n",status,task_9_id); OS_printf("Status after creating this task: %d\n",status); OS_printf("Id after creating this task: %d\n",task_9_id); if (status != PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_10_id, "Task 10", task_10, task_10_stack, TASK_10_STACK_SIZE, TASK_10_PRIORITY, 0); OS_printf("Create Status = %d, Id = %d\n",status,task_10_id); OS_printf("Status after creating this task: %d\n",status); OS_printf("Id after creating this task: %d\n",task_10_id); if (status != PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_11_id, "Task 11", task_11, task_11_stack, TASK_11_STACK_SIZE, TASK_11_PRIORITY, 0); OS_printf("Create Status = %d, Id = %d\n",status,task_11_id); OS_printf("Status after creating this task: %d\n",status); OS_printf("Id after creating this task: %d\n",task_11_id); if (status != PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_12_id, "Task 12", task_12, task_12_stack, TASK_12_STACK_SIZE, TASK_12_PRIORITY, 0); OS_printf("Create Status = %d, Id = %d\n",status,task_12_id); OS_printf("Status after creating this task: %d\n",status); OS_printf("Id after creating this task: %d\n",task_12_id); if (status != PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_13_id, "Task 13", task_13, task_13_stack, TASK_13_STACK_SIZE, TASK_13_PRIORITY, 0); OS_printf("Create Status = %d, Id = %d\n",status,task_13_id); OS_printf("Status after creating this task: %d\n",status); OS_printf("Id after creating this task: %d\n",task_13_id); if (status != PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_14_id, "Task 14", task_14, task_14_stack, TASK_14_STACK_SIZE, TASK_14_PRIORITY, 0); OS_printf("Create Status = %d, Id = %d\n",status,task_14_id); OS_printf("Status after creating this task: %d\n",status); OS_printf("Id after creating this task: %d\n",task_14_id); if (status != PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_15_id, "Task 15", task_15, task_15_stack, TASK_15_STACK_SIZE, TASK_15_PRIORITY, 0); OS_printf("Create Status = %d, Id = %d\n",status,task_15_id); OS_printf("Status after creating this task: %d\n",status); OS_printf("Id after creating this task: %d\n",task_15_id); if (status != PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_16_id, "Task 16", task_16, task_16_stack, TASK_16_STACK_SIZE, TASK_16_PRIORITY, 0); OS_printf("Create Status = %d, Id = %d\n",status,task_16_id); OS_printf("Status after creating this task: %d\n",status); OS_printf("Id after creating this task: %d\n",task_16_id); if (status != PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_17_id, "Task 17", task_17, task_17_stack, TASK_17_STACK_SIZE, TASK_17_PRIORITY, 0); OS_printf("Create Status = %d, Id = %d\n",status,task_17_id); OS_printf("Status after creating this task: %d\n",status); OS_printf("Id after creating this task: %d\n",task_17_id); if (status != PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_18_id, "Task 18", task_18, task_18_stack, TASK_18_STACK_SIZE, TASK_18_PRIORITY, 0); OS_printf("Create Status = %d, Id = %d\n",status,task_18_id); OS_printf("Status after creating this task: %d\n",status); OS_printf("Id after creating this task: %d\n",task_18_id); if (status != PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_19_id, "Task 19", task_19, task_19_stack, TASK_19_STACK_SIZE, TASK_19_PRIORITY, 0); OS_printf("Create Status = %d, Id = %d\n",status,task_19_id); OS_printf("Status after creating this task: %d\n",status); OS_printf("Id after creating this task: %d\n",task_19_id); if (status != PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_20_id, "Task 20", task_20, task_20_stack, TASK_20_STACK_SIZE, TASK_20_PRIORITY, 0); OS_printf("Create Status = %d, Id = %d\n",status,task_20_id); OS_printf("Status after creating this task: %d\n",status); OS_printf("Id after creating this task: %d\n",task_20_id); if (status == PASS) failTaskCreatecount++; /* Testing the Deletions of all the tasks we have created */ if (OS_TaskDelete(task_0_id) != PASS) failTaskDeletecount++; if (OS_TaskDelete(task_1_id) != PASS) failTaskDeletecount++; if (OS_TaskDelete(task_2_id) != PASS) failTaskDeletecount++; if (OS_TaskDelete(task_3_id) != PASS) failTaskDeletecount++; if (OS_TaskDelete(task_4_id) != PASS) failTaskDeletecount++; if (OS_TaskDelete(task_5_id) != PASS) failTaskDeletecount++; if (OS_TaskDelete(task_6_id) != PASS) failTaskDeletecount++; if (OS_TaskDelete(task_7_id) != PASS) failTaskDeletecount++; if (OS_TaskDelete(task_8_id) != PASS) failTaskDeletecount++; if (OS_TaskDelete(task_9_id) != PASS) failTaskDeletecount++; if (OS_TaskDelete(task_10_id) != PASS) failTaskDeletecount++; if (OS_TaskDelete(task_11_id) != PASS) failTaskDeletecount++; if (OS_TaskDelete(task_12_id) != PASS) failTaskDeletecount++; if (OS_TaskDelete(task_13_id) != PASS) failTaskDeletecount++; if (OS_TaskDelete(task_14_id) != PASS) failTaskDeletecount++; if (OS_TaskDelete(task_15_id) != PASS) failTaskDeletecount++; if (OS_TaskDelete(task_16_id) != PASS) failTaskDeletecount++; if (OS_TaskDelete(task_17_id) != PASS) failTaskDeletecount++; if (OS_TaskDelete(task_18_id) != PASS) failTaskDeletecount++; if (OS_TaskDelete(task_19_id) != PASS) failTaskDeletecount++; /* This Task was never created successfully */ if (OS_TaskDelete(task_20_id) == PASS) failTaskDeletecount++; /* These next few tasks were deleted already, testing a "redelete" */ if (OS_TaskDelete(task_1_id) == PASS) failTaskDeletecount++; if (OS_TaskDelete(task_2_id) == PASS) failTaskDeletecount++; if (OS_TaskDelete(task_3_id) == PASS) failTaskDeletecount++; /* Creating some more tasks for testing name functions */ InitializeTaskIds(); /* Create Task 0 again */ status = OS_TaskCreate( &task_0_id, "Task 0", task_0, task_0_stack, TASK_0_STACK_SIZE, TASK_0_PRIORITY, 0); /*OS_printf("Create Status = %d, Id = %d\n",status,task_0_id); */ if (status != PASS) failTaskCreatecount++; /* Try and create another "Task 0", should fail as we already have one named "Task 0" */ status = OS_TaskCreate( &task_1_id, "Task 0", task_0, task_0_stack, TASK_0_STACK_SIZE, TASK_0_PRIORITY, 0); /* OS_printf("Create Status = %d, Id = %d\n",status,task_1_id); */ if (status == PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_2_id, "Task 2", task_2, task_2_stack, TASK_2_STACK_SIZE, TASK_2_PRIORITY, 0); /* OS_printf("Create Status = %d, Id = %d\n",status,task_2_id); */ if (status != PASS) failTaskCreatecount++; status = OS_TaskCreate( &task_3_id, "Task 3", task_3, task_3_stack, TASK_3_STACK_SIZE, TASK_3_PRIORITY, 0); /* OS_printf("Create Status = %d, Id = %d\n",status,task_3_id); */ if (status != PASS) failTaskCreatecount++; status = OS_TaskGetIdByName(&task_0_id, "Task 0"); /* OS_printf("Satus after Getting the id of \"Task 0\":%d,%d \n\n",status,task_0_id); */ /*first newly created task should have id == 0*/ if (status != PASS || task_0_id != 0) failGetIdcount++; status = OS_TaskGetIdByName(&task_1_id, "Task 1"); /*OS_printf("Satus after Getting the id of \"Task 1\":%d,%d \n\n",status,task_1_id);*/ if (status == PASS) failGetIdcount++; status = OS_TaskGetIdByName(&task_2_id, "Task 2"); /* OS_printf("Satus after Getting the id of \"Task 2\":%d,%d \n\n",status,task_2_id);*/ if (status != PASS || task_2_id != 1) failGetIdcount++; status = OS_TaskGetIdByName(&task_3_id, "Task 3"); /* OS_printf("Satus after Getting the id of \"Task 3\":%d,%d \n\n",status,task_3_id); */ if (status != PASS || task_3_id != 2) failGetIdcount++; if (OS_TaskDelete(task_0_id) != PASS) failTaskDeletecount++; if (OS_TaskDelete(task_1_id) == PASS) failTaskDeletecount++; if (OS_TaskDelete(task_2_id) != PASS) failTaskDeletecount++; if (OS_TaskDelete(task_3_id) != PASS) failTaskDeletecount++; if (failTaskCreatecount != 0) OS_printf("Task Create Failed Count: %d\n", failTaskCreatecount); if (failTaskDeletecount != 0) OS_printf("Task Delete Failed Count: %d\n", failTaskDeletecount); if (failGetIdcount != 0) OS_printf("Task Get ID Failed Count: %d\n", failGetIdcount); totalfail = failTaskCreatecount + failTaskDeletecount + failGetIdcount; return totalfail; }/* end TestTasks */ /* ************************************************************************************ */ int TestQueues(void) { int status; int failQCreatecount = 0; int failQDeletecount = 0; int failQGetIdcount = 0; int totalfailures = 0; InitializeQIds(); status = OS_QueueCreate( &msgq_0, "q 0", MSGQ_DEPTH, MSGQ_SIZE, 0); /* OS_printf("Status after Creating q 0: %d,%d\n",status,msgq_0); */ if (status != PASS) failQCreatecount++; status = OS_QueueCreate( &msgq_1, "q 1", MSGQ_DEPTH, MSGQ_SIZE, 0); /* OS_printf("Status after Creating q 1: %d,%d\n",status,msgq_1); */ if (status != PASS) failQCreatecount++; status = OS_QueueCreate( &msgq_2, "q 2", MSGQ_DEPTH, MSGQ_SIZE, 0); /* OS_printf("Status after Creating q 2: %d,%d\n",status,msgq_2); */ if (status != PASS) failQCreatecount++; status = OS_QueueCreate( &msgq_3, "q 3", MSGQ_DEPTH, MSGQ_SIZE, 0); /* OS_printf("Status after Creating q 3: %d,%d\n",status,msgq_3); */ if (status != PASS) failQCreatecount++; status = OS_QueueCreate( &msgq_4, "q 4", MSGQ_DEPTH, MSGQ_SIZE, 0); /* OS_printf("Status after Creating q 4: %d,%d\n",status,msgq_4); */ if (status != PASS) failQCreatecount++; status = OS_QueueCreate( &msgq_5, "q 5", MSGQ_DEPTH, MSGQ_SIZE, 0); /* OS_printf("Status after Creating q 5: %d,%d\n",status,msgq_5); */ if (status != PASS) failQCreatecount++; status = OS_QueueCreate( &msgq_6, "q 6", MSGQ_DEPTH, MSGQ_SIZE, 0); /* OS_printf("Status after Creating q 6: %d,%d\n",status,msgq_6); */ if (status != PASS) failQCreatecount++; status = OS_QueueCreate( &msgq_7, "q 7", MSGQ_DEPTH, MSGQ_SIZE, 0); /* OS_printf("Status after Creating q 7: %d,%d\n",status,msgq_7); */ if (status != PASS) failQCreatecount++; status = OS_QueueCreate( &msgq_8, "q 8", MSGQ_DEPTH, MSGQ_SIZE, 0); /* OS_printf("Status after Creating q 8: %d,%d\n",status,msgq_8); */ if (status != PASS) failQCreatecount++; status = OS_QueueCreate( &msgq_9, "q 9", MSGQ_DEPTH, MSGQ_SIZE, 0); /* OS_printf("Status after Creating q 9: %d,%d\n",status,msgq_9); */ if (status != PASS) failQCreatecount++; /* This one should fail, it is queue number 11 */ status = OS_QueueCreate( &msgq_10, "q 10", MSGQ_DEPTH, MSGQ_SIZE, 0); /* OS_printf("Status after Creating q 10: %d, %d\n",status,msgq_10); */ if (status == PASS) failQCreatecount++; /* Trying now to Delete all of the Queues created. */ status = OS_QueueDelete(msgq_0); /* OS_printf("Status after Deleting q 0: %d\n",status); */ if (status != PASS) failQDeletecount++; status = OS_QueueDelete(msgq_1); /* OS_printf("Status after Deleting q 1: %d\n",status); */ if (status != PASS) failQDeletecount++; status = OS_QueueDelete(msgq_2); /* OS_printf("Status after Deleting q 2: %d\n",status); */ if (status != PASS) failQDeletecount++; status = OS_QueueDelete(msgq_3); /* OS_printf("Status after Deleting q 3: %d\n",status); */ if (status != PASS) failQDeletecount++; status = OS_QueueDelete(msgq_4); /* OS_printf("Status after Deleting q 4: %d\n",status); */ if (status != PASS) failQDeletecount++; status = OS_QueueDelete(msgq_5); /* OS_printf("Status after Deleting q 5: %d\n",status); */ if (status != PASS) failQDeletecount++; status = OS_QueueDelete(msgq_6); /* OS_printf("Status after Deleting q 6: %d\n",status); */ if (status != PASS) failQDeletecount++; status = OS_QueueDelete(msgq_7); /* OS_printf("Status after Deleting q 7: %d\n",status); */ if (status != PASS) failQDeletecount++; status = OS_QueueDelete(msgq_8); /* OS_printf("Status after Deleting q 8: %d\n",status); */ if (status != PASS) failQDeletecount++; status = OS_QueueDelete(msgq_9); /* OS_printf("Status after Deleting q 9: %d\n",status); */ if (status != PASS) failQDeletecount++; /* This one should have never gotten created, so it */ /* shouldn't get deleted */ status = OS_QueueDelete(msgq_10); /* OS_printf("Status after Deleting q 10: %d\n",status); */ if (status == PASS) failQDeletecount++; /* Create Some more Queues for trying to get the id by name */ InitializeQIds(); status = OS_QueueCreate( &msgq_0, "q 0", MSGQ_DEPTH, MSGQ_SIZE, 0); /* OS_printf("Status after Creating q 0: %d,%d\n",status,msgq_0);*/ if (status != PASS) failQCreatecount++; /* This one should fail */ status = OS_QueueCreate( &msgq_1, "q 0", MSGQ_DEPTH, MSGQ_SIZE, 0); /* OS_printf("Status after Creating q 0 again: %d,%d\n",status,msgq_1); */ if (status == PASS) failQCreatecount++; status = OS_QueueCreate( &msgq_2, "q 2", MSGQ_DEPTH, MSGQ_SIZE, 0); /* OS_printf("Status after Creating q 2: %d,%d\n",status,msgq_2); */ if (status != PASS) failQCreatecount++; status = OS_QueueCreate( &msgq_3, "q 3", MSGQ_DEPTH, MSGQ_SIZE, 0); /* OS_printf("Status after Creating q 3: %d,%d\n",status,msgq_3); */ if (status != PASS) failQCreatecount++; /* * Now that the Queues are created, its time to see if we can find * the propper ID by the name of the queue; */ status = OS_QueueGetIdByName(&msgq_0,"q 0"); if (status != PASS || msgq_0 != 0) failQGetIdcount++; status = OS_QueueGetIdByName(&msgq_1,"q 1"); if (status == PASS) failQGetIdcount++; status = OS_QueueGetIdByName(&msgq_2,"q 2"); if (status != PASS || msgq_2 != 1) failQGetIdcount++; status = OS_QueueGetIdByName(&msgq_3,"q 3"); if (status != PASS || msgq_3 != 2) failQGetIdcount++; /* Time to Delete the Queues we just created */ status = OS_QueueDelete(msgq_0); /* OS_printf("Status after Deleting q 0 : %d\n",status); */ if (status != PASS) failQDeletecount++; status = OS_QueueDelete(msgq_1); /* OS_printf("Status after Deleting q 1: %d\n",status); */ if (status == PASS) failQDeletecount++; status = OS_QueueDelete(msgq_2); /* OS_printf("Status after Deleting q 2: %d\n",status); */ if (status != PASS) failQDeletecount++; status = OS_QueueDelete(msgq_3); /* OS_printf("Status after Deleting q 3: %d\n",status); */ if (status != PASS) failQDeletecount++; totalfailures = failQCreatecount + failQDeletecount + failQGetIdcount; if (totalfailures != 0) { OS_printf("Queue Create Failed Count: %d\n",failQCreatecount); OS_printf("Queue Delete Failed Count: %d\n",failQDeletecount); OS_printf("Queue Get ID Failed Count: %d\n",failQGetIdcount); } return totalfailures; }/* end TestQueues */ /* *************************************************************************** */ int TestBinaries(void) { int failBinCreatecount = 0; int failBinDeletecount = 0; int failBinGetIdcount = 0; int totalfailures = 0; int status; InitializeBinIds(); status = OS_BinSemCreate( &bin_0,"Bin 0",1,0); /* OS_printf("Status after creating: %d,%d\n",status,bin_0); */ if (status != OS_SUCCESS) failBinCreatecount++; status = OS_BinSemCreate( &bin_1,"Bin 1",1,0); /* OS_printf("Status after creating: %d,%d\n",status,bin_1); */ if (status != OS_SUCCESS) failBinCreatecount++; status = OS_BinSemCreate( &bin_2,"Bin 2",1,0); /* OS_printf("Status after creating: %d,%d\n",status,bin_2); */ if (status != OS_SUCCESS) failBinCreatecount++; status = OS_BinSemCreate( &bin_3,"Bin 3",1,0); /* OS_printf("Status after creating: %d,%d\n",status,bin_3); */ if (status != OS_SUCCESS) failBinCreatecount++; status = OS_BinSemCreate( &bin_4,"Bin 4",1,0); /* OS_printf("Status after creating: %d,%d\n",status,bin_4); */ if (status != OS_SUCCESS) failBinCreatecount++; status = OS_BinSemCreate( &bin_5,"Bin 5",1,0); /* OS_printf("Status after creating: %d,%d\n",status,bin_5); */ if (status != OS_SUCCESS) failBinCreatecount++; status = OS_BinSemCreate( &bin_6,"Bin 6",1,0); /* OS_printf("Status after creating: %d,%d\n",status,bin_6); */ if (status != OS_SUCCESS) failBinCreatecount++; status = OS_BinSemCreate( &bin_7,"Bin 7",1,0); /* OS_printf("Status after creating: %d,%d\n",status,bin_7); */ if (status != OS_SUCCESS) failBinCreatecount++; status = OS_BinSemCreate( &bin_8,"Bin 8",1,0); /* OS_printf("Status after creating: %d,%d\n",status,bin_8); */ if (status != OS_SUCCESS) failBinCreatecount++; status = OS_BinSemCreate( &bin_9,"Bin 9",1,0); /* OS_printf("Status after creating: %d,%d\n",status,bin_9); */ if (status != OS_SUCCESS) failBinCreatecount++; status = OS_BinSemCreate( &bin_10,"Bin 10",1,0); /* OS_printf("Status after creating: %d,%d\n",status,bin_10); */ if (status == OS_SUCCESS) failBinCreatecount++; status = OS_BinSemDelete(bin_0); /* OS_printf("Status after deleteing:%d\n",status); */ if (status != OS_SUCCESS) failBinDeletecount++; status = OS_BinSemDelete(bin_1); /* OS_printf("Status after deleteing:%d\n",status); */ if (status != OS_SUCCESS) failBinDeletecount++; status = OS_BinSemDelete(bin_2); /* OS_printf("Status after deleteing:%d\n",status); */ if (status != OS_SUCCESS) failBinDeletecount++; status = OS_BinSemDelete(bin_3); /* OS_printf("Status after deleteing:%d\n",status); */ if (status != OS_SUCCESS) failBinDeletecount++; status = OS_BinSemDelete(bin_4); /* OS_printf("Status after deleteing:%d\n",status); */ if (status != OS_SUCCESS) failBinDeletecount++; status = OS_BinSemDelete(bin_5); /* OS_printf("Status after deleteing:%d\n",status); */ if (status != OS_SUCCESS) failBinDeletecount++; status = OS_BinSemDelete(bin_6); /* OS_printf("Status after deleteing:%d\n",status); */ if (status != OS_SUCCESS) failBinDeletecount++; status = OS_BinSemDelete(bin_7); /* OS_printf("Status after deleteing:%d\n",status); */ if (status != OS_SUCCESS) failBinDeletecount++; status = OS_BinSemDelete(bin_8); /* OS_printf("Status after deleteing:%d\n",status); */ if (status != OS_SUCCESS) failBinDeletecount++; status = OS_BinSemDelete(bin_9); /* OS_printf("Status after deleteing:%d\n",status); */ if (status != OS_SUCCESS) failBinDeletecount++; status = OS_BinSemDelete(bin_10); /* OS_printf("Status after deleteing:%d\n",status); */ if (status == OS_SUCCESS) failBinDeletecount++; /* * Now Create a few extra semaphores * to test GetIdByName */ InitializeBinIds(); status = OS_BinSemCreate( &bin_0,"Bin 0",OS_SEM_FULL,0); /* OS_printf("Status after creating: %d,%d\n",status,bin_0); */ if (status != OS_SUCCESS) failBinCreatecount++; status = OS_BinSemCreate( &bin_1,"Bin 0",OS_SEM_FULL,0); /* OS_printf("Status after creating: %d,%d\n",status,bin_1); */ if (status == OS_SUCCESS) failBinCreatecount++; status = OS_BinSemCreate( &bin_2,"Bin 2",OS_SEM_EMPTY,0); /* OS_printf("Status after creating: %d,%d\n",status,bin_2); */ if (status != OS_SUCCESS) failBinCreatecount++; status = OS_BinSemCreate( &bin_3,"Bin 3",OS_SEM_EMPTY,0); /* OS_printf("Status after creating: %d,%d\n",status,bin_3); */ if (status != OS_SUCCESS) failBinCreatecount++; status = OS_BinSemGetIdByName(&bin_0,"Bin 0"); /* OS_printf("Status after GETID: %d,%d\n",status,bin_0); */ if (status != OS_SUCCESS || bin_0 != 0) failBinGetIdcount++; status = OS_BinSemGetIdByName(&bin_1,"Bin 1"); /* OS_printf("Status after GETID: %d,%d\n",status,bin_1); */ if (status == OS_SUCCESS) failBinGetIdcount++; status = OS_BinSemGetIdByName(&bin_2,"Bin 2"); /* OS_printf("Status after GETID: %d,%d\n",status,bin_2); */ if (status != OS_SUCCESS || bin_2 != 1) failBinGetIdcount++; status = OS_BinSemGetIdByName(&bin_3,"Bin 3"); /* OS_printf("Status after GETID: %d,%d\n",status,bin_3); */ if (status != OS_SUCCESS || bin_3 != 2) failBinGetIdcount++; status = OS_BinSemDelete(bin_0); /* OS_printf("Status after deleteing:%d\n",status); */ if (status != OS_SUCCESS) failBinDeletecount++; /* this one was never created */ status = OS_BinSemDelete(bin_1); /* OS_printf("Status after deleteing:%d\n",status); */ if (status == OS_SUCCESS) failBinDeletecount++; if (failBinCreatecount != 0) OS_printf("Bin Sem Create Failed Count %d\n", failBinCreatecount); if (failBinDeletecount != 0) OS_printf("Bin Sem Delete Failed Count %d\n", failBinDeletecount); if (failBinGetIdcount != 0) OS_printf("Bin Sem Get ID Failed Count %d\n", failBinGetIdcount); totalfailures = failBinCreatecount + failBinDeletecount + failBinGetIdcount; return totalfailures; }/* end TestBinaries */ /* ************************************************************************************ */ int TestMutexes(void) { int failMutCreatecount = 0; int failMutDeletecount = 0; int failMutGetIdcount = 0; int totalfailures = 0; int status; InitializeMutIds(); status = OS_MutSemCreate( &mut_0,"Mut 0",0); /* OS_printf("Status after creating Mut 0: %d,%d\n",status,mut_0); */ if (status != OS_SUCCESS) failMutCreatecount++; status = OS_MutSemCreate( &mut_1,"Mut 1",0); /* OS_printf("Status after creating Mut 1: %d,%d\n",status,mut_1); */ if (status != OS_SUCCESS) failMutCreatecount++; status = OS_MutSemCreate( &mut_2,"Mut 2",0); /* OS_printf("Status after creating Mut 2: %d,%d\n",status,mut_2); */ if (status != OS_SUCCESS) failMutCreatecount++; status = OS_MutSemCreate( &mut_3,"Mut 3",0); /* OS_printf("Status after creating Mut 3: %d,%d\n",status,mut_3); */ if (status != OS_SUCCESS) failMutCreatecount++; status = OS_MutSemCreate( &mut_4,"Mut 4",0); /* OS_printf("Status after creating Mut 4: %d,%d\n",status,mut_4); */ if (status != OS_SUCCESS) failMutCreatecount++; status = OS_MutSemCreate( &mut_5,"Mut 5",0); /* OS_printf("Status after creating Mut 5: %d,%d\n",status,mut_5); */ if (status != OS_SUCCESS) failMutCreatecount++; status = OS_MutSemCreate( &mut_6,"Mut 6",0); /* OS_printf("Status after creating Mut 6: %d,%d\n",status,mut_6); */ if (status != OS_SUCCESS) failMutCreatecount++; status = OS_MutSemCreate( &mut_7,"Mut 7",0); /* OS_printf("Status after creating Mut 7: %d,%d\n",status,mut_7); */ if (status != OS_SUCCESS) failMutCreatecount++; status = OS_MutSemCreate( &mut_8,"Mut 8",0); /* OS_printf("Status after creating Mut 8: %d,%d\n",status,mut_8); */ if (status != OS_SUCCESS) failMutCreatecount++; status = OS_MutSemCreate( &mut_9,"Mut 9",0); /* OS_printf("Status after creating Mut 9: %d,%d\n",status,mut_9); */ if (status != OS_SUCCESS) failMutCreatecount++; status = OS_MutSemCreate( &mut_10,"Mut 10",0); /* OS_printf("Status after creating Mut 10: %d,%d\n",status,mut_10); */ if (status == OS_SUCCESS) failMutCreatecount++; status = OS_MutSemDelete(mut_0); /* OS_printf("Status after deleteing Mut 0:%d\n",status); */ if (status != OS_SUCCESS) failMutDeletecount++; status = OS_MutSemDelete(mut_1); /* OS_printf("Status after deleteing Mut 1:%d\n",status); */ if (status != OS_SUCCESS) failMutDeletecount++; status = OS_MutSemDelete(mut_2); /* OS_printf("Status after deleteing Mut 2:%d\n",status); */ if (status != OS_SUCCESS) failMutDeletecount++; status = OS_MutSemDelete(mut_3); /* OS_printf("Status after deleteing Mut 3:%d\n",status); */ if (status != OS_SUCCESS) failMutDeletecount++; status = OS_MutSemDelete(mut_4); /* OS_printf("Status after deleteing Mut 4:%d\n",status); */ if (status != OS_SUCCESS) failMutDeletecount++; status = OS_MutSemDelete(mut_5); /* OS_printf("Status after deleteing Mut 5:%d\n",status); */ if (status != OS_SUCCESS) failMutDeletecount++; status = OS_MutSemDelete(mut_6); /* OS_printf("Status after deleteing Mut 6:%d\n",status); */ if (status != OS_SUCCESS) failMutDeletecount++; status = OS_MutSemDelete(mut_7); /* OS_printf("Status after deleteing Mut 7:%d\n",status); */ if (status != OS_SUCCESS) failMutDeletecount++; status = OS_MutSemDelete(mut_8); /* OS_printf("Status after deleteing Mut 8:%d\n",status); */ if (status != OS_SUCCESS) failMutDeletecount++; status = OS_MutSemDelete(mut_9); /* OS_printf("Status after deleteing Mut 9:%d\n",status); */ if (status != OS_SUCCESS) failMutDeletecount++; status = OS_MutSemDelete(mut_10); /* OS_printf("Status after deleteing Mut 10:%d\n",status); */ if (status == OS_SUCCESS) failMutDeletecount++; /* * Now Create a few extra semaphores * to test GetIdByName */ InitializeMutIds(); status = OS_MutSemCreate( &mut_0,"Mut 0",0); /* OS_printf("Status after creating Mut 0: %d,%d\n",status,mut_0); */ if (status != OS_SUCCESS) failMutCreatecount++; status = OS_MutSemCreate( &mut_1,"Mut 0",0); /* OS_printf("Status after creating Mut 0 again: %d,%d\n",status,mut_1); */ if (status == OS_SUCCESS) failMutCreatecount++; status = OS_MutSemCreate( &mut_2,"Mut 2",0); /* OS_printf("Status after creating Mut 2: %d,%d\n",status,mut_2); */ if (status != OS_SUCCESS) failMutCreatecount++; status = OS_MutSemCreate( &mut_3,"Mut 3",0); /* OS_printf("Status after creating Mut 3: %d,%d\n",status,mut_3); */ if (status != OS_SUCCESS) failMutCreatecount++; status = OS_MutSemGetIdByName(&mut_0,"Mut 0"); if (status != OS_SUCCESS || mut_0 != 0) failMutGetIdcount++; status = OS_MutSemGetIdByName(&mut_1,"Mut 1"); if (status == OS_SUCCESS) failMutGetIdcount++; status = OS_MutSemGetIdByName(&mut_2,"Mut 2"); if (status != OS_SUCCESS || mut_2 != 1) failMutGetIdcount++; status = OS_MutSemGetIdByName(&mut_3,"Mut 3"); if (status != OS_SUCCESS || mut_3 != 2) failMutGetIdcount++; status = OS_MutSemDelete(mut_0); /* OS_printf("Status after deleteing Mut 0:%d\n",status); */ if (status != OS_SUCCESS) failMutDeletecount++; /* this one was never created*/ status = OS_MutSemDelete(mut_1); /* OS_printf("Status after deleteing Mut 1:%d\n",status); */ if (status == OS_SUCCESS) failMutDeletecount++; status = OS_MutSemDelete(mut_2); /* OS_printf("Status after deleteing Mut 2:%d\n",status); */ if (status != OS_SUCCESS) failMutDeletecount++; status = OS_MutSemDelete(mut_3); /* OS_printf("Status after deleteing Mut 3:%d\n",status); */ if (status != OS_SUCCESS) failMutDeletecount++; if (failMutCreatecount != 0) OS_printf("Mutex Create Failed Count %d\n", failMutCreatecount); if (failMutDeletecount != 0) OS_printf("Mutex Delete Failed Count %d\n", failMutDeletecount); if (failMutGetIdcount != 0) OS_printf("Mutex Get ID Failed Count %d\n", failMutGetIdcount); totalfailures = failMutCreatecount + failMutDeletecount + failMutGetIdcount; return totalfailures; } /* end TestMutexes */ /* These next several tasks simply initialize the ids to a number which * cannot occur in the system itself. This helps avoid confusion when a create * fails, and the previous value of the id is displayed * */ /* ************************************************************************** */ void InitializeTaskIds(void) { task_0_id = 99; task_1_id = 99; task_2_id = 99; task_3_id = 99; task_4_id = 99; task_5_id = 99; task_6_id = 99; task_7_id = 99; task_8_id = 99; task_9_id = 99; task_10_id = 99; task_11_id = 99; task_12_id = 99; task_13_id = 99; task_14_id = 99; task_15_id = 99; task_16_id = 99; task_17_id = 99; task_18_id = 99; task_19_id = 99; task_20_id = 99; return; } /* end InitializeTaskIds */ /* **************************************************************************** */ void InitializeQIds(void) { msgq_0 = 99; msgq_1 = 99; msgq_2 = 99; msgq_3 = 99; msgq_4 = 99; msgq_5 = 99; msgq_6 = 99; msgq_7 = 99; msgq_8 = 99; msgq_9 = 99; msgq_10 = 99; msgq_id = 99; return; } /* end InitializeQIds */ /* ***************************************************************************** */ void InitializeBinIds(void) { bin_0 = 99; bin_1 = 99; bin_2 = 99; bin_3 = 99; bin_4 = 99; bin_5 = 99; bin_6 = 99; bin_7 = 99; bin_8 = 99; bin_9 = 99; bin_10 = 99; return; } /* end InitializeBinIds */ /* ***************************************************************************** */ void InitializeMutIds(void) { mut_0 = 99; mut_1 = 99; mut_2 = 99; mut_3 = 99; mut_4 = 99; mut_5 = 99; mut_6 = 99; mut_7 = 99; mut_8 = 99; mut_9 = 99; mut_10 = 99; return; } /* end InitializeMutIds */ /* ***************************************************************************** */ int TestGetInfos(void) { int status; int failTaskCreatecount = 0; int failTaskDeletecount = 0; int failQCreatecount = 0; int failQDeletecount = 0; int failBinCreatecount = 0; int failBinDeletecount = 0; int failMutCreatecount = 0; int failMutDeletecount = 0; int failGetInfocount = 0; int totalfailures = 0; OS_task_prop_t task_prop; OS_queue_prop_t queue_prop; OS_bin_sem_prop_t bin_prop; OS_mut_sem_prop_t mut_prop; /* first step is to create an object to to get the properties of */ status = OS_TaskCreate( &task_0_id, "Task 0", task_0, task_0_stack, TASK_0_STACK_SIZE, TASK_0_PRIORITY, 0); if (status != PASS) failTaskCreatecount++; status = OS_QueueCreate( &msgq_0, "q 0", MSGQ_DEPTH, MSGQ_SIZE, 0); /* OS_printf("Status after Creating q 0: %d,%d\n",status,msgq_0); */ if (status != PASS) failQCreatecount++; status = OS_BinSemCreate( &bin_0,"Bin 0",1,0); /* OS_printf("Status after creating: %d,%d\n",status,bin_0); */ if (status != OS_SUCCESS) failBinCreatecount++; status = OS_MutSemCreate( &mut_0,"Mut 0",0); /* OS_printf("Status after creating: %d,%d\n",status,mut_0); */ if (status != OS_SUCCESS) failMutCreatecount++; /* Next Step is to get the properties of the objects */ status = OS_TaskGetInfo(task_0_id, &task_prop); if (status != OS_SUCCESS) failGetInfocount++; status = OS_QueueGetInfo(msgq_0, &queue_prop); if (status != OS_SUCCESS) failGetInfocount++; status = OS_BinSemGetInfo(bin_0, &bin_prop); if (status != OS_SUCCESS) failGetInfocount++; status = OS_MutSemGetInfo(mut_0, &mut_prop); if (status != OS_SUCCESS) failGetInfocount++; if (OS_TaskDelete(task_0_id) != PASS) failTaskDeletecount++; status = OS_QueueDelete(msgq_0); /* OS_printf("Status after Deleting q 0: %d\n",status); */ if (status != PASS) failQDeletecount++; status = OS_BinSemDelete(bin_0); /* OS_printf("Status after deleteing:%d\n",status); */ if (status != OS_SUCCESS) failBinDeletecount++; status = OS_MutSemDelete(mut_0); /* OS_printf("Status after deleteing:%d\n",status); */ if (status != OS_SUCCESS) failMutDeletecount++; totalfailures = failMutDeletecount + failBinDeletecount + failQDeletecount + failTaskDeletecount + failMutCreatecount + failBinCreatecount + failQCreatecount + failTaskCreatecount + failGetInfocount; return totalfailures; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rgrigore <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/12/27 21:25:40 by rgrigore #+# #+# */ /* Updated: 2018/01/03 18:46:29 by rgrigore ### ########.fr */ /* */ /* ************************************************************************** */ #include <fcntl.h> #include <unistd.h> #include "fillit.h" char *empty_map(int size) { char *str; int i; int j; str = (char*)malloc(((size + 1) * size) * sizeof(char)); ft_bzero(str, (size + 1) * size + 1); j = -1; while (++j < size) { i = -1; while (++i < size) str[j * (size + 1) + i] = '.'; str[j * (size + 1) + i] = '\n'; } return (str); } void print(t_etris *tet, int count, int size) { char *str; int i; int j; str = empty_map(size); while (count-- > 0) { j = -1; while (++j < tet->height) { i = -1; while (++i < tet->width) if ((tet->value >> (16 * (j + 1) - 1 - i)) & 1) str[(tet->y + j) * (size + 1) + i + tet->x] = tet->id; } tet++; } while (*str) write(1, &(*str++), 1); } int error(char *str) { while (*str) { write(1, &(*str), 1); str++; } write(1, "\n", 1); return (1); } void ft_bzero(void *s, size_t n) { unsigned char *c; size_t i; c = (unsigned char*)s; i = 0; while (i < n) c[i++] = 0; s = c; } int main(int argc, char **argv) { t_etris tetris[27]; uint16_t map[16]; int count; int size; if (argc != 2) return (error("usage: ./fillit [input_file]")); ft_bzero(tetris, sizeof(t_etris) * (26 + 1)); if (!(count = read_tetri(open(argv[1], O_RDONLY), tetris))) return (error("error")); ft_bzero(map, sizeof(uint16_t) * 16); if ((size = solve(tetris, count, map)) == 0) return (error("error")); print(tetris, count, size); return (0); }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <errno.h> #define INIT_STACK_SIZE 5 #define STACK_EXTEND_SIZE 5 // typedef struct elemType // { // int data; // char name; // } elemType; typedef int elemType; typedef struct stack { elemType *top; elemType *base; int stackSize; } Stack, *pStack; // pStack initStack(pStack pS); bool initStack(Stack *S); // elemType get_base_elem(Stack *S); elemType get_top_elem(Stack *S); // bool pop(Stack **S, elemType *e); bool pop(Stack *S, elemType **e); // bool push(Stack **S, elemType data); bool push(Stack *S, elemType data); bool visit(Stack *S); int main() { Stack S1; elemType tmp; tmp = malloc(sizeof(elemType)); initStack(&S1); for (elemType i = 1; i < 100; i++) { push(&S1, i); printf("stack size is:%d\n", S1.stackSize); } for (int i = 1; i < 100; i++) { pop(&S1, &tmp); printf("tmp is :%d\n", tmp); } } bool visit(Stack *S) { return true; } bool initStack(Stack *S) { (*S).base = (elemType *)malloc(INIT_STACK_SIZE * sizeof(Stack)); (*S).stackSize = INIT_STACK_SIZE; if (!(*S).base) { return false; exit(1); } (*S).top = (*S).base; return true; } elemType get_top_elem(Stack *S) { if ((*S).top == (*S).base) { return 0; } return *((*S).top - 1); } bool pop(Stack *S, elemType **e) { if ((*S).top == (*S).base) { return false; } *e = *((*S).top - 1); (*S).top--; // printf("func tmp is :%d\n", *e); return true; } bool push(Stack *S, elemType data) { if ((*S).top - (*S).base >= (*S).stackSize) { // printf("pre base ptr is:%p\n", (*S).base); (*S).base = (elemType *)realloc((*S).base, ((*S).stackSize + STACK_EXTEND_SIZE) * sizeof(elemType)); // printf("after base ptr is:%p\n", (*S).base); (*S).top = (*S).base + (*S).stackSize; (*S).stackSize += STACK_EXTEND_SIZE; } if (!(*S).base) { return false; exit(1); } *(*S).top++ = data; return true; }
C
// |oled_driver.c|: Implementation of the OLED Display Drivers // // @author: Joe Gibson // @author: Adam Luckenbaugh #include "oled_driver.h" //Initialize OLED Display Driver void oled_d_init(void) { //Initialize OLED Display RIT128x96x4Init(1000000); } //Print at 0,0 with full brightness void oled_d_print_origin(char *str) { IntMasterDisable(); RIT128x96x4StringDraw(str, 0, 0, MAX_BRIGHTNESS); IntMasterEnable(); } //Print at x,y with full brightness void oled_d_print_xy(char *str, unsigned long x, unsigned long y) { IntMasterDisable(); RIT128x96x4StringDraw(str, x, y, MAX_BRIGHTNESS); IntMasterEnable(); } //Print at x,y with given brightness void oled_d_print_xyb(char *str, unsigned long x, unsigned long y, unsigned long b) { IntMasterDisable(); RIT128x96x4StringDraw(str, x, y, b); IntMasterEnable(); } //Display a full-spanning horizontal bar with varying height and // brightness, corresponding to the 'volume' of the input audio signal void oled_d_display_bar(int aHeight) { char * cDarkStr = "#####################"; char * cClearStr = " "; unsigned charHeight = 8; unsigned rowInc = OLED_ROWS / charHeight; //Calculate brightness as a percentage of MAX_BRIGHTNESS, // but keep between MAX_BRIGHTNESS and MIN_BRIGHTNESS unsigned brightness = ((unsigned)((aHeight / 1023.0) * (double)MAX_BRIGHTNESS) % (MAX_BRIGHTNESS - MIN_BRIGHTNESS)) + MIN_BRIGHTNESS; //Display a vertical bar with a variable height and variable brightness for(unsigned rows = 0; rows < OLED_ROWS / charHeight; rows++) { if( rowInc - rows < (rowInc * (aHeight / 1023.0) )) { oled_d_print_xyb(cDarkStr, 0, rows * charHeight, brightness); } else { oled_d_print_xyb(cClearStr, 0, rows * charHeight, brightness); } } } //Clear the screen void oled_d_clear(void) { IntMasterDisable(); RIT128x96x4Clear(); IntMasterEnable(); }
C
#ifndef NCMLIB_COPY_CMDARG_H_ #define NCMLIB_COPY_CMDARG_H_ #include <stdio.h> #include <stdlib.h> #include "nk/log.h" static inline void copy_cmdarg(char *dest, const char *src, size_t destlen, const char *argname) { ssize_t olen = snprintf(dest, destlen, "%s", src); if (olen < 0) suicide("snprintf failed on %s; your system is broken?", argname); if ((size_t)olen >= destlen) suicide("snprintf would truncate %s arg; it's too long", argname); } #endif /* NCMLIB_COPY_CMDARG_H_ */
C
#include "graph.h" void add_edge(graph* curr_graph, edge* new_edge) { } void edge_swap(edge* a, edge* b) { edge c = *a; *a = *b; *b =c; } int main() { return 0; }
C
//Peter's smoke #include<stdio.h> int main() { int a,n,k; while(scanf("%d %d",&n,&k)==2) { a=n; while(n>=k) { a=a+(n/k); n=(n/k)+(n%k); } printf("%d\n",a); } return 0; }
C
#include "misc.h" #include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char* argv[]) { if(argc > 3) { printf("Usage: [PROGRAM NAME] [FILE NAME] [USE LARGE]\n"); return 0; } else if(argc == 3) { // initialize file name unsigned int fnlen = strlen(argv[1]); char* fn2bit = (char*) malloc(fnlen+6); strcpy(fn2bit, argv[1]); strcpy(fn2bit+fnlen, "_2bit"); fn2bit[fnlen+5] = '\0'; char* fn3bit = (char*) malloc(fnlen+6); strcpy(fn3bit, argv[1]); strcpy(fn3bit+fnlen, "_3bit"); fn3bit[fnlen+5] = '\0'; // create 2 bit and 3 bit genome unsigned int len = 3000001; if(argv[2][0] == 't' || argv[2][0] == 'T') len = GENOME_SIZE; unsigned int fsz2bit = (2*len-1)/BYTE_SIZE + 1; unsigned int fsz3bit = (3*len-1)/BYTE_SIZE + 1; char* genome_2bit = (char*) malloc(fsz2bit*sizeof(char)); char* genome_3bit = (char*) malloc(fsz3bit*sizeof(char)); memset(genome_2bit, 0, fsz2bit); memset(genome_3bit, 0, fsz3bit); printf("generating file...\n"); for(unsigned int i = 0; i < len - 1; i++) { unsigned int rnd = randnum(0, 3); char bp = '*'; switch(rnd) { case 0: bp = 'a'; break; case 1: bp = 'c'; break; case 2: bp = 'g'; break; case 3: bp = 't'; break; } write_bp_2bit(genome_2bit, i, bp); write_bp_3bit(genome_3bit, i, bp); } write_bp_3bit(genome_3bit, len-1, '$'); // verify result printf("verifying result...\n"); for(unsigned int i = 0; i < len - 1; i++) { char bp2 = get_bp_2bit(genome_2bit, i); char bp3 = get_bp_3bit(genome_3bit, i); if(bp2 != bp3) { printf("%d: %c != %c\n", i, bp2, bp3); return 0; } } // save to disk printf("saving to disk...\n"); write_file(fn2bit, genome_2bit, fsz2bit); write_file(fn3bit, genome_3bit, fsz3bit); // free memory free(genome_2bit); free(genome_3bit); free(fn2bit); free(fn3bit); } else if(argc == 2) { char* genome3bit; read_file(argv[1], &genome3bit); unsigned int len = GENOME_SIZE; for(unsigned int i = 0; i < len; i++) { char bp = get_bp_3bit(genome3bit, i); if(bp == '*') printf("error!!!\n"); } unsigned long long int read_sz = READ_SIZE; unsigned long long int read_num = READ_NUM; size_t srfsz = read_sz*read_num*2/8; char* sr2 = (char*) malloc(srfsz); memset(sr2, 0, srfsz); unsigned int k = 0; for(unsigned int i = 0; i < read_num; i++) { int diff = 0; int diffnum = randnum(0,2); unsigned int stpos = randnum(0, len-100-read_sz); unsigned int endpos = stpos + read_sz; for(unsigned int j = stpos; j < endpos; j++) { unsigned int coin = randnum(0, 1); char bp = get_bp_3bit(genome3bit, j); if(coin == 0 || diffnum <= 0) { write_bp_2bit(sr2, k, bp); } else if(coin == 1 && diffnum > 0) { if(bp == 'a') { unsigned int rndn = randnum(0,2); switch(rndn) { case 0: { write_bp_2bit(sr2, k, 'c'); break; } case 1: { write_bp_2bit(sr2, k, 'g'); break; } case 2: { write_bp_2bit(sr2, k, 't'); break; } } } if(bp == 'c') { unsigned int rndn = randnum(0,2); switch(rndn) { case 0: { write_bp_2bit(sr2, k, 'a'); break; } case 1: { write_bp_2bit(sr2, k, 'g'); break; } case 2: { write_bp_2bit(sr2, k, 't'); break; } } } if(bp == 'g') { unsigned int rndn = randnum(0,2); switch(rndn) { case 0: { write_bp_2bit(sr2, k, 'a'); break; } case 1: { write_bp_2bit(sr2, k, 'c'); break; } case 2: { write_bp_2bit(sr2, k, 't'); break; } } } if(bp == 't') { unsigned int rndn = randnum(0,2); switch(rndn) { case 0: { write_bp_2bit(sr2, k, 'a'); break; } case 1: { write_bp_2bit(sr2, k, 'c'); break; } case 2: { write_bp_2bit(sr2, k, 'g'); break; } } } diffnum--; diff++; }// else if k++; }// inner for } // outer for printf("generated\n"); write_file("short_read_2bit", sr2, srfsz); } // else if }
C
#include <stdlib.h> int reverse(int x) { int digit; int result = 0; int prev_result = 0; while (x != 0) { digit = x % 10; prev_result = result; result = result * 10 + digit; if (((result - digit) / 10) != prev_result) /*overflow*/ return 0; x = x / 10; } return result; }
C
#include "lists.h" /** * add_dnodeint_end - function that adds a new node at the end of a list_t list * @head: input header pointer * @n: input int value * Return: the address of the new element, or NULL if it failed */ dlistint_t *add_dnodeint_end(dlistint_t **head, const int n) { dlistint_t *newNode; dlistint_t *temp; newNode = malloc(sizeof(dlistint_t)); if (newNode == NULL) return (NULL); (*newNode).n = n; (*newNode).next = NULL; if (*head == NULL) { (*newNode).prev = NULL; *head = newNode; } else { temp = *head; while ((*temp).next != NULL) temp = (*temp).next; (*temp).next = newNode; (*newNode).prev = temp; } return (newNode); }
C
#include "Stack.h" /* Push data to the stack */ void* push(Stack* stack, void* data) { // Argument validation. if (stack == NULL || data == NULL) return NULL; Node* newNode = initializeNewNode(); newNode->data = data; newNode->next = stack->head; stack->head = newNode; stack->size++; return data; } /* Pop data from the stack */ void* pop(Stack* stack) { // Argument validation if (stack == NULL) return NULL; Node* popedNode = stack->head; stack->head = stack->head->next; stack->size--; return popedNode->data; } /* Peek at top of stack */ void* peek(Stack* stack) { // Argument validation if (stack == NULL || stack->head == NULL) return NULL; return stack->head->data; } /* Init new stack struct. */ Stack* initializeNewStack() { Stack* newStack = (Stack*)malloc(sizeof(Stack)); newStack->head = NULL; newStack->size = 0; } /* Init new node stuct. */ Node* initializeNewNode() { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = NULL; newNode->next = NULL; }
C
/*********************************************************************************** Xinzhan: This header file: 1),defines the shape that used to fit signal, and supply this shape to TMinuit. 2), contains the fcn global function that TMinuit will minimize. ***********************************************************************************/ #ifndef _GEMFITTINGSHAPE_H_ #define _GEMFITTINGSHAPE_H_ #include <TMath.h> #include "Config.h" //================================================================================== //Global Variables, needed by TMinuit //passing the fit function TF1 *fparam; //passing the data points for fcn Int_t nTS = kMAXADC; Double_t X[kMAXADC]; Double_t Y[kMAXADC]; Double_t Sigma[kMAXADC]; //================================================================================== Double_t Pdf(Double_t *xPtr, Double_t par[]) { //Distribution function AKA model /* //Original fitting function //Use this shape to fit data TF1 fV("fV", "[0]*(x-[2])/([1])*exp(-(x-[2])/[1])"); //fitting funtion fV.SetRange(-300,500); fV.SetParameters(700.0, 65.0, 20.0); fV.SetParLimits(0, 0.0, 5000000); fV.SetParLimits(1, 0.0, 500); fV.SetParLimits(2, -100.0, 1000); */ Double_t x = *xPtr; Double_t A = par[0]; //normalization Double_t start = par[2]; //Start Time Double_t shape = par[1]; //Shapping Time Double_t f=0; f = A * (x-start)/(shape)*TMath::Exp(-(x-start)/shape); return f; } //================================================================================== Double_t CalcNLL(Int_t nTS, Double_t *X, Double_t *Y, Double_t *Sigma, TF1* f) { //NLL calculation Function //nTS -> # of Time Bins AKA # of data points //X -> coordinates of x //Y -> coordinates of y //Sigma -> error on y //f -> model Double_t nll = 0; for(int i=0;i<nTS;i++) { Double_t x = X[i]; Double_t y = Y[i]; Double_t sigma = Sigma[i]; Double_t mu = f->Eval(x); if(mu < 1e-10) mu = 1e-10; // avoid log(0) problems nll -= (-0.5)*TMath::Log(2*TMath::Pi()*sigma) - 0.5*(y-mu)*(y-mu)/sigma/sigma; } return 2*nll; //factor of -2 so minuit gets the errors right } //================================================================================== void fcn(int& npar, double* deriv, double& f, double par[], int flag) { //Function to be passed to TMinuit; This function is in fixed format for (int i=0; i<npar; i++) { fparam->SetParameter(i,par[i]); } f = CalcNLL(nTS, X, Y, Sigma ,fparam); } #endif
C
#include <stdio.h> #include "myBank.h" #define ROW 50 #define COL 2 #define Close 0 #define Open 1 double Bank_account[ROW][COL] = {0}; void Create_new_account(){ int number_account = 901; int i = 0; while(i < 50){ if(Bank_account[i][0] == Close){ double amount; printf("enter amount: "); scanf("%lf", &amount); Bank_account[i][1] = amount; Bank_account[i][0] = Open; number_account += i; printf("number account: %d", number_account); return; } i++; } printf("The bank is full"); } void BalanceStatus(){ int account_number; printf("enter number account: "); scanf("%d", &account_number); int i = (account_number % 50)-1; if(Bank_account[i][0] == Open){ double balace_status = Bank_account[i][1]; printf("balance_status: %0.2lf", balace_status); }else{ printf("the account is close");} } void Cash_Deposit(){ int account_number; printf("enter number account: "); scanf("%d", &account_number); int i = (account_number % 50)-1; if(Bank_account[i][0] == Open){ double amount; printf("enter how much money to deposit: "); scanf("%lf", &amount); Bank_account[i][1] += amount; printf("balance_status: %0.2lf", Bank_account[i][1]); }else{ printf("the account is close");} } void Cash_Withdrawl(){ int account_number; printf("enter number account: "); scanf("%d", &account_number); int i = (account_number % 50)-1; if(Bank_account[i][0] == Open){ double amount; printf("enter how much money to withdrawl: "); scanf("%lf", &amount); if(Bank_account[i][1] > amount && Bank_account[i][1] > 0){ Bank_account[i][1] -= amount; printf("balance_status: %0.2lf", Bank_account[i][1]); } else{printf("their is no money to withdrawl");} }else{ printf("the account is close");} } void Close_account(){ int account_number; printf("enter number account: "); scanf("%d", &account_number); int i = (account_number % 50)-1; if(Bank_account[i][0] == Open){ Bank_account[i][0] = Close; }else{printf("the bank is already close");} } void Interest(){ int i = 0; double interest_rate; printf("enter number inseret: "); scanf("%lf", &interest_rate); while(i < ROW){ if(Bank_account[i][0] == Open){ Bank_account[i][1] = Bank_account[i][1]*(1 + interest_rate/100); } i++; } } void Printing(){ int account_number = 901; int i = 0; while(i < ROW){ if(Bank_account[i][0] == Open){ printf("\nbalance_status of account number %d is: %0.2lf",account_number, Bank_account[i][1]); } account_number++; i++; } } void Exit(){ int i = 0; while(i < ROW){ if(Bank_account[i][0] == Open){ Bank_account[i][0] = Close; Bank_account[i][1] = Close; } i++; } return; }
C
/*****************************************************************************/ /* Mikko Majamaa */ /*****************/ /* this file contains the code related to reading and handling the data of the name files */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "name_list.h" #define LEN 80 Name *Empty_name_list(Name *pA) { Name *ptr; ptr = pA; while (pA != NULL) { pA = pA->pN; free(ptr); ptr = pA; } return NULL; } void Print_name_list(Name *pA) { Name *ptr; if (pA == NULL) { //empty namelist printf("Nimilista on tyhjä.\n"); return; } else { ptr = pA; while (ptr != NULL) { printf("%s %ld\n", ptr->name, ptr->qty); ptr = ptr->pN; } return; } } Name *Read_name_file(Name *pA) { Name *ptr_new, *ptr; FILE *file; char file_name[LEN]; char line[LEN]; char *p1 = NULL, *p2 = NULL; //pointers for first and second columns char qty_names_str[LEN]; int qty_lines = 0; printf("Anna luettavan tiedoston nimi: "); scanf("%s", file_name); if (pA != NULL) { //namelist is not empty printf("Poistetaan aiemmat tiedot ja luetaan uudet.\n"); pA = Empty_name_list(pA); } printf("Luetaan tiedosto %s.\n", file_name); fflush(stdin); if ((file = fopen(file_name, "r")) == NULL) { //open file perror("Tiedoston avaaminen epäonnistui"); return NULL; } fgets(line, LEN, file); //remove the first line (header line) fflush(stdin); while (fgets(line, LEN, file) != NULL) { qty_lines += 1; if ((ptr_new = (Name*)malloc(sizeof(Name))) == NULL) { //allocate memory perror("Muistin varaus epäonnistui.\n"); } p1 = strtok(line, ";"); p2 = strtok(NULL, "\n"); strcpy(ptr_new->name, p1); strcpy(qty_names_str, p2); ptr_new->qty = atoi(qty_names_str); if (pA == NULL) { //empty list pA = ptr_new; ptr = ptr_new; } else { ptr->pN = ptr_new; //add node to the end of the list ptr = ptr_new; } } fclose(file); printf("Tiedosto %s luettu, %d nimiriviä.\n", file_name, qty_lines); return pA; } /*****************************************************************************/ /* eof */
C
/************************************************************** 1090번 jongtae0509 C 정확한 풀이코드 길이:182 byte(s) 수행 시간:0 ms 메모리 :1120 kb ****************************************************************/ #include<stdio.h> int main() { long long int a,r,n,i; long long int nn; scanf("%lld %lld %lld",&a,&r,&n); nn=n-1; for(i=0;i<nn;i++){ a=a*r; } printf("%lld",a); }
C
/* Sắp xếp chèn : Di chuyển các phần tử có giá trị lớn hơn giá trị key về sau một vị trí so với vị trí ban đầu của nó */ #include<stdio.h> #define MAX 100 void nhap(int a[],int n) { for(int i=0;i<n;i++) { scanf("%d",&a[i]); } } void xuat(int a[],int n) { for(int i=0;i<n;i++) { printf("%4d",a[i]); } printf("\n"); } void sapxep(int a[],int n) { int i,j,k; for(i=1;i<n;i++) { k=a[i]; j=i-1; while(j>=0 && a[j]>k) { a[j+1]=a[j]; j=j-1; } a[j+1]=k; } } int main() { int n=0; scanf("%d",&n); int a[MAX]; nhap(a,n); xuat(a,n); sapxep(a,n); // printf("Day so da sap xep: \n"); xuat(a,n); return 0; }
C
#include "tree.h" #include <string.h> #include <stdio.h> #include <stdlib.h> #include "lmalloc.h" struct tnode *newNode(void) { struct tnode *retnode = 0; retnode = (struct tnode *)lmalloc(sizeof(struct tnode)); // Initialize fields: retnode->dtype = NULL_TYPE; retnode->data = NULL; retnode->lson = NULL; retnode->rson = NULL; // TODO : Initialize remaining fields with null/0 cast to correct type. // Then return the created node return retnode; } void freeNode(struct tnode *node2free) { if (node2free != 0) { // Only free if the value is non-null // TODO : Free child nodes of this node freeNode(node2free->lson); freeNode(node2free->rson); // free contents of data if (node2free->dtype != 0) { lfree (node2free->data); } // TODO : Free the node itself freeNode(node2free); } } // // insertRight - Inserts a node into the right son of another node // parameters - root [tnode *] - Node who's child will be replaced // child [tnode *] - New child node // returns [tnode *] - Pointer to node that was replaced or null // if son was empty. struct tnode *insertRight(struct tnode *root, struct tnode *child) { struct tnode *ret = root->rson; root->rson = child; return ret; } // // insertLeft - Inserts a node into the left son of another node // parameters - root [tnode *] - Node who's child will be replaced // child [tnode *] - New child node // returns [tnode *] - Pointer to node that was replaced or null // if son was empty. // struct tnode *insertLeft(struct tnode *root, struct tnode *child) { struct tnode *ret = root->lson; root->lson = child; return ret; } // // setData - Sets the data type and data pointer in a node // parameters - node [tnode *] - Node which is to be updated // data (void *) - Pointer to node data // dtype (enum datatype) - Type of data being inserted // // returns [null] // void setData(struct tnode *node, void *data2add, enum datatype dtype) { // TODO : Set the dtype and data fields from the parameters passed in node->dtype = dtype; node->data = data2add; } // // encode - Encodes data from a node into a buffer // // void encode(struct tnode *root, char **buffer) { // Process data switch (root->dtype) { case CHAR_TYPE: sprintf(*buffer, "%c", * (char *)root->data); break; case SHORT_TYPE: sprintf(*buffer, "%hi", * (short *)root->data); break; // TODO : encode short field into a character buffer case LONG_TYPE: sprintf(*buffer, "%li", * (long *)root->data); break; // TODO : encode short field into a character buffer case STRING_TYPE: sprintf(*buffer, "%s", (char *)root->data); break; // TODO : encode short field into a character buffer default: break; } } // // walk - Walk a binary tree in the given order, PRE_ORDER, POST_ORDER, // or IN_ORDER. The walk is performed recursively. // // parameters - wt - (enum walktype) - Type of tree walk // root - (struct tnode *) - Root node of tree // buffer - (char **buffer) - String of data from the // nodes of the tree. This is a double pointer so // caller can send in the address of an array. // // returns [void] // void Preorder (struct tnode *root, char **buffer, char *buf){ if(root == NULL) return; encode(root, buffer); strcat(buf, *buffer); Preorder(root->lson, buffer, buf); Preorder(root->rson, buffer, buf); } void Postorder (struct tnode *root, char **buffer, char *buf){ if(root == NULL) return; Postorder(root->lson, buffer, buf); Postorder(root->rson, buffer, buf); encode(root, buffer); strcat(buf, *buffer); } void Inorder (struct tnode *root, char **buffer, char *buf){ if(root == NULL) return; Inorder(root->lson, buffer, buf); encode(root, buffer); strcat(buf, *buffer); Inorder(root->rson, buffer, buf); } void walk(enum walktype wt, struct tnode *root, char **buffer) { // TODO : Use the wt parameter to determine which walk to do. // You may add methods for each of the different types of tree walk. The // processing of the tree must be recursive, NOT iterative. char buf[256]; if (wt == PRE_ORDER){ buf[0] = '\0'; Preorder(root, buffer, buf); } else if(wt == POST_ORDER){ buf[0] = '\0'; Postorder(root, buffer, buf); } else if(wt == IN_ORDER){ buf[0] = '\0'; Inorder(root, buffer, buf); } strcpy(*buffer, buf); }
C
/* * File: x14-1main.c * Application of the module to operate on polygons * The application expects a text file as input, which contains polygons. The * file is of the form: * degree * coefficient1 coefficient2 ... coefficientN */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include "x14-1poly.h" #define MAX (10) #define MAX_DEGREE (1000) /* * Function: cleanUp * Purpose: to get rid of any used memory */ static void cleanUp( Abstract_Polynomial poly[], int size ){ int i; for(i = 0; i < size; i++) destruct_Polynomial( &poly[i] ); } int main(int argc, char * argv[]){ FILE *file; int degree, i; int currentSize = 0; int pos1, pos2; double *val; double tempPoly[ MAX_DEGREE ]; Abstract_Polynomial new, polynomials[ MAX ]; Abstract_Enumeration e; if( argc != 2){ fprintf(stderr, "Usage: program filename\n"); return EXIT_FAILURE; } if( ((file = fopen(argv[1], "r")) == NULL) ){ fprintf(stderr,"could not open the file\n"); return EXIT_FAILURE; } /* now read in the file : create polynomials */ while( 1 ){ /* * format is : #degree newline all coefficients on one line etc */ if( fscanf(file,"%d\n", &degree) != 1){ if( feof( file)) break; fprintf(stderr, "Error reading\n"); cleanUp( polynomials, currentSize ); return EXIT_FAILURE; } if( degree > MAX_DEGREE ){ fprintf(stderr, "max allowable degree is %d, truncating\n", MAX_DEGREE); degree = MAX_DEGREE; } /* read in each coefficient */ for(i = 0; i <= degree; i++){ if( fscanf(file,"%lf\n", &tempPoly[ i ]) != 1){ if( feof( file)) break; fprintf(stderr, "Error reading\n"); cleanUp( polynomials, currentSize ); return EXIT_FAILURE; } } if( (polynomials[ currentSize ] = constructor_Polynomial( degree, tempPoly)) == NULL){ fprintf(stderr, "Error creating polynomial\n"); cleanUp( polynomials, currentSize ); return EXIT_FAILURE; } currentSize ++; if( currentSize > MAX){ fprintf(stderr, "too many polynomials in file, max allowed is %d\n", MAX); break; } if(feof( file )) break; } if( currentSize == 0 ){ /* nothing read */ fprintf(stderr, " empty poly set !\n"); cleanUp( polynomials, currentSize ); return EXIT_FAILURE; } /* now show the polynomials */ for(i = 0; i < currentSize; i++) showPolynomial( polynomials[i] ); /* construct enumeration over first poly */ if( (e = construct_Enumeration( (void *)polynomials[0] )) == NULL){ fprintf(stderr, "enumeration construction failed\n"); cleanUp( polynomials, currentSize ); return EXIT_FAILURE; } while( hasMoreElements_Enumeration( e ) ){ if( (val = (double *)nextElement_Enumeration( e )) == NULL){ fprintf(stderr, "enumeration error\n"); cleanUp( polynomials, currentSize ); return EXIT_FAILURE; } printf("Got %f \t", *val); } printf("\n"); while(1){ printf("Enter the positions of two polynomials (between 0 and %d, (-1 -1) to end ) > ", currentSize - 1); if( scanf("%d%d", &pos1, &pos2) == 2) { if( pos1 == -1 && pos2 == -1) return EXIT_SUCCESS; } else { printf("Incorrect input\n"); break; } while( getchar() != '\n' ) ; if(pos1 < 0 || pos2 < 0 || pos1 >=currentSize || pos2 >=currentSize){ printf("Out of range\n"); continue; } new = AddPolys( polynomials[ pos1 ], polynomials[ pos2 ]); if( !new ){ fprintf(stderr, "addition error\n"); cleanUp( polynomials, currentSize ); return EXIT_FAILURE; } printf("now adding\n"); showPolynomial( new ); printf("now multiplying \n"); destruct_Polynomial( &new ); if((new = MultPolys( polynomials[ pos1 ], polynomials[ pos2 ])) == NULL ) { fprintf(stderr, "addition error\n"); cleanUp( polynomials, currentSize ); return EXIT_FAILURE; } showPolynomial( new ); destruct_Polynomial( &new ); } if(fclose( file ) == EOF) return EXIT_FAILURE; cleanUp(polynomials, currentSize ); return EXIT_SUCCESS; }
C
#include "holberton.h" /** * times_table - check the code for Holberton School students. * * Return: Always 0. */ void times_table(void) { int init = 0, i, j, fd, ld; for (i = 0; i <= 9; i++) { for (j = 0; j <= 9; j++) { if (init < 10) { _putchar(init + '0'); } else { fd = init / 10; ld = init % 10; _putchar(fd + '0'); _putchar(ld + '0'); } init += i; if (j != 9) { _putchar(','); _putchar(' '); if (init < 10) { _putchar(' '); } } } _putchar('\n'); init = 0; } }
C
#ifndef MATRIX_METHODS_H_INCLUDED #define MATRIX_METHODS_H_INCLUDED void invert_matrix(double mat[3][3],double M[3][3]); /** *@fn void invert_matrix (double mat[3][3],double M[3][3]); *Invert a 3x3 matrix. *@param[in] mat: The matrix. *@param[in/out] Yb: The inverted matrix. */ void matrix_product(double MG[3][3],double MD[3][1], double MR[3][1]); /** *@fn void matrix_product (double MG[3][3],double MD[3][1], double MR[3][1]); *Calculate the product of a 3x3 matrix with a 3x1 matrix. *@param[in] MG: The 3x3 matrix. *@param[in] MD: The 3x1 matrix. *@param[in/out] MR: The new 3x1 matrix calculated. */ void matrix_translation(double T[3][1],double S[3][1],double St[3][1]); /** *@fn void matrix_translation (double T[3][1],double S[3][1],double St[3][1]); *Calculate the translation of a matrix 3x1 by a vector 3x1. *@param[in] T: The translation vector. *@param[in] S: The matrix 3x1. *@param[in/out] St: The new 3x1 matrix translated. */ #endif // MATRIX_METHODS_H_INCLUDED
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_split.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: smurad <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/12/15 20:20:39 by smurad #+# #+# */ /* Updated: 2019/12/18 08:04:53 by smurad ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static int strcount(char const *s, char c) { int i; int j; int scount; scount = 0; j = 0; i = 0; while (s[j]) { while (s[j] == c && s[j]) { i = 0; j++; } while (s[j] != c && s[j]) { i++; j++; } if (i != 0) scount++; } return (scount); } char **ft_split(char const *s, char c) { char **res; int istart; int ilen; int i; i = 0; ilen = 0; istart = 0; if (!s || !(res = malloc(sizeof(char *) * (strcount(s, c) + 1)))) return (NULL); while (s[istart]) { while (s[istart] == c && s[istart + ilen]) istart++; while (s[istart + ilen] != c && s[istart + ilen]) ilen++; if (ilen != 0) { res[i++] = ft_substr(s, istart, ilen); istart = istart + ilen; ilen = 0; } } res[i] = NULL; return (res); }
C
#include "lista_LSE.h" int main(void) { char *vetor_INPUT[] = {"joao do pulo", "pedro bandeira", "anita garibaldi", "maria luiza"}; int Q = 4; system("clear"); printf("\n VETOR %d elementos\n", Q); /** cria um PONTEIRO PARA UMA lista **/ NOH_tipo_LSE * L; L = NULL; // aqui sim eh necessario ... VAZIA printf("ENDERECOS de L: %p : &L %p" , L , &L ); printf("\n Compto de Lista: %d NOSH", comprimento_lista(&L) ); // APLICACAO 1 for(int i=0; i < Q; i++ ) { //printf("\n => %d : %d : %s", i, ins_fim_lista( vetor_INPUT[i] , &L ), vetor_INPUT[i] ); ins_fim_lista_2( vetor_INPUT[i] , &L ); // printf("\n ...inserindo...: %d: %s" , i, vetor_INPUT[i]); }; printf("\n Compto de Lista: %d NOSH", comprimento_lista(&L) ); // APLICACAO 2 for(int i=0; i < Q; i++ ) { ins_inic_lista(vetor_INPUT[i] , &L ); }; // PARA FINS DE TESTES .... imp_lista( L ); printf("\n Compto de Lista: %d NOSH", comprimento_lista(&L) ); printf("\n Recursivo 1 Compto de Lista: %d NOSH", recurs_comp_lista_1( L )); printf("\n Recursivo 2 Compto de Lista: %d NOSH", recurs_comp_lista_2( &L )); /* if( exclui_n_esimo_lista( 4 , &L ) ) printf("\nExclusao com sucesso" ); else printf("\nExclusao com INsucesso" ); if( exclui_n_esimo_lista( 1 , &L ) ) printf("\nExclusao com sucesso" ); else printf("\nExclusao com INsucesso" ); if( exclui_n_esimo_lista( 4 , &L ) ) printf("\nExclusao com sucesso" ); else printf("\nExclusao com INsucesso" ); if( exclui_n_esimo_lista( 44 , &L ) ) printf("\nExclusao com sucesso" ); else printf("\nExclusao com INsucesso em 44" ); if( exclui_n_esimo_lista( 0 , &L ) ) printf("\nExclusao com sucesso" ); else printf("\nExclusao com INsucesso em 0" ); if( inclui_n_esima_lista( 2 , "inclui 2a posicao da lista", &L )) printf("\n INCLUSAO 2a posicao com sucesso" ); else printf("\nINCLUSAO com INsucesso" ); if( inclui_n_esima_lista( 1 , "inclui 1a posicao da lista", &L )) printf("\n INCLUSAO 1a posicao com sucesso" ); else printf("\nINCLUSAO com INsucesso" ); imp_lista( L ); if( exclui_o_ultimo_lista( &L ) ) printf("\nExclusao do ultimo sucesso" ); else printf("\nExclusao com INsucesso ULTIMO" ); //printf("fim: %p %p\n", L->next, ancora->next ); imp_lista( L ); */ // falta destruir lista destroi_lista( &L ); puts("\n... SUCESSO..."); return 1; }
C
#include <stdio.h> #include <stdlib.h> #include <limits.h> #include <assert.h> #include "dump-bits.h" unsigned get_clear_mask(int p, int n) { return (~(~0 << n)) << p; } /* Exercise 2-6. Write a function setbits(x,p,n.y) that returns x ith the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged. */ unsigned setbits(unsigned x, int p, int n, unsigned y) { unsigned y_mask; y_mask = (y & get_clear_mask(0, n)) << (p - n + 1); // first set our target section of x to all zeros, // then 'or' with our mask return (x & ~get_clear_mask(p - n + 1, n)) | y_mask; } void test_setbits(unsigned x, int y, int p, int n, unsigned expected_result) { unsigned result = setbits(x, p, n, y); printf("\nResults:\n\n"); printf("\t%-15s", "Expected:"); dump_bits(expected_result); printf("\t%-15s", "Actual:"); dump_bits(result); assert(result == expected_result); } /* Exercise 2-7. Write a function invert(x,p,n) that returns x with the n bits that begin at position p inverted (i.e., 1 changed into 0 and vice versa), leaving the others untouched. */ unsigned invert(unsigned x, int p, int n) { unsigned inverted_mask = (~x & get_clear_mask(p - n + 1, n)); return (x & ~get_clear_mask(p - n + 1, n)) | inverted_mask; } void test_invert(unsigned x, int p, int n, unsigned expected_result) { unsigned result = invert(x, p, n); printf("\nResults:\n\n"); printf("\t%-15s", "Expected:"); dump_bits(expected_result); printf("\t%-15s", "Actual:"); dump_bits(result); assert(result == expected_result); } /* Exercise 2-8. Write a function rightrot(x,n) that returns the value of the integer rotated to the right by n bit positions. */ //hacky... int count_bits() { int x = 1; int count = 1; while(x > 0) { x <<= 1; count++; } return count; } int rightrot(int x, int n) { static int number_of_bits_to_carry = 0; int carry; unsigned result = x; if (number_of_bits_to_carry == 0) { number_of_bits_to_carry = count_bits() - 1; } for(int i = 0; i < n; i++) { carry = (result & 1) << number_of_bits_to_carry; result = (result >> 1) | carry; } return result; } void test_rightrot(int x, int n, int expected_result) { int result = rightrot(x, n); printf("\nResults:\n\n"); printf("\t%-15s", "Expected:"); dump_bits(expected_result); printf("\t%-15s", "Actual:"); dump_bits(result); printf("\n"); assert(result == expected_result); } int main() { /* printf("%ld\n", strtol("11100000000000000000000000000001", NULL, 2)); */ /* test_setbits(87, 458, 7, 4, 167); */ /* test_setbits(144, 7, 5, 3, 184); */ /* test_invert(170, 5, 4, 150); */ /* test_invert(65280, 13, 2, 52992); */ test_rightrot(strtol("00000000000000000000000000001111", NULL, 2), 3, strtol("11100000000000000000000000000001", NULL, 2)); test_rightrot(strtol("01000000000000000000000000001010", NULL, 2), 5, strtol("01010010000000000000000000000000", NULL, 2)); test_rightrot(strtol("00000000000000000000000010000000", NULL, 2), 1, strtol("00000000000000000000000001000000", NULL, 2)); }
C
#include <stdio.h> #include <stdlib.h> /* array= arreglo de datos ORDENADO. vARIABLE QUE TIENE un conjunto de variables en su interior (ordenadas) definicion int c; | int NOSE[5]; c=28 escribo la variable; | NOSE [3] posicin 4 (porque empieza de cero). Toma el valor que hay ah k=c lectura | k = NOSE [3] leo en k el valor del array en la posicin 3 tipo nombre [cantidad de elementos]. El tamao es fijo, no crece ni se achica (durante la ejecucin del cdigo) // Programa que pida 5 numeros al usuario y calcule el promedio; pero con array. 1) pedir numeros y guardar 2) recorrer el array y promediar. */ #define SIZE_ARRAY 6 // ESTO LO DEFINO PORQUE SI CAMBIO EL VALOR, AUTOMATICAMENTE ME LO CAMBIA ABAJO SIN TENER QUE CAMBIARLO CADA VEZ int main() { int numero[SIZE_ARRAY]; float promedio; int i; int suma=0; for(i=0; i<SIZE_ARRAY;i++) // este ciclo guarda los valores a ingresar en el vector. { printf("Ingrese un numero \n"); scanf("%d",&numero[i]); } for (i=0;i<SIZE_ARRAY;i++) // este ciclo, recorre el vector y suma cada uno de los nmeros ingresados en c/ posicin { suma= suma+numero[i]; } promedio= (float) suma/SIZE_ARRAY; // finalmente calculo el promedio. printf("El promedio es %.2f", promedio); return 0; }
C
#include <stdio.h> #include <string.h> #include "CuTest.h" #include "../src/hashtable.h" #include "../src/scope.h" void test_create_scope(CuTest *tc) { CuAssertIntEquals(tc, 0, scope_numbers()); scope_new(); CuAssertIntEquals(tc, 1, scope_numbers()); scope_reset(); } void test_reset_should_have_no_scope(CuTest *tc) { scope_new(); CuAssertIntEquals(tc, 1, scope_numbers()); scope_reset(); CuAssertIntEquals(tc, 0, scope_numbers()); scope_reset(); } void test_insert_and_retrieve_entry_to_scope(CuTest *tc) { scope_new(); scope_sym_table_insert("a", "A", NULL); CuAssertPtrNotNull(tc, scope_search_identifier("a")); scope_reset(); } void test_do_not_find_entry_scope(CuTest *tc) { scope_new(); CuAssertIntEquals(tc, 1, scope_numbers()); CuAssertFalse(tc, is_identifier_declared("a")); CuAssertPtrNull(tc, scope_search_identifier("a")); scope_reset(); } void test_search_on_parent_scope(CuTest *tc) { /* parent */ scope_new(); scope_sym_table_insert("a", "A", NULL); /* new scope */ scope_new(); CuAssertIntEquals(tc, 2, scope_numbers()); CuAssertPtrNotNull(tc, scope_search_identifier("a")); scope_reset(); }
C
/*====================================================================* * * void _setbuf(FILE *fp, char *buffer); * * _stdio.h * * assign a special buffer to the file control block addressed by the * FILE pointer argument; if the buffer argument is NULL then assign a * one-byte buffer; * * a custom buffer may be assigned after the file is opened but before * i/o is performed; if no buffer is assigned then subsequent i/o will * be buffered as dictated by the default i/o library implementation; * * For example, a stream May be set to 'buffered' I/O with: * * _setbuf(fp,malloc(_BUFSIZE)); * * or set to 'unbuffered' I/O with: * * _setbuf(fp, NULL); * *. Motley Tools by Charles Maier *: Published 1982-2005 by Charles Maier for personal use *; Licensed under the Internet Software Consortium License * *--------------------------------------------------------------------*/ #include "_stdio.h" void _setbuf (register FILE *fp, char *buffer) { extern char _unbuf []; if ((fp != NULL) && ((fp->_flag & (_IOREAD|_IOWRITE)) != 0) && ((fp->_flag & (_IOERR|_IOEOF)) == 0)) { if ((fp->_flag & (_IOALLOC)) != 0) free (fp->_base); fp->_flag &= ~(_IOUNBUF|_IOALLOC); if (buffer != NULL) { fp->_ptr = fp->_base = buffer; fp->_cnt = ((fp->_flag & (_IOREAD)) != 0)? (0):(_BUFSIZE); fp->_flag |= (_IOALLOC); } else { fp->_ptr = fp->_base = &_unbuf [fp->_file]; fp->_cnt = ((fp->_flag & (_IOREAD)) != 0)? (0):(1); fp->_flag |= (_IOUNBUF); } } return; }
C
#include <obj/obj.h> #include <obj/stb_zlib.h> implement(Data) Data Data_with_bytes(Class cl, uint8 *bytes, uint length) { Data self = auto(Data); self->bytes = bytes; self->length = length; return self; } Data Data_with_size(uint length) { Data self = auto(Data); self->bytes = (uint8 *)malloc(length); self->length = length; return self; } void Data_get_vector(Data self, void **buf, size_t type_size, uint *count) { *buf = (void *)self->bytes; *count = self->length / type_size; } void Data_free_data(Data self, void *ptr) { free(ptr); } void *Data_alloc_data(Data self, size_t size) { return malloc(size); } String Data_base64_encode(Class cl, uint8 *input, int length, int primitive_size, bool compress) { const uint8 *b64 = (const uint8 *)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const uint8 pad = '='; String str = auto(String); int clength = 0; uint8 *cbytes = stbi_zlib_compress(input, length, &clength, 0); if (!cbytes) return NULL; int divis = clength / 3 * 3; if (compress) call(str, concat_char, '^'); for (int x = 0; x < divis; x += 3) { uint8 b0 = cbytes[x], b1 = cbytes[x + 1], b2 = cbytes[x + 2]; uint8 buf[4]; buf[0] = b64[b0 >> 2]; buf[1] = b64[((b0 & 0x03) << 4) | ((b1 & 0xF0) >> 4)]; buf[2] = b64[((b1 & 0x0F) << 2) | (b2 >> 6)]; buf[3] = b64[b2 & 0x3F]; call(str, concat_chars, (const char *)buf, 4); } int remaining = clength - divis; if (remaining > 0) { uint8 buf[4]; uint8 b0 = cbytes[divis]; if (remaining == 2) { uint8 b1 = cbytes[divis + 1]; buf[0] = b64[b0 >> 2]; buf[1] = b64[((b0 & 0x03) << 4) | ((b1 & 0xF0) >> 4)]; buf[2] = b64[((b1 & 0x0F) << 2)]; buf[3] = pad; } else { buf[0] = b64[b0 >> 2]; buf[1] = b64[((b0 & 0x03) << 4)]; buf[2] = pad; buf[3] = pad; } call(str, concat_chars, (const char *)buf, 4); } return str; } String Data_to_string(Data self) { return class_call(Data, base64_encode, self->bytes, self->length, 1, true); } uint8 *Data_base64_decode(Class cl, const char *input, int input_len, int *output_len, int primitive_size) { bool compressed = false; int input_len_ = input_len; class_Data dcl = (class_Data)cl; if (input && input[0] == '^') { input_len--; input++; compressed = true; } if (!input || input_len % 4) return NULL; size_t alloc_len = (size_t)input_len / 4 * 3; uint8 *cbytes = dcl->alloc_data(NULL, alloc_len); int cursor = 0; int pfound = 0; const static int16 map[] = { -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, // 40 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, // 50 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, // 60 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 70 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 80 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, // 90 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // 100 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, // 110 49, 50, 51, -1, -1, -1, -1, -1, -1, -1 // 120 }; for (int i = 0; i < input_len; i += 4) { uint8 x[4]; for (int ii = 0; ii < 4; ii++) { uint8 b = input[i + ii]; if (b < 40 || b >= 130) return NULL; int16 v; if (b == '=') { v = 0; pfound++; } else { v = map[b - 40]; if (v == -1) return NULL; } x[ii] = (uint8)v; } uint8 bytes[3]; bytes[0] = (x[0] << 2) | (x[1] >> 4); bytes[1] = ((x[1] & 0xF) << 4) | (x[2] >> 2); bytes[2] = (x[2] << 6) | (x[3] & 0x3F); memcpy(&cbytes[cursor], bytes, 3); cursor += 3; } int pad = 0; int clength = alloc_len; if (input_len >= 4) { if (input[input_len - 1] == '=') { pad++; if (input[input_len - 2] == '=') pad++; } clength -= pad; } uint8 *output; if (compressed) { void *output_decoded = (uint8 *)stbi_zlib_decode_malloc((const char *)cbytes, clength, output_len); dcl->free_data(NULL, cbytes); if (dcl->alloc_data != Data_alloc_data) { output = dcl->alloc_data(NULL, (size_t)*output_len); memcpy(output, output_decoded, (size_t)*output_len); free(output_decoded); } else output = output_decoded; } else { output = (uint8 *)cbytes; *output_len = clength; } if (!output || pfound != pad) return NULL; return output; } Data Data_from_string(Class cl, String value) { if (!value || value->length % 4) return NULL; Data self = (Data)autorelease(new_obj((class_Base)cl, 0)); class_Data data_class = (class_Data)cl; self->bytes = data_class->base64_decode(cl, value->buffer, value->length, &self->length, 1); return self->bytes ? self : NULL; } void Data_free(Data self) { call(self, free_data, self->bytes); }
C
#include <stdio.h> #include <stdlib.h> #include "sins_types.h" #include "sins_const.h" #include "box.h" #include "primitives.h" #include "primitives_utils.h" #include "gc.h" #include "bytefield.h" #include "bytefield_utils.h" char *line = "======================================================================================\n"; int main(void) { __initHeap(_A_(0)); __VAR__ p1; p1 = allocVar(); printf(line); printf("Only 1 boxint var. Heap should be empty before and after gc:\n"); setVar(p1, __boxint(_A_(1), 42)); dumpByteField(getHeap()); gc_run(getHeap(), getNewHeap()); dumpByteField(getHeap()); printf(line); printf(line); printf("Only 1 boxpair var. Heap should contain the pair before and after gc:\n"); setVar(p1, __cons(_A_(2), __boxint(_A_(1), 3), __boxint(_A_(1), 4))); dumpByteField(getHeap()); gc_run(getHeap(), getNewHeap()); dumpByteField(getHeap()); printf(line); printf(line); printf("Only 1 boxpair var but 2 more pairs created. Heap should contain 3 pairs before and 1 after gc:\n"); setVar(p1, __cons(_A_(2), __boxint(_A_(1), 5), __boxint(_A_(1), 6))); setVar(p1, __cons(_A_(2), __boxint(_A_(1), 7), __boxint(_A_(1), 8))); dumpByteField(getHeap()); gc_run(getHeap(), getNewHeap()); dumpByteField(getHeap()); printf(line); printf(line); printf("2 more boxpair vars, 3 new pairs created. Heap should contain 4 pairs before and 3 after gc:\n"); __VAR__ p2, p3; p2 = allocVar(); p3 = allocVar(); setVar(p1, __cons(_A_(2), __boxint(_A_(1), 3), __boxint(_A_(1), 4))); setVar(p2, __cons(_A_(2), __boxint(_A_(1), 5), __boxint(_A_(1), 6))); setVar(p3, __cons(_A_(2), __boxint(_A_(1), 7), __boxint(_A_(1), 8))); dumpByteField(getHeap()); gc_run(getHeap(), getNewHeap()); dumpByteField(getHeap()); printf(line); printf(line); printf("3 vars. p1 == pair; p2 == vector; p3 == string. Heap should contain 5 pairs before and 3 after gc:\n"); setVar(p3, __createString("**Variable p3**")); setVar(p2, __createVector(_A_(1), __boxint(_A_(1), 12))); dumpByteField(getHeap()); gc_run(getHeap(), getNewHeap()); dumpByteField(getHeap()); printf(line); printf(line); printf("Set 3 vars to null. Heap should have 3 objects before and 0 after\n"); setVar(p1, __NULL__); setVar(p2, __NULL__); setVar(p3, __NULL__); dumpByteField(getHeap()); gc_run(getHeap(), getNewHeap()); dumpByteField(getHeap()); printf(line); printf(line); printf("p1 <= vector(3)\n"); printf("p1[0] <= string('Allo')\n"); printf("p2 <= cons(10, 11)\n"); printf("p1[1] <= p2\n"); printf("p2 <= cons(5, 6)\n"); printf("p3 <= vector(5)\n"); setVar(p1, __createVector(_A_(1), __boxint(_A_(1), 3))); __vectorSet(_A_(2), getVar(p1), __boxint(_A_(1), 0), __createString("Allo")); setVar(p2, __cons(_A_(2), __boxint(_A_(1), 10), __boxint(_A_(1), 11))); __vectorSet(_A_(2), getVar(p1), __boxint(_A_(1), 1), getVar(p2)); setVar(p2, __cons(_A_(2), __boxint(_A_(1), 5), __boxint(_A_(1), 6))); setVar(p3, __createVector(_A_(1), __boxint(_A_(1), 5))); dumpByteField(getHeap()); gc_run(getHeap(), getNewHeap()); dumpByteField(getHeap()); printf(line); freeByteField(getHeap()); return __SUCCESS__; }
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 find(int decimal_number,int base) { if (decimal_number == 0) return 0; else return (decimal_number % base + 10 * find(decimal_number / base,base)); } // Driver code int main() { int decimal_number; int base; printf("Entre le numero decimal : "); scanf("%d",&decimal_number); printf("Entre la base : "); scanf("%d",&base); printf("%d", find(decimal_number,base)); return 0; }
C
#include <stdio.h> int main(void) { long long int s=0,i,n,j; scanf("%lld",&n); long long int arr[n],t; for(i=0;i<n;i++) scanf("%lld ",&arr[i]); for(i=0;i<n;i++){ for(j=i+1;j<n;j++){ if(arr[i]<arr[j]){ t=arr[i]; arr[i]=arr[j]; arr[j]=t;}}} for(i=0;i<n;i++){ s=s*10+arr[i]; } printf("%lld",s); return 0; }
C
#include<stdio.h> #include<math.h> #include<stdlib.h> #define f(x) (1/(1+(x*x))) void trapezoidal(void); void simpson(void); int main() { int c,count=0; float s=0.0,s1=0.0; while(1) { if(count==0){ printf("\t\t\tWelcome to Integrator:"); printf("\n\t\t\tPlease Select from the following methods:");} printf("\n\n \t\t\t\tMethod 1:Trapezoidal Rule:\n\t\t\t\tMethod 2:Simpson's 1/3rd Rule:\n\t\t\t\tPress 3 to Exit Integrator"); printf("\n\t\t\t\t--------------------------------------------- "); printf("\n\n Enter Your Choice:\t"); scanf("%d",&c); switch(c) { case 1: trapezoidal();break; case 2: simpson(); break; case 3: exit(0); default: printf("\n Your Choice is Invalid."); break; } count++; } } void trapezoidal() { float a,b,h,s=0.0,y[100]; int i,c,n; printf("\n Please Enter The Number Of Intervals:"); scanf("%d",&n); printf("\n Enter the value of a:"); scanf("%f",&a); printf("\n Enter the value of b:"); scanf("%f",&b); printf("\n Enter the value of h:"); h=((b-a)/n); printf("%f",h); printf("\n \tx \tf(x)"); for(i=0;i<=n;i++) { y[i]=f(a+(i*h)); printf("\n %f \t %f",(a+i*h),y[i]); } for(i=1;i<n;i++) { s=s+y[i]; } s=((y[0]+y[n])+2*s); s=s*(h/2); printf("\n %f",s); } void simpson(){ float a,b,h,s=0.0,s1=0.0,y[100]; int i,c,n; printf("\n Please Enter The Number Of Intervals:"); scanf("%d",&n); printf("\n Enter the value of a:"); scanf("%f",&a); printf("\n Enter the value of b:"); scanf("%f",&b); printf("\n Enter the value of h:"); h=((b-a)/n); printf("%f",h); printf("\n \tx \tf(x)"); for(i=0;i<=n;i++) { y[i]=f(a+(i*h)); printf("\n %f \t %f",a+i*h,y[i]); } for(i=1;i<n;i++) { if(i%2==0) s=s+2*y[i]; else { s1=s1+4*y[i]; } } s=((y[0]+y[n])+s+s1); s=s*(h/2); printf("\n %f",s); }
C
#include "test.h" #include "matching.h" char *utest_matching_match_offset() { Label l1 = label_full("test"); Label l2 = label_full("abctest"); Label l3 = label_full("te"); Label l4 = label_full("abctestabc"); Matching m0 = match(l1, l2); mu_assert("No offset #1", match_type(m0) == NONE); l2->i += 3; Matching m1 = match(l1, l2); mu_assert("offset #1", match_type(m1) == EXACT); Matching m2 = match(l3, l2); mu_assert("offset #2", match_type(m2) == PARTIAL_RIGHT); l4->j -= 3; l4->i += 3; Matching m3 = match(l4, l1); mu_assert("offset #3", match_type(m3) == EXACT); const char *text = "abcab"; l1 = label(text, 0, 5); // abcab l2 = label(text, 0, 2); // ab Matching m4 = match(l1, l2); mu_assert("Offset #4", match_type(m4) == PARTIAL_LEFT); m4 = match(l2, l1); mu_assert("Offset #5", match_type(m4) == PARTIAL_RIGHT); return NULL; } char *utest_matching_match() { Matching m0 = match(label_full("xest"), label_full("test")); mu_assert("No match #1", match_type(m0) == NONE); Matching m = match(label_full("test"), label_full("xest")); mu_assert("No match #2", match_type(m) == NONE); Matching m2 = match(label_full("xest"), label_full("xest")); mu_assert("Exact match 1", m2.n == 4); mu_assert("Exact match 2", m2.l == 0); mu_assert("Exact match 3", m2.r == 0); mu_assert("Exact match 4", match_type(m2) == EXACT); Matching m3 = match(label_full("xest"), label_full("xester")); mu_assert("Partial match l #1", m3.n == 4); mu_assert("Partial match l #2", m3.l == 0); mu_assert("Partial match l #3", m3.r == 2); mu_assert("Partial match l #4", match_type(m3) == PARTIAL_RIGHT); Matching m4 = match(label_full("xester"), label_full("xest")); mu_assert("Partial match l #5", m4.n == 4); mu_assert("Partial match l #6", m4.r == 0); mu_assert("Partial match l #7", m4.l == 2); mu_assert("Partial match l #8", match_type(m4) == PARTIAL_LEFT); Matching m5 = match(label_full("a"), label_full("abaa")); mu_assert("Match", m5.n == 1); Matching m6 = match(label_full("he"), label_full("")); Matching m7 = match(label_full(""), label_full("he")); mu_assert("Partial match #9", match_type(m6) == PARTIAL_LEFT); mu_assert("Partial match #10", match_type(m7) == PARTIAL_RIGHT); // Considered partial l. Not a situation that occurs in the algorithm Matching m8 = match(label_full("abcde"), label_full("abcxx")); mu_assert("Partial match #11", match_type(m8) == PARTIAL_LEFT); return NULL; } char *test_matching() { mu_run_utest(utest_matching_match); mu_run_utest(utest_matching_match_offset); return NULL; }
C
/************************** * Jordan Simmons 10743844 * 3600.001 Group 3 * Reverse *************************/ #include "major1.h" void reverse(unsigned int num) { int temp = num; unsigned int reverse_num = (num & 1); unsigned int count = 31; char binary[32]; printf("\nThe number is: %u\n", num); for (int i = 1; i <= 32; i++) { if (temp % 2) { binary[32 - i] = '1'; } else { binary[32 - i] = '0'; } temp /= 2; } printf("The binary representation is: %s\n", binary); temp = num; temp >>= 1; while(temp) { // true while temp contains at least one TRUE bit (1) reverse_num <<= 1; // left shift stored bits // add on right most bit based on temp's right most bit reverse_num |= (temp & 1); temp >>= 1; // right shift temp count--; // increment count } reverse_num <<= count; // shift number of digits skipped as rest were 0's printf("\nThe reversed number is: %u\n", reverse_num); for (int i = 1; i <= 32; i++) { if (reverse_num % 2) { binary[32 - i] = '1'; } else { binary[32 - i] = '0'; } reverse_num /= 2; } printf("The binary representation is: %s\n\n", binary); }
C
int copia_string(char dest[], char fonte[]) { // Recebe: o endereco da string dest e o endereco da string fonte. // Retorna: a quantidade de caracteres copiados de fonte para dest. int i; for (i = 0; dest[i] != '\0'; i++) { dest[i] = fonte[i]; } return i; }
C
#include <stdio.h> void forEachForString(char *str, void (*f)(char *)); void changeMe(char *character) { int ascii = *character; int diff = 32; if (ascii >= 97) printf("%c\n", *character - diff); else printf("%c\n", *character + diff); } int main() { char *mystr = "asdf"; forEachForString(mystr, changeMe); } void forEachForString(char *str, void (*f)(char *)) { int i = 0; while (str[i] != '\0') { f(&str[i]); ++i; } }
C
/* $Id: transforms.c,v 1.1 2006/11/22 20:31:50 observe Exp $ */ #ifndef lint static char vcid[] = "$Id: transforms.c,v 1.1 2006/11/22 20:31:50 observe Exp $"; #endif /* lint */ /*********** Coordinate transformation routines *************/ /* All angles assumed to be in radians upon input */ #include "orbfit.h" /* First takes RA,DEC in equatorial to ecliptic */ void eq_to_ec( double ra_eq, double dec_eq, double *lat_ec, double *lon_ec, double **partials) { double sd,cd,cr,se,ce,y,x; se = sin(ECL); ce = cos(ECL); sd = ce * sin(dec_eq) - se * cos(dec_eq)*sin(ra_eq); *lat_ec = asin(sd); y = ce*cos(dec_eq)*sin(ra_eq) + se*sin(dec_eq); x = cos(dec_eq)*cos(ra_eq); *lon_ec = atan2(y,x); if (partials!=NULL) { cd = sqrt(1.-sd*sd); /* form Jacobian matrix (assume not at pole)*/ partials[1][1] = -se*cos(dec_eq)*cos(ra_eq)/cd; partials[1][2] = (ce*cos(dec_eq)+se*sin(dec_eq)*sin(ra_eq)) / cd; partials[2][1] = cos(dec_eq)*partials[1][2] / cd; partials[2][2] = se*cos(ra_eq) / (cd*cd); } return; } /* And transform x,y,z from eq to ecliptic */ void xyz_eq_to_ec(double x_eq, double y_eq, double z_eq, double *x_ec, double *y_ec, double *z_ec, double **partials) { double se,ce; se = sin(ECL); ce = cos(ECL); *x_ec = x_eq; *y_ec = ce*y_eq + se*z_eq; *z_ec = -se*y_eq + ce*z_eq; if (partials!=NULL) { partials[1][1] = 1.; partials[1][2] = partials[1][3] = partials[2][1] = partials[3][1] = 0.; partials[2][2] = partials[3][3] = ce; partials[2][3] = se; partials[3][2] = -se; } return; } /**To reverse above, just flip sign of ECL effectively: ***/ void ec_to_eq( double lat_ec, double lon_ec, double *ra_eq, double *dec_eq, double **partials) { double sd,cd,cr,se,ce,y,x; se = sin(-ECL); ce = cos(ECL); sd = ce * sin(lat_ec) - se * cos(lat_ec)*sin(lon_ec); *dec_eq = asin(sd); y = ce*cos(lat_ec)*sin(lon_ec) + se*sin(lat_ec); x = cos(lat_ec)*cos(lon_ec); *ra_eq = atan2(y,x); if (partials!=NULL) { cd = sqrt(1.-sd*sd); /* form Jacobian matrix (assume not at pole)*/ partials[2][2] = -se*cos(lat_ec)*cos(lon_ec)/cd; partials[2][1] = (ce*cos(lat_ec)+se*sin(lat_ec)*sin(lon_ec)) / cd; partials[1][2] = cos(lat_ec)*partials[2][1] / cd; partials[1][1] = se*cos(lon_ec) / (cd*cd); } return; } /* And transform x,y,z from ecliptic to eq */ void xyz_ec_to_eq(double x_ec, double y_ec, double z_ec, double *x_eq, double *y_eq, double *z_eq, double **partials) { double se,ce; se = sin(-ECL); ce = cos(ECL); *x_eq = x_ec; *y_eq = ce*y_ec + se*z_ec; *z_eq = -se*y_ec + ce*z_ec; if (partials!=NULL) { partials[1][1] = 1.; partials[1][2] = partials[1][3] = partials[2][1] = partials[3][1] = 0.; partials[2][2] = partials[3][3] = ce; partials[2][3] = se; partials[3][2] = -se; } return; } /*** Go between ecliptic coords & tangent-plane system at *** lat0, lon0 aligned with ecliptic. keep the center *** of projection as static variables to update as needed ****/ double old_lat0=-999., old_lon0, clat0, slat0, clon0, slon0; void check_latlon0(double lat0, double lon0) { if (lat0 == old_lat0 && lon0==old_lon0) return; old_lat0 = lat0; old_lon0 = lon0; clat0 = cos(lat0); slat0 = sin(lat0); clon0 = cos(lon0); slon0 = sin(lon0); return; } /* first routine goes from ecliptic lat/lon to projected x/y angles*/ void ec_to_proj(double lat_ec, double lon_ec, double *x_proj, double *y_proj, double lat0, double lon0, double **partials) { double clat,slat,cdlon,sdlon; double xp, yp, zp; check_latlon0(lat0,lon0); cdlon = cos(lon_ec - lon0); sdlon = sin(lon_ec - lon0); clat = cos(lat_ec); slat = sin(lat_ec); xp = clat * sdlon; yp = clat0*slat - slat0*clat*cdlon; zp = slat0*slat + clat0*clat*cdlon; /* Go from cartesian to tangent-plane coords; don't worry here * about zp=0 which occurs 90 degrees from tangent point. */ *x_proj = xp/zp; *y_proj = yp/zp; /* take the small-angle approximation for the partial deriv. * matrix, which should be good enough for anything within a * few degrees of the projection point. */ if (partials!=NULL) { partials[1][2] = clat; partials[1][1] = partials[2][2] = 0.; partials[1][2] = 1.; } return; } /** Now the inverse, from projected xy to ecliptic lat/lon **/ void proj_to_ec(double x_proj, double y_proj, double *lat_ec, double *lon_ec, double lat0, double lon0, double **partials) { double zp; check_latlon0(lat0,lon0); zp = 1./sqrt(1 + x_proj*x_proj + y_proj*y_proj); *lat_ec = asin( zp* (slat0 + y_proj*clat0) ); *lon_ec = lon0 + asin( x_proj * zp / cos(*lat_ec) ); /* take the small-angle approximation for the partial deriv. * matrix, which should be good enough for anything within a * few degrees of the projection point. */ if (partials!=NULL) { partials[2][1] = 1./cos(*lat_ec); partials[1][1] = partials[2][2] = 0.; partials[1][2] = 1.; } return; } /** Next go from x,y,z in ecliptic orientation to x,y,z in tangent-point * orientiation. */ void xyz_ec_to_proj( double x_ec, double y_ec, double z_ec, double *x_p, double *y_p, double *z_p, double lat0, double lon0, double **partials) { check_latlon0(lat0,lon0); *x_p = -slon0 * x_ec + clon0 * y_ec; *y_p = -clon0*slat0*x_ec -slon0*slat0*y_ec +clat0*z_ec; *z_p = clon0*clat0*x_ec +slon0*clat0*y_ec +slat0*z_ec; if (partials!=NULL) { partials[1][1] = -slon0; partials[1][2] = clon0; partials[1][3] = 0.; partials[2][1] = -clon0*slat0; partials[2][2] = -slon0*slat0; partials[2][3] = clat0; partials[3][1] = clon0*clat0; partials[3][2] = slon0*clat0; partials[3][3] = slat0; } return; } /** And finally from tangent x,y,z to ecliptic x,y,z */ void xyz_proj_to_ec( double x_p, double y_p, double z_p, double *x_ec, double *y_ec, double *z_ec, double lat0, double lon0, double **partials) { check_latlon0(lat0,lon0); *x_ec =-slon0 *x_p -clon0*slat0*y_p +clon0*clat0*z_p; *y_ec = clon0 *x_p -slon0*slat0*y_p +slon0*clat0*z_p; *z_ec = clat0 * y_p +slat0 * z_p; if (partials!=NULL) { partials[1][1] =-slon0; partials[1][2] =-clon0*slat0; partials[1][3] = clon0*clat0; partials[2][1] = clon0; partials[2][2] =-slon0*slat0; partials[2][3] = slon0*clat0; partials[3][1] = 0.; partials[3][2] = clat0; partials[3][3] = slat0; } return; } void orbitElements(XVBASIS *xv, ORBIT *orb) { int i,j,k; double combinedMass; /* mass of Sun + mass of KBO */ double epochTime; /* We note that the origin of the inertial rectangular co-ordinate system is itself a dynamical center - the Sun. The co-ordinate system is aligned so that +x-axis points towards the vernal equinox and xy plane co-incides with the fundamental plane of the celestial co-ordinate system. This fundamental plane corresponds to the ecliptic plane since the orbit is heliocentric. Thus, the vectors r and v are referred to the ecliptic co-ordinate system by using equatorial to ecliptic transformation. */ double R[4], V[4]; double rMagnitude, velSquare, radVelDotProduct; double eccentricityVector[4], angularMomentum[4], ascendingNode[4]; double semimajor, eccentricity, inclination, longitudeOfAscendingNode; double semiLatusRectum; double hMagnitude, ascendingNodeMagnitude; /* magnitude of angular momentum */ double ascEccDotProduct, argumentOfPerifocus; double xBar, yBar; double cosE, sinE, E1, E2, eccentricAnomaly; /* E1 and E2 are used to decide the quadrant of Eccentric Anomaly */ double meanAnomaly, meanMotion, timeOfPerifocalPassage; combinedMass = GM * 1.00134 ; /* Alter GM to account for total SS mass*/ epochTime=jd0; R[1] = xv->x; R[2] = xv->y; R[3] = xv->z; V[1] = xv->xdot; V[2] = xv->ydot; V[3] = xv->zdot; rMagnitude = sqrt(R[1]*R[1] + R[2]*R[2] + R[3]*R[3]); velSquare = V[1]*V[1] + V[2]*V[2] + V[3]*V[3]; radVelDotProduct = R[1]*V[1] + R[2]*V[2] + R[3]*V[3]; for (k=1;k<=3;k++) { eccentricityVector[k] = (velSquare/combinedMass - 1/rMagnitude)*R[k] - (radVelDotProduct/combinedMass)*V[k]; } /* Angular mom is cross product of rad and vel */ angularMomentum[1] = R[2]*V[3] - R[3]*V[2]; angularMomentum[2] = R[3]*V[1] - R[1]*V[3]; angularMomentum[3] = R[1]*V[2] - R[2]*V[1]; /* Ascending Node vector is cross product of k-unit vector and angular momentum vector. k = [0 0 1] and h = [hx, hy, hz] */ ascendingNode[1] = -angularMomentum[2]; ascendingNode[2] = angularMomentum[1]; ascendingNode[3] = 0.0; semimajor = 1/(2/rMagnitude - velSquare/combinedMass); eccentricity = sqrt(eccentricityVector[1]*eccentricityVector[1] + eccentricityVector[2]*eccentricityVector[2] + eccentricityVector[3]*eccentricityVector[3]); semiLatusRectum = (angularMomentum[1]*angularMomentum[1] + angularMomentum[2]*angularMomentum[2] + angularMomentum[3]*angularMomentum[3])/combinedMass; /* p = h-square by mu */ hMagnitude = sqrt( angularMomentum[1]*angularMomentum[1] + angularMomentum[2]*angularMomentum[2] + angularMomentum[3]*angularMomentum[3] ); inclination = acos(angularMomentum[3]/hMagnitude); /* in radians here */ ascendingNodeMagnitude = sqrt(ascendingNode[1]*ascendingNode[1] + ascendingNode[2]*ascendingNode[2] + ascendingNode[3]*ascendingNode[3]); longitudeOfAscendingNode = acos(ascendingNode[1]/ascendingNodeMagnitude); /* Capital Omega in radians here */ if (ascendingNode[2] < 0) longitudeOfAscendingNode = 2*PI - longitudeOfAscendingNode; /* ???could use atan2 here?? */ ascEccDotProduct = ascendingNode[1]*eccentricityVector[1] + ascendingNode[2]*eccentricityVector[2] + ascendingNode[3]*eccentricityVector[3]; argumentOfPerifocus = acos(ascEccDotProduct/ (ascendingNodeMagnitude*eccentricity)); /* Small omega in radians here */ if (eccentricityVector[3] < 0) argumentOfPerifocus = 2*PI - argumentOfPerifocus; xBar = (semiLatusRectum - rMagnitude)/eccentricity; yBar = radVelDotProduct*sqrt(semiLatusRectum/combinedMass)/eccentricity; /* From here, we assume that the motion is elliptical */ cosE = (xBar/semimajor) + eccentricity; sinE = yBar/(semimajor*sqrt(1-eccentricity*eccentricity)); /* where semimajor*sqrt(1-eccentricity*eccentricity) is semiminor */ eccentricAnomaly = atan2(sinE,cosE); meanAnomaly = eccentricAnomaly - eccentricity*sinE; /* radians */ meanMotion = sqrt(combinedMass/(pow(semimajor,3.))); timeOfPerifocalPassage = epochTime - meanAnomaly/meanMotion/DAY; /* This comes from M=n(t-T) where t is epoch time and T is time of perifocal passage, in days */ orb->a=semimajor; orb->e=eccentricity; orb->i=inclination/DTOR;/* in degrees now */ orb->lan = longitudeOfAscendingNode / DTOR; /*Long of ascending node*/ orb->aop = argumentOfPerifocus / DTOR; /*argument of perihelion, degrees*/ orb->T=timeOfPerifocalPassage; /*Time of perihelion passage (JD)*/ return; } /* function orbitElements ends */ /* JD routine stolen from skycalc: * I have changed the structre & routine to allow floating d/h/m/s * entries.*/ /* Converts a date (structure) into a julian date. Only good for 1900 -- 2100. */ double date_to_jd(struct date_time date) { short yr1=0, mo1=1; long jdzpt = 1720982, jdint, inter; double jd,jdfrac; short dint; if((date.y <= 1900) | (date.y >= 2100)) { printf("Date out of range. 1900 - 2100 only.\n"); return(0.); } if(date.mo <= 2) { yr1 = -1; mo1 = 13; } dint = floor(date.d); /*truncate to integer portion */ jdint = 365.25*(date.y+yr1); /* truncates */ inter = 30.6001*(date.mo+mo1); jdint = jdint+inter+dint+jdzpt; jd = jdint; jdfrac=((date.s/60.+date.mn)/60.+date.h/24.)+date.d-dint; if(jdfrac < 0.5) { jdint--; jdfrac=jdfrac+0.5; } else jdfrac=jdfrac-0.5; jd=jdint+jdfrac; return(jd); } /****************************************************************** * Get phase space from orbital elements ******************************************************************/ void elements_to_xv(ORBIT *o, double jd, XVBASIS *xv) { double eccentricAnomaly, r0[3], v0[3], r1[3], v1[3], r2[3], v2[3]; double meanAnomaly; double c, s, t, dt; double mu = GM*SSMASS; /*use SSMASS, work in AU/yrs*/ if (o->e >= 1. || o->a <=0.) { fprintf(stderr,"elements_to_xv only for closed orbits now\n"); exit(1); } /* get the eccentric Anomaly from the mean anomaly */ meanAnomaly = (jd - o->T)*DAY * pow(o->a,-1.5) * sqrt(mu); /* Put it near 0 */ t = floor (meanAnomaly / TPI); meanAnomaly -= t*TPI; /* Use bisection to find solution (adapt Numerical Recipes)*/ { #define JMAX 40 #define TOLERANCE (DAY/24./3600.) double f, fmid, x1, x2, dx, xmid, rtb; int j; x1 = meanAnomaly - o->e; x2 = meanAnomaly + o->e; f = x1 - o->e * sin(x1) - meanAnomaly; fmid= x2 - o->e * sin(x2) - meanAnomaly; if (f*fmid > 0.0) { fprintf(stderr,"Error, eccentricAnomaly root not bracketed\n"); fprintf(stderr,"f, fmid %f %f\n",f,fmid); exit(1); } rtb = f < 0.0 ? (dx=x2-x1,x1) : (dx=x1-x2,x2); for (j=1;j<=JMAX;j++) { xmid=rtb+(dx *= 0.5); fmid= xmid - o->e * sin(xmid) - meanAnomaly; if (fmid <= 0.0) rtb=xmid; if (fabs(dx) < TOLERANCE || fmid == 0.0) break; } if (j>=JMAX) { fprintf(stderr,"eccentricAnomaly took too long\n"); exit(1); } meanAnomaly = rtb; #undef JMAX #undef TOLERANCE } /*Coordinates and velocity in the system aligned with orbit: */ c = cos(meanAnomaly); s = sin(meanAnomaly); r0[0] = o->a * (c - o->e); r0[1] = o->a * s * sqrt(1-o->e*o->e); dt = sqrt(pow(o->a,3.)/mu) * ( 1 - o->e*c); v0[0] = -o->a * s / dt; v0[1] = o->a * c * sqrt(1-o->e*o->e) / dt; /* Rotate about z to put perihelion at arg of peri */ c = cos(o->aop*DTOR); s = sin(o->aop*DTOR); r1[0] = r0[0]*c - r0[1]*s; r1[1] = r0[0]*s + r0[1]*c; v1[0] = v0[0]*c - v0[1]*s; v1[1] = v0[0]*s + v0[1]*c; /* Rotate about x axis to incline orbit */ c = cos(o->i*DTOR); s = sin(o->i*DTOR); r2[0] = r1[0]; r2[1] = r1[1]*c; r2[2] = r1[1]*s; v2[0] = v1[0]; v2[1] = v1[1]*c; v2[2] = v1[1]*s; /* Rotate about z axis to bring node to longitude */ c = cos(o->lan*DTOR); s = sin(o->lan*DTOR); xv->x = r2[0]*c - r2[1]*s; xv->y = r2[0]*s + r2[1]*c; xv->z = r2[2]; xv->xdot = v2[0]*c - v2[1]*s; xv->ydot = v2[0]*s + v2[1]*c; xv->zdot = v2[2]; return; } /* Transform from an orbital element representation to a PBASIS * description. Sets up projected coordinate system to the proper * situation for the desired epoch as well, so the global lat0, lon0, * etc. will be changed. */ void elements_to_pbasis(ORBIT *o, double jd, int obscode, PBASIS *p) { XVBASIS xv; double xec, yec, zec; elements_to_xv(o, jd, &xv); /* Set up a new coordinate system that centers on current-epoch * positions */ earth_ssbary(jd, obscode, &xBary, &yBary, &zBary); /* Get target vector in ecliptic coords, set lat0/lon0 */ xBary *= -1.; yBary *= -1.; zBary *= -1.; xyz_eq_to_ec(xBary, yBary, zBary, &xec, &yec, &zec,NULL); xv.x += xec; xv.y+=yec; xv.z+=zec; lon0 = atan2(xv.y, xv.x); lat0 = asin( xv.z / sqrt(xv.x*xv.x + xv.y*xv.y + xv.z*xv.z)); jd0 = jd; /* Rotate target and bary into the projected system */ xyz_ec_to_proj(xec, yec, zec, &xBary, &yBary, &zBary, lat0, lon0, NULL); xyz_ec_to_proj(xv.x, xv.y, xv.z, &xv.x, &xv.y, &xv.z, lat0, lon0, NULL); xyz_ec_to_proj(xv.xdot, xv.ydot, xv.zdot, &xv.xdot, &xv.ydot, &xv.zdot, lat0, lon0, NULL); p->g = 1./xv.z; p->a = xv.x * p->g; p->b = xv.y * p->g; p->adot = xv.xdot * p->g; p->bdot = xv.ydot * p->g; p->gdot = xv.zdot * p->g; return; }
C
#include <stdbool.h> #include <stddef.h> #include <stdint.h> typedef struct{ uint16_t* subpalette; uint8_t size; uint8_t order;//définit l'ordre dans la palette finale. Insérer plusieurs sous-palettes avec le même ordre provoquera une erreur. uint8_t offset;//où commence la subpalette dans le tableau }Subpalette; typedef struct{ uint16_t* palette; uint24_t size; Subpalette** subpalettes; Subpalette** currentlyUsedSubPalettes; uint8_t subpaletteCount; }Palette; typedef struct{ Subpalette* allowedSubPalette;//la liste des palettes pour lesquelles ce sprite est valide uint8_t* data; uint8_t height; uint8_t width; }Sprite; typedef struct{ Palette* palettes; Sprite* sprites; }Group;
C
/* ** EPITECH PROJECT, 2018 ** PSU_2018_malloc ** File description: ** show_alloc_mem.c */ #include "../include/malloc.h" static void my_putstr(char *str) { int len = 0; while (str && str[len]) len++; write(1, str, len); } static void show_pointer(void *ptr) { char *base = "0123456789ABCDEF"; unsigned long nbr = (unsigned long)ptr; unsigned long i = 1; unsigned long digit; my_putstr("0x"); while (nbr / i >= 16) i = i * 16; while (i > 0) { digit = nbr / i % 16; write(1, &base[digit], 1); i = i / 16; } } static void show_bytes(size_t nbr) { char *base = "0123456789"; unsigned long i = 1; unsigned long digit; while (nbr / i >= 10) i = i * 10; while (i > 0) { digit = nbr / i % 10; write(1, &base[digit], 1); i = i / 10; } my_putstr(" bytes"); } static void show_alloc(metadata_t *data) { if (data->free) return; show_pointer(data->data); my_putstr(" - "); show_pointer(data->data + data->size); my_putstr(" : "); show_bytes(data->size); } void show_alloc_mem(void) { metadata_t *tmp = first_alloc(0, NULL); my_putstr("break : "); show_pointer(sbrk(0)); my_putstr("\n"); if (tmp) { show_alloc(tmp); tmp = tmp->next; } while (tmp && tmp != first_alloc(0, NULL)) { show_alloc(tmp); tmp = tmp->next; } }
C
#include<stdio.h> #include<string.h> #define length 1000 int inputs[length]; char file[] = __FILE__; int main() { char *filename = strtok(file, "."); strcat(filename, ".in"); FILE *fin = fopen(filename, "rb"); int x, n = 0; // n equals inputs.size - 1 while(fscanf(fin, "%d", &x) == 1 && x != 0) { inputs[n ++] = x; } for(int i = n - 1; i > 0; i --) { printf("%d ", inputs[i]); } printf("%d\n", inputs[0]); fclose(fin); return 0; }
C
#ifndef _TABLA_H #define _TABLA_H #include <stdbool.h> #include <stdio.h> #include "def.h" typedef FILE *tTabla; void encabezado(void); /* * imprime el titulo del juego * aunque no tenga nada que ver con la tabla, los tads que lo usan importan este tad */ tTabla abrirTabla(void); /* * si existe abre la tabla, sino la crea */ tTabla escribirTabla(tTabla tabla, int record, int tiempo); /* * si es el caso, pide el nombre al usuario, guarda el nuevo record e imprime la tabla * sino, solo imprime la tabla */ void comandos(tTabla tabla, char comando); /* * llama a funciones dependiendo de 'comando' * 'b' y 'v' son funciones con la tabla, respalda y restaura respectivamente * 'a' y 'c' son funciones que imprimen en pantalla, ayuda y acerca de respectivamente */ tTabla cerrarTabla(tTabla tabla); /* * cierra el archivo tabla */ #endif
C
// Write a function reverse(s) that reverses the character string s. // Use it to write a program that reverses its input a line at a time. // Revise the main routine of the longest-line program so it will correctly // print the length of arbitrary long input lines, and as much as possible of the text. #include <stdio.h> #include <libc.h> void reverse(char *str); int main(void) { char *str = strdup("1234567890"); printf("%s\n", str); reverse(str); printf("%s\n", str); return 0; } void reverse(char *str) { int len = strlen(str); int i; char symbol; for (i = 0; i < len/2; ++i) { symbol = str[i]; str[i] = str[len - i - 1]; str[len - i - 1] = symbol; } }
C
#include "holberton.h" /** * _prompt - Print prompt ($ ) and call fun for to split a string * @argv: name of program * Return: never returns */ char **_prompt(char **argv) { int bytes_rd = 0, inputcounter = 1; size_t n_bytes = 1024; char *str = NULL, *newstr, **command; signal(SIGINT, sighandler); while (1) { if (isatty(STDIN_FILENO)) dollar(); /*Call fun dollar who prints a dollar(prompt)*/ bytes_rd = getline(&str, &n_bytes, stdin); if (bytes_rd == EOF) /*When control + d is pressed*/ { if (isatty(STDIN_FILENO) == 0) { free(str); exit(0); } else { free(str); _putchar('\n'); exit(0); } } if (bytes_rd > 1) { fflush(stdin); command = token(str); newstr = executor(command, inputcounter, argv[0]); inputcounter++; } } free(str); free(newstr); return (argv); } /** * dollar - prints dollar and space to the prompt * Return: On sucess 2. * On error, -1 is returned, and errno is set appropriately. */ int dollar(void) { char c[2] = "$ "; return (write(1, &c, 2)); }
C
#include<stdio.h> #include<string.h> //𰸴󣿣why int main(){ char a[60],b[60],c[60],d[60]; int i,j; int m,day,t; scanf("%s\n%s\n%s\n%s",a,b,c,d); for(i=0;i<strlen(a)&&i<strlen(b);i++){ if((a[i]==b[i])&&a[i]>=65&&a[i]<=90){ m=a[i]; break; } } for(;i<strlen(a)&&i<strlen(b);i++){ if((a[i]==b[i])&&((a[i]>=65&&a[i]<=78)||(a[i]>=48&&a[i]<=57))){ day=a[i]; if((day>=65&&day<=78)){ day=day-54; }else{ day=day-48; } break; } } for(i=0;i<strlen(c)&&i<strlen(d);i++){ if((c[i]==d[i])&&((c[i]>=65&&d[i]<=90)||(c[i]>=97&&c[i]<=122))){ t=i; break; } } switch(m){ case 'A':printf("MON ");break; case 'B':printf("TUE ");break; case 'C':printf("WED ");break; case 'D':printf("THU ");break; case 'E':printf("FRI ");break; case 'F':printf("SAT ");break; case 'G':printf("SUN ");break; } if(day<=9){ printf("0%d:",day); //cout<<x/10<<x%10<<":"; }else{ printf("%d:",day); } if(t<=9){ printf("0%d",t); }else{ printf("%d",t); } return 0; } /* #include<iostream> #include<string> using namespace std; int main(){ string s1; string s2; string s3; string s4; cin>>s1>>s2>>s3>>s4; int mark=0; for(int i=0;i<s1.size()&&i<s2.size();i++){ if(s1[i]==s2[i]&&(s1[i]>='A'&&s1[i]<='G')){ switch(s1[i]){ case 'A': cout<<"MON ";break; case 'B': cout<<"TUE ";break; case 'C': cout<<"WED ";break; case 'D': cout<<"THU ";break; case 'E': cout<<"FRI ";break; case 'F': cout<<"SAT ";break; case 'G': cout<<"SUN ";break; } mark=i; break; } } for(int j=mark+1;j<s1.size()&&j<s2.size();j++){ if(s1[j]==s2[j]&&(s1[j]>='A' &&s1[j]<='N' || s1[j]>='0'&&s1[j]<='9')){ if(s1[j]>='A'&&s1[j]<='N'){ int x=s1[j]-'A'+10; cout<<x/10<<x%10<<":"; } else{ int y=s1[j]-'0'; cout<<y/10<<y%10<<":"; } break; } } for(int k=0;k<s3.size()&&k<s4.size();k++){ if(s3[k]==s4[k]&&(s3[k]>='A'&&s3[k]<='Z'||s3[k]>='a'&&s3[k]<='z')){ cout<<k/10<<k%10<<endl; } } system("pause"); return 0; } */
C
#include "convertions_operations.h" #include<stdio.h> #include<string.h> #include<math.h> long int Bin_to_Dec(long int bin) { int rem,sum=0,i=0; while(bin!=0) { rem=bin%10; bin=bin/10; sum=sum+rem*pow(2,i); i++; } printf("\nEquivalent Decimal Number : %d",sum); } long int Bin_to_Oct(long int bin) { int i=0,rem,sum=0,remain[100],len=0; while(bin!=0) { rem=bin%10; bin=bin/10; sum=sum+rem*pow(2,i); i++; } i=0; while(sum!=0) { remain[i]=sum%8; sum=sum/8; i++; len++; } printf("\nEquivalent Octal Number : "); for(i=len-1;i>=0;i--) { printf("%d",remain[i]); } } long int Bin_to_Hex(long int bin) { int rem,i=0,sum=0,remain[100],len=0; while(bin!=0) { rem=bin%10; bin=bin/10; sum=sum+rem*pow(2,i); i++; } i=0; while(sum!=0) { remain[i]=sum%16; sum=sum/16; i++; len++; } printf("\nEquivalent Hexa-Decimal Number : "); for(i=len-1;i>=0;i--) { switch(remain[i]) { case 10: printf("A"); break; case 11: printf("B"); break; case 12: printf("C"); break; case 13: printf("D"); break; case 14: printf("E"); break; case 15: printf("F"); break; default: printf("%d",remain[i]); } } } long int Dec_to_Bin(long int dec) { int rem[50],i,len=0; do { rem[i]=dec%2; dec=dec/2; i++; len++; } while(dec!=0); printf("\nEquivalent Binary Number : "); for(i=len-1;i>=0;i--) { printf("%d",rem[i]); } } long int Dec_to_Oct(long int dec) { int rem[50],i,len=0; do { rem[i]=dec%8; dec=dec/8; i++; len++; } while(dec!=0); printf("\nEquivalent Octal Number : "); for(i=len-1;i>=0;i--) { printf("%d",rem[i]); } } long int Dec_to_Hex(long int dec) { int rem[50],i,len=0; do { rem[i]=dec%16; dec=dec/16; i++; len++; } while(dec!=0); printf("\nEquivalent Hexa-Decimal Number : "); for(i=len-1;i>=0;i--) { switch(rem[i]) { case 10: printf("A"); break; case 11: printf("B"); break; case 12: printf("C"); break; case 13: printf("D"); break; case 14: printf("E"); break; case 15: printf("F"); break; default: printf("%d",rem[i]); } } } long int Oct_to_Bin(long int oct) { int rem[50],len=0,decimal=0,i=0,num,ans; while(oct!=0) { ans=oct % 10; decimal = decimal + ans * pow(8,i); i++; oct = oct/10; } i=0; do { rem[i]=decimal%2; decimal=decimal/2; i++; len++; } while(decimal!=0); printf("\nEquivalent Binary Number : "); for(i=len-1;i>=0;i--) { printf("%d",rem[i]); } } long int Oct_to_Dec(long int oct) { int decimal=0,i=0,num,ans; while(oct!=0) { ans=oct % 10; decimal = decimal + ans * pow(8,i); i++; oct = oct/10; } printf("\nEquivalent Decimal Number : %d",decimal); } long int Oct_to_Hex(long int oct) { int rem[50],len=0,decimal=0,i=0,num,ans=0; while(oct!=0) { ans=oct % 10; decimal = decimal + ans * pow(8,i); i++; oct = oct/10; } i=0; while(decimal!=0) { rem[i]=decimal%16; decimal=decimal/16; i++; len++; } printf("\nEquivalent Hexa-Decimal Number : "); for(i=len-1;i>=0;i--) { switch(rem[i]) { case 10: printf("A"); break; case 11: printf("B"); break; case 12: printf("C"); break; case 13: printf("D"); break; case 14: printf("E"); break; case 15: printf("F"); break; default: printf("%d",rem[i]); } } } char Hex_to_Bin(char hex[]) { int i=0; printf("\nEquivalent Binary Number : "); for(i=0;i<strlen(hex);i++) { switch (hex[i]) { case '0': printf("0000"); break; case '1': printf("0001"); break; case '2': printf("0010"); break; case '3': printf("0011"); break; case '4': printf("0100"); break; case '5': printf("0101"); break; case '6': printf("0110"); break; case '7': printf("0111"); break; case '8': printf("1000"); break; case '9': printf("1001"); break; case 'A': case 'a': printf("1010"); break; case 'B': case 'b': printf("1011"); break; case 'C': case 'c': printf("1100"); break; case 'D': case 'd': printf("1101"); break; case 'E': case 'e': printf("1110"); break; case 'F': case 'f': printf("1111"); break; default: printf("\n Invalid hexa digit %c ", hex[i]); } } } char Hex_to_Dec(char hex[]) { int i,num=0,power=0,decimal=0; for(i=strlen(hex)-1;i>=0;i--) { if(hex[i]=='A'||hex[i]=='a') { num=10; } else if(hex[i]=='B'||hex[i]=='b') { num=11; } else if(hex[i]=='C'||hex[i]=='c') { num=12; } else if(hex[i]=='D'||hex[i]=='d') { num=13; } else if(hex[i]=='E'||hex[i]=='e') { num=14; } else if(hex[i]=='F'||hex[i]=='f') { num=15; } else //(a[i]>=0 || a[i]<=9) { num=hex[i]-48; } decimal=decimal+num*pow(16,power); power++; } printf("\nEquivalent Decimal Number : %d",decimal); } char Hex_to_Oct(char hex[]) { int i,len,num=0,power=0,decimal=0,rem[100]; for(i=strlen(hex)-1;i>=0;i--) { if(hex[i]=='A'||hex[i]=='a') { num=10; } else if(hex[i]=='B'||hex[i]=='b') { num=11; } else if(hex[i]=='C'||hex[i]=='c') { num=12; } else if(hex[i]=='D'||hex[i]=='d') { num=13; } else if(hex[i]=='E'||hex[i]=='e') { num=14; } else if(hex[i]=='F'||hex[i]=='f') { num=15; } else //(a[i]>=0 || a[i]<=9) { num=hex[i]-48; } decimal=decimal+num*pow(16,power); power++; } i=0,len=0; while(decimal!=0) { rem[i]=decimal%8; decimal=decimal/8; i++; len++; } printf("\nEquivalent Octal Number : "); for(i=len-1;i>=0;i--) { printf("%d",rem[i]); } }
C
#include<stdio.h> #include<math.h> int main() { int n, a[500], s, g; printf("Enter size of array: "); scanf("%d", &n); printf("Enter numbers: "); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); if (i == 0) { s = a[i]; g = a[i]; } if (a[i] < s) { s = a[i]; } if (a[i] > g) { g = a[i]; } } if (s == g) { printf("No 2nd greatest element"); } else { for (int i = 0; i < n; i++) { if (a[i] > s and a[i] < g) s = a[i]; } printf("2nd greatest element: %d\n", s); } }
C
/** 题目意思是给一堆木棍,每个木棍的两个端点都涂上颜色,问能否将这堆木棍彼此相连组成一根大木棍, 相连的条件是:如果两个小木棍有颜色相同的端点,那么可以通过颜色相同的端点将他们连接起来。比如题目给的例子: blue red red violet cyan blue blue magenta magenta cyan 可以这样连起来(blue magenta)(magenta cyan)(cyan blue) (blue red)(red violet)。 不难发现,在最终组成的大木棍中,除了首尾两个端点的颜色的出现次数可能是奇数外,其他任意一种颜色出现的次数必定是偶数,因为中间的每种颜色都是成对出现的。 如果用图表示,每种颜色是一个顶点,那么至多只有两个点的度为奇数。当然只有这一个条件还是不够的,比如下边这个例子: blue red red blue cyan black black cyan 虽然所有颜色的度都是偶数,但是还是不能满足要求,用图表述这种情况的话就是图不是连通的。因此还有一个条件是图要连通。 是不是很像欧拉通路啊?其实就是欧拉通路。直接上定理了,无向图G有欧拉通路的充分必要条件为:G连通,G中只有两个奇度顶点(它们分别是欧拉通路的两个端点)。 既然得到结论了,是不是直接邻接矩阵搞起啊?其实没必要,邻接矩阵的重点是保存了边,而如果只是判断是不是欧拉通路的话,完全没必要保存边的信息, 因为我们只关心两点:顶点的度,图是否连通。判断图是否连通可以用集合来做,每个集合代表一个连通子图(即集合中的任意两个顶点都是连通的), 初始时每个顶点构成一个集合。然后每读入一个边,就可以进行如下操作: 首先更新该边两个顶点的度,然后将两个顶点所在集合合并,然后该边就可以舍弃了(不需要存下来),继续读下一条边。读完所有的边后,就可以检查条件了, 统计一下奇数度顶点的个数,再就是如果图是连通的,那么最后所有的顶点都会属于同一个集合。 集合可以用并查集来做,主要操作有两个,判断元素所属的集合find,合并集合union 。并查集大体分链式和树型两种实现,简单说下两种实现优缺点, 链式find操作快,复杂度O(1),union的时间和链的长度有关;树型find操作的时间和树的高度有关,union操作是O(1) 。我的实现用的是树型的。 另外本题顶点并不是0,1,2.....这种数字型,而是字符串型的,因为数据量较大,所以需要比较高效的字符串查找。可以用hash,可以用Trie树,我用的是动态创建的Trie树。 **/ #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct tNode{ struct tNode* next[26];//trie树中该节点的孩子 int degree; struct tNode* representation_element;//集合的代表元 }Node; Node* root;//trie树根 Node* union_node;//如果图是连通的,所有的节点应该指向同一个代表元(也就是属于一个集合),保存该代表元 int odd_count;//奇数度节点的个数 Node* create_node(char value,Node* parent){ Node* node=(Node*)malloc(sizeof(Node)); memset(node->next,0,sizeof(node->next)); node->degree=-1; node->representation_element=node;//初始时一个节点构成一个集合,集合的代表元当然就是它自己啦 if(parent!=NULL){ int i=(int)(value-'a'); Node** next=parent->next; if(next[i]==NULL){ next[i]=node; } } return node; } /** *查找,找不到的话动态创建Trie树节点 */ Node* search_or_insert(char* str){ int j=0; char c; Node* current_node=root; while((c=str[j++])!='\0'){ int i=(int)(c-'a'); if(current_node->next[i]==NULL){ current_node=create_node(c,current_node); }else{ current_node=current_node->next[i]; } } if(current_node->degree==-1){ current_node->degree=1; }else{ current_node->degree++; } return current_node; } /** *集合的合并 */ void union_set(Node* first_node,Node* second_node){ while(first_node->representation_element!=first_node){//找到各自的代表元,如果一个节点的代表元等于该节点本身,它就是代表元啦 first_node=first_node->representation_element; } while(second_node->representation_element!=second_node){ second_node=second_node->representation_element; } if(first_node==second_node){//本就是一个集合,直接返回吧 return; } second_node->representation_element=first_node;//将second_node的代表元修改为first_node } void go_get_result(Node* node){//前序遍历啦 if(node==NULL){ return; } int degree; if(node!=root&&(degree=node->degree)!=-1){ if((degree&1)==1){ odd_count++; if(odd_count==3){//根据欧拉通路的条件.....奇数度的点太多了 printf("Impossible\n"); exit(0); } } if(union_node==NULL){ union_node=node->representation_element; }else{ Node * current_node=node; while(current_node->representation_element!=current_node){ current_node=current_node->representation_element; } if(union_node!=current_node){//不连通 printf("Impossible\n"); exit(0); } } } Node** next=node->next; int i=0; for(;i<26;i++){ go_get_result(next[i]); } // free(node); } int main(void){ char first[11]; char second[11]; root=create_node('a',NULL); union_node=NULL; odd_count=0; while(scanf("%s %s",first,second)!=EOF){ Node* first_node=search_or_insert(first); Node* second_node=search_or_insert(second); union_set(first_node,second_node);//根据棒子合并集合 } go_get_result(root); printf("Possible\n"); //free释放下内存.. return 0; }
C
/* $Id: hanoi_ll.c,v 1.4 2006/02/28 20:57:26 mmr Exp $ <[email protected]>, 2004-05-31 Hanoi Tower Inocent Implementation */ /* Include */ #include <stdio.h> #include <stdlib.h> #ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/glut.h> #else #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #endif /* =-=-=-==-==-==-==-==-==-==-==-==-==-==-=-= */ /* Constants */ /* Window */ #define b1n_WINDOW_X 640 /* Window's Width */ #define b1n_WINDOW_Y 480 /* Window's Height */ /* Pillars */ #define b1n_PILLARS 3 #define b1n_PILLARS_BASE -1 /* Pillars' Base (ie. not a disc) */ #define b1n_PILLARS_RADIUS 0.1 #define b1n_PILLARS_HEIGHT 1.5 /* Discs */ #define b1n_DISCS_MIN 2 #define b1n_DISCS_MAX 10 #define b1n_DISCS_DEFAULT 2 /* Misc */ #define b1n_TRUE 1 #define b1n_FALSE 0 #define b1n_FAIL -1 #define b1n_SUCCESS 0 /* =-=-=-==-==-==-==-==-==-==-==-==-==-==-=-= */ /* Macros */ /* #define b1n_FIND_LAST(a) while(a) */ #define b1n_RANDOM2(min,max) min+((int)((float)rand()/RAND_MAX*(max-min))) #define b1n_RANDOM(max) b1n_RANDOM2(0, max) #define b1n_RANDCOLOR glColor3b(b1n_RANDOM(255), b1n_RANDOM(255), b1n_RANDOM(255)); /* =-=-=-==-==-==-==-==-==-==-==-==-==-==-=-= */ /* Types */ typedef struct b1n_stack { int value; struct b1n_stack *next; } b1n_stack; /* =-=-=-==-==-==-==-==-==-==-==-==-==-==-=-= */ /* Prototypes */ /* Draw */ void b1n_drawDisk(GLdouble, GLdouble); /* Draw a disc */ void b1n_drawCylinder(GLdouble, GLdouble, GLdouble); /* Draw a cylinder */ /* Game */ void b1n_gameRenderSetup(void); /* OpenGL Setup */ void b1n_gameSetup(int, char **); /* Pillars and Discs Setup */ void b1n_gameDraw(void); /* Draw pillars and discs */ void b1n_gameDrawPillars(void);/* Draw pillars */ void b1n_gameDrawDiscs(void); /* Draw discs */ void b1n_gameQuit(void); /* Free memory and exit gracefully */ int b1n_pillarsCreate(void); /* Create Pillars (stacks) */ int b1n_pillarsSetup(int); /* Initial Pillars Setup */ void b1n_pillarsDestroy(void); /* Destroy Pillars (free memory) */ /* CallBack */ void b1n_callbackReshape(GLint, GLint); void b1n_callbackMouse(void); void b1n_callbackKeyboard(unsigned char, int, int); static void b1n_callbackSpecialkey(int, int, int); /* Stack */ b1n_stack *b1n_stackCreate(void); /* Create a Stack */ b1n_stack *b1n_stackPush(b1n_stack *, int); /* Push an item into a Stack */ int b1n_stackPop(b1n_stack *); /* Pop an item from a Stack */ /* Misc */ void b1n_usage(const char *); void b1n_bail(int, const char *); /* =-=-=-==-==-==-==-==-==-==-==-==-==-==-=-= */ /* Global Vars */ /* Pillars */ b1n_stack *g_pillars[b1n_PILLARS]; /* Position in Space */ GLdouble g_pos_x = 0, g_pos_y = 90; GLUquadricObj *g_qobj; /* =-=-=-==-==-==-==-==-==-==-==-==-==-==-=-= */ /* Main */ int main(int argc, char **argv) { /* Initializing Glut */ glutInit(&argc, argv); glutInitWindowSize(b1n_WINDOW_X, b1n_WINDOW_Y); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); glutCreateWindow("mmr's Hanoi"); /* Setting the Game up (render, pillars and discs) */ b1n_gameRenderSetup(); b1n_gameSetup(argc, argv); /* Setting the Callback up */ glutReshapeFunc(b1n_callbackReshape); glutSpecialFunc(b1n_callbackSpecialkey); glutKeyboardFunc(b1n_callbackKeyboard); glutDisplayFunc(b1n_gameDraw); /* Loop */ glutMainLoop(); /* Just to be Nice */ b1n_gameQuit(); return b1n_SUCCESS; } /* =-=-=-==-==-==-==-==-==-==-==-==-==-==-=-= */ /* Draw */ /* Draws a cylinder with a flat disc at each end */ void b1n_drawCylinder(GLdouble outerRadius, GLdouble innerRadius, GLdouble height) { glPushMatrix(); gluCylinder(g_qobj, outerRadius, outerRadius, height, 20, 1); glPushMatrix(); glRotatef(180, 0.0, 1.0, 0.0); gluDisk(g_qobj, innerRadius, outerRadius, 20, 1); glPopMatrix(); glTranslatef(0.0, 0.0, height); gluDisk(g_qobj, innerRadius, outerRadius, 20, 1); glPopMatrix(); } /* Draws a disc */ void b1n_drawDisk(GLdouble innerRadius, GLdouble outerRadius) { glPushMatrix(); gluDisk(g_qobj, innerRadius, outerRadius, 20, 1); glPopMatrix(); } /* =-=-=-==-==-==-==-==-==-==-==-==-==-==-=-= */ /* Game */ void b1n_gameDraw(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix(); glRotatef(g_pos_x, 0, 1, 0); glRotatef(g_pos_y, 1, 0, 0); glTranslatef(-1.0, 0.0, 0.0); b1n_gameDrawPillars(); b1n_gameDrawDiscs(); glutSwapBuffers(); glPopMatrix(); } void b1n_gameDrawPillars(void) { int i, j; GLdouble dpos; b1n_stack *cur; glPushMatrix(); for(i=0, j=b1n_PILLARS_HEIGHT; i<b1n_PILLARS; i++){ glPushMatrix(); /* Space between cylinders */ glTranslatef(i, 0.0, 0.0); /* Drawing Cylinder */ b1n_drawCylinder(b1n_PILLARS_RADIUS, 0.0, b1n_PILLARS_HEIGHT); /* Drawing Disks */ glPushMatrix(); b1n_RANDCOLOR; cur = g_pillars[i]; dpos = 0; while(cur != NULL){ if(cur->value != b1n_PILLARS_BASE){ // b1n_RANDCOLOR; dpos += cur->value*0.01; glTranslatef(0.0, 0.0, 0.2); glutSolidTorus(0.1, cur->value*0.1, 20, 20); j++; } cur = cur->next; } glPopMatrix(); glColor3f(1, 1, 1); glPopMatrix(); } glPopMatrix(); } void b1n_gameDrawDiscs(void) { //glutSolidTorus(0.05, 0.15, 20, 20); } /* Game Setup (Pillars and Discs) */ void b1n_gameSetup(int argc, char **argv) { int discs; /* Checking if the user suggested discs quantity */ if(argc>1){ discs = atoi(argv[1]); /* Checking if its within the valid range */ if(discs < b1n_DISCS_MIN || discs > b1n_DISCS_MAX){ b1n_usage(argv[0]); } } else { discs = b1n_DISCS_DEFAULT; } /* Creating pillars (stacks) */ if(b1n_pillarsCreate()){ /* Setting pillars up */ if(!b1n_pillarsSetup(discs)){ b1n_bail(b1n_FAIL, "Could not setup pillars."); } } else { b1n_bail(b1n_FAIL, "Could not create pillars."); } } /* OpenGL Setup (Background, Light, Projection) */ void b1n_gameRenderSetup(void) { GLfloat mat_specular[] = {1.0, 1.0, 1.0, 1.0}; GLfloat mat_shininess[] = {50.0}; GLfloat light_position1[] = {1.0, 1.0, 1.0, 0.0}; GLfloat light_position2[] = {-1.0, 1.0, 1.0, 0.0}; /* Quadric */ g_qobj = gluNewQuadric(); /* Set up Lighting */ glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); glLightfv(GL_LIGHT0, GL_POSITION, light_position1); glLightfv(GL_LIGHT1, GL_POSITION, light_position2); /* Initial render mode is with full shading and LIGHT 0 enabled. */ glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glDepthFunc(GL_LEQUAL); glEnable(GL_DEPTH_TEST); glDisable(GL_ALPHA_TEST); glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE); glEnable(GL_COLOR_MATERIAL); glShadeModel(GL_SMOOTH); } /* Free Memory and Quit gracefully */ void b1n_gameQuit(void) { b1n_pillarsDestroy(); /* Freeing memory */ exit(b1n_SUCCESS); /* Quitting */ } /* Create Pillars (stacks) */ int b1n_pillarsCreate(void) { int i, ret = b1n_TRUE; for(i=0; i<b1n_PILLARS && ret; i++){ #ifdef DEBUG printf("Creating pillar %d\n", i); #endif if((g_pillars[i] = b1n_stackCreate()) != NULL){ g_pillars[i]->value = b1n_PILLARS_BASE; g_pillars[i]->next = NULL; ret = b1n_TRUE; } else { ret = b1n_FALSE; } } return ret; } /* Initial Pillars Setup */ int b1n_pillarsSetup(int d) { int i; int ret = b1n_TRUE; /* The initial Setup is: pillar 0 => d discs pillar 1 => 0 discs pillar 2 => 0 discs */ /* Popullating pillar 0 from d to 0 */ for(i=d; i>0 && ret; i--){ #ifdef DEBUG printf("Pushed Disc %d on pillar 0\n", i); #endif g_pillars[0] = b1n_stackPush(g_pillars[0], i); } return ret; } /* Destroy Pillars (free memory) */ void b1n_pillarsDestroy(void) { int i; b1n_stack *cur, *next; /* Freeing memory for each one of the Pillars */ for(i=0; i<b1n_PILLARS; i++){ #ifdef DEBUG printf("Destroying pillar %d\n", i); #endif cur = g_pillars[i]; /* Freeing memory for each disc on this Pillar */ while(cur != NULL){ #ifdef DEBUG if(cur->value != b1n_PILLARS_BASE){ printf("\tDestroying disc %d!\n", cur->value); } #endif next = cur->next; free(cur); cur = next; } } } /* =-=-=-==-==-==-==-==-==-==-==-==-==-==-=-= */ /* Stack */ /* Create a Stack */ b1n_stack * b1n_stackCreate(void) { return (b1n_stack *) malloc(sizeof(b1n_stack)); } /* Pop an item from a Stack */ int b1n_stackPop(b1n_stack *stack) { b1n_stack *next; int value = 0; if(stack != NULL){ next = stack->next; value = stack->value; free(stack); stack = next; } return value; } /* Push an item from a Stack */ b1n_stack * b1n_stackPush(b1n_stack *stack, int value) { b1n_stack *new = (b1n_stack *) malloc(sizeof(b1n_stack)); new->next = stack; new->value = value; stack = new; return stack; } /* =-=-=-==-==-==-==-==-==-==-==-==-==-==-=-= */ /* CallBack */ void b1n_callbackReshape(GLint w, GLint h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(65.0, (GLfloat) w / (GLfloat) h, 1.0, 20.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0, 0.0, -5.0); glScalef(1.5, 1.5, 1.5); } void b1n_callbackKeyboard(unsigned char k, int x, int y) { switch(k){ case 27: case 'q': case 'Q': b1n_gameQuit(); break; } } static void b1n_callbackSpecialkey(int k, int x, int y) { switch(k){ case GLUT_KEY_LEFT: if ((g_pos_x -= 10) <= 0) g_pos_x = 360; break; case GLUT_KEY_RIGHT: if ((g_pos_x += 10) >= 360) g_pos_x = 0; break; case GLUT_KEY_UP: if ((g_pos_y += 10) >= 360) g_pos_y = 0; break; case GLUT_KEY_DOWN: if ((g_pos_y -= 10) <= 0) g_pos_y = 360; break; } glutPostRedisplay(); } void b1n_callbackMouse(void) { } /* =-=-=-==-==-==-==-==-==-==-==-==-==-==-=-= */ /* Misc */ void b1n_bail(int c, const char *m) { fprintf(stderr, "%s\n", m); exit(c); } void b1n_usage(const char *p) { fprintf(stderr, "Usage: %s [discs]" "\nDiscs Min:\t%02d" "\nDiscs Max:\t%02d" "\nDiscs Default:\t%02d\n", p, b1n_DISCS_MIN, b1n_DISCS_MAX, b1n_DISCS_DEFAULT); exit(b1n_FAIL); }
C
#include <mctop.h> #include <mctop_internal.h> #include <mctop_profiler.h> #include <math.h> const size_t mctop_prof_correction_stdp_limit = 8; static ticks mctop_prof_correction_calc(mctop_prof_t* prof, const size_t num_entries) { dvfs_scale_up(1e6, 0.95, NULL); size_t std_dev_perc_lim = mctop_prof_correction_stdp_limit; mctop_prof_stats_t stats; do { for (volatile size_t i = 0; i < num_entries; i++) { MCTOP_PROF_START(prof, ts); COMPILER_BARRIER(); MCTOP_PROF_STOP(prof, ts, i); } mctop_prof_stats_calc(prof, &stats); } while (stats.std_dev_perc > std_dev_perc_lim++); return stats.median; } mctop_prof_t* mctop_prof_create(size_t num_entries) { mctop_prof_t* prof = malloc_assert(sizeof(mctop_prof_t) + (num_entries * sizeof(ticks))); prof->size = num_entries; prof->correction = 0; prof->correction = mctop_prof_correction_calc(prof, num_entries); return prof; } void mctop_prof_free(mctop_prof_t* prof) { free(prof); prof = NULL; } static int mctop_prof_comp_ticks(const void *elem1, const void *elem2) { ticks f = *((ticks*)elem1); ticks s = *((ticks*)elem2); if (f > s) return 1; if (f < s) return -1; return 0; } static inline ticks mctop_prof_abs_diff(ticks a, ticks b) { if (a > b) { return a - b; } return b - a; } void mctop_prof_stats_calc(mctop_prof_t* prof, mctop_prof_stats_t* stats) { qsort(prof->latencies, prof->size, sizeof(ticks), mctop_prof_comp_ticks); stats->num_vals = prof->size; stats->median = prof->latencies[prof->size >> 1]; const size_t median2x = 2 * stats->median; size_t n_elems = 0; ticks sum = 0; for (size_t i = 0; i < stats->num_vals; i++) { if (likely(prof->latencies[i] < median2x)) { sum += prof->latencies[i]; n_elems++; } } const ticks avg = sum / n_elems;; stats->avg = avg; ticks sum_diff_sqr = 0; for (size_t i = 0; i < stats->num_vals; i++) { if (likely(prof->latencies[i] < median2x)) { ticks adiff = mctop_prof_abs_diff(prof->latencies[i], avg); sum_diff_sqr += (adiff * adiff); } } stats->std_dev = sqrt(sum_diff_sqr / n_elems); stats->std_dev_perc = 100 * (1 - (avg - stats->std_dev) / avg); } void mctop_prof_stats_print(mctop_prof_stats_t* stats) { printf("## mctop_prof stats #######\n"); printf("# #Values = %zu\n", stats->num_vals); printf("# Average = %zu\n", stats->avg); printf("# Median = %zu\n", stats->median); printf("# Std dev = %.2f\n", stats->std_dev); printf("# Std dev%% = %.2f%%\n", stats->std_dev_perc); printf("###########################\n"); }
C
#include "../main.gen.h" //PUBLIC void console_clear(void) // PUBLIC; { printf("\e[;H\e[2J"); } view_size console_size(void) // PUBLIC; { view_size view_size; view_size.width = 0; view_size.height = 0; struct winsize ws; if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) != -1) { view_size.width = ws.ws_col; view_size.height = ws.ws_row; } return view_size; }
C
#include "funciones.h" #include <stdio.h> /** \brief sumar dos numeros * \param A variable float a sumar * \param B variable float a sumar * \return total de la suma * */ float suma(float A, float B) { float total; total=A+B; return total; } /** \brief restar dos numeros * \param A variable float a restar * \param B variable float a restar * \return total de la resta * */ float resta(float A, float B) { float total; total=A-B; return total; } /** \brief dividir dos numeros * \param A variable float dividendo * \param B variable float divisor * \return total de la division * */ float division(float A, float B) { float total; total=A/B; return total; } /** \brief multiplicar dos numeros * \param A variable float a multiplicar * \param B variable float a multiplicar * \return total de la multiplicacion * */ float multiplicacion(float A, float B) { float total; total=A*B; return total; } /** \brief sacar factorial de un numero * \param variable int a factorizar * \return valor del factorial * */ int factorial (int A) { int resultadoFactorial=1; int i; for(i=(int)A; i>=1; i--) { resultadoFactorial= resultadoFactorial*i; } return resultadoFactorial; } /** \brief Ingresar numero por usuario * \param numero a guardar * \return valor de numero guardado * */ void ingresarNumero(float* pNumero) { printf("Ingrese un numero: "); fflush(stdin); scanf("%f", pNumero); }
C
/* * Harness based test for the OBC flash memory. * * Tests functionality of writing and reading memory at the byte level, writing to and reading from eeprom, * writing and reading headers and fields from memory sections. * * NOTE: See mem.c notes on flash memory architecture - generally need to do an erase before every test function * * Most tests check that the memory is all 1s before doing a write - make sure the data isn't just left over from a previous run of the test */ #include <stdlib.h> #include <test/test.h> #include <uart/uart.h> #include <spi/spi.h> #include "../../src/mem.h" #define ERASE_ADDR_COUNT 20 #define DATA_LENGTH 5 #define RANDOM_MAX_LEN 255 #define ROLLOVER_ADDR_1 0x1FFFFC #define ROLLOVER_ADDR_2 0x3FFFFB #define ROLLOVER_ADDR_3 0x5FFFFD #define NUM_ROLLOVER 3 #define ROLLOVER_DATA {0xDE, 0xAD, 0xBE, 0xEF, 0xBA, 0xF0, 0x0D, 0x12} #define ROLLOVER_DATA_LEN 8 // Macros to compare structs without having to do it for each of the fields every time #define ASSERT_EQ_DATE(date1, date2) \ ASSERT_EQ(date1.yy, date2.yy); \ ASSERT_EQ(date1.mm, date2.mm); \ ASSERT_EQ(date1.dd, date2.dd); #define ASSERT_EQ_TIME(time1, time2) \ ASSERT_EQ(time1.hh, time2.hh); \ ASSERT_EQ(time1.mm, time2.mm); \ ASSERT_EQ(time1.ss, time2.ss); #define ASSERT_EQ_ARRAY(array1, array2, count) \ for (uint8_t i = 0; i < count; i++) { \ ASSERT_EQ((array1)[i], (array2)[i]); \ } #define ASSERT_NEQ_ARRAY(array1, array2, count) \ for (uint8_t i = 0; i < count; i++) { \ ASSERT_NEQ((array1)[i], (array2)[i]); \ } rtc_date_t rand_rtc_date(void) { rtc_date_t date = { .yy = random() & 0xFF, .mm = random() & 0xFF, .dd = random() & 0xFF }; return date; } rtc_time_t rand_rtc_time(void) { rtc_time_t time = { .hh = random() & 0xFF, .mm = random() & 0xFF, .ss = random() & 0xFF }; return time; } void populate_zeros(uint8_t* array, uint8_t len) { for (uint8_t i = 0; i < len; i++) { array[i] = 0x00; } } void populate_ones(uint8_t* array, uint8_t len) { for (uint8_t i = 0; i < len; i++) { array[i] = 0xFF; } } // Test the erase_mem() void erase_mem_test(void) { erase_mem(); // take a random sample of the memory to see if erase works // values should all be 0xff uint32_t num_addrs = MEM_NUM_CHIPS * (1UL << MEM_CHIP_ADDR_WIDTH); for(uint8_t i = 0; i < ERASE_ADDR_COUNT; i++){ uint32_t addr = random() % num_addrs; uint8_t read[1] = { 0x00 }; read_mem_bytes(addr, read, 1); ASSERT_EQ(read[0], 0xFF); } } //Test single write/read for consistency void single_write_read_test(void) { erase_mem(); uint32_t address = 0x0ADF00; uint8_t data = 0xDD; uint8_t write[1] = {data}; uint8_t read[1] = {0x00}; uint8_t ones[1]; populate_ones(ones, 1); read_mem_bytes(address, read, 1); ASSERT_EQ_ARRAY(ones, read, 1); write_mem_bytes(address, write, 1); read_mem_bytes(address, read, 1); ASSERT_EQ_ARRAY(write, read, 1); } //Test multiple write/read for consistency void multiple_write_read_test(void) { erase_mem(); uint32_t address = 0x05ABEEF; uint8_t data[5] = {0xAA, 0xBB, 0xCC, 0xDD, 0xEE}; uint8_t read[5] = {0x00, 0x00, 0x00, 0x00, 0x00}; uint8_t ones[5]; populate_ones(ones, 5); read_mem_bytes(address, read, 5); ASSERT_EQ_ARRAY(ones, read, 5); write_mem_bytes(address, data, 5); read_mem_bytes(address, read, 5); for(uint8_t i=0; i<5; i++){ ASSERT_EQ(data[i], read[i]); } } //More read/write tests for different address void multiple_write_read_test_2(void) { erase_mem(); uint32_t address = 0x300000; uint8_t write[20]; for(uint8_t i=0; i<20; i++) write[i] = i%16; uint8_t read[20]; for(uint8_t i=0; i<20; i++) read[i] = 0x00; uint8_t ones[20]; populate_ones(ones, 20); read_mem_bytes(address, read, 20); ASSERT_EQ_ARRAY(ones, read, 20); write_mem_bytes(address, write, 20); read_mem_bytes(address, read, 15); ASSERT_EQ_ARRAY(write, read, 15); //read shouldn't touch the last 5 bytes in the read array ASSERT_EQ_ARRAY(&ones[15], &read[15], 5); } // Test random read and write capabilities void random_read_write_test(void) { erase_mem(); uint32_t num_addrs = MEM_NUM_CHIPS * (1UL << MEM_CHIP_ADDR_WIDTH); uint32_t addr = random() % num_addrs; // Use a random number of bytes uint8_t len = (random() % RANDOM_MAX_LEN) + 1; // Array needs to be big enough to hold the maximum number of bytes uint8_t write[RANDOM_MAX_LEN]; for(uint8_t i = 0; i<len ; i++) { write[i] = random() % 0XFF; } uint8_t read[RANDOM_MAX_LEN]; uint8_t ones[RANDOM_MAX_LEN]; populate_ones(ones, RANDOM_MAX_LEN); read_mem_bytes(addr, read, RANDOM_MAX_LEN); ASSERT_EQ_ARRAY(ones, read, RANDOM_MAX_LEN); write_mem_bytes(addr, write, len); read_mem_bytes(addr, read, len); for(uint8_t i=0; i<len; i++) { ASSERT_EQ(read[i], write[i]); } } // Test memory roll over capabilities. Board has three memory chips, so two roll overs void roll_over_test(void) { erase_mem(); uint32_t addr[NUM_ROLLOVER] = {ROLLOVER_ADDR_1, ROLLOVER_ADDR_2, ROLLOVER_ADDR_3}; uint8_t write[ROLLOVER_DATA_LEN] = ROLLOVER_DATA; uint8_t read[ROLLOVER_DATA_LEN]; uint8_t ones[ROLLOVER_DATA_LEN]; populate_ones(ones, ROLLOVER_DATA_LEN); for(uint8_t i=0; i<NUM_ROLLOVER; i++){ populate_zeros(read, ROLLOVER_DATA_LEN); read_mem_bytes(addr[i], read, ROLLOVER_DATA_LEN); if (i == NUM_ROLLOVER - 1) { ASSERT_EQ_ARRAY(ones, read, MEM_NUM_ADDRESSES - ROLLOVER_ADDR_3); } else { ASSERT_EQ_ARRAY(ones, read, ROLLOVER_DATA_LEN); } write_mem_bytes(addr[i], write, ROLLOVER_DATA_LEN); populate_zeros(read, ROLLOVER_DATA_LEN); read_mem_bytes(addr[i], read, ROLLOVER_DATA_LEN); for(uint8_t j=0; j<ROLLOVER_DATA_LEN; j++){ if (i == NUM_ROLLOVER - 1 && j >= 3) { // check chip 3 rollover outside of address range ASSERT_NEQ(write[j], read[j]); } else { ASSERT_EQ(write[j], read[j]); } } } } // EEPROM test void eeprom_test(void) { // load all section data from eeprom read_all_mem_sections_eeprom(); uint32_t eps_hk_block_prev = read_eeprom_or_default(eps_hk_mem_section.curr_block_eeprom_addr, 0); uint32_t pay_hk_block_prev = read_eeprom_or_default(pay_hk_mem_section.curr_block_eeprom_addr, 0); uint32_t pay_opt_block_prev = read_eeprom_or_default(pay_opt_mem_section.curr_block_eeprom_addr, 0); set_mem_section_curr_block(&eps_hk_mem_section, eps_hk_mem_section.curr_block + 1); set_mem_section_curr_block(&pay_hk_mem_section, pay_hk_mem_section.curr_block + 1); set_mem_section_curr_block(&pay_opt_mem_section, pay_opt_mem_section.curr_block + 1); ASSERT_EQ(eps_hk_block_prev + 1, read_eeprom(eps_hk_mem_section.curr_block_eeprom_addr)); ASSERT_EQ(pay_hk_block_prev + 1, read_eeprom(pay_hk_mem_section.curr_block_eeprom_addr)); ASSERT_EQ(pay_opt_block_prev + 1, read_eeprom(pay_opt_mem_section.curr_block_eeprom_addr)); } // Test headers for each of the mem_sections (metadata) void mem_header_test_individual( mem_section_t* section ) { erase_mem(); // eps_hk_mem_section mem_header_t write = { .block_num = section->curr_block, .date = rand_rtc_date(), .time = rand_rtc_time(), .status = 0x00, }; write_mem_header_main(section, section->curr_block, &write); write_mem_header_status(section, section->curr_block, write.status); mem_header_t read; read_mem_header(section, section->curr_block, &read); ASSERT_EQ(write.block_num, read.block_num); ASSERT_EQ(write.status, read.status); ASSERT_EQ_DATE(write.date, read.date); ASSERT_EQ_TIME(write.time, read.time); } void mem_header_test(void){ mem_header_test_individual(&eps_hk_mem_section); mem_header_test_individual(&pay_hk_mem_section); mem_header_test_individual(&pay_opt_mem_section); } //Test field (metadata) void mem_field_test_individual( mem_section_t* section) { erase_mem(); uint8_t field_num = random() % section->fields_per_block; // Random 24-bit number uint32_t write = (random() % 0xFFFFFF) + 1; uint32_t read = 0x00000000; read = read_mem_field(section, section->curr_block, field_num); ASSERT_EQ(0xFFFFFF, read); write_mem_field(section, section->curr_block, field_num, write); read = read_mem_field(section, section->curr_block, field_num); ASSERT_EQ(write, read); } void mem_field_test(void) { mem_field_test_individual(&eps_hk_mem_section); mem_field_test_individual(&pay_hk_mem_section); mem_field_test_individual(&pay_opt_mem_section); } //test blocks void mem_block_test_1(void){ erase_mem(); uint32_t write_fields_1[obc_hk_mem_section.fields_per_block]; uint32_t write_fields_2[eps_hk_mem_section.fields_per_block]; uint32_t write_fields_3[pay_hk_mem_section.fields_per_block]; uint32_t write_fields_4[pay_opt_mem_section.fields_per_block]; //random 32 bit numbers for (int a = 0; a < obc_hk_mem_section.fields_per_block; a++){ write_fields_1[a] = (random() & 0xFFFFFF); } for (int a = 0; a < eps_hk_mem_section.fields_per_block; a++){ write_fields_2[a] = (random() & 0xFFFFFF); } for (int a = 0; a < pay_hk_mem_section.fields_per_block; a++){ write_fields_3[a] = (random() & 0xFFFFFF); } for (int a = 0; a < pay_opt_mem_section.fields_per_block; a++){ write_fields_4[a] = (random() & 0xFFFFFF); } uint32_t* write_test_fields[4] = {write_fields_1, write_fields_2, write_fields_3, write_fields_4}; mem_header_t write_header[4]; uint32_t block_num[4]; //write to all sections for (int i = 0; i < 4; i++){ mem_section_t* section = all_mem_sections[i]; section->curr_block = 1;//////////////// block_num[i] = section->curr_block; (write_header[i]).block_num = section->curr_block; (write_header[i]).date = rand_rtc_date(); (write_header[i]).time = rand_rtc_time(); (write_header[i]).status = 0x00; uint32_t prev_block = section->curr_block; write_mem_header_main(section, block_num[i], &(write_header[i])); write_mem_header_status(section, block_num[i], write_header[i].status); for (uint8_t field_num = 0; field_num < section->fields_per_block; field_num++) { write_mem_field(section, block_num[i], field_num, write_test_fields[i][field_num]); } ASSERT_EQ(prev_block, block_num[i]);/////////////// } uint32_t read_fields_1[obc_hk_mem_section.fields_per_block]; uint32_t read_fields_2[eps_hk_mem_section.fields_per_block]; uint32_t read_fields_3[pay_hk_mem_section.fields_per_block]; uint32_t read_fields_4[pay_opt_mem_section.fields_per_block]; uint32_t* read_test_fields[4] = {read_fields_1, read_fields_2, read_fields_3, read_fields_4}; mem_header_t read_header[4]; uint32_t read_block_num[4]; //read from all sections for (int i = 0; i < 4; i++){ mem_section_t* section = all_mem_sections[i]; section->curr_block = 1;//////////////////// read_block_num[i] = section->curr_block; read_mem_data_block(section, read_block_num[i], &(read_header[i]), read_test_fields[i]); } for (int i=0; i<4; i++){ ASSERT_EQ(block_num[i], read_block_num[i]); } //check headers for (int i = 0; i < 4; i++){ ASSERT_EQ((write_header[i]).block_num, (read_header[i]).block_num); //this should be the case right. ASSERT_EQ_DATE((write_header[i]).date, (read_header[i]).date); ASSERT_EQ_TIME((write_header[i]).time, (read_header[i]).time); ASSERT_EQ((write_header[i]).status, (read_header[i]).status); } //check fields for (uint8_t a = 0; a < obc_hk_mem_section.fields_per_block; a++){ ASSERT_EQ(write_fields_1[a], read_fields_1[a]); } for (uint8_t a = 0; a < eps_hk_mem_section.fields_per_block; a++){ ASSERT_EQ(write_fields_2[a], read_fields_2[a]); } for (uint8_t a = 0; a < pay_hk_mem_section.fields_per_block; a++){ ASSERT_EQ(write_fields_3[a], read_fields_3[a]); } for (uint8_t a = 0; a < pay_opt_mem_section.fields_per_block; a++){ ASSERT_EQ(write_fields_4[a], read_fields_4[a]); } } //actually test blocks void mem_block_test_2(void){ erase_mem(); uint32_t write_fields_1[obc_hk_mem_section.fields_per_block]; uint32_t write_fields_2[eps_hk_mem_section.fields_per_block]; uint32_t write_fields_3[pay_hk_mem_section.fields_per_block]; uint32_t write_fields_4[pay_opt_mem_section.fields_per_block]; uint32_t read_fields_1[obc_hk_mem_section.fields_per_block]; uint32_t read_fields_2[eps_hk_mem_section.fields_per_block]; uint32_t read_fields_3[pay_hk_mem_section.fields_per_block]; uint32_t read_fields_4[pay_opt_mem_section.fields_per_block]; //populate with random data for (uint8_t i=0; i<obc_hk_mem_section.fields_per_block; i++){ write_fields_1[i] = 0x765432; read_fields_1[i] = 0x234567; } for (uint8_t i=0; i<eps_hk_mem_section.fields_per_block; i++){ write_fields_2[i] = 0x765432; read_fields_2[i] = 0x234567; } for (uint8_t i=0; i<pay_hk_mem_section.fields_per_block; i++){ write_fields_3[i] = 0x765432; read_fields_3[i] = 0x234567; } for (uint8_t i=0; i<pay_opt_mem_section.fields_per_block; i++){ write_fields_4[i] = 0x765432; read_fields_4[i] = 0x234567; } //test obc housekeeping mem_section_t* section = all_mem_sections[0]; section->curr_block = 0;// uint32_t block_num = section->curr_block; mem_header_t write_header; mem_header_t read_header; write_header.block_num = section->curr_block; write_header.date = rand_rtc_date(); write_header.time = rand_rtc_time(); write_header.status = 0x00; write_mem_header_main(section, block_num, &write_header); write_mem_header_status(section, block_num, write_header.status); for (uint8_t field_num = 0; field_num < section->fields_per_block; field_num++) { write_mem_field(section, block_num, field_num, write_fields_1[field_num]); } ASSERT_EQ(block_num,0); read_mem_data_block(section, block_num, &read_header, read_fields_1); ASSERT_EQ(block_num,0); ASSERT_EQ(write_header.block_num, read_header.block_num); ASSERT_EQ(write_header.status, read_header.status); for (uint8_t i=0; i<obc_hk_mem_section.fields_per_block; i++){ ASSERT_EQ(write_fields_1[i], read_fields_1[i]); } //test eps housekeeping section = all_mem_sections[1]; section->curr_block = 0;// block_num = section->curr_block; write_header.block_num = section->curr_block; write_header.date = rand_rtc_date(); write_header.time = rand_rtc_time(); write_header.status = 0x00; write_mem_header_main(section, block_num, &write_header); write_mem_header_status(section, block_num, write_header.status); for (uint8_t field_num = 0; field_num < section->fields_per_block; field_num++) { write_mem_field(section, block_num, field_num, write_fields_2[field_num]); } ASSERT_EQ(block_num,0); read_mem_data_block(section, block_num, &read_header, read_fields_2); ASSERT_EQ(block_num,0); ASSERT_EQ(write_header.block_num, read_header.block_num); ASSERT_EQ(write_header.status, read_header.status); for (uint8_t i=0; i<eps_hk_mem_section.fields_per_block; i++){ ASSERT_EQ(write_fields_2[i], read_fields_2[i]); } //test pay housekeeping section = all_mem_sections[2]; section->curr_block = 0;// block_num = section->curr_block; write_header.block_num = section->curr_block; write_header.date = rand_rtc_date(); write_header.time = rand_rtc_time(); write_header.status = 0x00; write_mem_header_main(section, block_num, &write_header); write_mem_header_status(section, block_num, write_header.status); for (uint8_t field_num = 0; field_num < section->fields_per_block; field_num++) { write_mem_field(section, block_num, field_num, write_fields_3[field_num]); } ASSERT_EQ(block_num,0); read_mem_data_block(section, block_num, &read_header, read_fields_3); ASSERT_EQ(block_num,0); ASSERT_EQ(write_header.block_num, read_header.block_num); ASSERT_EQ(write_header.status, read_header.status); for (uint8_t i=0; i<pay_hk_mem_section.fields_per_block; i++){ ASSERT_EQ(write_fields_3[i], read_fields_3[i]); } //test pay optical section = all_mem_sections[3]; section->curr_block = 0;// block_num = section->curr_block; write_header.block_num = section->curr_block; write_header.date = rand_rtc_date(); write_header.time = rand_rtc_time(); write_header.status = 0x00; write_mem_header_main(section, block_num, &write_header); write_mem_header_status(section, block_num, write_header.status); for (uint8_t field_num = 0; field_num < section->fields_per_block; field_num++) { write_mem_field(section, block_num, field_num, write_fields_4[field_num]); } ASSERT_EQ(block_num,0); read_mem_data_block(section, block_num, &read_header, read_fields_4); ASSERT_EQ(block_num,0); ASSERT_EQ(write_header.block_num, read_header.block_num); ASSERT_EQ(write_header.status, read_header.status); for (uint8_t i=0; i<pay_opt_mem_section.fields_per_block; i++){ ASSERT_EQ(write_fields_4[i], read_fields_4[i]); } } void section_byte_isolation_test(void) { erase_mem(); uint8_t ones[10]; populate_ones(ones, 10); // Write PAY_HK uint8_t write_pay_hk[5] = {0x00}; for (uint8_t i = 0; i < 5; i++) { write_pay_hk[i] = i + 50; } uint8_t read_pay_hk[5] = {0x00}; read_mem_section_bytes(&pay_hk_mem_section, 0, read_pay_hk, 5); ASSERT_EQ_ARRAY(read_pay_hk, ones, 5); ASSERT_TRUE(write_mem_section_bytes(&pay_hk_mem_section, 0, write_pay_hk, 5)); read_mem_section_bytes(&pay_hk_mem_section, 0, read_pay_hk, 5); ASSERT_EQ_ARRAY(read_pay_hk, write_pay_hk, 5); // Write EPS_HK, don't overwrite PAY_HK // Address offset from beginning of EPS_HK, should be 0x0FFFFB uint32_t eps_hk_section_addr = eps_hk_mem_section.end_addr - eps_hk_mem_section.start_addr - 4; uint8_t write_eps_hk[10] = {0x00}; for (uint8_t i = 0; i < 10; i++) { write_eps_hk[i] = i + 13; } uint8_t read_eps_hk[10] = {0x00}; read_mem_section_bytes(&eps_hk_mem_section, eps_hk_section_addr, read_eps_hk, 5); ASSERT_EQ_ARRAY(read_eps_hk, ones, 5); uint32_t full_write_start_addr = eps_hk_section_addr + eps_hk_mem_section.start_addr; ASSERT_FALSE(write_mem_section_bytes(&eps_hk_mem_section, eps_hk_section_addr, write_eps_hk, 10)); erase_mem_sector(full_write_start_addr); ASSERT_FALSE(write_mem_section_bytes(&eps_hk_mem_section, eps_hk_section_addr, write_eps_hk, 6)); erase_mem_sector(full_write_start_addr); ASSERT_TRUE(write_mem_section_bytes(&eps_hk_mem_section, eps_hk_section_addr, write_eps_hk, 5)); read_mem_section_bytes(&eps_hk_mem_section, eps_hk_section_addr, read_eps_hk, 5); ASSERT_EQ_ARRAY(read_eps_hk, write_eps_hk, 5); // Check that PAY_HK is unchanged read_mem_section_bytes(&pay_hk_mem_section, 0, read_pay_hk, 5); ASSERT_EQ_ARRAY(read_pay_hk, write_pay_hk, 5); } void cmd_block_test(void) { erase_mem(); // eps_hk_mem_section mem_header_t write_header = { .block_num = prim_cmd_log_mem_section.curr_block, .date = rand_rtc_date(), .time = rand_rtc_time(), .status = 0x00, }; mem_header_t read_header; uint32_t block_num; uint16_t write_cmd_num; uint8_t write_opcode; uint32_t write_arg1; uint32_t write_arg2; uint16_t read_cmd_num; uint8_t read_opcode; uint32_t read_arg1; uint32_t read_arg2; block_num = 13542; write_cmd_num = 5; write_opcode = 1; write_arg1 = 1000000000; write_arg2 = 132497; ASSERT_TRUE(write_mem_cmd_block(&prim_cmd_log_mem_section, block_num, &write_header, write_cmd_num, write_opcode, write_arg1, write_arg2)); write_mem_header_status(&prim_cmd_log_mem_section, block_num, write_header.status); read_mem_cmd_block(&prim_cmd_log_mem_section, block_num, &read_header, &read_cmd_num, &read_opcode, &read_arg1, &read_arg2); ASSERT_EQ(write_header.block_num, read_header.block_num); ASSERT_EQ(write_header.status, read_header.status); ASSERT_EQ_DATE(write_header.date, read_header.date); ASSERT_EQ_TIME(write_header.time, read_header.time); ASSERT_EQ(write_cmd_num, read_cmd_num); ASSERT_EQ(write_opcode, read_opcode); ASSERT_EQ(write_arg1, read_arg1); ASSERT_EQ(write_arg2, read_arg2); block_num = 1000000; ASSERT_FALSE(write_mem_cmd_block(&prim_cmd_log_mem_section, block_num, &write_header, write_cmd_num, write_opcode, write_arg1, write_arg2)); write_mem_header_status(&prim_cmd_log_mem_section, block_num, write_header.status); } /* Test the ability to erase a 4kb sector of memory given an address */ void mem_sector_erase_test(void){ uint8_t data[DATA_LENGTH] = {0xAA, 0xBB, 0xCC, 0xDD, 0xEE}; uint8_t read[1] = {0}; /* Generate random address by seeding and calling random */ uint32_t address = random() % MEM_NUM_ADDRESSES; /* Write to location in sector and verify that write worked */ write_mem_bytes(address, data, DATA_LENGTH); for (uint32_t i = address; i < address + DATA_LENGTH; i++){ read_mem_bytes(i, read, 1); ASSERT_EQ(read[0], data[i-address]); } /* Erase sector */ erase_mem_sector(address); /* Read written bits in sector and verify that bits are all one */ for (uint32_t i = address; i < address + DATA_LENGTH; i++){ read_mem_bytes(i, read, 1); ASSERT_EQ(read[0], 0xFF); } } /* Test the ability to erase a block of memory given an address */ void mem_block_erase_test(void){ uint8_t data[DATA_LENGTH] = {0xAA, 0xBB, 0xCC, 0xDD, 0xEE}; uint8_t read[1] = {0}; uint32_t address = random() % MEM_NUM_ADDRESSES; /* Write to location in block and verify that write worked */ write_mem_bytes(address, data, DATA_LENGTH); for (uint32_t i = address; i < address + DATA_LENGTH; i++){ read_mem_bytes(i, read, 1); ASSERT_EQ(read[0], data[i-address]); } /* Erase block */ erase_mem_block(address); /* Read written bits in block and verify that bits are all one */ for (uint32_t i = address; i < address + DATA_LENGTH; i++){ read_mem_bytes(i, read, 1); ASSERT_EQ(read[0], 0xFF); } } test_t t1 = { .name = "erase mem test", .fn = erase_mem_test }; test_t t2 = { .name = "single write read test", .fn = single_write_read_test }; test_t t3 = { .name = "multiple write read test", .fn = multiple_write_read_test }; test_t t4 = { .name = "multiple write read test 2", .fn = multiple_write_read_test_2 }; test_t t5 = { .name = "random read write test", .fn = random_read_write_test }; test_t t6 = { .name = "rollover test", .fn = roll_over_test }; test_t t7 = { .name = "eeprom test", .fn = eeprom_test }; test_t t8 = { .name = "mem header test", .fn = mem_header_test }; test_t t9 = { .name = "mem field test", .fn = mem_field_test }; test_t t10 = { .name = "mem block test 1", .fn = mem_block_test_1 }; test_t t11 = { .name = "mem block test 2", .fn = mem_block_test_2 }; test_t t12 = { .name = "section byte isolation test", .fn = section_byte_isolation_test }; test_t t13 = { .name = "cmd block test", .fn = cmd_block_test }; test_t t14 = { .name = "sector erase test", .fn = mem_sector_erase_test }; test_t t15 = { .name = "block erase test", .fn = mem_block_erase_test }; test_t* suite[] = { &t1, &t2, &t3, &t4, &t5, &t6, &t7, &t8, &t9, &t10, &t11, &t12, &t13, &t14, &t15 }; int main(void) { init_uart(); init_spi(); init_mem(); run_tests(suite, sizeof(suite) / sizeof(suite[0])); return 0; }
C
#include <stdlib.h> #include <comp421/hardware.h> #include <comp421/yalnix.h> /** * Forks a child process which then goes and calls Exec() and runs another * process. The parent returns. * * Expected Output: * Will print a starting message, then either parent or child prints. If the * child executes first out of the fork, then the output of the exec-ed file * is output. * Should see calls to exit from both processes * * Requires: * Fork, Exec, Exit */ extern int main() { char *filename = "test_exec"; char *argvec[] = { "Hello", "I'm", "test", "args", NULL}; TracePrintf(0, "Starting forktest program\n"); TracePrintf(0, "PID: %d\n", GetPid()); if (Fork()) { TracePrintf(0, "I'm the parent, PID: %d\n", GetPid()); } else { TracePrintf(0, "I'm the child, PID: %d\n", GetPid()); Exec(filename, argvec); } return(0); }
C
/* * ===================================================================================== * * Filename: Communication.c * * Description: * * Version: 1.0 * Created: 10/10/12 22:51:16 * Revision: none * Compiler: gcc * * Author: (), * Company: NDSL UESTC * * ===================================================================================== */ #include "Communication.h" #include "Epoll.h" int create_pipes(int epoll_fd) { int pipe_fds[2]; if(pipe(pipe_fds) < 0) { LOG_ERROR("create pipe 1 error : %s" , strerror(errno)); return -1; } (g_global_value.thread_to_main)[0] = pipe_fds[0]; (g_global_value.thread_to_main)[1] = pipe_fds[1]; /* if(setNonblock(pipe_fds[0]) < 0) { LOG_ERROR("set fd %d to nonblock error!" , pipe_fds[0]); return -1; } */ if(add_to_epoll(epoll_fd , pipe_fds[0] , EPOLLIN , NULL) < 0) { LOG_ERROR("add thread to main read fd %d to epoll error!" , pipe_fds[0]); return -1; } if(pipe(pipe_fds) < 0) { LOG_ERROR("create pipe 2 error : %s" , strerror(errno)); close_pipe(g_global_value.thread_to_main); return -1; } (g_global_value.main_to_thread)[0] = pipe_fds[0]; (g_global_value.main_to_thread)[1] = pipe_fds[1]; if(pipe(pipe_fds) < 0) { LOG_ERROR("create pipe 3 error : %s" , strerror(errno)); close_pipe(g_global_value.main_to_thread); close_pipe(g_global_value.thread_to_main); return -1; } (g_global_value.wakeup_and_block)[0] = pipe_fds[0]; (g_global_value.wakeup_and_block)[1] = pipe_fds[1]; return 0; } void close_pipe(int *pipe_fds) { close(pipe_fds[0]); close(pipe_fds[1]); } //需要通知子线程阻塞 int notice_thread_blocking() { int notice_word = STOP_CHAR; if(write_to_thread_blocking(g_global_value.main_to_thread[1] , &notice_word , sizeof(notice_word)) < 0) //向这个管道写入阻塞字符 { LOG_ERROR("In notice_thread_blocking : write block word %d to thread error !" , notice_word); return -1; } return 0; } int notice_thread_working() { char notice_word = CONT_CHAR; if(write_to_thread_blocking(g_global_value.wakeup_and_block[1] , &notice_word , sizeof(notice_word)) < 0) { LOG_ERROR("In notice_thread_working : write continue word %c to thread error !" , notice_word); return -1; } return 0; } int notice_thread_new_bucket(int bucket_nr) { if(write_to_thread_blocking(g_global_value.main_to_thread[1] , &bucket_nr , sizeof(bucket_nr)) < 0) { LOG_ERROR("In notice_thread_new_bucket : write bucket No.%d to thread error !" , bucket_nr); return -1; } return 0; } int notice_thread_start_recycle() { int notice_word = START_CHAR; if(write_to_thread_blocking(g_global_value.main_to_thread[1] , &notice_word , sizeof(notice_word)) < 0) { LOG_ERROR("In notice_thread_start_recycle : write thread start recycle %d error !" , notice_word); return -1; } return 0; } //子线程完成了一个桶,需要将这个桶号发送给主线程 int deal_with_thread_notice(int fd) { int bucket_nr; int read_ret = read_from_thread_blocking(fd , &bucket_nr); if(read_ret < 0) { LOG_ERROR("In deal_with_thread_notice : read data from pipe error !"); return -1; } else if(1 == read_ret) { LOG_WARNING_TIME("In deal_with_thread_notice : thread close pipe !!!"); return 1; } if(FINISH_ALL == bucket_nr) { g_global_value.I_finish = 1; return 0; } if(list_append_value(g_global_value.finish_bucket_list , bucket_nr) < 0) { LOG_ERROR("In deal_with_thread_notice : add new bucket No.%d to finish error !" , bucket_nr); return -1; } return 0; } //查看是否子线程需要暂停,返回0说明不需要暂停,否则继续 //返回值有三个: //返回-1说明需要子线程阻塞! //返回0说明主线程不需要子线程阻塞 //返回1说明主线程关闭了管道 int thread_check_waiting(int *read_value) { int read_fd = g_global_value.main_to_thread[0]; int need_wait = 0; int read_ret = -1; RE_READ : read_ret = read(read_fd , &need_wait , sizeof(need_wait)); if(read_ret < 0) { if(EINTR == errno) goto RE_READ; else if(EAGAIN == errno) //非阻塞读取,返回EAGAIN说明不需要暂停 { *read_value = -1; return 0; } else { LOG_ERROR("In check_waiting : nonblocking read pipe1 error : %s" , strerror(errno)); return -1; } } else if(0 == read_ret) { LOG_WARNING_TIME("In check_waiting : Never Happen ! main close pipe1!!!"); return 1; } else if(STOP_CHAR == need_wait) //需要暂停 { return -1; } else { *read_value = need_wait; return 0; } return 0; } int thread_wait_main_wakeup() { char restart_char = 0; int read_fd = g_global_value.wakeup_and_block[0]; int read_ret = -1; RE_RRAD: read_ret = read(read_fd , &restart_char , sizeof(restart_char)); if(read_ret < 0) { if(EINTR == errno) goto RE_RRAD; else { LOG_ERROR("In thread_wait_main_wakeup : read pipe3 fd %d error : %s" , read_fd , strerror(errno)); return -1; } } else if(0 == read_ret) { LOG_ERROR_TIME("In thread_wait_main_wakeup : Never Happen ! main close pipe3!!!"); return 1; } else { if(CONT_CHAR == restart_char) return 0; else { LOG_INFO("Read from pipe3 , read : %c" , restart_char); goto RE_RRAD; } } return 0; }
C
#include <stdio.h> #include <stdlib.h> int bill(int units) { int bill, totalbill; if (units < 30) { bill = units*8; } else if (units < 60) { bill = (29*8) + (units-30)*15; } else if (units < 90) { bill = (29*8) + (29*15) + (units-60)*20; } else { bill = (29*8) + (29*15) + (29*20) + (units-90)*30; } totalbill = bill + 200; return totalbill; } int main() { int units; printf ("Enter your units consumption: "); scanf ("%d",&units); printf ("\nYour bill amount: %d",bill(units)); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <signal.h> #include <sys/types.h> #include <unistd.h> int ctrl_c_counter = 0; unsigned int time_passed = 0; void handler_sigint(int signum) { printf("Passaram %u segundos\n", time_passed); ctrl_c_counter++; } void handler_sigquit(int signum) { printf("Clicou %d vezes em CTRL+C", ctrl_c_counter); exit(0); } void handler_sigalrm(int signum) { time_passed++; alarm(1); } int main(int argc, const char* argv[]) { if (signal(SIGINT, handler_sigint) == SIG_ERR) { perror("SIGINT failed"); } if (signal(SIGQUIT, handler_sigquit) == SIG_ERR) { perror("SIGOUT failed"); } if (signal(SIGALRM, handler_sigalrm) == SIG_ERR) { perror("SIGOUT failed"); } alarm(1); while (1) { pause(); } }
C
#include "../minishell.h" static void ft_dollar_start(int *i, char **str, t_struct *env, int *flag) { int start; int finish; start = 0; finish = 0; if (!(*flag) && (*str)[*i] == '\'') *flag = 1; else if ((*flag) && (*str)[*i] == '\'') *flag = 0; else if (!(*flag) && (*str)[*i] == '$' && !ft_isspace((*str)[(*i) + 1])) { if ((*str)[(*i) + 1] == '?') *str = ft_status_dollar(*str, *i, env); else { start = *i; finish = ft_check_finish(*str, start); *str = ft_dollar_change(*str, start, finish, env); } (*flag) = 0; *i = -1; } } char *ft_check_dollar2(char *s, t_struct *env) { int i; int flag; char *str; i = 0; flag = 0; str = ft_strdup(s); free(s); while (str[i]) { ft_dollar_start(&i, &str, env, &flag); i++; } return (str); }
C
#include <stdio.h> int weight(int n, int w, int t[]){ if (w == 0){ return 1; } if (n == -1){ return 0; } return (weight(n-1,w-t[n],t) || (weight(n-1,w+t[n],t) == 1) || (weight(n-1,w,t) == 1)); return 0; } int main(){ int n,w; scanf("%d %d\n", &n, &w); int t[n]; int suma; for(int i=0;i<n;i++){ scanf("%d", &t[i]); suma += t[i]; } if (suma >= w){ if (weight(n-1,w,t) == 1){ printf("YES"); } else{ printf("NO"); } } else{ printf("NO"); } return 0; }
C
/** * @author : Niculescu Mihai Alexandru */ #include "utils.h" /** * implementarea pentru strdup, deoarece functia nu este in standard-ul C */ char *my_strdup(const char *string) { char *duplicat; int i, len = 0; while (string[len] != '\0') { ++len; } duplicat = (char *) malloc((len + 1) * sizeof(char)); if (duplicat != NULL) { for (i = 0; i < len; i++) { duplicat[i] = string[i]; } duplicat[len] = '\0'; } return duplicat; }
C
#include<stdio.h> #include<conio.h> #include<string.h> void main() { char a[100],b[100]; int l,t,p=0,k=0,i,j,flag=0,count=0; scanf("%s %s",a,b); l=strlen(a); t=strlen(b); while(p<l) { if(a[p]==b[k]) { count=0; for(i=p,j=0;i<p+t,j<t;i++,j++) { if(a[i]==b[j]) { count++; } } if(count==t) { printf("yes"); break; } else { flag++; } } p++; } if(flag>1) { printf("no"); } getch(); }
C
#include<stdio.h> int main() { int i,j,n; printf("Enter the number : "); scanf("%d",&n); printf("\n"); for(i=n;i>0;i--) { for (j=1;j<=n;j++) { if(j<i) { printf(" "); } else { printf(" |*|"); } } printf("\n"); } return 0; }
C
#ifndef _IBAARD_STRIP_H #define _IBAARD_STRIP_H /** @file * Functions to strip some characters from strings */ #if (defined _WIN32) || (defined _BROKEN_IO) #include <stdio.h> #endif /** Strip \\n from the end of a string * * @param buf the string to strip * @return a pointer to buf */ char *stripn(char *buf); /** Strip \\r\\n from the end of a string * * @param buf the string to strip * @return a pointer to buf */ char *striprn(char *buf); /** Strip 0x01 from the end of a string * * @param buf the string to strip * @return a pointer to buf */ char *stripa(char *buf); #endif
C
#include <stdio.h> #include <stdlib.h> struct node { int info; struct node *link; }; struct node *create(struct node *start); void compare(struct node *start); struct node *addtobeg(struct node *start, int data); struct node *addatend(struct node *start, int data); void compare(struct node *start) { struct node *p; int flag = 1; p = start; int max, min; while(p != NULL) { if(flag == 1) { max = p -> info; min = p -> info; flag = 0; } else { if(max < p -> info) max = p -> info; else if(min > p -> info) min = p -> info; } p = p -> link; } printf("%d\n", max); printf("%d\n", min); } struct node *create(struct node *start) { int i, n, data; printf("Enter the number of nodes"); scanf("%d", &n); start = NULL; if(n == 0) return start; printf("Enter the element to be inserted"); scanf("%d", &data); start = addtobeg(start, data); for(i = 2; i <= n; i++) { printf("Enter the element to be inserted"); scanf("%d", &data); start = addatend(start, data); } return start; } struct node *addtobeg(struct node *start, int data) { struct node *tmp; tmp = (struct node *)malloc(sizeof(struct node)); tmp -> info = data; tmp -> link = start; start = tmp; return start; } struct node *addatend(struct node *start, int data) { struct node *p, *tmp; tmp = (struct node *)malloc(sizeof(struct node)); tmp -> info = data; p = start; while(p -> link != NULL) p = p -> link; p -> link = tmp; tmp -> link = NULL; return start; } int main() { struct node *start = NULL; start = create(start); compare(start); return 0; }
C
#include<stdio.h> #include<string.h> int main() { char a[10]; int n,i,j,count=o; scanf("%s",s); n=strlen(a); for(i=0;i<=n;i++) { for(j=i+1;j<=n;j++) { ifa[i]=b[i] { count=1; break; } else { continue; } } } if(count==0) { printf("yes...isogram") } else { printf("no"); } return 0; }
C
// code.h Stan Eisenstat (09/23/08) // // Interface to putBits/getBits #include <limits.h> // Write code (#bits = nBits) to standard output. // [Since bits are written as CHAR_BIT-bit characters, any extra bits are // saved, so that final call must be followed by call to flushBits().] void putBits (int nBits, int code); // Flush any extra bits to standard output void flushBits (void); // Return next code (#bits = nBits) from standard input (EOF on end-of-file) int getBits (int nBits);
C
#include<stdio.h> int main() { int stack[5], top=-1, value, operation; printf("Enter 1 for push, 2 for pop, 3 to show the top.\n"); printf("-1 venge dite\n"); while(1) { printf("Choice koren: "); scanf("%d", &operation); if(operation ==-1) { printf("Venge gelo\n"); break; } if(operation == 1) { ///push printf("value den: "); top++; scanf("%d", &stack[top]); printf("Push hoise\n"); } else if(operation == 2) { ///Pop top--; printf("Pop hoise\n"); } else if(operation == 3) { ///Top printf("Top e ase: %d\n", stack[top]); } else { printf("Matha kharap hoise naki???? option dekhen nai????\n"); } } return 0; }
C
#include "../globals.h" void setup_Boss() { Problem.Periodic[0] = Problem.Periodic[1] = Problem.Periodic[2] = false; Problem.Boxsize[0] = 0.032; //5e16 cm in parsec Problem.Boxsize[1] = 0.032; Problem.Boxsize[2] = 0.032; sprintf ( Problem.Name, "IC_Boss" ); const double rho = 56458.857; // 3.82 *10e-18 in g/cm^3 in solar masses per cubic parsec Problem.Rho_Max = rho * 1.1; Density_Func_Ptr = &Boss_Density; } float Boss_Phi ( double const x, double const y ) { return atan2( y , x ); } /* At first we set up a constant density in the Box */ float Boss_Density ( const int ipart , const double bias ) { double const x = P[ipart].Pos[0] - Problem.Boxsize[0] * 0.5; double const y = P[ipart].Pos[1] - Problem.Boxsize[1] * 0.5; double const z = P[ipart].Pos[2] - Problem.Boxsize[2] * 0.5; double Radius = sqrt ( x*x + y*y + z*z ); const double rho = 56458.857; if ( Radius < 0.016 ) { return rho * ( 1 + 0.1 * cos ( 2 * Boss_Phi ( x, y ) ) ); } else { return rho * 0.05; } }
C
/* Ficheiro: fork.c Autor: João Caldeira / Knuckles / SaucyGoat (which one?) Este programa demonstra algumas operações básicas sobre processos. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> // para o fork() e o sleep() #include <sys/wait.h> // para o wait() #define MAX_ITER 3 /* RESUMO DO PROGRAMA Começamos por fazer a chamada de sistema fork() e guardar o seu valor de retorno. O processo criado (processo filho) é uma cópia do pai - o espaço de endereçamento e o contexto de execução são copiados. Qual será o valor de retorno da chamada fork()? - ao processo pai é devolvido o pid (process id) do filho - ao processo filho é devolvido 0 (zero) - caso a chamada de sistema falhe, é devolvido -1 Tendo dois processos a executar o mesmo código, teremos então 3 condições: - se o valor de retorno for igual a 0, trata-se do processo filho, e portanto o código executado será o que está incluído nessa condição - se o valor de retorno for superior a 0, temos o pid do filho, pelo que será o pai a executar o código incluído nessa condição - se o valor de retorno for inferior a 0, a chamada de sistema falhou e portanto terminamos o programa */ int main () { int r = fork(); // guardamos o valor de retorno do fork() if (r == 0) { // verificar se é o filho // CÓDIGO DO PROCESSO FILHO int i; // chamada de sistema que devolve o pid do processo printf("Filho:\tHello! Sou o filho com pid=%d.\n", getpid()); for (i = 0; i < MAX_ITER; i++) { sleep(1); printf("Filho:\tExisto há cerca de %d segundos!\n", i+1); } sleep(1); printf("Filho:\tMr. Stark, I don't feel so good... Vou terminar!\n"); // filho termina com sucesso exit(EXIT_SUCCESS); } else if (r > 0) { // verificar se é o pai // CÓDIGO DO PROCESSO PAI int status; int pid; printf("Pai:\tHello! Sou o pai que criou o filho pid=%d\n", r); // execução do pai é suspendida até que um dos seus filhos termine pid = wait(&status); /* - wait(): devolve o pid do filho que terminou, ou -1 caso ocorra um erro - WIFEXITED: devolve "true" caso o filho tenha terminado normalmente, "false" caso contrário - WEXITSTATUS: devolve o exit status do filho (em caso de sucesso, o valor é 0) */ if (WIFEXITED(status)) printf("Pai:\tFilho %d terminou com código de retorno %d.\n", pid, WEXITSTATUS(status)); else printf("Pai:\tFilho %d terminou abruptamente.\n", pid); // pai termina com sucesso exit(EXIT_SUCCESS); } else { // verificar se a chamada fork() deu erro printf("Oops! Erro no fork().\n"); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }
C
/* This is free and unencumbered software released into the public domain. */ /** * Compatibility shim for the GNU Multiple Precision Arithmetic Library (GMP). * * @author Arto Bendiken * @see https://drylib.org/xref/gmp.html * @see https://gmplib.org/repo/gmp/file/default/mini-gmp/mini-gmp.h */ #pragma once //////////////////////////////////////////////////////////////////////////////// #include <dry/base/integer.h> #include <stdarg.h> /* for va_list */ #include <stddef.h> /* for size_t */ //////////////////////////////////////////////////////////////////////////////// typedef dry_integer_t mpz_t[1]; //////////////////////////////////////////////////////////////////////////////// #ifdef __cplusplus extern "C" { #endif static inline void mpz_init(mpz_t x) { x->value = 0; } static inline void mpz_init_set_si(mpz_t rop, signed long int op) { rop->value = op; } static inline void mpz_clear(mpz_t x) { x->value = 0; } static inline long int mpz_get_si(const mpz_t op) { return (long int)op->value; } static inline void mpz_mul(mpz_t rop, const mpz_t op1, const mpz_t op2) { rop->value = op1->value * op2->value; } #ifdef __cplusplus } // extern "C" #endif
C
#include <math.h> #include "const.h" //general functions void mdelay(int milli_seconds); int a_gt_b(float a,float b); float max(float a,float b); float k_model(float speed,float throttle,float brake); void sevenseg_simulate(char bcd[8]); float calc_speed(long double time); long double calc_time(float speed); float smooth_speed(float speed[5]); void mdelay(int milli_seconds) { // Converting time into milli_seconds // Storing start time clock_t start_time = clock(); // looping till required time is not achieved while (clock() < start_time + milli_seconds) ; } int a_gt_b(float a,float b){ // function returns 1 if a is greater than b 0 otherwise if(a > b){ return 1; }else{ return 0; } } float max(float a,float b){ // function returns the max value of two inputs if(a>b){ return a; }else{ return b; } } void floattodig(float number){ float dig_vals[16] = {0.0,0.0625,0.125,0.1875,0.250,0.3125,0.375,0.4375,0.5,0.5625,0.625,0.6875,0.75,0.875,0.9375,1.0}; int bin_equiv[16][4] = {{0,0,0,0},{0,0,0,1},{0,0,1,0},{0,0,1,1},{0,1,0,0},{0,1,0,1},{0,1,1,0},{0,1,1,1},{1,0,0,0},{1,0,0,1},{1,0,1,0},{1,0,1,1},{1,1,0,0},{1,1,0,1},{1,1,1,0},{1,1,1,1}}; float min_sep = 1.0; int i,digital_equiv; for(i=0;i<16;i++){ if(fabs(number-dig_vals[i]) < min_sep){ digital_equiv = i; min_sep = fabs(number-dig_vals[i]); } } for(i=0;i<4;i++){ printf("%d ",bin_equiv[digital_equiv][i]); } } // models the speed of the tram based on current speed, throttle power and brake (boolean) // function needs to be called every clock cycle to be accurate // # defined values for kinetic coefficients are used // The trams speed is modelled in the following way: float k_model(float speed,float throttle,float brake){ double nspeed = speed/3.6; //convert to SI units float a = 0; if(throttle > 0.1){ nspeed = nspeed + throttle; }else{ nspeed = nspeed - FRICTION_CONSTANT; double ke = 0.5 * TRAM_MASS * nspeed*nspeed; float distance = nspeed; float aero_force = (0.5*AERO_CONSTANT*nspeed*nspeed); ke = ke - fabs(aero_force*distance); ke = ke - fabs(brake*(BRAKE_FORCE*distance)); nspeed = sqrt((2*ke)/TRAM_MASS); } return max((nspeed*3.6),0.1); } float stopping_distance(float speed,float brake){ float distance = 0.0; float curr_speed = speed; while(curr_speed > 1.0){ curr_speed = k_model(curr_speed,0.0,brake); distance = distance + curr_speed; } return distance; } float min_stopping_brake_force(float speed, float station_distance){ float i=0.1; float st_d = stopping_distance(speed,0.0); while((i<1.1) && (st_d>station_distance)){ st_d = stopping_distance(speed,i); i = i+0.1; } printf("Min braking force is %f\n",i); return i; } //simulate the 7seg display connected to a 4511 microcontroller void sevenseg_simulate(char bcd[8]){ int i = 0; int speed = 0; int tens = 0; int units = 0; int power; while(i<4){ power = pow(2,(3-i)); tens = tens + (bcd[i]-'0')*power; i++; } while(i<8){ power = pow(2,(3-(i-4))); units = units + (bcd[i]-'0')*power; i++; } speed = 10*tens+units; printf("Current Speed: %d\n",speed); } float calc_speed(long double time){ long double distance = WHEELD * 3.14159265 / 1000; float speed_ms = distance/time; float speed_kph = speed_ms * 3600 / 1000; return speed_kph; } // function returns the number of cycles to count for a given speed before the GPIO will change long double calc_time(float speed){ float nspeed = speed / 3600 * 1000; // SI speed of the tram long double distance = WHEELD * 3.14159265 / 1000; // distance for a full wheel revolution in m long double time; if(speed > 0.01){ time = distance / nspeed; // number of seconds for a full wheel revolution }else{ time = 10000.0000; } return time; } float smooth_speed(float speed[5]){ float avg_speed = 0.0; float residuals[5]; float avg_residual = 0; float max_residual = 0; int max_residual_index = 0; int i; i=0; while(i<5){ avg_speed = avg_speed + (5-i)*speed[i]; // 5x0 + 4x1 + 3x2 + 2x3 + 1x4 / 15 i++; } avg_speed = avg_speed/15; if((speed[0] > 0.0) && (speed[1] > 0.0) && (speed[2] == 0.0) && (speed[3] == 0.0)){ avg_speed = speed[0]; speed[1] = speed[0]; speed[2] = speed[0]; speed[3] = speed[0]; speed[4] = speed[0]; } i=0; while(i<5){ residuals[i] = (speed[i] - avg_speed)*(speed[i] - avg_speed); avg_residual = avg_residual + residuals[i]; if(residuals[i] > max_residual){ max_residual = residuals[i]; max_residual_index = i; } i++; } avg_residual = avg_residual/5; if((max_residual > (avg_speed/2)) && (avg_speed != 0.0)){ speed[max_residual_index] = avg_speed; avg_speed = smooth_speed(speed); } return avg_speed; } void sevenseg_print(int speed){ int units = speed%10; int tens = floor(speed - units)/10; char bcd[8]; int i = 0; int power; while(i < 4){ power = pow(2,(3-i)); bcd[i] = (tens/power)+'0'; tens = tens-(bcd[i]-'0')*power; i++; } while(i<8){ power = pow(2,(3-(i-4))); bcd[i] = (units/power)+'0'; units = units-(bcd[i]-'0')*power; i++; } sevenseg_simulate(bcd); }