language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include<stdio.h> int a[10]; int cg(int x,int y) {int tmp;tmp=a[x];a[x]=a[y];a[y]=tmp;} int main() { int i,j,k,min=0; for(i=0;i<10;i++)scanf("%d",&a[i]); for(i=0;i<10;i++)printf("%d ",a[i]); printf("\n"); for(i=0;i<9;i++) { min=i; for(j=i;j<10;j++) { if(a[min]>a[j])min=j; } if(min!=i)cg(min,i); } for(i=0;i<10;i++)printf("%d ",a[i]); printf("\n"); return 0; }
C
#include <stdio.h> #include <math.h> int main(){ float num; int interval = 0; char intSym; scanf("%f", &num); if(num <= 100 || num > 0){ interval = ceil(num/25); intSym = (interval-1) ? '(' : '['; printf("Intervalo %c%d,%d]\n", intSym, (interval-1) * 25, interval * 25); } else { printf("Fora de intervalo\n"); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "dk_tool.h" int main() { Node *theNode = NULL; FILE *afile = fopen("txt.txt","r"); if (afile != NULL) { //переменная, в которую поочередно будут помещаться считываемые байты char symbol; //чтение одного байта из файла //проверка на конец файла или ошибку чтения while ((symbol = fgetc(afile)) != EOF) { if (isalpha(symbol)) { while (isalpha(symbol)) { theNode = add(theNode, symbol); symbol = fgetc(afile); //чтение одного байта из файла } //проверяем что именно произошло:кончился файл //или это ошибка чтения if (theNode != NULL) { print(theNode); del(theNode); theNode = NULL; } } //если файл не закончился, и не было ошибки чтения //выводим код считанного символа на экран printf("%c", symbol); } //закрываем файл fclose(afile); } else { printf("No file\n"); return 1; } return; }
C
/* * reconstruction.c * Author: sunder */ #include "hype.h" //---------------------------------------------------------------------------- // Value of Nth Order basis functions //---------------------------------------------------------------------------- PetscReal basis(PetscReal x, PetscReal y, PetscInt n) { switch (n) { case 0: return 1.0; break; case 1: return x; break; case 2: return y; break; case 3: return x*x - 1./12.; break; case 4: return y*y - 1./12.; break; case 5: return x*y; break; case 6: return x*(x*x - 3./20.); break; case 7: return y*(y*y - 3./20.); break; case 8: return y*(x*x - 1./12.); break; case 9: return x*(y*y - 1./12.); break; default: return 0.0; } } //---------------------------------------------------------------------------- // Gradients of Nth Order basis functions //---------------------------------------------------------------------------- void basis_grad(PetscReal x, PetscReal y, PetscInt n, PetscReal* grad_x, PetscReal* grad_y) { switch (n) { case 0: *grad_x = 0.0; *grad_y = 0.0; break; case 1: *grad_x = 1.0; *grad_y = 0.0; break; case 2: *grad_x = 0.0; *grad_y = 1.0; break; case 3: *grad_x = 2.0*x; *grad_y = 0.0; break; case 4: *grad_x = 0.0; *grad_y = 2.0*y; break; case 5: *grad_x = y; *grad_y = x; break; case 6: *grad_x = 3.0*x*x - 3./20.; *grad_y = 0.0; ; break; case 7: *grad_x = 0.0; *grad_y = 3.0*y*y - 3./20.; break; case 8: *grad_x = 2.0*x*y; *grad_y = (x*x - 1./12.); break; case 9: *grad_x = (y*y - 1./12.); *grad_y = 2.0*x*y; break; default: *grad_x = 0.0; *grad_y = 0.0; } } //---------------------------------------------------------------------------- // Minmod slope limiter //---------------------------------------------------------------------------- PetscReal minmod(PetscReal a, PetscReal b) { if (a*b < 0.0) { return 0.0; } else { if (PetscAbsReal(a) < PetscAbsReal(b) ) return a; else return b; } } //---------------------------------------------------------------------------- // 2D 3th order WENO reconstruction //---------------------------------------------------------------------------- PetscReal pow4(PetscReal a) { PetscReal a2 = a*a; return a2*a2; } void weno2(const PetscReal* U_x, const PetscReal* U_y, const PetscReal* U_xy, PetscReal* coeffs, PetscReal* u_coeffs) { PetscReal u_0 = U_xy[0]; PetscReal u_ip1 = U_x[3]; PetscReal u_jp1 = U_y[3]; PetscReal u_im1 = U_x[1]; PetscReal u_jm1 = U_y[1]; coeffs[0] = u_0; coeffs[1] = minmod(u_ip1-u_0,u_0-u_im1); coeffs[2] = minmod(u_jp1-u_0,u_0-u_jm1); u_coeffs[0] = u_0; u_coeffs[1] = 0.5*(u_ip1-u_im1); u_coeffs[2] = 0.5*(u_jp1-u_jm1); } void weno3(const PetscReal* U_x, const PetscReal* U_y, const PetscReal* U_xy, PetscReal* coeffs, PetscReal* u_coeffs) { const PetscReal central_cell_wt = 100.0; PetscReal u_0 = U_xy[0]; PetscReal u_ip1 = U_x[3]; PetscReal u_jp1 = U_y[3]; PetscReal u_ip1jp1 = U_xy[1]; PetscReal u_im1 = U_x[1]; PetscReal u_jm1 = U_y[1]; PetscReal u_ip1jm1 = U_xy[2]; PetscReal u_ip2 = U_x[4]; PetscReal u_jp2 = U_y[4]; PetscReal u_im1jp1 = U_xy[3]; PetscReal u_im2 = U_x[0]; PetscReal u_jm2 = U_y[0]; PetscReal u_im1jm1 = U_xy[4]; PetscReal u_x[3]; PetscReal u_xx[3]; PetscReal u_xy[4]; PetscReal wt[4]; PetscReal IS[4]; PetscReal total, temp; // Reconstruct in x-direction u_x[0] = -2.0*u_im1 + 0.5*u_im2 + 1.5*u_0; u_xx[0] = 0.5*(u_im2 - 2.0*u_im1 + u_0); u_x[1] = 0.5*(u_ip1 - u_im1); u_xx[1] = 0.5*(u_im1 - 2.0*u_0 + u_ip1); u_x[2] = -1.5*u_0 + 2.0*u_ip1 - 0.5*u_ip2; u_xx[2] = 0.5*(u_0 - 2.0*u_ip1 + u_ip2); IS[0] = u_x[0]*u_x[0] + r13_3*u_xx[0]*u_xx[0]; wt[0] = 1.0/( pow4(IS[0] + small_num) ); IS[1] = u_x[1]*u_x[1] + r13_3*u_xx[1]*u_xx[1]; wt[1] = central_cell_wt/( pow4(IS[1] + small_num) ); IS[2] = u_x[2]*u_x[2] + r13_3*u_xx[2]*u_xx[2]; wt[2] = 1.0/( pow4(IS[2] + small_num) ); total = wt[0] + wt[1] + wt[2]; wt[0] = wt[0]/total; wt[1] = wt[1]/total; wt[2] = wt[2]/total; u_coeffs[0] = u_0; u_coeffs[1] = u_x[1]; u_coeffs[3] = u_xx[1]; coeffs[0] = u_0; coeffs[1] = wt[0]*u_x[0] + wt[1]*u_x[1] + wt[2]*u_x[2]; coeffs[3] = wt[0]*u_xx[0] + wt[1]*u_xx[1] + wt[2]*u_xx[2]; // Reconstruct in y-direction u_x[0] = -2.0*u_jm1 + 0.5*u_jm2 + 1.5*u_0; u_xx[0] = 0.5*(u_jm2 - 2.0*u_jm1 + u_0); u_x[1] = 0.5*(u_jp1 - u_jm1); u_xx[1] = 0.5*(u_jm1 - 2.0*u_0 + u_jp1); u_x[2] = -1.5*u_0 + 2.0*u_jp1 - 0.5*u_jp2; u_xx[2] = 0.5*(u_0 - 2.0*u_jp1 + u_jp2); IS[0] = u_x[0]*u_x[0] + r13_3*u_xx[0]*u_xx[0]; wt[0] = 1.0/( pow4(IS[0] + small_num) ); IS[1] = u_x[1]*u_x[1] + r13_3*u_xx[1]*u_xx[1]; wt[1] = central_cell_wt/( pow4(IS[1] + small_num) ); IS[2] = u_x[2]*u_x[2] + r13_3*u_xx[2]*u_xx[2]; wt[2] = 1.0/( pow4(IS[2] + small_num) ); total = wt[0] + wt[1] + wt[2]; wt[0] = wt[0]/total; wt[1] = wt[1]/total; wt[2] = wt[2]/total; u_coeffs[2] = u_x[1]; u_coeffs[4] = u_xx[1]; coeffs[2] = wt[0]*u_x[0] + wt[1]*u_x[1] + wt[2]*u_x[2]; coeffs[4] = wt[0]*u_xx[0] + wt[1]*u_xx[1] + wt[2]*u_xx[2]; // Reconstruction in xy-direction u_xy[0] = u_ip1jp1 - u_0 - coeffs[1] - coeffs[2] - coeffs[3] - coeffs[4]; u_xy[1] = -u_ip1jm1 + u_0 + coeffs[1] - coeffs[2] + coeffs[3] + coeffs[4]; u_xy[2] = -u_im1jp1 + u_0 - coeffs[1] + coeffs[2] + coeffs[3] + coeffs[4]; u_xy[3] = u_im1jm1 - u_0 + coeffs[1] + coeffs[2] - coeffs[3] - coeffs[4]; temp = 4.0*(coeffs[3]*coeffs[3] + coeffs[4]*coeffs[4]); IS[0] = temp + u_xy[0]*u_xy[0]; wt[0] = 1.0/(pow4(IS[0] + small_num)); IS[1] = temp + u_xy[1]*u_xy[1]; wt[1] = 1.0/(pow4(IS[1] + small_num)); IS[2] = temp + u_xy[2]*u_xy[2]; wt[2] = 1.0/(pow4(IS[2] + small_num)); IS[3] = temp + u_xy[3]*u_xy[3]; wt[3] = 1.0/(pow4(IS[3] + small_num)); total = wt[0] + wt[1] + wt[2] + wt[3]; wt[0] = wt[0]/total; wt[1] = wt[1]/total; wt[2] = wt[2]/total; wt[3] = wt[3]/total; u_coeffs[5] = 0.25*(u_ip1jp1 - u_ip1jm1 - u_im1jp1 + u_im1jm1); coeffs[5] = wt[0]*u_xy[0] + wt[1]*u_xy[1] + wt[2]*u_xy[2] + wt[3]*u_xy[3]; } void weno4(const PetscReal* U_x, const PetscReal* U_y, const PetscReal* U_xy, PetscReal* coeffs, PetscReal* u_coeffs) { PetscReal gammaHi = 0.85; PetscReal gammaLo = 0.85; PetscReal u_0 = U_xy[0]; PetscReal u_ip1 = U_x[3]; PetscReal u_jp1 = U_y[3]; PetscReal u_ip1jp1 = U_xy[1]; PetscReal u_im1 = U_x[1]; PetscReal u_jm1 = U_y[1]; PetscReal u_ip1jm1 = U_xy[2]; PetscReal u_ip2 = U_x[4]; PetscReal u_jp2 = U_y[4]; PetscReal u_im1jp1 = U_xy[3]; PetscReal u_im2 = U_x[0]; PetscReal u_jm2 = U_y[0]; PetscReal u_im1jm1 = U_xy[4]; PetscReal u_xR4, u_yR4, u_xxR4, u_yyR4, u_xyR4, u_xxxR4, u_yyyR4, u_xxyR4, u_xyyR4; PetscReal u_xR3[5]; PetscReal u_yR3[5]; PetscReal u_xxR3[5]; PetscReal u_yyR3[5]; PetscReal u_xyR3[5]; PetscReal IS_R4; PetscReal gamma_R4; PetscReal w_R4; PetscReal IS_R3[5]; PetscReal gamma_R3[5]; PetscReal w_R3[5]; PetscReal sum = 0.0; PetscReal wt_ratio; PetscInt i; gamma_R4 = gammaHi; gamma_R3[0] = (1.0 - gammaHi)*gammaLo; for (i = 1 ; i < 5; ++i) gamma_R3[i] = 0.25*(1-gammaHi)*(1-gammaLo); // Fourth order stencil u_xR4 = r41_60*(-u_im1 + u_ip1) + r11_120*(u_im2 - u_ip2); u_yR4 = r41_60*(-u_jm1 + u_jp1) + r11_120*(u_jm2 - u_jp2); u_xxR4 = -u_0 + 0.5*(u_im1 + u_ip1); u_yyR4 = -u_0 + 0.5*(u_jm1 + u_jp1); u_xyR4 = 0.25*(u_im1jm1 - u_im1jp1 - u_ip1jm1 + u_ip1jp1); u_xxxR4 = r1_6*(u_im1 - u_ip1) + r1_12*(u_ip2 - u_im2); u_yyyR4 = r1_6*(u_jm1 - u_jp1) + r1_12*(u_jp2 - u_jm2); u_xxyR4 = 0.25*(-u_im1jm1 + u_im1jp1 - u_ip1jm1 + u_ip1jp1) + 0.5*(u_jm1 - u_jp1); u_xyyR4 = 0.5*(u_im1 - u_ip1) + 0.25*(u_ip1jp1 - u_im1jm1 - u_im1jp1 + u_ip1jm1); u_coeffs[0] = u_0; u_coeffs[1] = u_xR4; u_coeffs[2] = u_yR4; u_coeffs[3] = u_xxR4; u_coeffs[4] = u_yyR4; u_coeffs[5] = u_xyR4; u_coeffs[6] = u_xxxR4; u_coeffs[7] = u_yyyR4; u_coeffs[8] = u_xxyR4; u_coeffs[9] = u_xyyR4; IS_R4 = (u_xR4 + 0.1*u_xxxR4)*(u_xR4 + 0.1*u_xxxR4) + r13_3*(u_xxR4*u_xxR4 + u_yyR4*u_yyR4) + (u_yR4 + 0.1*u_yyyR4)*(u_yR4 + 0.1*u_yyyR4) + 39.05*(u_xxxR4*u_xxxR4 + u_yyyR4*u_yyyR4) + r7_6*u_xyR4*u_xyR4 + 4.7*(u_xxyR4*u_xxyR4 + u_xyyR4*u_xyyR4); w_R4 = gamma_R4/(pow4(IS_R4 + small_num)); sum = w_R4; // Stencil 1 (centered stencil) u_xR3[0] = 0.5*(-u_im1 + u_ip1); u_yR3[0] = 0.5*(-u_jm1 + u_jp1); u_xxR3[0] = -u_0 + 0.5*(u_im1 + u_ip1); u_yyR3[0] = -u_0 + 0.5*(u_jm1 + u_jp1); u_xyR3[0] = 0.25*(u_im1jm1 - u_im1jp1 - u_ip1jm1 + u_ip1jp1); // Stencil 2 (left biased stencil) u_xR3[1] = 1.5*u_0 - 2.0*u_im1 + 0.5*u_im2; u_yR3[1] = 0.5*(-u_jm1 + u_jp1); u_xxR3[1] = 0.5*u_0 - u_im1 + 0.5*u_im2; u_yyR3[1] = -u_0 + 0.5*u_jm1 + 0.5*u_jp1; u_xyR3[1] = 0.5*(u_im1jm1 - u_im1jp1 - u_jm1 + u_jp1); // Stencil 3 (right biased stencil) u_xR3[2] = -1.5*u_0 + 2.0*u_ip1 - 0.5*u_ip2; u_yR3[2] = 0.5*(-u_jm1 + u_jp1); u_xxR3[2] = 0.5*u_0 - u_ip1 + 0.5*u_ip2; u_yyR3[2] = -u_0 + 0.5*u_jm1 + 0.5*u_jp1; u_xyR3[2] = 0.5*(-u_ip1jm1 + u_ip1jp1 + u_jm1 - u_jp1); // Stencil 4 (bottom biased stencil) u_xR3[3] = 0.5*(-u_im1 + u_ip1); u_yR3[3] = 1.5*u_0 - 2.0*u_jm1 + 0.5*u_jm2; u_xxR3[3] = -u_0 + 0.5*u_im1 + 0.5*u_ip1; u_yyR3[3] = 0.5*u_0 - u_jm1 + 0.5*u_jm2; u_xyR3[3] = 0.5*(-u_im1 + u_im1jm1 + u_ip1 - u_ip1jm1); // Stencil 5 (top biased stencil) u_xR3[4] = 0.5*(-u_im1 + u_ip1); u_yR3[4] = -1.5*u_0 + 2.0*u_jp1 - 0.5*u_jp2; u_xxR3[4] = -u_0 + 0.5*u_im1 + 0.5*u_ip1; u_yyR3[4] = 0.5*u_0 - u_jp1 + 0.5*u_jp2; u_xyR3[4] = 0.5*(u_im1 - u_im1jp1 - u_ip1 + u_ip1jp1); // Find the smoothness indicators for (i = 0; i < 5; ++i) { IS_R3[i] = u_xR3[i]*u_xR3[i] + u_yR3[i]*u_yR3[i] + r13_3*(u_xxR3[i]*u_xxR3[i] + u_yyR3[i]*u_yyR3[i]) + r7_6*u_xyR3[i]*u_xyR3[i]; w_R3[i] = gamma_R3[i]/(pow4(IS_R3[i] + small_num)); sum += w_R3[i]; } // Normalize the weights w_R4 = w_R4/sum; for (i = 0; i < 5; ++i) w_R3[i] = w_R3[i]/sum; wt_ratio = w_R4/gamma_R4; coeffs[0] = u_0; coeffs[1] = wt_ratio*(u_xR4 - gamma_R3[0]*u_xR3[0] - gamma_R3[1]*u_xR3[1] - gamma_R3[2]*u_xR3[2] - gamma_R3[3]*u_xR3[3] - gamma_R3[4]*u_xR3[4]) + w_R3[0]*u_xR3[0] + w_R3[1]*u_xR3[1] + w_R3[2]*u_xR3[2] + w_R3[3]*u_xR3[3] + w_R3[4]*u_xR3[4]; coeffs[2] = wt_ratio*(u_yR4 - gamma_R3[0]*u_yR3[0] - gamma_R3[1]*u_yR3[1] - gamma_R3[2]*u_yR3[2] - gamma_R3[3]*u_yR3[3] - gamma_R3[4]*u_yR3[4]) + w_R3[0]*u_yR3[0] + w_R3[1]*u_yR3[1] + w_R3[2]*u_yR3[2] + w_R3[3]*u_yR3[3] + w_R3[4]*u_yR3[4]; coeffs[3] = wt_ratio*(u_xxR4 - gamma_R3[0]*u_xxR3[0] - gamma_R3[1]*u_xxR3[1] - gamma_R3[2]*u_xxR3[2] - gamma_R3[3]*u_xxR3[3] - gamma_R3[4]*u_xxR3[4]) + w_R3[0]*u_xxR3[0] + w_R3[1]*u_xxR3[1] + w_R3[2]*u_xxR3[2] + w_R3[3]*u_xxR3[3] + w_R3[4]*u_xxR3[4]; coeffs[4] = wt_ratio*(u_yyR4 - gamma_R3[0]*u_yyR3[0] - gamma_R3[1]*u_yyR3[1] - gamma_R3[2]*u_yyR3[2] - gamma_R3[3]*u_yyR3[3] - gamma_R3[4]*u_yyR3[4]) + w_R3[0]*u_yyR3[0] + w_R3[1]*u_yyR3[1] + w_R3[2]*u_yyR3[2] + w_R3[3]*u_yyR3[3] + w_R3[4]*u_yyR3[4]; coeffs[5] = wt_ratio*(u_xyR4 - gamma_R3[0]*u_xyR3[0] - gamma_R3[1]*u_xyR3[1] - gamma_R3[2]*u_xyR3[2] - gamma_R3[3]*u_xyR3[3] - gamma_R3[4]*u_xyR3[4]) + w_R3[0]*u_xyR3[0] + w_R3[1]*u_xyR3[1] + w_R3[2]*u_xyR3[2] + w_R3[3]*u_xyR3[3] + w_R3[4]*u_xyR3[4]; coeffs[6] = wt_ratio*u_xxxR4; coeffs[7] = wt_ratio*u_yyyR4; coeffs[8] = wt_ratio*u_xxyR4; coeffs[9] = wt_ratio*u_xyyR4; } void Reconstruct(const PetscReal* U_x, const PetscReal* U_y, const PetscReal* U_xy, const PetscInt N, PetscReal* coeffs, PetscReal* u_coeffs) { switch (N) { case 0: coeffs[0] = U_xy[0]; break; case 1: weno2(U_x,U_y,U_xy,coeffs,u_coeffs); break; case 2: weno3(U_x,U_y,U_xy,coeffs,u_coeffs); break; case 3: weno4(U_x,U_y,U_xy,coeffs,u_coeffs); default: break; } }
C
/**************************************************************************************************** ** File name: terminal.c ** функции работы с RS485 ****************************************************************************************************/ /* Includes ------------------------------------------------------------------*/ #include "mcu_config.h" #include "FreeRTOS.h" #include "task.h" #include "queue.h" #include "ErrorProcessing.h" #include "delay.h" #include "LPH8731-3C.h" #include "stdio.h" /* Private variables ---------------------------------------------------------*/ extern xQueueHandle xQueue_usart_data_in; // дескриптор очереди для данных от USART extern xQueueHandle xQueue_usart_data_out; // дескриптор очереди для данных в USART extern unsigned char rx_buffer[DATA_PACKET_LEN]; // пакет на прием (USART) extern unsigned char quest_start_flag; /* Private function prototypes ---------------------------------------------------------*/ void cmd_parcer (unsigned char *packet); /*======================================================================================*/ /************************************************************************************************************* * Прием данных и формирование пакета *************************************************************************************************************/ void Usart485terminal (void) { unsigned char usart_packet[DATA_PACKET_LEN]; unsigned char rx_from_xQueue_rx_data; unsigned char index = 0; portBASE_TYPE xStatus; do { xStatus = xQueueReceive(xQueue_usart_data_in, &rx_from_xQueue_rx_data, ( portTickType ) 10); // считываем и обрабатываем if (xStatus != pdPASS) SendError(GLOBAL_ERROR); // Если попытка чтения не ok — индицировать ошибку. if (rx_from_xQueue_rx_data == MASTER_START_BYTE) // пришел признак начала пакета? { if (index > (DATA_PACKET_LEN-1)) index = 0; // указатель в 0 и набираем пакет } usart_packet[index++] = rx_from_xQueue_rx_data; // запись данных в пакет и увеличение указателя if (index == DATA_PACKET_LEN) // пакет набран? { index = 0; // сбрасываем указатель if ((usart_packet[0] == MASTER_START_BYTE) && (usart_packet[DATA_PACKET_LEN-1] == STOP_BYTE)) cmd_parcer(usart_packet); // вызываем обработчик usart_packet[0] = 0; // обнуляем стартовый контрольный байт usart_packet[DATA_PACKET_LEN-1] = 0; // обнуляем стоповый контрольный байт } vTaskDelay(1); }while (uxQueueMessagesWaiting(xQueue_usart_data_in) != 0); // крутим, пока есть данные в очереди } /******************************************************************************* * Function Name : cmd_parcer * Description : распарсиваем запрос *******************************************************************************/ void cmd_parcer (unsigned char *packet) { char lcd_buf[70]; unsigned char tx_pack[DATA_PACKET_LEN]; portBASE_TYPE xStatus; if (packet[1] != QUEST_ID) return; tx_pack[0] = SLAVE_START_BYTE; tx_pack[1] = QUEST_ID; tx_pack[2] = 0x01; tx_pack[4] = STOP_BYTE; tx_pack[DATA_PACKET_LEN-1] = STOP_BYTE; switch (packet[2]) // распарсиваем запрос { case CMD_MASTER_TEST: // gotov ili ne gotov k rabote tx_pack[2] = AppState; /* if (AppState == QUEST_READY){ tx_pack[2] = CMD_SLAVE_READY; } else { tx_pack[2] = CMD_SLAVE_NOT_READY; } */ // подсчитать контрольную сумму и всунуть в tx_pack[4] delay_ms(5); xStatus = xQueueSendToBack(xQueue_usart_data_out, &tx_pack, 0); if (xStatus != pdPASS) SendError(GLOBAL_ERROR); // Если попытка записи не была успешной — индицировать ошибку. break; case CMD_MASTER_WORK_START: // nacinaem kvest quest_start_flag = 1; break; case CMD_MASTER_STATUS_REQ: // zapros vipolnen kvest ili net tx_pack[2] = AppState; /* if (AppState == QUEST_COMPLETED){ tx_pack[2] = CMD_SLAVE_COMPLETED; } else { tx_pack[2] = CMD_SLAVE_NOT_COMLETED; } */ // подсчитать контрольную сумму и всунуть в tx_pack[4] delay_ms(5); xStatus = xQueueSendToBack(xQueue_usart_data_out, &tx_pack, 0); if (xStatus != pdPASS) SendError(GLOBAL_ERROR); // Если попытка записи не была успешной — индицировать ошибку. break; case CMD_MASTER_SET_IDLE: // kvest vipolnen, vse pogasitj, vernutj v ishodnoe sostojanie i zdatj zapros Test ili Work_start quest_start_flag = 0; break; case 0xFF: sprintf (lcd_buf,"%02X %02X %02X %02X %02X", packet[0], packet[1], packet[2], packet[3], packet[4]); LCD_Puts(lcd_buf, 1, 60, DARK_BLUE, WHITE,1,1); tx_pack[2] = AppState; tx_pack[4] = STOP_BYTE; tx_pack[DATA_PACKET_LEN-1] = STOP_BYTE; delay_ms(5); tx_pack[3] = packet[3]; xStatus = xQueueSendToBack(xQueue_usart_data_out, &tx_pack, 0); if (xStatus != pdPASS) SendError(GLOBAL_ERROR); // Если попытка записи не была успешной — индицировать ошибку. sprintf (lcd_buf,"%02X %02X %02X %02X %02X", tx_pack[0], tx_pack[1], tx_pack[2], tx_pack[3], tx_pack[4]); LCD_Puts(lcd_buf, 1, 40, DARK_BLUE, WHITE,1,1); break; default: break; } }
C
///////////////////////////// // // // SISTEMAS OPERACIONAIS // // TRABALHO 2 // // // // Talles Siqueia Ceolin // // 201610108 // // // ///////////////////////////// // versão com threads #include "curl_code.h" #include <stdbool.h> #include <string.h> #include <pthread.h> #include <time.h> #define MAX_CLIQUES 7 #define TAMANHO_MAX 256 #define COLOR_RED "\x1b[31m" #define COLOR_GREEN "\x1b[32m" #define COLOR_YELLOW "\x1b[33m" #define COLOR_BLUE "\x1b[34m" #define COLOR_MAGENTA "\x1b[35m" #define COLOR_CYAN "\x1b[36m" #define COLOR_RESET "\x1b[0m" #define COLOR_B_RED "\x1b[1;31m" #define COLOR_B_GREEN "\x1b[1;32m" // estrutura dos argumentos da thread typedef struct ThreadArg { int id; char* paginaInicial; char* palavraProcurada; } threadArg; // printa página que está acessando void printPaginaAtual(int threadID, int cliqueAtual, char* url){ if (cliqueAtual == 0){ printf(COLOR_MAGENTA "Thread %d → " COLOR_YELLOW "Link Inicial:" COLOR_CYAN " Acessando página → %s\n" COLOR_RESET, threadID, url); }else{ printf(COLOR_MAGENTA "Thread %d → " COLOR_YELLOW " %dº Link:" COLOR_CYAN " Acessando página → %s\n" COLOR_RESET, threadID, cliqueAtual, url); } return; } // printa mensagem de game-over void printPerdeuJogo(int threadID){ printf(COLOR_MAGENTA "Thread %d → " COLOR_B_RED " A palavra não foi encontrada, número máximo de cliques foi atingido!\n" COLOR_RESET, threadID); return; } // printa mensagem de jogo vencido void printGanhouJogo(int threadID, char* palavraProcurada, int cliqueAtual){ if (cliqueAtual == 1){ printf(COLOR_MAGENTA "Thread %d → " COLOR_B_GREEN " Encontrou a palavra %s após %d clique!\n" COLOR_RESET, threadID, palavraProcurada, cliqueAtual); }else{ printf(COLOR_MAGENTA "Thread %d → " COLOR_B_GREEN " Encontrou a palavra %s após %d cliques!\n" COLOR_RESET, threadID, palavraProcurada, cliqueAtual); } return; } // verifica se link direciona para fora da wikipedia ou para uma imagem bool paginaInvalida(char* url){ if(strstr(url, "https://pt.wikipedia.org/wiki/") == NULL){ return true; }else if (strstr(url, ".svg") != NULL){ return true; }else if (strstr(url, ".png") != NULL){ return true; }else if (strstr(url, ".jpeg") != NULL){ return true; }else if(strstr(url, "Carregar_ficheiro") != NULL){ return true; } return false; } // verifica se palavra desejada está na página bool encontrouPalavra(char* page_content, char* palavraProcurada){ return strstr(page_content, palavraProcurada) != NULL; } void* seteCliques(char* url, char* palavraProcurada, int cliquesRestantes, int threadID){ // controla número máximo de cliques if (cliquesRestantes < 0){ printPerdeuJogo(threadID); return 0; } // print para visualizar quais páginas está acessando int cliqueAtual = MAX_CLIQUES - cliquesRestantes; printPaginaAtual(threadID, cliqueAtual, url); // page_content recebe o conteudo da pagina a partir do url CURL *curl_handle; char *page_content = download_page(curl_handle, url); // verifica se palavra desejada está na página if(encontrouPalavra(page_content, palavraProcurada)){ printGanhouJogo(threadID, palavraProcurada, cliqueAtual); return 0; }else{ // links: lista de links lidos. A funcao find_links ira tentar ler 50 links dentro da pagina. int links_readed; char **links = find_links(curl_handle, page_content, 50, &links_readed); // Verifica se o link sorteado não é exterior ao wikipedia int random; do{ random = rand() % links_readed; }while (paginaInvalida(links[random])); // acessa um link sorteado e repete a função seteCliques(links[random], palavraProcurada, cliquesRestantes - 1, threadID); } } void* threadStart (void* arg) { // Recebe argumentos da thread threadArg* input = arg; int id = input->id; char* paginaInicial = input->paginaInicial; char* palavraProcurada = input->palavraProcurada; // Função recursiva principal do jogo seteCliques(paginaInicial, palavraProcurada, MAX_CLIQUES, id); return 0; } int main(void){ srand(time(NULL)); // Define número de threads de acordo com o usuário int nThreads; printf(COLOR_B_GREEN "Quantas threads o jogo deve utilizar?\n\t" COLOR_RESET); scanf("%d", &nThreads); // Define a palavra a ser procurada char palavra[TAMANHO_MAX]; printf(COLOR_B_GREEN "Qual palavra deseja procurar? (Ex: Apple)\n\t" COLOR_RESET); scanf("%s", palavra); // inicio do temporizador clock_t inicio = clock(); // Cria vetor de threads e vetor de argumentos (usado para definir um índice para cada thread) pthread_t* threadArray = (pthread_t*) malloc(nThreads * sizeof(pthread_t)); threadArg* args = (threadArg*) malloc(nThreads * sizeof(threadArg)); for (int i = 0; i < nThreads; i++){ args[i].id = i + 1; args[i].paginaInicial = "https://pt.wikipedia.org/wiki/Sistema_operativo"; args[i].palavraProcurada = palavra; pthread_create(&threadArray[i], NULL, threadStart, &args[i]); } // Espera todas threads for (int i = 0; i < nThreads; i++){ pthread_join(threadArray[i], NULL); } // Limpeza da bibioteca curl curl_global_cleanup(); // mostra tempo decorrido no programa clock_t fim = clock(); double tempo = ((double) (fim - inicio)) / CLOCKS_PER_SEC; printf("Fim de jogo! Tempo decorrido: %f\n", tempo); return 0; }
C
#include "holberton.h" /** * get_bit - function that returns the value of a bit at a given index. * @n: var int * @index: var index * Return: the value of the bit at index index or -1 if an error occured */ int get_bit(unsigned long int n, unsigned int index) { if (index > 64) return (-1); return ((n >> index) & 1 ? 1 : 0); }
C
#include "sunclock.h" #include <math.h> #include "project.h" #define PI 3.14159265358979323846 #define fixangle(a) ((a) - 360.0 * (floor((a) / 360.0))) /* Fix angle */ #define fixangr(a) ((a) - (PI*2) * (floor((a) / (PI*2)))) /* Fix angle in radians*/ #define dtr(x) ((x) * (PI / 180.0)) /* Degree->Radian */ #define rtd(x) ((x) / (PI / 180.0)) /* Radian->Degree */ /* PI / 180 = .0174532925199 */ #define DCOS(x) (cos((x) * .0174532925199)) #define DSIN(x) (sin((x) * .0174532925199)) #define DTAN(x) (tan((x) * .0174532925199)) #define MAX(a,b) ((a) > (b) ? (a) : (b)) #define MIN(a,b) ((a) < (b) ? (a) : (b)) mapwindow skywin, telwin, horwin; mapwindow *mapwin[3] = { &skywin, &telwin, &horwin }; int numwins = 3; /* exportable */ static double xf_west, xf_east, xf_north, xf_south, xf_bottom; static int xf_xcen, xf_ycen, xf_ybot; static int xf_w_left, xf_w_right, xf_w_top, xf_w_bot; double xf_c_scale; /* local storage */ static int xfs_proj_mode; /* sin_dlcen = sin (phi0) = sin (declination of center), cos_dlcen similar */ static double xfs_ra_cen, xfs_dl_cen, sin_dlcen, cos_dlcen, chart_scale; static double xfs_scale; /* Formerly yscale */ static double xfs_vinv, xfs_hinv; static int xfs_wide_warn; /* Forward functions. */ static void init_gt(mapwindow *win); static void do_gt(double lat, double lon, double *xloc, double *yloc, double *r_theta); static void inv_gt(double x, double y, double *latp, double *lonp); /* return TRUE if a (in degrees) is west of b */ /* west is towards lower values of RA, e.g. 60 is west of 90 */ static int westof(double a, double b) { double diff; diff = b - a; if (diff > 180) diff -= 360; if (diff < -180) diff += 360; return diff > 0; } /* return TRUE if a (in degrees) is east of b */ /* east is towards higher values of RA, e.g. 90 is east of 60 */ static int eastof(double a, double b) { double diff; diff = b - a; if (diff > 180) diff -= 360; if (diff < -180) diff += 360; return diff < 0; } /* TRANSFORMATION FUNCTIONS */ /** stereographic projection: Imagine object projected on a sphere of radius 1. Center of chart is against a piece of paper. You are looking at the center of the chart through the center of the sphere. The objects are seen projected on the piece of paper. to do it: 1) get angle from center to object, call this theta. 2) get direction from center to object, call this phi. 3) projection of object will be 2*tan(theta/2) from the center of the paper, in the direction phi. to do steps 1 & 2, use alt-azimuth formula, with theta = 90 - alt. scale: when theta = scale, projected object = min(ww,wh)/2 from center. i.e. 2*tan(scale/2)*xfs_scale = min(ww,wh)/2. or xfs_scale = (min(ww,wh)/2)/(2*tan(scale/2)) = min(ww,wh)/(4*tan(scale/2)) put factor of 2 in xfs_scale to save a little computation xfs_scale = min(ww,wh)/(2*tan(scale/2)) R = tan(theta/2)*xfs_scale. */ /** alt-azimuth: sin(alt) = sin(obs_lat)sin(obj_dl) + cos(obs_lat)cos(obj_dl)cos(hour) cos(azi) = (cos(obs_lat)sin(obj_dl) - sin(obs_lat)cos(obj_dl)cos(hour)) / cos(alt) sin(azi) = (-cos(obj_dl)sin(hour)) / cos(alt) tan(azi) = -cos((obj_dl)sin(hour) / (cos(obs_lat)sin(obj_dl) - sin(obs_lat)cos(obj_dl)cos(hour)) with alt = 90 - theta, azi = phi, hour = lon - racen, obj_dl =lat, and obs_lat = dlcen, this becomes: cos(theta) = sin(dlcen)sin(lat) + cos(dlcen)cos(lat)cos(lon - racen) tan(phi) = -cos(lat)sin(lon - racen) / (cos(dlcen)sin(lat) - sin(dlcen)cos(lat)cos(lon - racen)) racen and dlcen are constants for a chart, so introduce variables racen, sin_dlcen, cos_dlcen. also add chart_scale which is chart->scale in radians. initxform sets these static variables. Other projections from book. **/ int initxform(mapwindow *win) { double tscale = 0; #ifdef NEEDED double adj, xscale; #endif xfs_proj_mode = win->proj_mode; if (win->scale <= 0.0) return FALSE; if (win->height == 0) return FALSE; xfs_ra_cen = win->racen; xfs_dl_cen = win->dlcen; xf_xcen = win->x_offset + (win->width) / 2; xf_ycen = win->y_offset + (win->height) / 2; xf_ybot = win->y_offset; xf_north = (win->dlcen + win->scale / 2); xf_south = (win->dlcen - win->scale / 2); if (xf_north > 90.0) xf_north = 90.0; if (xf_south < -90.0) xf_south = -90.0; if (win->invert) { xfs_vinv = -1.0; // xfs_hinv = 1; xf_bottom = xf_north; } else { xfs_vinv = 1.0; // xfs_hinv = -1; xf_bottom = xf_south; } if (win->mirror) { xfs_hinv = -1; } else { xfs_hinv = 1; } #ifdef NEEDED if (xfs_proj_mode == SANSONS) { /* * calculate xf_east and xf_west by calculating the widest range of lon * which will be within the chart. * xscale is other than win->scale in order to widen the horizontal viewing * area, which otherwise shrinks near the poles under Sanson's projection * this happens in polar maps which do not span the celestial equator */ adj = 1.0; if (xf_north * xf_south > 0.0) adj = MAX(DCOS(xf_north), DCOS(xf_south)); xscale = win->scale / adj; tscale = xscale * win->width/win->height / 2.0; if (tscale > 180.0) tscale = 180.0; } else if (xfs_proj_mode == RECTANGULAR) { tscale = win->scale * win->width / (2 * win->height); if (tscale > 180.0) tscale = 180.0; }; #endif // NEEDED xf_east = win->racen + tscale; xf_west = win->racen - tscale; /* set warning, may have problems in SANSONS or RECTANGULAR with lines which should wrap around */ #ifdef NEEDED if (((xfs_proj_mode == SANSONS) || (xfs_proj_mode == RECTANGULAR)) && (tscale > 90.0)) xfs_wide_warn = TRUE; else #endif xfs_wide_warn = FALSE; xf_w_left = win->x_offset; xf_w_right = win->x_offset + win->width; xf_w_bot = win->y_offset; xf_w_top = win->y_offset + win->height; switch (xfs_proj_mode) { case GNOMONIC: case ORTHOGR: case STEREOGR: sin_dlcen = DSIN(win->dlcen); cos_dlcen = DCOS(win->dlcen); chart_scale = win->scale * .0174532925199; /* Radians */ break; #ifdef NEEDED case SANSONS: case RECTANGULAR: default: break; #endif } /* xf_c_scale is the size in degrees which one pixel occupies on the map */ /* xfs_scale is the conversion factor for size of the picture (= R in some formulas for stereographic, gnomonic and orthographic projections) */ if (xfs_proj_mode == STEREOGR) { xfs_scale = MIN(win->height, win->width) / (4.0 * DTAN(win->scale / 2.0)); xf_c_scale = win->c_scale = 1.0 / (2.0 * DTAN(0.5) * xfs_scale); #ifdef NEEDED } else if (xfs_proj_mode == SANSONS) { xfs_scale = win->height / win->scale; xf_c_scale = win->c_scale = win->scale / win->height; #endif } else if (xfs_proj_mode == GNOMONIC) { xfs_scale = MIN(win->height, win->width) / (2.0 * DTAN(win->scale / 2.0)); xf_c_scale = win->c_scale = 1.0/(DTAN(1.0) * xfs_scale); #ifdef NEEDED } else if (xfs_proj_mode == ORTHOGR) { xfs_scale = MIN(win->height, win->width) / (2.0 * DSIN(win->scale / 2.0)); xf_c_scale = win->c_scale = 1.0 / (DSIN(1.0) * xfs_scale); } else if (xfs_proj_mode == RECTANGULAR) { xfs_scale = win->height / win->scale; xf_c_scale = win->c_scale = 1.0 / xfs_scale; #endif } /* initialize gnomonic transform function */ init_gt(win); return TRUE; } void xform(double lat, double lon, int *xloc, int *yloc, int *inregion) { double theta, actheta, rac_l; double denom; double Dcoslat, Dsinlat, Dcosrac_l, Dsinrac_l; /* Dcoslat, Dsinlat: of object latitude in degrees = phi Dcosrac_l, Dsinrac_l: of object ra - longditude of center = d(lambda) */ double xlocd, ylocd; /* double precision for xloc and yloc */ switch (xfs_proj_mode) { #ifdef NEEDED case SANSONS: /* * This is Sanson's Sinusoidal projection. Its properties: * (1) area preserving * (2) preserves linearity along y axis (declination/azimuth) */ /* because of the (xfs_ra_cen-lon) below, lon must be continuous across the plotted region. xf_west is xfs_ra_cen - (scale factor), xf_east is xfs_ra_cen + (scale factor), so xf_west may be negative, and xf_east may be > 360.0. lon should be 0 <= lon < 360.0. we must bring lon into the range. if xf_west < 0 and (xf_west + 360) < lon then lon is in the right half of the chart and needs to be adjusted if xf_east > 360 and (xf_east - 360) > lon then lon is in the left half of the chart and needs to be adjusted */ if ((xf_west < 0.0) && (lon>(xf_west+360.0))) lon -= 360.0; if ((xf_east > 360.0) && (lon<(xf_east-360.0))) lon += 360.0; *xloc = (int) (xf_xcen + (int) xfs_hinv * ((xfs_ra_cen - lon) * xfs_scale * DCOS(lat)) + 0.5); *yloc = (int) (xf_ybot + (int) xfs_vinv * ((lat - xf_bottom) * xfs_scale) + 0.5); *inregion = ((lon >= xf_west) && (lon <= xf_east) && (lat >= xf_south) && (lat <= xf_north)); break; #endif case STEREOGR: /* Stereographic projection */ rac_l = lon - xfs_ra_cen; Dsinlat = DSIN(lat); Dcoslat = DCOS(lat); Dcosrac_l = DCOS(rac_l); Dsinrac_l = DSIN(rac_l); actheta = sin_dlcen * Dsinlat + cos_dlcen * Dcoslat * Dcosrac_l; if (actheta > 1.0) theta = 0.0; else if (actheta < -1.0) theta = 3.14159265358979323846; else theta = acos(actheta); *inregion = (theta <= chart_scale); if (*inregion) { denom = (1 + sin_dlcen * Dsinlat + cos_dlcen * Dcoslat * Dcosrac_l) / xfs_scale; *xloc = (int) (xf_xcen - 2 * xfs_hinv * Dcoslat * Dsinrac_l / denom + 0.5); *yloc = (int) (xf_ycen + 2 * xfs_vinv * (cos_dlcen * Dsinlat - sin_dlcen * Dcoslat * Dcosrac_l) / denom + 0.5); } break; case GNOMONIC: /* Gnomonic projection */ rac_l = lon - xfs_ra_cen; Dsinlat = DSIN(lat); Dcoslat = DCOS(lat); Dcosrac_l = DCOS(rac_l); Dsinrac_l = DSIN(rac_l); actheta = sin_dlcen * Dsinlat + cos_dlcen * Dcoslat * Dcosrac_l; if (actheta > 1.0) theta = 0.0; else if (actheta < -1.0) theta = 3.14159265358979323846; else theta = acos(actheta); if (theta <= 1.57) { /* avoid wrapping */ denom = (sin_dlcen * Dsinlat + cos_dlcen * Dcoslat * Dcosrac_l) / xfs_scale; *yloc = (int) (ylocd = xf_ycen + (int) xfs_vinv * (cos_dlcen * Dsinlat - sin_dlcen * Dcoslat * Dcosrac_l) / denom + 0.5); *xloc = (int) (xlocd = xf_xcen - xfs_hinv * Dcoslat * Dsinrac_l / denom + 0.5); *inregion = ((xlocd >= xf_w_left) && (xlocd <= xf_w_right) && (ylocd <= xf_w_top) && (ylocd >= xf_w_bot)); } else *inregion = FALSE; break; #ifdef NEEDED case ORTHOGR: rac_l = lon - xfs_ra_cen; Dsinlat = DSIN(lat); Dcoslat = DCOS(lat); Dcosrac_l = DCOS(rac_l); Dsinrac_l = DSIN(rac_l); actheta = sin_dlcen * Dsinlat + cos_dlcen * Dcoslat * Dcosrac_l; if (actheta > 1.0) theta = 0.0; else if (actheta < -1.0) theta = 3.14159265358979323846; else theta = acos(actheta); if (theta <= 1.57) { /* avoid wrapping */ *yloc = (int) (ylocd = xf_ycen + (int) xfs_vinv * xfs_scale * (cos_dlcen * Dsinlat - sin_dlcen * Dcoslat * Dcosrac_l)); *xloc = (int) (xlocd = xf_xcen - xfs_hinv * xfs_scale * Dcoslat * Dsinrac_l); *inregion = ((xlocd >= xf_w_left) && (xlocd <= xf_w_right) && (ylocd <= xf_w_top) && (ylocd >= xf_w_bot)); } else *inregion = FALSE; break; case RECTANGULAR: if ((xf_west < 0.0) && (lon>(xf_west+360.0))) lon -= 360.0; if ((xf_east > 360.0) && (lon<(xf_east-360.0))) lon += 360.0; *yloc = (int) (ylocd = xf_ycen + (int)xfs_vinv * xfs_scale * (lat - xfs_dl_cen)); *xloc = (int) (xlocd = xf_xcen + xfs_hinv * xfs_scale * (xfs_ra_cen - lon)); *inregion = ((xlocd >= xf_w_left) && (xlocd <= xf_w_right) && (ylocd <= xf_w_top) && (ylocd >= xf_w_bot)); break; #endif // NEEDED default: break; } } /* Given x and y of a point on the display, return the latitude and longitude */ int invxform(int x, int y, double *latp, double *lonp) { int i; int winnum; mapwindow *win; /* temporaries to hold values set by initxform */ double t_xf_west, t_xf_east, t_xf_north, t_xf_south, t_xf_bottom; int t_xf_w_left, t_xf_w_right, t_xf_w_top, t_xf_w_bot; int t_xf_xcen, t_xf_ycen, t_xf_ybot; double t_xf_c_scale; int t_xfs_proj_mode; double t_xfs_ra_cen, t_sin_dlcen, t_cos_dlcen, t_chart_scale; double t_xfs_scale; double t_xfs_vinv, t_xfs_hinv; double rho; double R, theta; double l, m, n; double l_, m_, n_; *latp = 0.0; *lonp = 0.0; /* First, find which mapwindow the point is in */ for (i = 0; i < numwins; i++) { if ((x >= mapwin[i]->x_offset) && (y >= mapwin[i]->y_offset) && (x <= (mapwin[i]->x_offset+mapwin[i]->width)) && (y <= (mapwin[i]->y_offset+mapwin[i]->height))) /* point is in window i */ break; } if (i == numwins) return -1; /* outside all windows */ winnum = i; win = mapwin[winnum]; /* Now, initialize inverse transformation for window winnum */ t_xf_west = xf_west; t_xf_east = xf_east; t_xf_north = xf_north; t_xf_south = xf_south; t_xf_bottom = xf_bottom; t_xf_xcen = xf_xcen; t_xf_ycen = xf_ycen; t_xf_ybot = xf_ybot; t_xf_w_left = xf_w_left; t_xf_w_right = xf_w_right; t_xf_w_top = xf_w_top; t_xf_w_bot = xf_w_bot; t_xf_c_scale = xf_c_scale; t_xfs_proj_mode = xfs_proj_mode; t_xfs_ra_cen = xfs_ra_cen; t_sin_dlcen = sin_dlcen; t_cos_dlcen = cos_dlcen; t_chart_scale = chart_scale; t_xfs_scale = xfs_scale; t_xfs_vinv = xfs_vinv; t_xfs_hinv = xfs_hinv; initxform(win); /* Calculate lat and lon */ switch (win->proj_mode) { #ifdef NEEDED case SANSONS: *latp = (y - xf_ybot) / xfs_scale * xfs_vinv + xf_bottom; *lonp = -((x - xf_xcen) / (xfs_scale * xfs_hinv * DCOS(*latp)) - xfs_ra_cen); break; #endif case GNOMONIC: case ORTHOGR: case STEREOGR: x -= xf_xcen; y -= xf_ycen; y *= (int) xfs_vinv; x *= (int) xfs_hinv; R = sqrt((double) ((((long) x) * x) + (((long) y) * y))); theta = atan2((double) y, (double) x); /* rho is the angle from the center of the display to the object on the unit sphere. */ switch (win->proj_mode) { case STEREOGR: rho = 2.0 * atan(R / (2.0 * xfs_scale)); break; case GNOMONIC: rho = atan(R / xfs_scale); break; #ifdef NEEDED case ORTHOGR: rho = asin(R / xfs_scale); break; #endif } /* transform from (rho, theta) to l m n direction cosines */ l = sin(rho) * cos(theta); /* rho and theta are in radians */ m = sin(rho) * sin(theta); n = cos(rho); /* transform to new declination at center new axes rotated about x axis (l) */ l_ = l; m_ = m * sin_dlcen - n * cos_dlcen; n_ = m * cos_dlcen + n * sin_dlcen; /* calculate lon and lat */ *lonp = atan2(l_, m_) / 0.0174532925199 + xfs_ra_cen - 180.0; *latp = 90 - acos(n_) / 0.0174532925199; break; #ifdef NEEDED case RECTANGULAR: *latp = (y - xf_ycen) / (xfs_vinv * xfs_scale) + xfs_dl_cen; *lonp = (xf_xcen - x) / (xfs_hinv * xfs_scale) + xfs_ra_cen; break; #endif default: /* error */ winnum = -1; } /* restore initxform's variables */ xf_west = t_xf_west; xf_east = t_xf_east; xf_north = t_xf_north; xf_south = t_xf_south; xf_bottom = t_xf_bottom; xf_xcen = t_xf_xcen; xf_ycen = t_xf_ycen; xf_ybot = t_xf_ybot; xf_w_left = t_xf_w_left; xf_w_right = t_xf_w_right; xf_w_top = t_xf_w_top; xf_w_bot = t_xf_w_bot; xf_c_scale = t_xf_c_scale; xfs_proj_mode = t_xfs_proj_mode; xfs_ra_cen = t_xfs_ra_cen; sin_dlcen = t_sin_dlcen; cos_dlcen = t_cos_dlcen; chart_scale = t_chart_scale; xfs_scale = t_xfs_scale; xfs_vinv = t_xfs_vinv; xfs_hinv = t_xfs_hinv; if (*lonp >= 360.0) *lonp -= 360.0; if (*lonp < 0.0) *lonp += 360.0; return winnum; } /* Gnomonic transformation Used to draw vectors as great circles in Gnomonic transform a great circle is projected to a line. */ static double gt_sin_dlcen, gt_cos_dlcen, gt_chart_scale; static double gt_scale; /* endpoints of west and east boundaries in SANSONS and RECTANGULAR */ static double gt_wx1, gt_wy1, gt_wx2, gt_wy2; static double gt_ex1, gt_ey1, gt_ex2, gt_ey2; /* midpoint, a and b for north and south boundaries. y = a*x*x + y0 for parabola (b == 0.0) 1 = x*x/a + (y-y0)*(y-y0)/b for ellipse */ static double gt_ny0, gt_na, gt_nb; static double gt_sy0, gt_sa, gt_sb; /* radius for STEREOGRAPHIC, GNOMONIC, and ORTHOGRAPHIC */ static double gt_r; /* Can we clip to boundaries analytically? */ static int gt_use_boundaries; static void init_gt(mapwindow *win) { #ifdef NEEDED double x_1, x_2, y_1, y_2; double r_theta; #endif double adj; gt_use_boundaries = TRUE; gt_sin_dlcen = DSIN(win->dlcen); gt_cos_dlcen = DCOS(win->dlcen); gt_chart_scale = win->scale * .0174532925199; /* Radians */ /* gt_scale is the conversion factor for size of the picture ( = R) */ if (xfs_proj_mode == STEREOGR) gt_scale = MIN(win->height, win->width) / (2.0 * DTAN(win->scale)); else gt_scale = MIN(win->height, win->width) / (2.0 * DTAN(win->scale / 2.0)); adj = xf_c_scale * 0.9; /* use boundaries slightly more restricted than full plot */ /* calculate boundaries of region */ switch (xfs_proj_mode) { #ifdef NEEDED case SANSONS: case RECTANGULAR: do_gt(xf_south+adj, xf_west+adj, &gt_wx1, &gt_wy1, &r_theta); gt_use_boundaries &= (r_theta <= 1.57); do_gt(xf_north-adj, xf_west+adj, &gt_wx2, &gt_wy2, &r_theta); gt_use_boundaries &= (r_theta <= 1.57); do_gt(xf_south+adj, xf_east-adj, &gt_ex1, &gt_ey1, &r_theta); gt_use_boundaries &= (r_theta <= 1.57); do_gt(xf_north-adj, xf_east-adj, &gt_ex2, &gt_ey2, &r_theta); gt_use_boundaries &= (r_theta <= 1.57); do_gt(xf_north-adj, xfs_ra_cen, &x_1, &y_1, &r_theta); gt_use_boundaries &= (r_theta <= 1.57); gt_ny0 = y_1; if (fabs(xf_north-adj) > (90 - fabs(win->dlcen))) { /* ellipse */ do_gt(xf_north-adj, xfs_ra_cen + 180, &x_2, &y_2, &r_theta); gt_use_boundaries &= (r_theta <= 1.57); gt_nb = (y_2 - y_1)/2; gt_ny0 = y_1 + gt_nb ; gt_nb = gt_nb * gt_nb; do_gt(xf_north-adj, xfs_ra_cen + 90, &x_1, &y_1, &r_theta); gt_use_boundaries &= (r_theta <= 1.57); gt_na = x_1 * x_1 / (1 - (y_1 - gt_ny0) * (y_1 - gt_ny0) / gt_nb); } else { /* parabola */ if (gt_use_boundaries) { gt_nb = 0.0; gt_na = (gt_ey2 - gt_ny0) / (gt_ex2 * gt_ex2); /* error if gt_ex2 == 0.0, as when r_theta was > 1.57 */ } } do_gt(xf_south+adj, xfs_ra_cen, &x_1, &y_1, &r_theta); gt_use_boundaries &= (r_theta <= 1.57); gt_sy0 = y_1; if (fabs(xf_south+adj) > (90 - fabs(win->dlcen))) { /* ellipse */ do_gt(xf_south+adj, xfs_ra_cen + 180, &x_2, &y_2, &r_theta); gt_use_boundaries &= (r_theta <= 1.57); gt_sb = (y_2 - y_1) / 2; gt_sy0 = y_1 - gt_sb ; gt_sb = gt_sb * gt_sb; do_gt(xf_south+adj, xfs_ra_cen + 90, &x_1, &y_1, &r_theta); gt_use_boundaries &= (r_theta <= 1.57); do_gt(xf_south+adj, xfs_ra_cen + 270, &x_2, &y_2, &r_theta); gt_use_boundaries &= (r_theta <= 1.57); gt_sa = (x_2 - x_1) / 2; gt_sa = gt_sa * gt_sa; } else { /* parabola */ if (gt_use_boundaries) { gt_sb = 0.0; gt_sa = (gt_ey1 - gt_sy0) / (gt_ex1 * gt_ex1); /* error if gt_ex2 == 0.0, as when r_theta was > 1.57 */ } } break; #endif // NEEDED case STEREOGR: gt_r = MIN(win->height, win->width) / 2.0 - 1; break; #ifdef NEEDED case ORTHOGR: gt_use_boundaries = FALSE; /* can't handle this analytically */ break; #endif case GNOMONIC: gt_wx1 = gt_wx2 = xf_w_left - xf_xcen + 1; gt_ex1 = gt_ex2 = xf_w_right - xf_xcen - 1; gt_ey1 = gt_wy1 = xf_w_bot - xf_ycen + 1; gt_ey2 = gt_wy2 = xf_w_top - xf_ycen - 1; break; default: /* error */ break; } } /* Note, returns xloc and yloc as doubles */ static void do_gt(double lat, double lon, double *xloc, double *yloc, double *r_theta) { double theta, rac_l; double denom; double Dcoslat, Dsinlat, Dcosrac_l, Dsinrac_l; /* Dcoslat, Dsinlat: of object latitude in degrees = phi Dcosrac_l, Dsinrac_l: of object ra - longditude of center = d(lambda) */ rac_l = lon - xfs_ra_cen; Dsinlat = DSIN(lat); Dcoslat = DCOS(lat); Dcosrac_l = DCOS(rac_l); Dsinrac_l = DSIN(rac_l); *r_theta = theta = acos(gt_sin_dlcen*Dsinlat + gt_cos_dlcen * Dcoslat * Dcosrac_l); if (theta <= 1.57) { /* avoid wrapping */ denom = (gt_sin_dlcen * Dsinlat + gt_cos_dlcen * Dcoslat * Dcosrac_l) / gt_scale; *yloc = xfs_vinv * (gt_cos_dlcen * Dsinlat - gt_sin_dlcen * Dcoslat * Dcosrac_l) / denom; *xloc = xfs_hinv * (- Dcoslat * Dsinrac_l / denom); }; } /* Given x and y of a point on the display, return the latitude and longitude */ static void inv_gt(double x, double y, double *latp, double *lonp) { double rho; double R, theta; double l, m, n; double l_, m_, n_; y *= xfs_vinv; x *= xfs_hinv; *latp = 0.0; *lonp = 0.0; /* Calculate lat and lon */ R = sqrt((double) ((((long) x) * x) + (((long) y) * y))); theta = atan2((double) y, (double) x); /* rho is the angle from the center of the display to the object on the unit sphere. */ rho = atan(R / gt_scale); /* transform from (rho, theta) to l m n direction cosines */ l = sin(rho) * cos(theta); /* rho and theta are in radians */ m = sin(rho) * sin(theta); n = cos(rho); /* transform to new declination at center new axes rotated about x axis (l) */ l_ = l; m_ = m * gt_sin_dlcen - n * gt_cos_dlcen; n_ = m * gt_cos_dlcen + n * gt_sin_dlcen; /* calculate lon and lat */ *lonp = atan2(l_, m_) / 0.0174532925199 + xfs_ra_cen - 180.0; if (n_ > 1) n_ = 1; if (n_ < -1) n_ = -1; *latp = 90 - acos(n_) / 0.0174532925199; if (*lonp >= 360.0) *lonp -= 360.0; if (*lonp < 0.0) *lonp += 360.0; } /* * clipping extentions (ccount) */ #define Fuz 0.1 static void quadrat(double a, double b, double c, double *x_1, double *x_2, int *n) { double t; if (a == 0) { *n = 0; } else { t = b * b - 4 * a * c; if (t < 0) { *n = 0; } else if (t == 0) { *x_1 = -b/(2*a); *n = 1; } else { *x_1 = (-b + sqrt(t)) / (2 * a); *x_2 = (-b - sqrt(t)) / (2 * a); *n = 2; }; }; } static void gcmidpoint(double lat1, double lon1, double lat2, double lon2, double *pmlat, double *pmlon) { double l1, m1, n1; double l2, m2, n2; double l3, m3, n3; /* transform from (ra, dec) to l m n direction cosines */ l1 = DCOS(lat1) * DCOS(lon1); m1 = DCOS(lat1) * DSIN(lon1); n1 = DSIN(lat1); l2 = DCOS(lat2) * DCOS(lon2); m2 = DCOS(lat2) * DSIN(lon2); n2 = DSIN(lat2); l3 = l1 + l2; m3 = m1 + m2; n3 = n1 + n2; n3 /= sqrt(l3 * l3 + m3 * m3 + n3 * n3); *pmlon = atan2(m3, l3) / 0.0174532925199; if ((*pmlon < 0) && (lon1 > 0) && (lon2 > 0)) *pmlon += 360.0; *pmlat = asin(n3) / 0.0174532925199; } /* calculate and return the intersection point of two lines given two points on each line */ static void line_intersect(double x_1, double y_1, double x_2, double y_2, double x_3, double y_3, double x_4, double y_4, double *x, double *y, int *int_1) { double a, b, c, d; int x1, y1; double lat_1, lon_1; int in; if (fabs(x_2 - x_1) > 1e-5) { /* Slope may be calculated */ a = (y_2 - y_1)/(x_2 - x_1); b = y_1 - a * x_1; if ((fabs(x_4 - x_3) < 1e-5)) { /* This slope is infinite */ /* calculate intersection */ *x = x_3; *y = a*x_3 + b; *int_1 = TRUE; } else { /* Both slopes may be calculated */ c = (y_4 - y_3)/(x_4 - x_3); d = y_3 - c * x_3; if (fabs(a - c) < 1e-5) { /* Slopes the same, no intersection */ *int_1 = FALSE; } else { /* calculate intersection */ *x = (d - b)/(a - c); *y = (a*d - b*c)/(a - c); *int_1 = TRUE; }; }; } else { /* Slope is infinite */ if ((fabs(x_4 - x_3) < 1e-5)) { /* this slope is also infinite */ *int_1 = FALSE; } else { /* There's an intersection */ c = (y_4 - y_3)/(x_4 - x_3); d = y_3 - c * x_3; *x = x_1; *y = c*x_1 + d; *int_1 = TRUE; }; }; if (*int_1) if (((((y_1 - Fuz) <= *y) && (*y <= (y_2 + Fuz))) || (((y_2 - Fuz) <= *y) && (*y <= (y_1 + Fuz)))) && ((((x_1 - Fuz) <= *x) && (*x <= (x_2 + Fuz))) || (((x_2 - Fuz) <= *x) && (*x <= (x_1 + Fuz))))) *int_1 = TRUE; else *int_1 = FALSE; if (*int_1) { inv_gt(*x, *y, &lat_1, &lon_1); xform(lat_1, lon_1, &x1, &y1, &in); if (!in) *int_1 = FALSE; } } #ifdef NEEDED // y = a*x*x + b static void para_intersect(double x_1, double y_1, double x_2, double y_2, double a, double b, double *x, double *y, int *int_1) { double c, d; double xroot1, xroot2; double yr1, yr2, r1, r2; int n; int x1, y1; double lat_1, lon_1; int in; if (fabs(x_2 - x_1) < 1e-5) { /* Line has infinite slope */ *x = x_1; *y = a * x_1 * x_1 + b; *int_1 = TRUE; } else { /* Line slope may be calculated */ c = (y_2 - y_1) / (x_2 - x_1); d = y_1 - c * x_1; if (a < 1e-5) { /* virtually a straight line y = b */ if (fabs(c) < 1e-5) { /* Constant y */ n = 0; } else { xroot1 = (b - d) / c; n = 1; }; } else { quadrat(a, -c, b - d, &xroot1, &xroot2, &n); }; if (n == 0) { /* No intersection */ *int_1 = FALSE; } else if (n == 1) { /* One intersection */ *x = xroot1; *y = a * xroot1 * xroot1 + b; *int_1 = TRUE; } else { /* Two intersections */ yr1 = c * xroot1 + d; yr2 = c * xroot2 + d; r1 = (xroot1 - x_1) * (xroot1 - x_1) + (yr1 - y_1) * (yr1 - y_1) + (xroot1 - x_2) * (xroot1 - x_2) + (yr1 - y_2) * (yr1 - y_2); r2 = (xroot2 - x_1) * (xroot2 - x_1) + (yr2 - y_1) * (yr2 - y_1) + (xroot2 - x_2) * (xroot2 - x_2) + (yr2 - y_2) * (yr2 - y_2); if (r1 > r2) { *x = xroot2; *y = yr2; *int_1 = TRUE; } else { *x = xroot1; *y = yr1; *int_1 = TRUE; }; } } if (*int_1) if (((((y_1 - Fuz) <= *y) && (*y <= (y_2 + Fuz))) || (((y_2 - Fuz) <= *y) && (*y <= (y_1 + Fuz)))) && ((((x_1 - Fuz) <= *x) && (*x <= (x_2 + Fuz))) || (((x_2 - Fuz) <= *x) && (*x <= (x_1 + Fuz))))) *int_1 = TRUE; else *int_1 = FALSE; if (*int_1) { inv_gt(*x, *y, &lat_1, &lon_1); xform(lat_1, lon_1, &x1, &y1, &in); if (!in) *int_1 = FALSE; } } // x*x/a + (y-y0)*(y-y0)/b - 1 = 0 static void ellip_intersect(double x_1, double y_1, double x_2, double y_2, double a, double b, double y0, double *x, double *y, int *int_1) { double c, d; double xroot1, xroot2; double yr1, yr2, r1, r2; int n; int x1, y1; double lat_1, lon_1; int in; if (fabs(x_2 - x_1) < 1e-5) { /* Line has infinite slope */ xroot1 = xroot2 = *x = x_1; if (x_1 * x_1 / a > 1.0) { n = 0; *int_1 = FALSE; } else if (x_1 * x_1 / a == 1.0) { yr1 = y0; n = 1; *int_1 = TRUE; } else { yr1 = y0 + sqrt(b * (1 - x_1 * x_1 / a)); yr2 = y0 - sqrt(b * (1 - x_1 * x_1 / a)); n = 2; *int_1 = TRUE; } } else { /* Line slope may be calculated */ c = (y_2 - y_1)/(x_2 - x_1); d = y_1 - c * x_1; quadrat(b + a * c * c, 2 * a * c * (d - y0), a * (d - y0) * (d - y0) - a * b, &xroot1, &xroot2, &n); if (n == 0) { /* No intersection */ *int_1 = FALSE; } else if (n == 1) { /* One intersection */ *x = xroot1; *y = c * xroot1 + d; *int_1 = TRUE; } else { /* Two intersections */ yr1 = c * xroot1 + d; yr2 = c * xroot2 + d; *int_1 = TRUE; }; }; if (n == 2) { r1 = (xroot1 - x_1) * (xroot1 - x_1) + (yr1 - y_1) * (yr1 - y_1) + (xroot1 - x_2) * (xroot1 - x_2) + (yr1 - y_2) * (yr1 - y_2); r2 = (xroot2 - x_1) * (xroot2 - x_1) + (yr2 - y_1) * (yr2 - y_1) + (xroot2 - x_2) * (xroot2 - x_2) + (yr2 - y_2) * (yr2 - y_2); if (r1 > r2) { *x = xroot2; *y = yr2; *int_1 = TRUE; } else { *x = xroot1; *y = yr1; *int_1 = TRUE; } } if (*int_1) if ((((y_1 <= *y) && (*y <= y_2)) || ((y_2 <= *y) && (*y <= y_1))) && (((x_1 <= *x) && (*x <= x_2)) || ((x_2 <= *x) && (*x <= x_1)))) *int_1 = TRUE; else *int_1 = FALSE; if (*int_1) { inv_gt(*x, *y, &lat_1, &lon_1); xform(lat_1, lon_1, &x1, &y1, &in); if (!in) *int_1 = FALSE; } } #endif // NEEDED static void circ_intersect(double x_1, double y_1, double x_2, double y_2, double r, double *x1, double *y1, int *int_1, double *x2, double *y2, int *int_2) { double c, d; double xroot1, xroot2; double yr1, yr2, r1, r2; int n; int xt1, yt1; double lat_1, lon_1; int in; if (fabs(x_2 - x_1) < 1e-5) { /* Line has infinite slope */ xroot1 = xroot2 = *x1 = *x2 = x_1; if (fabs(r) > fabs(x_1)) { yr1 = sqrt(r * r - x_1 * x_1); yr2 = -yr1; n = 2; *int_1 = *int_2 = TRUE; } else if (fabs(r) == fabs(x_1)) { yr1 = 0; n = 1; *int_1 = *int_2 = TRUE; } else { n = 0; *int_1 = *int_2 = FALSE; }; } else { /* Line slope may be calculated */ c = (y_2 - y_1)/(x_2 - x_1); d = y_1 - c * x_1; quadrat(1 + c * c, 2 * c * d, d * d - r * r, &xroot1, &xroot2, &n); if (n == 0) { /* No intersection */ *int_1 = *int_2 = FALSE; } else if (n == 1) { /* One intersection */ *x1 = xroot1; *y1 = c * xroot1 + d; *int_1 = TRUE; *int_2 = FALSE; } else { /* Two intersections */ yr1 = c*xroot1 + d; yr2 = c*xroot2 + d; *int_1 = *int_2 = TRUE; }; }; if (n == 2) { r1 = (xroot1 - x_1) * (xroot1 - x_1) + (yr1 - y_1) * (yr1 - y_1) + (xroot1 - x_2) * (xroot1 - x_2) + (yr1 - y_2) * (yr1 - y_2); r2 = (xroot2 - x_1) * (xroot2 - x_1) + (yr2 - y_1) * (yr2 - y_1) + (xroot2 - x_2) * (xroot2 - x_2) + (yr2 - y_2) * (yr2 - y_2); if (r1 > r2) { *x1 = xroot2; *y1 = yr2; *x2 = xroot1; *y2 = yr1; *int_1 = *int_2 = TRUE; } else { *x1 = xroot1; *y1 = yr1; *x2 = xroot2; *y2 = yr2; *int_1 = *int_2 = TRUE; } } if (*int_1) if ((((y_1 <= *y1) && (*y1 <= y_2)) || ((y_2 <= *y1) && (*y1 <= y_1))) && (((x_1 <= *x1) && (*x1 <= x_2)) || ((x_2 <= *x1) && (*x1 <= x_1)))) *int_1 = TRUE; else *int_1 = FALSE; if (*int_1) { inv_gt(*x1, *y1, &lat_1, &lon_1); xform(lat_1, lon_1, &xt1, &yt1, &in); if (!in) *int_1 = FALSE; } if (*int_2) if ((((y_1 <= *y2) && (*y2 <= y_2)) || ((y_2 <= *y2) && (*y2 <= y_1))) && (((x_1 <= *x2) && (*x2 <= x_2)) || ((x_2 <= *x2) && (*x2 <= x_1)))) *int_2 = TRUE; else *int_2 = FALSE; if (*int_2) { inv_gt(*x2, *y2, &lat_1, &lon_1); xform(lat_1, lon_1, &xt1, &yt1, &in); if (!in) *int_2 = FALSE; } } /* defines and clipped_at are for use in area drawing, to indicate that a corner has fallen in the area */ #define NO_CLIP 0 #define WEST_CLIP 1 #define EAST_CLIP 2 #define NORTH_CLIP 4 #define SOUTH_CLIP 8 #define RADIUS_CLIP 16 #define NE_CORNER 6 #define SE_CORNER 10 #define NW_CORNER 5 #define SW_CORNER 9 static int clip_at1, clip_at2; /* return transformed values clipped so both endpoints are inregion */ /* return lats and lons */ /* The line is a great circle on the celestial sphere, or a line in lat and long (e.g. the line 0h 0d to 2h 10d contains the point at 0.5h 5d). Gnomonic transformation maps a great circle to a line. There are three possibilities: 1) both endpoints are in the region. 2) one endpoint is in the region. 3) both endpoints are outside of the drawn region. In case 1, nothing needs to be done. In case 2, a second point at the intersection of the line and the boundary of the drawn region is calculated. In case 3, it is possible that some segment of the line is in the drawn region, and two points along the boundary are calculated. The boundary of the drawn region, projected through gnomonic transformation, are: Sansons: lines on east and west, a line, a parabola, or an ellipse to the north and south. ellipse iff declination of boundary > (90 - decl. of center) Stereographic: circle Gnomonic: rectangle Orthographic: rectangle in orthographic is very comples, use a circle. Simple: same as sansons. */ int clipr_xform(double lat1, double lon1, double lat2, double lon2, int *xloc1, int *yloc1, int *xloc2, int *yloc2, int great_circle, double *plat1, double *plon1, double *plat2, double *plon2) { int Lisin, Risin; double x_1, y_1, x_2, y_2; double theta_1, theta_2; int int_w, int_e, int_n, int_s, int_r1, int_r2; double xw, xe, xn, xs, xr1, xr2, yw, ye, yn, ys, yr1, yr2; double Llat, Llon, Rlat, Rlon, Mlat, Mlon; int Lx, Ly, Rx, Ry, Mx, My; int inL, inR, inM; *plon1 = lon1; *plon2 = lon2; *plat1 = lat1; *plat2 = lat2; clip_at1 = clip_at2 = NO_CLIP; xform(lat1, lon1, xloc1, yloc1, &Lisin); xform(lat2, lon2, xloc2, yloc2, &Risin); if (Lisin && Risin) /* is already ok: case 1 */ return TRUE; if (great_circle && gt_use_boundaries) { /* Transform to gnomonic */ do_gt(lat1, lon1, &x_1, &y_1, &theta_1); do_gt(lat2, lon2, &x_2, &y_2, &theta_2); if ((theta_1 > 1.57) || (theta_2 > 1.57)) /* out of field, skip */ return FALSE; /* Find intersections with boundaries */ switch (xfs_proj_mode) { #ifdef NEEDED case SANSONS: case RECTANGULAR: line_intersect(x_1, y_1, x_2, y_2, gt_wx1, gt_wy1, gt_wx2, gt_wy2, &xw, &yw, &int_w); line_intersect(x_1, y_1, x_2, y_2, gt_ex1, gt_ey1, gt_ex2, gt_ey2, &xe, &ye, &int_e); if (gt_nb == 0.0) { /* parabola */ para_intersect(x_1, y_1, x_2, y_2, gt_na, gt_ny0, &xn, &yn, &int_n); } else { ellip_intersect(x_1, y_1, x_2, y_2, gt_na, gt_nb, gt_ny0, &xn, &yn, &int_n); } if (gt_sb == 0.0) { /* parabola */ para_intersect(x_1, y_1, x_2, y_2, gt_sa, gt_sy0, &xs, &ys, &int_s); } else { ellip_intersect(x_1, y_1, x_2, y_2, gt_sa, gt_sb, gt_sy0, &xs, &ys, &int_s); } int_r1 = int_r2 = FALSE; break; #endif // NEEDED case GNOMONIC: line_intersect(x_1, y_1, x_2, y_2, gt_wx1, gt_wy1, gt_wx2, gt_wy2, &xw, &yw, &int_w); line_intersect(x_1, y_1, x_2, y_2, gt_ex1, gt_ey1, gt_ex2, gt_ey2, &xe, &ye, &int_e); line_intersect(x_1, y_1, x_2, y_2, gt_ex2, gt_ey2, gt_wx2, gt_wy2, &xn, &yn, &int_n); line_intersect(x_1, y_1, x_2, y_2, gt_wx1, gt_wy1, gt_ex1, gt_ey1, &xs, &ys, &int_s); int_r1 = int_r2 = FALSE; break; case STEREOGR: circ_intersect(x_1, y_1, x_2, y_2, gt_r, &xr1, &yr1, &int_r1, &xr2, &yr2, &int_r2); int_w = int_n = int_s = int_e = FALSE; case ORTHOGR: break; default: /* error */ break; }; if (!(!Lisin && !Risin)) { /* case 2 */ if (int_w) { x_1 = xw; y_1 = yw; if (Risin) clip_at1 = WEST_CLIP; else clip_at2 = WEST_CLIP; } else if (int_e) { x_1 = xe; y_1 = ye; if (Risin) clip_at1 = EAST_CLIP; else clip_at2 = EAST_CLIP; } else if (int_n) { x_1 = xn; y_1 = yn; if (Risin) clip_at1 = NORTH_CLIP; else clip_at2 = NORTH_CLIP; } else if (int_s) { x_1 = xs; y_1 = ys; if (Risin) clip_at1 = SOUTH_CLIP; else clip_at2 = SOUTH_CLIP; } else if (int_r1) { x_1 = xr1; y_1 = yr1; if (Risin) clip_at1 = RADIUS_CLIP; else clip_at2 = RADIUS_CLIP; } else { /* fprintf(stderr, "Error drawing vector\n"); fprintf(stderr, "from (%.3f %.3f) to (%.3f %.3f)\n", lat1, lon1, lat2, lon2);*/ return FALSE; }; if (Lisin) { /* Need to find new point 2 */ inv_gt(x_1, y_1, plat2, plon2); xform(*plat2, *plon2, xloc2, yloc2, &inM); } else { /* Need to find new point 1 */ inv_gt(x_1, y_1, plat1, plon1); xform(*plat1, *plon1, xloc1, yloc1, &inM); }; } else { /* case 3 */ if (int_w && int_e) { x_1 = xw; y_1 = yw; x_2 = xe; y_2 = ye; clip_at1 = WEST_CLIP; clip_at2 = EAST_CLIP; } else if (int_w && int_n) { x_1 = xw; y_1 = yw; x_2 = xn; y_2 = yn; clip_at1 = WEST_CLIP; clip_at2 = NORTH_CLIP; } else if (int_w && int_s) { x_1 = xw; y_1 = yw; x_2 = xs; y_2 = ys; clip_at1 = WEST_CLIP; clip_at2 = SOUTH_CLIP; } else if (int_e && int_n) { x_1 = xe; y_1 = ye; x_2 = xn; y_2 = yn; clip_at1 = EAST_CLIP; clip_at2 = NORTH_CLIP; } else if (int_e && int_s) { x_1 = xe; y_1 = ye; x_2 = xs; y_2 = ys; clip_at1 = EAST_CLIP; clip_at2 = SOUTH_CLIP; } else if (int_n && int_s) { x_1 = xn; y_1 = yn; x_2 = xs; y_2 = ys; clip_at1 = NORTH_CLIP; clip_at2 = SOUTH_CLIP; } else if (int_r1 && int_r2) { x_1 = xr1; y_1 = yr1; x_2 = xr2; y_2 = yr2; clip_at1 = clip_at2 = RADIUS_CLIP; } else return FALSE; inv_gt(x_1, y_1, plat1, plon1); inv_gt(x_2, y_2, plat2, plon2); xform(*plat1, *plon1, xloc1, yloc1, &inM); xform(*plat2, *plon2, xloc2, yloc2, &inM); } return TRUE; } else { /* find boundaries by bisection */ if (!Lisin && !Risin) /* is hopeless */ return FALSE; /* Now, one side is in, and the other out. Make sure we won't have problems with crossing 0h */ /* If the difference between lon1 and lon2 is greater than the difference if you subtract 360 from the larger, then shift the larger by 360 degrees */ if (fabs(MAX(lon1,lon2) - MIN(lon1,lon2)) > fabs(MAX(lon1,lon2) - 360.0 - MIN(lon1,lon2))) if (lon2 > 180.0) lon2 -= 360.0; else lon1 -= 360.0; Llat = lat1; Llon = lon1; Rlat = lat2; Rlon = lon2; xform(Llat, Llon, &Lx, &Ly, &inL); xform(Rlat, Rlon, &Rx, &Ry, &inR); /* One endpoint is in. Now use bisection to find point at edge */ do { if (great_circle) { gcmidpoint(Llat, Llon, Rlat, Rlon, &Mlat, &Mlon); } else { Mlat = (Llat + Rlat) / 2.0; Mlon = (Llon + Rlon) / 2.0; }; xform(Mlat, Mlon, &Mx, &My, &inM); if (inL) /* L in R out */ if (inM) { /* between M and R */ Llat = Mlat; Llon = Mlon; inL = inM; Lx = Mx; Ly = My; } else { /* between M and L */ Rlat = Mlat; Rlon = Mlon; inR = inM; Rx = Mx; Ry = My; } else /* L out R in */ if (inM) { /* between M and L */ Rlat = Mlat; Rlon = Mlon; inR = inM; Rx = Mx; Ry = My; } else { /* between M and R */ Llat = Mlat; Llon = Mlon; inL = inM; Lx = Mx; Ly = My; }; } while ((fabs((Llat - Rlat)) > xf_c_scale) || (fabs((Llon - Rlon)) > xf_c_scale)); if (Lisin) { /* Left point is in, bisection found right point */ *xloc2 = Lx; /* Use Lx, Ly, since they're inside bounds */ *yloc2 = Ly; *plon2 = Llon; *plat2 = Llat; } else { /* Bisection found left point */ *xloc1 = Rx; /* Use Rx, Ry, since they're inside bounds */ *yloc1 = Ry; *plon1 = Rlon; *plat1 = Rlat; } return TRUE; } } /* Draw a curved line between points 1 and 2. clipxform has been called, xloc1, yloc1, xloc2, yloc2 are in bounds */ void drawcurveline(double lat1, double lon1, double lat2, double lon2, int xloc1, int yloc1, int xloc2, int yloc2, int line_style, int great_circle, int clevel) { double mlat, mlon; /* midpoint lat and long */ #ifdef NEEDED double tlat1, tlat2; /* temporary */ int txloc1, tyloc1, in; int txloc2, tyloc2; double slope1; #endif // NEEDED int mxloc, myloc; /* transformed */ int mpx, mpy; /* from given x,y */ int inregion; /* ra difference should be less than 180 degrees: take shortest path */ if ((xfs_proj_mode == STEREOGR) || (xfs_proj_mode == GNOMONIC) || (xfs_proj_mode == ORTHOGR)) if ((lon1 - lon2) > 180.0) lon1 -= 360.0; else if ((lon2 - lon1) > 180.0) lon2 -= 360.0; #ifdef NEEDED /* Adjust so lon1 and lon2 are continuous across region: see xform */ /* needed so midpoint is correct */ if ((xfs_proj_mode == SANSONS) || (xfs_proj_mode == RECTANGULAR)) { if ((xf_west < 0.0) && (lon1>(xf_west+360.0))) lon1 -= 360.0; if ((xf_east > 360.0) && (lon1<(xf_east-360.0))) lon1 += 360.0; if ((xf_west < 0.0) && (lon2>(xf_west+360.0))) lon2 -= 360.0; if ((xf_east > 360.0) && (lon2<(xf_east-360.0))) lon2 += 360.0; /* path crosses boundary of map */ /* if the distance from point1 to left (East) + point2 to right or point2 to right and point2 to left is less than distance from point1 to point2, then we have a problem. */ if (xfs_wide_warn) if ((fabs(lon1-xf_east) + fabs(xf_west-lon2)) < (fabs(lon1-lon2))) { slope1 = (lat2 - lat1)/(fabs(lon1-xf_east) + fabs(xf_west-lon2)); tlat1 = lat1 + slope1 * fabs(lon1-(xf_east-xf_c_scale)); xform(tlat1, xf_east-xf_c_scale, &txloc1, &tyloc1, &in); drawcurveline(lat1, lon1, tlat1, xf_east-xf_c_scale, xloc1, yloc1, txloc1, tyloc1, line_style, great_circle, 0); tlat2 = lat2 - slope1 * fabs(lon2-(xf_west+xf_c_scale)); xform(tlat2, xf_west+xf_c_scale, &txloc2, &tyloc2, &in); drawcurveline(tlat2, xf_west+xf_c_scale, lat2, lon2, txloc2, tyloc2, xloc2, yloc2, line_style, great_circle, 0); return; } else if ((fabs(lon2-xf_east)+fabs(xf_west-lon1)) < (fabs(lon1-lon2))) { slope1 = (lat1 - lat2)/(fabs(lon2-xf_east) + fabs(xf_west-lon1)); tlat1 = lat2 + slope1 * fabs(lon2-(xf_east-xf_c_scale)); xform(tlat1, xf_east-xf_c_scale, &txloc1, &tyloc1, &in); drawcurveline(lat2, lon2, tlat1, xf_east-xf_c_scale, xloc2, yloc2, txloc1, tyloc1, line_style, great_circle, 0); tlat2 = lat1 - slope1 * fabs(lon1-(xf_west+xf_c_scale)); xform(tlat2, xf_west+xf_c_scale, &txloc2, &tyloc2, &in); drawcurveline(tlat2, xf_west+xf_c_scale, lat1, lon1, txloc2, tyloc2, xloc1, yloc1, line_style, great_circle, 0); return; }; } #endif // NEEDED if (great_circle) { gcmidpoint(lat1, lon1, lat2, lon2, &mlat, &mlon); } else { mlat = (lat1 + lat2)/2; mlon = (lon1 + lon2)/2; }; xform(mlat, mlon, &mxloc, &myloc, &inregion); mpx = (xloc1 + xloc2) / 2; mpy = (yloc1 + yloc2) / 2; if (inregion && ((abs(mpx - mxloc) + abs(mpy - myloc)) > 0) && (clevel < 100)) { /* center is not where it should be */ drawcurveline(lat1, lon1, mlat, mlon, xloc1, yloc1, mxloc, myloc, line_style, great_circle, ++clevel); drawcurveline(mlat, mlon, lat2, lon2, mxloc, myloc, xloc2, yloc2, line_style, great_circle, ++clevel); } else { D_movedraw(xloc1, yloc1, xloc2, yloc2, line_style); } } #ifdef NEEDED /* Area handling */ /* Works often, but is far from rigorous */ static struct t_area_struct { double lat, lon; int great_circle; int clipped_at; } area_raw[100], area_clip[200], area_1[200], area_2[200]; static int nsegments = 0, nseg_clip = 0, nseg_1 = 0, nseg_2 = 0; areastart(lat, lon, great_circle) double lat, lon; int great_circle; { if (nsegments != 0) areafinish(); nsegments = 0; area_raw[nsegments].lat = lat; area_raw[nsegments].lon = lon; area_raw[nsegments].great_circle = great_circle; nsegments++; } areaadd(lat, lon, great_circle) double lat, lon; int great_circle; { area_raw[nsegments].lat = lat; area_raw[nsegments].lon = lon; area_raw[nsegments].great_circle = great_circle; nsegments++; } int wrap_area(); areafinish() { int i; int xloc, yloc, xloc2, yloc2; int inregion; double tlat1, tlon1, tlat2, tlon2, tlat3, tlon3, tlat4, tlon4; double slope1; int done, old_n; int curr_area; int gt12; int wraps; int done_clip; done_clip = FALSE; nseg_clip = nseg_1 = nseg_2 = 0; wraps = FALSE; /* skip if no point is within region */ done = TRUE; for (i = 0; i < nsegments; i++) { xform(area_raw[i].lat, area_raw[i].lon, &xloc, &yloc, &inregion); if (inregion) done = FALSE; }; if (done) return; if ((xfs_proj_mode == SANSONS) || (xfs_proj_mode == RECTANGULAR)) { if (xfs_wide_warn) for (i = 0; i < (nsegments - 1); i++) if (wrap_area(area_raw[i].lat, area_raw[i].lon, area_raw[i+1].lat, area_raw[i+1].lon, &tlat1, &tlon1, &tlat2, &tlon2)) wraps = TRUE; if (!xfs_wide_warn) { /* Use algorithm to clip area_raw to rectangular region */ /* Use area_1 and area_2 as scratch */ /* clip against west from area_raw to area_1 */ tlat1 = area_raw[nsegments-1].lat; tlon1 = area_raw[nsegments-1].lon; for (i = 0, nseg_1 = 0; i < nsegments; i++) { tlat4 = area_raw[i].lat; tlon4 = area_raw[i].lon; if (eastof(tlon4, xf_west)) { if (eastof(tlon1, xf_west)) { /* last point and new point (4) are in, add new point */ } else { /* new point in, but old out. Calculate intersection point (2), add it and new point */ slope1 = (tlat4 - tlat1) / (tlon4 - tlon1); tlat2 = tlat1 + slope1 * (xf_west-tlon1); tlon2 = xf_west; area_1[nseg_1].lat = tlat2; area_1[nseg_1].lon = tlon2; area_1[nseg_1].great_circle = area_raw[i].great_circle; area_1[nseg_1].clipped_at = WEST_CLIP; nseg_1++; } area_1[nseg_1].lat = tlat4; area_1[nseg_1].lon = tlon4; area_1[nseg_1].great_circle = area_raw[i].great_circle; area_1[nseg_1].clipped_at = 0; nseg_1++; } else { if (eastof(tlon1, xf_west)) { /* new point out, but old point in. Calculate intersection and add it */ slope1 = (tlat4 - tlat1) / (tlon4 - tlon1); tlat2 = tlat1 + slope1 * (xf_west-tlon1); tlon2 = xf_west; area_1[nseg_1].lat = tlat2; area_1[nseg_1].lon = tlon2; area_1[nseg_1].great_circle = area_raw[i].great_circle; area_1[nseg_1].clipped_at = WEST_CLIP; nseg_1++; } } tlat1 = tlat4; tlon1 = tlon4; } /* clip against south from area_1 to area_2 */ tlat1 = area_1[nseg_1-1].lat; tlon1 = area_1[nseg_1-1].lon; for (i = 0, nseg_2 = 0; i < nseg_1; i++) { tlat4 = area_1[i].lat; tlon4 = area_1[i].lon; if (tlat4 > xf_south) { if (tlat1 > xf_south) { /* last point and new point (4) are in, add new point */ } else { /* new point in, but old out. Calculate intersection point (2), add it and new point */ slope1 = (tlon4 - tlon1) / (tlat4 - tlat1); tlat2 = xf_south; tlon2 = tlon1 + slope1 * (xf_south-tlat1); area_2[nseg_2].lat = tlat2; area_2[nseg_2].lon = tlon2; area_2[nseg_2].great_circle = area_1[i].great_circle; area_2[nseg_2].clipped_at = SOUTH_CLIP; nseg_2++; } area_2[nseg_2].lat = tlat4; area_2[nseg_2].lon = tlon4; area_2[nseg_2].great_circle = area_1[i].great_circle; area_2[nseg_2].clipped_at = 0; nseg_2++; } else { if (tlat1 > xf_south) { /* new point out, but old point in. Calculate intersection and add it */ slope1 = (tlon4 - tlon1) / (tlat4 - tlat1); tlat2 = xf_south; tlon2 = tlon1 + slope1 * (xf_south-tlat1); area_2[nseg_2].lat = tlat2; area_2[nseg_2].lon = tlon2; area_2[nseg_2].great_circle = area_1[i].great_circle; area_2[nseg_2].clipped_at = SOUTH_CLIP; nseg_2++; } } tlat1 = tlat4; tlon1 = tlon4; } /* clip against east from area_2 to area_1 */ tlat1 = area_2[nseg_2-1].lat; tlon1 = area_2[nseg_2-1].lon; for (i = 0, nseg_1 = 0; i < nseg_2; i++) { tlat4 = area_2[i].lat; tlon4 = area_2[i].lon; if (westof(tlon4, xf_east)) { if (westof(tlon1, xf_east)) { /* last point and new point (4) are in, add new point */ } else { /* new point in, but old out. Calculate intersection point (2), add it and new point */ slope1 = (tlat4 - tlat1) / (tlon4 - tlon1); tlat2 = tlat1 + slope1 * (xf_east-tlon1); tlon2 = xf_east; area_1[nseg_1].lat = tlat2; area_1[nseg_1].lon = tlon2; area_1[nseg_1].great_circle = area_2[i].great_circle; area_1[nseg_1].clipped_at = EAST_CLIP; nseg_1++; } area_1[nseg_1].lat = tlat4; area_1[nseg_1].lon = tlon4; area_1[nseg_1].great_circle = area_2[i].great_circle; area_1[nseg_1].clipped_at = 0; nseg_1++; } else { if (westof(tlon1, xf_east)) { /* new point out, but old point in. Calculate intersection and add it */ slope1 = (tlat4 - tlat1) / (tlon4 - tlon1); tlat2 = tlat1 + slope1 * (xf_east-tlon1); tlon2 = xf_east; area_1[nseg_1].lat = tlat2; area_1[nseg_1].lon = tlon2; area_1[nseg_1].great_circle = area_2[i].great_circle; area_1[nseg_1].clipped_at = EAST_CLIP; nseg_1++; } } tlat1 = tlat4; tlon1 = tlon4; } /* clip against north from area_1 to area_clip */ tlat1 = area_1[nseg_1-1].lat; tlon1 = area_1[nseg_1-1].lon; for (i = 0, nseg_clip = 0; i < nseg_1; i++) { tlat4 = area_1[i].lat; tlon4 = area_1[i].lon; if (tlat4 < xf_north) { if (tlat1 < xf_north) { /* last point and new point (4) are in, add new point */ } else { /* new point in, but old out. Calculate intersection point (2), add it and new point */ slope1 = (tlon4 - tlon1) / (tlat4 - tlat1); tlat2 = xf_north; tlon2 = tlon1 + slope1 * (xf_north-tlat1); area_clip[nseg_clip].lat = tlat2; area_clip[nseg_clip].lon = tlon2; area_clip[nseg_clip].great_circle = area_1[i].great_circle; area_clip[nseg_clip].clipped_at = NORTH_CLIP; nseg_clip++; } area_clip[nseg_clip].lat = tlat4; area_clip[nseg_clip].lon = tlon4; area_clip[nseg_clip].great_circle = area_1[i].great_circle; area_clip[nseg_clip].clipped_at = 0; nseg_clip++; } else { if (tlat1 < xf_north) { /* new point out, but old point in. Calculate intersection and add it */ slope1 = (tlon4 - tlon1) / (tlat4 - tlat1); tlat2 = xf_north; tlon2 = tlon1 + slope1 * (xf_north-tlat1); area_clip[nseg_clip].lat = tlat2; area_clip[nseg_clip].lon = tlon2; area_clip[nseg_clip].great_circle = area_1[i].great_circle; area_clip[nseg_clip].clipped_at = NORTH_CLIP; nseg_clip++; } } tlat1 = tlat4; tlon1 = tlon4; } if ((area_clip[0].lat != area_clip[nseg_clip-1].lat) || (area_clip[0].lon != area_clip[nseg_clip-1].lon)) { area_clip[nseg_clip].lat = area_clip[0].lat; area_clip[nseg_clip].lon = area_clip[0].lon; area_clip[nseg_clip].great_circle = area_raw[i].great_circle; area_clip[nseg_clip].clipped_at = WEST_CLIP; nseg_clip++; } if (nseg_clip > 0) doarea(area_clip, nseg_clip); done_clip = TRUE; }; }; if (!done_clip) { /* Scan list of segments, constructing clipped polygon */ for (i = 0; i < (nsegments - 1); i++) { if (clipr_xform(area_raw[i].lat, area_raw[i].lon, area_raw[i+1].lat, area_raw[i+1].lon, &xloc, &yloc, &xloc2, &yloc2, area_raw[i+1].great_circle, &tlat1, &tlon1, &tlat2, &tlon2)) { addsegment(tlat1, tlon1, tlat2, tlon2, (nseg_clip > 0) ? area_clip[nseg_clip-1].clipped_at : 0, clip_at1, clip_at2, area_raw[i].great_circle, area_raw[i+1].great_circle); }; }; /* ensure that area is closed. */ /* redraw first segment */ if ((nseg_clip > 0) && ((area_clip[nseg_clip-1].lat != area_clip[0].lat) || (area_clip[nseg_clip-1].lon != area_clip[0].lon))) { i = 0; done = FALSE; old_n = nseg_clip; do { if (clipr_xform(area_raw[i].lat, area_raw[i].lon, area_raw[i+1].lat, area_raw[i+1].lon, &xloc, &yloc, &xloc2, &yloc2, area_raw[i+1].great_circle, &tlat1, &tlon1, &tlat2, &tlon2)) { addsegment(tlat1, tlon1, tlat2, tlon2, (nseg_clip > 0) ? area_clip[nseg_clip-1].clipped_at : 0, clip_at1, clip_at2, area_raw[i].great_circle, area_raw[i+1].great_circle); done = TRUE; } i++; } while ((i < (nsegments - 1)) && (!done)); if ((old_n+1) < nseg_clip) nseg_clip--; /* only needed one added */ } /* Now fix problem of areas crossing from left to right across boundary */ /* if the distance from point1 to left (East) + point2 to right or point2 to right and point2 to left is less than distance from point1 to point2, then we have a problem. */ curr_area = 1; for (i = 0; i < (nseg_clip - 1); i++) { if (wraps && wrap_area(area_clip[i].lat, area_clip[i].lon, area_clip[i+1].lat, area_clip[i+1].lon, &tlat1, &tlon1, &tlat2, &tlon2)) { /* Crosses boundary */ switch (curr_area) { case 1: /* finish segment in part 1, begin part 2 */ area_1[nseg_1].lat = area_clip[i].lat; area_1[nseg_1].lon = area_clip[i].lon; area_1[nseg_1].great_circle = area_clip[i].great_circle; area_1[nseg_1].clipped_at = area_clip[i].clipped_at; nseg_1++; area_1[nseg_1].lat = tlat1; area_1[nseg_1].lon = tlon1; area_1[nseg_1].great_circle = area_clip[i].great_circle; area_1[nseg_1].clipped_at = area_clip[i].clipped_at; nseg_1++; curr_area = 2; area_2[nseg_2].lat = tlat2; area_2[nseg_2].lon = tlon2; area_2[nseg_2].great_circle = area_clip[i].great_circle; area_2[nseg_2].clipped_at = area_clip[i].clipped_at; nseg_2++; gt12 = (tlon1 > tlon2); /* area 1 greater than area 2 */ break; case 2: /* finish part 2, draw it, close gap in part 1 */ if (((gt12) && (tlon1 < tlon2)) || ((!gt12) && (tlon1 > tlon2))){ tlat3 = tlat1; tlon3 = tlon1; tlat1 = tlat2; tlon1 = tlon2; tlat2 = tlat3; tlon2 = tlon3; }; area_2[nseg_2].lat = area_clip[i].lat; area_2[nseg_2].lon = area_clip[i].lon; area_2[nseg_2].great_circle = area_clip[i].great_circle; area_2[nseg_2].clipped_at = area_clip[i].clipped_at; nseg_2++; area_2[nseg_2].lat = tlat2; area_2[nseg_2].lon = tlon2; area_2[nseg_2].great_circle = area_clip[i].great_circle; area_2[nseg_2].clipped_at = area_clip[i].clipped_at; nseg_2++; area_2[nseg_2].lat = area_2[0].lat; area_2[nseg_2].lon = area_2[0].lon; area_2[nseg_2].great_circle = TRUE; area_2[nseg_2].clipped_at = area_2[0].clipped_at; nseg_2++; doarea(area_2, nseg_2); curr_area = 1; area_1[nseg_1].lat = tlat1; area_1[nseg_1].lon = tlon1; area_1[nseg_1].great_circle = TRUE; area_1[nseg_1].clipped_at = area_1[nseg_1-1].clipped_at; nseg_1++; break; default: break; }; } else { switch (curr_area) { case 1: area_1[nseg_1].lat = area_clip[i].lat; area_1[nseg_1].lon = area_clip[i].lon; area_1[nseg_1].great_circle = area_clip[i].great_circle; area_1[nseg_1].clipped_at = area_clip[i].clipped_at; nseg_1++; break; case 2: area_2[nseg_2].lat = area_clip[i].lat; area_2[nseg_2].lon = area_clip[i].lon; area_2[nseg_2].great_circle = area_clip[i].great_circle; area_2[nseg_2].clipped_at = area_clip[i].clipped_at; nseg_2++; break; default: break; } } }; if (nseg_clip > 0) { area_1[nseg_1].lat = area_clip[nseg_clip-1].lat; area_1[nseg_1].lon = area_clip[nseg_clip-1].lon; area_1[nseg_1].great_circle = area_clip[nseg_clip-1].great_circle; area_1[nseg_1].clipped_at = area_clip[nseg_clip-1].clipped_at; nseg_1++; }; if (nseg_1 > 0) doarea(area_1, nseg_1); }; /* Mark it done */ nsegments = 0; } doarea(area, nseg) struct t_area_struct area[]; int nseg; { int i; int xloc, yloc, xloc2, yloc2; double tlat1, tlon1, tlat2, tlon2; for (i = 0; i < (nseg - 1); i++) { if (clipr_xform(area[i].lat, area[i].lon, area[i+1].lat, area[i+1].lon, &xloc, &yloc, &xloc2, &yloc2, area[i+1].great_circle, &tlat1, &tlon1, &tlat2, &tlon2)) { if (i == 0) D_areamove(xloc, yloc); /* Here we can add tests to add segments along the boundary of projection modes other than SANSONS and RECTANGULAR */ addareacurved(tlat1, tlon1, tlat2, tlon2, xloc, yloc, xloc2, yloc2, area[i+1].great_circle, 0); if (i == (nseg - 2)) D_areafill(xloc2, yloc2); } } } int wrap_area(lat1, lon1, lat2, lon2, plat1, plon1, plat2, plon2) double lat1, lon1, lat2, lon2; double *plat1, *plon1, *plat2, *plon2; { double slope1, tlat1, tlat2; /* Adjust so lon1 and lon2 are continuous across region: see xform */ /* needed so midpoint is correct */ if ((xfs_proj_mode == SANSONS) || (xfs_proj_mode == RECTANGULAR)) { if ((xf_west < 0.0) && (lon1>(xf_west+360.0))) lon1 -= 360.0; if ((xf_east > 360.0) && (lon1<(xf_east-360.0))) lon1 += 360.0; if ((xf_west < 0.0) && (lon2>(xf_west+360.0))) lon2 -= 360.0; if ((xf_east > 360.0) && (lon2<(xf_east-360.0))) lon2 += 360.0; /* path crosses boundary of map */ /* if the distance from point1 to left (East) + point2 to right or point2 to right and point2 to left is less than distance from point1 to point2, then we have a problem. */ if (xfs_wide_warn) if ((fabs(lon1-xf_east) + fabs(xf_west-lon2)) < (fabs(lon1-lon2))) { /* point 1 close to east boundary */ slope1 = (lat2 - lat1)/(fabs(lon1-xf_east) + fabs(xf_west-lon2)); tlat1 = lat1 + slope1 * fabs(lon1-(xf_east-xf_c_scale)); /* segment from (lat1, lon1) to (tlat1, xf_east-xf_c_scale) is on one side of boundary */ *plat1 = tlat1; *plon1 = xf_east-xf_c_scale; if (*plon1 > 360) *plon1 -= 360; if (*plon1 < 0) *plon1 += 360; tlat2 = lat2 - slope1 * fabs(lon2-(xf_west+xf_c_scale)); /* segment from (tlat2, xf_west+xf_c_scale) to (lat2, lon2) is on one side of boundary */ *plat2 = tlat2; *plon2 = xf_west+xf_c_scale; if (*plon2 > 360) *plon2 -= 360; if (*plon2 < 0) *plon2 += 360; return TRUE; } else if ((fabs(lon2-xf_east)+fabs(xf_west-lon1)) < (fabs(lon1-lon2))) { /* point 1 close to west boundary */ slope1 = (lat1 - lat2)/(fabs(lon2-xf_east) + fabs(xf_west-lon1)); tlat1 = lat2 + slope1 * fabs(lon2-(xf_east-xf_c_scale)); /* segment from (lat2, lon2) to (tlat1, xf_east-xf_c_scale) is on one side of boundary */ *plat2 = tlat1; *plon2 = xf_east-xf_c_scale; if (*plon2 > 360) *plon2 -= 360; if (*plon2 < 0) *plon2 += 360; tlat2 = lat1 - slope1 * fabs(lon1-(xf_west+xf_c_scale)); /* segment from (tlat2, xf_west+xf_c_scale) to (lat1, lon1) is on one side of boundary */ *plat1 = tlat2; *plon1 = xf_west+xf_c_scale; if (*plon1 > 360) *plon1 -= 360; if (*plon1 < 0) *plon1 += 360; return TRUE; }; } return FALSE; } addsegment(tlat1, tlon1, tlat2, tlon2, last_clip, clip_1, clip_2, gc_1, gc_2) double tlat1, tlon1, tlat2, tlon2; int last_clip, clip_1, clip_2; int gc_1, gc_2; { /* just add a segment */ area_clip[nseg_clip].lat = tlat1; area_clip[nseg_clip].lon = tlon1; area_clip[nseg_clip].great_circle = gc_1; area_clip[nseg_clip].clipped_at = clip_1; nseg_clip++; area_clip[nseg_clip].lat = tlat2; area_clip[nseg_clip].lon = tlon2; area_clip[nseg_clip].great_circle = gc_2; area_clip[nseg_clip].clipped_at = clip_2; nseg_clip++; } /* addareacurved: add a set of boundary segments between points 1 and 2 clipxform has been called, xloc1, yloc1, xloc2, yloc2 are in bounds */ addareacurved(lat1, lon1, lat2, lon2, xloc1, yloc1, xloc2, yloc2, great_circle, clevel) int xloc1, yloc1, xloc2, yloc2; double lat1, lon1, lat2, lon2; int great_circle; /* draw as great circle */ int clevel; /* safety valve */ { double mlat, mlon; /* midpoint lat and long */ int mxloc, myloc; /* transformed */ int mpx, mpy; /* from given x,y */ int inregion; /* ra difference should be less than 180 degrees: take shortest path */ if ((xfs_proj_mode == STEREOGR) || (xfs_proj_mode == GNOMONIC) || (xfs_proj_mode == ORTHOGR)) if ((lon1 - lon2) > 180.0) lon1 -= 360.0; else if ((lon2 - lon1) > 180.0) lon2 -= 360.0; /* Adjust so lon1 and lon2 are continuous across region: see xform */ /* needed so midpoint is correct */ if ((xfs_proj_mode == SANSONS) || (xfs_proj_mode == RECTANGULAR)) { if ((xf_west < 0.0) && (lon1>(xf_west+360.0))) lon1 -= 360.0; if ((xf_east > 360.0) && (lon1<(xf_east-360.0))) lon1 += 360.0; if ((xf_west < 0.0) && (lon2>(xf_west+360.0))) lon2 -= 360.0; if ((xf_east > 360.0) && (lon2<(xf_east-360.0))) lon2 += 360.0; } if (great_circle) { gcmidpoint(lat1, lon1, lat2, lon2, &mlat, &mlon); } else { mlat = (lat1 + lat2)/2; mlon = (lon1 + lon2)/2; }; xform(mlat, mlon, &mxloc, &myloc, &inregion); mpx = (xloc1 + xloc2)/2; mpy = (yloc1 + yloc2)/2; if (((abs(mpx - mxloc) + abs(mpy - myloc)) > 0) && (clevel < 100)) { /* center is not where it should be */ addareacurved(lat1, lon1, mlat, mlon, xloc1, yloc1, mxloc, myloc, great_circle, ++clevel); addareacurved(mlat, mlon, lat2, lon2, mxloc, myloc, xloc2, yloc2, great_circle, ++clevel); } else { D_areaadd(xloc2, yloc2); } } #endif // NEEDED
C
/* ** EPITECH PROJECT, 2019 ** BSQ : display_result.h ** File description: ** Displays the map with 'X's where the biggest square is located. (header) */ #ifndef DEF_DISPLAY_RESULT #define DEF_DISPLAY_RESULT #include <unistd.h> #include "map.h" #include "square.h" void display_result(map_t *map, square *biggest_square); void display_character(map_t *map, int row, int col, square *biggest_sqr); void my_putchar(char c); #endif // DEF_DISPLAY_RESULT
C
//input : 1401601499 //output: legal // 1*1+4*2+0*3+1*4+6*5+0*6+1*7+4*8+9*9+9*10=253 //253%11=0 ===> legal // =1===> illegal #include<stdio.h> int main() { int isbn,sum=0,count=0; printf("enter the value of ISBN number "); scanf("%d",&isbn); while(isbn%10!=0) { //140160149900 isbn=isbn/10; count++; } if(count==10) { for(int i=10;i>0;i--) { int a=isbn%10; sum=sum+(a*i); isbn=isbn/10; } sum=sum%11; if(sum==0) printf("the isbn number is LEGAL"); else printf("the isbn number is ILLEGAL"); } else printf("the number isILLEGAL"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printf.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: eserebry <eserebry@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/08/19 20:34:30 by eserebry #+# #+# */ /* Updated: 2017/09/21 22:54:14 by eserebry ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" void flag_init(t_flag *flag) { flag->sp = 0; flag->plus = 0; flag->neg = 0; flag->minus = 0; flag->hash = 0; flag->zero = 0; flag->prec = -1; flag->width = 0; } void print_conversion(const char *restrict format, t_printf *e) { e->i++; set_tag(format, e); set_flag(format, e); get_spec(format, e); } int ft_printf(const char *restrict format, ...) { t_printf e; e.i = 0; e.ret = 0; e.fd = 1; va_start(e.ap[0], format); va_copy(e.ap[1], e.ap[0]); while (format[e.i] != '\0') { if (format[e.i] == '{') check_settings(format, &e); else if (format[e.i] == '%' && format[e.i + 1] != '%') print_conversion(format, &e); else if (format[e.i] == '%' && format[e.i + 1] == '%') { e.ret += write(e.fd, "%", 1); e.i += 2; } else e.ret += write(e.fd, &format[e.i++], 1); } va_end(e.ap[0]); return (e.ret); }
C
#include <stdio.h> #include "st_vector.h" int main() { st_vector(int) Z; st_init(Z); st_push(Z,123); st_push(Z,435); st_push(Z,567); printf("%zu\n", Z.len); int z = st_pop(Z); z = st_pop(Z); printf("%d\n", z); st_free(Z); return 0; }
C
#include "Redovi.h" #include <stdlib.h> void insertPQueue(deoReda **red, deoReda *deo) { deoReda *tr = *red, *pred = NULL; if (tr == NULL) { *red = deo; (*red)->sledeci = NULL; } else { while ((tr != NULL) && (deo->razdaljna>tr->razdaljna)) { pred = tr; tr = tr->sledeci; } if (pred == NULL) { deo->sledeci = *red; *red = deo; } else if (tr == NULL) { pred->sledeci = deo; deo->sledeci = NULL; } else { deo->sledeci = tr; pred->sledeci = deo; } } return; } deoReda* deletePQueue(deoReda **red) { deoReda *tr = *red; if (tr == NULL) return NULL; else { *red = tr->sledeci; tr->sledeci = NULL; } return tr; } void clearPQueue(deoReda *red) { deoReda *tr = red, *pom; while (tr != NULL) { pom = tr->sledeci; tr->sledeci = NULL; free(tr); tr = pom; } return; } //fje za rad sa prioritetnim redom po razdaljini void insertQueue(deoReda **red, deoReda *deo) { deoReda *tr = *red; if (tr == NULL) { *red = deo; (*red)->sledeci = NULL; } else { while (tr->sledeci != NULL) { tr = tr->sledeci; } tr->sledeci = deo; } return; }
C
#include<stdio.h> #define MIN(c,d) (c < d ? c : d) #define MAX(a,b) (a > b ? a : b) int main() { int t,a,b,c; int i; scanf("%d",&t); for(i = 1; i <= t; i++) { scanf("%d %d %d",&a,&b,&c); if((a > b && b > c) || (c > b && b > a)) { printf("Case %d: %d\n",i,b); } else if((b > a && a > c) || (c > a && a > b)) { printf("Case %d: %d\n",i,a); } else if(((a > c && c > b) || (b > c && c > a))) { printf("Case %d: %d\n",i,c); } } return 0; }
C
/** * Author: João Leal© * * Revised by: Bruno Veiga - 1180712 * Revised by: Bruno Ribeiro - 1180573 */ #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <sys/wait.h> #include <string.h> #include <time.h> #include <semaphore.h> #include "structs.h" /** * This program serves as an user interface */ int main() { int fd, data_size=sizeof(Shm_struct); char input; sem_t *sems[5]; Shm_struct *sh_data; /* opens shared memory */ fd = shm_open("/shm_ex10", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); if (fd==-1) { perror("Shared memory failure."); exit(1); } if (ftruncate(fd, data_size)==-1) { perror("Size allocation failure."); exit(1); } sh_data=(Shm_struct *) mmap(NULL, data_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (sh_data==MAP_FAILED) { perror("Mmap failure."); exit(1); } /* Initializes struct variables */ sh_data->readcount=0; sh_data->writercount=0; /* opens semaphores */ /* protects variable readcount */ if ((sems[0] = sem_open("mute1", O_CREAT | O_RDWR, 0644, 1)) == SEM_FAILED) { perror("Semaphore failure."); exit(1); } /* protects variable writercount */ if ((sems[1] = sem_open("mute2", O_CREAT | O_RDWR, 0644, 1)) == SEM_FAILED) { perror("Semaphore failure."); exit(1); } /* makes sure only one reader is trying to access records */ if ((sems[2] = sem_open("mute3", O_CREAT | O_RDWR, 0644, 1)) == SEM_FAILED) { perror("Semaphore failure."); exit(1); } /* writer semaphore */ if ((sems[3] = sem_open("writer", O_CREAT | O_RDWR, 0644, 1)) == SEM_FAILED) { perror("Semaphore failure."); exit(1); } /* reader semaphore */ if ((sems[4] = sem_open("reader", O_CREAT | O_RDWR, 0644, 1)) == SEM_FAILED) { perror("Semaphore failure."); exit(1); } do { printf("\n1 - Insert record\n2 - Consult record\n3 - Consult all records\n4 - Clear memory\n0 - Exit\n\n"); scanf("%c%*c", &input); switch (input) { case '1': system("./insert"); break; case '2': system("./consult"); break; case '3': system("./consult_all"); break; case '4': system("./clear_mem"); break; case '0': printf("Closing program...\n"); break; default: printf("Input not recognized\n"); break; } } while (input!='0'); /* Closes shared memeory */ if(munmap(sh_data, data_size)==-1) { perror("Munmap failure."); exit(1); } close(fd); return 0; }
C
#include <unistd.h> #include "internalFuncts.c" int displayheader(struct posix_header *header) { printf("======= EXTRACTING THE FILE =======\n"); printf("GETTING THE HEADER...\n"); printf("Filename is %s\n", header->name); printf("%s\n", header->size); printf( "===================================\n" ); return 0; } int append() { int chk = 0; return chk; } int appendNew() { int chk = 0; return chk; } int create(int fd_arch, char** files, int fcount) // fill tar file with contents { int chk = 0; printf("fcount = %d", fcount); struct posix_header *header; for(int fileNum = 0; fileNum != fcount; fileNum ++) { header = getHeaderInfo( files[ fileNum ] ); if( header != NULL ) { write(fd_arch, header, 512); if (header->typeflag != DIRTYPE) writeFileContent( fd_arch, files[ fileNum ] ); else { chk -= recursiveTar(header->name, fd_arch); } free( header ); } else { chk ++; printf("tar: Error archiving %s\n", files[fileNum]); } } fillMissing( fd_arch ); return chk; } int extract(int fd_arch, char *archname, int fcount, char** files) // extract the contents to the new files { long int i = 0; long int size = 0; int chk = 0; int fchk = 0; //int size = 0; long int archsize = getSize(archname); printf("tar file size is %ld\n", archsize); while(i < archsize) { // if (i > 0) // i += 512 - (i % 512); headerInfo *header = reverseHeader(fd_arch, i); i += 512; displayheader(header); if((fcount > 0 && cmpName(files[fchk], header->name) == 0) || fcount == 0) { if (header != NULL && getLength(header->name) > 0) { if (header->typeflag != DIRTYPE) { createReg(header, fd_arch); long int size = getBlocksSize(reverseConvert(header->size, 8)); i += size; } else { chk -= createDir(header); printf("This is a dir with the name %s\n", header->name); } free(header); } else { chk++; free(header); return chk; } } printf("Stopped at %ld byte. Size is %ld\n", i, size); if (i < 0 && size < 0) return 2; } return chk; } int list(int archfd, int fcount, char** filenames) // list the filenames { int chk = 0; int i = 0; char* filename = malloc(100); while(filename != NULL) { headerInfo *header = reverseHeader(archfd, i); filename = header->name; if (fcount == 0 || (fcount > 0 && cmpName(filenames[i], filename) == 0)) { if (getLength(filename) <= 0) break; long int size = getBlocksSize(reverseConvert(header->size, 8)); i += 512 + size; printf("%s\n", filename); } } free(filename); return chk; } int fManip(struct Options opts) { switch (opts.mod) { case 'r': append(); break; case 'u': appendNew(); break; case 'c': create(opts.archfd, opts.files, opts.fcount); break; case 'x': extract(opts.archfd, opts.archname, opts.fcount, opts.files); break; case 't': list(opts.archfd, opts.fcount, opts.files); } return 0; }
C
#include"headers.h" void execute_history(char ** parsed_commands){ int num=10; if(history_latest!=19){num=history_latest+1;} if(parsed_commands[1]!=NULL)num=atoi(parsed_commands[1]); if(num>=11)num=10; for(int i=0;i<num;i++){ printf("%s",history[history_latest-i]); } }
C
#include <stdlib.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <sys/io.h> #include <stdio.h> #include <errno.h> #include "ledmatrixUtils.h" #include "i2c-utils.h" #include <legato.h> // private variables static uint8_t led_matrix_currentDeviceAddress; static uint8_t led_matrix_offsetAddress; static uint8_t led_matrix_baseAddress; static uint32_t led_matrix_deviceId[3]; // Unique device ID(96 bits: Low, Middle, High) static char led_matrix_i2c_bus[255] = "/dev/i2c-0"; static void i2cSendByte(uint8_t address, uint8_t data) { int i2c_fd = open(led_matrix_i2c_bus, O_RDWR); if (i2c_fd < 0) { LE_ERROR("i2cSendByte: failed to open %s", led_matrix_i2c_bus); } if (ioctl(i2c_fd, I2C_SLAVE_FORCE, address) < 0) { LE_ERROR("Could not set address to 0x%02x: %s\n", address, strerror(errno)); return; } i2c_smbus_write_byte(i2c_fd, data); close(i2c_fd); } static void i2cSendBytes(uint8_t address, uint8_t *data, uint8_t len) { int i2c_fd = open(led_matrix_i2c_bus, O_RDWR); if (i2c_fd < 0) { LE_ERROR("i2cSendByte: failed to open %s", led_matrix_i2c_bus); } if (ioctl(i2c_fd, I2C_SLAVE_FORCE, address) < 0) { LE_ERROR("Could not set address to 0x%02x: %s\n", address, strerror(errno)); return; } i2c_smbus_write_i2c_block_data(i2c_fd, data[0], len-1, data+1); close(i2c_fd); } static void i2cSendContinueBytes(uint8_t address, uint8_t *data, uint8_t len) { uint8_t cbytes = I2C_CMD_CONTINUE_DATA; int i2c_fd = open(led_matrix_i2c_bus, O_RDWR); if (i2c_fd < 0) { LE_ERROR("i2cSendByte: failed to open %s", led_matrix_i2c_bus); } if (ioctl(i2c_fd, I2C_SLAVE_FORCE, address) < 0) { LE_ERROR("Could not set address to 0x%02x: %s\n", address, strerror(errno)); return; } i2c_smbus_write_i2c_block_data(i2c_fd, cbytes, len+1, data); close(i2c_fd); } static void i2cReceiveBytes(uint8_t address, uint8_t *data, uint8_t len) { int i2c_fd = open(led_matrix_i2c_bus, O_RDWR); if (i2c_fd < 0) { LE_ERROR("i2cSendByte: failed to open %s", led_matrix_i2c_bus); } if (ioctl(i2c_fd, I2C_SLAVE_FORCE, address) < 0) { LE_ERROR("Could not set address to 0x%02x: %s\n", address, strerror(errno)); return; } i2c_smbus_read_i2c_block_data(i2c_fd, 0, len, data); close(i2c_fd); } // /************************************************************* // * Description // * Get vendor ID of device. // * Parameter // * Null. // * Return // * Return vendor ID of device. // *************************************************************/ static uint16_t led_matrix_getDeviceVID(void) { uint8_t data[4] = {0, }; i2cSendByte(led_matrix_currentDeviceAddress, I2C_CMD_GET_DEV_ID); i2cReceiveBytes(led_matrix_currentDeviceAddress, data, 4); return (uint16_t)(data[0] + data[1] * 256); } // /************************************************************* // * Description // * Get product ID of device. // * Parameter // * Null. // * Return // * Return product ID of device. // *************************************************************/ static uint16_t led_matrix_getDevicePID(void) { uint8_t data[4] = {0, }; i2cSendByte(led_matrix_currentDeviceAddress, I2C_CMD_GET_DEV_ID); i2cReceiveBytes(led_matrix_currentDeviceAddress, data, 4); return (uint16_t)(data[2] + data[3] * 256); } // /************************************************************* // * Description // * Change i2c base address of device. // * Parameter // * newAddress: 0x10-0x70, The new i2c base address of device. // * Return // * Null. // *************************************************************/ static void led_matrix_changeDevicebaseAddress(uint8_t newAddress) { uint8_t data[2] = {0, }; if (!(newAddress >= 0x10 && newAddress <= 0x70)) { newAddress = GROVE_TWO_RGB_LED_MATRIX_DEF_I2C_ADDR; } data[0] = I2C_CMD_SET_ADDR; data[1] = newAddress; led_matrix_baseAddress = newAddress; i2cSendBytes(led_matrix_currentDeviceAddress, data, 2); led_matrix_currentDeviceAddress = led_matrix_baseAddress + led_matrix_offsetAddress; sleep(0.2); } // /************************************************************* // * Description // * Restore the i2c address of device to default. // * Parameter // * Null. // * Return // * Null. // *************************************************************/ static void led_matrix_defaultDeviceAddress(void) { i2cSendByte(led_matrix_currentDeviceAddress, I2C_CMD_RST_ADDR); led_matrix_baseAddress = GROVE_TWO_RGB_LED_MATRIX_DEF_I2C_ADDR; led_matrix_currentDeviceAddress = led_matrix_baseAddress + led_matrix_offsetAddress; sleep(0.2); } // /************************************************************* // * Description // * Turn on the indicator LED flash mode. // * Parameter // * Null. // * Return // * Null. // *************************************************************/ static void led_matrix_turnOnLedFlash(void) { i2cSendByte(led_matrix_currentDeviceAddress, I2C_CMD_LED_ON); } // /************************************************************* // * Description // * Turn off the indicator LED flash mode. // * Parameter // * Null. // * Return // * Null. // *************************************************************/ static void led_matrix_turnOffLedFlash(void) { i2cSendByte(led_matrix_currentDeviceAddress, I2C_CMD_LED_OFF); } // /************************************************************* // * Description // * Enable device auto sleep mode. Send any I2C commands will // * wake up all the sleepy devices. // * Parameter // * Null. // * Return // * Null. // *************************************************************/ static void led_matrix_enableAutoSleep(void) { i2cSendByte(led_matrix_currentDeviceAddress, I2C_CMD_AUTO_SLEEP_ON); } // /************************************************************* // * Description // * Don't need this function anymore. // * (Wake device from sleep mode. It takes about 0.15ms.) // * Parameter // * Null. // * Return // * Null. // *************************************************************/ static void led_matrix_wakeDevice(void) { usleep(200); } // /************************************************************* // * Description // * Disable device auto sleep mode. // * Parameter // * Null. // * Return // * Null. // *************************************************************/ static void led_matrix_disableAutoSleep(void) { i2cSendByte(led_matrix_currentDeviceAddress, I2C_CMD_AUTO_SLEEP_OFF); } // /************************************************************* // * Description // * Setting the display orientation. // * This function can be used before or after display. // * DO NOT WORK with displayColorWave(), displayClockwise(), displayColorAnimation() // * Parameter // * orientation: DISPLAY_ROTATE_0, DISPLAY_ROTATE_90, DISPLAY_ROTATE_180, // * DISPLAY_ROTATE_270, which means the display will rotate 0°, 90°,180° or 270°. // * Return // * Null. // *************************************************************/ static void led_matrix_setDisplayOrientation(enum orientation_type_t orientation) { uint8_t data[2] = {0, }; data[0] = I2C_CMD_DISP_ROTATE; data[1] = (uint8_t)orientation; i2cSendBytes(led_matrix_currentDeviceAddress, data, 2); } // /************************************************************* // * Description // * Setting the display offset of x-axis and y-axis. // * This function can be used before or after display. // * DO NOT WORK with displayColorWave(), displayClockwise(), displayColorAnimation(), // * displayNumber(when number<0 or number>=10), displayString(when more than one character) // * Parameter // * offset_x: The display offset value of horizontal x-axis, range from -8 to 8. // * offset_y: The display offset value of horizontal y-axis, range from -8 to 8. // * Return // * Null. // *************************************************************/ static void led_matrix_setDisplayOffset(int offset_x, int offset_y) { // convert to positive offset_x +=8; offset_y +=8; if (offset_x < 0) offset_x = 0; else if (offset_x > 16) offset_x = 16; if (offset_y < 0) offset_y = 0; else if (offset_y > 16) offset_y = 16; uint8_t data[3] = {0, }; data[0] = I2C_CMD_DISP_OFFSET; data[1] = (uint8_t)offset_x; data[2] = (uint8_t)offset_y; i2cSendBytes(led_matrix_currentDeviceAddress, data, 3); } // /************************************************************* // * Description // * Display a bar on RGB LED Matrix. // * Parameter // * bar: 0 - 32. 0 is blank and 32 is full. // * duration_time: Set the display time(ms) duration. Set it to 0 to not display. // * forever_flag: Set it to true to display forever, and the duration_time will not work. // * Or set it to false to display one time. // * color: Set the color of the display, range from 0 to 255. See COLORS for more details. // * Return // * Null. // *************************************************************/ static void led_matrix_displayBar(uint8_t bar, uint16_t duration_time, bool forever_flag, uint8_t color) { uint8_t data[6] = {0, }; data[0] = I2C_CMD_DISP_BAR; if (bar > 32) bar = 32; data[1] = bar; data[2] = (uint8_t)(duration_time & 0xff); data[3] = (uint8_t)((duration_time >> 8) & 0xff); data[4] = forever_flag; data[5] = color; i2cSendBytes(led_matrix_currentDeviceAddress, data, 6); } // /************************************************************* // * Description // * Display a colorful bar on RGB LED Matrix. // * Parameter // * bar: 0 - 32. 0 is blank and 32 is full. // * duration_time: Set the display time(ms) duration. Set it to 0 to not display. // * forever_flag: Set it to true to display forever, and the duration_time will not work. // * Or set it to false to display one time. // * Return // * Null. // *************************************************************/ static void led_matrix_displayColorBar(uint8_t bar, uint16_t duration_time, bool forever_flag) { uint8_t data[5] = {0, }; data[0] = I2C_CMD_DISP_COLOR_BAR; if (bar > 32) bar = 32; data[1] = bar; data[2] = (uint8_t)(duration_time & 0xff); data[3] = (uint8_t)((duration_time >> 8) & 0xff); data[4] = forever_flag; i2cSendBytes(led_matrix_currentDeviceAddress, data, 5); } // /************************************************************* // * Description // * Display a wave on RGB LED Matrix. // * Parameter // * color: Set the color of the display, range from 0 to 255. See COLORS for more details. // * duration_time: Set the display time(ms) duration. Set it to 0 to not display. // * forever_flag: Set it to true to display forever, and the duration_time will not work. // * Or set it to false to display one time. // * Return // * Null. // *************************************************************/ static void led_matrix_displayColorWave(uint8_t color, uint16_t duration_time, bool forever_flag) { uint8_t data[5] = {0, }; data[0] = I2C_CMD_DISP_COLOR_WAVE; data[1] = color; data[2] = (uint8_t)(duration_time & 0xff); data[3] = (uint8_t)((duration_time >> 8) & 0xff); data[4] = forever_flag; i2cSendBytes(led_matrix_currentDeviceAddress, data, 5); } // /************************************************************* // * Description // * Display a clockwise(or anti-clockwise) animation on RGB LED Matrix. // * Parameter // * is_cw: Set it true to display a clockwise animation, while set it false to display a anti-clockwise // * is_big: Set it true to display a 8*8 animation, while set it false to display a 4*4 animation // * duration_time: Set the display time(ms) duration. Set it to 0 to not display. // * forever_flag: Set it to true to display forever, and the duration_time will not work. // * Or set it to false to display one time. // * Return // * Null. // *************************************************************/ static void led_matrix_displayClockwise(bool is_cw, bool is_big, uint16_t duration_time, bool forever_flag) { uint8_t data[6] = {0, }; data[0] = I2C_CMD_DISP_COLOR_CLOCKWISE; data[1] = is_cw; data[2] = is_big; data[3] = (uint8_t)(duration_time & 0xff); data[4] = (uint8_t)((duration_time >> 8) & 0xff); data[5] = forever_flag; i2cSendBytes(led_matrix_currentDeviceAddress, data, 6); } // /************************************************************* // * Description // * Display other built-in animations on RGB LED Matrix. // * Parameter // * index: the index of animations, // * 0. big clockwise // * 1. small clockwise // * 2. rainbow cycle // * 3. fire // * 4. walking child // * 5. broken heart // * duration_time: Set the display time(ms) duration. Set it to 0 to not display. // * forever_flag: Set it to true to display forever, and the duration_time will not work. // * Or set it to false to display one time. // * Return // * Null. // *************************************************************/ static void led_matrix_displayColorAnimation(uint8_t index, uint16_t duration_time, bool forever_flag) { uint8_t data[6] = {0, }; uint8_t from, to; data[0] = I2C_CMD_DISP_COLOR_ANIMATION; switch(index) { case 0: from = 0; to = 28; break; case 1: from = 29; to = 41; break; case 2: // rainbow cycle from = 255; to = 255; break; case 3: // fire from = 254; to = 254; break; case 4: // walking from = 42; to = 43; break; case 5: // broken heart from = 44; to = 52; break; default: break; } data[1] = from; data[2] = to; data[3] = (uint8_t)(duration_time & 0xff); data[4] = (uint8_t)((duration_time >> 8) & 0xff); data[5] = forever_flag; i2cSendBytes(led_matrix_currentDeviceAddress, data, 6); } // /************************************************************* // * Description // * Display emoji on LED matrix. // * Parameter // * emoji: Set a number from 0 to 29 for different emoji. // * 0 smile 10 heart 20 house // * 1 laugh 11 small heart 21 tree // * 2 sad 12 broken heart 22 flower // * 3 mad 13 waterdrop 23 umbrella // * 4 angry 14 flame 24 rain // * 5 cry 15 creeper 25 monster // * 6 greedy 16 mad creeper 26 crab // * 7 cool 17 sword 27 duck // * 8 shy 18 wooden sword 28 rabbit // * 9 awkward 19 crystal sword 29 cat // * 30 up 31 down 32 left // * 33 right 34 smile face 3 // * duration_time: Set the display time(ms) duration. Set it to 0 to not display. // * forever_flag: Set it to true to display forever, and the duration_time will not work. // * Or set it to false to display one time. // * Return // * Null. // *************************************************************/ static void led_matrix_displayEmoji(uint8_t emoji, uint16_t duration_time, bool forever_flag) { uint8_t data[5] = {0, }; data[0] = I2C_CMD_DISP_EMOJI; data[1] = emoji; data[2] = (uint8_t)(duration_time & 0xff); data[3] = (uint8_t)((duration_time >> 8) & 0xff); data[4] = forever_flag; i2cSendBytes(led_matrix_currentDeviceAddress, data, 5); } // /************************************************************* // * Description // * Display a number(-32768 ~ 32767) on LED matrix. // * Parameter // * number: Set the number you want to display on LED matrix. Number(except 0-9) // * will scroll horizontally, the shorter you set the duration time, // * the faster it scrolls. The number range from -32768 to +32767, if // * you want to display larger number, please use displayString(). // * duration_time: Set the display time(ms) duration. Set it to 0 to not display. // * forever_flag: Set it to true to display forever, or set it to false to display one time. // * color: Set the color of the display, range from 0 to 255. See COLORS for more details. // * Return // * Null. // *************************************************************/ static void led_matrix_displayNumber(int16_t number, uint16_t duration_time, bool forever_flag, uint8_t color) { uint8_t data[7] = {0, }; data[0] = I2C_CMD_DISP_NUM; data[1] = (uint8_t)((uint16_t)number & 0xff); data[2] = (uint8_t)(((uint16_t)number >> 8) & 0xff); data[3] = (uint8_t)(duration_time & 0xff); data[4] = (uint8_t)((duration_time >> 8) & 0xff); data[5] = forever_flag; data[6] = color; i2cSendBytes(led_matrix_currentDeviceAddress, data, 7); } // /************************************************************* // * Description // * Display a string on LED matrix. // * Parameter // * str: The string pointer, the maximum length is 28 bytes. String will // * scroll horizontally when its length is more than 1. The shorter // * you set the duration time, the faster it scrolls. // * duration_time: Set the display time(ms) duration. Set it to 0 to not display. // * forever_flag: Set it to true to display forever, or set it to false to display one time. // * color: Set the color of the display, range from 0 to 255. See COLORS for more details. // * Return // * Null. // *************************************************************/ static void led_matrix_displayString(char *str, uint16_t duration_time, bool forever_flag, uint8_t color) { uint8_t data[36] = {0, }; uint8_t len = strlen(str); if (len >= 28) len = 28; for (uint8_t i = 0; i < len; i++) data[i + 6] = str[i]; data[0] = I2C_CMD_DISP_STR; data[1] = forever_flag; data[2] = (uint8_t)(duration_time & 0xff); data[3] = (uint8_t)((duration_time >> 8) & 0xff); data[4] = len; data[5] = color; if (len > 25) { i2cSendBytes(led_matrix_currentDeviceAddress, data, 31); usleep(1000); // 1ms i2cSendContinueBytes(led_matrix_currentDeviceAddress, data+31, (len - 25)); } else { i2cSendBytes(led_matrix_currentDeviceAddress, data, (len + 6)); } } // /************************************************************* // * Description // * Display user-defined frames on LED matrix. // * Parameter // * buffer: The data pointer. 1 frame needs 64bytes data. Frames will switch // * automatically when the frames_number is larger than 1. The shorter // * you set the duration_time, the faster it switches. // * duration_time: Set the display time(ms) duration. Set it to 0 to not display. // * forever_flag: Set it to true to display forever, or set it to false to display one time. // * frames_number: the number of frames in your buffer. Range from 1 to 5. // * Return // * Null. // *************************************************************/ static void led_matrix_displayFrames(uint8_t *buffer, uint16_t duration_time, bool forever_flag, uint8_t frames_number) { uint8_t data[72] = {0, }; // max 5 frames in storage if (frames_number > 5) frames_number = 5; else if (frames_number == 0) return; data[0] = I2C_CMD_DISP_CUSTOM; data[1] = 0x0; data[2] = 0x0; data[3] = 0x0; data[4] = frames_number; for (int i = frames_number-1; i >= 0; i--) { data[5] = i; for (int j = 0; j < 64; j++) data[8+j] = buffer[j+i*64]; if (i == 0) { // display when everything is finished. data[1] = (uint8_t)(duration_time & 0xff); data[2] = (uint8_t)((duration_time >> 8) & 0xff); data[3] = forever_flag; } i2cSendBytes(led_matrix_currentDeviceAddress, data, 24); usleep(1000); i2cSendContinueBytes(led_matrix_currentDeviceAddress, data+24, 24); usleep(1000); i2cSendContinueBytes(led_matrix_currentDeviceAddress, data+48, 24); } } static void led_matrix_displayFrames64(uint64_t *buffer, uint16_t duration_time, bool forever_flag, uint8_t frames_number) { uint8_t data[72] = {0, }; // max 5 frames in storage if (frames_number > 5) frames_number = 5; else if (frames_number == 0) return; data[0] = I2C_CMD_DISP_CUSTOM; data[1] = 0x0; data[2] = 0x0; data[3] = 0x0; data[4] = frames_number; for (int i = frames_number - 1; i >= 0; i--) { data[5] = i; // different from uint8_t buffer for (int j = 0; j < 8; j++) { for (int k = 7; k >= 0; k--) { data[8+j*8+(7-k)] = ((uint8_t *)buffer)[j*8+k+i*64]; } } if (i == 0) { // display when everything is finished. data[1] = (uint8_t)(duration_time & 0xff); data[2] = (uint8_t)((duration_time >> 8) & 0xff); data[3] = forever_flag; } i2cSendBytes(led_matrix_currentDeviceAddress, data, 24); usleep(1000); i2cSendContinueBytes(led_matrix_currentDeviceAddress, data+24, 24); usleep(1000); i2cSendContinueBytes(led_matrix_currentDeviceAddress, data+48, 24); } } // /************************************************************* // * Description // * Display color block on LED matrix with a given uint32_t rgb color. // * Parameter // * rgb: uint32_t rgb color, such as 0xff0000(red), 0x0000ff(blue) // * duration_time: Set the display time(ms) duration. Set it to 0 to not display. // * forever_flag: Set it to true to display forever, or set it to false to display one time. // * Return // * Null. // *************************************************************/ static void led_matrix_displayColorBlock(uint32_t rgb, uint16_t duration_time, bool forever_flag) { uint8_t data[7] = {0, }; data[0] = I2C_CMD_DISP_COLOR_BLOCK; // red green blue data[1] = (uint8_t)((rgb >> 16) & 0xff); data[2] = (uint8_t)((rgb >> 8) & 0xff); data[3] = (uint8_t)(rgb & 0xff); data[4] = (uint8_t)(duration_time & 0xff); data[5] = (uint8_t)((duration_time >> 8) & 0xff); data[6] = forever_flag; i2cSendBytes(led_matrix_currentDeviceAddress, data, 7); } // /************************************************************* // * Description // * Display nothing on LED Matrix. // * Parameter // * Null. // * Return // * Null. // *************************************************************/ static void led_matrix_stopDisplay(void) { i2cSendByte(led_matrix_currentDeviceAddress, I2C_CMD_DISP_OFF); } // /************************************************************* // * Description // * Store the frames(you send to the device) to flash. It takes about 200ms. // * Parameter // * Null. // * Return // * Null. // *************************************************************/ static void led_matrix_storeFrames(void) { i2cSendByte(led_matrix_currentDeviceAddress, I2C_CMD_STORE_FLASH); usleep(200000); // 200ms } // /************************************************************* // * Description // * Delete all the frames in the flash of device. It takes about 200ms. // * Parameter // * Null. // * Return // * Null. // *************************************************************/ static void led_matrix_deleteFrames(void) { i2cSendByte(led_matrix_currentDeviceAddress, I2C_CMD_DELETE_FLASH); usleep(200000); // 200ms } // /************************************************************* // * Description // * Display frames which is stored in the flash of device. // * Parameter // * duration_time: Set the display time(ms) duration. Set it to 0 to not display. If there // * are more than 1 frame to display, frames will switch automatically. The // * shorter you set the duration_time, the faster it switches. // * forever_flag: Set it to true to display forever, or set it to false to display one time. // * from: the index of frames in your flash. Range from 1 to 5. // * to: the index of frames in your flash. Range from 1 to 5. // * Return // * Null. // *************************************************************/ static void led_matrix_displayFramesFromFlash(uint16_t duration_time, bool forever_flag, uint8_t from, uint8_t to) { uint8_t data[6] = {0, }; uint8_t temp = 0; // 1 <= from <= to <= 5 if (from < 1) from = 1; else if (from > 5) from =5; if (to < 1) to = 1; else if (to > 5) to = 5; if (from > to) { temp = from; from = to; to = temp; } data[0] = I2C_CMD_DISP_FLASH; data[1] = (uint8_t)(duration_time & 0xff); data[2] = (uint8_t)((duration_time >> 8) & 0xff); data[3] = forever_flag; data[4] = from-1; data[5] = to-1; i2cSendBytes(led_matrix_currentDeviceAddress, data, 6); usleep(200000); // 200ms } // /************************************************************* // * Description // * Enable TX and RX pin test mode. // * Parameter // * Null. // * Return // * Null. // *************************************************************/ static void led_matrix_enableTestMode(void) { i2cSendByte(led_matrix_currentDeviceAddress, I2C_CMD_TEST_TX_RX_ON); } // /************************************************************* // * Description // * Enable TX and RX pin test mode. // * Parameter // * Null. // * Return // * Null. // *************************************************************/ static void led_matrix_disableTestMode(void) { i2cSendByte(led_matrix_currentDeviceAddress, I2C_CMD_TEST_TX_RX_OFF); } // /************************************************************* // * Description // * Get software vresion. // * Parameter // * Null. // * Return // * Return software version. // *************************************************************/ static uint32_t led_matrix_getTestVersion(void) { uint8_t data[3] = {0, }; i2cSendByte(led_matrix_currentDeviceAddress, I2C_CMD_TEST_GET_VER); i2cReceiveBytes(led_matrix_currentDeviceAddress, data, 3); return (uint32_t)(data[2] + (uint32_t)data[1] * 256 + (uint32_t)data[0] * 256 * 256); } // /************************************************************* // * Description // * Reset device. // * Parameter // * Null. // * Return // * Null. // *************************************************************/ static void led_matrix_resetDevice(void) { } // /************************************************************* // * Description // * Get device id. // * Parameter // * Null. // * Return // * Null. // *************************************************************/ static void led_matrix_getdeviceId(void) { i2cSendByte(led_matrix_currentDeviceAddress, I2C_CMD_GET_DEVICE_UID); i2cReceiveBytes(led_matrix_currentDeviceAddress, (uint8_t *)led_matrix_deviceId, 12); } #define I2C_HUB_PORT_RASPI 0x08 #define I2C_HUB_PORT_IOT 0x01 #define I2C_HUB_PORT_GPIO 0x04 #define I2C_HUB_PORT_USB_HUB 0x02 #define I2C_HUB_PORT_ALL 0x0F /** * Function: Configure I2C hub to enable I2C bus that connected to led matrix * Params: - hub_address: I2C address of hub * - port: Bus ports **/ int i2c_hub_select_port(uint8_t hub_address, uint8_t port) { int result = 0; int i2c_fd = open(led_matrix_i2c_bus, O_RDWR); if (i2c_fd < 0) { LE_ERROR("i2cSendByte: failed to open %s", led_matrix_i2c_bus); } if (ioctl(i2c_fd, I2C_SLAVE_FORCE, hub_address) < 0) { LE_ERROR("Could not set address to 0x%02x: %s\n", hub_address, strerror(errno)); return -1; } const int writeResult = i2c_smbus_write_byte(i2c_fd, port); if (writeResult < 0) { LE_ERROR("smbus write failed with error %d\n", writeResult); result = -1; } else { result = 0; } close(i2c_fd); return result; } struct led_matrix *led_matrix_create(const char *i2c_bus, uint8_t base, uint8_t screenNumber) { struct led_matrix *res = malloc(sizeof(struct led_matrix)); if (res == NULL) { LE_ERROR("led_matrix_create: failed to create led matrix"); return NULL; } res->getDeviceVID = &led_matrix_getDeviceVID; res->getDevicePID = &led_matrix_getDevicePID; res->changeDeviceBaseAddress = &led_matrix_changeDevicebaseAddress; res->defaultDeviceAddress = &led_matrix_defaultDeviceAddress; res->turnOnLedFlash = &led_matrix_turnOnLedFlash; res->turnOffLedFlash = &led_matrix_turnOffLedFlash; res->enableAutoSleep = &led_matrix_enableAutoSleep; res->wakeDevice = &led_matrix_wakeDevice; res->disableAutoSleep = &led_matrix_disableAutoSleep; res->setDisplayOrientation = &led_matrix_setDisplayOrientation; res->setDisplayOffset = &led_matrix_setDisplayOffset; res->displayBar = &led_matrix_displayBar; res->displayColorBar = &led_matrix_displayColorBar; res->displayColorWave = &led_matrix_displayColorWave; res->displayClockwise = &led_matrix_displayClockwise; res->displayColorAnimation = &led_matrix_displayColorAnimation; res->displayEmoji = &led_matrix_displayEmoji; res->displayNumber = &led_matrix_displayNumber; res->displayString = &led_matrix_displayString; res->displayFrames = &led_matrix_displayFrames; res->displayFrames64 = &led_matrix_displayFrames64; res->displayColorBlock = &led_matrix_displayColorBlock; res->stopDisplay = &led_matrix_stopDisplay; res->storeFrames = &led_matrix_storeFrames; res->deleteFrames = &led_matrix_deleteFrames; res->displayFramesFromFlash = &led_matrix_displayFramesFromFlash; res->enableTestMode = &led_matrix_enableTestMode; res->disableTestMode = &led_matrix_disableTestMode; res->getTestVersion = &led_matrix_getTestVersion; res->resetDevice = &led_matrix_resetDevice; res->getDeviceId = &led_matrix_getdeviceId; if (!(screenNumber >= 1 && screenNumber <= 16)) screenNumber = 1; if (!(base >= 0x10 && base <= 0x70)) base = GROVE_TWO_RGB_LED_MATRIX_DEF_I2C_ADDR; led_matrix_offsetAddress = screenNumber - 1; led_matrix_baseAddress = base; led_matrix_currentDeviceAddress = led_matrix_offsetAddress + led_matrix_baseAddress; memcpy(led_matrix_i2c_bus, i2c_bus, strlen(i2c_bus)); led_matrix_i2c_bus[strlen(i2c_bus)] = 0; i2c_hub_select_port(0x71, I2C_HUB_PORT_ALL); return res; } int led_matrix_release(struct led_matrix *led_matrix) { free(led_matrix); return 0; }
C
/* Exercise 5-4. Write a function strend(s,t) which returns 1 if the string t occurs at the end of the string s, and zero otherwise. */ #include <string.h> #include <stdio.h> /* strend(): returns 1 if t is at the end of s, otherwise 0. */ int strend(const char *s, const char *t) { const char *a; /* anticipated start of t in s */ a = s + strlen(s) - strlen(t); while (*a!='\0' && *t!='\0' && (*a++ == *t++)) ; return !(a - (s+strlen(s))); } int main(int argc, char **argv) { const char s[] = "Hi my name is Rhys."; const char t[] = "Rhys"; const char q[] = "Rhys."; printf("strend(s=%s, t=%s)\t= %d\n", s, t, strend(s,t)); printf("strend(s=%s, q=%s)\t= %d\n", s, q, strend(s,q)); return 0; }
C
/* GLIB - Library of useful routines for C programming Copyright (C) 2009-2015 Free Software Foundation, Inc. Written by: Slava Zanko <slavazanko@gmail.com>, 2009, 2013. This file is part of the Midnight Commander. The Midnight Commander is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The Midnight Commander is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** \file glibcompat.c * \brief Source: compatibility with older versions of glib * * Following code was copied from glib to GNU Midnight Commander to * provide compatibility with older versions of glib. */ #include <config.h> #include <string.h> #include "global.h" #include "glibcompat.h" /*** global variables ****************************************************************************/ /*** file scope macro definitions ****************************************************************/ /*** file scope type declarations ****************************************************************/ /*** file scope variables ************************************************************************/ /*** file scope functions ************************************************************************/ /*** public functions ****************************************************************************/ /* --------------------------------------------------------------------------------------------- */ #if ! GLIB_CHECK_VERSION (2, 16, 0) /** * g_strcmp0: * @str1: (allow-none): a C string or %NULL * @str2: (allow-none): another C string or %NULL * * Compares @str1 and @str2 like strcmp(). Handles %NULL * gracefully by sorting it before non-%NULL strings. * Comparing two %NULL pointers returns 0. * * Returns: an integer less than, equal to, or greater than zero, if @str1 is <, == or > than @str2. * * Since: 2.16 */ int g_strcmp0 (const char *str1, const char *str2) { if (!str1) return -(str1 != str2); if (!str2) return str1 != str2; return strcmp (str1, str2); } #endif /* ! GLIB_CHECK_VERSION (2, 16, 0) */ /* --------------------------------------------------------------------------------------------- */ #if ! GLIB_CHECK_VERSION (2, 28, 0) /** * g_slist_free_full: * @list: a pointer to a #GSList * @free_func: the function to be called to free each element's data * * Convenience method, which frees all the memory used by a #GSList, and * calls the specified destroy function on every element's data. * * Since: 2.28 **/ void g_slist_free_full (GSList * list, GDestroyNotify free_func) { g_slist_foreach (list, (GFunc) free_func, NULL); g_slist_free (list); } /* --------------------------------------------------------------------------------------------- */ /** * g_list_free_full: * @list: a pointer to a #GList * @free_func: the function to be called to free each element's data * * Convenience method, which frees all the memory used by a #GList, and * calls the specified destroy function on every element's data. * * Since: 2.28 */ void g_list_free_full (GList * list, GDestroyNotify free_func) { g_list_foreach (list, (GFunc) free_func, NULL); g_list_free (list); } #endif /* ! GLIB_CHECK_VERSION (2, 28, 0) */ /* --------------------------------------------------------------------------------------------- */ #if ! GLIB_CHECK_VERSION (2, 22, 0) /** * Creates a new GError with the given domain and code, and a message formatted with format. * @param domain error domain * @param code error code * @param format printf()-style format for error message * @param args va_list of parameters for the message format * @returns a new GError */ GError * g_error_new_valist (GQuark domain, gint code, const gchar * format, va_list args) { char *message; GError *ret_value; message = g_strdup_vprintf (format, args); ret_value = g_error_new_literal (domain, code, message); g_free (message); return ret_value; } #endif /* ! GLIB_CHECK_VERSION (2, 22, 0) */ /* --------------------------------------------------------------------------------------------- */
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "shellp.h" const char * token_sep = " \r\n\\\t"; char ** parseline(char * line, int * num_args){ char ** args = malloc(1024 * sizeof(char *)); char * arg; int argnum = 0; for ( int i = 0; i < 1024; i ++){ args[i] = (char *)malloc(1024); if (args[i] == NULL){ printf("Malloc failure\n"); exit(1); } } arg = strtok(line,token_sep); if(debug > 5) printf("pl-%s\n",arg); // Parse this string to pull out special shell characters // while ( arg != NULL){ char this_str[1024]; char new_str[1024]; strcpy(this_str,arg); strcpy(new_str,""); int nindex = 0; int tindex = 0; if(debug > 5) printf("pl2-%s\n",arg); while(1){ char c = this_str[tindex]; if (debug > 10) { if ( debug > 6) printf("1char=%c, arg=%s, t=%s, n=%s, ti=%d, ni=%d\n", c,arg,this_str, new_str, tindex, nindex); } if ( c == '|' || c == '<' || c == '>' || c == '(' || c == ')' ){ if (nindex != 0){ new_str[nindex] = '\0'; if (debug > 5) printf("plx-%s\n",new_str); strcpy(args[argnum],new_str); argnum++; strcpy(new_str,""); nindex = 0; } args[argnum][0] = c; args[argnum][1] = '\0'; argnum++; tindex += 1; continue; } new_str[nindex] = c; new_str[nindex+1] = '\0'; if (debug > 10) { if (debug > 5) printf("2char=%c, arg=%s, t=%s, n=%s, ti=%d, ni=%d\n", c,arg,this_str, new_str, tindex, nindex); } if (c == '\0') break; tindex++; nindex++; if (tindex > 1024) { printf("shellp error parsing line\n"); exit(1); } } if ( debug > 6) printf("plx-%s argnum gs\n",new_str); if (strlen(new_str)){ strcpy( args[argnum], new_str); argnum++; } if ( debug > 5) printf("plx-%s argnum\n",new_str); arg = strtok(NULL,token_sep); } args[argnum] = NULL; return args; } /* arg = strtok(line,token_sep); printf("pl-%s\n",arg); while ( arg != NULL){ // Assemble < and > with filename if ( arg[0] == '<'){ if (strlen(arg) == 1 ){ char * tmp = strtok(NULL,token_sep); strcat(arg,tmp); } } if ( arg[0] == '>'){ if (strlen(arg) == 1 || (strlen(arg)==2 && arg[1] == '>')){ char * tmp = strtok(NULL,token_sep); strcat(arg,tmp); } } // Put pipes on seperate line char * ret; if ((ret = strchr(arg,'|')) != NULL) { char * saveptr; if (debug > 11) printf("1=%s %d\n", arg, argnum); int add = 1; if (arg[0] == '|'){ args[argnum] = "|"; argnum++; add = 0; } part1 = strtok(arg,"|"); if (debug > 11) printf("2=%s %d\n", arg, argnum); while (part1 != NULL ){ args[argnum] = part1; argnum++; if (add){ args[argnum] = "|"; argnum++; add = 0; } part1 = strtok(NULL,"|"); if (strchr(arg,'|')) add = 1; if (debug > 11) printf("3=%s %d\n", arg, argnum); } } args[argnum] = arg; argnum++; if (argnum > argsize){ fprintf(stderr,"too many arguments\n"); exit (1); } arg = strtok(NULL,token_sep); printf("pl2-%s\n",arg); } args[argnum] = NULL; *num_args = argnum; */
C
// ***************************************************************************** // usart0_isr.c // // USART0 Interrupt Service Routine // // This demonstration is designed to read 10 characters into a buffer. // After the 10th character arrives, transmit the 10 characters back. // // The application is interrupt-driven. // // Author: James P Lynch June 22, 2008 // ***************************************************************************** // ******************************************************* // Header Files // ******************************************************* #include "include/AT91SAM7S128.h" #include "include/board.h" // ******************************************************* // Global Variables // ******************************************************* char Buffer[32]; // holds received characters unsigned long nChars = 0; // counts number of received chars char *pBuffer = &Buffer[0]; // pointer into Buffer void Usart0IrqHandler(void) { volatile AT91PS_USART pUsart0 = AT91C_BASE_US0; // create a pointer to USART0 structure // determine which interrupt has occurred // assume half-duplex operation here, only one interrupt type at a time if ((pUsart0->US_CSR & AT91C_US_RXRDY) == AT91C_US_RXRDY) { // we have a receive interrupt, // remove it from Receiver Holding Register and place into buffer[] *pBuffer++ = pUsart0->US_RHR; nChars++; // check if 10 characters have been received if (nChars >= 10) { // yes, redirect buffer pointer to beginning pBuffer = &Buffer[0]; nChars = 0; // disable the receive interrupt, enable the transmit interrupt pUsart0->US_IER = AT91C_US_TXEMPTY; // enable TXEMPTY usart0 transmit interrupt pUsart0->US_IDR = ~AT91C_US_TXEMPTY; // disable all interrupts except TXEMPTY // send first received character, TXEMPTY interrupt will send the rest pUsart0->US_THR = *pBuffer++; nChars++; } } else if ((pUsart0->US_CSR & AT91C_US_TXEMPTY) == AT91C_US_TXEMPTY) { // we have a transmit interrupt (previous char has clocked out) // check if 10 characters have been transmitted if (nChars >= 10) { // yes, redirect buffer pointer to beginning pBuffer = &Buffer[0]; nChars = 0; // enable receive interrupt, disable the transmit interrupt pUsart0->US_IER = AT91C_US_RXRDY; // enable RXRDY usart0 receive interrupt pUsart0->US_IDR = ~AT91C_US_RXRDY; // disable all interrupts except RXRDY } else { // no, send next character pUsart0->US_THR = *pBuffer++; nChars++; } } }
C
#inculde<stdio.h> void waitingtime(int ar[],int ar2[],int n) { int i,j; ar[0]=0; printf("\n\nCalulating the waiting time for every process"); for(i=1;i<n;i++) { ar[i]=0; for(j=0;j<i;j++) { ar[i]=ar[i]+ar2[j]; } } return(ar); } void turnartime(int ar[],int ar2[],int tat[],int n) { printf("\n\nCalulating the turn around time for every process"); int i; for(i=0;i<n;i++) { tat[i]=ar[i]+ar2[i]; } return(tat); } /* number of process n<=20; */ int main() { int pid[20]; //process id int bt[20]; //burst time int wt[20]; //waiting time int tat[20]; //turn around time int n,i,j; printf("Enter No. of process"); scanf("%d",&n); printf("Enter the Process Id in proper sequence: "); for(i=0;i<n;i++) { scanf("%d",&pid[i]); } printf("Enter the Burst Time in proper sequence: "); for(i=0;i<n;i++) { scanf("%d",&bt[i]); } waitingtime(wt,bt,n); turnartime(wt,bt,tat,n); float avgtat=0; printf("\nProcess\tBT\tWT\tTAT"); for(i=0;i<n;i++) { printf("\nP-%d\t%d\t%d\t%d",pid[i],bt[i],wt[i],tat[i]); avgtat=avgtat+tat[i]; } avgtat=avgtat/n; printf("\n\nAverage Turn Around Time= %f",avgtat); printf("\n\nSolution using SHORTEST JOB FIRST: "); //waitingtime(wt); printf("\n Sorting the processes "); int temp; for(i=0;i<n;i++) { for(j=0;j<n-i-1;j++) { if(bt[j]>bt[j+1]) { temp=bt[j+1]; bt[j+1]=bt[j]; bt[j]=temp; } } } for(i=0;i<n;i++){ wt[i]=0; } waitingtime(wt,bt,n); turnartime(wt,bt,tat,n); avgtat=0; printf("\nProcess\tBT\tWT\tTAT"); for(i=0;i<n;i++) { printf("\nP-%d\t%d\t%d\t%d",pid[i],bt[i],wt[i],tat[i]); avgtat=avgtat+tat[i]; } avgtat=avgtat/n; printf("\n\nAverage Turn Around Time= %f",avgtat); printf("\n\nSolution using SHORTEST JOB FIRST, (CPU is idol for 1 unit at starting) "); for(i=0;i<n;i++){ wt[i]=0; } printf("\n\nCalulating the waiting time for every process"); wt[0]=1; for(i=1;i<n;i++) { wt[i]=0; for(j=0;j<i;j++) { wt[i]=wt[i]+bt[j]; } } turnartime(wt,bt,tat,n); avgtat=0; printf("\nProcess\tBT\tWT\tTAT"); for(i=0;i<n;i++) { printf("\nP-%d\t%d\t%d\t%d",pid[i],bt[i],wt[i],tat[i]); avgtat=avgtat+tat[i]; } avgtat=avgtat/n; printf("\n\nAverage Turn Around Time= %f",avgtat); }
C
#include "../test.h" #include <aerospike/as_random.h> #include <pthread.h> #include <string.h> #include <ctype.h> /****************************************************************************** * TEST CASES *****************************************************************************/ static uint64_t n3, n4, n5, n6; static void* worker1(void* data) { n3 = as_random_get_uint64(); n4 = as_random_get_uint64(); return NULL; } static void* worker2(void* data) { n5 = as_random_get_uint64(); n6 = as_random_get_uint64(); return NULL; } TEST(random_number, "random numbers" ) { pthread_t thread1; pthread_create(&thread1, NULL, worker1, NULL); pthread_t thread2; pthread_create(&thread2, NULL, worker2, NULL); uint64_t n1 = as_random_get_uint64(); uint64_t n2 = as_random_get_uint64(); pthread_join(thread1, NULL); pthread_join(thread2, NULL); assert(n1 != n2 && n1 != n3 && n1 != n4 && n1 != n5 && n1 != n6); assert(n2 != n3 && n2 != n4 && n2 != n5 && n2 != n6); assert(n3 != n4 && n3 != n5 && n3 != n6); assert(n4 != n5 && n4 != n6); assert(n5 != n6); } TEST(random_bytes, "random bytes" ) { uint8_t b1[3]; memset(b1, 0, sizeof(b1)); as_random_get_bytes(b1, 0); assert(b1[0] == 0); as_random_get_bytes(b1, 2); assert(b1[2] == 0); uint8_t b2[64]; memset(b2, 0, sizeof(b2)); as_random_get_bytes(b2, 8); assert(b2[8] == 0); as_random_get_bytes(b2, 63); assert(b2[63] == 0); } TEST(random_str, "random string" ) { char buf[10]; int len = sizeof(buf) - 1; as_random_get_str(buf, len); for (int i = 0; i < len; i++) { int rv = isalnum(buf[i]); assert(rv != 0); } } /****************************************************************************** * TEST SUITE *****************************************************************************/ SUITE(random_numbers, "random number generator") { suite_add(random_number); suite_add(random_bytes); suite_add(random_str); }
C
#include <stdio.h> #include <stdlib.h> main(){ float n1,n2; scanf("%f%f",&n1,&n2); if(n1 > n2){ printf("O %f é maior !\n",n1); } if(n2 >n1){ printf("O %f é maior !\n",n2); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* init.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: pkuussaa <pkuussaa@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/06/15 15:11:48 by pkuussaa #+# #+# */ /* Updated: 2020/06/16 15:47:00 by pkuussaa ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/graphics.h" t_ants **init_ants(t_graphics *info) { t_ants **tmp; int i; i = 0; if (!(tmp = (t_ants **)malloc(sizeof(t_ants *) * info->ants + 1))) exit(EXIT_FAILURE); while (i < info->ants) { if (!(tmp[i] = (t_ants *)malloc(sizeof(t_ants)))) exit(EXIT_FAILURE); tmp[i]->name = i + 1; tmp[i]->room_name = ft_strdup(info->start); i++; } tmp[i] = NULL; return (tmp); } double *init_list_int(double x, double y) { double *list; if (!(list = (double*)malloc(sizeof(double) * 2))) exit(EXIT_FAILURE); list[0] = x; list[1] = y; return (list); } void init_info(t_graphics *info) { info->mlx = mlx_init(); info->ptr = mlx_new_window(info->mlx, 1500, 800, "lem-in"); info->img = mlx_new_image(info->mlx, 1500, 800); info->img2 = mlx_new_image(info->mlx, 750, 400); info->data_addr = mlx_get_data_addr(info->img, &(info->bits_per_pixel), &(info->size_line), &(info->endian)); info->data_addr2 = mlx_get_data_addr(info->img2, &(info->bits_per_pixel2), &(info->size_line2), &(info->endian2)); info->stop = -1; info->index = 0; info->speed = 1; info->check = 0; info->i = 0; } void allocate_result_lists(t_graphics *info, int y, int check) { if (check == -1) { if (!(info->indexes = (int**)malloc(sizeof(int*) * y))) exit(EXIT_FAILURE); if (!(info->paths = (double****)malloc(sizeof(double***) * y))) exit(EXIT_FAILURE); if (!(info->size = (int*)malloc(sizeof(int) * y))) exit(EXIT_FAILURE); } else { if (!(info->paths[y] = (double***)malloc(sizeof(double**) * check))) exit(EXIT_FAILURE); if (!(info->indexes[y] = (int*)malloc(sizeof(int) * check))) exit(EXIT_FAILURE); } } void init_result_array(t_graphics *info) { int i; int y; int x; y = 0; while (info->result[y]) y++; info->loop = y; allocate_result_lists(info, y, -1); y = -1; while (info->result[++y]) { i = 0; x = -1; while (info->result[y][i]) i++; allocate_result_lists(info, y, i); info->size[y] = i; info->y = y; while (++x < i) { info->index = x; info->paths[y][x] = moving_algorithm(info, info->ant_moves[y][x]); } } }
C
/* Create a function that returns True if three points belong to the same line, and False otherwise. Each point is represented by a list consisting of an x- and y-coordinate. Examples same_line([[0, 0], [1, 1], [3, 3]]) ➞ True same_line([[-2, -1], [2, 1], [0, 0]]) ➞ True same_line([[-2, 0], [-10, 0], [-8, 0]]) ➞ True same_line([[0, 0], [1, 1], [1, 2]]) ➞ False same_line([[3, 4], [3, 5], [6, 6]]) ➞ False Notes Note the special case of a vertical line. */ #include <assert.h> #include <stdbool.h> #include <stdio.h> typedef struct { int x, y; } Point; int det3x3(int m[3][3]) { int d; int c00, c01, c02; int m00, m01, m02, m10, m11, m12, m20, m21, m22; m00 = m[0][0]; m01 = m[0][1]; m02 = m[0][2]; m10 = m[1][0]; m11 = m[1][1]; m12 = m[1][2]; m20 = m[2][0]; m21 = m[2][1]; m22 = m[2][2]; c00 = m11 * m22 - m12 * m21; c01 = m12 * m20 - m10 * m22; c02 = m10 * m21 - m11 * m20; d = m00 * c00 + m01 * c01 + m02 * c02; return d; } int collinear(Point p[3]) { int m[3][3] = { {p[0].x, p[0].y, 1}, {p[1].x, p[1].y, 1}, {p[2].x, p[2].y, 1}, }; return det3x3(m) == 0; } int main(void) { Point p1[] = {{0, 0}, {1, 1}, {3, 3}}; Point p2[] = {{-2, -1}, {2, 1}, {0, 0}}; Point p3[] = {{-2, 0}, {-10, 0}, {-8, 0}}; Point p4[] = {{0, 0}, {0, 5}, {0, 7}}; Point p5[] = {{9, 9}, {8, 8}, {6, 6}}; Point p6[] = {{0, 0}, {1, 1}, {1, 2}}; Point p7[] = {{3, 4}, {3, 5}, {6, 6}}; Point p8[] = {{9, 8}, {8, 8}, {6, 6}}; assert(collinear(p1) == true); assert(collinear(p2) == true); assert(collinear(p3) == true); assert(collinear(p4) == true); assert(collinear(p5) == true); assert(collinear(p6) == false); assert(collinear(p7) == false); assert(collinear(p8) == false); return 0; }
C
/* * gt_uthread_attr.c * */ #include <sys/time.h> #include <assert.h> #include "gt_thread.h" #include "gt_uthread.h" #include "gt_kthread.h" #include "gt_common.h" #include "gt_typedefs.h" void uthread_attr_getcputime(uthread_attr_t *attr, struct timeval *tv) { tv->tv_sec = attr->execution_time.tv_sec; tv->tv_usec = attr->execution_time.tv_usec; } void uthread_attr_getschedparam(uthread_attr_t *attr, struct uthread_sched_param *param) { param->priority = attr->priority; param->group_id = attr->group_id; } void uthread_attr_setschedparam(uthread_attr_t *attr, const struct uthread_sched_param *param) { attr->priority = param->priority; attr->group_id = param->group_id; } void uthread_attr_init(uthread_attr_t *attr, int gid) { attr->priority = UTHREAD_ATTR_PRIORITY_DEFAULT; attr->group_id = UTHREAD_ATTR_GROUP_DEFAULT; attr->gid = gid; //printf("gid %d\n", attr->gid); attr->execution_time.tv_sec = 0; attr->execution_time.tv_usec = 0; attr->timeslice_start = attr->execution_time; } int uthread_attr_getgid(uthread_attr_t *attr) { return attr->gid; } uthread_attr_t *uthread_attr_create() { uthread_attr_t *attr = emalloc(sizeof(*attr)); return attr; } void uthread_attr_destroy(uthread_attr_t *attr) { free(attr); } /* performs "final - initial", puts result in `result`. returns 1 if answer is negative, * 0 otherwise. taken from gnu.org */ static int timeval_subtract(struct timeval *result, struct timeval *final, struct timeval *initial) { /* Perform the carry for the later subtraction by updating y. */ if (final->tv_usec < initial->tv_usec) { int nsec = (initial->tv_usec - final->tv_usec) / 1000000 + 1; initial->tv_usec -= 1000000 * nsec; initial->tv_sec += nsec; } if (final->tv_usec - initial->tv_usec > 1000000) { int nsec = (final->tv_usec - initial->tv_usec) / 1000000; initial->tv_usec += 1000000 * nsec; initial->tv_sec -= nsec; } /* Compute the time remaining to wait. tv_usec is certainly positive. */ result->tv_sec = final->tv_sec - initial->tv_sec; result->tv_usec = final->tv_usec - initial->tv_usec; /* Return 1 if result is negative. */ return final->tv_sec < initial->tv_sec; } /* adds `a` and `b`, puts result in `result`. Assumes both `a` and `b` are positive */ static void timeval_add(struct timeval *result, struct timeval *a, struct timeval *b) { result->tv_sec = a->tv_sec + b->tv_sec; result->tv_usec = a->tv_usec + b->tv_usec; while (result->tv_usec > 1000000) { result->tv_usec -= 1000000; result->tv_sec++; } } void uthread_attr_set_elapsed_cpu_time(uthread_attr_t *attr) { checkpoint("k%d: u%d: entering uthread_attr_set_elapsed_cpu_time", kthread_current_kthread()->cpuid, kthread_current_kthread()->current_uthread->tid); struct timeval now, elapsed; while (gettimeofday(&now, NULL)); timeval_subtract(&elapsed, &now, &attr->timeslice_start); timeval_add(&attr->execution_time, &attr->execution_time, &elapsed); checkpoint("Execution time: %ld.%06ld s", attr->execution_time.tv_sec, attr->execution_time.tv_usec); }
C
#include <stdio.h> int main() { #if 0 int a1 = 1, a2 = 0; printf("sizeof int:%d\n", sizeof(a1)); while (a2 < a1) { a2 = a1; a1++; } printf("a1=%d\n", a1); printf("a2=%d\n", a2); long b1 = 1, b2 = 0; printf("sizeof long:%d\n", sizeof(b1)); while (b2 < b1) { b2 = b1; b1++; } printf("b1=%ld\n", b1); printf("b2=%ld\n", b2); #endif long long c1 = 429496721, c2 = 429496720; printf("sizeof long long:%d\n", sizeof(c1)); while (c2 < c1) { c2 = c1; c1 += 1; } printf("c1=%lld\n", c1); printf("c2=%lld\n", c2); return 0; }
C
#include <stdio.h> #include <string.h> /* * Looks for a string inside another one and returns a pointer to its * occurance or else a NULL. */ int findchar(search_str, c) char *search_str, c; { int index = 0; while (search_str[index] != '\0') { if (search_str[index++] == c) { return 1; } } return (0); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_histopt_args.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: maissa-b <maissa-b@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/03/11 18:59:29 by maissa-b #+# #+# */ /* Updated: 2017/03/29 13:03:03 by maissa-b ### ########.fr */ /* */ /* ************************************************************************** */ #include "42sh.h" /* ** ft_histopt_p est la fonction qui va gerer le comportement de l'option 'p' ** du builtin history, qui est de simplement afficher la substitution ** des arguments sans stocker la commande dans l'historique. */ int ft_histopt_p(t_lst *hist, char **args) { int i; char *tmp; t_elem *tmp_tail; i = 0; tmp_tail = hist->tail; if (args && args[1]) { while (args[++i] != NULL) { tmp = NULL; if ((tmp = ft_strtrim(args[i])) == NULL) { return (ERR_EXIT); } ft_putendl_fd(tmp, 1); (tmp) ? ft_strdel(&tmp) : 0; } ft_del_elem(&tmp_tail, hist); } return (i); } /* ** ft_histopt_s est la fonction qui gere le comportement de l'option 's' ** du builtin history, qui est de sauvegarder args dans l'historique sans ** stocker la commande elle meme. */ int ft_histopt_s(t_lst *hist, char **args) { t_elem *elem; elem = hist->tail; ft_del_elem(&elem, hist); if ((elem = ft_init_elem()) == NULL) return (ERR_EXIT); if ((elem->name = ft_tabconcat(args)) == NULL) return (ERR_EXIT); ft_insert_elem(elem, hist); return (0); }
C
bool hatSwitchControl(); void joystickControl(); void drive() { if(!hatSwitchControl()) { //joystickControl(); } } int oldHat = -1; bool hatSwitchControl() { int hatValue = joystick.joy1_TopHat; if (hatValue != oldHat) { writeDebugStreamLine("hatvalue is %d", hatValue); oldHat = hatValue; } switch (hatValue) { case 0: motor[rightMotor] = 100; motor[leftMotor] = 100; break; case 1: //forward right motor[rightMotor] = 10; motor[leftMotor] = 40; break; case 2: //turn right motor[rightMotor] = -50; motor[leftMotor] = 50; break; case 3: //back-right motor[rightMotor] = -10; motor[leftMotor] = -40; break; case 4: //back motor[rightMotor] = -100; motor[leftMotor] = -100; break; case 5: //back-left motor[rightMotor] = -40; motor[leftMotor] = -10; break; case 6: //turn left motor[rightMotor] = 50; motor[leftMotor] = -50; break; case 7: //forward-left motor[rightMotor] = 40; motor[leftMotor] = 10; break; default: motor[rightMotor] = 0; motor[leftMotor] = 0; break; } return (hatValue != -1); } void joystickControl() { //Integer variable that allows you to specify a "deadzone" where values (both positive or negative) //less than the threshold will be ignored. int threshold = 10; //Driving Control if(abs(joystick.joy1_y2) > threshold) // If the right analog stick's Y-axis readings are either above or below the threshold... { motor[rightMotor] = joystick.joy1_y2; // ...move the right side of the robot. } else // Else the readings are within the threshold, so... { motor[rightMotor] = 0; // ...stop the right side of the robot. } if(abs(joystick.joy1_y1) > threshold) // If the left analog stick's Y-axis readings are either above or below the threshold... { motor[leftMotor] = joystick.joy1_y1; // ...move the left side of the robot. } else // Else the readings are within the threshold, so... { motor[leftMotor] = 0; // ...stop the left side of the robot. } }
C
#include <gtk/gtk.h> void on_button(GtkWidget *pButton, gpointer data){ const gchar * sText = "click"; GtkWidget * label = gtk_label_new(sText); GtkWidget *pTempEntry; GtkWidget *pTempLabel; GList *pList; /* Recuperation de la liste des elements que contient la GtkVBox */ pList = gtk_container_get_children(GTK_CONTAINER((GtkWidget*)data)); /* Le premier element est le Table */ pTempEntry = GTK_WIDGET(pList->data); /* Cet element est le GtkLabel */ pTempLabel = GTK_WIDGET(pList->data); /* Recuperation du texte contenu dans le GtkEntry */ sText = gtk_entry_get_text(GTK_ENTRY(pTempEntry)); printf("sText : %s\n",(char *)sText); /* Modification du texte contenu dans le GtkLabel */ gtk_label_set_text(GTK_LABEL(pTempLabel), sText); /* Liberation de la memoire utilisee par la liste */ g_list_free(pList); gtk_label_set_text(GTK_LABEL(label), sText); } void panneau(GtkWidget *frame, int row){ GtkWidget * button = gtk_button_new_with_label("panneau"); g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(on_button), frame); gtk_table_attach_defaults(GTK_TABLE(frame), button, 0, 1, 0, 1 ); } void ecran(GtkWidget * frame){ GtkWidget * label = gtk_label_new("ecran"); gtk_table_attach_defaults(GTK_TABLE(frame), label, 1, 5, 0, 1 ); } void config(GtkWidget *window, GtkWidget * frame){ gtk_table_set_row_spacings(GTK_TABLE(frame), 2); gtk_table_set_col_spacings(GTK_TABLE(frame), 2); gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); gtk_window_set_default_size(GTK_WINDOW(window), 800, 600); gtk_window_set_title(GTK_WINDOW(window), "GtkTable"); gtk_container_set_border_width(GTK_CONTAINER(window), 5); } int main( int argc, char *argv[]) { gtk_init(&argc, &argv); GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);; GtkWidget *frame = gtk_table_new(1, 5, TRUE); config(window, frame); panneau(frame, 0); ecran(frame); gtk_container_add(GTK_CONTAINER(window), frame); g_signal_connect_swapped(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), G_OBJECT(window)); gtk_widget_show_all(window); gtk_main(); return 0; }
C
// // Program.c // Listing 14 // // Created by Mustafa Youldash on 8/3/17. // Copyright © 2017 Umm Al-Qura University. All rights reserved. // #include <stdio.h> int main(void) { int a = 21, b=10, c; c = a++; printf("Line 1 - Value of c is %d\n",c); c = a--; printf("Line 2 - Value of c is %d\n",c); return 0; }
C
/* ========== Question: Imagine the case of a darshan queue at a holy temple, where the queue is divided into three levels: I, II, and III. There are three categories of darshan: i) Normal, ii) Special Darshan, and iii) Special Darshan with Puja. A devotee for normal darshan is entered into the queue of level -III. When it is found that queue level II is not full, then the devotee from front of the queue level III is removed and inserted to the queue level II. Similarly, when queue level I is not full, a devotee from the front of level II is removed and inserted to level I. However, a devotee for Special Darshan and Special darshan with puja is inserted directly in the end of queue level II and I respectively. Write a menu driven program in C / C++ to implement the above data structure and all its operations. ========== */ // Include the required header files #include<stdio.h> // Consider that the maximum number of people in each queue ca be 15 const max_size = 10; // Functions for queue operations void addDevotee(int queue[], int *front, int *rear, int *qno) { if(*rear == max_size-1) { printf("\nAll The Queues Are Full! \nPlease Try Again After Some Time!"); } else if(isEmptyQ(queue, &front, &rear) == 1) { *front=0; *rear =0; queue[*rear]=1; printf("\nCongrats! You found a place in the queue %d",*qno); } else { *rear = *rear+1; queue[*rear]=1; printf("\nCongrats! You found a place in the queue %d",*qno); } } void removeDevotee(int queue, int *front, int *rear, int *qno) { if(isEmptyQ(queue, &front, &rear) == 1) { printf("\nThe queue %d is empty", *qno); return; } else if (*front == *rear) { *front = -1; *rear = -1; } else { *front = *front + 1; } } int isEmptyQ(int queue[], int *front, int *rear) { if(*front == -1 && *rear == -1) { return 1; } else { return 0; } } int isNotFull(int queue[], int *front, int *rear, int *qno) { if(*rear == max_size-1) { return 0; } else { *qno = *qno-1; printf("\nWAIT!!! The Queue level %d is not yet full!",*qno); return 1; } } // Main Function int main() { // Declare the needed variables to solve this problem int choice,q1[max_size],q2[max_size],q3[max_size],f1=-1,f2=-1,f3=-1,r1=-1,r2=-1,r3=-1,cq; while(1) { // Menu printf("\n\n\t\t\t Managing queue at temple\n"); printf("\nChoose the category: "); printf("\n 1. Normal Devotee"); printf("\n 2. Special Devotee"); printf("\n 3. Special Devotee with puja"); printf("\nEnter your choice: "); scanf("%d",&choice); // for normal devotee if(choice == 1) { // Add the devotee to queue level 3 cq=3; addDevotee(q3,&f3,&r3,&cq); // Check for a position in queue 2 if(isNotFull(q2,&f2,&r2,&cq) == 1) { // Remove the man from queue 3 and put him in queue 2 removeDevotee(q3,&f3,&r3,&cq); addDevotee(q2,&f2,&r2,&cq); } else { printf("\nQueue level 1 and 2 are full! the devotee stays in Queue 3 for some time!"); } // Check for a position in queue 1 if(isNotFull(q1,&f1,&r1,&cq) == 1) { // Remove the man from queue 3 and put him in queue 2 removeDevotee(q2,&f2,&r2,&cq); addDevotee(q1,&f1,&r1,&cq); } else { printf("\nQueue level 1 and 2 are full! the devotee stays in Queue 3 for some time!"); } } // for special darshan devotee else if(choice == 2) { // Add the devotee to queue level 2 cq=2; addDevotee(q2,&f2,&r2,&cq); // Check for a position in queue 1 if(isNotFull(q1,&f1,&r1,&cq) == 1) { // Remove the man from queue 3 and put him in queue 2 removeDevotee(q2,&f2,&r2,&cq); addDevotee(q1,&f1,&r1,&cq); } else { printf("\nQueue level 1 is full! the devotee stays in Queue 2 for some time!"); } } // for special darshan with puja devotee else if(choice == 3) { // Add the devotee to queue level 1 cq=1; addDevotee(q1,&f1,&r1,&cq); } else { printf("\nInvalid Input"); } } }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include "../header/tableaux.h" //Déclarartion des prototypes de fonctions //======================================== void TabCarre(int[], int); //Définition des fonctions void TabCarre(int tableau[], int n) { int i; for (i=0 ; i < n ; i++) tableau[i] = tableau[i]*tableau[i]; } //Fin de la fonction //Fonction main() : Entrée de l'exécution du programme int main(int argc, char *argv[]) { int n, tab[n]; system("clear"); printf("Entrer la taille du tableau : "); scanf("%d",&n); remplirTab(tab, n); //Appel de la fonction saisie du tableau TabCarre(tab, n); afficherTab(tab,n); //Appel de la fonction afficher le tableau } //fin du main()
C
// gcc -Ofast -march=native ./pinwheels.c -o pinwheels; ./pinwheels | mpv - -scale oversample #include <stdio.h> #include <stdint.h> #include <stdlib.h> #define W (1080 / 4) #define H (1920 / 4) #define STATES 3 char rule[] = "--+---00000+---++" "------00000++++++" "--+++-00000+++-++"; int8_t table[3][17]; int main(int argc, char **argv){ static int8_t world[W][H][2] = {0}; static uint32_t color[STATES] = {0x20400FF, 0, 0xFF4020}; int16_t i, j, k; int8_t flag = 0; srand(12343); for(i = 0; i < 3; i ++){ for(j = 0; j < 17; j ++){ k = rule[17 * i + j]; switch(k){ case '0': table[i][j] = 0; break; case '+': table[i][j] = 1; break; case '-': table[i][j] = -1; } } } for(i = 0; i < W; i ++){ for(j = 0; j < H; j ++){ world[i][j][0] = world[i][j][1] = (rand() % 3) - 1; } } flag = 0; while (1){ printf("P6\n%d %d\n255\n", H, W); for(i = 0; i < W; i ++){ for(j = 0; j < H; j ++){ int8_t temp[9], sum = 8; int64_t u; // Put all neighbors into an array. temp[0] = world[i][j][flag]; temp[1] = world[(W + i - 1) % W][j][flag]; temp[2] = world[(i + 1) % W][j][flag]; temp[3] = world[i][(H + j - 1) % H][flag]; temp[4] = world[i][(j + 1) % H][flag]; temp[5] = world[(i + 1) % W][(H + j - 1) % H][flag]; temp[6] = world[(W + i - 1) % W][(j + 1) % H][flag]; temp[7] = world[(i + 1) % W][(j + 1) % H][flag]; temp[8] = world[(W + i - 1) % W][(H + j - 1) % H][flag]; for (k = 1; k < 9; k ++){ sum += temp[k]; } u = table[temp[0] + 1][sum]; world[i][j][!flag] = u; u = color[u + 1]; putchar(u & 255); u >>= 8; putchar(u & 255); u >>= 8; putchar(u & 255); } } flag ^= 1; } }
C
/* The C programming language includes a very limited standard library in comparison to other modern programming languages. This is a collection of common Computer Science algorithms which may be used in C projects. Copyright (C) 2016, Guilherme Castro Diniz. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation (FSF); in version 2 of the license. This program is distributed in the hope that it can be useful, but WITHOUT ANY IMPLIED WARRANTY OF ADEQUATION TO ANY MARKET OR APPLICATION IN PARTICULAR. See the GNU General Public License for more details. <http://www.gnu.org/licenses/> */ #include <stdio.h> #include <stdlib.h> #define itemtype int #define public #define private static #define RED 0 #define BLACK 1 typedef struct node { itemtype data; int color; /* if red=0 then the node is black */ struct node * left; struct node * right; struct node * parent; } Node; /** * Insert elements in binary tree. * * @param node ** tree, the root of the tree, is a node type pointer. * @param itemtype val, value to insert. * * @returns by parameter the tree with the new element. */ public void insert(Node ** tree, itemtype value){ if ((*tree) == NULL){ *tree = (createNode(value)); return; } if (value < (*tree)->data){ insert(&(*tree)->left, value); } else if (value > (*tree)->data){ insert(&(*tree)->right, value); } else{ return; } (*tree)->height = 1 + max(height(&(*tree)->left), height(&(*tree)->right)); balance = getBalance(&(*tree)); if (balance > 1 && value < (*tree)->left->data){ rightRotate(&(*tree)); return; } else if (balance < -1 && value > (*tree)->right->data){ leftRotate(&(*tree)); return; } else if (balance > 1 && value > (*tree)->left->data){ leftRotate(&(*tree)->left); rightRotate(&(*tree)); return; } else if (balance < -1 && value < (*tree)->right->data){ rightRotate(&(*tree)->right); leftRotate(&(*tree)); return; } } /** * Print avl tree in inorder form. * * @param node * tree, the root of the tree, is a node type pointer. * */ public void print_in_order(Node * tree) { if(tree != NULL){ print_in_order(tree->left); printf("%d ", tree->data); print_in_order(tree->right); } } int main(){ return 0; }
C
#include "unknow_project.h" t_face_list create_t_face_list(void) { t_face_list list; if (!(list.face = (t_face *)malloc(sizeof(t_face) * PUSH_SIZE))) error_exit(-25, "Can't malloc a t_face array"); // printf("malloc t_face_list.face\n"); list.size = 0; list.max_size = PUSH_SIZE; return (list); } t_face_list *initialize_t_face_list(void) { t_face_list *list; if (!(list = (t_face_list *)malloc(sizeof(t_face_list)))) error_exit(-26, "Can't create a t_face_list array"); // printf("malloc t_face_list\n"); *list = create_t_face_list(); return (list); } void t_face_list_push_back(t_face_list *dest, t_face to_add) { t_face *tmp; int i; if ((dest->size + 1) >= dest->max_size) { tmp = dest->face; if (!(dest->face = (t_face *)malloc(sizeof(t_face) \ * (dest->size + 1 + PUSH_SIZE)))) error_exit(-27, "Can't realloc a t_face array"); // printf("malloc t_face_list_push_back\n"); i = -1; while (++i < dest->size) dest->face[i] = tmp[i]; free(tmp); dest->max_size += PUSH_SIZE; } dest->face[dest->size] = to_add; dest->size++; } void t_face_list_add_back(t_face_list *dest, t_face *to_add) { t_face *tmp; int i; if ((dest->size + 1) >= dest->max_size) { tmp = dest->face; if (!(dest->face = (t_face *)malloc(sizeof(t_face) \ * (dest->size + 1 + PUSH_SIZE)))) error_exit(-20, "Can't realloc a t_face array"); // printf("malloc t_face_list_add_back\n"); i = -1; while (++i < dest->size) dest->face[i] = tmp[i]; free(tmp); dest->max_size += PUSH_SIZE; } dest->face[dest->size].index_vertices[0] = to_add->index_vertices[0]; dest->face[dest->size].index_vertices[1] = to_add->index_vertices[1]; dest->face[dest->size].index_vertices[2] = to_add->index_vertices[2]; dest->face[dest->size].index_uvs[0] = to_add->index_uvs[0]; dest->face[dest->size].index_uvs[1] = to_add->index_uvs[1]; dest->face[dest->size].index_uvs[2] = to_add->index_uvs[2]; dest->face[dest->size].normale = to_add->normale; (dest->size)++; } void delete_t_face_list(t_face_list dest) { free(dest.face); // printf("delete t_face_list\n"); } void free_t_face_list(t_face_list *dest) { delete_t_face_list(*dest); free(dest); // printf("free t_face_list\n"); } void clean_t_face_list(t_face_list *dest) { dest->size = 0; } t_face t_face_list_at(t_face_list *dest, int index) { if (index < 0 || index >= dest->size) error_exit(-28, "Segfault : t_face_list out of range"); return (dest->face[index]); } t_face *t_face_list_get(t_face_list *dest, int index) { if (index < 0 || index >= dest->size) error_exit(-28, "Segfault : t_face_list out of range"); return (&dest->face[index]); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #define SIZE 80 //һһεַ int main() { int index,j=0,k=0; int arr[255]={0}; char str[]={"hsdjadisjrh"}; // printf("%d",strlen(str)); for(index=0;index <strlen(str);index++) { arr[str[index]]++; } for(index=0;index<strlen(str);index++) { if(arr[str[index]]==1) { printf("first char is :%c",str[index]); break; } } system("pause"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define BUFFER_SIZE 40 #define TRUE 1 #define FALSE 0 // Estrutura de Dados typedef struct no { char pal[20]; int urg; struct no *prox; } Elem; // Valores globais de ampĺo acesso int bufferCount = 0; FILE * outputFile, * inputFile; Elem * Buffer; // Cria uma lista circular com "n" posições. Sendo size = n Elem * createRingBuffer(int size){ // Ponteiros auxiliares Elem * prevNode, * newNode; if(size >= 1){ Elem * bufferList = (Elem *) malloc(sizeof(Elem)); // Atribuindo dados Temporarios strcpy(bufferList->pal, "\0"); bufferList-> urg = -1; bufferList->prox = NULL; prevNode = bufferList; // Agora criamos os outros N-1 elementos for (int i = 2; i <= size; i++){ newNode = (Elem *) malloc(sizeof(Elem)); // Atribuindo dados Temporarios strcpy(bufferList->pal, "\0"); newNode-> urg = -1; newNode->prox = NULL; // Linka o ultimo nó ao novo nó prevNode->prox = newNode; // Atualiza o ultimo Nó prevNode = newNode; } // Linka o ultimo nó ao primeiro prevNode->prox = bufferList; return bufferList; } return NULL; } // Le, printa e conta todos os nós do buffer void printBuffer(Elem * writerPointer, Elem * readPointer){ Elem * currentNode = NULL; int listSize = 0; if(Buffer == NULL) printf("\nLista vazia!"); else { currentNode = Buffer; printf("\n=========== BUFFER ===========\n\n"); // Percorre todos elementos até voltar ao "inicio" novamente do { // Exibie local do ponteiro de Escrita if(currentNode == writerPointer) printf("(W)"); // Exibie local do ponteiro de Leitura if(currentNode == readPointer) printf("(R)"); printf("[%s, %d]-->", currentNode->pal, currentNode->urg); listSize++; currentNode = currentNode->prox; } while(currentNode != Buffer); printf("/LOOP/"); printf("\n\n=========== ====== ===========\n"); } puts(""); //printf("\n> [%d] Elementos percorridos\n", listSize); } // Insere um registro no Buffer Elem * insertData(char word[20], int urg, Elem * writePointer){ // Buffer está Lotado n/n if(bufferCount == BUFFER_SIZE) printf("> Buffer lotado \n"); else { strcpy(writePointer->pal, word); writePointer->urg = urg; writePointer = writePointer->prox; bufferCount++; } return writePointer; } // "Remove" um registro do Buffer Elem * deleteData(Elem * readPointer, Elem * writePointer){ // Escreve no arquivo fprintf(outputFile, "%s\n", readPointer->pal); // Caso a palavra removida seja PRTY if(strcmp(readPointer->pal, "PRTY") == 0) { // Limpa o valor strcpy(readPointer->pal, "\0"); int jumpValue = readPointer->urg; readPointer->urg = -1; // Neste caso pulamo URG posições POSSIVEIS. // Visto que nao pode ultrapassar o ponteiro de escrita for(int i = 0; i < jumpValue; i++){ // Caso tenha chegado ao ultimo valor inserido if(readPointer == writePointer) { i = jumpValue; // Caso contrario, apenas pula uma posição } else { //bufferCount--; readPointer = readPointer->prox; } } } else { // "Limpamos" o dado no Buffer strcpy(readPointer->pal, "\0"); readPointer->urg = -1; // Não permitir ultrapassar o ponteiro de escrita if(readPointer->prox != writePointer) readPointer = readPointer->prox; } bufferCount--; return readPointer; } // Le o arquivo "pacotes.dat" void readFileEntries(){ Elem * writePointer = Buffer; Elem * readPointer = Buffer; int fileEntries = 0; int readedEntries = 0; // Valores de entrada do arquivo int intA, intB; char string[20]; // Leitura até o fim do arquivo while(fscanf(inputFile, "%d %s %d\n", &intA, string, &intB) == 3){ // Caso seja uma "inserção" if(intA == 0) { // Caso a leitura seja 'NULL' finalizamos o programa if(strcmp(string, "NULL") == 0) break; writePointer = insertData(string, intB, writePointer); fileEntries++; } // Caso seja uma "remoção" else if (intA == 1){ readPointer = deleteData(readPointer, writePointer); readedEntries++; } else printf("> Entrada invalida!\n"); } puts(""); printf("> [%d]\tEntradas escritas \n", fileEntries); printf("> [%d]\tEntradas lidas \n", readedEntries); printf("> [%d]\tElementos no Buffer", bufferCount); puts(""); printBuffer(writePointer, readPointer); } // Função Principal int main(int argc, char const *argv[]) { // Cria o buffer circular Buffer = createRingBuffer(BUFFER_SIZE); // Arquivos que serão utilizados outputFile = fopen("lidos.dat", "w+"); inputFile = fopen("pacotes.dat", "r"); // Verifica abertura do arquivo if(outputFile == NULL || inputFile == NULL) { printf("> Erro na abertura dos arquivos!\n"); return 0; } // Faz a leitura de entrada e inicia o algoritimo do buffer readFileEntries(); // Fecha todos arquivos fclose(outputFile); fclose(inputFile); return 0; }
C
#include "stdio.h" #include "stdlib.h" /* https://leetcode.com/problems/move-zeroes/ Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. Note: You must do this in-place without making a copy of the array. Minimize the total number of operations. */ #if 0//bubble concept void swap(int *i,int *j) { int tmp = *i; *i = *j; *j = tmp; } void moveZeroes(int* nums, int numsSize) { int i = 0; int j = 0; int a; for(i=0; i<numsSize; i++) { if(nums[i] == 0)// need to swap to back { int tmp = i; for(j=tmp+1; j<numsSize; j++) { if(nums[tmp]!=nums[j]) { swap(&(nums[tmp]),&(nums[j])); tmp=j; } } } } } #endif void moveZeroes(int* nums, int numsSize) { int i = 0; int pos = 0; int count = 0; for(i=0;i<numsSize;i++) { if(nums[i]!=0) { nums[count++] = nums[i]; } } for(i=count;i<numsSize;i++) { nums[i] = 0; } } void main() { int nums[] = {0,0,1}; int size = sizeof(nums)/sizeof(nums[0]); int i=0; moveZeroes(nums,size); for(i=0; i<size; i++) { printf("%d ",nums[i]); } }
C
#include "shell.h" #include <stdlib.h> /** *forkitfunction - if user's is already a direct path to command, the function *will execute *@all: all variables * *Return: 0 upon success */ int forkitfunction(struct wrap *all) { int status; pid_t process = fork(); if (process == -1) _error(all, NULL); if (process == 0) { if (execve(all->cmdarray[0], all->cmdarray, all->env) == -1) { _error(all, NULL); _exit(1); } else exit(0); } else { wait(&status); if (WIFEXITED(status)) all->retval = WEXITSTATUS(status); return (all->retval); } return (0); } /** * _strdup - returns pointer to copy of a string * @str: string given * Return: pointer to copy of string, NULL if insufficient memory */ char *_strdup(char *str) { char *strptr = NULL; int count; if (str == NULL) return (NULL); for (count = 0; str[count] != '\0'; count++) { } strptr = malloc(sizeof(char) * (count + 1)); if (strptr == NULL) return (NULL); for (count = 0; str[count] != '\0'; count++) strptr[count] = str[count]; strptr[count] = '\0'; return (strptr); } /** *_strcat - used to concatenate user's input with pathname to *execute command, also adds a forward slash *@dest: original string *@src: string to be added to end of dest *Return: concatenated string with foward slash between */ char *_strcat(char *dest, char *src) { int dest_count, src_count, count; char *space = NULL; src_count = 0; dest_count = 0; while (dest[dest_count] != 0) dest_count++; while (src[src_count] != '\0') src_count++; space = malloc(sizeof(char) * (dest_count + src_count) + 2); if (space == NULL) return (NULL); count = 0; while (dest[count] != '\0') { space[count] = dest[count]; count++; } /* 47 is forward slash*/ space[count++] = 47; src_count = 0; while (src[src_count] != 0) space[count++] = src[src_count++]; space[count] = 0; return (space); } /** * _strncmp - compares two strings * @s1: first string, of two, to be compared in length * @s2: second string, of two, to be compared * Return: 0 on success, anything else is a failure */ int _strncmp(char *s1, char *s2) { int i; i = 0; while (s1[i] == s2[i]) { if (s1[i] == '\0') return (0); i++; } return (s1[i] - s2[i]); }
C
#include <string.h> #include <stdio.h> #include <stddef.h> #include <stdlib.h> /* 这道题的关键是找任意两个数的不同的比特位数,所以对于两个数来说,只要比特位有一处不同就加一。 那对于很多个数来说,相当于32个比特位其实都是独立关系的,所以可以拆开来看。 把比特位是0和1的分成两拨,各自组合就可以了,即one*zero */ int totalHammingDistance(int * nums, int n) { int i, j; int mask; int total = 0; int tmp; for (i = 0; i < 32; i++) { mask = 1 << i; tmp = 0; for (j = 0; j < n; j++) { if (mask & nums[j]) tmp++; } total += tmp * (n - tmp); } return total; } int main(int argc, char **argv) { int nums[] = {4, 14, 2}; int ret = totalHammingDistance(nums, 3); printf("The total hanming Distance is %d\n", ret); }
C
void afficherChauffeur(ptville pdebutVille){ ptville px = pdebutVille->villeSuivante; ptlivraison py; while(px->villeSuivante != NULL) { py = px->listeLivraison->livraisonSuivante; printf("Dans la ville %d, chauffeur :\t\n",px->numVille); while(py->livraisonSuivante != NULL) { printf("\t\t\t\t%d\n", py->chauffeur); py = py->livraisonSuivante; } px = px->villeSuivante; } }
C
#include <stdio.h> /* for printf() and fprintf() */ #include <sys/socket.h> /* for recv() and send() */ #include <unistd.h> /* for close() */ #include "Practical.h" #define RCVBUFSIZE 32 /* Size of receive buffer */ void HandleTCPClient(int clntSocket) { char echoBuffer[RCVBUFSIZE]; /* Buffer for echo string */ int recvMsgSize; /* Size of received message */ /* Receive message from client */ if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0) DieWithSystemMessage("recv() failed"); /* Send received string and receive again until end of transmission */ while (recvMsgSize > 0) /* zero indicates end of transmission */ { /* Echo message back to client */ if (send(clntSocket, echoBuffer, recvMsgSize, 0) != recvMsgSize) DieWithSystemMessage("send() failed"); /* See if there is more data to receive */ if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0) DieWithSystemMessage("recv() failed"); } close(clntSocket); /* Close client socket */ }
C
// Name: Sameer Raj // Roll number: 1801CS42 // Task 2 // Assignment 10 #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <unistd.h> #include <sys/types.h> #define MX 100 #define NN 1000001 #define INT_MAX 1000000000 int arr[NN], ctr = 1; bool over = false; FILE *fptr; struct node { // Node of the linkedlis contains value and next pointer int val; struct node *next; }; struct node* allocNode() { // for allocating linkedlist node in C struct node* Node = (struct node*)malloc(sizeof(struct node)); Node -> next = NULL; return Node; } void deallocate(struct node* ptr) { // deallocate the dynamic memory while(ptr != NULL) { struct node* temp = ptr; ptr = ptr -> next; free(temp); } } void print(struct node *ptr, int tot, int tim) { // print the pages after every second int cnt = 0; while(ptr != NULL) { printf("%d\t", ptr -> val); ptr = ptr -> next; cnt++; } while(cnt++ < tot) printf("X\t"); printf("at t = %d\n", tim); } int findLeastRecentlyUsed(struct node* head, int *pageUsed) { // function to find least recently used page int i, num, tim = INT_MAX; while(head != NULL) { if(pageUsed[head -> val] < tim) { tim = pageUsed[head -> val]; num = head -> val; } head = head -> next; } return num; } void changeNode(int value, struct node* head, int put) { // remove the least used node from linkedlist while(head != NULL) { if(head -> val == value) { head -> val = put; break; } head = head -> next; } return; } void solve() { // Main solve function int pages, cur, size = 0, faults = 0, tot = 0, i; // Define varibales int pageUsed[MX]; for(cur = 0; cur < MX; cur++) // defin and alloacte bool array to check if page is present or not pageUsed[cur] = INT_MAX; struct node *head = NULL, *itr = NULL; if(fscanf(fptr,"%d", &pages) == EOF) { // Scan the f value if not EOF over = true; return; } printf("Try: %d\n\n", ctr++); printf("LRU:\n"); while(true) { fscanf(fptr, "%d", &cur); if(cur == -1) break; arr[tot] = cur; tot++; printf("%d ", cur); } printf("\n"); printf("Frame content at each time step t\n"); for(i = 0; i < pages; i++) { printf("F%d\t", i + 1); } printf("\n"); print(head, pages, 0); // Print at start for (i = 0; i < tot; i++) { cur = arr[i]; if(pageUsed[cur] == INT_MAX) { // page is not present faults++; if(size < pages) { // all the pages are not allocated in page table if(head == NULL) { head = allocNode(); // Then only add that page in the end of linkedlist, check if head is NULL head -> val = cur; head -> next = NULL; itr = head; } else { itr -> next = allocNode(); itr = itr -> next; itr -> val = cur; itr -> next = NULL; } size++; } else { // Remove the front from linedlist and add to the end int leastUsedPage = findLeastRecentlyUsed(head, pageUsed); pageUsed[leastUsedPage] = INT_MAX; changeNode(leastUsedPage, head, cur); } } pageUsed[cur] = i; // current page used at time tim print(head, pages, i + 1); // print each time } deallocate(head); // deallocate the memory printf("#Page Faults: %d\n", faults); // Print the page faults printf("-------------------------------------------------------------------\n\n"); } int main() { fptr = fopen("pages.txt", "r"); // open file if(fptr == NULL) { // If file not found printf("Error: File not found!\n"); } while(!over) { // Till file content not over solve(); } fclose(fptr); }
C
/* Условие задачи void strCopy(char target[], char source[]) Гарантируется, что строка target не короче строки source. */ #include <stdio.h> void strCopy(char target[], char source[]) { int limit; for ( limit = 0; source[limit] != 0; limit++ ) { target[limit] = source[limit]; } target[limit] = 0; } int main() { char strIn[100] = { 'A', 'l', 'e', 'x', ' ', 'H', 'e', 'l', 'l', 'o' }; char strOut[100]; //scanf("%s", strIn); strCopy(strOut, strIn); printf("%s\n", strOut); }
C
#include <stdio.h> #include <stdlib.h> typedef struct kitap { char kad[30]; double fiyat; } K; typedef struct raf { int rkod; char rtur[30]; int ksayi; K *kitaplar; } R; R *bilgi_al(R *k, int raf) { int i; if(raf == 1) k = (R*)malloc(sizeof(R)*1); else k = (R*)realloc(k,raf*sizeof(R)); printf("%-2d.Raf kodu :",raf); scanf("%d",&(k+raf-1)->rkod); printf("%-2d.Raf tur :",raf); fflush(stdin); gets((k+raf-1)->rtur); printf("%-2d.Raf kitap sayisi :",raf); scanf("%d",&(k+raf-1)->ksayi); (k+raf-1)->kitaplar = (K*)malloc(sizeof(K)*(k+raf-1)->ksayi); for(i=0; i<(k+raf-1)->ksayi; i++) { printf("%-2d.Raf %-2d.Kitap ad :",raf,i+1); fflush(stdin); gets(((k+raf-1)->kitaplar+i)->kad); printf("%-2d.Raf %-2d.Kitap fiyat :",raf,i+1); scanf("%lf",&((k+raf-1)->kitaplar+i)->fiyat); } printf("\n\n*****************************************\n\n"); return k; } void listele(R *k, int raf) { int i,j; for(i=0; i<raf; i++) { printf("%-2d.Raf Kodu : %d - Turu : %s - Kitap Sayisi : %d\n\n",i+1,(k+i)->rkod,(k+i)->rtur,(k+i)->ksayi); for(j=0; j<(k+i)->ksayi; j++) { printf("%-2d.Kitap ad : %s - Fiyat : %.2lf TL\n\n",j+1,((k+i)->kitaplar+j)->kad,((k+i)->kitaplar+j)->fiyat); } printf("\n\n*****************************************\n\n"); } } int main() { int adet = 0,secim =1; R *kitap_bilgi; while(secim != 2) { printf("1)**Raf Ekle**\n\n2)**Listele ve Cikis**\n\nSecim :"); scanf("%d",&secim); printf("\n"); switch(secim) { case 1: adet++; kitap_bilgi = bilgi_al(kitap_bilgi,adet); break; case 2: listele(kitap_bilgi,adet); break; default: printf("\nGecersiz islem !..\n"); //break; } } }
C
#include <stdio.h> #include <conio.h> #include <windows.h> #define MAX 100 #define BEZEICHNUNG_MAX_L 30 struct modell { char bezeichnung[BEZEICHNUNG_MAX_L + 1]; int kleistung; int verbrauch; int hoehe; int breite; int tiefe; double preis; }; void gotoxy(int x, int y) { COORD coord; coord.X = x; coord.Y = y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); }; char antwort(void) { char temp; while(1) { temp=getch(); if(temp=='j' || temp=='J')return('J'); if(temp=='n' || temp=='J')return('N'); } } char menue(void) { char eingabe; system("cls"); gotoxy(19,1); printf("Klimager\204te"); gotoxy(15,3); printf("1.) Eingabe"); gotoxy(15,5); printf("2.) Ausgabe"); gotoxy(15,7); printf("3.) L\224schen"); gotoxy(15,9); printf("4.) Ersetzen"); gotoxy(15,11); printf("5.) Suchen"); gotoxy(15,13); printf("x.) Ende"); gotoxy(15,20); printf("Ihre Auswahl: "); do { eingabe=getch(); }while(!(eingabe>='1' && eingabe<='5') && eingabe!='x'); return(eingabe); };
C
////////////////////////////////////////////////////// // // Projet TFTPD32. Mai 98 Ph.jounin - Jan 2003 // File async_log.c: Asynchronous multithread Log management // // source released under European Union Public License // ////////////////////////////////////////////////////// #include "headers.h" #include <stdio.h> #include <stdlib.h> #include "threading.h" #include "..\_libs\event_log\eventlog.h" /////////////////////////////// // // LOG function // add an entry into the log window // // The LOG function may be called by any thread // it adds an entry into the linked list (using semaphore protected Push function) // then set an event to wake up the console thread // /////////////////////////////// static int AppendToFile (const char *filename, const char *szLog, int len) { int Ark; HANDLE hLog; int dummy=0; DWORD dwPos; // Loop since the file may be already opened by another thread Ark=0 ; do { Ark++; hLog = CreateFile ( filename, GENERIC_WRITE, FILE_SHARE_READ, // permit read operations NULL, OPEN_ALWAYS, // open or create FILE_ATTRIBUTE_NORMAL, NULL ); if (hLog==INVALID_HANDLE_VALUE) Sleep (50); } while (hLog==INVALID_HANDLE_VALUE && Ark<3); if (hLog!=INVALID_HANDLE_VALUE) { dwPos = SetFilePointer (hLog, 0, NULL, FILE_END); if (dwPos != INVALID_SET_FILE_POINTER) { WriteFile (hLog, szLog, len, & dummy, NULL); WriteFile (hLog, "\r\n", 2, & dummy, NULL); // probably not necessary, just in case... FlushFileBuffers (hLog); } CloseHandle (hLog); } // append log return dummy; } // LogToFile // LOG window can be called concurrently by every worker thread or background window void __cdecl LOG (int DebugLevel, const char *szFmt, ...) { va_list marker; char szBuf [LOGSIZE], *lpTxt=szBuf; SYSTEMTIME sTime; int ThreadPriority; time_t dNow; static struct S_Pacing { time_t time; int count; } sPacing; if (DebugLevel > sSettings.LogLvl || tThreads[TH_CONSOLE].hEv==INVALID_HANDLE_VALUE) return; // PJO 2017: add a poor man pacing to avoid flooding GUI #define PER_THREAD_PER_SEC_MAX_MSG 100 time (&dNow); if (dNow == sPacing.time) { ++sPacing.count; if ( sPacing.count> PER_THREAD_PER_SEC_MAX_MSG/2 ) { // let the GUI run (otherwise it may either freeze the GUI or create a buffer overflow) // bug found by Peter Baris ThreadPriority = GetThreadPriority (GetCurrentThread()); SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_IDLE); Sleep (1); // pass the hand SetThreadPriority (GetCurrentThread(), ThreadPriority); } if ( sPacing.count> PER_THREAD_PER_SEC_MAX_MSG ) return; } else { sPacing.time = dNow; sPacing.count = 0; } // format the string with wsprintf and timestamp szBuf [sizeof szBuf - 1] = 0; GetLocalTime (&sTime); va_start( marker, szFmt ); /* Initialize variable arguments. */ #ifdef MSVC lpTxt += vsprintf_s (lpTxt, szBuf + sizeof szBuf - lpTxt -1 , szFmt, marker); sprintf_s ( lpTxt, szBuf + sizeof szBuf - lpTxt -1 , " [%02d/%02d %02d:%02d:%02d.%03d]", sTime.wDay, sTime.wMonth, sTime.wHour, sTime.wMinute, sTime.wSecond, sTime.wMilliseconds ); #else lpTxt += vsprintf (lpTxt, szFmt, marker); wsprintf (lpTxt, " [%02d/%02d %02d:%02d:%02d.%03d]", sTime.wDay, sTime.wMonth, sTime.wHour, sTime.wMinute, sTime.wSecond, sTime.wMilliseconds ); #endif lpTxt += sizeof (" [00/00 00:00:00.000]"); // push the message into queue SendMsgRequest ( C_LOG, szBuf, (int) (lpTxt - szBuf), FALSE, FALSE ); // Add the log into the file if (sSettings.szTftpLogFile[0]!=0) { AppendToFile (sSettings.szTftpLogFile, szBuf, (int) (lpTxt - szBuf - 1)); } // Log into file } // LOG /////////////////////////////// // Synchronous send /////////////////////////////// // Report an error to the GUI, also goes into the event log void __cdecl SVC_ERROR (const char *szFmt, ...) { va_list marker; char szBuf [LOGSIZE]; szBuf[LOGSIZE-1]=0; va_start( marker, szFmt ); /* Initialize variable arguments. */ #ifdef MSVC vsprintf_s (szBuf, sizeof szBuf -1 , szFmt, marker); #else vsprintf (szBuf, szFmt, marker); #endif // push the message into queue -> don't block thread but retain msg SendMsgRequest ( C_ERROR, szBuf, lstrlen (szBuf), FALSE, TRUE ); va_end (marker); if (sSettings.bEventLog) WriteIntoEventLog (szBuf, C_ERROR); } // SVC_ERROR // Report an warning to the GUI void __cdecl SVC_WARNING (const char *szFmt, ...) { va_list marker; char szBuf [LOGSIZE]; szBuf[LOGSIZE-1]=0; va_start( marker, szFmt ); /* Initialize variable arguments. */ #ifdef MSVC vsprintf_s (szBuf, sizeof szBuf -1 , szFmt, marker); #else vsprintf (szBuf, szFmt, marker); #endif // push the message into queue -> block until msg sent SendMsgRequest ( C_WARNING, szBuf, lstrlen (szBuf), FALSE, FALSE ); va_end (marker); } // SVC_WARNING
C
#include<stdio.h> #include<stdlib.h> int main() { char a[1000]; int n,i,j; scanf("%s",a); for(i=0;a[i]!='.';i++){} if(a[i-1]-48==9) { printf("GOTO Vasilisa."); exit(getch()); } else { if(a[i+1]-48<5) { for(j=0;j<i;j++) printf("%c",a[j]); } else { for(j=0;j<i-1;j++) printf("%c",a[j]); n=(a[i-1]-48)+1; printf("%d",n); } } getch(); }
C
#include "odbcs.h" #ifdef ODBCS /* Returns IP-address (ipv4) for the given host_name. If not found, then exit code (rc) is non-zero. Usage: odbi_host.x host_name Author: Sami Saarinen, ECMWF, 20-Dec-2007 */ int main(int argc, char *argv[]) { int rc = 2; /* by default all NOT ok */ if (--argc >= 1) { char *hostout = NULL; struct hostent *h = gethostbyname(argv[1]); if (h && h->h_addrtype == AF_INET) { char **pptr; char str[ODBCS_INET_ADDRSTRLEN]; const char *p = NULL; pptr = h->h_addr_list; for ( ; *pptr != NULL ; pptr++) { p = Inet_ntop(h->h_addrtype, *pptr, str, sizeof(str)); } if (p) { printf("%s\n",p); rc = 0; } /* All ok */ } } else rc = 1; /* arg#1 is missing */ return rc; } #else #include <stdio.h> int main() { fprintf(stderr,"***Error: ODB client/server not implemented on this platform\n"); return 3; } #endif
C
#include "stdlib.h" #include "math.h" #include "stdio.h" int rinv(a,n) int n; double a[]; { int *is,*js,i,j,k,l,u,v; double d,p; is=malloc(n*sizeof(int)); js=malloc(n*sizeof(int)); for (k=0; k<=n-1; k++) { d=0.0; for (i=k; i<=n-1; i++) for (j=k; j<=n-1; j++) { l=i*n+j; p=fabs(a[l]); if (p>d) { d=p; is[k]=i; js[k]=j;} } if (d+1.0==1.0) { free(is); free(js); printf("err**not inv\n"); return(0); } if (is[k]!=k) for (j=0; j<=n-1; j++) { u=k*n+j; v=is[k]*n+j; p=a[u]; a[u]=a[v]; a[v]=p; } if (js[k]!=k) for (i=0; i<=n-1; i++) { u=i*n+k; v=i*n+js[k]; p=a[u]; a[u]=a[v]; a[v]=p; } l=k*n+k; a[l]=1.0/a[l]; for (j=0; j<=n-1; j++) if (j!=k) { u=k*n+j; a[u]=a[u]*a[l];} for (i=0; i<=n-1; i++) if (i!=k) for (j=0; j<=n-1; j++) if (j!=k) { u=i*n+j; a[u]=a[u]-a[i*n+k]*a[k*n+j]; } for (i=0; i<=n-1; i++) if (i!=k) { u=i*n+k; a[u]=-a[u]*a[l];} } for (k=n-1; k>=0; k--) { if (js[k]!=k) for (j=0; j<=n-1; j++) { u=k*n+j; v=js[k]*n+j; p=a[u]; a[u]=a[v]; a[v]=p; } if (is[k]!=k) for (i=0; i<=n-1; i++) { u=i*n+k; v=i*n+is[k]; p=a[u]; a[u]=a[v]; a[v]=p; } } free(is); free(js); return(1); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdbool.h> // Compile this program with: // cc -std=c99 -Wall -Werror -pedantic -o lab3 lab3.c // Execution of the whole program begins at the main function int my_strlen(char* str) { int len = 0; while (str[len] != '\0') { len++; } return len; } int number_of_vowels(char* str) { int num_vowels = 0; char vowels[] = {'a', 'e', 'i', 'o', 'u'}; for (int i = 0; i < strlen(str); i++) { for (int j = 0; j < strlen(vowels); j++) { if (str[i] == vowels[j]) num_vowels++; } } return num_vowels; } bool is_safe(char* str) { bool safe = false; int isUpperCount = 0; int isLowerCount = 0; int isDigitCount = 0; for (int i = 0; i < strlen(str); i++) { if (isupper(str[i])) { isUpperCount++; } else if (islower(str[i])) { isLowerCount++; } else if (isdigit(str[i])) { isDigitCount++; } } if (isUpperCount >= 2 && isLowerCount >= 2 && isDigitCount >= 2) { safe = true; } return safe; } /* returns - 1 if the first string is less than second string returns 0 if the the strings are equal returns 1 if the first string is greater than the second string */ int my_strcmp(char* str1, char* str2) { bool higher = true; bool isEqual = true; if (my_strlen(str1) != my_strlen(str2)) { isEqual = false; } for (int i = 0; i < strlen(str1); i++) { if (str1[i] != str2[i]) { if (str1[i] > str2[i]) { higher = false; isEqual = false; } } } if (isEqual) { return 0; } else if (higher) { return 1; } else { return -1; } } bool is_palindrome(char* str) { int end = strlen(str) - 1; int half = strlen(str)/2; for (int i = 0; i < half; i++) { if (str[i] != str[end-i]) { return false; } } return true; } // Using the Luhn algorithm bool valid_card(char* cardnum) { int s1 = 0; int s2 = 0; int cardpos = strlen(cardnum) - 2; int even = true; if (isdigit(cardnum[cardpos+1])) { s1 = atoi(&cardnum[cardpos+1]); } while (cardpos >= 0) { if (isdigit(cardnum[cardpos])) { int num = cardnum[cardpos] - '0'; if (even) { num = num * 2; while(num) { s2 = s2 + num % 10; num /= 10; } } else { s1 = s1 + num; } } even = !even; cardpos--; } if (((s1 + s2) % 10) == 0) { return true; } else { return false; } } int main(int argc, char *argv[]) { if (strcmp(argv[1],"strlen") == 0) { printf("Length is: %i\n",my_strlen(argv[2])); } else if (strcmp(argv[1], "numvowels") == 0) { printf("Number of vowels is: %i\n", number_of_vowels(argv[2])); } else if (strcmp(argv[1], "safe") == 0) { printf("String is safe: %s\n", is_safe(argv[2]) ? "true" : "false"); } else if (strcmp(argv[1], "strcmp") == 0) { printf("The strings are same: %i\n", my_strcmp(argv[2], argv[3])); } else if (strcmp(argv[1], "palindrome") == 0) { printf("String is palindrome: %s\n", is_palindrome(argv[2]) ? "true" : "false"); } else if (strcmp(argv[1], "validcard") == 0) { printf("Card is valid: %s\n", valid_card(argv[2]) ? "true" : "false"); } }
C
#include <stdio.h> int divide (int a, int b); int main() { int a = 144, b = 5; int resultado = divide (a, b); printf("%d\n", resultado); return 0; } int divide (int a, int b) { if (a < b) return 0; else return (divide(a-b,b) + 1); // O +1 representa o sinal se -1 é negativo }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include "crc32.h" #include "scomp.h" #define HDR_SIZE 10 #define TRL_SIZE 8 #define SND_TIMEOUT 100 static int dummycb( void *data, int size, int to ) { return 0; (void)data; (void)size; (void)to; } static struct { int use_crc; ScompCb_t snd; ScompCb_t rcv; } scompOpt = { 1, dummycb, dummycb, }; static unsigned int scompSeq = 0; static inline int xd2dd( int c ) { char h[] = "0123456789ABCDEFabcdef"; char *p = strchr( h, c ); int d; if ( !p || !*p ) return -1; d = p - h; if ( 15 < d ) d -= 6; return d; } static unsigned long xtoul( const char *s, int *rl ) { int d; unsigned long res = 0; while ( *rl && 0 <= ( d = xd2dd( *s ) ) ) { res = res * 16 + d; ++s; --*rl; } return res; } int ScompSetOption( enum ScompOpt_enum opt, ScompOpt_t val ) { int res = SCOMP_ERR_OK; switch ( opt ) { case SCOMP_OPT_USE_CRC: scompOpt.use_crc = val.i; break; case SCOMP_OPT_SNDCB: scompOpt.snd = val.cb; break; case SCOMP_OPT_RCVCB: scompOpt.rcv = val.cb; break; default: res = SCOMP_ERR_BADOPT; break; } return res; } const char *ScompStrErr( int e ) { const char *msg[] = { "no error",// SCOMP_ERR_OK "timeout",//SCOMP_ERR_TIMEOUT "send",//SCOMP_ERR_SND "receive",//SCOMP_ERR_RCV "crc mismatch",//SCOMP_ERR_CRC "sequence number mismatch",//SCOMP_ERR_SEQ "message type mismatch",//SCOMP_ERR_TYPE "parameter out of range",//SCOMP_ERR_RANGE "number encoding",//SCOMP_ERR_BADNUM "bad option specifier",//SCOMP_ERR_BADOPT "buffer overflow",//SCOMP_ERR_OVER }; if ( 0 > e || ( sizeof msg / sizeof *msg ) <= (unsigned)e ) return "unknown"; return msg[e]; } static inline void incSeq( void ) { scompSeq = ( scompSeq + 1 ) % ( SCOMP_MAXSEQ + 1 ); } int ScompSend( char *data, int size, int *seq, int type ) { int res = SCOMP_ERR_OK; char hdr[HDR_SIZE + 1]; char trl[TRL_SIZE + 1] = "00000000"; crc32_t crc; if ( SCOMP_MAXPAYLOAD < size ) return SCOMP_ERR_RANGE; if ( 0 > *seq ) *seq = scompSeq; sprintf( hdr, "%04X%c%04X#", *seq, type, size ); if ( scompOpt.use_crc ) { crc32_init( &crc ); crc32_update( &crc, (uint8_t *)hdr, HDR_SIZE ); crc32_update( &crc, (uint8_t *)data, size ); crc32_final( &crc ); sprintf( trl, "%08X", crc ); } #ifdef __APPLE__ char * buffer; int sizeTotal = HDR_SIZE + size + TRL_SIZE; buffer = (char*) malloc (sizeTotal); if (buffer==NULL) res = SCOMP_ERR_OVER; else { memcpy(buffer, hdr, HDR_SIZE); memcpy(buffer + HDR_SIZE, data, size); memcpy(buffer + HDR_SIZE + size, trl, TRL_SIZE); } if (scompOpt.snd( buffer, sizeTotal, SND_TIMEOUT ) != (sizeTotal)) res = SCOMP_ERR_SND; free (buffer); #else if ( HDR_SIZE != scompOpt.snd( hdr, HDR_SIZE, SND_TIMEOUT ) || size != scompOpt.snd( data, size, SND_TIMEOUT ) || TRL_SIZE != scompOpt.snd( trl, TRL_SIZE, SND_TIMEOUT ) ) { res = SCOMP_ERR_SND; } #endif incSeq(); return res; } int ScompSendResponse( char *data, int size, int seq ) { int sseq = seq; return ScompSend( data, size, &sseq, SCOMP_RESPONSE ); } int ScompRecv( char *data, int *size, int *seq, int *type, int to ) { int rl = 0; int len = 0; char hdr[HDR_SIZE + 1]; char trl[TRL_SIZE + 1]; crc32_t crc = 0x00000000; // get header rl = scompOpt.rcv( hdr, HDR_SIZE, to ); if ( 0 == rl ) return SCOMP_ERR_TIMEOUT; else if ( HDR_SIZE != rl ) return SCOMP_ERR_RCV; hdr[rl] = '\0'; // extract sequence number rl = 4; *seq = xtoul( hdr, &rl ); if ( 0 != rl ) return SCOMP_ERR_BADNUM; // extract type field (request or response) *type = hdr[4]; // extract length field rl = 4; len = xtoul( hdr + 5, &rl ); if ( 0 != rl ) return SCOMP_ERR_BADNUM; if ( len > *size ) return SCOMP_ERR_OVER; *size = len; // get payload data if ( 0 < len ) { rl = scompOpt.rcv( data, len, to ); if ( 0 == rl ) return SCOMP_ERR_TIMEOUT; else if ( rl != len ) return SCOMP_ERR_RCV; } // get trailer rl = scompOpt.rcv( trl, TRL_SIZE, to ); if ( 0 == rl ) return SCOMP_ERR_TIMEOUT; else if ( TRL_SIZE != rl ) return SCOMP_ERR_RCV; trl[rl] = '\0'; // check crc if ( scompOpt.use_crc ) { crc32_init( &crc ); crc32_update( &crc, (uint8_t *)hdr, HDR_SIZE ); crc32_update( &crc, (uint8_t *)data, len ); crc32_final( &crc ); rl = 8; if ( xtoul( trl, &rl ) != crc || 0 != rl ) return SCOMP_ERR_CRC; } return SCOMP_ERR_OK; } int ScompExch( char *query, int qsz, char *resp, int *rsz, int to ) { int sseq = -1; int rseq; int type; int r = ScompSend( query, qsz, &sseq, SCOMP_REQUEST ); *resp = '\0'; if ( SCOMP_ERR_OK == r && SCOMP_ERR_OK == ( r = ScompRecv( resp, rsz, &rseq, &type, to ) ) ) { if ( rseq != sseq ) r = SCOMP_ERR_SEQ; else if ( type != SCOMP_RESPONSE ) r = SCOMP_ERR_TYPE; } return r; } /* EOF */
C
#include <stdio.h> #include <stdlib.h> int BuscaBinaria(int busca, int v[],int n) { int right = n-1,left = 0; int middle; if (busca < left || busca > right) return -1; while (v[right] != busca) { middle = (right+left)/2; if (busca <= v[middle]) right = middle; else if (busca > v[middle]) left = middle; } return right; } int main() { int n, tam=10; int v[tam]; int i; for(i=0; i<tam; i++) { scanf("%d", &v[i]); } scanf("%d", &n); printf("Where are number in array? It's in -> : %d", BuscaBinaria(n, v, tam)); return 0; }
C
#include<stdio.h> void swap(int*x,int*y) { int sd=0; sd=*x; *x=*y; *y=temp; } int main() { int a=10; int b=58; swap(a,b); return 0; }
C
#include <stdio.h> #include <ctype.h> /* ctype.h is for 'isalpha' I used this to detect letters instead of numbers when looking for words. */ #define true 0 #define false 1 main() /* Count words */ { int c, wordCount, isWord; isWord = false; c = wordCount = 0; while ((c = getchar()) != EOF) { if (c == ' ' || c == '\n' || c == '\t') isWord = false; else if (isWord == false && isalpha(c)) isWord = true; ++wordCount; } } printf("Word count: %d", wordCount); }
C
#include <stdio.h> #include <assert.h> #include "util.h" /* Using the or operator is good for turning designated bits on. */ int main() { short a = 0b1010000; // Binary 80 /* TODO: Initialize 'mask' such that when 'a' is OR'ed with it turns the last three bits of 'a' on. */ short mask; assert((a | mask) == 0b1010111); /* TODO: Initialize 'decimal_result' with a decimal number so that the assertion passes. Moreover, what is 0b1010111 in decimal? */ short decimal_result; assert((a | mask) == decimal_result); part_completed(7); return 0; }
C
// Example usage: // > gcc -o pi-serial-c pi-serial.c // > ./pi-serial-c // // Example output: // Result: 3.141237 // Elapsed time: 0.294798 // #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> double drandom() { // Generate a uniform random number [0, 1). return (double) rand() / RAND_MAX; } double estimate_pi(unsigned long n) { unsigned long m = 0; double x, y; for(int i = 0; i < n; ++i) { x = drandom(); y = drandom(); if (sqrt(x*x + y*y) < 1.0) m++; } return (double) m * 4.0 / (double) n; } int main() { unsigned long n = 20 * 1000 * 1000; clock_t start = clock(); double result = estimate_pi(n); clock_t end = clock(); double elapsed_time = (double) (end - start) / CLOCKS_PER_SEC; printf("Result: %f\n", result); printf("Elapsed time: %f\n", elapsed_time); return 0; }
C
int fibonacci (int n, int a, int b) { if (n <= 2) { return b; } return fibonacci(n - 1, b, a + b); } int fib (int n) { return fibonacci(n, 1, 1); }
C
#include "atlas_misc.h" void ATL_UROT(const int N, TYPE *X, const int incX, TYPE *Y, const int incY, const TYPE c, const TYPE s) /* * rot, no unrolling, arbitrary incX, incY, S & C */ { int i; TYPE tmp; for (i=N; i; i--, Y += incY, X += incX) { tmp = c * *X + s * *Y; *Y = c * *Y - s * *X; *X = tmp; } }
C
#include<iostream> #include<vector> #include<queue> #include<map> #include<string> using namespace std; #include <assert.h> class Solution { public: string getPermutation(int n, int k) { vector<int> val(n, 0); int i;for(i=0;i<n;i++) val[i]=i+1; t9[0] = 0;t9[1]=1;for(i=2;i<10;i++) t9[i]=t9[i-1]*i; return get1(0,val,n,k); } private: int t9[10]; string get1(int pos, vector<int> val,int n,int k) { if(pos == n) return ""; string rs; if(pos == n-1) { rs.push_back(val.at(0)+'0'); return rs; } int m = t9[n-pos-1]; int t1 = k/m; if(k%m == 0) t1--; rs.push_back(val.at(t1)+'0'); //cout<<m<<" "<<rs<<endl; int ss=val.size(); for(int i=t1;i<ss-1;i++) val[i]=val[i+1]; val.pop_back(); return rs+get1(pos+1, val, n, k-t1*m); } }; int main() { Solution solution; std::cout<<solution.getPermutation(3,5)<<std::endl; }
C
#ifndef __PROGTEST__ #include <stdio.h> #include <assert.h> #define RECT_NO_OVERLAP 0 #define RECT_OVERLAP 1 #define RECT_A_IN_B 2 #define RECT_B_IN_A 3 #define RECT_ERROR (-1) #endif /* __PROGTEST__ */ int rectanglePosition ( int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2 ) { /* todo */ } #ifndef __PROGTEST__ int main ( int argc, char * argv [] ) { assert ( rectanglePosition ( 0, 0, 50, 20, 10, 5, 75, 40 ) == RECT_OVERLAP ); assert ( rectanglePosition ( 0, 20, 50, 0, 75, 40, 10, 5 ) == RECT_OVERLAP ); assert ( rectanglePosition ( 0, 0, 50, 20, -100, 100, 100, 90 ) == RECT_NO_OVERLAP ); assert ( rectanglePosition ( 0, 0, 50, 20, 50, -100, 100, 100 ) == RECT_NO_OVERLAP ); assert ( rectanglePosition ( 0, 0, 10, 10, 2, 8, 4, 6 ) == RECT_B_IN_A ); assert ( rectanglePosition ( 2, 6, 3, 7, 1, 5, 4, 8 ) == RECT_A_IN_B ); assert ( rectanglePosition ( 1, 6, 3, 7, 1, 5, 4, 8 ) == RECT_OVERLAP ); assert ( rectanglePosition ( 0, 0, 1, 1, 1, 0, 0, 1 ) == RECT_OVERLAP ); assert ( rectanglePosition ( 0, 0, 50, 20, 50, -100, 100, -100 ) == RECT_ERROR ); return 0; } #endif /* __PROGTEST__ */
C
#include <stdio.h> int main(void) { int a; //data variable int *p; //pointer variable int **q; //pointer to pointer int ***r;//pointer to pointer to pointer a = 10; //assigning 10 to a p = &a; //assigning address of a to p q = &p; //assigning address of p to q | single pointer to double pointer r = &q; //assigning address of q to r | double pointer to tripal pointer printf("a = %d; &a = %p;\n*p = %d; p = %p; &p = %p;\n**q = %d; q = %p; &q = %p;\n***r = %d; r = %p; &r = %p;\n", a, &a, *p, p, &p, **q, q, &q, ***r, r, &r); return 0; }
C
/* ** main2.c for emacs in /home/kevin.ferchaud/PSU_2016_navy ** ** Made by ferchaud kevin ** Login <kevin.ferchaud@epitech.net> ** ** Started on Thu Feb 2 20:06:50 2017 ferchaud kevin ** Last update Sun Feb 5 18:17:12 2017 Maxime Le Huu Nho */ #include "my.h" char *strcapamoi(char *str) { int i; if (str == NULL) return (NULL); i = 0; str = my_strdup(str); while (str[i]) { if (str[i] >= 'a' && str[i] <= 'z') str[i] -= 32; i++; } return (str); } int checkfinish(char **map) { int cpt; int cpt2; int x; cpt = -1; cpt2 = 0; x = 0; while (map[cpt2] != '\0') { if (map[cpt2][++cpt] == 'x') x++; if (map[cpt2][cpt] == '\n') { cpt2++; cpt = -1; } } if (x == 14) return (1); return (0); } char *checkvalueattack(char *coord) { char stock; if (coord[0] >= '1' && coord[0] <= '8') if (coord[1] >= 'A' && coord[1] <= 'H') { stock = coord[1]; coord[1] = coord[0]; coord[0] = stock; } return (coord); } int checkvalidattack(char *coord) { if (coord == NULL) return (2); if (my_strlen(coord) != 2) { write(1, "wrong position\n", my_strlen("wrong position\n")); return (0); } if (((coord[0] >= 'A' && coord[0] <= 'H') && (coord[1] >= '1' && coord[1] <= '8')) || ((coord[1] >= 'A' && coord[1] <= 'H') && (coord[0] >= '1' && coord[0] <= '8'))) return (1); else { write(1, "wrong position\n", my_strlen("wrong position\n")); return (0); } } int attacknavy(char **map, char *coord) { int cpt; int cpt2; cpt = -1; cpt2 = -1; while (map[0][++cpt] != coord[0]); while (map[++cpt2][0] != coord[1]); if (map[cpt2][cpt] >= '2' && map[cpt2][cpt] <= '5') return (1); else return (0); }
C
#include <project.h> static void unittest1(t_test *test) { char buf[9]; bzero(buf, 9); ft_strcat(buf, ""); ft_strcat(buf, "Bon"); ft_strcat(buf, "j"); ft_strcat(buf, "our."); ft_strcat(buf, ""); mt_assert(strcmp(buf, "Bonjour.") == 0); mt_assert(buf == ft_strcat(buf, "")); } void suite_02_part2_ft_strcat(t_suite *suite) { SUITE_ADD_TEST(suite, unittest1); }
C
#include <stdio.h> #include <string.h> int add_sum(int answered[26], int group_size, int *sum) { int count = 0; for (int i = 0; i < 26; ++i) { if (answered[i] >= group_size) { count++; } } *sum += count; return count; } int main(int argc, char *argv[]) { FILE *file = fopen("input_06.txt", "r"); if (!file) { printf("Failed to open input file.\n"); return 0; } int sum = 0; int answered[26] = {0}; char buffer[28] = {0}; int group = 0; int group_size = 0; while (fgets(buffer, 28, file)) { if (buffer[0] == '\n') { int count = add_sum(answered, group_size, &sum); printf("Group %d - %d\n", group++, count); group_size = 0; memset(answered, 0, sizeof(int) * 26); } else { group_size++; char *c = buffer; while (*c >= 'a' && *c <= 'z') { answered[*c - 'a'] += 1; c++; } } } int count = add_sum(answered, group_size, &sum); printf("Group %d - %d\n", group++, count); printf("%d\n", sum); fclose(file); return 0; }
C
#ifndef LOGS_H_ #define LOGS_H_ #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <stdbool.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <time.h> #include <sys/times.h> #define GROUP_LEADER (getpid() == getpgid(getpid())) #define GROUP_ID (getpgid(getpid())) /** * @brief struct containg relevant information about program logs * */ struct logs { FILE* fp; /* FILE struct pointing to LOG_FILENAME */ char file_path[1024]; /* String containig LOG_FILENAME path */ bool available; /* true if LOG_FILENAME is set, else false */ }; /** * @brief Checks if the LOG_FILENAME environment variable * is properly set * * @param argc count of arguments passed to the new process * @param argv vector of arguments passed to a process when it is created */ void logs_setup(int argc, char *argv[]); // ----------------------- PROCESSES LOGS ----------------------- /** * @brief Registers to the LOG_FILENAME whenever a process is created * * @param argc count of arguments passed to the new process * @param argv vector of arguments passed to a process when it is created */ void proc_creat(int argc, char* argv[]); /** * @brief Registers to the LOG_FILENAME whenever a process is terminated * * @param pid Terminated Processed ID * @param status Exit status from process */ void proc_exit(int pid, int status); /** * @brief Registers to the LOG_FILENAME whenever a FILE/DIR is processed * * @param file_path String that contains the path to FILE/DIR * @param old_mode previous FILE/DIR permissions mode * @param new_mode new FILE/DIR permissions mode * @param pid Process ID responsible for processing FILE/DIR */ void file_modf(char* file_path, mode_t old_mode, mode_t new_mode, pid_t pid); // ----------------------- SIGNAL LOGS ----------------------- /** * @brief Registers to LOG_FILENAME whenever a process sends a signal * * @param signal string that contains signal's name * @param pid Process ID of the signal's receiver */ void signal_sent(char* signal, pid_t pid); /** * @brief Registers to LOG_FILENAME whenever a process receives a signal * * @param signal string that contains signal's name */ void signal_recv(char* signal); #endif // LOGS_H_
C
#include<stdio.h> int main(){ int input,i; printf("Enter the range upto which prime numbers has to be found"); scanf("%d",&input); int prime[input+1]; //first initialize every element to be prime for(i=0;i<=input;i++){ prime[i]=1; } for(int number=2;number*number<=i;number++){ if(prime[number]==1){ //update the multiples of number as not prime.. for(int i=number*number;i<=input;i=i+number){ prime[i]=0; } } } //if array elements initialized to 0 means not a prime and 1 means prime for(int iterator=2;iterator<=input;iterator++){ if(prime[iterator]==1){ printf("%d ",iterator); } } }
C
// Copyright 2020 Gregory Davill <greg.davill@gmail.com> // Copyright 2020 Michael Welling <mwelling@ieee.org> #include <dac53608.h> #include <i2c.h> #define DAC_I2C_ADDR 0b1001000 static bool dac_write(uint8_t addr, uint16_t d) { char data[2]; data[0] = d >> 8; data[1] = d & 0xFF; return i2c_write(DAC_I2C_ADDR, addr, data, 2); } static bool dac_read(uint8_t addr, uint16_t* d) { char data[2] = {0}; bool ret = i2c_read(DAC_I2C_ADDR, addr, data, 2, false); *d = data[0] << 8 | data[1]; return ret; } bool dac_write_channel(uint8_t index, uint16_t val) { return dac_write(index+8, val); } void dac_reset() { i2c_reset(); msleep(1); //printf("Write i2c: Reset. %u\n", ret); bool ret = dac_write(2, 0x000A); /* Wait for it to reset */ msleep(100); /* enable all DAC channels */ dac_write(1, 0x0000); } bool dac_read_id() { uint16_t value = 0; bool ret = dac_read(2, &value); if(ret == true & value == 0x0300) return true; return false; }
C
/* * analog.c * * Created on: May 2, 2018 * Author: Marco */ //=========================================================================== /*------------------------------- Includes --------------------------------*/ //=========================================================================== #include "analog.h" /* Drivers */ #include "gpio.h" /* Libs */ #include "delays.h" //=========================================================================== //=========================================================================== /*------------------------------ Prototypes -------------------------------*/ //=========================================================================== static uint8_t analogHWInitialize(uint32_t channels); static uint8_t analogSWInitialize(void); static void analogConfigChannels(uint32_t channels); //=========================================================================== //=========================================================================== /*------------------------------ Semaphores -------------------------------*/ //=========================================================================== static SemaphoreHandle_t analogMutex; //=========================================================================== //=========================================================================== /*------------------------------- Functions -------------------------------*/ //=========================================================================== //--------------------------------------------------------------------------- uint8_t analogInitialize(uint32_t channels){ if( analogHWInitialize(channels) ) return 1; if( analogSWInitialize() ) return 2; return 0; } //--------------------------------------------------------------------------- uint8_t analogRead(uint8_t channel, uint16_t *buffer){ /* Selects channel to be first in conversion sequence */ ADC1->SQR3 = channel & 0x1F; /* Clears end-of-conversion flag and starts a new conversion */ ADC1->SR &= (uint16_t)(~ADC_SR_EOC); ADC1->CR2 |= ADC_CR2_ADON; /* Waits for conversion */ #if configANALOG_READ_TIMEOUT == 0 while(!(ADC1->SR & ADC_SR_EOC)); #else uint32_t k; k = configANALOG_READ_TIMEOUT; while( !(ADC1->SR & ADC_SR_EOC) && (--k) ); if(k == 0) return 1; #endif *buffer = (uint16_t)ADC1->DR; return 0; } //--------------------------------------------------------------------------- uint8_t analogMutexTake(uint32_t ticks){ if( xSemaphoreTake(analogMutex, ticks) != pdTRUE ) return 1; return 0; } //--------------------------------------------------------------------------- uint8_t analogMutexGive(void){ if( xSemaphoreGive(analogMutex) != pdTRUE) return 1; return 0; } //--------------------------------------------------------------------------- //=========================================================================== //=========================================================================== /*--------------------------- Static functions ----------------------------*/ //=========================================================================== //--------------------------------------------------------------------------- static uint8_t analogHWInitialize(uint32_t channels){ uint32_t k; /* Initialize analog inputs */ analogConfigChannels(channels); /* Selects clock divider and enables the peripheral */ RCC->CFGR |= RCC_CFGR_ADCPRE_DIV6; RCC->APB2ENR |= RCC_APB2ENR_ADC1EN; /* * Turns ADC on and waits initialization. The reference manual states * that, before calibration, the ADC should be on for at least two ADC * clock cycles. At 12 MHz, that's around ~0.167 ns. So, we wait ~1 us. */ ADC1->CR2 = ADC_CR2_ADON; delaysSub(0x0A); ADC1->CR2 = ADC_CR2_CAL | ADC_CR2_ADON; #if configANALOG_CAL_TIMEOUT == 0 while(ADC1->CR2 & ADC_CR2_CAL); #else k = configANALOG_CAL_TIMEOUT; while( (ADC1->CR2 & ADC_CR2_CAL) && (--k) ); if(k == 0) return 1; #endif /* Sets sampling time for all channels to be 239.5 ADC cycles */ ADC1->SMPR1 = 0x00FFFFFF; ADC1->SMPR2 = 0x3FFFFFFF; return 0; } //--------------------------------------------------------------------------- static uint8_t analogSWInitialize(void){ analogMutex = xSemaphoreCreateMutex(); if(analogMutex == NULL) return 1; return 0; } //--------------------------------------------------------------------------- static void analogConfigChannels(uint32_t channels){ /* First, sets channels 0~7, which are all in PORTA, pins 0~7 */ if( channels & (0xFFU) ){ gpioPortEnable(GPIOA); gpioConfig(GPIOA, (uint16_t)(channels & 0xFFU), GPIO_MODE_INPUT, GPIO_CONFIG_INPUT_ANALOG); } /* Now, sets channels 8~9, which are all in PORTB, pins 0~1 */ if( channels & (0x300U) ){ gpioPortEnable(GPIOB); gpioConfig(GPIOB, (uint16_t)((channels & 0x300U) >> 8U), GPIO_MODE_INPUT, GPIO_CONFIG_INPUT_ANALOG); } /* Lastly, sets channels 10~15, which are all in PORTC, pins 0~5 */ if( channels & (0xFC00U) ){ gpioPortEnable(GPIOC); gpioConfig(GPIOC, (uint16_t)((channels & 0xFC00U) >> 10U), GPIO_MODE_INPUT, GPIO_CONFIG_INPUT_ANALOG); } } //--------------------------------------------------------------------------- //===========================================================================
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <string.h> #include <signal.h> #include <limits.h> #include <unistd.h> #define ERROR(string) {printf(string);exit(1);} void read_confi(char*); void prepare(); void start_threads(); void join_threads(); void *producer(void *fvoid); void *consumer(void *fvoid); int check_length(int len); void sig_handler(int signo); void ending(); int finished, P, K, N,search_type, print_type, nk, L, c_index = 0, p_index = 0; char file_name[FILENAME_MAX] ; FILE *file; char **buffer; pthread_mutex_t *mutex; pthread_t *k_threads, *p_threads; pthread_cond_t r_cond, w_cond; int main(int argc, char* argv[]){ if (argc != 2) ERROR("Wrong amount of args!\n"); read_confi(argv[1]); prepare(); start_threads(); join_threads(); ending(); return 0; } void read_confi(char *file){ FILE *file_con = fopen(file, "r"); if (file_con == NULL) ERROR("Error while reading conf file!\n"); fscanf(file_con, "%d %d %d %s %d %d %d %d", &P, &K, &N, file_name, &L, &search_type, &print_type, &nk); printf("Configurations: %d %d %d %s %d %d %d %d\n", P, K, N, file_name, L, search_type, print_type, nk); fclose(file_con); } void prepare(){ file = fopen(file_name, "r"); if (file == NULL) ERROR("Error while opening file for reading\n"); buffer = calloc(N, sizeof(char*)); mutex = calloc(N+2, sizeof(pthread_mutex_t)); for(int i = 0; i < N+2; i++) { pthread_mutex_init (&mutex[i], NULL); } p_threads = calloc(P, sizeof(pthread_t)); k_threads = calloc(P, sizeof(pthread_t)); pthread_cond_init(&w_cond, NULL); pthread_cond_init(&r_cond, NULL); signal(SIGINT, sig_handler); } void start_threads(){ for (int i = 0; i < P; i++){ pthread_create(&p_threads[i], NULL, producer, NULL); } for (int i = 0; i < K; i++){ pthread_create(&k_threads[i], NULL, consumer, NULL); } } void join_threads(){ for (int i = 0; i < P; i++){ pthread_join(p_threads[i], NULL); } finished = 1; for (int i = 0; i < K; i++){ pthread_join(k_threads[i], NULL); } } void *producer(void *fvoid) { char line[LINE_MAX]; int index; while(fgets(line, LINE_MAX, file)!=NULL){ printf("\nproducer %ld takes reading line\n", pthread_self()); pthread_mutex_lock(&mutex[N]); while (buffer[p_index] != NULL) pthread_cond_wait(&r_cond, &mutex[N]); index = p_index; p_index =(p_index + 1) % N; printf("%d\n", p_index); pthread_mutex_lock(&mutex[index]); printf("producer %ld takes buffer[%d]\n", pthread_self(), index); buffer[index] = calloc((strlen(line)+1), sizeof(char)); strcpy(buffer[index], line); printf("Line is copied by producer %ld to buffer[%d]\n", pthread_self(), index); pthread_mutex_unlock(&mutex[N]); pthread_cond_broadcast(&w_cond); pthread_mutex_unlock(&mutex[index]); } printf("The whole text is completed!\n"); return NULL; } void *consumer(void *fvoid){ char *line; int index; while(1){ printf("Consumer %ld takes reading line\n", pthread_self()); pthread_mutex_lock(&mutex[N+1]); while (buffer[c_index] == NULL){ if (finished){ pthread_mutex_unlock(&mutex[N+1]); return NULL; } pthread_cond_wait(&w_cond, &mutex[N+1]); } index = c_index; c_index =(c_index + 1) % N; pthread_mutex_lock(&mutex[index]); pthread_mutex_unlock(&mutex[N+1]); line = buffer[index]; buffer[index] = NULL; pthread_cond_broadcast(&r_cond); pthread_mutex_unlock(&mutex[index]); if (check_length(strlen(line))) printf("buffer[%d]:%s\n", index, line); free(line); } } int check_length(int len){ return search_type == (len > L ? 1: len < 0 ? -1:0); } void ending(){ fclose(file); for (int i = 0; i < N; i++) free(buffer[i]); free(buffer); for (int i = 0; i < N+2; i++) pthread_mutex_destroy(&mutex[i]); free(mutex); pthread_cond_destroy(&r_cond); pthread_cond_destroy(&w_cond); } void sig_handler(int signo){ for (int i = 0; i < P; i++) pthread_cancel(p_threads[i]); for (int i = 0; i < K; i++) pthread_cancel(k_threads[i]); ending(); exit(0); }
C
#include "interpolation.h" float interpolation(float inputVal, float x1, float x2, float y1, float y2); float limitedInterpolation(float inputVal, float x1, float x2, float y1, float y2); float interpolation(float inputVal, float x1, float x2, float y1, float y2) { static float deltaX = 0.0; static float deltaY = 0.0; static float m = 0.0; static float c = 0.0; static float outputVal = 0.0; //y = m.x + c deltaX = (x2 - x1); deltaY = (y2 - y1); m = (deltaY/deltaX); c = (y1 - (m*x1)); outputVal = ((m*inputVal) + c); return outputVal; } //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- float limitedInterpolation(float inputVal, float x1, float x2, float y1, float y2) { float limitedOutputVal = 0; limitedOutputVal = interpolation( inputVal, x1, x2, y1, y2 ); if(y1 > y2) { if(limitedOutputVal > y1) { return y1; } else if(limitedOutputVal < y2) { return y2; } else { return limitedOutputVal; } } else { if(limitedOutputVal > y2) { return y2; } else if(limitedOutputVal < y1) { return y1; } else { return limitedOutputVal; } } }
C
/* Enonce : L'objectif est de deboguer ce programme comportant un bug "evident". Compilez-le et trouvez le bug a l'aide des methodes adaptees de debogage. Competences : 1,2,88,107,108,109 Difficulte : 1 */ #include <stdio.h> int main() { int *age; printf("Bonjour,\n"); printf("Entrez votre age\n"); scanf("%d", age); printf("Vous avez %d ans\n", *age); return 0; }
C
/** * @file basic.c * @brief Memory management, portable types, math constants, and timing * @author Pascal Getreuer <getreuer@gmail.com> * * This file implements a function Clock, a timer with millisecond * precision. In order to obtain timing at high resolution, platform- * specific functions are needed: * * - On Windows systems, the GetSystemTime function is used. * - On UNIX systems, the gettimeofday function is used. * * This file attempts to detect whether the platform is Windows or UNIX * and defines Clock accordingly. * * * Copyright (c) 2010-2011, Pascal Getreuer * All rights reserved. * * This program is free software: you can use, modify and/or * redistribute it under the terms of the simplified BSD License. You * should have received a copy of this license along this program. If * not, see <http://www.opensource.org/licenses/bsd-license.html>. */ #include <stdlib.h> #include <stdarg.h> #include "basic.h" /** @brief malloc with an error message on failure. */ void *MallocWithErrorMessage(size_t Size) { void *Ptr; if(!(Ptr = malloc(Size))) ErrorMessage("Memory allocation of %u bytes failed.\n", Size); return Ptr; } /** @brief realloc with an error message and free on failure. */ void *ReallocWithErrorMessage(void *Ptr, size_t Size) { void *NewPtr; if(!(NewPtr = realloc(Ptr, Size))) { ErrorMessage("Memory reallocation of %u bytes failed.\n", Size); Free(Ptr); /* Free the previous block on failure */ } return NewPtr; } /** @brief Redefine this function to customize error messages. */ void ErrorMessage(const char *Format, ...) { va_list Args; va_start(Args, Format); /* Write a formatted error message to stderr */ vfprintf(stderr, Format, Args); va_end(Args); } #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) /* Windows: implement with GetSystemTime */ #define WIN32_LEAN_AND_MEAN #include <windows.h> /* Clock: Get the system clock in milliseconds */ unsigned long Clock() { static SYSTEMTIME TimeVal; GetSystemTime(&TimeVal); return (unsigned long)((unsigned long)TimeVal.wMilliseconds + 1000*((unsigned long)TimeVal.wSecond + 60*((unsigned long)TimeVal.wMinute + 60*((unsigned long)TimeVal.wHour + 24*(unsigned long)TimeVal.wDay)))); } #else /* UNIX: implement with gettimeofday */ #include <sys/time.h> #include <unistd.h> /* Clock: Get the system clock in milliseconds */ unsigned long Clock() { struct timeval TimeVal; gettimeofday(&TimeVal, NULL); return (unsigned long)(TimeVal.tv_usec/1000 + TimeVal.tv_sec*1000); } #endif
C
#include "headers.h" int redirection(char **arg, char *home, int size) { int f1 = 0, f2 = 0, f3 = 0; int fd, curr ,start,end = size; char in[10000]; char out[10000]; for (int i = 0; i < size; i++) { if (!(strcmp(arg[i], "<") == 0)==0) { strcpy(in,arg[i+1]); f1 = i; end = i; } if (strcmp(arg[i], ">") == 0) { strcpy(out, arg[i + 1]); fd = open(out, O_WRONLY | O_CREAT | O_TRUNC, 0644); close(fd); f2 = i; if(f2<end){ end = f2; } } if (strcmp(arg[i], ">>") == 0) { strcpy(out, arg[i + 1]); fd = open(out, O_WRONLY | O_CREAT | O_APPEND, 0644); close(fd); f3 = i; if(f3<end){ end = f3; } } } if (f1 == 0 && f2 == 0 && f3 == 0) { return 0; } // printf("red-%d",end); pid_t pid; pid = fork(); if (pid == 0) { int fd2; if (f1) { struct stat inp; if (stat(in, &inp) < 0) { perror(in); } fd2 = open(in, O_RDONLY, 0644); // printf("%d\n",fd2); if (dup2(fd2, 0) < 0) { perror("dup2 failed"); return 0; } close(fd2); } if (f2>f3) { fd = open(out, O_WRONLY | O_CREAT | O_TRUNC, 0644); if (dup2(fd, 1) < 0) { perror("dup2 failed"); return 0; } close(fd); } else if (f3>f2) { fd = open(out, O_WRONLY | O_CREAT | O_APPEND, 0644); if (dup2(fd, 1) < 0) { perror("dup2 failed"); return 0; } close(fd); } execute(arg , home, end ); exit(0); } else { wait(NULL); } return 1; }
C
int add(int a, int b, int c){ return a+b+c; } int main(){ int x =0; int y = 3; int z =5; return add(x,y,z); }
C
#include <stdio.h> #include <stdlib.h> // Para usar o exit() #include <stdbool.h> // Para poder usar o booleano void fatal(char *msg) { fprintf(stderr, "Erro: %s\n", msg); exit(1); } void usage(void) { printf("Uso: \n\treadpe <arquivo.exe>\n"); exit(1); } bool ispe(const unsigned char *b) { // Função que irá dizer se o arquivo é um PE ou não return if (b[0] == 'M' && b[1] == 'Z'); // 'M' == 0x4d e o 'Z' 0x5a. Irá retornar True ou False } int main(int argc, char *argv[]) { FILE *fh; unsigned char buffer[32]; if(argc != 2) { // fatal("Paramentro necessário faltando!"); usage(); } fh = fopen(argv[1], "rb"); // fopen é uma função que abre o arquivo. Parametros "rb" da função fopen para abrir um binaŕio if (fh == NULL) { fatal("Arquivo não encontrado ou sem permissão de leitura!"); } if (fread(buffer, 32, 1, fh)) { // Função para ler um arquivo fatal("Não consegui ler os 32 bytes do arquivo"); } fclose(fh); // Fecha o arquivo que foi aberto // printf("%c\n", buffer[1]); if (!ispe(buffer) ) { fatal("O arquivo não parece ser um executável PE!"); } return 0; }
C
/* ** character.c for Naruto2 in /home/valentin/Projets_persos/Naruto2 ** ** Made by valentin combes ** Login <combes_v@epitech.net> ** ** Started on Thu Apr 19 10:20:31 2012 valentin combes ** Last update Sun Apr 22 21:07:35 2012 valentin combes */ #include "naruto.h" t_perso *add_character(char *name, int allowed) { t_perso *tmp; tmp = xmalloc(sizeof(*tmp)); tmp->name = my_strcreat(name); tmp->allowed = allowed; tmp->prev = NULL; tmp->next = NULL; return (tmp); } void fill_character(t_tournoi *tournoi, int fd_perso) { t_perso *tmp; char *s; int allow; if (!tournoi->pers) { s = get_next_line(fd_perso); allow = my_get_nbr(s + strlen(s) - 1); s[strlen(s) - 2] = '\0'; tournoi->pers = add_character(s, allow); s = xfree(s); } tmp = tournoi->pers; s = get_next_line(fd_perso); while (s) { allow = my_get_nbr(s + strlen(s) - 1); s[strlen(s) - 2] = '\0'; tmp->next = add_character(s, allow); tmp->next->prev = tmp; tmp = tmp->next; s = xfree(s); s = get_next_line(fd_perso); } } void free_character(t_tournoi *tournoi) { t_perso *tmp; t_perso *plop; tmp = tournoi->pers; while (tmp) { plop = tmp->next; tmp = xfree(tmp); tmp = plop; } } void show_character(t_tournoi * tournoi) { t_perso *tmp; tmp = tournoi->pers; while (tmp) { if (tmp->allowed) my_printf("%s\n", tmp->name); else my_printf("%C%s\n", BOLDGREY, tmp->name); tmp = tmp->next; } }
C
/* iki_boyutlu_dizi_ekrana_yazdirma_kullanici_girisli.c */ #include<stdio.h> #include<math.h> int main(){ int a[3][3]; int i,j; for(i=0;i<3;i++){ for(j=0;j<3;j++){ printf("%d %d elemanini gir = ",i+1,j+1); scanf("%d",&a[i][j]); } } printf("Girilen Matris...\n_______________\n"); for(i=0;i<3;i++){ for(j=0;j<3;j++){ printf("%7d ",a[i][j]); } printf("\n"); } return 0; }
C
//////////////////////////////////////////////////////////////////////// // // Copyright 2015 PMC-Sierra, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you // may not use this file except in compliance with the License. You may // obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 Unless required by // applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for // the specific language governing permissions and limitations under the // License. // //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // // Author: Logan Gunthorpe // // Description: // Write thread which pops buffers from the wqueue and processes // their results. Multiple threads either copy the buffer to another // file or swaps the target phrase at the indexes found. // //////////////////////////////////////////////////////////////////////// #include "writethrd.h" #include "readthrd.h" #include <capi/worker.h> #include <capi/macro.h> #include <capi/capi.h> #include <capi/wqueue.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/resource.h> #include <fcntl.h> #include <unistd.h> #include <pthread.h> #include <errno.h> #include <string.h> #include <stdio.h> #include <inttypes.h> struct writethrd { struct worker worker; const char *fpath; struct fifo *fifo; int flags; unsigned long matches; char swap_phrase[17]; pthread_t wqueue_thrd; struct rusage wqueue_rusage; }; static void *copy_thread(void *arg) { struct writethrd *wt = container_of(arg, struct writethrd, worker); int fd = open(wt->fpath, O_WRONLY); if (fd < 0) { perror("copy thread open"); return NULL; } struct readthrd_item *item; while ((item = fifo_pop(wt->fifo)) != NULL) { lseek(fd, item->offset, SEEK_SET); if (write(fd, item->buf, item->real_bytes) < 0) { perror("Copy Thread Write"); exit(EIO); } free(item->buf); free(item); } close(fd); worker_finish_thread(&wt->worker); return NULL; } static void *swap_thread(void *arg) { struct writethrd *wt = container_of(arg, struct writethrd, worker); int fd = -1; if (!(wt->flags & WRITETHREAD_SEARCH_ONLY)) { fd = open(wt->fpath, O_WRONLY); if (fd < 0) { perror("swap thread open"); return NULL; } } size_t plen = strlen(wt->swap_phrase); struct readthrd_item *item; unsigned long matches = 0; while ((item = fifo_pop(wt->fifo)) != NULL) { uint32_t *indexes = item->buf; for (int i = 0; i < item->result_bytes / sizeof(*indexes); i++) { if (indexes[i] == INT32_MAX) break; int idx = indexes[i] + item->offset; matches++; if (wt->flags & WRITETHREAD_PRINT_OFFSETS) printf("%10"PRId32"\n", idx); if (wt->flags & WRITETHREAD_SEARCH_ONLY) continue; lseek(fd, idx, SEEK_SET); if (write(fd, wt->swap_phrase, plen) < 0) { perror("Swap Thread Write"); exit(EIO); } } free(item->buf); free(item); } __sync_add_and_fetch(&wt->matches, matches); if (fd >= 0) close(fd); worker_finish_thread(&wt->worker); return NULL; } static void *wqueue_thread(void *arg) { struct writethrd *wt = arg; int last = 0; unsigned next_index = 0; while(!last) { struct wqueue_item it; int error_code = wqueue_pop(&it); int dirty = it.flags & WQ_DIRTY_FLAG || wt->flags & WRITETHREAD_ALWAYS_WRITE; struct readthrd_item *item = it.opaque; if (error_code) { fprintf(stderr, "Error 0x%04x processing buffer %d (at 0x%p)\n", error_code, item->index, item->buf); exit(EIO); } if (wt->flags & WRITETHREAD_VERBOSE) printf("Got Buffer %d: %p for %zd (%d)\n", item->index, item->buf, item->offset, dirty); if (item->index != next_index++) { fprintf(stderr, "Error buffers came back out of order!\n"); exit(EPIPE); } last = item->last; item->result_bytes = it.dst_len; if (wt->flags & WRITETHREAD_DISCARD || !dirty) { free(item->buf); free(item); } else { fifo_push(wt->fifo, item); } } fifo_close(wt->fifo); getrusage(RUSAGE_THREAD, &wt->wqueue_rusage); return NULL; } static int check_file(const char *f, int truncate) { int fd = open(f, O_WRONLY | O_CREAT | (truncate ? O_TRUNC : 0), 0664); if (fd < 0) { fprintf(stderr, "Unable to open '%s': %s\n", f, strerror(errno)); return -1; } close(fd); return 0; } static int next_power_of_2(int x) { x--; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; x++; return x; } struct writethrd *writethrd_start(const char *fpath, const char *swap_phrase, int num_threads, int flags) { if (!(flags & WRITETHREAD_SEARCH_ONLY) && check_file(fpath, flags & WRITETHREAD_TRUNCATE)) return NULL; struct writethrd *wt = malloc(sizeof(*wt)); if (wt == NULL) return NULL; wt->fifo = fifo_new(next_power_of_2(num_threads*2)); if (wt->fifo == NULL) goto error_out; fifo_open(wt->fifo); wt->fpath = fpath; wt->flags = flags; wt->matches = 0; strncpy(wt->swap_phrase, swap_phrase, sizeof(wt->swap_phrase) - 1); wt->swap_phrase[sizeof(wt->swap_phrase) - 1] = 0; if (pthread_create(&wt->wqueue_thrd, NULL, wqueue_thread, wt)) goto error_fifo_out; void *(*start_routine) (void *); start_routine = swap_thread; if (wt->flags & WRITETHREAD_COPY) start_routine = copy_thread; if (worker_start(&wt->worker, num_threads, start_routine)) goto error_wqueue_stop; return wt; error_wqueue_stop: pthread_cancel(wt->wqueue_thrd); error_fifo_out: fifo_free(wt->fifo); error_out: free(wt); return NULL; } void writethrd_join(struct writethrd *wt) { if (wt == NULL) return; pthread_join(wt->wqueue_thrd, NULL); worker_join(&wt->worker); } void writethrd_print_cputime(struct writethrd *wt) { if (wt == NULL) return; fprintf(stderr, "Write Thread CPU Time:\n"); worker_print_cputime(&wt->worker, &wt->wqueue_rusage, "W"); } void writethrd_free(struct writethrd *wt) { if (wt == NULL) return; worker_free(&wt->worker); fifo_free(wt->fifo); free(wt); } unsigned long writethrd_matches(struct writethrd *wt) { return wt->matches; }
C
#include "defines.h" #include "data.h" #define PropertyLen 7 typedef struct{ char* key; char* value; } dict_entry; char* null_char = "NULL"; char* PropertiesList = NULL; dict_entry Properties[PropertyLen] = { {.key = "mode", .value = "judje"}, {.key = "source", .value = "run.c"}, {.key = "lbinary", .value = "run"}, {.key = "wbinary", .value = "run.exe"}, {.key = "project", .value = "root"}, {.key = "projectroot", . value = "bin"}, {.key = "help", .value = "help"} }; char** GetProperty(char* propertyname){ if (Equals(propertyname, "properties")){ int len = 2 + PropertyLen; for(int i = 0; i < PropertyLen; i++){ len += CountChar(Properties[i].value, '\n'); } PropertiesList = malloc(sizeof(char) * len); PropertiesList[0] = '\n'; PropertiesList[len] = 0; for(int i = 0; i < PropertyLen; i++){ for(int j = 0; (Properties[i]).value[j] != 0; j++){ PropertiesList[i + j] = Properties[i].value[j]; } PropertiesList[++i] = '\n'; } return &PropertiesList; } for(int i = 0; i < PropertyLen; i++){ if (Equals(Properties[i].key, propertyname)){ char** ret = &(Properties[i].value); return ret; } } return &null_char; }
C
// https://www.urionlinejudge.com.br/judge/en/problems/view/2310 #include <stdio.h> int main(int argc, char *argv[]) { int n, tmpSer, tmpBlk, tmpAtk, totSer = 0, totBlk = 0, totAtk = 0; int tmpScsSer, tmpScsBlk, tmpScsAtk, totScsSer = 0, totScsBlk = 0, totScsAtk = 0; char tmpName[100]; scanf("%d", &n); while (n >= 1) { scanf("%s", &tmpName); scanf("%d %d %d", &tmpSer, &tmpBlk, &tmpAtk); totSer += tmpSer; totBlk += tmpBlk; totAtk += tmpAtk; scanf("%d %d %d", &tmpScsSer, &tmpScsBlk, &tmpScsAtk); totScsSer += tmpScsSer; totScsBlk += tmpScsBlk; totScsAtk += tmpScsAtk; n--; } printf("Pontos de Saque: %.2f %%.\n", (totScsSer + 0.0) / totSer * 100); printf("Pontos de Bloqueio: %.2f %%.\n", (totScsBlk + 0.0) / totBlk * 100); printf("Pontos de Ataque: %.2f %%.\n", (totScsAtk + 0.0) / totAtk * 100); return 0; }
C
#include <stdio.h> int convnum(int conv); int main() { unsigned long n, o; int i, j; unsigned int num[62]; printf("base 10 input: "); scanf("%lu", &n); for (i = 2; i <= 62; i++) { printf("base %d: ", i); j = 0; o = n; while (o != 0) { num[j] = o % i; o /= i; j++; } j--; while (j >= 0) { printf("%c", convnum(num[j])); j--; } printf("\n"); } return 0; } int convnum(int conv) { if (conv <= 9) { return conv + '0'; } else if (conv > 9 && conv < 36) { return conv + 'a' - 10; } else if (conv >= 36 && conv < 62) { return conv + 'A' - 36; } else return -1; }
C
/* ** change_key_quit.c for change_key_quit in /home/marel_m/Rendu/Semestre_2/Systeme_Unix/PSU_2015_tetris ** ** Made by maud marel ** Login <marel_m@epitech.net> ** ** Started on Sun Feb 28 18:56:56 2016 maud marel ** Last update Tue Mar 8 15:40:47 2016 maud marel */ #include "tetris.h" bool change_key_quit(t_tetris *tetris, char *str) { int i; int j; i = 0; while (str && str[i] != '=') i++; i++; if (i == my_strlen(str)) wrong_options(str); if ((tetris->options->quit = malloc(sizeof(char) * my_strlen(str) - (i + 1))) == NULL) return (false); j = 0; while (str[i] != '\0') { tetris->options->quit[j] = str[i]; i++; j++; } tetris->options->quit[j] = '\0'; return (true); } bool change_key_quit_simp(t_tetris *tetris, char *str) { if ((tetris->options->quit = my_strdup(str)) == NULL) return (false); return (true); }
C
#include <stdio.h> int main() { long long int N; int T; scanf("%d", &T); while(T--) { scanf("%lld", &N); if(N&1)printf("BOB\n"); else printf("ALICE\n"); } return 0; }
C
#include "ready_queue_utils.h" int compare_nodes(Node *node1, Node *node2) { int res = node1->priority - node2->priority; return (res == 0) ? (node2->timestamp - node1->timestamp) : res; }
C
#include <minios/sem.h> #include <minios/idt.h> #include "con.h" extern void kbd_intr(); struct console_s console[MAX_CONSOLES]; struct console_s *current_con; size_t con_read(struct file_s *flip, char *buf, size_t n); ssize_t con_write(struct file_s *flip, char *buf, size_t n); static struct file_operations_s ops = { .read = con_read, .write = con_write }; void con_switch(int con_num) { con_num %= MAX_CONSOLES; current_con = &console[con_num]; kbd_currentkbd(&current_con->kbd); /* update video ram with new console */ vga_copy_vram(current_con->video); vga_move_cursor(current_con->x, current_con->y); } void con_init() { int i, j, k; /* initialize virtual consoles (MAX_CONSOLES < 10) */ for (i = 0; i < MAX_CONSOLES; i++) { console[i].i = i; console[i].x = 0; console[i].y = 0; console[i].xlimit = 0; for (j = 0; j < 25; j++) { for (k = 0; k < 80; k++) { console[i].video[j][k].letter = 0; console[i].video[j][k].color = VGA_FC_WHITE; } } kbd_init(&console[i].kbd); } /* make current virtual terminal dev */ con_switch(0); /* manage keyboard interruptions */ idt_register(33, kbd_intr, DEFAULT_PL); /* register device */ dev_register(DEV_TTY, &ops); } void con_right() { con_switch((current_con->i + 1) % MAX_CONSOLES); } void con_left() { if (current_con->i == 0) con_switch(MAX_CONSOLES - 1); else con_switch(current_con->i - 1); } void scrollup(struct video_char_s video[25][80]) { int i, j; for (i = 0; i < 24; i++) { for (j = 0; j < 80; j++) { video[i][j].letter = video[i+1][j].letter; video[i][j].color = video[i+1][j].color; } } for (j = 0; j < 80; j++) { video[24][j].letter = 0; video[24][j].color = VGA_FC_WHITE; } } /* print 1 key in the screen */ void con_print_key(struct console_s *c, char key) { switch (key) { case KEY_LEFT: con_left(); break; case KEY_RIGHT: con_right(); break; case '\n': c->x = c->xlimit = 0; if (c->y == 24) { scrollup(c->video); if (c == current_con) vga_scrollup_vram(); } else { c->y++; } break; case '\b': if (c->x > c->xlimit) { c->x--; c->video[c->y][c->x].letter = 0; if (c == current_con) vga_print_key(c->y, c->x, 0); } break; case '\t': key = ' '; default: c->video[c->y][c->x].letter = key; c->video[c->y][c->x].color = VGA_FC_WHITE; if (c == current_con) vga_print_key(c->y, c->x, key); c->x++; if (c->x == 80) { c->x = c->xlimit = 0; if (c->y == 24) { scrollup(c->video); if (c == current_con) vga_scrollup_vram(); } else { c->y++; } } } if (c == current_con) vga_move_cursor(c->x, c->y); } size_t con_read(struct file_s *flip, char *buf, size_t n) { int minor = iminor(flip->f_ino); sem_wait(&console[minor].kbd.data); return kbd_getline(&console[minor].kbd, buf, n); } int con_realwrite(struct console_s *con, const char* msg, int n) { int i; for (i = 0; i < n; ++i) con_print_key(con, msg[i]); con->xlimit = con->x; return i; } ssize_t con_write(struct file_s *flip, char *buf, size_t n) { int minor = iminor(flip->f_ino); return con_realwrite(&console[minor], buf, n); }
C
#include "stm32f1xx_ll_bus.h" #include "stm32f1xx_ll_gpio.h" #include "stm32f1xx_ll_utils.h" #include "stm32f1xx_ll_usart.h" #include "stm32f1xx_ll_rcc.h" #include "stm32f1xx_ll_system.h" // utile dans la fonction SystemClock_Config #include "Allure.h" #include "Voile.h" #include "string.h" #define TAILLE_MESSAGE_MAX 100 #define USARTX USART1 // Structure pour grer la transmission du message struct t_transmission { char message[TAILLE_MESSAGE_MAX];// Le message lui mme int position;// La position du caractere a envoyer int taille_message; //On peut envoyer des messages de tailles variables, il faut donc spcifier la taille char envoyer;// Boolen utilis comme flag -> vrai on envoie, faux on fait rien char exceptionnel; //Boolen utilis comme flag -> vrai on envoie un message excep donc, on ne fait pas l'envoi regulier }; /** * @brief Initialise une structure t_transmission. * @note Structure initialise : (message -> 00:00:00:, end_of_message -> 0x0D, position -> 0, first_appel -> 1) * @param @ de la structure a initialiser * @retval None */ void init_t_transmission(struct t_transmission * transmission) { int i; for (i=0; i<TAILLE_MESSAGE_MAX; i++) { transmission->message[i] = '0'; } transmission->message[TAILLE_MESSAGE_MAX - 1] = '\0'; transmission->position = 0; transmission->taille_message = 0; transmission->envoyer = 0; transmission->exceptionnel = 0; } static struct t_transmission transmission; void ConfTransmission(){ LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_USART1); //On enable la clock pour l'USARt LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_GPIOA); //enable la clock du gpio o est l'USART LL_GPIO_SetPinMode(GPIOA,LL_GPIO_PIN_9,LL_GPIO_MODE_ALTERNATE); // Mode fonction alternative PIN USART Tx LL_USART_InitTypeDef USART_InitStruct; LL_USART_StructInit(&USART_InitStruct); USART_InitStruct.BaudRate = 9600; //Set Baud rate -> 19200Bd USART_InitStruct.DataWidth = LL_USART_DATAWIDTH_8B; //Set data width -> 8bits USART_InitStruct.Parity = LL_USART_PARITY_NONE;// Disable Parity USART_InitStruct.StopBits = LL_USART_STOPBITS_1;// Set stop bit -> 1 USART_InitStruct.TransferDirection = LL_USART_DIRECTION_TX;//Set sens -> TX Only LL_USART_Init(USARTX, &USART_InitStruct);// Applique les modifs LL_USART_Enable(USARTX);// Rend l'USART enable A FAIRE EN DERNIER /*LL_USART_EnableDirectionTx(USARTX); //Enable direction Tx LL_USART_SetParity(USARTX,LL_USART_PARITY_NONE); // disable parity bit LL_USART_SetStopBitsLength(USARTX,LL_USART_STOPBITS_1); LL_USART_SetBaudRate(USARTX, 72000000,9600); //Set Baud Rate 9600 (rgle de trois avec 1 pour 36 000 0000 LL_USART_Enable(USARTX); //Enable Usart*/ LL_GPIO_SetPinMode(GPIOA,LL_GPIO_PIN_11,LL_GPIO_MODE_OUTPUT); LL_GPIO_SetPinOutputType(GPIOA,LL_GPIO_PIN_11,LL_GPIO_OUTPUT_PUSHPULL); init_t_transmission(&transmission); } void EnvoiRegulier(char * Allure, char * tension){ if (!transmission.exceptionnel) { /* Message de la forme suivante : _____________________________ Allure actuelle : xxxxxxxxxxx Tension des voiles : xxxxxxxx _____________________________*/ static char promptligne1[] = "Allure actuelle : "; static int promptligne1size = 19; static char promptligne2[] = "Tension des voiles : "; static int promptligne2size = 22; static char rc[] = "\n"; static int rcsize = 2; transmission.message[0] = '\0'; int current_size = 1; current_size = Concatenate(promptligne1, transmission.message, promptligne1size, current_size, TAILLE_MESSAGE_MAX); current_size = Concatenate(Allure, transmission.message, size_of(Allure), current_size, TAILLE_MESSAGE_MAX); current_size = Concatenate(rc, transmission.message, rcsize, current_size, TAILLE_MESSAGE_MAX); current_size = Concatenate(promptligne2, transmission.message, promptligne2size, current_size, TAILLE_MESSAGE_MAX); current_size = Concatenate(tension, transmission.message, size_of(tension), current_size, TAILLE_MESSAGE_MAX); current_size = Concatenate(rc, transmission.message, rcsize, current_size, TAILLE_MESSAGE_MAX); current_size = Concatenate(rc, transmission.message, rcsize, current_size, TAILLE_MESSAGE_MAX); transmission.envoyer = 1; transmission.position = 0; transmission.taille_message = current_size; } } /*LL_GPIO_SetOutputPin(GPIOA,LL_GPIO_PIN_11); int tailleAllure = sizeof(Allure); int tailleTension = 8; //ATTENTION TAILLE int index = 0; while(index < tailleAllure){ if (LL_USART_IsActiveFlag_TXE(USART1)){ //On regarde si le flag de transmission termine est actif LL_USART_TransmitData8(USART1, (uint8_t) Allure[index]); //On envoie le message (8 bits) index++; } } index = 0; while(index < tailleTension){ if (LL_USART_IsActiveFlag_TXE(USART1)){ //On regarde si le flag de transmission termine est actif LL_USART_TransmitData8(USART1, (uint8_t) tension[index]); //On envoie le message (8 bits) index++; } } LL_GPIO_ResetOutputPin(GPIOA,LL_GPIO_PIN_11); }*/ void EnvoiExceptionnel(char * msgAlarme){ /* Message de la forme suivante : _____________________________ Allure actuelle : xxxxxxxxxxx Tension des voiles : xxxxxxxx _____________________________*/ static char prompt[] = "WARNING : "; static int promptsize = 11; static char rc[] = "\n"; static int rcsize = 2; transmission.message[0] = '\0'; int current_size = 1; current_size = Concatenate(rc, transmission.message, rcsize, current_size, TAILLE_MESSAGE_MAX); current_size = Concatenate(rc, transmission.message, rcsize, current_size, TAILLE_MESSAGE_MAX); current_size = Concatenate(prompt, transmission.message, promptsize, current_size, TAILLE_MESSAGE_MAX); current_size = Concatenate(msgAlarme, transmission.message, size_of(msgAlarme), current_size, TAILLE_MESSAGE_MAX); current_size = Concatenate(rc, transmission.message, rcsize, current_size, TAILLE_MESSAGE_MAX); current_size = Concatenate(rc, transmission.message, rcsize, current_size, TAILLE_MESSAGE_MAX); transmission.envoyer = 1; transmission.position = 0; transmission.taille_message = current_size; transmission.exceptionnel = 1; } /*LL_GPIO_SetOutputPin(GPIOA,LL_GPIO_PIN_11); int tailleMessage = sizeof(msgAlarme); int index = 0; while(index < tailleMessage){ if (LL_USART_IsActiveFlag_TXE(USART1)){ //On regarde si le flag de transmission termine est actif LL_USART_TransmitData8(USART1, (uint8_t) msgAlarme[index]); //On envoie le message (8 bits) index++; } } LL_GPIO_ResetOutputPin(GPIOA,LL_GPIO_PIN_11); }*/ void EnvoyerCaractere(void) { if (transmission.envoyer) { LL_GPIO_SetOutputPin(GPIOA,LL_GPIO_PIN_11); if (LL_USART_IsActiveFlag_TXE(USARTX)) {//On regarde si le flag de transmission termine est actif if (transmission.position < transmission.taille_message) { LL_USART_TransmitData8(USARTX, (uint8_t)(transmission.message[transmission.position])); transmission.position += 1; } else { transmission.envoyer = 0; transmission.exceptionnel = 0; } } LL_GPIO_ResetOutputPin(GPIOA,LL_GPIO_PIN_11); } }
C
#ifdef _WINDOWS #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #endif #include"leptjson.h" #include<assert.h> #include <errno.h> /* errno, ERANGE */ #include <math.h> /* HUGE_VAL */ #ifndef LEPT_PARSE_STACK_INIT_SIZE #define LEPT_PARSE_STACK_INIT_SIZE 256 #endif /*װһṹֹ*/ typedef struct { const char* json; char* stack; size_t top, size; }lept_context; #define ISDIGIT(c) (c>='0' && c<='9') #define ISDIGIT1TO9(c) (c>='1'&&c<='9') #define EXPECT(c,ch) do{\ assert(*(c->json)==ch);\ c->json++;\ }while(0) #define PUTC(con,ch) \ do{ \ *((char*)lept_contest_push(con,1)) = ch;\ } while (0) #define STRING_ERROR(ret) do{\ c->top = head;\ return ret;}while(0) /*ո*/ static void lept_parse_whitespace(lept_context* lc) { char *t = lc->json; while (*t == ' '||*t =='\t'||*t == '\n'||*t == '\r') { t++; } lc->json = t; } static int lept_parse_literal(lept_context*c, lept_value*v,const char* lit,lept_type type) { assert(lit != NULL&& lit[0]); //ַstrlenundefined behavior int len = strlen(lit); char first_c = lit[0]; EXPECT(c, first_c);//֮ﻹҪexceptassertһ£ΪҪвԶ char* t = c->json; //ɹ||ص㣬Խʵķнԭ int i = 0; while (i<len-1)//EXCEPTѾ1 { if (t[i] != lit[i + 1]) return LEPT_PARSE_INVALID_VALUE; i++; } c->json += len - 1; //EXCEPTѾ1 v->type = type; return LEPT_PARSE_OK; } /*״̬*/ /* trick: ԼдĴжstrtodjson׼IJ֣ͨstrtodת ڳTOO_BIG֮ĴȫԼжϣҪENDжϣҲҪͨendc->jsonλ ע notice: strtodжnumberķشķʽ*/ static int lept_parse_number(lept_context*c, lept_value* v) { char* p = c->json; if (*p == '-') p++; //߹һ,-ѡ÷ش //һȹ if (*p == '0') p++; else if (ISDIGIT1TO9(*p)) { while (ISDIGIT1TO9(*p)) p++; } else return LEPT_PARSE_INVALID_VALUE; //˵DZ뾭ģԲΪ //ѡfrac if (*p == '.') { p++; if (!ISDIGIT(*p)) return LEPT_PARSE_INVALID_VALUE;//Сһ while (ISDIGIT(*p)) p++; } //ѡ exp if (*p == 'e' || *p == 'E') { p++; if (*p == '+' || *p == '-') p++; if (!ISDIGIT(*p)) return LEPT_PARSE_INVALID_VALUE;//eһ while (ISDIGIT(*p)) p++; } errno = 0; v->u.n = strtod(c->json, NULL); if (errno == ERANGE && (v->u.n == HUGE_VAL || v->u.n == -HUGE_VAL)) return LEPT_PARSE_NUMBER_TOO_BIG; v->type = LEPT_NUMBER; c->json = p; return LEPT_PARSE_OK; } /* һַиֵ,byteѹ notice: ںиֵ */ static void* lept_contest_push(lept_context* c, size_t size) { /*mistake: assert*/ assert(size > 0); if (c->size == 0) { c->size = LEPT_PARSE_STACK_INIT_SIZE; c->stack = (char*)malloc(c->size * sizeof(char)); } if (c->top + size > c->size) { while (c->top + size > c->size) { c->size += c->size >> 1; //1.5 c->stack = (char*)realloc(c->stack, c->size * sizeof(char)); } } c->top += size; /*qustion㲻voidҲʽת*/ return (void*)(c->stack + c->top); } static void* lept_contest_pop(lept_context* c,size_t size) { assert(c->top >= size); c->top -= size; return c->stack + (c->top -= size); } //mistake:Ӧóstaitc,Ϊset /* * c: stack in lept_contest * size: lenth * return: void */ void lept_set_string(lept_value*v, const char* c,size_t size) { //ûбҪlept_contest assert(v != NULL && (c != NULL || size == 0)); /*mistake:ûfree*/ lept_free(v); /*mistake: reallocﲢûڹ캯ĵطռ䣬õʱ*/ v->u.s.s = (char*)malloc( (size+1) * sizeof(char)); memcpy(v->u.s.s, c, size); v->u.s.s[size] = '\0'; v->type = LEPT_STRING; v->u.s.len = size; } /*ַ4charת4λ16unsigned int*/ static const char* lept_parse_hex4(const char* p, unsigned* u) { int i; *u = 0; for (i = 0; i < 4; i++) { char ch = *p++; *u <<= 4; if (ch >= '0' && ch <= '9') *u |= ch - '0'; else if (ch >= 'A' && ch <= 'F') *u |= ch - ('A' - 10); else if (ch >= 'a' && ch <= 'f') *u |= ch - ('a' - 10); else return NULL; } return p; } static void lept_encode_utf8(lept_context* c, unsigned u) { if (u <= 0x7F) //0X7F 111 1111 PUTC(c, u & 0xFF);//0XFF 1111 1111 else if (u <= 0x7FF) { PUTC(c, 0xC0 | ((u >> 6) & 0xFF)); PUTC(c, 0x80 | (u & 0x3F)); } else if (u <= 0xFFFF) { PUTC(c, 0xE0 | ((u >> 12) & 0xFF)); PUTC(c, 0x80 | ((u >> 6) & 0x3F)); PUTC(c, 0x80 | (u & 0x3F)); } else { assert(u <= 0x10FFFF); PUTC(c, 0xF0 | ((u >> 18) & 0xFF)); PUTC(c, 0x80 | ((u >> 12) & 0x3F)); PUTC(c, 0x80 | ((u >> 6) & 0x3F)); PUTC(c, 0x80 | (u & 0x3F)); } } /*LEPT_PARSE_INVALID_STRING_ESCAPEعc->stack*/ static int lept_parse_string(lept_context*c, lept_value* v) { EXPECT(c, '\"'); size_t head = c->top; //mistakeʼҾstackheadˣֻĿǰ unsigned u, u2; char* p = c->json; //EXPECT Ѿ++ int len = 0; while (1) { switch (*p) { case '"': //Ӳ\ /*mistake:һʼдv->u.s.s = (char*)lept_contest_pop(c, len); contestٺlept_valueҲû,ӽ*/ lept_set_string(v, c->stack, c->top- head); c->json = p + 1; return LEPT_PARSE_OK; case '\0': c->top = head;//mistake:ˣΪصIJmistake,һµ p++; return LEPT_PARSE_MISS_QUOTATION_MARK; case '\\': p++; switch (*p) { case '\"': PUTC(c, '\"'); break; case '\\': PUTC(c, '\\'); break; case '/': PUTC(c, '/'); break; case 'b': PUTC(c, '\b'); break; case 'f': PUTC(c, '\f'); break; case 'n': PUTC(c, '\n'); break; case 'r': PUTC(c, '\r'); break; case 't': PUTC(c, '\t'); break; case 'u': p++; if (!(p = lept_parse_hex4(p, &u))) STRING_ERROR(LEPT_PARSE_INVALID_UNICODE_HEX); if (u >= 0xD800 && u <= 0xDBFF) { /* surrogate pair */ if (*p++ != '\\') STRING_ERROR(LEPT_PARSE_INVALID_UNICODE_SURROGATE); if (*p++ != 'u') STRING_ERROR(LEPT_PARSE_INVALID_UNICODE_SURROGATE); if (!(p = lept_parse_hex4(p, &u2))) STRING_ERROR(LEPT_PARSE_INVALID_UNICODE_HEX); if (u2 < 0xDC00 || u2 > 0xDFFF) STRING_ERROR(LEPT_PARSE_INVALID_UNICODE_SURROGATE); u = (((u - 0xD800) << 10) | (u2 - 0xDC00)) + 0x10000; } lept_encode_utf8(c, u); break; default: //c->top = head; //notice: ҪعģյģΪǿ³ԣ //return LEPT_PARSE_INVALID_STRING_ESCAPE; STRING_ERROR(LEPT_PARSE_INVALID_STRING_ESCAPE); } default: if ((unsigned char)*p < 0x20) { STRING_ERROR(LEPT_PARSE_INVALID_STRING_CHAR); } PUTC(c, *p); p++; break; } } } /*ûlept_parseҪбfreeַռ*/ void lept_free(lept_value*v) { /*mistake:жϺassert*/ assert(v != NULL); if (v->type == LEPT_STRING) free(v->u.s.s); v->type = LEPT_NULL; } /*֮Բдlept_parseҾҪǹܵһֻΪparse ws value wsе valueDZ*/ /*ȷߴ*/ /*дֳɺüСֹif߸ӵcase*/ static int lept_parse_value(lept_context* lc, lept_value*v) { switch (lc->json[0]) { case 'n':return lept_parse_literal(lc,v,"null",LEPT_NULL); break; case 't':return lept_parse_literal(lc,v,"true",LEPT_TRUE); break; case 'f':return lept_parse_literal(lc,v,"false",LEPT_FALSE); break; case '\0':return LEPT_PARSE_EXPECT_VALUE; break; case '"':return lept_parse_string(lc, v); default: return lept_parse_number(lc,v); break; } } /*ͨƶjsonָķʽڸ䴫εʱöഫһʾλõIJ*/ int lept_parse(lept_value* lvalue, const char* json) { lept_context lc; lc.json = json; lc.size = 0; lc.top = 0; assert(lvalue != NULL); //ҪjsonǷΪnull,ΪﲻǺߵΣûΣmark:question lvalue->type = LEPT_NULL; //ĬΪnull lept_parse_whitespace(&lc); int ret = lept_parse_value(&lc, lvalue); lept_parse_whitespace(&lc); if (ret == LEPT_PARSE_OK&&*(lc.json) != '\0') ret = LEPT_PARSE_ROOT_NOT_SINGULAR; return ret; } // get method lept_type lept_get_type(const lept_value* v) { return v->type; } double lept_get_number(const lept_value*v) { assert(v != NULL && v->type == LEPT_NUMBER); return v->u.n; } //mistake: Ӧ÷const char* const char* lept_get_string(const lept_value*v) { assert(v != NULL && v->type == LEPT_STRING); return v->u.s.s; } size_t lept_get_string_length(const lept_value*v) { //mistake: assert assert(v != NULL && v->type == LEPT_STRING); return v->u.s.len; } /*LEPT_TRUE 1 FALSE 0*/ int lept_get_boolean(const lept_value* v) { assert(v != NULL && (v->type == LEPT_FALSE || v->type == LEPT_TRUE)); return v->type == LEPT_TRUE; } void lept_set_boolean(lept_value* v, int b) { //mistake: ûһв lept_free(v); v->type = b ? LEPT_TRUE : LEPT_FALSE; } void lept_set_number(lept_value* v, double n) { lept_free(v); v->type = LEPT_NUMBER; v->u.n = n; }
C
#include <stdio.h> #include <omp.h> static long num_steps = 100000; static double step; #define NUM_THREADS 8 int main () { int i, nthreads; double pi, sum[NUM_THREADS]; step = 1.0/(double) num_steps; omp_set_num_threads(NUM_THREADS); #pragma omp parallel { // fork int i, id, nthrds; double x; id = omp_get_thread_num(); nthrds = omp_get_num_threads(); if (id == 0) nthreads = nthrds; for (i=id, sum[id]=0.0;i< num_steps; i=i+nthrds) { x = (i+0.5)*step; sum[id] += 4.0/(1.0+x*x); // False Sharing nessa linha. // Toda vez que uma thread alterar um valor do vetor, a flag "alterada" // na cache será passada para true, de forma que a thread seguinte terá // de recarregar todo o vetor novamente, mesmo que a célula que vai mexer // não tenha propriamente uma alteração. } } // join for(i=0, pi=0.0;i<nthreads;i++) pi += sum[i] * step; printf("%lf\n", pi); return 0; }
C
#include "NU32.h" #include "direction.h" #include <stdio.h> #define BUF_SIZE 200 #define NU32_SYS_FREQ 80000000ul #define MAX_MESSAGE_LENGTH 10 int main(){ char buffer[BUF_SIZE]; NU32_Startup(); NU32_LED1 = 1; NU32_LED2 = 1; U1MODEbits.BRGH = 0; // U3BRG = (float)((NU32_SYS_FREQ / 38400) / 16) - 1; U1BRG = 129; // configure TX & RX pins U1STAbits.UTXEN = 1; U1STAbits.URXEN = 1; // turn on UART1 U1MODEbits.ON = 1; char message[MAX_MESSAGE_LENGTH]; while(1){ char data = 0; if(U1STAbits.URXDA) { // poll to see if there is data to read in RX FIFO data = U1RXREG; NU32_LED1 = 0; if(data == 0){ NU32_LED2 = 0; }else{ NU32_LED2 = 1; } } sprintf(message,data); NU32_WriteUART3(message); // send message back NU32_WriteUART3("\r\n"); } return 0; }
C
// // Created by Bernigend on 23.05.2020. // #ifndef LABORATORY_WORK_3_V2_BYTE_H #define LABORATORY_WORK_3_V2_BYTE_H struct Byte { char value; Byte* next; Byte* prev; Byte() { this->value = '\0'; this->next = NULL; this->prev = NULL; } explicit Byte(char _value) { this->value = _value; this->next = NULL; this->prev = NULL; } Byte(const Byte& byte) { this->value = byte.value; this->next = byte.next; this->prev = byte.prev; } }; typedef Byte* pByte; #endif //LABORATORY_WORK_3_V2_BYTE_H
C
#include <stdio.h> #include <stdlib.h> #include <conio.h> #include <string.h> #include "funciones.h" #include "autos.h" #include "egresos.h" #define TAMPROP 50 #define TAMAUTO 20 int main() { EPropietario listaDePropietario[TAMPROP]; inicializarListaPropietario(listaDePropietario,TAMPROP); inicializarPropietariosHardCode(listaDePropietario,TAMPROP); EAutos listaDeAutos[TAMAUTO]; inicializarListaAutos(listaDeAutos,TAMAUTO); inicializarAutosHardCode(listaDeAutos,TAMAUTO); EEgresos listaDeEgresosAutos[TAMAUTO]; inicializarEgresosHardCode(listaDeEgresosAutos,TAMAUTO); char seguir='s'; int opcion=0; do { printf("---------------------------------------\n\n"); printf("1- ALTA PROPIETARIO\n"); printf("2- MODIFICACION PROPIETARIO\n"); printf("3- BAJA PROPIETARIO\n"); printf("4- INGRESO DE AUTO\n"); printf("5- EGRESO DE AUTO\n"); printf("6- RECAUDACION TOTAL DE ESTACIONAMIENTO\n"); printf("7- RECAUDACION TOTAL POR MARCA\n"); printf("8- MOSTRAR PROPIETARIO CON SU AUTO\n"); printf("9- MOSTRAR LISTA AUTOS: AUDI\n"); printf("10- MOSTRAR LISTA TODOS AUTOS\n"); printf("11- Salir\n\n"); printf("Respuesta: "); scanf("%d",&opcion); printf("---------------------------------------\n"); switch(opcion) { case 1: altaDePropietario(listaDePropietario,TAMPROP); break; case 2: modificarDatos(listaDePropietario,TAMPROP); break; case 3: bajaPropietario(listaDePropietario,TAMPROP); break; case 4: ingresoDeAutomovil(listaDeAutos,TAMAUTO); break; case 5: egresodeAutos(listaDeEgresosAutos,TAMAUTO,listaDePropietario,TAMPROP,listaDeAutos); break; case 6: recaudacionTotal(listaDeEgresosAutos,TAMAUTO); break; case 7: recaudacionPorMarca(listaDeEgresosAutos,TAMAUTO); break; case 8: listaPropietarioConAutos(listaDePropietario,TAMPROP,listaDeAutos,TAMAUTO); break; case 9: listaAutoPorMarcaAudi(listaDeAutos,TAMAUTO,listaDePropietario,TAMPROP,3); break; case 10: listaAutosPorPatente(listaDeAutos,TAMAUTO,listaDePropietario,TAMPROP); break; seguir = 'n'; break; } system("pause"); system("cls"); }while(seguir=='s'); return 0; }
C
/*the maze problem * 2 stands for the start position * 3 stands for the end position * 0 stands for the road * 1 stands for the wall * 6 stands for the road you have walked * */ /*there are some examples for you 7 6 0 0 1 0 0 3 0 1 0 0 1 1 0 0 0 1 0 0 1 1 0 1 0 1 1 0 0 1 0 1 1 0 0 0 0 0 0 1 0 0 1 2*/ /* 16 12 1 1 1 1 1 1 2 0 0 1 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 1 1 0 1 0 0 1 0 1 0 1 0 1 0 0 1 0 1 0 0 0 0 0 1 0 0 1 0 0 1 1 1 0 1 0 1 0 1 0 0 0 0 0 0 1 0 0 1 0 0 0 1 1 1 0 1 1 1 0 1 1 1 0 1 0 0 1 0 0 0 1 0 1 0 0 0 1 0 0 0 1 0 0 0 0 0 1 0 1 0 1 0 1 0 1 1 0 1 0 0 1 1 0 0 0 0 0 1 0 0 1 0 0 0 0 1 0 0 1 0 0 1 0 1 0 0 0 0 0 1 0 0 1 0 0 1 0 1 0 1 0 1 1 0 0 0 0 1 0 1 1 1 1 0 0 0 1 1 0 1 0 0 3 0 0 */ #include<stdio.h> #define M 100 #define N 100 #define START 2 #define END 3 /* * a will store the maze * t will store the shortest way to exit the maze * tot is the total steps to exit the maze this time * min is the min steps to exit the maze * it is a x X y maze * flag will tell us whether you can exit the maze * */ int a[M][N]; int t[M][N]; int tot = 0 , min = 10000 , x , y , flag; void search(int m , int n){ int i , j; if((a[m][n] == 0 || a[m][n] == START )&& m >= 0 && n >= 0 && m < x && n <y){ tot ++; a[m][n] = 6; // for( i = 0 ; i < x ; i ++){ // for( j = 0 ; j < y ; j ++){ // printf("%d ",a[i][j]); // } // printf("\n"); // } // printf("\n\n"); search( m , n + 1); search( m , n - 1 ); search( m - 1 , n); search( m + 1 , n); if(a[m][n] != END) //@csk notice that END cannot be changed to another number a[m][n] = 0; tot --; } else if (a[m][n] == END){ tot++; if(min > tot){ min = tot; for( i = 0 ; i < x ; i ++){ for( j = 0 ; j < y ; j ++){ t[i][j] = a[i][j]; } } } // printf("exit\n%d steps\n",tot); // for( i = 0 ; i < x ; i ++){ // for( j = 0 ; j < y ; j ++){ // printf("%d ",a[i][j]); // } // printf("\n"); // } flag = 1; if(a[m][n] != END ) a[m][n] = 0; tot --; } } int main(){ flag = 0; printf("please enter the size of the maze\n"); scanf("%d%d", &x , &y); int i , j; int sx = 0 , sy = 0; printf("please enter the maze\n" "notice that\n" "2 stands for the start position\n" "3 stands for the end position\n" "0 stands for the road\n" "1 stands for the wall\n"); for( i = 0 ; i < x ; i ++){ for( j = 0 ; j < y ; j ++){ scanf("%d" , &a[i][j]); if( a[i][j] == START ){ sx = i; sy = j; } } } search( sx , sy ); if(flag){ printf("exit\n%d steps\n",min); for( i = 0 ; i < x ; i ++){ for( j = 0 ; j < y ; j ++){ printf("%d ",t[i][j]); } printf("\n"); } } else printf("cannot exit\n"); return 0; } /* * ʱһ * END STARTΪλã * Ҳһ * һ * ʱһ * * 뿪ܱ0 6*/ /*Լ * ӦĵԷ * ̬ʱԷּ򵥵߼ * ӡмԱȵԸõؿ * Եȱ޷е * ֻչʾ˵ǰǻһô*/
C
#include <stdio.h> int ft_recursive_power(int nb, int power); int main() { int number = 5; int power = 5; int result = ft_recursive_power(number, power); printf("%d", result); }
C
#include <stdlib.h> typedef struct node { int val; struct node * next; } node_t; node_t * head = NULL; head = malloc(sizeof(node_t)); if (head == NULL) { return 1; } head->val = 1; head->next = NULL;