language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> int main(void){ int count=0; int longest=0; int longest_n=0; int million=1000000; int n=0; million=14; million=million-1; for (longest=0;million!=1;million--){ printf("Evaluation of: %i\n",million); n=million; for (count=1;n!=1;count++){ if(n%2!=0) { n=3*n+1; } else { n=n/2; } printf(" term is %i\n",n); } printf("count is %i\n",count); if(count>longest){ longest=count; longest_n=million; } } printf("%i has %i terms\n",longest_n,longest); }
C
#include "MenuSection.h" #include <assert.h> #include <stdbool.h> #include "Window.h" #include "Renderer.h" #include "Font.h" #include "UI.h" #include "Mouse.h" #include "MenuGroup.h" #include "Menu.h" #include "Application.h" #include "World.h" typedef enum { Default = 0, Hover, Clicked } MenuSectionState; typedef enum { None = 0, File_New, File_Open, File_Save, File_Exit, } MenuSelectionEnum; // Menu u32 menu_section_state = 0; // File u32 file_number_items = 4; u32 file_menu_selection = 0; MenuSectionState fileMenuSectionState = Default; SDL_Rect file_menu_section_font_rect; SDL_Texture *file_menu_section_font_texture; // Edit u32 edit_number_items = 0; //u32 edit_menu_selection = 0; MenuSectionState editMenuSectionState = Default; SDL_Rect edit_menu_section_font_rect; SDL_Texture *edit_menu_section_font_texture; //////////////////////////////////////////////////// // File->New //u32 file_menu_new_id = File_New; SDL_Rect file_menu_new_font_rect; SDL_Texture *file_menu_new_font_texture; // File->Open //u32 file_menu_open_id = File_Open; SDL_Rect file_menu_open_font_rect; SDL_Texture *file_menu_open_font_texture; // File->Save //u32 file_menu_save_id = File_Save; SDL_Rect file_menu_save_font_rect; SDL_Texture *file_menu_save_font_texture; // File->LineSeparator1 // File->Exit //u32 file_menu_exit_id = File_Exit; SDL_Rect file_menu_exit_font_rect; SDL_Texture *file_menu_exit_font_texture; void MenuSection_Create(void) { SDL_Color color = { 0,0,0 }; // File fileMenuSectionState = Default; file_menu_section_font_texture = Font_RenderText(font_ui, "File", color); int temp_file_menu_width; int temp_file_menu_height; if (SDL_QueryTexture(file_menu_section_font_texture, NULL, NULL, &temp_file_menu_width, &temp_file_menu_height) != 0) { printf("ERROR: Could not query texture for size.\n"); exit(1); } file_menu_section_font_rect.x = 8; file_menu_section_font_rect.y = 2; file_menu_section_font_rect.w = temp_file_menu_width; file_menu_section_font_rect.h = temp_file_menu_height; // Edit editMenuSectionState = Default; edit_menu_section_font_texture = Font_RenderText(font_ui, "Edit", color); int temp_edit_menu_width; int temp_edit_menu_height; if (SDL_QueryTexture(edit_menu_section_font_texture, NULL, NULL, &temp_edit_menu_width, &temp_edit_menu_height) != 0) { printf("ERROR: Could not query texture for size.\n"); exit(1); } edit_menu_section_font_rect.x = (file_menu_section_font_rect.x + file_menu_section_font_rect.w + 8) + 8; edit_menu_section_font_rect.y = 2; edit_menu_section_font_rect.w = temp_edit_menu_width; edit_menu_section_font_rect.h = temp_edit_menu_height; /////////////////////////////////////////////////////////////////////////// // File->New file_menu_new_font_texture = Font_RenderText(font_ui, "New", color); int temp_file_menu_new_width; int temp_file_menu_new_height; if (SDL_QueryTexture(file_menu_new_font_texture, NULL, NULL, &temp_file_menu_new_width, &temp_file_menu_new_height) != 0) { printf("ERROR: Could not query texture for size.\n"); exit(1); } file_menu_new_font_rect.x = 20 + 8; file_menu_new_font_rect.y = 2 + 1*menu_height; file_menu_new_font_rect.w = temp_file_menu_new_width; file_menu_new_font_rect.h = temp_file_menu_new_height; // File->Open file_menu_open_font_texture = Font_RenderText(font_ui, "Open", color); int temp_file_menu_open_width; int temp_file_menu_open_height; if (SDL_QueryTexture(file_menu_open_font_texture, NULL, NULL, &temp_file_menu_open_width, &temp_file_menu_open_height) != 0) { printf("ERROR: Could not query texture for size.\n"); exit(1); } file_menu_open_font_rect.x = 20 + 8; file_menu_open_font_rect.y = 2 + 2 * menu_height; file_menu_open_font_rect.w = temp_file_menu_open_width; file_menu_open_font_rect.h = temp_file_menu_open_height; // File->Save file_menu_save_font_texture = Font_RenderText(font_ui, "Save", color); int temp_file_menu_save_width; int temp_file_menu_save_height; if (SDL_QueryTexture(file_menu_save_font_texture, NULL, NULL, &temp_file_menu_save_width, &temp_file_menu_save_height) != 0) { printf("ERROR: Could not query texture for size.\n"); exit(1); } file_menu_save_font_rect.x = 20 + 8; file_menu_save_font_rect.y = 2 + 3 * menu_height; file_menu_save_font_rect.w = temp_file_menu_save_width; file_menu_save_font_rect.h = temp_file_menu_save_height; // File->Exit file_menu_exit_font_texture = Font_RenderText(font_ui, "Exit", color); int temp_file_menu_exit_width; int temp_file_menu_exit_height; if (SDL_QueryTexture(file_menu_exit_font_texture, NULL, NULL, &temp_file_menu_exit_width, &temp_file_menu_exit_height) != 0) { printf("ERROR: Could not query texture for size.\n"); exit(1); } file_menu_exit_font_rect.x = 20 + 8; file_menu_exit_font_rect.y = 2 + 4 * menu_height; file_menu_exit_font_rect.w = temp_file_menu_exit_width; file_menu_exit_font_rect.h = temp_file_menu_exit_height; } void MenuSection_Destroy(void) { if (file_menu_new_font_texture != NULL) { SDL_DestroyTexture(file_menu_new_font_texture); } if (file_menu_open_font_texture != NULL) { SDL_DestroyTexture(file_menu_open_font_texture); } if (file_menu_save_font_texture != NULL) { SDL_DestroyTexture(file_menu_save_font_texture); } if (file_menu_exit_font_texture != NULL) { SDL_DestroyTexture(file_menu_exit_font_texture); } //////////////////////////////////////////////////////// if (file_menu_section_font_texture != NULL) { SDL_DestroyTexture(file_menu_section_font_texture); } if (edit_menu_section_font_texture != NULL) { SDL_DestroyTexture(edit_menu_section_font_texture); } Font_Unload(font_ui); } void MenuSection_Event(void) { bool isFileRect = (mouse_x > (u32)(file_menu_section_font_rect.x - 8) && mouse_x < (u32)(file_menu_section_font_rect.x + file_menu_section_font_rect.w + 8) && mouse_y >(u32)(file_menu_section_font_rect.y - 2) && mouse_y < (u32)(file_menu_section_font_rect.y + file_menu_section_font_rect.h + 1)); bool isEditRect = (mouse_x > (u32)(edit_menu_section_font_rect.x - 8) && mouse_x < (u32)(edit_menu_section_font_rect.x + edit_menu_section_font_rect.w + 8) && mouse_y >(u32)(edit_menu_section_font_rect.y - 2) && mouse_y < (u32)(edit_menu_section_font_rect.y + edit_menu_section_font_rect.h + 1)); bool isLeftPressed = mouse_button_left && !mouse_button_left_old; bool isLeftReleased = !mouse_button_left && mouse_button_left_old; if (!isFileRect && isLeftPressed && fileMenuSectionState == Clicked) { //printf("file_menu_selection: %d\n", file_menu_selection); switch (file_menu_selection) { case File_New: { //printf("New\n"); } break; case File_Open: { //printf("Open\n"); World_Load(WorldFilePath); } break; case File_Save: { //printf("Save\n"); World_Save(WorldFilePath); } break; case File_Exit: { //printf("Exit\n"); running = 0; } break; } } if (isFileRect) { if (isLeftReleased) { if (fileMenuSectionState == Hover) { fileMenuSectionState = Clicked; editMenuSectionState = Default; } } else { fileMenuSectionState = Hover; } } else { if (isLeftPressed && fileMenuSectionState == Clicked) { fileMenuSectionState = Default; } else if (isEditRect && fileMenuSectionState == Clicked) { fileMenuSectionState = Default; editMenuSectionState = Clicked; } } if (isEditRect) { if (isLeftReleased) { if (editMenuSectionState == Hover) { editMenuSectionState = Clicked; fileMenuSectionState = Default; } } else { editMenuSectionState = Hover; } } else { if (isLeftPressed && editMenuSectionState == Clicked) { editMenuSectionState = Default; } else if (isFileRect && editMenuSectionState == Clicked) { fileMenuSectionState = Clicked; editMenuSectionState = Default; } } if (isLeftReleased) { menu_section_state = (file_menu_selection != 0); /*|| (edit_menu_selection != 0);*/ file_menu_selection = 0; //edit_menu_selection = 0; //printf("menu_section_state: %d\n", menu_section_state); } } void MenuSection_Render(void) { assert(renderer); // File if (fileMenuSectionState == Hover) { SDL_SetRenderDrawColor(renderer, 0xAA, 0xAA, 0xAA, 0xFF); SDL_Rect rect; rect.x = file_menu_section_font_rect.x - 8; rect.y = 0; rect.w = file_menu_section_font_rect.w + 16; rect.h = file_menu_section_font_rect.h + 3; SDL_RenderFillRect(renderer, &rect); } else if (fileMenuSectionState == Clicked) { SDL_SetRenderDrawColor(renderer, 0xAA, 0xAA, 0xAA, 0xFF); SDL_Rect rectHover; rectHover.x = file_menu_section_font_rect.x - 8; rectHover.y = 0; rectHover.w = file_menu_section_font_rect.w + 16; rectHover.h = file_menu_section_font_rect.h + 3; SDL_RenderFillRect(renderer, &rectHover); SDL_Rect rect; rect.x = file_menu_section_font_rect.x - 8; rect.y = menu_height; rect.w = 100; rect.h = 2 + 4 * menu_height; MenuGroup_Render(rect); //////////////////////////////////////////////////// file_menu_selection = 0; if ((mouse_y / menu_height) > 0 && (mouse_y / menu_height) <= file_number_items) { SDL_Rect rectMenuSelect; rectMenuSelect.x = file_menu_new_font_rect.x - 20 - 8; rectMenuSelect.y = (mouse_y / menu_height)*menu_height + 1; rectMenuSelect.w = 100; rectMenuSelect.h = 2 + menu_height - 2; if (mouse_x > (u32)rectMenuSelect.x && mouse_x <= (u32)(rectMenuSelect.x + rectMenuSelect.w)) { SDL_SetRenderDrawColor(renderer, 0x67, 0x89, 0xAB, 0xFF); rectMenuSelect.x += 1; rectMenuSelect.w -= 2; SDL_RenderFillRect(renderer, &rectMenuSelect); file_menu_selection = (mouse_y / menu_height); } } //////////////////////////////////////////////////// //File->New SDL_RenderCopy(renderer, file_menu_new_font_texture, NULL, &file_menu_new_font_rect); //File->Open SDL_RenderCopy(renderer, file_menu_open_font_texture, NULL, &file_menu_open_font_rect); //File->Save SDL_RenderCopy(renderer, file_menu_save_font_texture, NULL, &file_menu_save_font_rect); //File->LineSeparator_1 SDL_RenderDrawLine(renderer, 1, 4 * menu_height, 100 - 2, 4 * menu_height); //File->Exit SDL_RenderCopy(renderer, file_menu_exit_font_texture, NULL, &file_menu_exit_font_rect); //////////////////////////////////////////////////// } SDL_RenderCopy(renderer, file_menu_section_font_texture, NULL, &file_menu_section_font_rect); // Edit if (editMenuSectionState == Hover) { SDL_SetRenderDrawColor(renderer, 0xAA, 0xAA, 0xAA, 0xFF); SDL_Rect rect; rect.x = edit_menu_section_font_rect.x - 8; rect.y = 0; rect.w = edit_menu_section_font_rect.w + 16; rect.h = edit_menu_section_font_rect.h + 3; SDL_RenderFillRect(renderer, &rect); } else if (editMenuSectionState == Clicked) { SDL_SetRenderDrawColor(renderer, 0xAA, 0xAA, 0xAA, 0xFF); SDL_Rect rectHover; rectHover.x = edit_menu_section_font_rect.x - 8; rectHover.y = 0; rectHover.w = edit_menu_section_font_rect.w + 16; rectHover.h = edit_menu_section_font_rect.h + 3; SDL_RenderFillRect(renderer, &rectHover); SDL_Rect rect; rect.x = edit_menu_section_font_rect.x - 8; rect.y = menu_height; rect.w = 100; rect.h = 2 + 4 * menu_height; MenuGroup_Render(rect); } SDL_RenderCopy(renderer, edit_menu_section_font_texture, NULL, &edit_menu_section_font_rect); }
C
/* Copyright (C) 1993 Massachusetts Institute of Technology, Cambridge, MA All rights reserved */ /* ray.c */ /* This code finds intersection points of B-spline and ray */ /* Based on Chun-Y Hu: ~chun/master/hidline/pclass/rayintersect.c */ /* arr_vec() BsplineToBezier() close_enough() deriv_sign() FilterNegative() implicitize_ray() int_number() loop_rayintersect() next_u() point_bspl() signchange_ex() solve_int() solve_u split_bspl() split_it() vec_arr() vec_neq() */ #include <stdio.h> #include <math.h> #include <malloc.h> #include "gen.h" #include "bspl.h" #include "editor.h" int loop_rayintersect(ParCurv **egeom, int nCurves, double *ray, double *point) { ParCurv **bezier; double rmin; short i, j, ni, nb; rmin = 2 * (egeom[0]->order - 1) * PRECISION; for (j=ni=0; j<nCurves; j++) { nb = BsplineToBezier(egeom[j], &bezier); for (i=0; i<nb; i++) ni += int_number(bezier[i], ray , point, rmin); for (i=0; i<nb; i++) free_egeom(bezier[i]); free_garray1((char *)bezier); } return ni; } /*-------------------------------------------------------------------*/ /* This function is to find the number of the intersection point of */ /* a ray and a piece of a b-spline. */ /*-------------------------------------------------------------------*/ int int_number(ParCurv *egeom, double *ray, double *point, double rmin) { ParCurv *kid1, *kid2; /* pointers for the two split pieces */ double implicit[3]; /* coefficients x,y,c of implicit function of ray */ double *coef, u; short i, n, nsign; coef = dbl_array1(egeom->ncontpts); implicitize_ray(point, ray, implicit); for (i=0; i<egeom->ncontpts; i++) coef[i] = implicit[0]*egeom->contpts[i]->x + implicit[1]*egeom->contpts[i]->y + implicit[2]; nsign = signchange_ex(coef, egeom->ncontpts, rmin); if (nsign == 0) { free_darray1(coef); return 0; } else if (nsign == 1 && deriv_sign(coef, egeom->ncontpts, rmin)) { u = solve_int(egeom, coef); /* record the u */ free_darray1(coef); if (FilterNegative(u, egeom, point) == 1) return 1; else return 0; } free_darray1(coef); kid1 = egeomalloc1(egeom->order, egeom->ncontpts); kid2 = egeomalloc1(egeom->order, egeom->ncontpts); /* kids have the same order and ncontpts with fathers' */ split_bspl(egeom, kid1, kid2); n = int_number(kid1, ray, point, rmin) + int_number(kid2, ray, point, rmin); free_egeom(kid1); free_egeom(kid2); return n; } /*-----------------------------------------------------*/ /* This function is to implicitize the function of ray */ /*-----------------------------------------------------*/ void implicitize_ray(double *point, double *ray, double *implicit) { implicit[0]= ray[1]; implicit[1]= -ray[0]; implicit[2]= ray[0]*point[1] - ray[1]*point[0]; } /*----------------------------------------------------*/ /* This function is to find the number of signchanges */ /*----------------------------------------------------*/ int signchange_ex(double *coeff, int ncontpts, double rmin) { short i, nsign = 0, sign, sign2; if (coeff[0] < -rmin) /* establish sign of coeff[0] */ sign = -1; else if (coeff[0] > rmin) sign = 1; else sign = 0; sign2 = sign; for (i = 1; i < ncontpts; i++) { if (coeff[i] < -rmin) sign = -1; else if (coeff[i] > rmin) sign = 1; else sign = 0; if (sign != sign2) /* keep track of changes */ nsign++; sign = sign2; } return nsign; } /*----------------------------------------------------------------------*/ /* this function is to see if there is sign change of the derivative of */ /* a bspl coefficient */ /*----------------------------------------------------------------------*/ int deriv_sign(double *coef, int ncontpts, double rmin) { double *deriv; short i, nsign; deriv = dbl_array1(ncontpts - 1 ); for (i=0; i<ncontpts-1; i++) deriv[i] = coef[i+1] - coef[i]; nsign = signchange_ex(deriv, ncontpts-1, rmin); free_darray1(deriv); if (nsign == 0) return 1; return 0; } /*------------------------------------------------------------------------*/ /* This function is to generate an imaginary b-spline curve and solve the */ /* unique solution of the polynominal */ /*------------------------------------------------------------------------*/ double solve_int(ParCurv *egeom, double *coeff) { ParCurv *sgeom; double u; short i; sgeom = egeomalloc1(egeom->order, egeom->ncontpts); for (i=0; i<egeom->kmem; i++ ) sgeom->knots[i] = egeom->knots[i]; for (i=0; i<egeom->ncontpts; i++) { sgeom->contpts[i]->x = coeff[i]; sgeom->contpts[i]->y = 0.0; sgeom->contpts[i]->z = 0.0; sgeom->contpts[i]->w = 1.0; } u = solve_u(sgeom, egeom->knots[0], egeom->knots[egeom->kmem-1]); free_egeom(sgeom); return u; } /*-------------------------------------------------------------------*/ /* This function is to solve the u value with the coefficient of the */ /* b-spline basis function */ /*-------------------------------------------------------------------*/ double solve_u(ParCurv *egeom, double start_pr, double end_pr) { double next; if (start_pr > end_pr) printf("It dosen't converge \n"); if (close_enough(point_bspl(egeom, start_pr))) return start_pr; else if (close_enough(point_bspl(egeom, end_pr))) return end_pr; else if (close_enough(point_bspl(egeom, next = next_u(egeom, start_pr)))) return next; return solve_u(egeom, next, end_pr); } /*------------------------------------------------*/ /* This function is to check if u is close enough */ /*------------------------------------------------*/ int close_enough(double f) { if (fabs(f) <= 1.0e-8) return 1; else return 0; } /*---------------------------------------------*/ /* This function is to find next approximate u */ /*---------------------------------------------*/ double next_u(ParCurv *egeom, double u) { vector *r; double next, start_knot, end_knot, x0, x1; r = evalderivbsp(egeom, u, 0); x0 = r->x; vectfree(r); r = evalderivbsp(egeom, u, 1); x1 = r->x; vectfree(r); next = u - x0/x1; if (next < (start_knot = egeom->knots[0])) return start_knot; else if (next > (end_knot = egeom->knots[egeom->kmem-1])) return end_knot; return(next); } /*-----------------------------------------------------------*/ /* This function is to compute the point of an integral bspl */ /*-----------------------------------------------------------*/ double point_bspl(ParCurv *egeom, double u) { vector *r; double pr; r = evalderivbsp(egeom, u, 0); pr = r->x; vectfree(r); return (pr); } /*--------------------------------------*/ /* Filter out values less than point[0] */ /*--------------------------------------*/ int FilterNegative(double u, ParCurv *egeom, double *point) { vector *r; double x; r = rbspeval(egeom, u, 0); x = r->x; vectfree(r); if (x - point[0] > 0.0) return 1; return 0; } /*---------------------------------------------------*/ /* This function is to split bspline into two pieces */ /*---------------------------------------------------*/ void split_bspl(ParCurv *egeom, ParCurv *kid1, ParCurv *kid2) { ParCurv *sgeom ; double ip; /* integer part */ double inserted_u; double **dadarray, **kidarray; int i, nknots; nknots = 2*egeom->order + egeom->ncontpts; modf((egeom->order + egeom->ncontpts)/2.0, &ip); /* ip is the middle point */ /* of the new knot index */ inserted_u = (egeom->knots[0] + egeom->knots[egeom->kmem-1]) / 2.0; sgeom = egeomalloc1(egeom->order, nknots - egeom->order); /* child has the same order, but egeom->order more ncontpts */ for (i=0; i<(int)ip; i++) sgeom->knots[i] = egeom->knots[i]; for (i=(int)ip; i<(int)ip + egeom->order; i++) sgeom->knots[i] = (egeom->knots[0] + egeom->knots[egeom->kmem-1]) / 2.0; /* that will add new knot in the middle point */ for (i=(short)ip + egeom->order; i<nknots; i++) sgeom->knots[i] = egeom->knots[i - egeom->order]; dadarray = dbl_array2(egeom->ncontpts, 4); kidarray = dbl_array2(egeom->ncontpts + egeom->order, 4); vec_arr(egeom->ncontpts, egeom->contpts, dadarray); curve_oslo1(egeom->order, egeom->ncontpts, nknots, egeom->knots, sgeom->knots, dadarray, kidarray); arr_vec(sgeom->ncontpts, kidarray, sgeom->contpts); free_darray2(dadarray); free_darray2(kidarray); split_it(inserted_u, sgeom, kid1, kid2); free_egeom(sgeom); } /*------------------------------------------------------*/ /* This function is to convert VECTOR to a double array */ /*------------------------------------------------------*/ void vec_arr(int ncontpts, vector **contpts, double **array) { short i; for (i=0; i<ncontpts; i++) { array[i][0] = contpts[i]->x; array[i][1] = contpts[i]->y; array[i][2] = contpts[i]->z; array[i][3] = contpts[i]->w; } } /*------------------------------------------------------*/ /* This function is to convert double array to a VECTOR */ /*------------------------------------------------------*/ void arr_vec(int ncontpts, double **array, vector **contpts) { short i; for (i=0; i<ncontpts; i++) { contpts[i]->x = array[i][0]; contpts[i]->y = array[i][1]; contpts[i]->z = array[i][2]; contpts[i]->w = array[i][3]; } } /*------------------------------------------------------------------------*/ /* This function is to split a b-spline which has been subdivided already */ /* into two pieces */ /*------------------------------------------------------------------------*/ void split_it(double u, ParCurv *father, ParCurv *kid1, ParCurv *kid2) { short i, j; int dadnk, kidnk; /* the number of kids' knot vector */ kidnk = kid1->order + kid1->ncontpts; dadnk = father->order + father->ncontpts; /* split the knot vector in the u */ for (i=j=0; father->knots[i]<=u; i++,j++) /* copy the knot vector */ kid1->knots[i] = father->knots[i]; for (i=0; i<kidnk; i++) kid2->knots[i] = father->knots[i + j - father->order]; /* split the contpts where the two consecutive contpts are the same */ for (i=j=0; vec_neq(father->contpts[i], father->contpts[i+1]); i++,j++) copyvector( father->contpts[i] , kid1->contpts[i] ); copyvector(father->contpts[j], kid1->contpts[j]); for (i=j+1; i<father->ncontpts; i++) copyvector(father->contpts[i], kid2->contpts[i-j-1]); } /*---------------------------------------------------------------*/ /* This function is to compare two vectors to see if they are != */ /*---------------------------------------------------------------*/ int vec_neq(vector *vector1, vector *vector2) { if (vector1->x == vector2->x && vector1->y == vector2->y && vector1->z == vector2->z && vector1->w == vector2->w) return 0; return 1; } /*---------------------------------------------*/ /* Decompose B-spline curve into bezier curves */ /*---------------------------------------------*/ int BsplineToBezier(ParCurv *egeom, ParCurv ***bezier) { ParCurv *egm; vector *r; double *knots, **inpoly, **outpoly, tang; int nKnots, nPts; short i, j, nb, nc, order; order = egeom->order; nc = egeom->ncontpts; nKnots = checknot(egeom); knots = dbl_array1(nKnots); prodknot(egeom, knots); inpoly = dbl_array2(nKnots, 4); outpoly = dbl_array2(nKnots, 4); for(i=0; i<nc; i++) { inpoly[i][0] = egeom->contpts[i]->x; inpoly[i][1] = egeom->contpts[i]->y; inpoly[i][2] = egeom->contpts[i]->z; inpoly[i][3] = egeom->contpts[i]->w; } curve_oslo1(egeom->order, egeom->ncontpts, nKnots, egeom->knots, knots, inpoly, outpoly); free_darray2(inpoly); nb = (nKnots-order)/order; (*bezier) = (ParCurv **)gen_array1(nb, sizeof(ParCurv *)); for (j=0; j*order < nKnots-order; j++) { (*bezier)[j] = egeomalloc1(order, order); (*bezier)[j]->order = order; (*bezier)[j]->ncontpts = order; for(i=0; i<order; i++) (*bezier)[j]->knots[i] = 0.0; for(i=order; i<2*order; i++) (*bezier)[j]->knots[i] = 1.0; for(i=0; i<(*bezier)[j]->order; i++) { (*bezier)[j]->contpts[i]->x = outpoly[i + j*order][0]; (*bezier)[j]->contpts[i]->y = outpoly[i + j*order][1]; (*bezier)[j]->contpts[i]->z = outpoly[i + j*order][2]; (*bezier)[j]->contpts[i]->w = outpoly[i + j*order][3]; } } free_darray2(outpoly); return nb; }
C
#include <stdio.h> #include <ctype.h> int getLine(char s[]); double atof(char s[]); #define MAXLINE 100 /* get line from user check for e or E get sign value get num value adjust decimal occording to sign and num values pass result to atoi() return result */ int main(){ char line[MAXLINE]; double lineValue; getLine(line); lineValue = atof(line); printf("%f\n", lineValue); return 1; } double atof(char s[]){ double val, power; int i, sign; for(i = 0; isspace(s[i]); i++) ; sign = (s[i] == '-') ? -1 : 1; if(s[i] == '+' || s[i] == '-') i++; for(val == 0.0; isdigit(s[i]); i++) val = 10.0 * val + (s[i] - '0'); if(s[i] == '.') i++; for(power = 1.0; isdigit(s[i]); i++) { val = 10.0 * val + (s[i] - '0'); power *= 10.0; } int exponentSign; int exponent; if(tolower(s[i]) == 'e') i++; if(s[i] == '-') { exponentSign = -1; i++; } else if(s[i] == '+'){ exponentSign = 1; i++; } else exponentSign = 1; exponent = (s[i] - '0'); // printf("%c %d\n", s[i-1], exponent); //Adjust power based on exponent int j; if(exponentSign == -1) { for(j = 0; j < exponent; j++){ power *= 10; } } else{ for(j = 0; j < exponent; j++){ power /= 10; } } // printf("Exponent Sign: %d\nExponent: %d\n", exponentSign, exponent); return sign * val / power; } int getLine(char s[]){ int c, i; for(i = 0; i < MAXLINE-1 && (c = getchar()) != EOF && c != '\n'; ++i) s[i] = c; if(i == 0 && c == '\n') printf("Empty line!\n"); if(c == '\n' && s[i-1] == '\t'){ s[i-1] = c; } else if(c == '\n' && s[i-1] == ' '){ s[i-1] = c; } else if(c == '\n'){ s[i] = c; ++i; } s[i] = '\0'; return i; }
C
// Copyright 2021 - 312CA Brinzan Darius-Ionut #include <stdio.h> #include <stdlib.h> #include <string.h> #include "function.h" #define MAX_STR 32 // functie pentru erori size_t out_of_bounds(size_t ind, size_t size, size_t planet){ if (ind >= size){ if (planet) printf("Planet out of bounds!\n"); else printf("Shield out of bounds!\n"); return 1; } return 0; } // functia pentru a da free planetelor void free_planet(struct planet *p){ struct shield *s = p->first_shield; do{ struct shield *tmp = s; s = s->next; free(tmp); }while(s != p->first_shield); free(p->nume); free(p); } // functia pentru a sterge planeta void delete_planet(struct galaxy *G, struct planet *p){ if (G->nr_planets == 1){ free_planet(p); G->nr_planets = 0; G->first = NULL; return; } if (G->first == p){ G->first = p->next; } p->prev->next = p->next; p->next->prev = p->prev; free_planet(p); --G->nr_planets; } // functia pentru a adauga elemente in lista noastra void add(struct galaxy *G, char *nume, size_t ind, const size_t nr_scuturi){ if (out_of_bounds(ind, G->nr_planets + 1, 1)){ free(nume); return; } // aloc shield-urile si le initializez pe toate cu valoarea 1 struct shield *first_scut = (struct shield*) malloc(sizeof(struct shield)); first_scut->val = 1; struct shield *last_scut = first_scut; for ( size_t i = 1 ; i < nr_scuturi ; ++i ){ struct shield *new_s = (struct shield*) malloc(sizeof(struct shield)); new_s->val = 1; last_scut->next = new_s; last_scut = new_s; } last_scut->next = first_scut; // aloc planeta si o initializez corespunzator struct planet *new_p = (struct planet *) malloc(sizeof(struct planet)); new_p->first_shield = first_scut; new_p->last_shield = last_scut; new_p->nr_shields = nr_scuturi; new_p->kills = 0; new_p->nume = nume; // incrementez numarul planetelor din galaxie ++G->nr_planets; printf("The planet %s has joined the galaxy.\n", nume); // conditie daca e prima planeta din galaxie if (G->nr_planets == 1){ new_p->next = new_p; new_p->prev = new_p; G->first = new_p; return; } // daca este prima planeta trebuie modificat si g->first if (ind == 0){ new_p->next = G->first; new_p->prev = G->first->prev; G->first->prev->next = new_p; G->first->prev = new_p; G->first = new_p; return; } // adauga planeta in galaxie ( o leaga la lista ) struct planet *curr = G->first->prev; while (ind){ curr = curr->next; --ind; } new_p->next = curr->next; new_p->prev = curr; curr->next->prev = new_p; curr->next = new_p; } // functia de remove a planetei din galaxie void black_hole(struct galaxy *G, size_t ind){ if (out_of_bounds(ind, G->nr_planets, 1)) return; struct planet *p = G->first; while (ind){ p = p->next; --ind; } printf("The planet %s has been eaten by the vortex.\n", p->nume); delete_planet(G, p); } // functia de upgrade a scutului planetei void upgrade_shield(const struct galaxy *G, size_t ind_p, size_t ind_s, const size_t val_upg){ if (out_of_bounds(ind_p, G->nr_planets, 1)) return; // parcurg lista de planete struct planet *p = G->first; while (ind_p){ p = p->next; --ind_p; } if (out_of_bounds(ind_s, p->nr_shields, 0)) return; // parcurg lista de shield-uri struct shield *s = p->first_shield; while (ind_s){ s = s->next; --ind_s; } // upgradez valoarea shield-ului s->val += val_upg; } // functia pentru a mari scutul planetei void expand_shield(const struct galaxy *G, size_t ind_p, size_t val_shld){ if (out_of_bounds(ind_p, G->nr_planets, 1)) return; // parcurg lista de planete struct planet *p = G->first; while (ind_p){ p = p->next; --ind_p; } // adaug un shield nou la finalul listei struct shield *new_s = (struct shield*) malloc(sizeof(struct shield)); new_s->val = val_shld; new_s->next = p->first_shield; p->last_shield->next = new_s; p->last_shield = new_s; ++p->nr_shields; } // functia de remove a scutului void remove_shield(const struct galaxy *G, size_t ind_p, size_t ind_s){ if (out_of_bounds(ind_p, G->nr_planets, 1)) return; // parcurg lista de planete struct planet *p = G->first; while (ind_p){ p = p->next; --ind_p; } if (out_of_bounds(ind_s, p->nr_shields, 0)) return; // conditie daca o planeta are mai putin de 4 shield-uri if (p->nr_shields == 4){ printf("A planet cannot have less than 4 shields!\n"); return; } // parcurg shield-urile struct shield *s = p->first_shield, *prev = p->last_shield; while (ind_s){ prev = s; s = s->next; --ind_s; } // leg vecinii intre ei prev->next = s->next; if (s == p->first_shield){ p->first_shield = p->first_shield->next; } if (s == p->last_shield){ p->last_shield = prev; } free(s); --p->nr_shields; } // functia de ciocnire a planetelor void collide(struct galaxy *G, size_t ind1, size_t ind2){ if (out_of_bounds(ind1, G->nr_planets, 1)) return; if (out_of_bounds(ind2, G->nr_planets, 1)) return; // parcurg planetele struct planet *p = G->first; while (ind1){ p = p->next; --ind1; } // initializez indicii si parcurg ambele liste int ind_s1 = p->nr_shields / 4, ind_s2 = p->next->nr_shields / 4 * 3; struct shield *s1 = p->first_shield, *s2 = p->next->first_shield; while (ind_s1){ s1 = s1->next; --ind_s1; } while (ind_s2){ s2 = s2->next; --ind_s2; } // conditii pentru fiecare caz de colision if (s1->val == 0 && s2->val){ printf("The planet %s has imploded.\n", p->nume); ++p->next->kills; delete_planet(G, p); --s2->val; } else if (s1->val && s2->val == 0){ printf("The planet %s has imploded.\n", p->next->nume); ++p->kills; delete_planet(G, p->next); --s1->val; } else if (s1->val == 0 && s2->val == 0){ printf("The planet %s has imploded.\n", p->nume); printf("The planet %s has imploded.\n", p->next->nume); delete_planet(G, p->next); delete_planet(G, p); } else { --s1->val; --s2->val; } } // functia de rotire a planetei : sens trigonometric + acelor de ceasornic void rotate(const struct galaxy *G, size_t ind, char sens, size_t nr){ if (out_of_bounds(ind, G->nr_planets, 1)) return; // parcurg lista de planete struct planet *p = G->first; while (ind){ p = p->next; --ind; } nr %= p->nr_shields; // conditii pentru rotatia in ambele sensuri if (sens == 'c'){ nr = p->nr_shields - nr; } else if (sens != 't'){ printf("Not a valid direction!\n"); return; } while (nr){ if (nr == 1){ p->last_shield = p->first_shield; } p->first_shield = p->first_shield->next; --nr; } } // functia de afisare a informatiilor despre respectiva planeta void show_info(const struct galaxy *G, const size_t indice){ if ( out_of_bounds(indice, G->nr_planets, 1)) return; struct planet *p = G->first; for ( size_t i = 0 ; i < indice ; ++i ){ p = p->next; } printf("NAME: %s\n", p->nume); if ( G->nr_planets == 1) printf("CLOSEST: none\n"); else if ( G->nr_planets == 2) printf("CLOSEST: %s\n", p->prev->nume); else printf("CLOSEST: %s and %s\n", p->prev->nume, p->next->nume); printf("SHIELDS: "); struct shield *s = p->first_shield; for ( size_t i = 0; i < p->nr_shields ; ++i ){ printf("%zu ", s->val); s = s->next; } printf("\n"); printf("KILLED: %zu\n", p->kills); } // functia care ne ajuta sa executam programul nostru void execute(struct galaxy *G, const char cmd[]){ if (!strcmp(cmd, "ADD")){ char *nume = (char *) malloc(MAX_STR); size_t ind, nr_sct; scanf("%s %zu %zu", nume, &ind, &nr_sct); add(G, nume, ind, nr_sct); } else if (!strcmp(cmd, "BLH")){ size_t ind; scanf("%zu", &ind); black_hole(G, ind); } else if (!strcmp(cmd, "UPG")){ size_t ind_p, ind_s, val_upg; scanf("%zu %zu %zu", &ind_p, &ind_s, &val_upg); upgrade_shield(G, ind_p, ind_s, val_upg); } else if (!strcmp(cmd, "EXP")){ size_t ind, val; scanf("%zu %zu", &ind, &val); expand_shield(G, ind, val); } else if (!strcmp(cmd, "RMV")){ size_t ind_p, ind_s; scanf("%zu %zu", &ind_p, &ind_s); remove_shield(G, ind_p, ind_s); } else if (!strcmp(cmd, "COL")){ size_t ind1, ind2; scanf("%zu %zu", &ind1, &ind2); collide(G, ind1, ind2); } else if (!strcmp(cmd, "ROT")){ size_t ind, nr; char sens; scanf("%zu %c %zu", &ind, &sens, &nr); rotate(G, ind, sens, nr); } else if (!strcmp(cmd, "SHW")){ size_t ind; scanf("%zu", &ind); show_info(G, ind); } } int main(void) { struct galaxy G = {0, NULL}; size_t nr_comenzi; scanf("%zu", &nr_comenzi); char cmd[4]; cmd[3] = '\0'; for (size_t i = 0; i < nr_comenzi; ++i){ scanf("%3s", cmd); execute(&G, cmd); } while (G.nr_planets){ struct planet *tmp = G.first; G.first = G.first->next; free_planet(tmp); --G.nr_planets; } return 0; }
C
#include <stdio.h> #include <stdlib.h> typedef struct node{ int value; struct node * left; struct node * right; }node; typedef node * nodePtr; int readint(void); void insert(int value, nodePtr * corrPtr); int height(nodePtr corrPtr); int max(int A, int B); int main(void){ int n_element = readint(); nodePtr root = NULL; int new_val; for(size_t i = 0; i < n_element; i++){ new_val = readint(); insert(new_val, &root); } printf("%d\n", height(root)); return 0; } int readint(void){ int num; scanf("%d", &num); return num; } int max(int A, int B){ return A > B ? A : B; } void insert(int value, nodePtr * corrPtr){ if(*corrPtr == NULL){ *corrPtr = (nodePtr) calloc(1, sizeof(node)); (*corrPtr)->value = value; return; } else { if(value < (*corrPtr)->value) insert(value, &((*corrPtr)->left)); else insert(value, &((*corrPtr)->right)); } } int height(nodePtr corrPtr){ if(corrPtr == NULL) return 0; return max(height(corrPtr->left), height(corrPtr->right)) + 1; }
C
// Eduardo Vudala Senoski GRR20195689 #include "interval.h" #include <math.h> #include <stdlib.h> #include <stdio.h> #include <string.h> void must_alloc(void* ptr, const char* desc){ if(!ptr){ fprintf(stderr, "Couldn't allocate memory for %s.", desc); exit(1); } } int is_smaller(float a, float b){ float min = fminf(a, b); if (min == a) return 1; return 0; } int is_greater(float a, float b){ float max = fmaxf(a, b); if (max == a) return 1; return 0; } void check_for_errors(Interval* inter){ if (is_greater(inter->min.f, inter->max.f)) exit(-1); if (inter->min.f == NAN || inter->max.f == NAN) exit(-1); } Interval* new_interval(char* id, float min, float max){ Interval* new = malloc(sizeof(Interval)); must_alloc(new, "new interval"); new->min.f = min; new->max.f = max; new->id = malloc(sizeof(char) * WORDSIZE); must_alloc(new->id, "new interval ID"); strcpy(new->id, id); check_for_errors(new); return new; } int name_to_index(char* name){ int index = atoi(name + 1); return index - 1; } Interval* add(char* id, Interval* A, Interval* B){ float min, max; min = A->min.f + B->min.f; max = A->max.f + B->max.f; if (min != -INFINITY) min = nextafterf(min, -FLT_MAX); if (max != INFINITY) max = nextafterf(max, FLT_MAX); return new_interval(id, min, max); } Interval* sub(char* id, Interval* A, Interval* B){ float min, max; min = A->min.f - B->max.f; max = A->max.f - B->min.f; if (min != -INFINITY) min = nextafterf(min, -FLT_MAX); if (max != INFINITY) max = nextafterf(max, FLT_MAX); return new_interval(id, min, max); } float get_min(float* v, int size){ float min = v[0]; for(int i = 1; i < size; i++) if(is_smaller(v[i], min)) min = v[i]; return min; } float get_max(float* v, int size){ float max = v[0]; for(int i = 1; i < size; i++) if(is_greater(v[i], max)) max = v[i]; return max; } Interval* mult(char* id, Interval* A, Interval* B){ float nums[4]; nums[0] = A->min.f * B->min.f; nums[1] = A->min.f * B->max.f; nums[2] = A->max.f * B->min.f; nums[3] = A->max.f * B->max.f; float min = get_min(nums, 4); float max = get_max(nums, 4); if (min != -INFINITY) min = nextafterf(min, -FLT_MAX); if (max != INFINITY) max = nextafterf(max, FLT_MAX); return new_interval(id, min, max); } Interval* divi(char* id, Interval* A, Interval* B){ float min, max; if (B->min.f == nextafterf(0.0, -FLT_MAX) || B->max.f == nextafterf(0.0, FLT_MAX)){ min = -INFINITY; max = INFINITY; } else { float nums[4]; nums[0] = A->min.f / B->max.f; nums[1] = A->min.f / B->min.f; nums[2] = A->max.f / B->max.f; nums[3] = A->max.f / B->min.f; min = get_min(nums, 4); max = get_max(nums, 4); if (min != -INFINITY) min = nextafterf(min, -FLT_MAX); if (max != INFINITY) max = nextafterf(max, FLT_MAX); } return new_interval(id, min, max); } int almost_equal(flt_or_int A, flt_or_int B){ if (A.f == -INFINITY || B.f == INFINITY) return 0; int ulp = A.i - B.i; if (abs(ulp) <= ULP_TOLERANCE) return 1; return 0; } void print_results(Interval** v, int size, int assignments){ for(int i = 0; i < size; i++) printf("%s = [%20.8e, %20.8e]\n", v[i]->id, v[i]->min.f, v[i]->max.f); printf("\nNão unitários:\n"); for(int i = assignments; i < size; i++){ if( !almost_equal(v[i]->min, v[i]->max) ){ printf("%s = [%20.8e, %20.8e]\n", v[i]->id, v[i]->min.f, v[i]->max.f); } } }
C
#include <stdio.h> #include <stdint.h> uint16_t main(char argc, char * argv[]){ int hi, mi, si, ho, mo, so, hd, md, sd; int ret, secs_i, secs_o, delta; ret = scanf("%d:%d:%d",&hi, &mi, &si); ret = scanf("%d:%d:%d",&ho, &mo, &so); if (ho < hi){ ho = ho + 24; } secs_i = hi*3600+mi*60+si; secs_o = ho*3600+mo*60+so; delta = secs_o - secs_i; hd = delta/3600; md = (delta % 3600) / 60; sd = delta % (60); if ((hd + md + sd) == 0){ hd = 24; } printf("%02d:%02d:%02d\n",hd, md, sd); return 0; }
C
#include "mta_crypt.h" #include <stdlib.h> #include <unistd.h> #include <string.h> #include <openssl/err.h> #define _GNU_SOURCE #include <openssl/evp.h> #define MTA_CRYPT_INPUT_KEY_VALIDATION(key, key_length) \ if (key == NULL){ \ return MTA_CRYPT_RET_NULL_PTR_RECEIVED; \ } \ if (key_length == 0){ \ return MTA_CRYPT_RET_KEY_ZERO_LENGTH; \ } \ if (key_length > EVP_MAX_KEY_LENGTH){ \ return MTA_CRYPT_RET_KEY_MAX_LENGTH_EXCEEDED; \ }; #define MTA_CRYPT_INPUT_DATA_VALIDATION(data, data_length) \ if (data == NULL){ \ return MTA_CRYPT_RET_NULL_PTR_RECEIVED; \ } \ if (data_length == 0){ \ return MTA_CRYPT_RET_DATA_ZERO_LENGTH; \ } \ if (data_length > EVP_MAX_KEY_LENGTH * 8){ \ return MTA_CRYPT_RET_DATA_MAX_LENGTH_EXCEEDED; \ } \ if (data_length % 8 != 0){ \ return MTA_CRYPT_RET_NOT_8_BYTE_MULTIPLICATION; \ }; #define MTA_CRYPT_NULL_VALIDATION(ptr) \ if (ptr == NULL){ \ return MTA_CRYPT_RET_NULL_PTR_RECEIVED; \ } #define MTA_CRYPT_CHECK_EVP_RET(ret, action) \ if (ret != 1){ \ action; \ } MTA_CRYPT_RET_STATUS MTA_encrypt(char* key, unsigned int key_length, char* plain_data, unsigned int plain_data_length, char* encrypted_data, unsigned int* encrypted_data_length) { int ret = MTA_CRYPT_RET_OK; EVP_CIPHER_CTX *ctx = 0; int len = 0; int evp_ret = 1; MTA_CRYPT_INPUT_KEY_VALIDATION(key, key_length); MTA_CRYPT_NULL_VALIDATION(plain_data); MTA_CRYPT_NULL_VALIDATION(encrypted_data); MTA_CRYPT_NULL_VALIDATION(encrypted_data_length); MTA_CRYPT_INPUT_DATA_VALIDATION(plain_data, plain_data_length); if(!(ctx = EVP_CIPHER_CTX_new())){ ret = MTA_CRYPT_RET_ERROR; goto fin; } MTA_CRYPT_CHECK_EVP_RET(EVP_EncryptInit_ex(ctx, EVP_rc2_ecb(), NULL, NULL, NULL), ret = MTA_CRYPT_RET_ERROR; goto fin); MTA_CRYPT_CHECK_EVP_RET(EVP_CIPHER_CTX_set_key_length(ctx, key_length), ret = MTA_CRYPT_RET_ERROR; goto fin); MTA_CRYPT_CHECK_EVP_RET(EVP_EncryptInit_ex(ctx, NULL, NULL, key, NULL), ret = MTA_CRYPT_RET_ERROR; goto fin); MTA_CRYPT_CHECK_EVP_RET(EVP_CIPHER_CTX_set_padding(ctx, 0), ret = MTA_CRYPT_RET_ERROR; goto fin); MTA_CRYPT_CHECK_EVP_RET(EVP_EncryptUpdate(ctx, encrypted_data, &len, plain_data, plain_data_length), ret = MTA_CRYPT_RET_ERROR; goto fin); *encrypted_data_length = len; fin: EVP_CIPHER_CTX_free(ctx); return ret; } MTA_CRYPT_RET_STATUS MTA_decrypt(char* key, unsigned int key_length, char* encrypted_data, unsigned int encrypted_data_length, char* plain_data, unsigned int* plain_data_length) { MTA_CRYPT_RET_STATUS ret = MTA_CRYPT_RET_OK; EVP_CIPHER_CTX *ctx = 0; int len = 0; int evp_ret = 1; MTA_CRYPT_INPUT_KEY_VALIDATION(key, key_length); MTA_CRYPT_NULL_VALIDATION(encrypted_data); MTA_CRYPT_NULL_VALIDATION(plain_data); MTA_CRYPT_NULL_VALIDATION(plain_data_length); if(!(ctx = EVP_CIPHER_CTX_new())){ ret = MTA_CRYPT_RET_ERROR; goto fin; } MTA_CRYPT_CHECK_EVP_RET(EVP_DecryptInit_ex(ctx, EVP_rc2_ecb(), NULL, NULL, NULL), ret = MTA_CRYPT_RET_ERROR; goto fin); MTA_CRYPT_CHECK_EVP_RET(EVP_CIPHER_CTX_set_key_length(ctx, key_length), ret = MTA_CRYPT_RET_ERROR; goto fin); MTA_CRYPT_CHECK_EVP_RET(EVP_DecryptInit_ex(ctx, NULL, NULL, key, NULL), ret = MTA_CRYPT_RET_ERROR; goto fin); MTA_CRYPT_CHECK_EVP_RET(EVP_CIPHER_CTX_set_padding(ctx, 0), ret = MTA_CRYPT_RET_ERROR; goto fin); MTA_CRYPT_CHECK_EVP_RET(EVP_DecryptUpdate(ctx, plain_data, &len, encrypted_data, encrypted_data_length), ret = MTA_CRYPT_RET_ERROR; goto fin); *plain_data_length = (unsigned int)len; fin: EVP_CIPHER_CTX_free(ctx); return ret; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_path.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: adeburea <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/08/30 11:18:41 by adeburea #+# #+# */ /* Updated: 2021/08/30 11:24:44 by adeburea ### ########.fr */ /* */ /* ************************************************************************** */ #include "pipex.h" char **get_all_paths(char **ep) { while (*ep) { if (!ft_strncmp(*ep, "PATH=", 5)) return (ft_split(&ep[0][5], ':')); ep++; } return (NULL); } char *get_right_path(char **ep, char *cmd) { int i; char **all_paths; char *temp; char *path; i = -1; all_paths = get_all_paths(ep); while (all_paths && all_paths[++i]) { temp = ft_strjoin(all_paths[i], "/"); path = ft_strjoin(temp, cmd); if (access(path, X_OK) != -1) { free(temp); ft_free_split(all_paths, NULL); return (path); } free(path); free(temp); } ft_free_split(all_paths, NULL); return (NULL); }
C
#define _POSIX_SOURCE /* * Soubor: proj2.c * Datum: 2017/4/23 * Autor: Bc. Lukas Pelanek, [email protected] * Projekt: Shell, projekt c. 2 pro predmet POS * Popis: Jednoduchy shell, ktery podporuje nasledujici funkce: <, >, & */ #include <stdlib.h> #include <ctype.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <stdio.h> #include <signal.h> #include <string.h> #include <pthread.h> #include <sys/types.h> #include <sys/wait.h> #define ARGS_BUFF_SIZE 64 #define INPUT_BUFF_SIZE 513 int errFlag; // kladne honoty -> korektni ukonceni, zaporne hodnoty -> chyba programu pthread_mutex_t mutex; pthread_cond_t condition; char input[513]; int foregroundProcessId; /* Signalizace druhemu vlaknu */ void Signalize() { pthread_mutex_lock(&mutex); pthread_cond_signal(&condition); pthread_mutex_unlock(&mutex); } /* Ceka na dokonceni druheho vlakan */ void Wait() { pthread_mutex_lock(&mutex); pthread_cond_wait(&condition, &mutex); pthread_mutex_unlock(&mutex); } /* Parsovani vstupu */ char **parseLine(char *line, int *background, char *inFile, char *outFile) { int index = 0; int bufferLength = ARGS_BUFF_SIZE; char *item; char **arguments = malloc(ARGS_BUFF_SIZE * sizeof(char*)); if (arguments == NULL) { fprintf(stderr, "Chyba pri volani malloc()\n"); exit(EXIT_FAILURE); } item = strtok(line, " \t\r\n\a"); while (item != NULL) { // zpracovani specialnich znaku if (strlen(item) == 1) { if (*item == '&' && *background <= 0) { *background = index; } else if (*item == '<') { if ((item = strtok(NULL, " \t\r\n\a")) == NULL) { inFile[0] = '\0'; } else { strcpy(inFile, item); } } else if (*item == '>') { if ((item = strtok(NULL, " \t\r\n\a")) == NULL) { outFile[0] = '\0'; } else { strcpy(outFile, item); } } arguments[index] = NULL; return arguments; } // vlozeni argumentu arguments[index] = item; index++; if (index >= bufferLength) { bufferLength += ARGS_BUFF_SIZE; if ((arguments = realloc(arguments, bufferLength * sizeof(char *))) == NULL) { fprintf(stderr, "Chyba pri volani realloc()\n"); exit(EXIT_FAILURE); } } item = strtok(NULL, " \t\r\n\a"); } arguments[index] = NULL; return arguments; } /* Hlavni telo vlakna, ktere spousti programy */ void *cmdThreadHandler() { char **args; int onBackground; char inFile[INPUT_BUFF_SIZE]; char outFile[INPUT_BUFF_SIZE]; pid_t pid; int status; int fd; while (errFlag == 0) { Wait(); onBackground = -1; inFile[0] = '\0'; outFile[0] = '\0'; // nacti parametry args = parseLine(input, &onBackground, inFile, outFile); // test zda nenastala chyba pri cteni if (errFlag != 0) { return NULL; } // spoustime pouze s argumenty po znak & if (onBackground > 0) { args[onBackground] = NULL; } pid = fork(); if (pid == 0) { // otevreni souboru pro zapis if(*outFile != '\0') { if ((fd = open(outFile, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR)) < 0) { perror("Nepodarilo se otevrit vystupni soubor"); exit(EXIT_FAILURE); } dup2(fd, 1); close(fd); } // otevreni souboru pro cteni else if (*inFile != '\0') { if ((fd = open(inFile, O_RDONLY)) < 0) { perror("Nepodarilo se otevrit vstupni soubor"); exit(EXIT_FAILURE); } dup2(fd, 0); close(fd); } // spusteni programu if (execvp(args[0], args) == -1) { perror("Chyba pri spousteni procesu"); // pokud chybu vyhodil proces na pozadi, vytisknu novy terminal if (onBackground > 0) { printf("$ "); fflush(stdout); } exit(EXIT_FAILURE); } } else if (pid < 0) { free(args); fprintf(stderr, "Chyba pri volani fork()\n"); exit(EXIT_FAILURE); } // Parent process else { // cekame na synovsky proces pokud nema bezet na popredi if (onBackground <= 0) { pthread_mutex_lock(&mutex); foregroundProcessId = pid; // bezici program na popredi id pthread_mutex_unlock(&mutex); waitpid(pid, &status, 0); // cekame na dokonceni synovskeho procesu pthread_mutex_lock(&mutex); foregroundProcessId = 0; // na popredi shell pthread_mutex_unlock(&mutex); } } free(args); // signalizujeme, ze ocekavame dalsi prikazy Signalize(); } return NULL; } /* Hlavni telo vlakna, ktere obsluhuje uzivatele */ void *readThreadHandler() { int length = 0; int ch; while (errFlag == 0) { // inicializace memset(input, 0x00, INPUT_BUFF_SIZE); printf("$ "); fflush(stdout); // nacteni vstupu a kontrola delky if ((length = read(0, input, INPUT_BUFF_SIZE)) == INPUT_BUFF_SIZE) { printf("Prilis dlouhy vstup!\n"); while ((ch = getchar()) != '\n' && ch != EOF); // vyprazdnime stdin continue; } // odradkovani if (strcmp(input, "\n") == 0) { continue; } // konec if (strcmp(input, "exit\n") == 0) { errFlag = 1; Signalize(); return NULL; } // zarazka input[INPUT_BUFF_SIZE - 1] = '\n'; // signalizuj, ze vstup je pripraven Signalize(); // Pockej na dokonceni druheho vlakna Wait(); } return NULL; } // ukonceni procesu na popredi void sigintHandler(int signum) { pthread_mutex_lock(&mutex); if (foregroundProcessId > 0) { kill(foregroundProcessId, SIGINT); } pthread_mutex_unlock(&mutex); } // tisk informace o potomku void sigchldHandler(int signum) { int retVal; pid_t pid = wait(&retVal); if (pid <= 0) { return; } // tisk informace if (WIFEXITED(retVal)) printf("Id: %d skoncil s navratovou hodnotou: %d\n$ ", pid, WEXITSTATUS(retVal)); else if (WIFSIGNALED(retVal)) printf("Id: %d ukoncen signalem: %d\n$ ", pid, WTERMSIG(retVal)); else if (WIFSTOPPED(retVal)) printf("Id: %d pozastave signalem: %d\n$ ", pid, WSTOPSIG(retVal)); else if (WIFCONTINUED(retVal)) { printf("Id: %d pokraccuje\n$ ", pid); } fflush(stdout); } int main(int argc, char **argv) { errFlag = 0; pthread_t readThread, cmdThread; struct sigaction sigint, sigchld; sigset_t set; // inicializace signalu memset(&sigint, '\0', sizeof(sigint)); memset(&sigchld, '\0', sizeof(sigchld)); // vyprazdni set sigemptyset(&set); // nastav struktury sigint.sa_handler = sigintHandler; sigint.sa_mask = set; sigint.sa_flags = 0; sigint.sa_restorer = NULL; sigchld.sa_handler = sigchldHandler; sigchld.sa_mask = set; sigchld.sa_flags = 0; sigchld.sa_restorer = NULL; // registruj signaly sigaction(SIGINT, &sigint, NULL); sigaction(SIGCHLD, &sigchld, NULL); // inicializce vlaken pthread_mutex_init(&mutex, NULL); pthread_cond_init(&condition, NULL); // vytvoreni vlaken pthread_create(&readThread, NULL, readThreadHandler, NULL); pthread_create(&cmdThread, NULL, cmdThreadHandler, NULL); // cekani na dokonceni vlaken pthread_join(readThread, NULL); pthread_join(cmdThread, NULL); // uvolneni pthread_mutex_destroy(&mutex); pthread_cond_destroy(&condition); return 0; }
C
/////queue using link list insertion and deletion #include<stdio.h> #include<stdlib.h> typedef struct st{ int i; struct st *next; }st; void insert(st **); void delete(st **); void display(st *); main() { st *hptr=0; int op; while(1) { printf("Enter option.\n 1)insert\t2)delete\t3)display\t4)exit\n"); scanf("%d",&op); switch(op) { case 1:insert(&hptr);break; case 2:delete(&hptr);break; case 3:display(hptr);break; case 4:return; default:return; } } } void display(st *ptr) { if(ptr==NULL) { printf("stack is empty\n"); return; } while(ptr) { printf("%d ",ptr->i); ptr=ptr->next; } } void insert(st**ptr) { st *new=malloc(sizeof(st)); printf("Enter the data::"); scanf("%d",&new->i); new->next=*ptr; *ptr=new; } void delete(st**ptr) { st*temp=*ptr,*t; if(*ptr==NULL) { printf("stack is underflow\n"); return; } if((*ptr)->next==NULL) *ptr=0; else { while(temp->next) { t=temp; temp=temp->next; } t->next=temp->next; } printf("%d is delete..\n",temp->i); free(temp); temp=NULL; }
C
#include "graph.h" AdjListNode *new_adj_list_node(int destination) { AdjListNode *new_node = malloc(sizeof(AdjListNode)); if (new_node == NULL) { log_error("new_adj_list_node()", MALLOC_ERR); return NULL; } new_node->destination = destination; new_node->next = NULL; return new_node; } Graph *create_graph(int vertices) { Graph *new_graph = malloc(sizeof(Graph)); if (new_graph == NULL) { log_error("create_graph()", MALLOC_ERR); return NULL; } new_graph->vertices = vertices; new_graph->vertex_array = malloc(sizeof(AdjList) * vertices); if (new_graph->vertex_array == NULL) { log_error("create_graph()", MALLOC_ERR); return NULL; } for (int i = 0; i < vertices; ++i) // ++i because of performance gain { new_graph->vertex_array[i].head = NULL; new_graph->vertex_array[i].adj_count = 0; } return new_graph; } void add_edge(Graph *graph, int from, int to) { if (graph == NULL) { log_error("add_edge()", NULL_OBJECT_ERR); return; } AdjListNode *new_node = new_adj_list_node(to); if (new_node == NULL) { log_error("add_edge()", NULL_OBJECT_ERR); return; } new_node->next = graph->vertex_array[from].head; // Add linked list at 'from' to new_node graph->vertex_array[from].head = new_node; // Then change linked list at 'from' to new_node's linked list graph->vertex_array[from].adj_count++; // Do the same for backwards new_node = new_adj_list_node(from); if (new_node == NULL) { log_error("add_edge()", NULL_OBJECT_ERR); return; } new_node->next = graph->vertex_array[to].head; graph->vertex_array[to].head = new_node; graph->vertex_array[to].adj_count++; } void print_graph(Graph *graph) { int vertex_index; for (vertex_index = 0; vertex_index < graph->vertices; ++vertex_index) { AdjListNode *cursor = graph->vertex_array[vertex_index].head; printf("\n%d ) ->", vertex_index); while (cursor != NULL) { printf("%d ->", cursor->destination); cursor = cursor->next; } printf("\n"); } } Graph *matrix_to_graph(AdjMatrixNode **matrix, int node_count) { Graph *new_graph = create_graph(node_count); for (size_t i = 0; i < node_count; ++i) for (size_t j = i; j < node_count; ++j) if (matrix[i][j].distance > 0) add_edge(new_graph, i, j); return new_graph; } //◤━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━◥ // ADJ MATRIX FUNCTIONS //◣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━◢ AdjMatrixNode **create_adj_matrix(int node_count) { AdjMatrixNode **new_matrix = malloc(sizeof(AdjMatrixNode*) * node_count); for (int i = 0; i < node_count; i++) { new_matrix[i] = malloc(sizeof(AdjMatrixNode) * node_count); for (int j = 0; j < node_count; j++) { new_matrix[i][j].distance = NO_CONNECTION; } } return new_matrix; } AdjMatrixNode **add_connection(AdjMatrixNode **matrix, int node_count, int from, int to, float distance) { if (from > node_count || to > node_count) { printf("Node does not exist"); return matrix; } matrix[from][to].distance = distance; } AdjMatrixNode **remove_connection(AdjMatrixNode **matrix, int node_count, int from, int to) { if (from > node_count || to > node_count) { printf("Node does not exist"); return matrix; } matrix[from][to].distance = NO_CONNECTION; } AdjMatrixNode **create_matrix_from_data(char *filename) { int node_count = line_counter(filename) - 1/* First line of the csv */; Sensor_Data *s_data = read_data(filename); if (s_data == NULL) { log_error("create_matrix_from_data()", NULL_OBJECT_ERR); return NULL; } AdjMatrixNode **new_matrix = create_adj_matrix(node_count); float distance; for (size_t i = 0; i < node_count; ++i) for (size_t j = 0; j < node_count; ++j) new_matrix[i][j].distance = is_connected(s_data[i], s_data[j], MAX_DIST); return new_matrix; } //◤━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━◥ // FILE STREAM FUNCTIONS //◣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━◢ // Unfortunately this function only works for my specific type of csv Sensor_Data *read_data(char *filename) { unsigned int l_count = line_counter(filename); Sensor_Data *data_list = malloc(sizeof(Sensor_Data) * (l_count - 1)); FILE *file_pointer; file_pointer = fopen(filename, "r"); if (file_pointer == NULL) { printf("Could not open the file %s!", filename); return 0; } char line[L_MAX]; int i = 0; // Discard first line for now fgets(line, L_MAX, file_pointer); while (fgets(line, L_MAX, file_pointer) != NULL) { //printf("%s\n", line); sscanf(line, "%d,%f,%f,%f\n", &data_list[i].index, &data_list[i].x, &data_list[i].y, &data_list[i].z); ++i; } fclose(file_pointer); return data_list; } unsigned int line_counter(char *filename) { FILE *file_pointer; file_pointer = fopen(filename, "r"); if (file_pointer == NULL) { printf("Could not open the file %s!", filename); return 0; } char c; unsigned int l_count = 0; for (c = getc(file_pointer); c != EOF; c = getc(file_pointer)) if (c == '\n') ++l_count; fclose(file_pointer); return l_count; } //◤━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━◥ // SENSOR DATA FUNCTIONS //◣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━◢ float get_distance(Sensor_Data point1, Sensor_Data point2) { return sqrtf(powf(point1.x - point2.x, 2) + powf(point1.y - point2.y, 2) + powf(point1.z - point2.z, 2)); } float is_connected(Sensor_Data point1, Sensor_Data point2, float max) { int distance = get_distance(point1, point2); if (distance <= max) return distance; else return 0; } //◤━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━◥ // ERROR LOGGING FUNCTIONS //◣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━◢ void log_error(char* function_name, ErrorType error_t) { fprintf(stderr, "ERROR: %s at function '%s' at line %d in file %s\n", error_type(error_t), function_name, __LINE__, __FILE__); } char* error_type(ErrorType error_t) { switch (error_t) { case MALLOC_ERR: return "MALLOC ERROR"; case NULL_OBJECT_ERR: return "NULL OBJECT ERROR"; case FILE_READ_ERR: return "FILE READ ERROR"; default: return "UNKNOWN ERROR"; } }
C
#include <linux/module.h> #include <linux/init.h> #include <linux/fs.h> #include <linux/kernel.h> #include <linux/uaccess.h> #include <linux/slab.h> MODULE_LICENSE("GPL"); MODULE_AUTHOR("wzr"); MODULE_DESCRIPTION("my second linux driver bufio"); MODULE_VERSION("v1.0"); #define BUFIO_MAJOR 225 #define BUF_SIZE 64 /* 4 user */ static char *buf; static int rp, wp; /* open */ static int bufio_open(struct inode *inode, struct file *file) { printk(KERN_ALERT "my bufio driver open()\n"); rp = 0, wp = 0; return 0; } /* read */ static ssize_t bufio_read(struct file *h_file, char *h_buf, size_t h_count, loff_t *h_offset) { int h_size; if (rp + h_count >= BUF_SIZE) h_size = BUF_SIZE - rp; else h_size = h_count; printk(KERN_ALERT "rp = %d, h_count = %d\n", rp, h_count); int h_re = copy_to_user(h_buf, buf + rp, h_size); printk(KERN_ALERT "read: buf = %s, h_size = %d\n", buf, h_size); rp += h_count; return h_size; } /* write */ static ssize_t bufio_write(struct file *h_file, const char *h_buf, size_t h_count, loff_t *h_offset) { int h_size; if (wp + h_count >= BUF_SIZE) h_size = BUF_SIZE - wp; else h_size = h_count; printk(KERN_ALERT "wp = %d, h_count = %d\n", wp, h_count); int h_re = copy_from_user(buf + wp, h_buf, h_size); printk(KERN_ALERT "write: buf = %s, h_size = %d\n", buf, h_size); wp += h_count; return h_size; } /* init struct file_operations */ static struct file_operations bufio_fops = { .owner = THIS_MODULE, .open = bufio_open, .read = bufio_read, .write = bufio_write}; /* init */ static int bufio_init(void) { int r = register_chrdev(BUFIO_MAJOR, "bufio_driver", &bufio_fops); if (r < 0) { printk("fail to register\n"); return r; } buf = kmalloc(BUF_SIZE, GFP_KERNEL); printk(KERN_ALERT "bufio driver init success\n"); return 0; } /* exit */ static void bufio_exit(void) { unregister_chrdev(BUFIO_MAJOR, "bufio_driver"); kfree(buf); printk(KERN_ALERT "bufio_exit !\n"); } module_init(bufio_init); module_exit(bufio_exit);
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef size_t int32 ; /* Variables and functions */ scalar_t__ AM_DEPTH ; size_t AM_PG_WIDTH ; double DB_STEP ; double PI ; double PM_PG_WIDTH ; size_t* amtable ; double sin (double) ; __attribute__((used)) static void makeAmTable(void) { int32 i; for (i = 0; i < AM_PG_WIDTH; i++) amtable[i] = (int32)((double)AM_DEPTH / 2 / DB_STEP * (1.0 + sin(2.0 * PI * i / PM_PG_WIDTH))); }
C
//------------------------------------------------------------------------------ // // File Name: Random.c // Author(s): Roland Shum // Project: MyGame // Course: CS230S19 // // Copyright 2019 DigiPen (USA) Corporation. // //------------------------------------------------------------------------------ #include "stdafx.h" #include "Random.h" //------------------------------------------------------------------------------ // Private Consts: //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Private Structures: //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Public Variables: //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Private Variables: //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Private Function Declarations: //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Public Functions: //------------------------------------------------------------------------------ // Initialize the random number generator (RNG). // You may use the example code from // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/rand. // However, if you do so, then you must cite this source within the .c file. void RandomInit() { // Seed the random generator. #if _DEBUG // Seed it with the same number all the time so its easier to debug. srand(0); #else // Seed it so that it uses the time. srand((unsigned)time(NULL)); #endif } // Generate a random number in the interval [rangeMin, rangeMax] (inclusive). // You may use the example code from // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/rand. // However, if you do so, then you must cite this source within the .c file. // Params: // rangeMin = The lowest possible number generated. // rangeMax = The highest possible number generated. // Returns: // A random number in the interval [rangeMin, rangeMax]. int RandomRange(int rangeMin, int rangeMax) { return rand() % (rangeMax + 1 - rangeMin) + rangeMin; } // Generate a random floating-point number in the interval [rangeMin, rangeMax] (inclusive). // Params: // rangeMin = The lowest possible number generated. // rangeMax = The highest possible number generated. float RandomRangeFloat(float rangeMin, float rangeMax) { return (rangeMax - rangeMin) * ((float)rand() / RAND_MAX) + rangeMin; } //------------------------------------------------------------------------------ // Private Functions: //------------------------------------------------------------------------------
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<time.h> #include<math.h> # define max_size 100000 struct node { char key[20]; char value[200]; }; int hash (char[]); void ViewList(struct node * []); void FlashCard(struct node * []); char * LowerCase(char[]); void Search(struct node *[]); /*----------Main----------*/ int main() { // file handing error check FILE *fWord, *fMeaning, *fout; fWord=fopen("/home/nihal/CodingPractice/Projects/main_word.txt", "r"); fMeaning=fopen("/home/nihal/CodingPractice/Projects/meaning.txt", "r"); if (fWord==NULL) { printf("File could not be read\n"); exit(1);} if (fMeaning==NULL) { printf("File could not be read\n"); exit(1);} char word[20]; char meaning[200]; //calculate number of words in file int num_of_words=0; while (fgets(meaning, sizeof(meaning),fMeaning)) num_of_words++; fclose(fMeaning); fMeaning=fopen("/home/nihal/CodingPractice/Projects/meaning.txt", "r"); // create hashlist int i=0; long int code; struct node *HashTable[max_size] = {0}; //table for storing key-values while (i<num_of_words) { fscanf(fWord,"%s",word); // fscanf because it reads a single word doesn't save new line fgets(meaning,sizeof(meaning),fMeaning); // fgets becasue for fscanf reads onyl until blank space code = hash(word); // obtain hash code for current word struct node * new_node = malloc(sizeof(struct node)); //define temporary new_node strcpy(new_node->key,LowerCase(word)); strcpy(new_node->value,LowerCase(meaning)); HashTable[code] = new_node; // assign new_node at the code position in HashTable i++; } int flag=0; while(1) { int option=0; printf("Hit 1.View List 2.Flash Card Mode 3. Search a word\n"); scanf("%d",&option); switch(option) { case 1: ViewList(HashTable);break; case 2: FlashCard(HashTable);break; case 3: Search(HashTable); break; default: printf("Invalid Option Try Again\n");break; } printf("To exit the application press 0 or press 9 to continue\n"); scanf("%d",&flag); if(flag == 0) break; else continue; } printf("Good Bye. All the best for GRE. P.S. Propriety software of Nihal and Yash Co.\n"); } /*----------Functions----------*/ int hash(char str[]) { int primes[]={2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71}; int length=strlen(str); int i=0; int code=0; while (i<length) { code = code + (str[i]-64)*primes[i]; i++; } return code; } void ViewList(struct node * HashTable[]) { long int i=0, count=0; for (;i<max_size; i++) { if (HashTable[i]==NULL) continue; else { printf("%s : %s", HashTable[i]->key, HashTable[i]->value); count++; } } } void FlashCard(struct node * HashTable[]) { printf("Welcome to the FlashCard mode! You will view a random word from the list. Try to guess its meaning.\n"); srand(time(0)); int input=0; int score=0; int answer=0,r; int exit=0; while(1) { while(1) { r = rand() % (max_size+1); if (HashTable[r] != NULL) break; } printf("Your word is: %s\nPress any key [0-9] to see its meaning.\n", HashTable[r]->key); scanf("%d",&input); if (input >= 0 || input <= 9) printf("The meaning is: %s\nDid you guess right? Press 0 for wrong answer 1 for right answer\n", HashTable[r]->value); scanf("%d",&answer); score = score + answer; printf("Your Score is: %d\nPress 4 to exit or 9 to continue\n",score); scanf("%d", &exit); if(exit == 4) break; else continue; } printf("Your total score is %d. Thank You for using Flash Card mode :)\n", score); }// end of FlashCard mode char * LowerCase(char str[]) { for(int i = 0; str[i]; i++) { str[i] = tolower(str[i]); } return str; } void Search(struct node * HashTable[]) { char word[20]; printf("Enter a word you want to search in the list: \n"); scanf("%s", word); int new_code=hash(word); if (HashTable[new_code]==NULL) printf("Sorry, the word is not present in the list\n"); else printf("Meaning is: %s", HashTable[new_code]->value); }
C
#include "holberton.h" /** * aux1 - This program will print using _putchar function * @s: array * @a: array * Description: prints Holberton using the function * Return: s * */ int aux1(char *s, int a) { if (*s == 0) { return (a); } if (*s != 0) { return (aux1(++s, ++a)); } return (0); } /** * aux2 - This program will print using _putchar function * @s: array * @b: array * @c: array * @d: array * Description: prints Holberton using the function * Return: s * */ int aux2(char *s, int b, int c, int d) { char *e; if (c <= (b / 2)) { e = s + (d - c); if (*s == *e) { return (aux2(++s, b, ++c, --d)); } else { return (0); } } return (1); } /** * is_palindrome - This program will print using _putchar function * @s: array * Description: prints Holberton using the function * Return: s * */ int is_palindrome(char *s) { int a = 0, b, c = 1, d; b = aux1(s, a); d = b; c = aux2(s, b, c, d); return (c); }
C
#include <pthread.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <ctype.h> #include <semaphore.h> int main (int argc, char *argv[]) { // Cogemos los parámetros de entrada if (argc != 4) printf("Por favor, indique el tipo de proceso y los dos semáforos.\n"); int tipo = atoi(argv[1]); sem_t semH = atoi(argv[2]); sem_t semP = atoi(argv[3]); // Mensaje de bienvenida switch (tipo) { case 1: printf("Soy un proceso de pagos, y acabo de ser creado.\n"); break; case 2: printf("Soy un proceso de anulaciones, y acabo de ser creado.\n"); break; case 3: printf("Soy un proceso de pre-reservas, y acabo de ser creado.\n"); break; case 4: printf("Soy un proceso de gradas, y acabo de ser creado.\n"); break; case 5: printf("Soy un proceso de eventos, y acabo de ser creado.\n"); break; default: printf("Soy un proceso desconocido ...\n"); break; } // Esperamos a que el padre nos de permiso (Inicio S.C) sem_wait(semH); // Imprimimos mensaje de S.C. switch (tipo) { case 1: printf("Soy un proceso de pagos, y estoy en mi sección crítica.\n"); break; case 2: printf("Soy un proceso de anulaciones, y estoy en mi sección crítica.\n"); break; case 3: printf("Soy un proceso de pre-reservas, y estoy en mi sección crítica.\n"); break; case 4: printf("Soy un proceso de gradas, y estoy en mi sección crítica.\n"); break; case 5: printf("Soy un proceso de eventos, y estoy en mi sección crítica.\n"); break; default: printf("Soy un proceso desconocido ...\n"); break; } getchar(); // Simulamos hacer cosas en la sección crítica ... // Devolvemos el control al padre (Fin S.C.) sem_post(semP); // Mensaje de despedida switch (tipo) { case 1: printf("Soy un proceso de pagos, y parece que ya acabé de hacer cosas.\n"); break; case 2: printf("Soy un proceso de anulaciones, y parece que ya acabé de hacer cosas.\n"); break; case 3: printf("Soy un proceso de pre-reservas, y parece que ya acabé de hacer cosas.\n"); break; case 4: printf("Soy un proceso de gradas, y parece que ya acabé de hacer cosas.\n"); break; case 5: printf("Soy un proceso de eventos, y parece que ya acabé de hacer cosas.\n"); break; default: printf("Soy un proceso desconocido ...\n"); break; } }
C
/* * main.c * * Created: 22/08/2018 14:13:50 * Author: Nikolaus Huber * Platform: Arduino Due - Atmel SAM3X8E * * Purpose: Blinks the LED0 on the Arduino Due * */ #include <asf.h> /* include asf library*/ #include <delay.h> int main (void) { /* System clock initialization */ sysclk_init(); /* Board peripherals initialization */ board_init(); /* Initialize LED0 on Port B Pin 27*/ PIOB->PIO_PER = 1 << 27; /* Pin Enable Register (PER) */ PIOB->PIO_OER = 1 << 27; /* Output Enable Register (OER) */ PIOB->PIO_OWER = 1 << 27; /* Output Write Enable Register (OWER) */ /* Defining Morse code constants */ int dot ; /* dot is the Short symbol */ int dash ; /* dash is the long symbol */ int symbolBreaK ; /* This is the space between two morse or symbol characters */ //int wordBreak ; /* This is the space between two words in morse */ dot = 200 ; dash = 3*dot ; symbolBreaK = 2*dot ; //wordBreak = 6*dot ; void off() { if((PIOB->PIO_ODSR & (1 << 27)) > 0) { /* If pin 27 is active -> turn off via Clear Output Data Register (CODR) */ PIOB->PIO_CODR = 1 << 27; delay_ms(200); } } void on() { if((PIOB->PIO_ODSR & (1 << 27)) < 1) PIOB->PIO_SODR = 1 << 27; } void blink(int t_on) { on(); delay_ms(t_on); off(); delay_ms(200); } void symbolBreak(){ off(); delay_ms(400); } void wordBreak(){ off(); delay_ms(1400); } /* Main loop */ while(1) { //H blink(dot); blink(dot); blink(dot); blink(dot); symbolBreak(); //E blink(dot); symbolBreak(); //L blink(dot); blink(dash); blink(dot); blink(dot); symbolBreak(); //L blink(dot); blink(dash); blink(dot); blink(dot); symbolBreak(); //O blink(dash); blink(dash); blink(dash); wordBreak(); // space //W blink(dot); blink(dash); blink(dash); symbolBreak(); //O blink(dash); blink(dash); blink(dash); symbolBreak(); //R blink(dot); blink(dash); blink(dot); symbolBreak(); //L blink(dot); blink(dash); blink(dot); blink(dot); symbolBreak(); //D blink(dash); blink(dot); blink(dot); symbolBreak(); off(); delay_ms(9000); /* See if pin 27 in Output Data Status Register (ODSR) is set */ /* if((PIOB->PIO_ODSR & (1 << 27)) > 0) { /* If pin 27 is active -> turn off via Clear Output Data Register (CODR) */ /*PIOB->PIO_CODR = 1 << 27; delay_ms(200); } else { /* If pin 27 is not active -> turn off via Set Output Data Register (SODR) */ //PIOB->PIO_SODR = 1 << 27; //} } /* while(1) */ /* Should never reach here ... */ return 1; }
C
//////////////////////////////////////////////////////////////////////////////// // // Przyklad wykorzystania makr zamazujacych kod CLEAR_START i CLEAR_END // // Wersja : PELock v2.0 // Jezyk : C/C++ // Autor : Bartosz Wjcik ([email protected]) // Strona domowa : https://www.pelock.com // //////////////////////////////////////////////////////////////////////////////// #include <windows.h> #include <stdio.h> #include <conio.h> #include "pelock.h" unsigned int i = 0, j = 0; void initialize_app(void) { // kod pomiedzy makrami CLEAR_START i CLEAR_END bedzie zaszyfrowany // w zabezpieczonym pliku, po wykonaniu tego kodu, zostanie on // zamazany w pamieci, ponowna proba wykonania kodu, spowoduje // ze zostanie on ominiety (tak jakby go tam nie bylo) CLEAR_START i = 1; j = 2; CLEAR_END } int main(int argc, char *argv[]) { // inicjalizuj aplikacje initialize_app(); // kod pomiedzy markerami CRYPT_START i CRYPT_END bedzie zaszyfrowany // w zabezpieczonym pliku CRYPT_START printf("Witaj swiecie!"); CRYPT_END printf("\n\nNacisnij dowolny klawisz, aby kontynuowac . . ."); getch(); return 0; }
C
#include<stdio.h> //жһǷΪ //ʾ 1: //: 1->2 // : false //ʾ 2 : // : 1->2->2->1 // : true typedef struct ListNode { int val; struct ListNode* next; }ListNode; struct ListNode* reverseList(struct ListNode* head) { struct ListNode* prev, *cur, * next; if (head == NULL || head->next == NULL) { return head; } prev = NULL; cur = head; while (cur) { next = cur->next; cur->next = prev; prev = cur; cur = next; } return prev; } struct ListNode* isPalindrome(struct ListNode* head) { struct ListNode* fast, * slow, * rList; if (head == NULL || head->next == NULL) { return "true"; } fast = slow = head; while (fast && fast->next) { fast = fast->next->next; slow = slow->next; } rList = reverseList(slow); while (head && rList) { if (head->val != rList->val) { return "false"; } head = head->next; rList = rList->next; } return "true"; }
C
#include <stdio.h> #ifdef _WIN32 #include <fcntl.h> #include <io.h> #include "iwyu_getopt.h" #else #include <getopt.h> #endif #include "dump.h" #include "buffer.h" #define BUFFER_SIZE 2048 buffer read_all_stdin() { buffer out_data = make_buffer(); char buffer[BUFFER_SIZE]; size_t amount_read; while ((amount_read = fread(buffer, 1, BUFFER_SIZE, stdin)) > 0) { buffer_append(&out_data, buffer, amount_read); }; if (ferror(stdin)) { perror("Could not read stdin"); exit(3); } return out_data; } int main(int argc, char *argv[]) { int print_strings = 0; struct option long_options[] = { {"print-strings", no_argument, &print_strings, 1}, {NULL, 0, NULL, 0} }; while (getopt_long(argc, argv, "", long_options, NULL) != -1) {} #ifdef _WIN32 // Switch stdin to binary if (_setmode(_fileno(stdin), _O_BINARY) == -1) { perror("Could not switch stdin to binary"); exit(1); } #endif buffer b = read_all_stdin(); dump_msgpack(b, print_strings); printf("\n"); }
C
/****************************************************************************** QuickUnion.c Find: Check if p and q have the same root. Union: To merge components containing p and q, set the id of p's root to the id of q's root. ============================================== algorithm initialize union find ============================================== quick-union N N N (worst case) ============================================== *******************************************************************************/ #include <stdio.h> typedef int bool; #define TRUE 1 #define FALSE 0 #define MAX_NODES 8 int id[MAX_NODES]; void initQuickUnion(int n) { int i = 0; for(i = 0; i < n; i++) { id[i] = i; } } int root(int i) { while(i != id[i]) i = id[i]; return i; } bool connected(int p, int q) { return root(p) == root(q); } void union_join(int p, int q) { int i = root(p); int j = root(q); id[i] = j; } void display() { int i = 0; for( i = 0; i < MAX_NODES; i++) printf("%d ", id[i]); printf("\n "); } /* method find() to the union-find data type so that find(i) returns the largest element in the connected component containing i. */ int find(int p) { int ret_largest = -1; int i = p; while(i != id[i]) { i = id[i]; if(ret_largest < id[i]) ret_largest = id[i]; } return ret_largest; } int main() { int largest_number_in_con_components = -1; initQuickUnion(MAX_NODES); union_join(0, 5); union_join(5, 6); union_join(6, 1); union_join(1, 2); union_join(2, 7); display(); printf((connected(0,7) == TRUE) ? "\nConnected" : "\nNot Connected"); largest_number_in_con_components = find(7); printf("Largest Number among connected components = %d", largest_number_in_con_components); return 0; }
C
// UVa 1586:Molar mass // Author: YuanJyun Lu #include<stdio.h> #include<string.h> #define maxn 100 int main(){ int T; char s[maxn]; scanf("%d",&T); while(T--){ scanf("%s",s); int n = strlen(s), multiple = 1; double sum = 0.0; for (int i = n-1; i>=0; i--){ switch (s[i]){ case 'C': sum += 12.01 * multiple; multiple = 1; break; case 'H': sum += 1.008 * multiple; multiple = 1; break; case 'O': sum += 16.00 * multiple; multiple = 1; break; case 'N': sum += 14.01 * multiple; multiple = 1; break; default: if ((i + 1) < n && (s[i+1] - '0') >= 0 &&(s[i+1] - '0')<= 9){ multiple = (s[i] - '0') * 10 + multiple; } else { multiple = s[i] - '0'; } break; } } printf("%.3f\n",sum); } return 0; }
C
/* * Fork * * oxben <[email protected]> */ #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/wait.h> #define COUNT 1000000 #define BUF_COUNT 1024 /** * @brief In loop, write a buffer to a file, read it from starts and check data is correct. * * @param count Number of times the file must be written and read * @param indent Indentation for informative messages * * @returns 0 on success * @returns -1 on failure */ int write_read(int count, int indent) { char filename[256]; pid_t pid; int fd; pid_t wbuf[BUF_COUNT]; pid_t rbuf[BUF_COUNT]; size_t bufsize = BUF_COUNT * sizeof(pid_t); off_t offset; int i, n, rc; pid = getpid(); snprintf(filename, sizeof(filename), "/tmp/forktest.%d", pid); printf("INFO: %*s[%d] Writing %d times to %s\n", indent*6, "", pid, count, filename); fd = open(filename, O_CREAT|O_RDWR|O_TRUNC, S_IRUSR|S_IWUSR); if (fd < 0) { printf("ERROR: [%d] creat() failed, fd=%d - %s\n", pid, fd, strerror(errno)); return -1; } for (i = 0; i < BUF_COUNT; i++) { wbuf[i] = pid; } for (i = 0; i < count; i++) { n = write(fd, wbuf, bufsize); if (n != bufsize) { printf("ERROR: [%d] write() failed, n=%d\n", pid, n); rc = -1; goto out; } offset = lseek(fd, 0, SEEK_SET); if (offset < 0) { printf("ERROR: [%d] lseek() failed, offset=%ld - %s\n", pid, offset, strerror(errno)); rc = -1; goto out; } n = read(fd, rbuf, bufsize); if (n != bufsize) { printf("ERROR: [%d] read() failed, n=%d - %s\n", pid, n, strerror(errno)); rc = -1; goto out; } rc = memcmp(wbuf, rbuf, bufsize); if (rc != 0) { printf("ERROR: [%d] memcmp() failed, rc=%d\n", pid, rc); rc = -1; goto out; } } rc = 0; printf("INFO: %*s[%d] Success\n", indent*6, "", pid); out: close(fd); unlink(filename); return rc; } /** * @brief Fork child and write/read to file. * * @param childcount Number of children for the current process * @param indent Indentation for informative messages * * @returns 0 on success * @returns -1 on failure */ int procfunc(int childcount, int indent) { pid_t pid; int status; int rc; int es = -1; rc = write_read(1, indent); if (rc) { return rc; } if (childcount > 0) { pid = fork(); if (pid > 0) { /* Parent */ rc = write_read(COUNT, indent); waitpid(pid, &status, 0); if ( WIFEXITED(status) ) { es = WEXITSTATUS(status); } if (rc || es) { rc = -1; } printf("INFO: %*s[%d] Done - rc=%d\n", indent*6, "", getpid(), rc); } else { rc = procfunc(childcount - 1, indent + 1); } } else { rc = write_read(COUNT, indent); printf("INFO: %*s[%d] Done - rc=%d\n", indent*6, "", getpid(), rc); } return rc; } int main(int argc, char **argv) { int rc; int child_count; char *endptr; if (argc != 2) { printf("Usage: %s <child_count>\n", argv[0]); return 1; } child_count = strtol(argv[1], &endptr, 10); if (child_count < 0 || endptr == argv[1]) { printf("Usage: %s <child_count>\n", argv[0]); return 1; } rc = procfunc(atoi(argv[1]), 0); return (rc == 0 ? 0 : 1); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jfazakas <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/11/06 11:28:52 by jfazakas #+# #+# */ /* Updated: 2015/11/06 16:31:55 by jfazakas ### ########.fr */ /* */ /* ************************************************************************** */ #include "good_coding_practices.h" int main(int ac, char **av) { int fd; char *line; log_simple("starting program."); if (choose_and_open_database(&fd, ac, av) == -1) { log_simple("ending program. could not open database."); return (0); } if (database_is_valid(fd) == 0) { log_simple("ending program. database invalid."); return (0); } go_to_the_file_start(fd); while (get_next_line(fd, &line) > 0) { if (has_grades_over(line, 8) && is_from_county(line, "CLUJ")) print_student_name(line); } close(fd); log_simple("ending succesful program."); return (0); }
C
#include <stdio.h> long long solve(){ long long n = 600851475143LL, p = 1; while (n > 1 && ++p) while (n % p == 0) n /= p; return p; } main(){ printf("%lld\n", solve()); }
C
#include <string> #include <vector> void generateTree(std::string const &name, std::string const &dir = ".") { TFile f((dir + "/" + name + ".root").c_str(), "RECREATE"); // Create file TTree tree(name.c_str(), "Tree with basic leaf variables"); // Create tree // Leaf variables Float_t px, py, pz; Double_t random; Int_t ev; // Each variable has a separate branch tree.Branch("px",&px,"px/F"); tree.Branch("py",&py,"py/F"); tree.Branch("pz",&pz,"pz/F"); tree.Branch("random",&random,"random/D"); tree.Branch("ev",&ev,"ev/I"); // Fill tree for (Int_t i = 0; i < 10; ++i) { px = 100 + i; py = 200 + i; pz = 300 + i; random = 400 + i; ev = 500 + i; tree.Fill(); } f.Write(); f.Close(); // Write tree to file } // Simple structure to hold the data struct simple_t { Float_t px, py, pz; Int_t ev; }; simple_t simple; // An instance of the structure to generate the data void generateTreeStruct(std::string const &name, std::string const &dir = ".") { TFile f((dir + "/" + name + ".root").c_str(), "RECREATE"); // Create file TTree tree(name.c_str(), "Tree from a C structure with basic variables"); // Create tree // A single branch contains all variables tree.Branch("simple", &simple, "px/F:py/F:pz/F:ev/I"); // Fill tree for (Int_t i = 0; i < 10; ++i) { simple.px = 100 + i; simple.py = 200 + i; simple.pz = 300 + i; simple.ev = 500 + i; tree.Fill(); } f.Write(); f.Close(); // Write tree to file } // Generate trees void generateAll() { std::string const dir = "./trees"; generateTree("Tree", dir); generateTreeStruct("TreeStruct", dir); } // Run all tests: // - It is assumed that the trees are already generated (if not, call 'generateAll()') // - The test will loop through the trees and generate the selector into the // folder 'generated_selectors' (NameOfTree.h and NameOfTree.C). // - The test will also try accessing the data in the tree. However, since the newly // generated NameOfTree.C is empty, it uses a different .C file (located under // 'test_selectors/NameOfTree.C'), which has been already filled with code accessing // the data. (Regarding the header file, it needs no modification, so the newly // generated one is used.) void runSimple() { const char *dirSaved = gSystem->pwd(); // Save working directory // Loop through test trees std::vector<std::string> trees = {"Tree", "TreeStruct"}; for (std::string const &treeName : trees) { fprintf(stderr, "Testing tree %s\n", treeName.c_str()); TFile f(("./trees/" + treeName + ".root").c_str()); // Load file TTree *t = (TTree*)f.Get(treeName.c_str()); // Load tree gSystem->cd("./generated_selectors"); // Go to gen. folder t->MakeSelector(); // Generate selector gSystem->cd(".."); // Go back t->Process(("./test_selectors/" + treeName + ".C").c_str()); // Run (pre-filled) selector } gSystem->cd(dirSaved); // Restore working directory }
C
#include "ARK1Utils.h" #include <stdio.h> #include <string.h> uint64_t roundFunction(uint64_t input, uint64_t subkey) { uint64_t q, r, s = input ^ subkey, output=0; q = AFFINE(s>>32); r=AFFINE(s); MIX(q,r); output |= r & 255; output |= (q & 255) << 8; q = AFFINE(s>>40); r=AFFINE(s>>8); MIX(q,r); output |= (r & 255) << 16; output |= (q & 255) << 24; q = AFFINE(s>>48); r=AFFINE(s>>16); MIX(q,r); output |= (r & 255) << 32; output |= (q & 255) << 40; q = AFFINE(s>>56); r=AFFINE(s>>24); MIX(q,r); output |= (r & 255) << 48; output |= (q & 255) << 56; return output; /* //printf("Encrypting %016llx\n", input); input, subkey; //printf("%016llx ^ %016llx: %016llx\n", input, subkey, output); //printf("\nSplitting\n"); //for(i=0;i<8;i++) printf("%02x ", bytearr[i]); printf("\n"); //printf("\nApplying affine function\n"); input[0] = affine(input[0]); input[1] = affine(input[1]); input[2] = affine(input[2]); input[3] = affine(input[3]); input[4] = affine(input[4]); input[5] = affine(input[5]); input[6] = affine(input[6]); input[7] = affine(input[7]); //for(i=0;i<8;i++) printf("%02x ", bytearr[i]); printf("\n"); //printf("\nShuffling\n"); shuffleBytes(input, 8); //for(i=0;i<8;i++) printf("%02x ", bytearr[i]); printf("\n"); //printf("\nMixing\n"); mix(input + 0, input +1); mix(input + 2, input + 3); mix(input + 4, input + 5); mix(input + 6, input + 7); //for(i=0;i<8;i++) printf("%02x", bytearr[i]); printf("\n"); */ } /* int main(void) { uint64_t input = 0x4aa0facb6cb33eddLL; uint64_t key0 = 0x0000000000000000LL; uint64_t key1 = 0x0000000000000000LL; uint64_t subkeys[101]; generateSubkeys(key0, key1, subkeys); input ^= subkeys[100]; uint64_t result = inverseRound(input, subkey[99]); printf("%016llx\n", result); uint8_t bytes[8]; //uint8_t byte = 0x0f; split(bytes, input); //int i; printf("%016llx \n", input); uint64_t state = roundFunction(0,0xc4a6c4a6c4a6c4a6LL); printf("%016llx \n", state); printf("\nAffine\n"); printf("%02x : %02x", byte, affine(byte)); printf("\nInverse affine\n"); printf("%02x : %02x", affine(byte), inverseAffine(affine(byte))); printf("\nShuffling\n"); for(i=0;i<8;i++) printf("%02x ", bytes[i]); shuffleBytes(bytes,8); printf("\n"); for(i=0;i<8;i++) printf("%02x ", bytes[i]); printf("\nInverse shuffle:\n");py inverseShuffle(bytes,8); for(i=0;i<8;i++) printf("%02x ", bytes[i]); printf("\nMixing\n"); for(i=0;i<4;i++) { mix(bytes, 2*i, 2*i+1); printf("%02x %02x ", bytes[2*i], bytes[2*i+1]); } printf("\nInverse mixing\n"); for(i=0;i<4;i++) { inverseMix(bytes, 2*i, 2*i+1); printf("%02x %02x ", bytes[2*i], bytes[2*i+1]); } printf("\nJoining\n"); uint64_t output = join(bytes); printf("%016llx\n", output); return 0; } */
C
/* * ccarray.h * * Created on: Dec 15, 2011 * Author: vova */ #ifndef __ccarray_h__ #define __ccarray_h__ #include <inttypes.h> #include <stdlib.h> #include <string.h> #ifndef __symbian__ # include <malloc.h> #endif #ifdef __cplusplus extern "C" { #endif typedef struct { size_t capacity; size_t item_size; size_t items_count; void * items; } ccarray_t; typedef int (*cmpfunc_t)( const void * v1, const void * v2 ); static inline ccarray_t * ccarray_create( size_t capacity, size_t item_size ) { ccarray_t * c = (ccarray_t * )calloc(1, sizeof(ccarray_t)); if ( c ) { if ( !( c->items = calloc(capacity, item_size) ) ) { free(c), c = 0; } else { c->capacity = capacity; c->items_count = 0; c->item_size = item_size; } } return c; } static inline void ccarray_destroy( ccarray_t * c ) { if ( c ) { if ( c->items ) { free(c->items); } free(c); } } static inline size_t ccarray_size( const ccarray_t * c ) { return c->items_count; } static inline size_t ccarray_capacity( const ccarray_t * c ) { return c->capacity; } static inline size_t ccarray_push_back( ccarray_t * c, const void * data ) { if ( c->items_count < c->capacity ) { size_t pos = c->items_count++; memcpy((uint8_t*)c->items + pos * c->item_size, data, c->item_size); return pos; } return (size_t) ( -1 ); } static inline size_t ccarray_push_front( ccarray_t * c, const void * data ) { if ( c->items_count < c->capacity ) { memmove((uint8_t*)c->items + c->item_size, c->items, c->items_count * c->item_size); memcpy(c->items, data, c->item_size); return 0; } return (size_t) ( -1 ); } static inline size_t ccarray_insert( ccarray_t * c, size_t pos, const void * data ) { if ( c->items_count < c->capacity ) { memmove((uint8_t*)c->items + ( pos + 1 ) * c->item_size, (uint8_t*)c->items + pos * c->item_size, ( c->items_count++ - pos ) * c->item_size); memcpy((uint8_t*)c->items + pos * c->item_size, data, c->item_size); return pos; } return (size_t) ( -1 ); } static inline size_t ccarray_pop_back( ccarray_t * c, void * data ) { if ( c->items_count < 1 ) { return (size_t) ( -1 ); } memcpy(data, (uint8_t*)c->items + --c->items_count * c->item_size, c->item_size); return c->items_count; } static inline size_t ccarray_pop_front( ccarray_t * c, void * data ) { if ( c->items_count < 1 ) { return (size_t) ( -1 ); } if ( data ) { memcpy(data, c->items, c->item_size); } memcpy(c->items, (uint8_t*)c->items + c->item_size, --c->items_count * c->item_size); return c->items_count; } static inline size_t ccarray_erase( ccarray_t * c, size_t pos ) { if ( pos < c->items_count ) { memcpy((uint8_t*)c->items + pos * c->item_size, (uint8_t*)c->items + ( pos + 1 ) * c->item_size, ( --c->items_count - pos ) * c->item_size); } return c->items_count; } static inline void ccarray_clear( ccarray_t * c ) { c->items_count = 0; } static inline void * ccarray_peek( const ccarray_t * c, size_t pos ) { return ((uint8_t*)c->items) + pos * c->item_size; } static inline void * ccarray_ppeek( ccarray_t * c, size_t pos ) { return *(void **) ( (uint8_t*) c->items + pos * c->item_size ); } static inline void * ccarray_peek_end( ccarray_t * c ) { return (uint8_t*)c->items + c->items_count * c->item_size; } static inline size_t ccarray_set_size( ccarray_t * c, size_t newsize ) { return (c->items_count = newsize); } static inline size_t ccarray_find_item( ccarray_t * c, const void * value ) { size_t pos = 0; const uint8_t * begin = (uint8_t*)c->items; const uint8_t * const end = (uint8_t*)c->items + c->items_count * c->item_size; while ( begin < end && bcmp(begin, value, c->item_size) != 0 ) { begin += c->item_size, ++pos; } return pos; } static inline size_t ccarray_find( ccarray_t * c, cmpfunc_t cmp, const void * value ) { size_t pos = 0; const uint8_t * begin = (uint8_t*)c->items; const uint8_t * const end = (uint8_t*)c->items + c->items_count * c->item_size; while ( begin < end && cmp(begin, value) != 0 ) { begin += c->item_size, ++pos; } return pos; } static inline void ccarray_sort( ccarray_t * c, size_t beg, size_t end, cmpfunc_t cmp) { qsort(((uint8_t*) c->items) + beg * c->item_size, end - beg, c->item_size, cmp); } static inline size_t ccarray_lowerbound(const ccarray_t * c, size_t beg, size_t end, cmpfunc_t cmp, const void * value) { const size_t origbeg = beg; size_t len = end - beg; size_t half, mid; int rc; while ( len > 0 ) { mid = beg + ( half = len >> 1 ); rc = cmp((uint8_t*)c->items + mid * c->item_size, value); if ( rc == 0 ) { beg = mid; break; } if ( rc > 0 ) { len = half; } else { beg = mid + 1; len -= ( half + 1 ); } } while ( beg > origbeg && cmp((uint8_t*) c->items + (beg - 1) * c->item_size, value) == 0 ) { -- beg; } return beg; } static inline int ccarray_create_slots( ccarray_t ** a, ccarray_t ** apool, size_t num_slots, size_t item_size ) { if ( !( *a = ccarray_create(num_slots, item_size) ) ) { return -1; } if ( !( *apool = ccarray_create(num_slots, item_size) ) ) { ccarray_destroy(*a), *a = 0; return -1; } ( *apool )->items_count = num_slots; return 0; } static inline void ccarray_destroy_slots( ccarray_t ** a, ccarray_t ** apool ) { if ( *a ) { ccarray_destroy(*a); *a = 0; } if ( *apool ) { ccarray_destroy(*apool); *apool = 0; } } static inline int ccarray_create_pslots( ccarray_t ** aq, ccarray_t ** ap, size_t num_slots, size_t slot_size ) { size_t i, j; if ( !( *aq = ccarray_create(num_slots, sizeof(void *)) ) ) { return -1; } if ( !( *ap = ccarray_create(num_slots, sizeof(void *)) ) ) { ccarray_destroy(*aq), *aq = 0; return -1; } for ( i = 0; i < num_slots; ++i ) { void * p = calloc(1, slot_size); if ( p ) { ccarray_push_back(*ap, &p); } else { for ( j = 0; j < i; ++j ) { ccarray_pop_back(*ap, &p); free(p); } ccarray_destroy(*aq), *aq = 0; ccarray_destroy(*ap), *ap = 0; return -1; } } return 0; } static inline void ccarray_destroy_pslots( ccarray_t ** aq, ccarray_t ** ap ) { void * p = 0; if ( *aq ) { while ( ccarray_size(*aq) > 0 ) { ccarray_pop_back(*aq, &p); if ( p ) { free(p); } } ccarray_destroy(*aq), *aq = 0; } if ( *ap ) { while ( ccarray_size(*ap) > 0 ) { ccarray_pop_back(*ap, &p); if ( p ) { free(p); } } ccarray_destroy(*ap), *ap = 0; } } #ifdef __cplusplus } #endif #endif /* __ccarray_h__ */
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "stm32f10x.h" #include "usart.h" #include "i2c.h" extern char* itoa (int value, char* buffer, int base); int main(void){ SystemInit(); usart1_init(); i2c_init(); char buf[4]; uint8_t data = 0xF0; write_pcf8574(0x4e, data); for(;;) { data = read_pcf8574(0x4e); itoa(data, buf, 16); usart1_puts("pcf8574 value = 0x"); usart1_puts(buf); usart1_puts("\r\n"); } return 0; }
C
#include<stdio.h> void Euclid(int num1, int num2);//Ŭ ˰ void divisor_multiple(int num1, int num2);// Ǵ void get_gcd(int nume1, int num2);// ִ 밡ٹ void Expanded_Euclid(int num1, int num2); int main() { int num1, num2, temp; int menu; while (1) { printf("޴ ԷϽÿ(Ͻ÷ -1): \n"); printf("------------------\n"); printf("1. Ŭ ˰ ִ ϱ.\n"); printf("2. Ǵ Ǵ.\n"); printf("3. ִ ˰\n"); printf("4. Ȯ Ŭ ˰\n"); printf("------------------\n"); scanf("%d", &menu); if (menu == -1) { break; } if (menu == 1) { printf(" ԷϽÿ:"); scanf("%d %d", &num1, &num2); if (num1 < num2) { temp = num1; num1 = num2; num2 = temp; } Euclid(num1, num2); } else if (menu == 2) { printf(" ԷϽÿ:"); scanf("%d %d", &num1, &num2); if (num1 < num2) { temp = num1; num1 = num2; num2 = temp; } divisor_multiple(num1, num2); } else if (menu == 3) { printf(" ԷϽÿ:"); scanf("%d %d", &num1, &num2); if (num1 < num2) { temp = num1; num1 = num2; num2 = temp; } get_gcd(num1, num2); } else if (menu == 4) { printf(" ԷϽÿ:"); scanf("%d %d", &num1, &num2); if (num1 < num2) { temp = num1; num1 = num2; num2 = temp; } Expanded_Euclid(num1, num2); } } return 0; } void Euclid(int num1, int num2) { int modular; while (num2 != 0) { printf("%d = %d * %d + %d\n", num1, num2, num1 / num2, num1 % num2); modular = num1 % num2; num1 = num2; num2 = modular; } printf("ִ %dԴϴ.\n", num1); } void divisor_multiple(int num1, int num2) { if (num1 %num2 == 0) { printf(" 谡 ˴ϴ.\n", num1, num2); } else { printf(" 谡 ʽϴ.\n"); } } void get_gcd(int num1, int num2) { int temp; printf("(%d, %d)\n", num1, num2); while (num2 != 0) { num1 = num1 - num2; if (num1 < num2) { temp = num1; num1 = num2; num2 = temp; } printf("(%d, %d)\n", num1, num2); } printf("ִ %dԴϴ.\n", num1); } void Expanded_Euclid(int num1, int num2) { int q, r, s1 = 1, s2 = 0, s, t1 = 0, t2 = 1, t; int modular; int a, b; a = num1; b = num2; printf(" q a b r s1 s2 s t1 t2 t\n"); while (num2 != 0) { q = num1 / num2; r = num1 % num2; s = s1 - (s2 * q); t = t1 - (t2 * q); printf("%5d %5d %5d %5d %5d %5d %5d %5d %5d %5d\n", q, num1, num2, r, s1, s2, s, t1, t2, t); modular = num1 %num2; num1 = num2; num2 = modular; s1 = s2; s2 = s; t1 = t2; t2 = t; if (num2 == 0) { break; } } printf(" %5d %5d %5d %5d %5d %5d\n", num1, num2, s1, s2, t1, t2); printf("gcd(%d, %d) = %dԴϴ. s = %d t = %dԴϴ.\n", a, b, num1, s1, t1); return 0; }
C
#include<stdio.h> #include<stdlib.h> int main() { int n; printf("Enter number of elements in the array"); scanf("%d",&n); int *ptr; ptr=(int*)malloc(sizeof(int)*n); int i,j,temp; for(i=0;i<n;i++) scanf("%d",&ptr[i]); for(i=0;i<n-1;i++) { for(j=0;j<n-i-1;j++) { if(ptr[j]>ptr[j+1]) { temp=ptr[j]; ptr[j]=ptr[j+1]; ptr[j+1]=temp; } } } for(i=0;i<n;i++) printf("%d, ",ptr[i]); }
C
#include "main.h" int main(int argc, char *argv[]) { FILE *outFile; char address[MAX_SIZE]; char name[MAX_SIZE] = "psinfo-report"; proc proc_info[10]; switch(argc){ case 2: sprintf(address, "/proc/%s/status", argv[1]); load_process(address, proc_info); show_process(proc_info); break; case 1: show_error(); break; default: if (strstr(argv[1], "-l")){ for(int i=0;i<argc-2;i++){ sprintf(address, "/proc/%s/status", argv[i+2]); load_process(address, proc_info); if(proc_info->pid!=-1){ show_process(proc_info); } } }else if (strstr(argv[1], "-r")){ for(int i=0;i<argc-2;i++){ strcat(name,"-"); strcat(name,argv[i+2]); } strcat(name,".info"); outFile = fopen (name, "w" ); printf("Se esta generando el informe: %s.\n",name); for(int i=0;i<argc-2;i++){ sprintf(address, "/proc/%s/status", argv[i+2]); load_process(address, proc_info); if(proc_info->pid!=-1){ save_process(outFile,proc_info); }else{ printf("Ocurrio un error al generar el informe: %s.\n",name); remove(name); return 0; } } fclose(outFile); printf("Informe generado.\n"); }else { show_error(); } break; } return 0; };
C
#include <stdlib.h> #include <stdio.h> int main(){ float milhas, km; printf("Digite a distancia em quilometros:"); scanf("%f", &km); milhas=km/1.61; printf("A distancia em milhas eh %.1f\n", milhas); system("pause"); return(0); }
C
#include<stdio.h> #include<string.h> int main(void) { char str[30]; int i,j,temp; scanf("%s",str); j=strlen(str)-1; i=0; while(j>i) { temp=str[i]; str[i]=str[j]; str[j]=temp; i++; j--; } printf("%s",str); return 0; }
C
#include <stdio.h> int invertir(int numAInvertir){ int aux, invert = 0; while (numAInvertir > 0){ aux = numAInvertir % 10; invert = invert * 10 + aux; numAInvertir /= 10; } return invert; } void main(){ int num, original, invertido; printf("Ingrese el numero: \n"); scanf("%d", &num); original = num; invertido = invertir(num); printf("El numero dado es = %d\n", original); printf("Su inverso es = %d\n", invertido); }
C
#include<stdio.h> int array_size() { int n; printf("Enter the size of the array\n"); scanf("%d",&n); return n; } void array(int a[],int n) { int i; printf("Enter the values in the array\n"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } } void bubblesort(int a[],int n) { int temp,i,j; for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(a[i]>a[j]) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } } void result(int a[],int n) { int i; printf("The array after bubble sort is\n"); for(i=0;i<n;i++) { printf("%d\n",a[i]); } } int main() { int n; n=array_size(); int a[n]; array(a,n); bubblesort(a,n); result(a,n); return 0; }
C
// // Created by 28943 on 2019/9/4. // #include "SeqList.h" void SeqListInit(SeqList* sl,size_t capacity){//ʼ assert(sl); if(capacity == 0){ sl->_array = NULL; sl->_size = 0; sl->_capacity = 0; }else{ sl->_capacity = capacity; sl->_size = 0; sl->_array = (DataType*)malloc(sizeof(DataType) * sl->_capacity); assert(sl); } } void SeqListDestory(SeqList* sl){//ݻͷڴ assert(sl); free(sl->_array); sl->_array = NULL; sl->_capacity = 0; sl->_size = 0; printf("ɹ!\n"); } void CheckCapacity(SeqList* sl){// assert(sl); if(sl->_size == sl->_capacity){ sl->_capacity += INCREASE_SIZE;// sl->_array = (DataType*)realloc(sl->_array,sizeof(DataType) * sl->_capacity); } } void SeqListPushBack(SeqList* sl,DataType x){//β assert(sl); CheckCapacity(sl); /* sl->_array[sl->_size] = x; ++sl->_size; printf("%dӳɹ!\n",x); */ SeqListInsert(sl, sl->_size, x); } void SeqListPopBack(SeqList* sl){//βɾ assert(sl); CheckCapacity(sl); /* if(sl->_size == 0){ printf("ɾʧ,˳ûԪ!\n"); return; } --sl->_size; printf("ɾĩλԪسɹ!\n"); */ SeqListErase(sl,sl->_size); } void SeqListPushFront(SeqList* sl,DataType x){//ͷ assert(sl); CheckCapacity(sl); /* if(sl->_size == 1){ sl->_array[sl->_size - 1] = x; }else{ for (size_t i = sl->_size ; i >= 1; --i) { sl->_array[i] = sl->_array[i - 1]; } sl->_array[0] = x; } ++sl->_size; printf("%dԪλóɹ!\n",x); */ SeqListInsert(sl,0,x); } void SeqListPopFront(SeqList* sl){//ͷɾ assert(sl); CheckCapacity(sl); /* if(sl->_size == 1){ --sl->_size; printf("Ԫɾɹ!\n"); }else{ for (size_t i = 0; i < sl->_size - 1; ++i) { sl->_array[i] = sl->_array[i + 1]; } --sl->_size; printf("Ԫɾɹ!\n"); } */ SeqListErase(sl,0); } void SeqListFind(SeqList* sl,DataType x) {//ָԪ assert(sl); if (sl->_size == 0) { printf("ʧ,˳ûԪ!\n"); } int count = 0; for (size_t i = 0; i < sl->_size; ++i) { if (x == sl->_array[i]) { ++count; if (count > 1) { printf("Լ%dλ\n", i); continue; } printf("%dλڵ%dλ\n", x, i); } } if (count == 0) { printf("ʧ,˳ûиԪ!\n"); } } void SeqListInsert(SeqList* sl,size_t pos,DataType x){//ָλòԪ assert(sl); if(pos < 0||pos > sl->_size){ printf("ʧ,˴λ!\n"); return; } if(pos == 0){ sl->_array[pos] = x; }else{ for (size_t i = sl->_size ; i >= pos ; --i) { sl->_array[i] = sl->_array[i - 1]; } } sl->_array[pos] = x; ++sl->_size; if (pos == sl->_size) { printf("ɹĩβԪ!\n"); } else if (pos == 0) { printf("ɹԪ!\n"); } else { printf("ɹӵ%dԪ!\n", pos); } /* if(pos == 0){//ֱӵͷ SeqListPushFront(sl,x); }else if(pos == sl->_size){//ֱӵβ SeqListPushBack(sl,x); }else{ } */ } void SeqListErase(SeqList* sl,size_t pos) {//ɾָλԪ assert(sl); if (sl->_size == 0) { printf("ɾʧ,˳ûԪ!\n"); } if(pos < 0||pos > sl->_size){ printf("ɾʧ,˴λ!\n"); return; } for (size_t i = pos; i < sl->_size - 1; ++i) { sl->_array[i] = sl->_array[i + 1]; } --sl->_size; if (pos == sl->_size) { printf("ɹɾĩβԪ!\n"); } else if (pos == 0) { printf("ɹɾԪ!\n"); } else { printf("ɹɾ%dԪ!\n", pos); } } void SeqListRemove(SeqList* sl,DataType x){ assert(sl); if(sl->_size == 0){ printf("ɾʧ,˳ûԪ!\n"); } int count = 0; for(size_t i = 0;i < sl->_size ; ++i){ if(x == sl->_array[i]){ ++count; SeqListErase(sl,i); break; } } if(count == 0){ printf("ɾʧ,δҵָԪ!\n"); } } void SeqListModify(SeqList* sl,size_t pos,DataType x){ assert(sl); if (sl->_size == 0) { printf("޸ʧ,˳ûԪ!\n"); } if(pos < 0||pos > sl->_size){ printf("޸ʧ,˴λ!\n"); return; } int tmp = sl->_array[pos]; sl->_array[pos] = x; printf("ɹ%dԪ%d޸Ϊ%d\n",pos,tmp,sl->_array[pos]); } void SeqListPrint(SeqList* sl){ assert(sl); if(sl->_size == 0){ printf("˳Ԫ!\n"); return; } for (size_t i = 0; i <= sl->_size - 1 ; ++i) { if(i < sl->_size - 1){ printf("%d,",sl->_array[i]); continue; } printf("%d\n",sl->_array[i]); return; } } void SeqListBubbleSort(SeqList* sl){//ð assert(sl); if(sl->_size == 0){ printf("˳Ԫ!\n"); return; } size_t end = sl->_size ; while (end--) { for (size_t i = 0; i < end; ++i) { if (sl->_array[i] > sl->_array[i + 1]) { size_t tmp = sl->_array[i]; sl->_array[i] = sl->_array[i + 1]; sl->_array[i + 1] = tmp; } } } printf("ɹ!\n"); } int SeqListBinaryFind(SeqList* sl,DataType x){ assert(sl); if(sl->_size == 0){ printf("˳Ԫ!\n"); return -1; } size_t right = sl->_size - 1; size_t left = 0; size_t mid; while(left <= right) { mid = (left + right) / 2; if (sl->_array[mid] == x) { printf("ɹҵԪ%d!\n", x); return mid; }else if(sl->_array[mid] > x){ right = mid - 1; continue; }else if(sl->_array[mid] < x){ left = mid + 1; continue; } } printf("δҵ%d!\n",x); return 1; } void SeqListRemoveAll(SeqList* sl,DataType x){ assert(sl); if(sl->_size == 0){ printf("˳Ԫ!\n"); return; } size_t i = sl->_size - 1; while(i--){ if(sl->_array[i] != x){ continue; }else{ SeqListErase(sl,i); } } }
C
#include<stdio.h> int main(void) { int a, b, c, d; //INPUT printf("Enter four numbers\n"); scanf("%d%d%d%d", &a, &b, &c, &d); //If a number is greater than the remaining four, then it must be the greatest one printf("\n========================================\n"); if (a > b && a > c && a > d) { printf("the biggest of four is = %d", a); } else if (b > a && b > c && b > d) { printf("the biggest of four is = %d", b); } else if (c > a && c > b && c > d) { printf("the biggest of four is = %d", c); } else if (d > a && d > b && d > c) { printf("the biggest of four is = %d", d); } printf("\n========================================\n"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_vec_prog.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ggwin-go <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/08/06 20:21:51 by wtalea #+# #+# */ /* Updated: 2019/08/25 14:04:24 by ggwin-go ### ########.fr */ /* */ /* ************************************************************************** */ #include "hash.h" #include "utils.h" static int match(char *query, int len_query, char *name, int len_name) { int i; i = 0; if (len_query > len_name) return (0); while (i < len_query) { if (name[i] != query[i]) return (0); i++; } return (1); } static void add_vector(t_string query, t_vector *vector, t_hash *table) { t_string s; while (table) { if (match(query.s, query.len, table->name, ft_strlen(table->name))) { s = str_copy(table->name); str_addback(&s, " ", 1); vec_addback(vector, &s); } table = table->next; } } static void fill_vector(t_string query, t_vector *vector, t_hash **table) { int i; t_string s; i = 0; while (i < HASH_LEN) add_vector(query, vector, table[i++]); if (match(query.s, query.len, "./", 2)) { s = str_copy("./"); vec_addback(vector, &s); } } t_vector get_vec_prog(t_string query) { t_vector vec; extern t_hash **g_table; vec = vec_create(0, sizeof(t_string)); fill_vector(query, &vec, g_table); ft_qsort(vec.v, vec.len, vec.size, cmp_pstring); return (vec); }
C
#include <math.h> #include "nwpl_mapproj_df.h" #include "nwpl_map_earth.h" # ifndef M_PI # define M_PI 3.14159265358979323846 # endif static const double pid2 = M_PI / 2.0; static const double pid4 = M_PI / 4.0; static const double deg2rad = M_PI / 180.0; static const double rad2deg = 180.0 / M_PI; # define ITER 3 int NWP_ellipse2sphere_F(const float *elat, const float *elon, const int size, const float slat, const float slon, float *lat, float *lon) { int i; double e_ecc = nwp_get_earth_ecc(); double ecc2 = e_ecc * e_ecc; double c = sqrt(1.0 + ecc2 * pow(cos(slat * deg2rad), 4.0) / (1.0 - ecc2)); /*poption parallel */ for (i = 0; i < size; i++) { double esinelat = e_ecc * sin(elat[i] * deg2rad); lat[i] = (atan( pow(tan(elat[i] * deg2rad / 2.0 + pid4), c) * pow((1.0 - esinelat) / (1.0 + esinelat), e_ecc * c / 2.0) ) * 2.0 - pid2) * rad2deg; lon[i] = (elon[i] - slon) * c + slon; } return 0; } int NWP_sphere2ellipse_F(const float *lat, const float *lon, const int size, const float slat, const float slon, float *elat, float *elon) { double e_ecc = nwp_get_earth_ecc(); double ecc2 = e_ecc * e_ecc; double cinv = 1.0 / sqrt( 1.0 + ecc2 * pow(cos(slat * deg2rad), 4.0 ) / (1.0 - ecc2)); int i; /*poption parallel */ for (i = 0; i < size; i++) { int j; /*poption noparallel */ for (elat[i] = lat[i], j = 0; j < ITER; j++) { double esinelat = e_ecc * sin(elat[i] * deg2rad); elat[i] = (atan( pow(tan(lat[i] * deg2rad / 2.0 + pid4), cinv) * pow((1.0 - esinelat) / (1.0 + esinelat), -e_ecc / 2.0) ) * 2.0 - pid2) * rad2deg; } elon[i] = (lon[i] - slon) * cinv + slon; } return 0; } int NWP_sphere2oblique_F(const float *lat, const float *lon, const int size, const float slat, const float slon, float *olat, float *olon) { int i; double sinslat = sin(slat * deg2rad); double cosslat = cos(slat * deg2rad); /*poption parallel */ for (i = 0; i < size; i++) { double sinlat = sin(lat[i] * deg2rad); double coslat = cos(lat[i] * deg2rad); double sindlon = sin((lon[i] - slon) * deg2rad); double cosdlon = cos((lon[i] - slon) * deg2rad); olat[i] = asin( sinslat * sinlat + cosslat * coslat * cosdlon ) * rad2deg; olon[i] = atan2(coslat * sindlon , ( cosslat * sinlat - sinslat * coslat * cosdlon )) * rad2deg; } return 0; } int NWP_oblique2sphere_F(const float *olat, const float *olon, const int size, const float slat, const float slon, float *lat, float *lon) { int i; double sinslat = sin(slat * deg2rad); double cosslat = cos(slat * deg2rad); /*poption parallel */ for (i = 0; i < size; i++) { double sinolat = sin(olat[i] * deg2rad); double cosolat = cos(olat[i] * deg2rad); double sinolon = sin(olon[i] * deg2rad); double cosolon = cos(olon[i] * deg2rad); lat[i] = asin( sinslat * sinolat + cosslat * cosolat * cosolon ) * rad2deg; lon[i] = atan2(sinolon * cosolat , ( cosslat * sinolat - sinslat * cosolat * cosolon )) * rad2deg + slon; } return 0; } int NWP_sphere2lambert_F(const float *lat, const float *lon, const int size, const float slat1, const float slat2, const float slon, const float rlat, const float rlon, const float rx, const float ry, const float d, float *x, float *y) { int i; double e_re = nwp_get_earth_rad_m(); double dinv = 1.0 / d; double sign = ( slat2 >= 0.0 ) ? 1.0 : -1.0; double m1 = cos(slat1 * deg2rad); double t1 = tan(pid4 - sign * slat1 * deg2rad / 2.0); double n, af, r0, x0, y0; if( slat1 == slat2 ) { n = cos( pid2 - sign * slat1 ); af = e_re * m1 / n / pow(t1, n); } else { double m2 = cos(slat2 * deg2rad); double t2 = tan(pid4 - sign * slat2 * deg2rad / 2.0); n = log(m1 / m2) / log(t1 / t2); af = e_re * m1 / n / pow(t1, n); } r0 = af * pow(tan(pid4 - sign * rlat * deg2rad / 2.0), n); x0 = rx - r0 * sin((rlon - slon) * deg2rad * n) * dinv; y0 = ry - sign * r0 * cos((rlon - slon) * deg2rad * n) * dinv; /*poption parallel */ for (i = 0; i < size; i++) { double dlon = lon[i] - slon; double tanx = tan(fabs(90.0 - sign * lat[i]) * deg2rad * 0.5); double r; r = af * pow(tanx, n); if (dlon > 180.0){ dlon -= 360.0; } else if (dlon < -180.0){ dlon += 360.0; } x[i] = x0 + r * sin(dlon * deg2rad * n) * dinv; y[i] = y0 + sign * r * cos(dlon * deg2rad * n) * dinv; } return 0; } int NWP_lambert2sphere_F(const float *x, const float *y, const int size, const float slat1, const float slat2, const float slon, const float rlat, const float rlon, const float rx, const float ry, const float d, float *lat, float *lon) { int i; double e_re = nwp_get_earth_rad_m(); double sign = ( slat2 >= 0.0 ) ? 1.0 : -1.0; double m1 = cos(slat1 * deg2rad); double t1 = tan(pid4 - sign * slat1 * deg2rad / 2.0); double n, af, r0, x0, y0; if( slat1 == slat2 ) { n = cos( pid2 - sign * slat1 ); af = e_re * m1 / n / pow(t1, n); } else { double m2 = cos(slat2 * deg2rad); double t2 = tan(pid4 - sign * slat2 * deg2rad / 2.0); n = log(m1 / m2) / log(t1 / t2); af = e_re * m1 / n / pow(t1, n); } r0 = af * pow(tan(pid4 - sign * rlat * deg2rad / 2.0), n); x0 = rx - r0 * sin((rlon - slon) * deg2rad * n) / d; y0 = ry - sign * r0 * cos((rlon - slon) * deg2rad * n) / d; /*poption parallel */ for (i = 0; i < size; i++) { double dx = x[i] - x0; double dy = sign * ( y[i] - y0 ); lat[i] = sign * (pid2 - atan( pow(sqrt(dx * dx + dy * dy) * d / af, 1.0 / n) ) * 2.0) * rad2deg; lon[i] = (atan2(dx, dy) / n) * rad2deg + slon; if (lon[i] > 180.0) { lon[i] -= 360.0; } } return 0; } int NWP_sphere2mercator_F(const float *lat, const float *lon, const int size, const float slat, const float rlat, const float rlon, const float rx, const float ry, const float d, float *x, float *y) { int i; double e_re = nwp_get_earth_rad_m(); double dinv = 1.0 / d; double ak = e_re * cos(slat * deg2rad); double x0 = rx - ak * rlon * deg2rad * dinv; double y0 = ry + ak * log(tan(pid4 + rlat * deg2rad / 2.0)) * dinv; /*poption parallel */ for (i = 0; i < size; i++) { x[i] = x0 + ak * (lon[i] < 0.0 ? 360.0 + lon[i] : lon[i]) * deg2rad * dinv; y[i] = y0 - ak * log(tan(pid4 + lat[i] * deg2rad / 2.0)) * dinv; } return 0; } int NWP_sphere2mercator2_F(const float *lat, const float *lon, const int size, const float slat, const float rlat, const float rlon, const float rx, const float ry, const float d, float *x, float *y) { int i; double e_re = nwp_get_earth_rad_m(); double dinv = 1.0 / d; double ak = e_re * cos(slat * deg2rad); double x0 = rx - ak * rlon * deg2rad * dinv; double y0 = ry + ak * log(tan(pid4 + rlat * deg2rad / 2.0)) * dinv; /*poption parallel */ for (i = 0; i < size; i++) { x[i] = x0 + ak * lon[i] * deg2rad * dinv; y[i] = y0 - ak * log(tan(pid4 + lat[i] * deg2rad / 2.0)) * dinv; } return 0; } int NWP_mercator2sphere_F(const float *x, const float *y, const int size, const float slat, const float rlat, const float rlon, const float rx, const float ry, const float d, float *lat, float *lon) { int i; double e_re = nwp_get_earth_rad_m(); double ak = e_re * cos(slat * deg2rad); double x0 = rx - ak * rlon * deg2rad / d; double y0 = ry + ak * log(tan(pid4 + rlat * deg2rad / 2.0)) / d; /*poption parallel */ for (i = 0; i < size; i++) { lat[i] = (atan(exp((y0 - y[i]) * d / ak)) * 2.0 - pid2) * rad2deg; lon[i] = ((x[i] - x0) * d / ak) * rad2deg; if (lon[i] > 180.0) { lon[i] -= 360.0; } } return 0; } int NWP_sphere2polar_F(const float *lat, const float *lon, const int size, const float slat, const float slon, const float rlat, const float rlon, const float rx, const float ry, const float d, float *x, float *y) { int i; double e_re = nwp_get_earth_rad_m(); double dinv = 1.0 / d; double sign = ( slat >= 0.0 ) ? 1.0 : -1.0; double ak = e_re * (1.0 + sin(sign * slat * deg2rad)); double r0 = ak * tan(pid4 - sign * rlat * deg2rad / 2.0); double x0 = rx - r0 * sin((rlon - slon) * deg2rad) * dinv; double y0 = ry - sign * r0 * cos((rlon - slon) * deg2rad) * dinv; /*poption parallel */ for (i = 0; i < size; i++) { double lon360 = lon[i] < 0.0 ? 360.0 + lon[i] : lon[i]; double r = ak * tan(fabs(90.0 - sign * lat[i]) * deg2rad * 0.5); x[i] = x0 + r * sin((lon360 - slon) * deg2rad) * dinv; y[i] = y0 + sign * r * cos((lon360 - slon) * deg2rad) * dinv; } return 0; } int NWP_polar2sphere_F(const float *x, const float *y, const int size, const float slat, const float slon, const float rlat, const float rlon, const float rx, const float ry, const float d, float *lat, float *lon) { int i; double e_re = nwp_get_earth_rad_m(); double sign = ( slat >= 0.0 ) ? 1.0 : -1.0; double ak = e_re * (1.0 + sin(sign * slat * deg2rad)); double r0 = ak * tan(pid4 - sign * rlat * deg2rad / 2.0); double x0 = rx - r0 * sin((rlon - slon) * deg2rad) / d; double y0 = ry - sign * r0 * cos((rlon - slon) * deg2rad) / d; /*poption parallel */ for (i = 0; i < size; i++) { double dx = x[i] - x0; double dy = sign * ( y[i] - y0 ); lat[i] = sign * (pid2 - atan( sqrt(dx * dx + dy * dy) * d / ak ) * 2.0) * rad2deg; lon[i] = atan2(dx, dy) * rad2deg + slon; if (lon[i] > 180.0) { lon[i] -= 360.0; } } return 0; } int NWP_mf_lambert_F(const float *lat, const int size, const float slat1, const float slat2, float *mf) { int i; double m1 = cos(slat1 * deg2rad); double m2 = cos(slat2 * deg2rad); double t1 = tan(pid4 - slat1 * deg2rad / 2.0); double t2 = tan(pid4 - slat2 * deg2rad / 2.0); double n = log(m1 / m2) / log(t1 / t2); double p1 = m1 / pow(t1, n); /*poption parallel */ for(i = 0; i < size; i++) { mf[i] = p1 * pow(tan(fabs(90.0 - fabs(lat[i])) * deg2rad * 0.5), n) / cos(lat[i] * deg2rad); } return 0; } int NWP_mf_mercator_F(const float *lat, const int size, const float slat, float *mf) { int i; double cosslat = cos(slat * deg2rad); /*poption parallel */ for (i = 0; i < size; i++) { mf[i] = cosslat / cos(lat[i] * deg2rad); } return 0; } int NWP_mf_polar_F(const float *lat, const int size, const float slat, float *mf) { int i; double fabssinslat = fabs(sin(slat * deg2rad)); /*poption parallel */ for (i = 0; i < size; i++) { mf[i] = (1.0 + fabssinslat) / (1.0 + fabs(sin(lat[i] * deg2rad))); } return 0; } float NWP_sphere_distance_F(const float alat, const float alon, const float blat, const float blon) { double e_re = nwp_get_earth_rad_m(); return acos( sin(alat * deg2rad) * sin(blat * deg2rad) + cos(alat * deg2rad) * cos(blat * deg2rad) * cos((blon - alon) * deg2rad) ) * e_re; }
C
/* example code for cc65, for NES * 3 sprite objects * using neslib * Doug Fraker 2017 */ #include "neslib.h" #include "lesson24.h" #include "Sprites.c" const unsigned char TEXT[]={ "Sprites"}; const unsigned char PALETTE_BG[]={ 0x0f, 0x00, 0x10, 0x30, // black, gray, lt gray, white 0,0,0,0, 0,0,0,0, 0,0,0,0 }; const unsigned char PALETTE_SP[]={ 0x0f, 0x0f, 0x0f, 0x28, // black, black, yellow 0,0,0,0, 0,0,0,0, 0,0,0,0 }; void main (void) { // rendering is disabled at the startup // the init code set the palette brightness to // pal_bright(4); // normal // load the palette pal_bg(PALETTE_BG); pal_spr(PALETTE_SP); // use the second set of tiles for sprites bank_spr(1); // load the text // vram_adr(NTADR_A(x,y)); vram_adr(NTADR_A(7,14)); // screen is 32 x 30 tiles // this sets a start position on the BG, where to draw the text, left to right vram_write((unsigned char*)TEXT,sizeof(TEXT)); // this draws the array to the screen // this function only works with rendering off, and should come after vram_adr() // normally, I would reset the scroll position // but the next function waits till v-blank and scroll is set automatically in the nmi routine // since the RAM was blanked to 0 in init code, scroll will be x = 0, y = 0 // turn on screen ppu_on_all(); // set some initial values Y_position = 0x80; X_position = 0x88; X_position2 = 0xa0; X_position3 = 0xc0; // infinite loop while (1){ // wait till beginning of the frame ppu_wait_nmi(); // clear all sprites from buffer oam_clear(); // reset index into the buffer sprid = 0; // push a single sprite // oam_spr(unsigned char x,unsigned char y,unsigned char chrnum,unsigned char attr,unsigned char sprid); // use tile #0, palette #0 sprid = oam_spr(X_position, Y_position, 0, 0, sprid); // push a metasprite // oam_meta_spr(unsigned char x,unsigned char y,unsigned char sprid,const unsigned char *data); sprid = oam_meta_spr(X_position2, Y_position, sprid, metasprite); // and another sprid = oam_meta_spr(X_position3, Y_position, sprid, metasprite2); Y_position++; } };
C
/* * clock.c * * Created: 10/01/2020 09:34:10 PM * Author: Mohamed Farag */ # define F_CPU 1000000UL #include <avr/io.h> //#include <avr/interrupt.h> #include <util/delay.h> #include "clock.h" #include "state.h" static unsigned char Hours = 0; static unsigned char Miniutes = 0; extern void clock_Update(void) { if (Miniutes == 59 && Hours == 23) { Miniutes = 0; Hours = 0; } else if (Miniutes == 59) { Miniutes = 0; Hours++; } else { Miniutes++; } } extern void Increment(unsigned char state) { switch(state) { case Set_Hours_State: if (Hours == 23) { Hours = 0; } else { Hours++; } break; case Set_Miniutes_State: if (Miniutes == 59) { Miniutes = 0; } else { Miniutes++; } break; default: break; } } extern void Decrement(unsigned char state) { switch(state) { case Set_Hours_State: if (Hours == 0) { Hours = 23; } else { Hours--; } break; case Set_Miniutes_State: if (Miniutes == 0) { Miniutes = 59; } else { Miniutes--; } break; default: break; } } extern unsigned char clock_Get_Minutes(void) { return Miniutes; } extern unsigned char clock_Get_Hours(void) { return Hours; }
C
#include <stdio.h> int main() { int x; int i=0,j=0; int flag = 0, flagline = 0; scanf("%d", &x); x--; while (--x>=0) { if (flag==0) { //f1管x,y轴方向的运动 i++; flag = 2; flagline = 0; } if (flag == 1) { j++; flag = 2; flagline = 1; } if (flag == 2) { if (flagline == 0) { //flagline管理分方向斜上,斜下的运动 i--; j++; if (i == 0)flag = 1; } else { j--; i++; if (j == 0)flag = 0; } } } printf("the num is : %d/%d", i+1, j+1); return 0; }
C
/* ============================================================================ Name : Flyod_Warshall.c Author : Naman Mandlik (3948) Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #define MAX 20 #define INF 999 void Floyd_Warshall(int Graph[][MAX],int Closure[MAX][MAX],int n) { int Distance[MAX][MAX],i,j,k,start,end,min,pos,path[MAX]; for(i=0;i<n;i++) { for(j=0;j<n;j++) { Distance[i][j]=Graph[i][j]; } } for(i=0;i<n;i++) { for(j=0;j<n;j++) { for(k=0;k<n;k++) { if(Distance[i][k]+Distance[k][j]<Distance[i][j]) Distance[i][j]=Distance[i][k]+Distance[k][j]; if(Closure[i][j]==1 || (Closure[i][k] && Closure[k][j])) Closure[i][j]=1; } } } printf("\nFinal distance matrix is:\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) { printf("%d\t",Distance[i][j]); } printf("\n"); } printf("\nFinal closure matrix is:\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) { printf("%d\t",Closure[i][j]); } printf("\n"); } printf("\nEnter the vertices from which you want to find the shortest path:\n"); printf("\nEnter the starting vertex:"); scanf("%d",&start); printf("\nEnter the destination vertex:"); scanf("%d",&end); if(start==end) { printf("\nStart and End node are same so I am on the end node only.."); } else { path[0]=start; j=1; while(1) { min=INF; for(i=0;i<n;i++) { if(Distance[start][i]<min && i!=start) { min=Distance[start][i]; pos=i; } } if(min!=INF) { start=pos; if(start!=end) { path[j++]=pos; } else { printf("\nPath for %d to %d is:\n",path[0],end); for(k=0;k<j;k++) { printf("%d->",path[k]); } printf("%d",end); break; } } else { printf("\nPath does not exist..."); break; } } } } int main(void) { int Graph[MAX][MAX],Closure[MAX][MAX],n,i,j; printf("\nEnter the number of vertices for the graph:"); scanf("%d",&n); for(i=0;i<n;i++) { for(j=0;j<n;j++) { Closure[i][j]=0; } } printf("\nEnter the information about the graph:(Enter 999 if there is no path)\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) { printf("\nEnter the distance from vertex %d to %d:",i,j); scanf("%d",&Graph[i][j]); if(Graph[i][j]!=INF) { Closure[i][j]=1; } else { Closure[i][j]=0; } } } printf("\nInitial directed graph is:\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) { printf("%d\t",Graph[i][j]); } printf("\n"); } printf("\nInitial closure matrix is:\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) { printf("%d\t",Closure[i][j]); } printf("\n"); } Floyd_Warshall(Graph,Closure,n); return 0; }
C
//***************************************************************************** // // This is the code that gets called when the processor receives a NMI. This // simply enters an infinite loop, preserving the system state for examination // by a debugger. // //***************************************************************************** void NmiSR(void) { // // Enter an infinite loop. // while(1) { } } //***************************************************************************** // // This is the code that gets called when the processor receives a fault // interrupt. This simply enters an infinite loop, preserving the system state // for examination by a debugger. // //***************************************************************************** void FaultISR(void) { // // Enter an infinite loop. // while(1) { } } //***************************************************************************** // // This is the code that gets called when the processor receives an unexpected // interrupt. This simply enters an infinite loop, preserving the system state // for examination by a debugger. // //***************************************************************************** void IntDefaultHandler(void) { // // Go into an infinite loop. // while(1) { } }
C
/** * List the current windows */ #include "common.h" #include <inttypes.h> typedef struct _WINDOW_INFORMATIONS { HWND hwnd; LPTSTR szClass; LPTSTR szTitle; BOOL bVisible; DWORD dwProcessId; DWORD dwThreadId; HMODULE hModule; HINSTANCE hInstance; } WINDOW_INFORMATIONS; typedef struct _ENUM_WIN_INFOS_LPARAM { DWORD nCount; WINDOW_INFORMATIONS *infos; } ENUM_WIN_INFOS_LPARAM; /** * Collect information about a window into the given WINDOW_INFORMATIONS structure */ static BOOL CollectWindowInformation(HWND hwnd, WINDOW_INFORMATIONS *pInfo) { UINT cchSize, cchLen; ZeroMemory(pInfo, sizeof(*pInfo)); pInfo->hwnd = hwnd; pInfo->bVisible = IsWindowVisible(hwnd); cchSize = MAX_PATH; pInfo->szClass = HeapAlloc(GetProcessHeap(), 0, cchSize * sizeof(TCHAR)); if (!pInfo->szClass) { print_winerr(_T("HeapAlloc(szClass)")); return FALSE; } cchLen = GetClassName(hwnd, pInfo->szClass, cchSize); assert(cchLen + 1 < cchSize && pInfo->szClass[cchLen] == 0); cchSize = GetWindowTextLength(hwnd) + 2; pInfo->szTitle = HeapAlloc(GetProcessHeap(), 0, cchSize * sizeof(TCHAR)); if (!pInfo->szTitle) { print_winerr(_T("HeapAlloc(szTitle)")); HeapFree(GetProcessHeap(), 0, pInfo->szClass); return FALSE; } cchLen = GetWindowText(hwnd, pInfo->szTitle, cchSize); assert(cchLen + 1 < cchSize && pInfo->szTitle[cchLen] == 0); pInfo->dwThreadId = GetWindowThreadProcessId(hwnd, &pInfo->dwProcessId); pInfo->hModule = (HMODULE)GetClassLongPtr(hwnd, GCLP_HMODULE); pInfo->hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE); return TRUE; } static void PrintWindowInfo(const WINDOW_INFORMATIONS *pInfo) { _tprintf(_T("[%#" PRIxPTR "] %c"), (UINT_PTR)pInfo->hwnd, pInfo->bVisible ? _T('V') : _T('-')); if (pInfo->szClass) { _tprintf(_T(" (%s)"), pInfo->szClass); } if (pInfo->szTitle) { _tprintf(_T(" \"%s\""), pInfo->szTitle); } _tprintf(_T(" PID %lu TID %lu"), pInfo->dwProcessId, pInfo->dwThreadId); if (pInfo->hModule) { _tprintf(_T(" module @%p"), pInfo->hModule); } if (pInfo->hInstance && pInfo->hInstance != pInfo->hModule) { _tprintf(_T(" instance @%p"), pInfo->hInstance); } if (pInfo->hwnd == GetDesktopWindow()) { _tprintf(_T(" (Desktop Window)")); } if (pInfo->hwnd == GetShellWindow()) { _tprintf(_T(" (Shell Window)")); } _tprintf(_T("\n")); } static void DestroyWindowInformation(WINDOW_INFORMATIONS *pInfo) { HeapFree(GetProcessHeap(), 0, pInfo->szClass); HeapFree(GetProcessHeap(), 0, pInfo->szTitle); CloseHandle(pInfo->hModule); CloseHandle(pInfo->hInstance); } /** * Callback for EnumWindows */ static BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam) { ENUM_WIN_INFOS_LPARAM *pWininfos = (ENUM_WIN_INFOS_LPARAM *)lParam; WINDOW_INFORMATIONS *pInfo; DWORD i; assert(pWininfos); /* Add one item to pWininfos->infos */ i = pWininfos->nCount; pWininfos->nCount = i + 1; pInfo = pWininfos->infos; if (pInfo) { pInfo = HeapReAlloc(GetProcessHeap(), 0, pInfo, (i + 1) * sizeof(WINDOW_INFORMATIONS)); } else { pInfo = HeapAlloc(GetProcessHeap(), 0, (i + 1) * sizeof(WINDOW_INFORMATIONS)); } pWininfos->infos = pInfo; if (!pInfo) { print_winerr(_T("HeapRealloc")); return FALSE; } /* Fill WINDOW_INFORMATIONS structure */ return CollectWindowInformation(hwnd, &pInfo[i]); } static int CompareWinInfosList(const void *arg1, const void *arg2) { const WINDOW_INFORMATIONS *pInfo1 = (const WINDOW_INFORMATIONS *)arg1; const WINDOW_INFORMATIONS *pInfo2 = (const WINDOW_INFORMATIONS *)arg2; int cmp; if (pInfo1->szTitle && !pInfo2->szTitle) return 1; if (!pInfo1->szTitle && pInfo2->szTitle) return -1; cmp = _tcsicmp(pInfo1->szTitle, pInfo2->szTitle); if (cmp) return cmp; if (pInfo1->szClass && !pInfo2->szClass) return 1; if (!pInfo1->szClass && pInfo2->szClass) return -1; cmp = _tcsicmp(pInfo1->szClass, pInfo2->szClass); if (cmp) return cmp; if (pInfo1->hwnd != pInfo2->hwnd) return (pInfo1->hwnd > pInfo2->hwnd) ? 1 : -1; return 0; } /** * Recursively list children of a given window */ static BOOL ListWindowsRec(HWND hwndParent, DWORD nIndent) { BOOL bRet = TRUE; DWORD i, j; ENUM_WIN_INFOS_LPARAM wininfos; ZeroMemory(&wininfos, sizeof(wininfos)); if (!hwndParent) { if (!EnumWindows(EnumWindowsProc, (LPARAM)&wininfos)) { print_winerr(_T("EnumWindows")); bRet = FALSE; goto cleanup; } } else { SetLastError(0); EnumChildWindows(hwndParent, EnumWindowsProc, (LPARAM)&wininfos); if (GetLastError()) { print_winerr(_T("EnumChildWindows")); bRet = FALSE; goto cleanup; } } if (wininfos.nCount) { assert(wininfos.infos); qsort(wininfos.infos, wininfos.nCount, sizeof(WINDOW_INFORMATIONS), CompareWinInfosList); } for (i = 0; i < wininfos.nCount; i++) { const WINDOW_INFORMATIONS *pInfo = &wininfos.infos[i]; for (j = 0; j < nIndent; j++) { _tprintf(_T(" ")); } PrintWindowInfo(pInfo); if (!ListWindowsRec(pInfo->hwnd, nIndent + 1)) { bRet = FALSE; goto cleanup; } } cleanup: if (wininfos.infos) { assert(wininfos.nCount > 0); for (i = 0; i < wininfos.nCount; i++) { DestroyWindowInformation(&wininfos.infos[i]); } HeapFree(GetProcessHeap(), 0, wininfos.infos); } return bRet; } int _tmain(void) { HWND hwnd; WINDOW_INFORMATIONS winInfo; hwnd = GetDesktopWindow(); _tprintf(_T("Current Desktop Window: hwnd = %#" PRIxPTR "\n"), (UINT_PTR)hwnd); if (hwnd && CollectWindowInformation(hwnd, &winInfo)) { _tprintf(_T("-> ")); PrintWindowInfo(&winInfo); DestroyWindowInformation(&winInfo); } hwnd = GetShellWindow(); _tprintf(_T("Current Shell Window: hwnd = %#" PRIxPTR "\n"), (UINT_PTR)hwnd); if (hwnd && CollectWindowInformation(hwnd, &winInfo)) { _tprintf(_T("-> ")); PrintWindowInfo(&winInfo); DestroyWindowInformation(&winInfo); } return ListWindowsRec(NULL, 0) ? 0 : 1; }
C
#include <stdio.h> #include <stdlib.h> /** * _strdup - function to malloc and free * @str: int * Return: allways char */ char *_strdup(char *str) { char *ptr; int c, i; if (str == NULL) return (NULL); for (c = 0; str[c] != '\0'; c++) { } ptr = malloc(c + 1 * sizeof(char)); if (ptr == NULL) return (NULL); for (i = 0; i < c; i++) { ptr[i] = str[i]; } return (ptr); }
C
#include <stdio.h> #include <stdlib.h> int validate(char *name) { int i; for (i=0;name[i] != '\0';i++) { if(!(name[i]>=65&&name[i]<=90)&& !(name[i]>=97&&name[i]<=122)) return 0; } return 1; }; int main() { char *name="ai"; //fgets(name,sizeof(name),stdin); if(validate(name)) { printf("string is valid"); } else { printf("string is invalid"); } }
C
/* ************************************************************************** */ /* LE - / */ /* / */ /* create_lines.c .:: .:/ . .:: */ /* +:+:+ +: +: +:+:+ */ /* By: nerahmou <[email protected]> +:+ +: +: +:+ */ /* #+# #+ #+ #+# */ /* Created: 2018/06/29 20:29:44 by nerahmou #+# ## ## #+# */ /* Updated: 2018/06/29 20:35:42 by nerahmou ### #+. /#+ ###.fr */ /* / */ /* / */ /* ************************************************************************** */ #include "lem_in.h" extern int g_w; extern int g_h; extern int g_max_x; extern int g_max_y; t_line *create_line(t_info *colonie, t_salle *src, t_salle *dest, SDL_Renderer *renderer) { t_line *new; t_line *tmp; if (!(new = malloc(sizeof(*new)))) exit(1); tmp = colonie->lines; new->src_x = ((src->x * g_w) / g_max_x) + 25; new->src_y = ((src->y * g_h) / g_max_y) + 25; new->dst_x = ((dest->x * g_w) / g_max_x) + 25; new->dst_y = ((dest->y * g_h) / g_max_y) + 25; new->next = NULL; if (tmp) { while (tmp->next) tmp = tmp->next; tmp->next = new; } else colonie->lines = new; return (colonie->lines); } void get_lines(t_info *colonie, SDL_Window *window, SDL_Renderer *rend) { t_salle *salle; t_connection *co; salle = colonie->salle; while (salle) { co = salle->co; while (co) { colonie->lines = create_line(colonie, salle, co->salle, rend); co = co->next; } salle = salle->next; } }
C
#include <stddef.h> const char *odd_or_even(const int *v, size_t sz) { int sum = 0; for (int i = 0; i < sz; i++) sum += v[i]; return sum % 2 == 0 ? "even" : "odd"; }
C
#include<stdio.h> #include<ctype.h> int main(){ char ch; //int i; ch = toupper(ch); //i = ch; scanf("c",&ch); //for (i = ch; ch<='Z'; ch++) //printf("character: %d\n",i); if ('a'<=ch && ch<= 'z') ch = ch-'a'+'A'; //scanf("%c",&ch); printf("%c",ch); return 0; }
C
// Version 1.4 // Created by Oliver Tan // 19 May 2011 // Pits your AI against each other // Must compile with Game.c and ai.c #include <stdio.h> #include <stdlib.h> #include <time.h> #include <assert.h> #include "Game.h" #include "mechanicalTurk.h" // Game aspects #define UNI_CHAR_NAME ('A' - UNI_A) #define WINNING_KPI 150 #define DICE_AMOUNT 2 // runGame defaults #define INVALID -1 #define DICE_FACES 6 #define NUM_DISCIPLINES 6 // Action: #define ACTION_NAMES \ { "Pass", "Build Campus", "Build GO8", "Obtain ARC", \ "Start Spinoff", "", "", "Retrain Student" } #define DISCIPLE_NAMES \ { "ThD", "BPS", "BQN", "MJobs", "MTV", "M$" } #define SCREEN_WIDTH 50 #define LINE_BREAK_SEPARATOR '-' #define CYAN STUDENT_BQN #define PURP STUDENT_MMONEY #define YELL STUDENT_MJ #define RED STUDENT_BPS #define GREE STUDENT_MTV #define BLUE STUDENT_THD #define MAX_PASS 9000 void randomDisciplines(int disciplines[]); void randomDice(int dice[]); void rigBoard(int disciplines[], int dice[]); void printPlayerStats(Game g, int turnPerson); int rollDice(void); int checkForWinner(Game g); void printLineBreak(void); int main(int argc, char *argv[]) { // miscellaneous /*int disciplines[NUM_REGIONS]; int dice[NUM_REGIONS];*/ Game g; // store the winner of each game int winner; // store game states within the game int keepPlaying; int turnFinished; int diceRollAmount; // random char *actions[] = ACTION_NAMES; int diceRoll; int passedTurns = 0; // seed rand! srand(time(NULL)); // while the game is wanting to be played, create new game, etc. keepPlaying = TRUE; while (keepPlaying == TRUE) { // create the game //randomDisciplines(disciplines); //randomDice(dice); // you can change this to randomiseDisciplines() and randomiseDice() later int disciplines[NUM_REGIONS] = {CYAN,PURP,YELL,PURP,YELL,RED ,GREE,GREE, RED ,GREE,CYAN,YELL,CYAN,BLUE,YELL,PURP,GREE,CYAN,RED }; int dice[NUM_REGIONS] = {9,10,8,12,6,5,3,7,3,11,4,6,4,9,9,2,8,10,5}; // rig board like the real game rigBoard(disciplines, dice); g = newGame(disciplines, dice); printf("Game created! Now playing...\n"); // start the game with noone as the winner winner = NO_ONE; while (winner == NO_ONE) { printLineBreak(); // start new turn by setting turnFinished to false then // rolling the dice diceRollAmount = 0; diceRoll = 0; while (diceRollAmount < DICE_AMOUNT) { diceRoll += rollDice(); diceRollAmount++; } throwDice(g, diceRoll); // new turn means new line break! printf("[Turn %d] The turn now belongs to University %c!\n", getTurnNumber(g), getWhoseTurn(g) + UNI_CHAR_NAME); printf("The dice has casted a %d!\n", diceRoll); printf("\n"); // keep going through the player's turn until // he/she decided to pass and finish the turn turnFinished = FALSE; while (turnFinished == FALSE && passedTurns < MAX_PASS) { // processes requests and all subrequests for a move and // checks if they are legal. only gives a move within the // scope of the defined actionCodes that is legal int turnPerson = getWhoseTurn(g); printPlayerStats(g, turnPerson); action a = decideAction(g); // if not passing, make the move; otherwise end the turn if (a.actionCode == PASS) { turnFinished = TRUE; printf("You have passed onto the next person.\n"); } else { // write what the player did, for a logs sake. printf("The action '%s' has being completed.\n", actions[a.actionCode]); if (a.actionCode == BUILD_CAMPUS || a.actionCode == OBTAIN_ARC || a.actionCode == BUILD_GO8) { printf(" -> Destination: %s\n", a.destination); } else if (a.actionCode == RETRAIN_STUDENTS) { printf(" -> DisciplineTo: %d\n", a.disciplineTo); printf(" -> DisciplineFrom: %d\n", a.disciplineFrom); } assert(isLegalAction(g, a)); // break this and the code dies. trololol! if (a.actionCode == START_SPINOFF) { if (rand() % 3 <= 1) { a.actionCode = OBTAIN_PUBLICATION; } else { a.actionCode = OBTAIN_IP_PATENT; } } makeAction(g, a); if (a.actionCode == PASS) { passedTurns++; } else { passedTurns = 0; } if (passedTurns >= MAX_PASS || getKPIpoints(g, turnPerson) >= WINNING_KPI) { turnFinished = TRUE; } } // if there is not a winner or pass, add a seperating line // to seperate actions being clumped together if (turnFinished == FALSE) { printf("\n"); } } // check if there is a winner winner = checkForWinner(g); } if (passedTurns >= MAX_PASS) { printf("AI passes too much.\n"); return EXIT_FAILURE; } printLineBreak(); printf("GAME OVER!\n"); printf("Vice Chanceller %c Won in %d Turns!!\n", winner + UNI_CHAR_NAME, getTurnNumber(g)); printf("\n"); int counter = UNI_A; while (counter < NUM_UNIS + UNI_A) { printf("Uni %c scored %d KPIs\n", counter + UNI_CHAR_NAME, getKPIpoints(g, counter)); counter++; } printPlayerStats(g, 1); printPlayerStats(g, 2); printPlayerStats(g, 3); printLineBreak(); disposeGame(g); // ask to play again printf("Ctrl+C will exit the game.\nOtherwise, the game will " "recommence by hitting enter."); int a = scanf("%*c"); a++; } return EXIT_SUCCESS; } // ----- game creation ----- void rigBoard(int disciplines[], int dice[]) { disciplines[0] = disciplines[2] = disciplines[7] = STUDENT_BPS; disciplines[11] = disciplines[16] = disciplines[18] = STUDENT_BQN; } // Allocates a set of random disciplines inside disciplines[] void randomDisciplines(int disciplines[]) { int disciplineIndex; disciplineIndex = 0; while (disciplineIndex < NUM_REGIONS) { // allocate each discipline with a random one disciplines[disciplineIndex] = rand() % NUM_DISCIPLINES; disciplineIndex++; } } // Allocates a set of random dice inside disciplines[] void randomDice(int dice[]) { int diceIndex; int diceRolled; int totalRoll; diceIndex = 0; while (diceIndex < NUM_REGIONS) { totalRoll = 0; // roll a dice DICE_AMOUNT and add the total diceRolled = 0; while (diceRolled < DICE_AMOUNT) { totalRoll += rollDice(); diceRolled++; } // allocate the totalRoll dice[diceIndex] = totalRoll; diceIndex++; } } void printPlayerStats(Game g, int turnPerson) { printf("Stats for %c:\n", turnPerson + UNI_CHAR_NAME); printf("KPIs: %d\n", getKPIpoints(g, turnPerson)); printf("ARCs: %d\n", getARCs(g, turnPerson)); printf("Campuses: %d\n", getCampuses(g, turnPerson)); printf("GO8s: %d\n", getGO8s(g, turnPerson)); printf("Publications: %d\n", getPublications(g, turnPerson)); printf("Patents: %d\n", getIPs(g, turnPerson)); int discipleIndex = 0; char *discipleNames[] = DISCIPLE_NAMES; while (discipleIndex < NUM_DISCIPLINES) { printf("Type %s: %d\n", discipleNames[discipleIndex], getStudents(g, turnPerson, discipleIndex)); discipleIndex++; } printf("\n"); } // return a number between 1...DICE_FACES int rollDice(void) { // modding returns between 0...(DICE_FACES-1), so add 1 return (rand() % DICE_FACES) + 1; } // ----- game actions ----- // check all players' KPI and returns the winner (if any) int checkForWinner(Game g) { int winner = NO_ONE; int playerIndex; playerIndex = UNI_A; while (playerIndex < NUM_UNIS + UNI_A) { // check if the player is over or equal the WINNING_KPI if (getKPIpoints(g, playerIndex) >= WINNING_KPI) { winner = playerIndex; } playerIndex++; } return winner; } // prints a new line, line break, then new line again void printLineBreak(void) { int counter; printf("\n"); // print the line break (SCREEN_WIDTH amount of // LINE_BREAK_SEPARATOR) counter = 0; while (counter < SCREEN_WIDTH) { printf("%c", LINE_BREAK_SEPARATOR); counter++; } printf("\n\n"); }
C
/*******************************************************************/ /* EP1 de MAC0422 - Sistemas Operacionais */ /* */ /* Simulador de uma corrida - ep2.c */ /* */ /* Autores: Gustavo Silva e Leonardo Padilha */ /* */ /*******************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <time.h> #define TRUE 1 #define FALSE 0 #define MODE_U -1 #define MODE_V 1 /********************************************************************/ /*********************** Estruturas usadas **************************/ /********************************************************************/ /* Estrutura do Ciclista */ typedef struct cyc { int id; /* identificador do ciclista. */ int lap; /* volta que o ciclista está. */ int vel; /* velocidade que ele está. */ int velM; /* velocidade máxima que ele pode adquirir. */ int team; /* equipe que ele está. */ int broken; /* valor que diz se está quebrado ou não. */ int deaccel; /* flag que diz se ele desaacelerou. */ int nextVel; /* velocidade para a proxima volta. */ int nextVelM; /* velocidade maxima para a próxima volta. */ int finalTick; /* tempo que ele demorou para chegar. */ float pos; /* posição da pista que ele está. */ pthread_t thread; /* identificador da thread. */ pthread_mutex_t velmutex; /* mutex para alteração da velocidade */ } CYCLIST; /* Estrutura de um slot da pista */ typedef struct sl { int mainpos; /* slot da pista principal. */ int ultrapos; /* slot da pista para ultrapassagem. */ pthread_mutex_t mut;/* mutex para o slot. */ } SLOT; /* Estrutura dos argumentos das threads */ typedef struct arguments { int i; } ARGS; /********************************************************************/ /************************ Variaveis Globais *************************/ /********************************************************************/ SLOT *pista; /* Vetor de slot pista */ CYCLIST *c; /* Vetor de ciclista */ int d; /* Tamanho da pista */ int mode; int debug; /* Parametro para debug*/ int cycsize; int raceEnd; int timeTick; int globalLap; int runners[2]; int timeToBreak; pthread_barrier_t barrera; pthread_mutex_t randmutex; pthread_mutex_t lapmutex; /********************************************************************/ /*********************** Declaração de funções **********************/ /********************************************************************/ void *ciclista (void *a); void *dummy (); void waitForSync (); void manageRace (); void breakCyclist (); void changeVel (); float dist (CYCLIST cycl); int selectVelMax (); int comparator (const void *a, const void *b); /********************************************************************/ /************************ Código das funções ************************/ /********************************************************************/ int main (int argc, char **argv) { int n, i, winners[2], thirdTick[2]; char type; ARGS* thread_arg; if (argc < 4) exit (EXIT_FAILURE); /* Inicialização das variáveis dadas na linha de comando*/ d = atoi (argv[1]); n = atoi (argv[2]); type = argv[3][0]; if (argc > 4 && strcmp (argv[4], "-d") == 0) debug = TRUE; else debug = FALSE; /* inicializando nosso gerador */ srand(time(NULL)); /* inicializando variaveis globais */ raceEnd = 0; runners[0] = n; runners[1] = n; cycsize = 2*n; globalLap = 0; timeToBreak = FALSE; /* Inicializando os 2xN ciclistas */ c = malloc (2 * n * sizeof (CYCLIST)); /* Modo para velocidades uniformes */ if (type == 'u') { for (i = 0; i < n; i++) { c[i].vel = 60; c[i].velM = 60; c[i].nextVelM = selectVelMax (); c[i].nextVel = c[i].nextVelM; c[i].deaccel = FALSE; c[i].team = 0; c[i].lap = 0; c[i].pos = 0.0; c[i].id = i + 1; c[i].finalTick = 0; c[i].broken = 0; pthread_mutex_init (&c[i].velmutex, NULL); } for (i = n; i < 2 * n; i++) { c[i].vel = 60; c[i].velM = 60; c[i].nextVelM = selectVelMax (); c[i].nextVel = c[i].nextVelM; c[i].deaccel = FALSE; c[i].team = 1; c[i].lap = 0; c[i].pos = d/2; c[i].id = i + 1; c[i].finalTick = 0; c[i].broken = 0; pthread_mutex_init (&c[i].velmutex, NULL); } mode = MODE_U; } /* Modo de velocidades variadas */ else if (type == 'v') { for (i = 0; i < n; i++) { c[i].vel = 30; c[i].velM = 30; c[i].nextVel = selectVelMax (); c[i].nextVel = c[i].nextVelM; c[i].deaccel = FALSE; c[i].team = 0; c[i].lap = 0; c[i].pos = 0.0; c[i].id = i + 1; c[i].finalTick = 0; c[i].broken = 0; pthread_mutex_init (&c[i].velmutex, NULL); } for (i = n; i < 2 * n; i++) { c[i].vel = 30; c[i].velM = 30; c[i].nextVel = selectVelMax (); c[i].nextVel = c[i].nextVelM; c[i].deaccel = FALSE; c[i].team = 1; c[i].lap = 0; c[i].pos = d/2; c[i].id = i + 1; c[i].finalTick = 0; c[i].broken = 0; pthread_mutex_init (&c[i].velmutex, NULL); } mode = MODE_V; } /* ERRO */ else return EXIT_FAILURE; /* Inicializando o vetor pista */ pista = malloc (d * sizeof (SLOT)); for (i = 0; i < d; i++) { pista[i].mainpos = 0; pista[i].ultrapos = 0; pthread_mutex_init (&pista[i].mut, NULL); } /* Inicializando a barreira para 2n threads e o mutex do random*/ pthread_barrier_init (&barrera, NULL, 2*n); pthread_mutex_init (&randmutex, NULL); pthread_mutex_init (&lapmutex, NULL); /* Disparando as threads */ for (i = 0; i < 2 * n; i++) { thread_arg = malloc (sizeof (ARGS)); thread_arg->i = i; pthread_create (&c[i].thread, NULL, &ciclista, thread_arg); } /* Esperando retornar*/ for (i = 0; i < 2 * n; i++) pthread_join (c[i].thread, NULL); /* após o fim da corrida */ printf("A corrida terminou!\n\nRanking:\n"); /* ordenar o ranking de ciclistas */ qsort ((void *) c, 2*n, sizeof (CYCLIST), comparator); winners[0] = winners[1] = thirdTick[0] = thirdTick[1] = 0; for (i = 0; i < cycsize; i++) { /* vamos contabilizar qual equipe venceu a corrida */ winners[c[i].team]++; /* pra isso, temos que ver qual terceiro ciclista acabou antes */ if (winners[c[i].team] == 3) thirdTick[c[i].team] = c[i].finalTick; /* exibindo ranking */ if (c[i].broken) printf("%do: Ciclista %d (Equipe %d) - ACIDENTE (Volta %d)\n", i+1, c[i].id, c[i].team+1, c[i].lap+1); else printf("%do: Ciclista %d (Equipe %d) - %.3fs\n", i+1, c[i].id, c[i].team+1, (float) (c[i].finalTick*60)/1000); } /* exibimos o print da vitória, pra terminar o EP */ if(thirdTick[0] < thirdTick[1]) printf("\nVitória da equipe 1!\n\n"); else if(thirdTick[0] > thirdTick[1]) printf("\nVitória da equipe 2!\n\n"); else printf("\nEmpate!\n\n"); return 0; } void *ciclista (void *a) { int i, j, passedLap, nextPos; int index1, index2, first, second; float dist1, dist2, next, changeIndex; pthread_t dummyid; ARGS* p = (ARGS *) a; i = p->i; while (TRUE) { /* Resetamos a flag de mudança de índice da posição do ciclista */ changeIndex = FALSE; /* Verificar se a corrida acabou */ if (raceEnd) break; /* Calcular a próxima posição do ciclista e quantos */ /*passos ele vai dar no vetor. */ if (c[i].vel == 60) { nextPos = (int) (c[i].pos + 1) % d; next = 1.0; } else { nextPos = (int) (c[i].pos + 0.5) % d; next = 0.5; } /* Solicitar acesso ao próximo slot */ pthread_mutex_lock (&pista[nextPos].mut); { /* Se não tiver ninguém no slot principal, vamos ocupar ele e desocupar */ /*o anterior. */ if (pista[nextPos].mainpos == 0) { /* Verifica se ele estava na posição anterior para poder zera-la*/ if (pista[(int) c[i].pos].mainpos == c[i].id) pista[(int) c[i].pos].mainpos = 0; else if (pista[(int) c[i].pos].ultrapos == c[i].id) pista[(int) c[i].pos].ultrapos = 0; /* O ciclista insere seu id na posição principal */ pista[nextPos].mainpos = c[i].id; /* Calculo da proxima posição*/ c[i].pos += next; if (c[i].pos >= d) c[i].pos = c[i].pos - d; /* Como houve a alteração da posição do ciclista, setamos a flag. */ changeIndex = TRUE; } /* Verifica se a próxima posição do ciclista é a que ele está. */ else if (pista[nextPos].mainpos == c[i].id) { c[i].pos += next; if (c[i].pos >= d) c[i].pos = c[i].pos - d; } /* Se a posição principal que o ciclista quer acessar está ocupada pos*/ /*um ciclista de outra equipe, tentamos inserir o ciclista na pista de*/ /*ultrapassagem. */ else if (pista[nextPos].ultrapos == 0 && (c[pista[nextPos].mainpos-1].team != c[i].team || c[pista[nextPos].mainpos-1].vel < c[i].vel)) { /* O ciclista insere seu id na posição de ultrapassagem. */ pista[nextPos].ultrapos = c[i].id; /* Verifica se ele estava na posição anterior para poder zera-la. */ if (pista[(int) c[i].pos].mainpos == c[i].id) pista[(int) c[i].pos].mainpos = 0; else if (pista[(int) c[i].pos].ultrapos == c[i].id) pista[(int) c[i].pos].ultrapos = 0; /* Calculo da proxima posição */ c[i].pos += next; if (c[i].pos >= d) c[i].pos = c[i].pos - d; /* Como houve a alteração da posição do ciclista, setamos a flag. */ changeIndex = TRUE; } /* Verifica se a próxima posição do ciclista é a que ele está (de ul-*/ /*trapassagem). */ else if (pista[nextPos].ultrapos == c[i].id) { c[i].pos += next; if (c[i].pos >= d) c[i].pos = c[i].pos - d; } /* Se o indice, */ if (changeIndex) { /* verificar se houve um incremento de volta. */ if ((c[i].team == 0 && nextPos == 0 && c[i].pos == 0.0) || (c[i].team == 1 && nextPos == d/2 && c[i].pos == d/2)) { c[i].lap++; /* Alteramos a velocidade do ciclista. */ if (mode == MODE_V) { pthread_mutex_lock (&c[i].velmutex); c[i].velM = c[i].nextVel; c[i].vel = c[i].velM; pthread_mutex_unlock (&c[i].velmutex); /* Selecionamos as próximas velocidades máximas. */ c[i].nextVelM = selectVelMax (); c[i].nextVel = c[i].nextVelM; /* Resetamos a flag de desaceleração. */ if (c[i].velM == 30 || c[i].deaccel) c[i].deaccel = FALSE; /* Todos que estiverem atrás dele ficarão a 30km/h */ if (c[i].velM == 30) changeVel (i); } /* Verificamos se ele é o primeiro a mudar de volta */ pthread_mutex_lock(&lapmutex); { if(c[i].lap > globalLap) { globalLap++; /* a cada quatro voltas, chance de alguem quebrar */ if(globalLap % 4 == 0 && globalLap < 16) { timeToBreak = TRUE; } } } pthread_mutex_unlock(&lapmutex); /* caso ele terminou a corrida, marcamos isso */ if(c[i].lap == 16) c[i].finalTick = timeTick + 1; /* verificamos se ele é o terceiro a passar */ passedLap = index1 = index2 = 0; dist1 = dist2 = 0.0; for (j = 0; j < cycsize; j++) { if(c[j].broken) continue; /* Guardamos tambem o primeiro e segundo colocados */ if (c[j].team == c[i].team && c[j].lap >= c[i].lap && i != j) { if (dist1 == 0.0) { /* O ultimo fator da soma corrige a diferença do ponto */ /*de largada das duas equipes. */ dist1 = (c[j].lap * d) + c[j].pos - c[j].team*(d/2); index1 = c[j].id; } else { dist2 = (c[j].lap * d) + c[j].pos - c[j].team*(d/2); index2 = c[j].id; } passedLap++; } } /* Exibimos o print de nova volta */ if (passedLap == 2) { if (dist1 > dist2) { first = index1; second = index2; } else { first = index2; second = index1; } printf("Ciclista %d (Equipe %d) finalizou a volta %d no instante %.3fs.\n", c[i].id, c[i].team+1, c[i].lap, (float) (timeTick*60)/1000); printf("Primeiro da equipe: %d\nSegundo da equipe: %d\n\n", first, second); } } } } pthread_mutex_unlock (&pista[nextPos].mut); /* sincronizar threads */ waitForSync(); /* verificamos se este ciclista quebrou e deve ser desligado */ if(c[i].broken) { pthread_create(&dummyid, NULL, &dummy, NULL); break; } } return NULL; } /* thread vazia, apenas para substituir os ciclistas quebrados */ void *dummy () { while(TRUE) { /* verificar se a corrida acabou */ if (raceEnd) break; /* sincronizar com o resto */ waitForSync(); } return NULL; } /* função que sincroniza todas as thread após uma iteração. utiliza duas barreiras pra isso, recheadas por código de controle do funcionamento da corrida. */ void waitForSync() { /* sincronizar na barreira para o intervalo seguinte */ int res = pthread_barrier_wait (&barrera); /* esta condição só vai ser executada em uma das threads */ if (res == PTHREAD_BARRIER_SERIAL_THREAD) { manageRace(); } /* mais uma barreira, pra garantir que ninguém vai recomeçar a volta sem saber se a corrida acabou */ pthread_barrier_wait (&barrera); } /* código que gerencia o funcionamento da corrida ao fim de cada iteração dos ciclistas. Só é executado em uma thread. */ void manageRace () { int j; /* Aumentar o tempo atual */ timeTick++; /* Printar tabuleiro caso o debug esteja habilitado */ if(debug) { printf("Instante: %.3f\n", (float) (timeTick*60)/1000); for (j = 0; j < d; j++) { printf("[%3.d][%3.d] %d\n", (int) pista[j].mainpos, (int) pista[j].ultrapos, j); } printf("\n"); printf("EQUIPE 1\n"); for (j = 0; j < cycsize / 2; j++) printf("Ciclista %d, velocidade %d (%d), posição %f\n", j+1, c[j].vel, c[j].velM, dist(c[j])); printf ("EQUIPE 2\n"); for (j = cycsize / 2; j < cycsize; j++) printf("Ciclista %d, velocidade %d (%d), posição %f\n", j+1, c[j].vel, c[j].velM, dist(c[j])); printf("\n\n"); } /* Verificar se é necessario quebrar algum ciclista */ if (timeToBreak) { timeToBreak = FALSE; breakCyclist(); } /* Verificar se a corrida acabou */ raceEnd = 1; for (j = 0; j < cycsize; j++) { if(c[j].broken) continue; /* Procuramos ciclistas que ainda nao acabaram */ if(c[j].lap < 16) { raceEnd = 0; break; } } } /* breakCyclist: quebra um ciclista aleatório com chance de 10% */ void breakCyclist () { int startpoint = 0, endpoint = cycsize, chance, lucky; /* Verificamos se as equipes são grandes o suficiente */ if(runners[0] == 3) startpoint = cycsize/2; if(runners[1] == 3) endpoint = cycsize/2; if(startpoint == endpoint) return; chance = rand() % 10; /* Chance é de 10% */ if(chance < 1) { do { /* Normalizamos o random pra escolher um dos ciclistas */ lucky = (rand() % (endpoint - startpoint)) + startpoint; } while(c[lucky].broken); c[lucky].broken = 1; pista[(int) c[lucky].pos].mainpos = 0; printf("Ciclista %d (Equipe %d) sofreu um acidente!\n\n", c[lucky].id, c[lucky].team + 1); runners[c[lucky].team]--; } } /* selectVelMax: retorna uma velocidade máxima (50% de ser 30km/h*/ /*e 50% de ser 60km/h). */ int selectVelMax () { int prob; /* Retornnamos a velocidade com base na probabilidade prob.*/ prob = rand() % 10; if (prob >= 5) return 30; else return 60; } /* changeVel: recebe um inteiro i e altera todas as velocidades */ /*dos ciclistas que são da mesma equipe e que estão atrás do ci- */ /*clista identificado por j por 30km/. */ void changeVel (int i) { int j; for (j = 0; j < cycsize; j++) { if (c[j].team == c[i].team && dist (c[j]) < dist (c[i])) { pthread_mutex_lock (&c[j].velmutex); if (c[j].nextVelM > 30 && !c[j].deaccel) { c[j].nextVel = 30; c[j].vel = 30; c[j].deaccel = TRUE; } pthread_mutex_lock (&c[j].velmutex); } } } /* dist: recebe um CYCLIST cycl e retorna a distancia percorrida */ /*por cycl. */ float dist (CYCLIST cycl) { float dist; if (cycl.team == 1) if (cycl.pos >= d/2) dist = cycl.lap*d + cycl.pos - d/2; else dist = cycl.lap*d + cycl.pos + d/2; else dist = cycl.lap*d + cycl.pos; return dist; } /* função que ordena os ciclistas por ordem de chegada, compa- */ /*rando dois a dois: */ /* - retorna um valor < 0 se A deve vir antes de B */ /* - retorna um valor > 0 se B deve vir antes de A */ /* - retorna 0 se são iguais */ int comparator (const void *a, const void *b) { CYCLIST *c1, *c2; /* Fazemos o cast para ponteiro de ciclista */ c1 = (CYCLIST*) a; c2 = (CYCLIST*) b; /* Se ambos estiverem quebrados, predomina o lap em que quebraram.*/ if(c1->broken && c2->broken) return c2->lap - c1->lap; /* Se apenas um estiver quebrado, ele vai pro fundo da lista. */ if(c1->broken) return 1; if(c2->broken) return -1; /* A comparação tradicional é por distancia percorrida, ja que mesmo */ /*apos passar a linha de chegada eles continuam andando */ return c1->finalTick - c2->finalTick; }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include "gtm/gtm_c.h" #include "gtm/gtm_client.h" #include "gtm/libpq-fe.h" typedef enum command_t { CMD_INVALID = 0, CMD_UNREGISTER } command_t; char *progname; command_t command; char *nodename = NULL; int gtmport = -1; char *gtmhost = NULL; char *myname = NULL; #define DefaultName "pgxc_clean_gtm" GTM_PGXCNodeType nodetype = 0; /* Invalid */ int verbose = 0; static int process_unregister_command(GTM_PGXCNodeType type, char *nodename); int main(int argc, char *argv[]) { int opt; int rc; progname = strdup(argv[0]); while ((opt = getopt(argc, argv, "p:h:n:Z:v")) != -1) { switch(opt) { case 'p': gtmport = atoi(optarg); break; case 'h': if (gtmhost) free(gtmhost); gtmhost = strdup(optarg); break; case 'n': if (myname) free(myname); myname = strdup(optarg); break; case 'v': verbose = 1; break; case 'Z': if (strcmp(optarg, "gtm") == 0) { nodetype = GTM_NODE_GTM; break; } else if (strcmp(optarg, "gtm_proxy") == 0) { nodetype = GTM_NODE_GTM_PROXY; break; } else if (strcmp(optarg, "gtm_proxy_postmaster") == 0) { nodetype = GTM_NODE_GTM_PROXY_POSTMASTER; break; } else if (strcmp(optarg, "coordinator") == 0) { nodetype = GTM_NODE_COORDINATOR; break; } else if (strcmp(optarg, "datanode") == 0) { nodetype = GTM_NODE_DATANODE; break; } else { fprintf(stderr, "%s: Invalid -Z option value, %s\n", progname, optarg); exit(2); } break; default: fprintf(stderr, "%s: Invalid option %c\n", progname, opt); exit(2); } } if (myname == NULL) myname = strdup(DefaultName); if (optind >= argc) { fprintf(stderr,"%s: No command specified.\n", progname); exit(2); } if (strcmp(argv[optind], "unregister") == 0) { command = CMD_UNREGISTER; if (optind + 1 >= argc) { fprintf(stderr, "%s: unregister: node name missing\n", progname); exit(2); } nodename = strdup(argv[optind + 1]); } else { fprintf(stderr, "%s: Invalid command %s\n", progname, argv[optind]); exit(2); } if (gtmport == -1) { fprintf(stderr, "%s: GTM port number not specified.\n", progname); exit(2); } if (gtmhost == NULL) { fprintf(stderr, "%s: GTM host name not specified.\n", progname); exit(2); } switch(command) { case CMD_UNREGISTER: if (nodetype == 0) { fprintf(stderr, "%s: unregister: -Z option not specified.\n", progname); exit(2); } rc = process_unregister_command(nodetype, nodename); break; default: fprintf(stderr, "%s: Internal error, invalid command.\n", progname); exit(1); } exit(rc); } static GTM_Conn *connectGTM() { char connect_str[256]; GTM_Conn *conn; sprintf(connect_str, "host=%s port=%d node_name=%s remote_type=%d postmaster=0", gtmhost, gtmport, myname == NULL ? DefaultName : myname, GTM_NODE_COORDINATOR); if ((conn = PQconnectGTM(connect_str)) == NULL) { fprintf(stderr, "%s: Could not connect to GTM\n", progname); return(NULL); } return(conn); } static int process_unregister_command(GTM_PGXCNodeType type, char *nodename) { GTM_Conn *conn; int res; conn = connectGTM(); if (conn == NULL) { fprintf(stderr, "%s: failed to connect to GTM\n", progname); return 1; } res = node_unregister(conn, type, nodename); if (res == GTM_RESULT_OK){ if (verbose) fprintf(stderr, "%s: unregister %s from GTM.\n", progname, nodename); GTMPQfinish(conn); return GTM_RESULT_OK; } else { fprintf(stderr, "%s: Failed to unregister %s from GTM.\n", progname, nodename); GTMPQfinish(conn); return res; } }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef char WCHAR ; typedef int UINT ; /* Variables and functions */ char* heap_alloc (int) ; int /*<<< orphan*/ memcpy (char*,char const*,int) ; int strlenW (char const*) ; __attribute__((used)) static WCHAR *append_path( const WCHAR *path, const WCHAR *segment, UINT *len ) { UINT len_path = 0, len_segment = strlenW( segment ); WCHAR *ret; *len = 0; if (path) len_path = strlenW( path ); if (!(ret = heap_alloc( (len_path + len_segment + 2) * sizeof(WCHAR) ))) return NULL; if (path && len_path) { memcpy( ret, path, len_path * sizeof(WCHAR) ); ret[len_path] = '\\'; *len += len_path + 1; } memcpy( ret + *len, segment, len_segment * sizeof(WCHAR) ); *len += len_segment; ret[*len] = 0; return ret; }
C
/* ** EPITECH PROJECT, 2020 ** PSU_minishell2_2019 ** File description: ** redirection */ #include <minishell.h> #include <my_printf.h> #include <my_tools.h> char *get_redir_file(char **cmd, char *r) { for (size_t i = 0; cmd[i] != NULL; i++) if (my_strcmp(cmd[i], r) == 0) return cmd[i + 1]; return NULL; } char **rm_redir(char **cmd, char *r) { char **tmp = malloc(sizeof(char *) * (my_strlentab(cmd))); for (int i = 0, j = 0; cmd[i] != NULL; i++, tmp[++j] = NULL) { if (my_strcmp(cmd[i], r) == 0) if (cmd[i + 1] != NULL) i += 2; else if (cmd[i + 1] == NULL) { free_array(tmp); return NULL; } if (cmd[i] == NULL) return tmp; if (cmd[i] != NULL) tmp[j] = my_strdup(cmd[i]); } return tmp; } void luanch_cmd_by_redir(char ***cmd, data_t *data, char *std, int (*excut)()) { int i = 0, w = 0, o = dup(std[1]), status = 0, n = -1; n = dup2(std[0], std[1]); data->error = select_lauch_type(cmd, data, excut); close(n); dup(o); } int redirection(char ***cmd, data_t *data, int (*excut)()) { remove_cmdsn_quotes(&(*cmd)[0], 1); if (my_strcmptab((*cmd), ">")) redirection_right(cmd, data, excut); if (my_strcmptab((*cmd), ">>")) redirection_double_right(cmd, data, excut); if (my_strcmptab((*cmd), "<")) redirection_left(cmd, data, excut); if (my_strcmptab((*cmd), "<<")) redirection_double_left(cmd, data, excut); return data->error; }
C
#define _XOPEN_SOURCE 500 #ifdef _WIN32 #define PATH_SEPARATOR "\\" #else #define PATH_SEPARATOR "/" #endif #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <ftw.h> #include <string.h> #include <time.h> enum Operator {BEFORE = -1, THEN = 0, AFTER = 1}; static enum Operator op; static time_t mtime; int parse_operator(const char *str, enum Operator *op) { if (strcmp(str, "<") == 0) { *op = BEFORE; return 0; } if (strcmp(str, "=") == 0) { *op = THEN; return 0; } if (strcmp(str, ">") == 0) { *op = AFTER; return 0; } return -1; } int compare_time(time_t t1, enum Operator op, time_t t2) { double seconds = difftime(t1, t2); // t1 - t2 switch (op) { case BEFORE: return (seconds < 0); case THEN: return (seconds == 0); case AFTER: return (seconds > 0); } return -1; } int is_dir(const char *path) { struct stat st; if (stat(path, &st) == -1) { return 0; } return S_ISDIR(st.st_mode); } char *make_path(const char *dirpath, const char *filename) { char *filepath = malloc(strlen(dirpath) + strlen(filename) + strlen(PATH_SEPARATOR) + 1); if (!filepath) { return NULL; } strcpy(filepath, dirpath); strcat(filepath, PATH_SEPARATOR); return strcat(filepath, filename); } const char *format_mode(mode_t st_mode) { // http://www.gnu.org/software/libc/manual/html_node/Testing-File-Type.html if (S_ISREG(st_mode)) return "file"; if (S_ISDIR(st_mode)) return "dir"; if (S_ISCHR(st_mode)) return "char dev"; if (S_ISBLK(st_mode)) return "block dev"; if (S_ISFIFO(st_mode)) return "fifo"; if (S_ISLNK(st_mode)) return "slink"; if (S_ISSOCK(st_mode)) return "sock"; return "?"; } char *format_time(time_t datetime) { char *str = malloc(20); // strlen("YYYY-MM-DD HH:MM:SS") + 1 = 20, sizeof(char) = 1 strftime(str, 20, "%Y-%m-%d %H:%M:%S", localtime(&datetime)); return str; } static int display_info(const char *filepath, const struct stat *st, __attribute__((unused)) int tflag, struct FTW *ftwbuf) { if (ftwbuf && ftwbuf->level == 0) { return 0; // skip main directory } if (compare_time(st->st_mtime, op, mtime) == 1) { char *st_atime_str = format_time(st->st_atime); char *st_mtime_str = format_time(st->st_mtime); printf("%-64.60s%-10s%-10zu%-22s%-22s\n", filepath, format_mode(st->st_mode), st->st_size, st_atime_str, st_mtime_str ); free(st_atime_str); free(st_mtime_str); } return 0; } int list_dir_nftw(const char *dirpath) { if (nftw(dirpath, display_info, 20, FTW_PHYS) == -1) { fprintf(stderr, "Cannot walk directory tree\n"); return -1; } return 0; } int list_dir_stat(const char *dirpath) { DIR *dirp = opendir(dirpath); if (!dirp) { fprintf(stderr, "Cannot open directory\n"); return -1; } // rewinddir(dirp); struct dirent *dirent; while ((dirent = readdir(dirp))) { const char *filename = dirent->d_name; if (strcmp(filename, ".") == 0 || strcmp(filename, "..") == 0) { continue; } char *filepath = make_path(dirpath, filename); struct stat st; if (lstat(filepath, &st)) { // instead of stat() fprintf(stderr, "Cannot get file status\n"); return -1; } display_info(filepath, &st, 1, NULL); if (S_ISDIR(st.st_mode)) { list_dir_stat(filepath); // recursive call } free(filepath); } if (closedir(dirp)) { fprintf(stderr, "Cannot close directory\n"); return -1; } return 0; } int main(int argc, char **argv) { if (argc != 4) { fprintf(stderr, "Invalid arguments\n\ Syntax: ./main <dirpath> <operator> <date>\n\ <dirpath> path to directory\n\ <operator> \"<\", \"=\", or \">\"\n\ <date> date in format YYYY-MM-DD HH:MM:SS\n\n"); return -1; } char *dirpath = realpath(argv[1], NULL); if (!dirpath) { fprintf(stderr, "Directory %s not found\n", dirpath); return -1; } if (!is_dir(dirpath)) { fprintf(stderr, "%s is not a directory\n", dirpath); return -1; } if (parse_operator(argv[2], &op) == -1) { fprintf(stderr, "Invalid operator\n"); return -1; } struct tm *mtime_tm = calloc(1, sizeof(struct tm)); // properly initializes struct tm if (strptime(argv[3], "%Y-%m-%d %H:%M:%S", mtime_tm) == NULL) { fprintf(stderr, "Invalid date\n"); return -1; } mtime = mktime(mtime_tm); #ifdef NFTW list_dir_nftw(dirpath); #else list_dir_stat(dirpath); #endif free(dirpath); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <unistd.h> void* thread_summation(void *arg); int sum = 0; int main(int argc, char *argv[]) { pthread_t t_id, t_id2; int range[] = {1,5}; int range2[] = {6,10}; pthread_create(&t_id,NULL,thread_summation,(void *)range); pthread_create(&t_id2,NULL,thread_summation,(void *)range2); pthread_join(t_id,NULL); pthread_join(t_id2,NULL); printf("result : %d\n",sum); return 0; } void* thread_summation(void *arg) { int start = ((int *) arg)[0]; int end = ((int *) arg)[1]; while(start <= end) { sum += start; start++; } return NULL; }
C
#ifndef expression_h #define expression_h #include <string> #include <iostream> #include "mapa.c" #include "valores.c" #include "Espacio.c" #include "Robot.c" #include "MapaRobots.c" #define ERRORTIPO -2 #define TIPOBOOL 0 #define TIPOINT 1 #define TIPOCHAR 2 #define TIPOID 3 using namespace std; //Clase expresion, diferentes constructores para usar el polimorfismo efectivamente class Expresion{ public: int tipo; // tipo del 0 al 3, indicando si es booleano // un id, un caracter o un numero // tipo = -1 indica que es una expresion compuesta // tipo == 0 -> es un booleano // tipo == 1 -> es un numero // tipo == 2 -> es un caracter // tipo == 3 -> es un ID bool unary; string operador; string id; int val; bool bval; string caracter; Expresion *right; Expresion *left; int lineNo; //Recibe dos expresiones y un operador, crea una expresion compuesta Expresion(string op, Expresion *l, Expresion *r, int line): operador(op),left(l),right(r){ unary = false; tipo = -1; lineNo = line; } //A continuacion 3 constructores que hacen los tipos basicos // para simplificar problemas por caracteres como \n y \t // se usa un string para representar a un caracter Expresion(string a,int t, int line){ unary = false; tipo = t; if (t == 2){ caracter = string(a); } if (t == 3){ id = string(a); } lineNo = line; } Expresion(bool v, int t,int line){ unary = false; bval = v; tipo = t; lineNo = line; } Expresion(int v, int t,int line){ unary = false; tipo = t; val = v; lineNo = line; } // Constructor para las operaciones unarias Expresion(string op, Expresion* l, int line):operador(op),left(l){ tipo = -1; unary = true; lineNo = line; } Valores evaluar(Robot* bot, MapaRobots& mapa, Espacio& space, map<string,Valores> tablasimb){ Valores aux; if (tipo == 0){ aux.booleano = bval; return aux; } if (tipo == 1){ aux.num = val; return aux; } if (tipo == 2){ aux.caracter = caracter[0]; return aux; } if (tipo == 3){ if (id == "me"){ return bot->valor; } else{ return tablasimb[id]; } } if (operador == "NEGACION"){ aux.booleano = !left->evaluar(bot,mapa,space,tablasimb).booleano; } if (operador == "RESTA"){ if (unary){ aux.num = -left->evaluar(bot,mapa,space,tablasimb).num; } else{ aux.num = left->evaluar(bot,mapa,space,tablasimb).num - right->evaluar(bot,mapa,space,tablasimb).num; } } if (operador == "MENOR"){ aux.booleano = left->evaluar(bot,mapa,space,tablasimb).num < right->evaluar(bot,mapa,space,tablasimb).num; } if (operador == "MAYOR"){ aux.booleano = left->evaluar(bot,mapa,space,tablasimb).num > right->evaluar(bot,mapa,space,tablasimb).num; } if (operador == "MAYORIGUAL"){ aux.booleano = left->evaluar(bot,mapa,space,tablasimb).num >= right->evaluar(bot,mapa,space,tablasimb).num; } if (operador == "MENORIGUAL"){ aux.booleano = left->evaluar(bot,mapa,space,tablasimb).num <= right->evaluar(bot,mapa,space,tablasimb).num; } if (operador == "IGUAL"){ aux.booleano = left->evaluar(bot,mapa,space,tablasimb).num == right->evaluar(bot,mapa,space,tablasimb).num or left->evaluar(bot,mapa,space,tablasimb).booleano == right->evaluar(bot,mapa,space,tablasimb).booleano or left->evaluar(bot,mapa,space,tablasimb).caracter == right->evaluar(bot,mapa,space,tablasimb).caracter; } if (operador == "DESIGUAL"){ aux.booleano = left->evaluar(bot,mapa,space,tablasimb).num != right->evaluar(bot,mapa,space,tablasimb).num and left->evaluar(bot,mapa,space,tablasimb).booleano != right->evaluar(bot,mapa,space,tablasimb).booleano and left->evaluar(bot,mapa,space,tablasimb).caracter != right->evaluar(bot,mapa,space,tablasimb).caracter; } if (operador == "CONJUNCION"){ aux.booleano = left->evaluar(bot,mapa,space,tablasimb).booleano and right->evaluar(bot,mapa,space,tablasimb).booleano; } if (operador == "DISYUNCION"){ aux.booleano = left->evaluar(bot,mapa,space,tablasimb).booleano or right->evaluar(bot,mapa,space,tablasimb).booleano; } if (operador == "SUMA"){ aux.num = left->evaluar(bot,mapa,space,tablasimb).num + right->evaluar(bot,mapa,space,tablasimb).num; } if (operador == "MULTIPLICACION"){ aux.num = left->evaluar(bot,mapa,space,tablasimb).num * right->evaluar(bot,mapa,space,tablasimb).num; } if (operador == "DIVISION"){ if (right->evaluar(bot,mapa,space,tablasimb).num == 0){ cout << "Error: division entre 0" << endl; cout << "Linea " << lineNo << endl; exit(0); } aux.num = left->evaluar(bot,mapa,space,tablasimb).num / right->evaluar(bot,mapa,space,tablasimb).num; } if (operador == "MODULO"){ if (right->evaluar(bot,mapa,space,tablasimb).num == 0){ cout << "Error: Modulo entre 0" << endl; cout << "Linea " << lineNo << endl; exit(0); } aux.num = left->evaluar(bot,mapa,space,tablasimb).num % right->evaluar(bot,mapa,space,tablasimb).num; } return aux; } // Funcion que calcula el tipo de una expresion int calcularTipo(MapaDeTipos& mapa,int t){ int aux,aux2; if (tipo == ERRORTIPO){ return tipo; } if (tipo >= 0 and tipo != TIPOID){ return tipo; } if (tipo == TIPOID){ if (id == "me"){ return t; } else if ((aux = mapa.obtenerTipo(id)) != -1){ return aux; } else if (aux == -1){ cout << "Error evaluando expresion. Linea " << lineNo << "." << endl; cout << "Razon: Variable " << id << " no declarada." << endl; return ERRORTIPO; } } if (operador == "NEGACION"){ if (left->calcularTipo(mapa,t) == TIPOBOOL){ return TIPOBOOL; } else{ return ERRORTIPO; } } if (operador == "RESTA" and unary){ if (left->calcularTipo(mapa,t) == TIPOINT){ return TIPOINT; } else{ return ERRORTIPO; } } if (operador == "MENOR" or operador == "MAYOR" or operador == "MENORIGUAL" or operador == "MAYORIGUAL"){ if (left->calcularTipo(mapa,t) == TIPOINT and right->calcularTipo(mapa,t) == TIPOINT){ return TIPOBOOL; } else{ return ERRORTIPO; } } if (operador == "IGUAL" or operador == "DESIGUAL"){ aux = left->calcularTipo(mapa,t); if (aux == ERRORTIPO){ return ERRORTIPO; } if (aux == right->calcularTipo(mapa,t)){ return TIPOBOOL; } else{ return ERRORTIPO; } } if (operador == "CONJUNCION" or operador == "DISYUNCION"){ if (left->calcularTipo(mapa,t) == TIPOBOOL and right->calcularTipo(mapa,t) == TIPOBOOL){ return TIPOBOOL; } else{ return ERRORTIPO; } } if (operador == "SUMA" or (operador == "RESTA" and !unary) or operador == "MULTIPLICACION" or operador == "DIVISION" or operador == "MODULO"){ if (left->calcularTipo(mapa,t) == TIPOINT and right->calcularTipo(mapa,t) == TIPOINT){ return TIPOINT; } else{ return ERRORTIPO; } } return ERRORTIPO; // por si acaso cthulu ataca el codigo y hace que salga de ifs. } //Funcion que recursivamente dice si una expresion compleja contiene el identificador "me" bool contieneMe(){ if (tipo == 3){ if (id == "me"){ return true; } } else if (tipo == -1){ if (unary){ return left->contieneMe(); } else{ return left->contieneMe() or right->contieneMe(); } } else{ return false; } } // Gran funcion que imprime el arbol de expresiones // usa el tipo y si es unario o no para // saber que imprimir // Argumento i que nos dice el numero de tabulaciones necesarias. void toString(int i){ if (tipo != -1){ switch(tipo){ case 0: // caso booleano if (bval){ cout << "true"; } else{ cout << "false"; } cout << endl; break; case 1: // caso numero cout << val << endl; break; case 2: // caso caracter cout << caracter << endl; break; case 3: // caso id cout << id << endl; break; } return; } if (unary){ cout << "Tipo: Unaria" << endl; for (int j = 0; j < i;j++){ //Estas tabulaciones son para mantenernos al cout <<" "; // mismo nivel que el resto del arbol } // en la salida estandar cout << "operacion: " << operador << "." << endl; for (int j = 0; j < i;j++){ cout <<" "; } cout << "operador unico: "; left->toString(i+1); } else{ cout << "Tipo: Binaria." << endl; for (int j = 0; j < i;j++){ cout <<" "; } cout << "operacion: " << operador << endl; for (int j = 0; j < i;j++){ cout <<" "; } cout << "operador izquierdo: "; left->toString(i+1); for (int j = 0; j < i;j++){ cout <<" "; } cout << "operador Derecho: "; right->toString(i+1); } } }; #endif
C
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * *************************************************************/ #define _SNPRINTF_DLLIMPORT __declspec( dllexport ) #include <stdarg.h> #include <stdio.h> #include <tchar.h> #include <systools/win32/snprintf.h> #if defined(_MSC_VER) && (_MSC_VER >= 1400) #pragma warning(disable:4273) // inconsistent dll linkage #endif #if (defined(_MSC_VER) && (_MSC_VER < 1300)) || (defined(__MINGW32_VERSION) && ((__MINGW32_MAJOR_VERSION < 3)||((__MINGW32_MAJOR_VERSION == 3)&&(__MINGW32_MINOR_VERSION < 18)))) /* The non-debug versions of _vscprintf/_scprintf are just calls to _vsprintf/_sprintf with string buffer pointer set to NULL, requires MSVCRT version 7.0 */ #ifdef __MINGW32__ static int __cdecl _vsctprintf( const TCHAR *format, va_list ap ) #else static int __cdecl _vsctprintf( const _TXCHAR *format, va_list ap ) #endif { FILE *fp = _tfopen( _T("NUL"), _T("wb") ); if ( fp ) { int retval = _vftprintf( fp, format, ap ); fclose( fp ); return retval; } return -1; } #endif /* This function retrieves the pointer to the last character of a buffer. That is the pointer to the last character of the buffer that fits completly into that buffer or the position of the terminating zero. buffer Pointer to a _TXCHAR buffer to be examined count size of the buffer to be examined return The pointer to the last character that fits into the buffer or NULL if count is zero or count is one and the first byte was a leading DBCS character */ static _TCHAR *GetLastBufferChar( _TCHAR *buffer, size_t count ) { _TCHAR *last = NULL; _TCHAR *cur = buffer; while ( (size_t)(cur - buffer) < count ) { last = cur; if ( !*last ) break; cur = _tcsinc(last); } return last; } /* Implementation of snprintf following the ISO/IEC 9899:1999 (ISO C99) standard */ _SNPRINTF_DLLIMPORT int __cdecl vsntprintf( _TCHAR *buffer, size_t count, const _TCHAR *format, va_list list ) { int retval; /* First of all call the existing non POSIX standard function assuming the buffer size will be large enough */ retval = _vsntprintf( buffer, count, format, list ); if ( retval < 0 ) { /* If the buffer wasn't large enough ensure that the buffer will be zero terminated */ _TCHAR *last = GetLastBufferChar( buffer, count ); if (last ) *last = 0; /* Retrieve the count of characters that would have been written if the buffer were large enough */ retval = _vsctprintf( format, list ); } else if ( (size_t)retval == count && count ) { /* If the buffer was large enough but not large enough for the trailing zero make the buffer zero terminated */ _TCHAR *last = GetLastBufferChar( buffer, count ); if (last ) *last = 0; } return retval; } /* Implementation of snprintf following the ISO/IEC 9899:1999 (ISO C99) standard */ _SNPRINTF_DLLIMPORT int __cdecl sntprintf( _TCHAR *buffer, size_t count, const _TCHAR *format, ... ) { va_list list; int retval; va_start( list, format ); retval = vsntprintf( buffer, count, format, list ); va_end( list ); return retval; }
C
/************************************************************************* > File Name: name.c > Author: > Mail: > Created Time: 2017年04月15日 星期六 15时47分34秒 ************************************************************************/ #include<stdio.h> void BSort(char a[][10],int size); int strcmp(char str1[],char str2[]); void exchange (char str1[],char str2[]); void mstrcpy(char str1[],char str2[]); int main() { char name[5][10] = {'\0'}; for(int i = 0;i < 5;i++) { scanf("%s",&name[i]); } BSort(name,5); printf("after sort:\n"); for(int i = 0;i < 5;i++) { printf("%s\n",name[i]); } return 0; } void BSort(char a[][10],int size) { for(int i = 0;i < size - 1;i++) { for(int j = 0;j < size - 1 - i;j++) { if(strcmp(a[j],a[j+1]) > 0) { exchange(a[j],a[j+1]); } } } } int strcmp(char str1[],char str2[]) { int i = 0; /* while('\0' != str1[i] && '\0' != str2[i]) { if(str1[i] == str2[i]) { i++; continue; } return str1[i] - str2[i]; }*/ while(str1[i] && str2[i] && str1[i] == str2[i]) { i++; return str1[i] - str2[i]; } return str1[i] - str2[i]; } void exchange (char str1[],char str2[]) { char temp[20] = {'\0'}; mstrcpy(temp,str1); mstrcpy(str1,str2); mstrcpy(str2,temp); } void mstrcpy(char str1[],char str2[]) { int i = 0; while((str1[i] = str2[i]) != '\0') { i++; } }
C
#include <stdio.h> int main() { int i , k =100; int sum=0,sum1= 0 ,sum2=0; for (i=1;i<101;i++) { sum = sum + i; } for (int j = 0; j < 50 ; j++){ sum1 = (k-j) + j; sum2 += sum1; } sum2 = sum2 + 50; printf("1부터 100까지의 합 : %d\n",sum); printf("1부터 100까지의 합 : %d\n",sum2); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <assert.h> #include <limits.h> #include <string.h> #include "floydwarshall.h" #define SQUARE(n) (n * n) #define ARRAY_SET(arr, width, row, col, value) (arr[row * width + col] = value) #define ARRAY_GET(arr, width, row, col) (arr[row * width + col]) #define VALUE (0) #define WEIGHT (1) #define NONE (-1) static apspinfo_t* create_apspinfo_struct(graph_t *graph) { apspinfo_t *apsp = malloc(sizeof(apspinfo_t)); assert(apsp); apsp->dist = malloc(sizeof(int) * SQUARE(graph->size)); assert(apsp->dist); apsp->next = malloc(sizeof(int) * SQUARE(graph->size)); assert(apsp->next); apsp->len = graph->size; // initialize "dist" and "next" tables for (int row = 0; row < graph->size; row++) { for (int col = 0; col < graph->size; col++) { int value = ((row == col) ? 0 : INT_MAX); ARRAY_SET(apsp->dist, graph->size, row, col, value); ARRAY_SET(apsp->next, graph->size, row, col, NONE); } queue_node_t *curr = graph->adjacency_list[row]->head; while (curr != NULL) { int data[2]; memcpy(data, curr->data, sizeof(int) * 2); ARRAY_SET(apsp->dist, graph->size, row, data[VALUE], data[WEIGHT]); ARRAY_SET(apsp->next, graph->size, row, data[VALUE], row); curr = curr->next; } } return apsp; } apspinfo_t* floyd_warshall(graph_t *graph) { apspinfo_t* apsp = create_apspinfo_struct(graph); int from, through, to; // vertices int distance_candidate, d1, d2; for (through = 0; through < graph->size; through++) { for (from = 0; from < graph->size; from++) { for (to = 0; to < graph->size; to++) { d1 = ARRAY_GET(apsp->dist, graph->size, from, through); d2 = ARRAY_GET(apsp->dist, graph->size, through, to); if (d1 == INT_MAX || d2 == INT_MAX) { continue; // a path "from->through->to" does not exist! } distance_candidate = d1 + d2; if (distance_candidate < ARRAY_GET(apsp->dist, graph->size, from, to)) // compare distance candidate with current distance { ARRAY_SET(apsp->dist, graph->size, from, to, distance_candidate); ARRAY_SET(apsp->next, graph->size, from, to, through); } } } } return apsp; } static void print_path(apspinfo_t *apsp, int from, int to) { int prev, next; size_t datasize = sizeof(int); queue_t *path = queue_create(datasize); for (prev = NONE, next = from; next != prev; prev = next, next = ARRAY_GET(apsp->next, apsp->len, prev, to)) { queue_enqueue(path, &next); } queue_enqueue(path, &to); while (path->head != NULL) { queue_dequeue(path, &next); printf("%i", next); if (path->head != NULL) { printf("->"); } } queue_destroy(path); } void floyd_warshall_print(apspinfo_t *apsp) { printf("All-Pairs Shortest Path:\n\n"); for (int from = 0; from < apsp->len; from++) { for (int to = 0; to < apsp->len; to++) { if (from == to) { continue; } int distance = ARRAY_GET(apsp->dist, apsp->len, from, to); if (distance == INT_MAX) { continue; } printf("%i->%i = %i (path: ", from, to, distance); print_path(apsp, from, to); printf(")\n"); } } }
C
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <math.h> int getCoinCount(int cents){ if (cents >= 25){ return cents / 25 + getCoinCount(cents % 25); } else if (cents >= 10){ return cents / 10 + getCoinCount(cents % 10); } else if (cents >= 5){ return cents / 5 + getCoinCount(cents % 5); } return cents; } int main(void){ char input_string[256]; char *pEnd; float changeNeeded; int centsNeeded; printf("O hai! How much change is owed? "); fgets(input_string, 100, stdin); changeNeeded = strtof(input_string, &pEnd); centsNeeded = roundf(changeNeeded * 100); while (changeNeeded <= 0){ printf("Retry: "); fgets(input_string, 100, stdin); changeNeeded = strtof(input_string, &pEnd); centsNeeded = changeNeeded * 100; } printf("%d\n", getCoinCount(centsNeeded)); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_split.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jhong <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/07 21:44:39 by jhong #+# #+# */ /* Updated: 2021/04/07 22:38:19 by jhong ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include <stdio.h> int is_charset(char c, char *charset) { while (*charset) if (c == *charset++) return (1); return (0); } int ft_count_charset(char *str, char *charset) { int cnt; int before; cnt = 1; before = 1; while (*str != 0) { if (is_charset(*str, charset)) { if (!before) cnt++; before = 1; } else before = 0; str++; } if (before) cnt--; return (cnt); } int ft_strstr_pos(char *str, char *charset) { int j; j = -1; while (str[++j] != 0) { if (is_charset(str[j], charset)) return (j); } return (j); } char *ft_strncpy(char *dest, char *str, int len) { while (len--) *dest++ = *str++; *dest = 0; return (str + 1); } char **ft_split(char *str, char *charset) { int i; int len; int size; char **strs; size = ft_count_charset(str, charset); strs = (char**)malloc(sizeof(char*) * (size + 1)); i = 0; while (i < size) { len = ft_strstr_pos(str, charset); if (len == 0) { str++; continue; } strs[i] = (char*)malloc(sizeof(char) * (len + 1)); str = ft_strncpy(strs[i], str, len); i++; } strs[i] = 0; return (strs); }
C
/** @file * A callback system for the cellvm, functions and times * can be pushed into the callback stack and ran every X clock ticks. */ #include <stdio.h> #include "cellvmcb.h" #include "config.h" /** * Get the next free callback slot avalible in the callback_stack. * @param stack Stack to get slot from. * @return Slot number free on success, -1 on fail. */ static int get_slot(const struct callback_stack *stack) { int i, ret; for (ret = -1, i = 0; i < CB_MAX; i++) { if (!stack->is_active[i]) { ret = i; break; } } return ret; } int add_callback(struct callback_stack *stack, callback_fptr function, unsigned int freq, char *symbol) { int slot; struct callback_slot *ptr; /* Get the next free slot, bail if there is none. */ if ((slot = get_slot(stack)) == -1) return -1; ptr = &stack->callbacks[slot]; ptr->function = function; ptr->frequency = freq; /* Set the entry for this slot in the active table to true. */ stack->is_active[slot] = 1; #ifdef DEBUG printf("Callback slot %d/%d assigned, freq:1/%d, address:%p symbol:%s\n", slot, CB_MAX, freq, function, symbol); #endif return slot; } int del_callback(struct callback_stack *stack, int slot) { /* If the slots not active this request is bullshit so dont do anything * if it is we set it to not active, deleting the structure it self is redundent as * all callbacks are checked against the active list first anyway. */ if (stack->is_active[slot]) { stack->is_active[slot] = 0; #ifdef DEBUG printf("Callback slot %d removed, address:%p\n", slot, stack->callbacks[slot].function); #endif return 0; } else return 1; } int do_callbacks(const struct callback_stack *stack, unsigned long reltick, int x, int y, char didstuff) { int i; for (i = 0; i < CB_MAX; i++) /* If the callback slot is active and it is the right tick % freqnecy. */ if (stack->is_active[i] && (!(reltick % stack->callbacks[i].frequency))) stack->callbacks[i].function(x,y, didstuff); return 0; }
C
#include "lists.h" /** * insert_node - malloc and insert node into sorted singly linked list * @head: pointer to head of linked list * @number: data for new node * Return: address of new node, or NULL if failed */ listint_t *insert_node(listint_t **head, int number) { listint_t *tmp = NULL; listint_t *new = NULL; if (!head) return (NULL); /* malloc new node */ new = malloc(sizeof(listint_t)); if (new == NULL) return (NULL); new->n = number; new->next = NULL; /* if no linked list, insert node as the only member */ if (*head == NULL) { *head = new; (*head)->next = NULL; return (new); } /* if only one node in linked list, do comparision and insert */ if ((*head)->next == NULL) { if ((*head)->n < new->n) (*head)->next = new; else { new->next = *head; *head = new; } return (new); } /* if lots of nodes in linked list, do comparision and insert */ tmp = *head; while (tmp->next != NULL) { /* if new node num is smaller than first node, insert */ if (new->n < tmp->n) { new->next = tmp; *head = new; return (new); } /* if new node num is the same as an existing node, insert */ /* compare previous node and next node, insert in between */ if (((new->n > tmp->n) && (new->n < (tmp->next)->n)) || (new->n == tmp->n)) { new->next = tmp->next; tmp->next = new; return (new); } tmp = tmp->next; } /* if new node is greatest and never inserted, insert now */ tmp->next = new; return (new); }
C
#include "common.h" int partition(int arr[], int size, int sep) { requires(size > 0); freeze(ARR, arr); // specification is still incomplete (e.g. ARR=[0,0,1], arr=[0,1, 1]) ensures( forall(t, range(0, ret), arr[t] < sep) && forall(t, range(ret, size), arr[t] >= sep) && forall(t, range(0, size), exists(k, range(0, size), arr[k] == ARR[t])) ); int first = 0; remember(size > 0 && first >= 0); for (; first < size && arr[first] < sep; first++) { assert( first < size && forall(k, range(0, first + 1), arr[k] < sep) && forall(t, range(0, size), exists(k, range(0, size), arr[k] == ARR[t])) ); } if (first == size) { return size; } for (int i = first + 1; i < size; i++) { assert( i > first && i < size && forall(t, range(0, first), arr[t] < sep) && forall(t, range(first, i), arr[t] >= sep) && forall(t, range(0, size), exists(k, range(0, size), arr[k] == ARR[t])) ); if (arr[i] < sep) { int tmp = arr[i]; arr[i] = arr[first]; arr[first] = tmp; first++; } } return first; }
C
#include "msgdist_utils.h" //------------------------------------------------------------------ sinal de encerramento do cliente void serverOffline() { char pipeName[20]; snprintf(pipeName, UTIL_BUFFER_SIZE, CLIENT_PIPE, getpid()); printf("MSGDIST: (CLIENT) Server is offline. Exiting now...\n"); unlink(pipeName); //Remover fifo do cliente exit(0); } //------------------------------------------------------------------ sinal de kick do cliente void kickedFromServer() { char pipeName[20]; snprintf(pipeName, UTIL_BUFFER_SIZE, CLIENT_PIPE, getpid()); printf("MSGDIST: (CLIENT) Server kicked you. Exiting now...\n"); unlink(pipeName); //Remover fifo do cliente exit(0); } //------------------------------------------------------------------ configuração do cliente MSGDIST_CLIENT initClient(char username[UTIL_BUFFER_SIZE]) { INFO_CLIENT sendMSG; int fd_server, n, fd_client; char pipeName[UTIL_BUFFER_SIZE]; MSGDIST_CLIENT client; // Username strncpy(sendMSG.client.username, username, UTIL_BUFFER_SIZE); // ID sendMSG.client.id = getpid(); // Nome do pipe snprintf(pipeName, UTIL_BUFFER_SIZE, CLIENT_PIPE, getpid()); strncpy(sendMSG.client.pipeName, pipeName, UTIL_BUFFER_SIZE); sendMSG.flag = 1; printf("MSGDIST: (CLIENT) Confirming username, sending to server...\n"); // Criar fifo do cliente mkfifo(pipeName, 0600); // Abrir para escrita pipe do servidor fd_server = open(SERVER_PIPE, O_WRONLY); n = write(fd_server, &sendMSG, sizeof (INFO_CLIENT)); //enviar para servidor // Recebe resposta fd_client = open(pipeName, O_RDONLY); n = read(fd_client, &client, sizeof (MSGDIST_CLIENT)); close(fd_client); close(fd_server); if (strcmp(client.username, "maxUser") == 0) { printf("\nMSGDIST: (ERROR) Maximum users in server was reached\n"); sleep(5); exit(EXIT_FAILURE); } else if (strcmp(client.username, username) != 0) { printf("\nMSGDIST: (CLIENT) Username already in use.\n"); } printf("\nMSGDIST: (CLIENT) Username received: %s\n", client.username); sendMSG.flag = 0; return client; } //------------------------------------------------------------------ inserção de um caracter MSG * insert_ch(char c, int index, int line, MSG * msg) { int i; char * phrase = (char*) malloc(sizeof (char)*UTIL_BUFFER_SIZE); index -= 4; switch (line) { case 1: strncpy(phrase, msg->topic, UTIL_BUFFER_SIZE); break; case 3: strncpy(phrase, msg->title, UTIL_BUFFER_SIZE); break; case 5: default: strncpy(phrase, msg->body, UTIL_BODY_SIZE); break; } for (i = UTIL_BUFFER_SIZE; i >= index; i--) { phrase[i] = phrase[i - 1]; } phrase[index] = c; switch (line) { case 1: strncpy(msg->topic, phrase, UTIL_BUFFER_SIZE); break; case 3: strncpy(msg->title, phrase, UTIL_BUFFER_SIZE); break; case 5: default: strncpy(msg->body, phrase, UTIL_BODY_SIZE); break; } free(phrase); return msg; } //------------------------------------------------------------------ remoção de um caracter MSG * delete_ch(int index, int line, MSG * msg) { int i; char *phrase = (char*) malloc(sizeof (char)*UTIL_BUFFER_SIZE); index -= 4; switch (line) { case 1: strncpy(phrase, msg->topic, UTIL_BUFFER_SIZE); break; case 3: strncpy(phrase, msg->title, UTIL_BUFFER_SIZE); break; case 5: default: strncpy(phrase, msg->body, UTIL_BODY_SIZE); break; } for (i = index; i <= UTIL_BUFFER_SIZE; i++) phrase[i] = phrase[i + 1]; phrase[index] = ' '; switch (line) { case 1: strncpy(msg->topic, phrase, UTIL_BUFFER_SIZE); break; case 3: strncpy(msg->title, phrase, UTIL_BUFFER_SIZE); break; case 5: default: strncpy(msg->body, phrase, UTIL_BODY_SIZE); break; } free(phrase); return msg; } //--------------------------------------------------------------------------------- envio de uma mensagem void sendMessage(MSGDIST_CLIENT * client, MSG * msg) { INFO_CLIENT sendMSG; int fd_server, n, fd_client; // Abrir para escrita pipe do servidor fd_server = open(SERVER_PIPE, O_WRONLY); strncpy(sendMSG.msg.topic, msg->topic, UTIL_BUFFER_SIZE); strncpy(sendMSG.msg.title, msg->title, UTIL_BUFFER_SIZE); strncpy(sendMSG.msg.body, msg->body, UTIL_BODY_SIZE); strncpy(sendMSG.msg.client.pipeName, client->pipeName, UTIL_BUFFER_SIZE); sendMSG.msg.client.id = client->id; strncpy(sendMSG.msg.client.username, client->username, UTIL_BUFFER_SIZE); sendMSG.msg.duration = 150; sendMSG.flag = 2; n = write(fd_server, &sendMSG, sizeof (INFO_CLIENT)); //enviar para servidor close(fd_server); int response; // Recebe resposta fd_client = open(client->pipeName, O_RDONLY); n = read(fd_client, &response, sizeof (int)); close(fd_client); if (response == 0) printf("\nMSGDIST: (CLIENT) Your message was received in the server.\n"); else if (response == 1) printf("\nMSGDIST: (CLIENT) Maximum number of messages reached in the server.\n"); else if (response == 2) printf("\nMSGDIST: (CLIENT) Message rejected. Be polite!\n"); } //--------------------------------------------------------------------------------- escreve mensagem void writeMessage(MSGDIST_CLIENT * client) { WINDOW *win; int nrow, ncol, posx, posy, oposx, oposy; int ch, flag = 0; MSG * msg = (MSG*) malloc(sizeof (MSG)); if (!msg) { printf("\nMSGDIST: (ERROR) Memory Allocation in 'cmdRoutineWriteMessage'.\n"); return; } initscr(); clear(); noecho(); cbreak(); keypad(stdscr, TRUE); getmaxyx(stdscr, nrow, ncol); win = newwin(24, 80, 0, 0); posy = 1; posx = 4; refresh(); mvprintw(0, 0, "TOPIC: \n"); mvprintw(1, 0, ">> \n"); mvprintw(2, 0, "TITLE: \n"); mvprintw(3, 0, ">> \n"); mvprintw(4, 0, "MESSAGE: \n"); mvprintw(5, 0, ">> \n"); move(posy, posx); do { ch = getch(); oposy = posy; oposx = posx; switch (ch) { case KEY_UP: if (posy == 3 || posy == 5) { posy -= 2; posx = 4; } else if (posy > 1) { posy--; posx = 4; } break; case KEY_DOWN: if (posy == 1 || posy == 3) { posy += 2; posx = 4; } else if (posy < (nrow - 1)) { posy++; posx = 4; } break; case KEY_LEFT: posx = (posx > 4) ? posx - 1 : posx; break; case KEY_RIGHT: posx = (posx < (ncol - 1)) ? posx + 1 : posx; break; case KEY_BACKSPACE: if (posx > 4) { posx = posx - 1; mvdelch(posy, posx); msg = delete_ch(posx, posy, msg); } break; case USER_KEY_ENTER: flag = 1; break; } if (ch != KEY_UP && ch != KEY_DOWN && ch != KEY_LEFT && ch != KEY_RIGHT && ch != USER_KEY_ENTER && ch != KEY_BACKSPACE) { if (posx <= ncol - 1) { mvinsch(posy, posx, ch); //insert the character before cursor in a curses window msg = insert_ch(ch, posx, posy, msg); if (posx < ncol - 1) { posx = posx + 1; } } } move(posy, posx); refresh(); } while (flag == 0); delwin(win); endwin(); sendMessage(client, msg); free(msg); } //--------------------------------------------------------------------------------- rotina de comandos // CLIENT_TOPICS void cmdRoutineShowTopics(MSGDIST_CLIENT *client) { MSG allMSG[UTIL_MAX_MSG], topics[UTIL_MAX_MSG]; INFO_CLIENT sendMessage; int fd_server, n, fd_client, i, j = 1, k, flag = 0; // Abrir para escrita pipe do servidor fd_server = open(SERVER_PIPE, O_WRONLY); strncpy(sendMessage.client.pipeName, client->pipeName, UTIL_BUFFER_SIZE); sendMessage.client.id = client->id; strncpy(sendMessage.client.username, client->username, UTIL_BUFFER_SIZE); sendMessage.flag = 3; n = write(fd_server, &sendMessage, sizeof (INFO_CLIENT)); //enviar para servidor close(fd_server); // Recebe resposta fd_client = open(client->pipeName, O_RDONLY); n = read(fd_client, &allMSG, sizeof (MSG) * UTIL_MAX_MSG); close(fd_client); if (n != sizeof (allMSG)) { printf("\nMSGDIST: (CLIENT) Error while receiving message from the server.\n"); return; } for (i = 0; i < UTIL_MAX_MSG; i++) { strncpy(topics[i].topic, allMSG[i].topic, UTIL_BUFFER_SIZE); topics[i].flag = -1; } printf("\nMSGDIST: (CLIENT) All topics: \n"); for (i = 0; i < UTIL_MAX_MSG; i++) { if (allMSG[i].flag != -1) { for (k = i - 1; k >= 0; k--) { if (strcmp(topics[i].topic, allMSG[k].topic) == 0) { flag = 1; } } if (flag == 0) { printf("\n %d. Topic: '%s' \n", j++, topics[i].topic); } flag = 0; } } return; } // CLIENT_TITLES void cmdRoutineTitles(char * arg, MSGDIST_CLIENT *client) { MSG allMSG[UTIL_MAX_MSG]; INFO_CLIENT sendMessage; int fd_server, n, fd_client, i, j = 1; // Abrir para escrita pipe do servidor fd_server = open(SERVER_PIPE, O_WRONLY); strncpy(sendMessage.client.pipeName, client->pipeName, UTIL_BUFFER_SIZE); sendMessage.client.id = client->id; strncpy(sendMessage.client.username, client->username, UTIL_BUFFER_SIZE); sendMessage.flag = 3; n = write(fd_server, &sendMessage, sizeof (INFO_CLIENT)); //enviar para servidor close(fd_server); // Recebe resposta fd_client = open(client->pipeName, O_RDONLY); n = read(fd_client, &allMSG, sizeof (MSG) * UTIL_MAX_MSG); close(fd_client); if (n != sizeof (allMSG)) { printf("\nMSGDIST: (CLIENT) Error while receiving message from the server.\n"); return; } printf("\nMSGDIST: (CLIENT) All titles from the topic '%s': \n", arg); for (i = 0; i < UTIL_MAX_MSG; i++) { if (allMSG[i].flag != -1 && strcmp(arg, allMSG[i].topic) == 0) { printf("\n %d. Title: '%s' \n", j, allMSG[i].title); j++; } } return; } // CLIENT_SUBS_TOPIC void cmdRoutineSubscribe(MSGDIST_CLIENT * client) { INFO_CLIENT sendMessage; int fd_server, n, fd_client, r, j = 1, k, flag = -1; char str[UTIL_BUFFER_SIZE]; MSG *allMSG; // Abrir para escrita pipe do servidor fd_server = open(SERVER_PIPE, O_WRONLY); strncpy(sendMessage.client.pipeName, client->pipeName, UTIL_BUFFER_SIZE); sendMessage.client.id = client->id; strncpy(sendMessage.client.username, client->username, UTIL_BUFFER_SIZE); sendMessage.flag = 5; printf("Title of the topic: "); scanf(" %20[^\n]", sendMessage.msg.topic); n = write(fd_server, &sendMessage, sizeof (INFO_CLIENT)); //enviar para servidor close(fd_server); // Recebe resposta fd_client = open(client->pipeName, O_RDONLY); n = read(fd_client, &r, sizeof (int)); close(fd_client); if (r == -1) { //Deixou de subscrever printf("\nMSGDIST: (CLIENT) The client no longer subscribes to the topic '%s'. \n", sendMessage.msg.topic); } if (r == 0) { //Começou a subscrever printf("\nMSGDIST: (CLIENT) The client now subscribes to the topic '%s'. \n", sendMessage.msg.topic); } if (r == 1) { //Topico não existe printf("\nMSGDIST: (CLIENT) The topic '%s' does not exists. \n", sendMessage.msg.topic); } } // CLIENT_SHOW_MESSAGE void cmdRoutineShowMessage(MSGDIST_CLIENT * client) { MSG allMSG[UTIL_MAX_MSG]; INFO_CLIENT sendMessage; int fd_server, n, fd_client, i, j = 1; char arg[UTIL_BUFFER_SIZE], arg1[UTIL_BUFFER_SIZE]; // Abrir para escrita pipe do servidor fd_server = open(SERVER_PIPE, O_WRONLY); strncpy(sendMessage.client.pipeName, client->pipeName, UTIL_BUFFER_SIZE); sendMessage.client.id = client->id; strncpy(sendMessage.client.username, client->username, UTIL_BUFFER_SIZE); sendMessage.flag = 3; n = write(fd_server, &sendMessage, sizeof (INFO_CLIENT)); //enviar para servidor close(fd_server); // Recebe resposta fd_client = open(client->pipeName, O_RDONLY); n = read(fd_client, &allMSG, sizeof (MSG) * UTIL_MAX_MSG); close(fd_client); if (n != sizeof (allMSG)) { printf("\nMSGDIST: (CLIENT) Error while receiving message from the server.\n"); return; } printf("\nTopic of the message: "); scanf(" %20[^\n]", arg1); printf("\nMSGDIST: (CLIENT) Choose one of the titles from the topic '%s': \n", arg1); for (i = 0; i < UTIL_MAX_MSG; i++) { if (allMSG[i].flag != -1 && strcmp(arg1, allMSG[i].topic) == 0) { printf("\n %d. Title: '%s' \n", j, allMSG[i].title); j++; } } printf("Title of the message: "); scanf(" %20[^\n]", arg); j = 0; for (i = 0; i < UTIL_MAX_MSG; i++) { if (allMSG[i].flag != -1 && strcmp(arg, allMSG[i].title) == 0) { printf("\nMSGDIST: (CLIENT) Message with the title '%s': \n", arg); printf("\n\tTopic: '%s'\n", allMSG[i].topic); printf("\tTitle: '%s'\n", allMSG[i].title); printf("\tMessage: '%s'\n\n", allMSG[i].body); j = 1; } } if (j == 0) { printf("\nMSGDIST: (CLIENT) Message with the title '%s' does not exists \n", arg); } } // CLIENT_HELP void cmdRoutineHelp() { printf("MSGDIST: (CLIENT) help:\n" "topics \t list all topics\n" "msg \t write a message\n" "titles <topic> \t list titles from a topic\n" "subscribe <topic> \t subscribe to a topic\n" "showmsg \t show message from a topic\n"); } // CLIENT_SHUTDOWN void cmdRoutineShutdown(char * name) { INFO_CLIENT info; int fd_server, n; char pipeName[20]; info.flag = 4; info.client.id = getpid(); strncpy(info.client.username, name, UTIL_BODY_SIZE); fd_server = open(SERVER_PIPE, O_WRONLY); n = write(fd_server, &info, sizeof (INFO_CLIENT)); //enviar para servidor close(fd_server); printf("\nMSGDIST: (CLIENT) shutting down....\n"); snprintf(pipeName, UTIL_BUFFER_SIZE, CLIENT_PIPE, getpid()); unlink(pipeName); //Remover fifo do cliente exit(0); } // CHAMADA DE FUNÇÕES void cmdRoutine(MSGDIST_CLIENT * client, char * cmd, char * arg) { if (strcmp(cmd, CLIENT_WRITE_MENSAGE) == 0) { writeMessage(client); } else if (strcmp(cmd, CLIENT_TOPICS) == 0) { cmdRoutineShowTopics(client); } else if (strcmp(cmd, CLIENT_TITLES) == 0) { if (strcmp(arg, UTIL_EMPTY) == 0) { printf("MSGDIST: (ERROR) This command needs an argument. Try 'help'\n"); } else { cmdRoutineTitles(arg, client); } } else if (strcmp(cmd, CLIENT_SUBS_TOPIC) == 0) { cmdRoutineSubscribe(client); } else if (strcmp(cmd, CLIENT_HELP) == 0) { cmdRoutineHelp(); } else if (strcmp(cmd, CLIENT_SHOW_MESSAGE) == 0) { cmdRoutineShowMessage(client); } else if (strcmp(cmd, CLIENT_SHUTDOWN) == 0) { cmdRoutineShutdown(client->username); } else { printf("MSGDIST: (ERROR) Command not found.\n"); putchar('\n'); } } // -------------------------------------------------------------- leitura de comandos void readRoutineCommands(MSGDIST_CLIENT * client) { char cmd[UTIL_BUFFER_SIZE]; char * argument; do { fflush(stdout); fflush(stdin); printf("MSGDIST@CLIENT >> "); scanf(" %19[^\n]s", cmd); // Separação do pedido recebido em comando e argumento strtok_r(cmd, " ", &argument); cmdRoutine(client, cmd, argument); } while (1); } int main(int argc, char* argv[], char * envp[]) { MSGDIST_CLIENT client; struct sigaction offlineSignal, kickSignal; // Leitura dos argumentos na linha de comandos if (argc != 2) { printf("MSGDIST: (ERROR) Number of agrs!\n"); exit(EXIT_FAILURE); } // Verificar se o servidor se encontra ativo if (access(SERVER_PIPE, F_OK) != 0) { printf("MSGDIST: (ERROR) Server is offline!\n"); exit(EXIT_FAILURE); } printf("MSGDIST: (CLIENT) initialized with PID %d\n\n", getpid()); client = initClient(argv[1]); offlineSignal.sa_flags = SA_SIGINFO; offlineSignal.sa_sigaction = serverOffline; kickSignal.sa_flags = SA_SIGINFO; kickSignal.sa_sigaction = kickedFromServer; sigaction(SIGUSR1, &offlineSignal, NULL); sigaction(SIGUSR2, &kickSignal, NULL); readRoutineCommands(&client); }
C
#include "fdf.h" t_vec3 *vec3(double x, double y, double z) { t_vec3 *ret; ret = malloc(sizeof(*ret)); ret->x = x; ret->y = y; ret->z = z; return (ret); } double vec3_length(const t_vec3 *v) { return (sqrt(v->x * v->x + v->y * v->y + v->z * v->z)); } double vec3_dot(const t_vec3 *a, const t_vec3 *b) { return (a->x * b->x + a->y * b->y + a->z * b->z); } void vec3_normalize(t_vec3 *v) { double len; double inv_len; len = vec3_dot(v, v); if (len > 0) { inv_len = 1 / sqrt(len); v->x *= inv_len; v->y *= inv_len; v->z *= inv_len; } } t_vec3 *vec3_cross(const t_vec3 *a, const t_vec3 *b) { t_vec3 *ret; ret = malloc(sizeof(*ret)); ret->x = a->y * b->z - a->z * b->y; ret->y = a->z * b->x - a->x * b->z; ret->z = a->x * b->y - a->y * b->x; return (ret); }
C
// sjf with arrival time - non preemptive #include<stdio.h> // function declarations void bubbleSort(int* burstTime, int* ArrivalTime, int* processNo, int n); void sjfsort(int* burstTime, int* ArrivalTime, int* processNo, int n); void swap(int* num1, int* num2); void computeStartTime(int* startTime, int* burstTime, int processCount); void computeWaitingTime(int* WaitTime, int* ArrivalTime, int* startTime, int processCount); void computeTurnAroundTime(int* BurstTime, int* turnAroundTime, int* WaitTime, int processCount); float AverageTime(int Time[], int n); int main(){ int n; printf("Enter number of processes: "); scanf("%d", &n); int burst_time[n], startTime[n], arrival_time[n], wait_time[n], turn_around_time[n], process_no[n], i; float avgWaitTime = 0, avgTurnArndTime = 0; // to read process burst time and arrival time for(i = 0; i < n; i++){ printf("Enter arrival time and burst time of process %d: ", i+1); scanf("%d %d", &arrival_time[i], &burst_time[i]); process_no[i] = i+1; } // sorting the jobs, burst time and arrival time depending on the process which has shortest burst time bubbleSort(burst_time, arrival_time, process_no, n); sjfsort(burst_time, arrival_time, process_no, n); // computations computeStartTime(startTime, burst_time, n); computeWaitingTime(wait_time, arrival_time, startTime, n); computeTurnAroundTime(burst_time, turn_around_time, wait_time, n); avgWaitTime = AverageTime(wait_time, n); avgTurnArndTime = AverageTime(turn_around_time, n); // Display the output printf("\nProcess no.\t burst time \t waiting time \t turnaround time \t arrival time\n"); for(i = 0; i < n; i++){ printf(" P[%d]%14d%18d%20d%18d\n", process_no[i], burst_time[i], wait_time[i], turn_around_time[i], arrival_time[i]); } printf("Average Waiting time = %.2f\n", avgWaitTime); printf("Average Turn around time = %.2f\n", avgTurnArndTime); return 0; } void swap(int* num1, int* num2){ int temp = *num1; *num1 = *num2; *num2 = temp; } // sort acc to arrival time void bubbleSort(int* burstTime, int* ArrivalTime, int* processNo, int n){ int i, j, temp; for(i = 0; i < n; i++){ for(j = 0; j < n-i-1; j++){ if(ArrivalTime[j] > ArrivalTime[j+1]){ swap(&burstTime[j], &burstTime[j+1]); swap(&processNo[j], &processNo[j+1]); swap(&ArrivalTime[j], &ArrivalTime[j+1]); } } } } // sort acc to burst time and availability of processes at a particalar arrival time void sjfsort(int* burstTime, int* ArrivalTime, int* processNo, int n){ int timecompleted = 0; int i, j; for(i = 0; i < n; i++){ int swapwithindex = i; for(j = i+1; j < n; j++){ if(ArrivalTime[j] <= timecompleted){ if(burstTime[j] < burstTime[i]){ swapwithindex = j; } } } swap(&burstTime[i], &burstTime[swapwithindex]); swap(&processNo[i], &processNo[swapwithindex]); swap(&ArrivalTime[i], &ArrivalTime[swapwithindex]); timecompleted += burstTime[i]; } } void computeStartTime(int* startTime, int* burstTime, int processCount){ int i; startTime[0] = 0; for(i = 1; i < processCount; i++){ startTime[i] = startTime[i-1] + burstTime[i-1]; } } void computeWaitingTime(int* WaitTime, int* ArrivalTime, int* start_time, int processCount){ int i; WaitTime[0] = 0; for(i = 1; i < processCount; i++){ WaitTime[i] = start_time[i] - ArrivalTime[i]; } } void computeTurnAroundTime(int* BurstTime, int* turnAroundTime, int* WaitTime, int processCount){ int i; turnAroundTime[0] = BurstTime[0]; for(i = 1; i < processCount; i++){ turnAroundTime[i] = WaitTime[i] + BurstTime[i]; } } float AverageTime(int Time[], int n){ int i; float avg = 0; for(i = 0; i < n; i++){ avg += Time[i]; } return avg/n; }
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int main(void) { int num1; printf("num1를 입력하세요\n"); scanf("%d", &num1); if ((num1 >> 31) == 0) printf("%d는(은) 양수입니다. 이 수의 절댓값은 %d이고, 절댓값을 4로 나눈 몫은 %d이고, 나머지는 %d입니다.", num1, num1,num1 / 4, num1 % 4); else printf("%d는(은) 음수입니다. 이 수의 절댓값은 %d이고, 절댓값을 4로 나눈 몫은 %d이고, 나머지는 %d입니다.", num1, -(num1), -(num1) / 4, -(num1) % 4); return 0; }
C
/* Problems 3.60 - 3.70 */ /* 3.60 */ // A. A[i][j][k] = Xd + L(i*S*T + j*T + k) // in this problem L = 4; // B. S = 9, T = 11, R = 5; // (S*T = 99) (T = 11) (S*T*R) = 1980/4; /* 3.61 */ // As my IDE doesn't support C99.. so I'm no sure whether or not my answer is right. // There are 4 value that must bu used : Arow, Brow, result and 4*n // so there are only one element that used to check the bounds //int var_prod_else(int n, int A[n][n], int B[n][n], int i, int k) //{ // int result = 0; // int *p_A = &A[i][0]; // int *p_B = &B[0][k]; // int *pEnd = &A[i][n]; // // while (p_A != pEnd) // { // result += *p_A * *p_B; // p_B += n; // p_A++; // A[i+1][j]; // } // // return result; //} /* 3.62 */ // A. M = 13. (52/4) // B. %edi -> i , %ecx -> j // line 8 & 9 // The sample version of code using a resiger (%ebx) to save the adress of A[j][i] // and then add an offset to update A[j+1][i]. MeanWhile it use another resiger (%esi) // to save the base adress of A[i][x] // C. // The same as above. My IDE doesn't support C99 so.. //void transpose(int M, int A[M][M]) //{ // int i, j; // int t = 0; // int *p_row; // int *p_col; // // for (i = 0; i < M; i++) // { // p_row = &A[i][0]; // use a variable to save base address // p_col = &A[0][j]; // the same above // for (j = 0; j < M, j++) // { // t = *p_row; // *p_row = *p_col; // *p_col = t; // p_row++; // A[i+1] same as line 5 in assmbly // p_col += M; // add offset // } // } //} /* 3.63 */ // E1(n) = 2n+1 // deduced from line 7 . 8 // E2(n) = 12n // deduce from line 9 & 19 /* 3.64 */ // A. 8(%ebp) = &result , 12(%ebp) = s1.a , 16(%ebp) = s1.p // It's very simple to draw the soultion // B. offset value // take %ebp as standard of 0 // 12 y // 8 x // 4 return address (prod) // 0 saved %ebp (current %ebp as well) // -4 s2.diff // -8 s2.sum // -12 s1.p // -16 s1.a // -20 adress of s2 (s2.sum's adress, That is offset -8) // -24 return adress (word_sum) // after call word_sum // C. push the initial adress of the structure in. // D. directly update the value of acceptor, through the passed adress. /* 3.65 */ // It seems to be 92/2 = 46 = A*B and 12 = B // But if B = 12 the &u should be 12*2 + 4 + 12 = 40 but no 36 // So, there must be alignment there. A*B could be either 46 or 45 // and B could be 9 , 10 or 11. Notice that both A and B are integer // A = 5 and B = 9 is right answer. /* 3.66 */ // This problem is so hard to me that I have take a lot of time trying to solve it. // lines operations comments // 3 mov 0x8(%ebp), %eax ; i -> %eax // 6 mov 0xc(%ebp), %ecx ; &bp -> %ecx // 9 lea (%eax,%eax,4), %eax ; 5i -> %eax // c add 0x4(%ecx,%eax,4), %eax ; [bp+20i+4] + 5i = x -> %eax // 10 mov 0xb8(%ecx), %edx ; [bp+0xb8] -> %edx // 16 add (%ecx), %edx ; [bp] + [bp+0xb8] = n -> %edx // 18 mov %edx, 0x8(%ecx,%eax,4) ; n -> [bp + 4*x + 8] // As we see that [bp] and [b+0xb8] should be denote bp->left and bp->right respectively // Then we can deduce that size(a[])*CNT = 180 /*size(a[]) no equal sizeof(a[])*/ and // we can deduce that Add(ap->x[ap->idx]) = bp + 4*x + 8 -(1). Meanwhile the address of // Add(ap->x[0]) = bp + 4 + size(a[]) + offset // offset is offset between a[i] and s[] // then Add(ap->x[ap->idx]) = bp + 4 + size(a[])*i + offset + sizeof(x[])*idx -(2) // So acc to (1)(2) 4 + 4*x = size(a[])*i + offset + sizeof(x[])*idx // That is 4 + 4*([bp+20i+4]) + 20*i = size(a[])*i + offset + sizeof(x[])*idx // Then we can guess that [bp+20i+4] is ap->idx and sothat offset = 4; // so 20*i + 4*idx = size(a[])*i + sizeof(x[])*idx // and size(a[]) = 20 sizeof(x[]) = 4 is the possible and most reasonable result // And CNT = 180/20 = 9 // Since sizeof(s[]) = 4 we can fill this structure //struct a_struct //{ // int idx; // int s[4]; //}; /* 3.67 */ // A. e1.p: 0, e1.y: 4, e2.x: 0, e2.next: 4; // B. 8 // C. //void proc(union ele *up) //{ // up->e2.next->e1.y = *(up->e2.next->e1.p) - (up->e1.y); //} // Can be simply deduced form the assmbly code. Far more easier than the last problem... /* 3.68 */ //// It just the basics of the c language. If you want to using fgets(), just remeber to check boundary //#include <stdio.h> // //void good_echo(void) //{ // int c = 0; // store EOF // // while (c = getchar(), c != '\n' && c != EOF) putchar(c); // // putchar(10); //} // // //int main() //{ // good_echo(); //} /* 3.69 */ // A. #include <stdio.h> #include <limits.h> typedef struct ELE *tree_ptr; struct ELE { tree_ptr left; tree_ptr right; long val; }; long trace(tree_ptr tp) { while (tp->left != NULL) tp = tp->left; return tp->val; } // B. // return the value of the leftmost subtree. /* 3.70 */ // long traverse(tree_ptr tp); // tp in %rdi // lines operations comments // 2 movq %rbx, -24(%rsp) ; save register // 3 movq %rbp, -16(%rsp) ; // 4 movq %r12, -8(%rsp) ; // 5 subq $24, %rsp ; deduct 24 for spaces // 6 movq %rdi, %rbp ; &tp -> rbp // the current tp // 7 movabsq $-9223372036854775808, %rax ; LONG_MIN -> rax // 8 testq %rdi, %rdi ; if tp == NULL // 9 je .L9 ; then goto .L9 // 10 movq (%rdi), %rbx ; save the current val // 11 movq 8(%rdi), %rdi ; tp->left -> rdi // undate rdi // 12 call traverse ; // 13 movq %rax, %r12 ; returnval -> r12 // 14 movq 16(%rbp), %rdi ; tp->right -> rdi // 15 call traverse ; // 16 cmpq %rax, %r12 ; If r12 >= rax // 17 cmovge %r12, %rax ; then r12 -> rax // 18 cmpq %rbx, %rax ; If rax < rbx // 19 cmovl %rbx, %rax ; then rbx -> rax // That is put the biggest one in right &left return and currentval into the rax. // 20 .L9 // 21 movq (%rsp), %rbx ; retrive register // 22 movq 8(%rsp), %rbp ; // 23 movq 16(%rsp), %r12 ; // 24 addq $24, %rsp ; release spaces // 25 ret ; return the rax That is the biggest value // I'm not sure whether the use of lines 2.3.4 & 21.22.23 are to save register or not. long traverse(tree_ptr tp) { if (tp == NULL) return LONG_MIN; return Min(tp->val, traverse(tp->left), traverse(tp->right)); } // B. return the smallest value in the tree.
C
void print(struct student *phead)// { struct student *p ; int t=0; system("cls"); if(count==0) { gotoxy(15,3); printf("Բ𣬵ǰûѧ!\n"); } else { gotoxy(15,3); printf("=================================================\n"); gotoxy(15,4); printf("|"); gotoxy(63,4); printf("|"); for(p=phead->next;p!=NULL;p=p->next) { gotoxy(28,5+t*8); printf("%dλͬѧ",t+1); gotoxy(15,5+t*8); printf("|"); gotoxy(63,5+t*8); printf("|"); gotoxy(25,6+t*8); printf("ID=%s",p->ID); gotoxy(15,6+t*8); printf("|"); gotoxy(63,6+t*8); printf("|"); gotoxy(25,7+t*8); printf("=%s",p->name); gotoxy(15,7+t*8); printf("|"); gotoxy(63,7+t*8); printf("|"); gotoxy(25,8+t*8); printf("=%lf",p->score[0]); gotoxy(15,8+t*8); printf("|"); gotoxy(63,8+t*8); printf("|"); gotoxy(25,9+t*8); printf("ѧ=%lf",p->score[1]); gotoxy(15,9+t*8); printf("|"); gotoxy(63,9+t*8); printf("|"); gotoxy(25,10+t*8); printf("Ӣ=%lf",p->score[2]); gotoxy(15,10+t*8); printf("|"); gotoxy(63,10+t*8); printf("|"); gotoxy(25,11+t*8); printf("ƽ:%lf",p->avg); gotoxy(15,11+t*8); printf("|"); gotoxy(63,11+t*8); printf("|"); gotoxy(25,12+t*8); printf("******************************"); t++; } gotoxy(15,13+(t-1)*8); printf("=================================================\n"); } gotoxy(28,15+(t-1)*8); printf("˵\n"); getch(); }
C
/* Program to illustrate the difference of prefix and postfix decrementing. Author: Kollen Gruizenga */ #include <stdio.h> int main(){ printf("I will be using two variables, A and B, both integers to demonstrate pre and post decrementing.\n\n"); int A=1; int B=0; printf("A value is %d, B value is %d.\n",A,B); B = A++ * 10; printf("Now, setting B to (A++ * 10) yields: %d\n",B); printf("A value is %d, B value is %d.\n",A,B); A = 1; B = 0; printf("\nNow let's start over and try the other way.\n"); printf("A value is %d, B value is %d.\n",A,B); B = ++A * 10; printf("Setting B to (++A * 10) yields: %d\n",B); return 0; }
C
// General setup File //Tempature Functions headers float celToFrah(float); float frahToCel(float); float getTemp(); // changed from into to float int getStatus(); int prevTemp = 0; // keeps track of the previous temp inorder to regulate display output int overHeat = 0; // over heat toggle state variable int sensorValue = 0; //potentiometer sensor value int pot = A0; //potentiometer pin float temp = 32.0; //temperature; // initialized to 32.0 but that changes as soon as the potentiometer has a value char mode = 'F'; // global mode character // this might not be a good practice // Warning_Alert - Variables int buzzer_tone_val = 500; // modify this value to change output tone/ frequency int alert_status=1; int warning_Buzzer = 9; // 8-ohm speaker on digital pin 9 int warning_LED = 13; // Buzzer connected to pin 13 //Tempature Functions float celToFrah(float Celsius) { float Fahrenheit = (9.0/5.0)*(Celsius) + 32.0; mode = 'F'; // sets mode to Fahrenheit return Fahrenheit; } float frahToCel(float Fahrenheit) { float Celsius = (5.0/9.0)*(Fahrenheit - 32.0); mode = 'C'; // sets mode to celsius return Celsius; } float getTemp(){ int sensorValue = analogRead(A0);// read the input of the potentiometer (0 - 1023) //added int temp = .1173*sensorValue; // scale to F return temp; } int getStatus(){ // gets the current status if(getTemp() > 100){ return 1; } return 0; } void lcdDisplay() { lcd.setCursor(0, 0); lcd.print("Temp: "); lcd.print(temp); lcd.print(mode); lcd.setCursor(0, 1); if(temp < 10 && prevTemp >= 10){ lcd.clear(); } if(getStatus()==1){ lcd.print("Alr: OVERHEATING"); overHeat = 1; } else{ //delay(2000); if(overHeat == 1){ lcd.clear(); overHeat = 0; } } prevTemp = temp; } void checkWarning() { // Warning_alert (Buzzer, LED) alert_status = getStatus(); if (alert_status==1){ digitalWrite(warning_LED, HIGH); // LED turned ON // BUZZER ON (map the buzzer_tone_val to a range for the speaker) tone(9, 440 * pow(2.0, (constrain(int(map(buzzer_tone_val, 0, 1023, 36, 84)), 35, 127) - 57) / 12.0), 1000); // delay(10); // Delay a little bit to improve simulation performance } else { digitalWrite(warning_LED, LOW); // LED turned OFF // BUZZER OFF (map the ZERO to a range for the speaker) tone(9, 0 * pow(2.0, (constrain(int(map(0, 0, 1023, 36, 84)), 35, 127) - 57) / 12.0), 1000); } } void setup() { // set up the LCD's number of columns and rows: lcd.begin(16, 2); pinMode(pot, INPUT); pinMode(warning_LED, OUTPUT); // Warning LED pinMode(warning_Buzzer, OUTPUT); // Buzzer }
C
/* * serial.c * * Created on: Jan 14, 2019 * Author: Collin Maker * * */ #include "msp.h" #include "globals.h" #include "serial.h" //================================================================================ //Initializes UART for serial communications //================================================================================ void UART0_init(void) { /*ONLY WORKS FOR BAUD OF 19200*/ EUSCI_A0->CTLW0 |=1; //Reset register=1 to allow config EUSCI_A0->MCTLW = 0;// Disable oversampling EUSCI_A0->CTLW0 = 0x0081; //1 S bit, no parity, SMCLK, 8-bit data EUSCI_A0->BRW = 26; /*3MHz SMCLK/115200 = 26.0416 */ P1->SEL0 |= 0x0C; //Setup pins 1.3 & 1.2 for UART communication P1->SEL1 &=~ 0x0C; EUSCI_A0->CTLW0 &=~ 1; //End config of EUSCI EUSCI_A0->IE |= 0x01; //Interrupt enable NVIC_SetPriority(EUSCIA0_IRQn, 4); NVIC_EnableIRQ(EUSCIA0_IRQn); } //================================================================================ //Function used to see if a full command has been received, if returns true // call ReadFromBuffer to parse command from buffer //================================================================================ int CheckFullCommand() { int i; for(i=RxReadIndex; i!=RxWriteIndex; i = (i+1)%BUFFER_SIZE) { if(RxBuffer[i] == NEWLINE_CHAR) { RxReadTo = i; return 1; } } return 0; //Command not yet finished } //================================================================================ //Function will read from previous RxReadIndex up until the RxReadTo set in CheckFullCommand() //================================================================================ void ReadFromBuffer() { int i = 0; for(RxReadIndex; RxReadIndex != RxReadTo; RxReadIndex = (RxReadIndex + 1) % BUFFER_SIZE) { RxRead[i++] = RxBuffer[RxReadIndex]; } RxRead[i] = '\0'; RxReadIndex++; //Moves past the newline character UARTFlag = 0; } //================================================================================ //Function will repeat the last received and parsed command from the computer // back to the computer //================================================================================ void EchoCommand() { int i; for(i = 0; i < BUFFER_SIZE; i++) { if(RxRead[i] == '\0') { break; } while((EUSCI_A0->IFG&0x02) == 0); EUSCI_A0->TXBUF=RxRead[i]; } }
C
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<fcntl.h> int main() { int fd1,fd2; char buf[1024]; char buf2[1024]; memset(buf2,'\0',sizeof(buf2)); memset(buf,'\0',sizeof(buf)); fd1 = open("simple.txt",O_RDONLY); fd2 = open("simple.txt",O_RDONLY); read(fd1,buf,4); printf("%s\n",buf); read(fd2,buf2,4); printf("%s\n",buf2); close(fd1); close(fd2); fd1 = open("simple.txt",O_RDONLY); fd2 = dup(fd1); read(fd1,buf,4); printf("%s\n",buf); read(fd2,buf2,4); printf("%s\n",buf2); close(fd1); close(fd2); return 0; }
C
#include<stdio.h> #include<conio.h> void main() { int num,i=40,r=70; printf("print odd number in a given range i to r:"); for (num=i;num<=r;num++) { if(num%2==1) printf("%d",num); } getch(); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <fcntl.h> #include <string.h> #define READ 0 #define WRITE 1 #define TAMANIO 100 int main (){ int bandera = 0; //bandera para finalizar el programa int p[2]; //pipe pipe(p); pid_t pid; //creo el proceso pid = fork(); while (bandera == 0){ //mientras la bandera sea 0 char mensaje[TAMANIO]; //leeo el mensaje scanf("%s",&mensaje); if(pid < 0){ //mensaje de error si hay problemas con la creacion del proceso printf("error\n"); return -1; } if(pid == 0){ //hijo close(p[WRITE]); //obtengo el mensaje mediante el pipe read(p[READ],mensaje, strlen(mensaje)+1); if(mensaje == "termina"){ //si el mensaje es termina imprime id del proceso hijo y cambia el valor de bandera printf("Proceso %d terminado\n",getpid()); bandera = 1; }else { // sino es termina el mensaje imprime el mensaje printf("MENSAJE: %s\n",mensaje); } close(p[READ]); }else { //padre close(p[READ]); //manda el mensaje por pipe write(p[WRITE],mensaje,strlen(mensaje) + 1); close(p[WRITE]); } } printf("Proceso %d terminado",getpid()); //cuando bandera == 1 imprime el id del proceso padre return 1; }
C
#include <time.h> #include "camera_cmd.h" void callback(int percentage, char* filename){ //((part_idx*100)/max_row) printf("\b\b\b\b\b%4d%%",percentage); fflush(stdout); } int main(int argc, char **argv) { if (argc != 3 && argc != 4) { fprintf(stderr, "Usage: %s <ip_port> <mote_id> [<img_type>]\n\t where img_type: 2=bw_jpg(default) 3=col_jpg 0=bw_raw 1=col_raw", argv[0]); exit(2); } int port = atoi(argv[1]); printf("connecting to serialforwarder: localhost:%d\n",port); comm_init("localhost", port); int node_id = atoi(argv[2]); int img_type = 2; if (argc==4) img_type=atoi(argv[3]); char filename[1024]; int ret=0; sprintf(filename,"./test%d",(int)time(NULL)); printf("sending img request to node %d: ",node_id); printf("%d\n",send_img_cmd(node_id, img_type)); printf("img: 0%%"); ret = receive_img(node_id, 0, filename, &callback); printf("\n"); if (ret==-1) printf("no pkts received!\n"); return 0; }
C
/************************************************************************************** Author: Stav Ofer Creation date: 2013-08-08 Last modified date: 2013-08-16 Description: Memory management functions, in method of contiguous allocation. Overhead: metadata of each block, general metadata at start and end of memory chunk. Requries externally assigned memory chunk, with size of at least sizeof(MPool) + 4*block_metadata (usually 4 bytes) "Weak" defragmentation: when accessing a free block (in MPOOLALLOC or -FREE), if following blocks are free - merging is performed. Note: MPool may not start at the exact beginning of the memory chunk; ***************************************************************************************/ #ifndef __MPOOL_H__ #define __MPOOL_H__ /* metadata for internal use, located at beginning of memory chunk */ typedef struct MPool MPool; /* Initialize memory chunck for use. Input: _mem - handle to memory chunck _size - size in bytes Output: handle to MPool */ MPool* MPoolInit (void *_mem, int _size); /* Allocate a block of memory to user Input: _mPool _size - # of bytes to allocate Output: handle to allocated memory block if not enough memory - return NULL same if size=0 */ void* MPoolAlloc (MPool* _mPool, int _size); /* Free memory blocks Input: - _mPool - block to free Output: none if block does not belong to MPool: undefined behavior if block already free: may merge with following block(s) */ void MPoolFree (MPool* _mPool, void* _blockFree); #endif /* __MPOOL_H__ */
C
#include <stdio.h> /** * program that prints all the arguments without using ac * @av: argument vector * Return: 1 upon success **/ int main(int ac, char **av) { int x; if (ac > 0) { for (x = 0; x < ac; x++) printf("%s\n", av[x]); } return (1); }
C
#include "unp.h" //若成功返回未连接套接字描述符,出错则不返回 int Udp_client(const char *host, const char *serv, SA **saptr, socklen_t *lenp) { int sockfd, n; struct addrinfo hints, *res, *ressave; bzero(&hints, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; //用于转化hostname,service参数 if((n = getaddrinfo(host, serv, &hints, &res)) != 0) err_quit("udp_client error for %s, %s: %s", host, serv, gai_strerror(n)); ressave = res; do{ sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if(sockfd >= 0) break; }while((res->ai_next) != NULL); if((res == NULL)) err_sys("udp_lient error for %s, %s", host, serv); //malloc用于分配一套接字地址结构的内存空间 *saptr = Malloc(res->ai_addrlen); //把对应创建的套接字的地址结构复制到这个内存空间 memcpy(*saptr, res->ai_addr, res->ai_addrlen); *lenp = res->ai_addrlen; freeaddrinfo(ressave); return sockfd; } int main(int argc, char *argv[]) { int sockfd, n; char recvline[MAXLINE + 1]; socklen_t salen; struct sockaddr *sa; if(argc != 3) err_quit("uage: daytimeudpcli1 <hostname/IPaddress> <service/port#>"); //调用Udp——client函数,然后显示将向其发送UDP数据报的服务器的IP地址和端口号。 sockfd = Udp_client(argv[1], argv[2], (void**) &sa, &salen); printf ("sending to %s\n", Sock_ntop_host(sa, salen)); Sendto(sockfd, "", 1, 0, sa, salen); n = Recvfrom(sockfd, recvline, MAXLINE, 0, NULL, NULL); recvline[n] = '\0'; Fputs(recvline, stdout); exit(0); }
C
/** * 在数的对二的补码表示中,我们编写的itoa函数不能处理最大的负数,即n = -2 ^ (字长 - 1)的情况,请解释其原因. * 修改该函数,使它在任何机器上运行时都能打印出正确的值. */ #include <stdio.h> #include <limits.h> #define abs(x) ((x) < 0 ? -(x) : (x)) void itoa(int n, char s[]); void itoa2(int n, char s[]); void reverse(char s[], int n); int main(){ char s[100]; itoa(12345, s); printf("n=%s\n", s); itoa(INT_MIN, s); printf("n_min=%s\n", s); itoa2(12345, s); printf("n2=%s\n", s); itoa2(INT_MIN, s); printf("n2_min=%s\n", s); return 0; } void itoa(int n, char s[]){ int sign, i = 0; if(n < 0){ sign = 0; n = -n; }else{ sign = 1; } do{ s[i++] = n % 10 + '0'; }while((n /= 10) > 0); if(sign == 0) s[i++] = '-'; s[i] = '\0'; reverse(s, i); } void itoa2(int n, char s[]){ int sign, i = 0; if(n < 0){ sign = 0; n = -n; }else{ sign = 1; } do{ s[i++] = abs(n % 10) + '0'; }while((n /= 10) != 0); if(sign == 0) s[i++] = '-'; s[i] = '\0'; reverse(s, i); } //反转字符串 void reverse(char s[], int n){ int i, j, tmp; i = 0, j = n - 1; while(i < j){ tmp = s[i]; s[i++] = s[j]; s[j--] = tmp; } }
C
#pragma once #include<stdbool.h> typedef int datatype; typedef struct Stack { datatype *val; int size; int capacity; }Stack; //ʼջ //void init(Stack* s); //ջ void extend(Stack* s); //ջ void pushStack(Stack* s, datatype val); //ջ void popStack(Stack* s); //ջԪ datatype return_top(Stack* s); //ջЧ int return_num(Stack* s); //жջǷΪ bool is_empty(Stack* s); //ջ //void destory(Stack* s);
C
#include "graph.h" #define GRAPH_PAGE 10000 #define LINE_PAGE 10000 #define GRAPH_NUM_POOL 5 #define TOLERANCE 1e-9 int cmp_double(const void * a, const void * b) { if (*(double*)a > *(double*)b) return 1; else if (*(double*)a < *(double*)b) return -1; else return 0; } int cmp_vert(const void * a, const void * b) { double pos1 = *(double *)(((struct sort_by_idx *)a)->data); double pos2 = *(double *)(((struct sort_by_idx *)b)->data); if (pos1 < pos2) return 1; else if (pos1 > pos2) return -1; else return 0; } int get_i(int pos, int len, int rev){ if (!rev) return pos; else return len - 1 - pos; } int cmp_color(bmp_color color1, bmp_color color2){ /* compare colors, by RGB values */ return color1.r == color2.r && color1.g == color2.g && color1.b == color2.b; } bmp_color validate_color (bmp_color color, bmp_color list[], bmp_color subst[], int len){ /* verify if color is in substitution list and return a valid color */ /* if not substitution list, return default color */ if (subst == NULL) return color; /* if not indicate especific colors, every color is substituted by first in list */ if (list == NULL) return subst[0]; int i; for (i = 0; i < len; i++){ /* sweep the list */ if (cmp_color(color, list[i])){ /* if in list, get the relative substitute */ return subst[i]; } } return color; /* return default color */ } void * graph_mem_pool2(enum graph_pool_action action){ static graph_pool_slot graph, line; int i; void *ret_ptr = NULL; /* initialize the graph pool, the first allocation */ if (graph.size < 1){ graph.pool[0] = malloc(GRAPH_PAGE * sizeof(graph_obj)); if (graph.pool){ graph.size = 1; //printf("Init graph\n"); } } /* initialize the lines pool, the first allocation */ if (line.size < 1){ line.pool[0] = malloc(LINE_PAGE * sizeof(line_node)); if (line.pool){ line.size = 1; //printf("Init line\n"); } } /* if current page is full */ if ((graph.pos >= GRAPH_PAGE) && (graph.size > 0)){ /* try to change to page previuosly allocated */ if (graph.page < graph.size - 1){ graph.page++; graph.pos = 0; //printf("change graph page\n"); } /* or then allocatte a new page */ else if(graph.page < GRAPH_POOL_PAGES-1){ graph.pool[graph.page + 1] = malloc(GRAPH_PAGE * sizeof(graph_obj)); if (graph.pool[graph.page + 1]){ graph.page++; graph.size ++; graph.pos = 0; //printf("Realloc graph\n"); } } } /* if current page is full */ if ((line.pos >= LINE_PAGE) && (line.size > 0)){ /* try to change to page previuosly allocated */ if (line.page < line.size - 1){ line.page++; line.pos = 0; //printf("change line page\n"); } /* or then allocatte a new page */ else if(line.page < GRAPH_POOL_PAGES-1){ line.pool[line.page + 1] = malloc(LINE_PAGE * sizeof(line_node)); if (line.pool[line.page + 1]){ line.page++; line.size ++; line.pos = 0; //printf("Realloc line\n"); } } } ret_ptr = NULL; if ((graph.pool[graph.page] != NULL) && (line.pool[line.page] != NULL)){ switch (action){ case ADD_GRAPH: if (graph.pos < GRAPH_PAGE){ ret_ptr = &(((graph_obj *)graph.pool[graph.page])[graph.pos]); graph.pos++; } break; case ADD_LINE: if (line.pos < LINE_PAGE){ ret_ptr = &(((line_node *)line.pool[line.page])[line.pos]); line.pos++; } break; case ZERO_GRAPH: graph.pos = 0; graph.page = 0; break; case ZERO_LINE: line.pos = 0; line.page = 0; break; case FREE_ALL: for (i = 0; i < graph.size; i++){ free(graph.pool[i]); graph.pool[i] = NULL; } graph.pos = 0; graph.page = 0; graph.size = 0; for (i = 0; i < line.size; i++){ free(line.pool[i]); line.pool[i] = NULL; } line.pos = 0; line.page = 0; line.size = 0; break; } } return ret_ptr; } void * graph_mem_pool(enum graph_pool_action action, int idx){ static graph_pool_slot graph[GRAPH_NUM_POOL], line[GRAPH_NUM_POOL]; int i; void *ret_ptr = NULL; if ((idx >= 0) && (idx < GRAPH_NUM_POOL)){ /* check if index is valid */ /* initialize the graph pool, the first allocation */ if (graph[idx].size < 1){ graph[idx].pool[0] = malloc(GRAPH_PAGE * sizeof(graph_obj)); if (graph[idx].pool){ graph[idx].size = 1; //printf("Init graph\n"); } } /* initialize the lines pool, the first allocation */ if (line[idx].size < 1){ line[idx].pool[0] = malloc(LINE_PAGE * sizeof(line_node)); if (line[idx].pool){ line[idx].size = 1; //printf("Init line\n"); } } /* if current page is full */ if ((graph[idx].pos >= GRAPH_PAGE) && (graph[idx].size > 0)){ /* try to change to page previuosly allocated */ if (graph[idx].page < graph[idx].size - 1){ graph[idx].page++; graph[idx].pos = 0; //printf("change graph page\n"); } /* or then allocatte a new page */ else if(graph[idx].page < GRAPH_POOL_PAGES-1){ graph[idx].pool[graph[idx].page + 1] = malloc(GRAPH_PAGE * sizeof(graph_obj)); if (graph[idx].pool[graph[idx].page + 1]){ graph[idx].page++; graph[idx].size ++; graph[idx].pos = 0; //printf("Realloc graph\n"); } } } /* if current page is full */ if ((line[idx].pos >= LINE_PAGE) && (line[idx].size > 0)){ /* try to change to page previuosly allocated */ if (line[idx].page < line[idx].size - 1){ line[idx].page++; line[idx].pos = 0; //printf("change line page\n"); } /* or then allocatte a new page */ else if(line[idx].page < GRAPH_POOL_PAGES-1){ line[idx].pool[line[idx].page + 1] = malloc(LINE_PAGE * sizeof(line_node)); if (line[idx].pool[line[idx].page + 1]){ line[idx].page++; line[idx].size ++; line[idx].pos = 0; //printf("Realloc line\n"); } } } ret_ptr = NULL; if ((graph[idx].pool[graph[idx].page] != NULL) && (line[idx].pool[line[idx].page] != NULL)){ switch (action){ case ADD_GRAPH: if (graph[idx].pos < GRAPH_PAGE){ ret_ptr = &(((graph_obj *)graph[idx].pool[graph[idx].page])[graph[idx].pos]); graph[idx].pos++; } break; case ADD_LINE: if (line[idx].pos < LINE_PAGE){ ret_ptr = &(((line_node *)line[idx].pool[line[idx].page])[line[idx].pos]); line[idx].pos++; } break; case ZERO_GRAPH: graph[idx].pos = 0; graph[idx].page = 0; break; case ZERO_LINE: line[idx].pos = 0; line[idx].page = 0; break; case FREE_ALL: for (i = 0; i < graph[idx].size; i++){ free(graph[idx].pool[i]); graph[idx].pool[i] = NULL; } graph[idx].pos = 0; graph[idx].page = 0; graph[idx].size = 0; for (i = 0; i < line[idx].size; i++){ free(line[idx].pool[i]); line[idx].pool[i] = NULL; } line[idx].pos = 0; line[idx].page = 0; line[idx].size = 0; break; } } } return ret_ptr; } graph_obj * graph_new(int pool_idx){ /* create new graphics object */ /* allocate the main struct */ //graph_obj * new_obj = malloc(sizeof(graph_obj)); graph_obj * new_obj = graph_mem_pool(ADD_GRAPH, pool_idx); if (new_obj){ /* initialize */ new_obj->owner = NULL; new_obj->pool_idx = pool_idx; /* initialize with a black color */ new_obj->color.r = 0; new_obj->color.g = 0; new_obj->color.b =0; new_obj->color.a = 255; /*new_obj->rot = 0; new_obj->scale = 1; new_obj->ofs_x = 0; new_obj->ofs_y = 0;*/ new_obj->tick = 0.0; //new_obj->thick_const = 0; //new_obj->fill = 0; new_obj->flags = 0; /* initialize with a solid line pattern */ new_obj->patt_size = 1; new_obj->pattern[0] = 1.0; int i; for (i = 0; i < 20; i++){ new_obj->cmplx_pat[i] = NULL; } /* extent init */ //new_obj->ext_ini = 0; new_obj->ext_min_x = 0.0; new_obj->ext_min_y = 0.0; new_obj->ext_min_z = 0.0; new_obj->ext_max_x = 0.0; new_obj->ext_max_y = 0.0; new_obj->ext_max_z = 0.0; new_obj->img = NULL; new_obj->u[0] = 1.0; new_obj->u[1] = 0.0; new_obj->u[2] = 0.0; new_obj->v[0] = 0.0; new_obj->v[1] = 1.0; new_obj->v[2] = 0.0; /* allocate the line list */ //new_obj->list = malloc(sizeof(line_node)); new_obj->list = graph_mem_pool(ADD_LINE, pool_idx); if(new_obj->list){ /* the list is empty */ new_obj->list->next = NULL; } else{ /* if allocation fails */ //free(new_obj); /* clear the main struct */ new_obj = NULL; } } return new_obj; } void line_add(graph_obj * master, double x0, double y0, double z0, double x1, double y1, double z1){ /* create and add a line object to the graph masters list */ if (master){ //line_node *new_line = malloc(sizeof(line_node)); line_node *new_line = graph_mem_pool(ADD_LINE, master->pool_idx); if (new_line){ new_line->x0 = x0; new_line->y0 = y0; new_line->z0 = z0; new_line->x1 = x1; new_line->y1 = y1; new_line->z1 = z1; new_line->next = NULL; if(master->list->next == NULL){ /* check if list is empty */ /* then, the new line is the first element */ master->list->next = new_line; } else{ /* look for the end of list */ line_node *tmp = master->list->next; while(tmp->next != NULL){ tmp = tmp->next; } /* then, the new line is put in end of list */ tmp->next = new_line; } /*update the extent of graph */ /* sort the coordinates of entire line*/ double min_x = (x0 <= x1) ? x0 : x1; double min_y = (y0 <= y1) ? y0 : y1; double min_z = (z0 <= z1) ? z0 : z1; double max_x = (x0 > x1) ? x0 : x1; double max_y = (y0 > y1) ? y0 : y1; double max_z = (z0 > z1) ? z0 : z1; if (!(master->flags & EXT_INI)){ master->flags |= EXT_INI; master->ext_min_x = min_x; master->ext_min_y = min_y; master->ext_min_z = min_z; master->ext_max_x = max_x; master->ext_max_y = max_y; master->ext_max_z = max_z; } else{ master->ext_min_x = (master->ext_min_x <= min_x) ? master->ext_min_x : min_x; master->ext_min_y = (master->ext_min_y <= min_y) ? master->ext_min_y : min_y; master->ext_min_z = (master->ext_min_z <= min_z) ? master->ext_min_z : min_z; master->ext_max_x = (master->ext_max_x > max_x) ? master->ext_max_x : max_x; master->ext_max_y = (master->ext_max_y > max_y) ? master->ext_max_y : max_y; master->ext_max_z = (master->ext_max_z > max_z) ? master->ext_max_z : max_z; } } } } void graph_merge(graph_obj * master, graph_obj *tail){ if ((master) && (tail)){ line_node *new_line = tail->list->next; if (new_line){ if(master->list->next == NULL){ /* check if list is empty */ /* then, the new line is the first element */ master->list->next = new_line; } else{ /* look for the end of list */ line_node *tmp = master->list->next; while(tmp->next != NULL){ tmp = tmp->next; } /* then, the new line is put in end of list */ tmp->next = new_line; } /*update the extent of graph */ /* sort the coordinates of entire line*/ if (!(master->flags & EXT_INI)){ master->flags |= EXT_INI; master->ext_min_x = tail->ext_min_x; master->ext_min_y = tail->ext_min_y; master->ext_min_z = tail->ext_min_z; master->ext_max_x = tail->ext_max_x; master->ext_max_y = tail->ext_max_y; master->ext_max_z = tail->ext_max_z; } else{ master->ext_min_x = (master->ext_min_x < tail->ext_min_x) ? master->ext_min_x : tail->ext_min_x; master->ext_min_y = (master->ext_min_y < tail->ext_min_y) ? master->ext_min_y : tail->ext_min_y; master->ext_min_z = (master->ext_min_z < tail->ext_min_z) ? master->ext_min_z : tail->ext_min_z; master->ext_max_x = (master->ext_max_x > tail->ext_max_x) ? master->ext_max_x : tail->ext_max_x; master->ext_max_y = (master->ext_max_y > tail->ext_max_y) ? master->ext_max_y : tail->ext_max_y; master->ext_max_z = (master->ext_max_z > tail->ext_max_z) ? master->ext_max_z : tail->ext_max_z; } } } } void graph_draw(graph_obj * master, bmp_img * img, double ofs_x, double ofs_y, double scale){ if ((master != NULL) && (img != NULL)){ if(master->list->next){ /* check if list is not empty */ int x0, y0, x1, y1, ok = 1; double xd0, yd0, xd1, yd1; line_node *current = master->list->next; int corners = 0, prev_x, prev_y; /* for fill */ int corner_x[10000], corner_y[10000], stroke[10000]; /* set the pattern */ patt_change(img, master->pattern, master->patt_size); /* set the color */ img->frg = master->color; /* set the tickness */ if (master->flags & THICK_CONST) img->tick = (int) round(master->tick); else img->tick = (int) round(master->tick * scale); /* draw the lines */ while(current){ /*sweep the list content */ /* apply the scale and offset */ ok = 1; ok &= !(isnan(xd0 = round((current->x0 - ofs_x) * scale))); ok &= !(isnan(yd0 = round((current->y0 - ofs_y) * scale))); ok &= !(isnan(xd1 = round((current->x1 - ofs_x) * scale))); ok &= !(isnan(yd1 = round((current->y1 - ofs_y) * scale))); //y0 = (int) round((current->y0 - ofs_y) * scale); //x1 = (int) round((current->x1 - ofs_x) * scale); //y1 = (int) round((current->y1 - ofs_y) * scale); if (ok){ x0 = (int) xd0; y0 = (int) yd0; x1 = (int) xd1; y1 = (int) yd1; bmp_line(img, xd0, yd0, xd1, yd1); //printf("%f %d %d %d %d\n", scale, x0, y0, x1, y1); if ((master->flags & FILLED) && (corners < 10000)){ /* check if object is filled */ /*build the lists of corners */ if (((x0 != prev_x)||(y0 != prev_y))||(corners == 0)){ corner_x[corners] = x0; corner_y[corners] = y0; stroke[corners] = 0; corners++; } corner_x[corners] = x1; corner_y[corners] = y1; stroke[corners] = 1; corners++; prev_x = x1; prev_y = y1; } } current = current->next; /* go to next */ } if ((master->flags & FILLED) && corners < 10000){ /* check if object is filled */ /* draw a filled polygon */ bmp_poly_fill(img, corners, corner_x, corner_y, stroke); } } } } int graph_draw2(graph_obj * master, bmp_img * img, double ofs_x, double ofs_y, double scale){ if ((master == NULL) || (img == NULL)) return 0; /* check if list is not empty */ if (master->list == NULL) return 0; if (master->list->next == NULL) return 0; double x0, y0, x1, y1; double dx, dy, modulus, sine, cosine; line_node *current = master->list->next; int i, iter; /* set the pattern */ patt_change(img, (double[]){1.0,}, 1); /* set the color */ img->frg = master->color; /* set the tickness */ if (master->flags & THICK_CONST) img->tick = (int) round(master->tick); else img->tick = (int) round(master->tick * scale); if (master->patt_size > 1) { /* if graph is dashed lines */ int patt_i = 0, patt_a_i = 0, patt_p_i = 0, draw; double patt_len = 0.0, patt_int, patt_part, patt_rem = 0.0, patt_acc, patt_rem_n; double patt_start_x = 0, patt_start_y = 0; double patt_start = 0; double p1x, p1y, p2x, p2y; double last; /* get the pattern length */ for (i = 0; i < master->patt_size && i < 20; i++){ patt_len += fabs(master->pattern[i]); } //patt_len *= scale; /*first vertice*/ if (current){ x0 = current->x0; y0 = current->y0; x1 = current->x1; y1 = current->y1; /* get polar parameters of line */ dx = x1 - x0; dy = y1 - y0; modulus = sqrt(pow(dx, 2) + pow(dy, 2)); cosine = 1.0; sine = 0.0; if (modulus > TOLERANCE){ cosine = dx/modulus; sine = dy/modulus; } /* find the start point of pattern, based in line - axis interceptions*/ patt_start_x = x0; patt_start_y = y0; patt_start = 0; if (fabs(dy) > TOLERANCE){ patt_start_x = (dy * x0 - dx * y0) / dy; patt_start_x /= 2; }else patt_start_x = 0; if (fabs(dx) > TOLERANCE){ patt_start_y = (dx * y0 - dy * x0) / dx; patt_start_y /= 2; }else patt_start_y = 0; /*find distance between pattern start and segment's first point */ if (fabs(cosine) > TOLERANCE){ patt_start = (patt_start_x - x0)/ cosine; } else if (fabs(sine) > TOLERANCE){ patt_start = (patt_start_y - y0)/ sine; } /* find the pattern initial conditions for the first point*/ if (patt_start <= 0){ /* start of pattern outside segment */ patt_start = fabs(fmod(patt_start, patt_len)); patt_acc = fabs(master->pattern[0]); for (i = 1; i < master->patt_size && i < 20; i++){ patt_i = i - 1; if (patt_start <= patt_acc){ patt_rem = (patt_acc - patt_start); break; } patt_acc += fabs(master->pattern[i]); } } else { /* start of pattern on segment -> reverse the search */ patt_start = fabs(fmod(patt_start, patt_len)); patt_acc = fabs(master->pattern[master->patt_size - 1]); for (i = 1; i < master->patt_size && i < 20; i++){ patt_i = master->patt_size - i; if (patt_start <= patt_acc){ patt_rem = fabs(master->pattern[patt_i]) - (patt_acc - patt_start); break; } patt_acc += fabs(master->pattern[patt_i - 1]); } } } /* draw the lines */ while(current){ /*sweep the list content */ x0 = current->x0; y0 = current->y0; x1 = current->x1; y1 = current->y1; /* get polar parameters of line */ dx = x1 - x0; dy = y1 - y0; modulus = sqrt(pow(dx, 2) + pow(dy, 2)); cosine = 1.0; sine = 0.0; if (modulus > TOLERANCE){ cosine = dx/modulus; sine = dy/modulus; } /* initial point */ draw = master->pattern[patt_i] >= 0.0; p1x = ((x0 - ofs_x) * scale); p1y = ((y0 - ofs_y) * scale); if (patt_rem <= modulus){ /* current segment needs some iterations over pattern */ /* find how many interations over whole pattern */ patt_part = modf((modulus - patt_rem)/patt_len, &patt_int); patt_part *= patt_len; /* remainder for the next step*/ /* find how many interations over partial pattern */ patt_a_i = 0; patt_p_i = patt_i; if (patt_rem > 0) patt_p_i++; if (patt_p_i >= master->patt_size) patt_p_i = 0; patt_acc = fabs(master->pattern[patt_p_i]); patt_rem_n = patt_part; /* remainder pattern for next segment continues */ if (patt_part < patt_acc) patt_rem_n = patt_acc - patt_part; last = modulus - patt_int*patt_len - patt_rem; /* the last stroke (pattern fractional part) of current segment*/ for (i = 0; i < master->patt_size && i < 20; i++){ patt_a_i = i; if (patt_part < patt_acc) break; last -= fabs(master->pattern[patt_p_i]); patt_p_i++; if (patt_p_i >= master->patt_size) patt_p_i = 0; patt_acc += fabs(master->pattern[patt_p_i]); patt_rem_n = patt_acc - patt_part; } /* first stroke - remainder of past pattern*/ p2x = patt_rem * scale * cosine + p1x; p2y = patt_rem * scale * sine + p1y; if (patt_rem > 0) { patt_i++; if (patt_i >= master->patt_size) patt_i = 0; if (draw){ bmp_line_norm(img, p1x, p1y, p2x, p2y, -sine, cosine); } } patt_rem = patt_rem_n; /* for next segment */ p1x = p2x; p1y = p2y; /* draw pattern */ iter = (int) (patt_int * (master->patt_size)) + patt_a_i; for (i = 0; i < iter; i++){ draw = master->pattern[patt_i] >= 0.0; p2x = fabs(master->pattern[patt_i]) * scale * cosine + p1x; p2y = fabs(master->pattern[patt_i]) * scale * sine + p1y; if (draw){ bmp_line_norm(img, p1x, p1y, p2x, p2y, -sine, cosine); } p1x = p2x; p1y = p2y; patt_i++; if (patt_i >= master->patt_size) patt_i = 0; } p2x = last * scale * cosine + p1x; p2y = last * scale * sine + p1y; draw = master->pattern[patt_i] >= 0.0; if (draw) bmp_line_norm(img, p1x, p1y, p2x, p2y, -sine, cosine); } else{ /* current segment is in same past iteration pattern */ p2x = modulus * scale * cosine + p1x; p2y = modulus * scale * sine + p1y; patt_rem -= modulus; if (draw){ bmp_line_norm(img, p1x, p1y, p2x, p2y, -sine, cosine); } p1x = p2x; p1y = p2y; } current = current->next; /* go to next */ } } else{ /* for continuous lines*/ while(current){ /*sweep the list content */ /* apply the scale and offset */ x0 = (current->x0 - ofs_x) * scale; y0 =(current->y0 - ofs_y) * scale; x1 = (current->x1 - ofs_x) * scale; y1 = (current->y1 - ofs_y) * scale; /* get polar parameters of line */ dx = x1 - x0; dy = y1 - y0; modulus = sqrt(pow(dx, 2) + pow(dy, 2)); cosine = 1.0; sine = 0.0; if (modulus > TOLERANCE){ cosine = dx/modulus; sine = dy/modulus; } if (master->pattern[0] >= 0.0) bmp_line_norm(img, x0, y0, x1, y1, -sine, cosine); current = current->next; /* go to next */ } } if (master->flags & FILLED){ graph_fill(master, img, ofs_x, ofs_y, scale); } } int graph_draw3(graph_obj * master, bmp_img * img, struct draw_param param){ if ((master == NULL) || (img == NULL)) return 0; /* check if list is not empty */ if (master->list == NULL) return 0; if (master->list->next == NULL) return 0; double x0, y0, x1, y1; double dx, dy, modulus, sine, cosine; line_node *current = master->list->next; int i, iter; /* if has a bitmap image associated */ if (master->img){ /* apply offset an scale */ /* insertion point is first vertice */ current = master->list->next; x0 = (current->x0 - param.ofs_x) * param.scale; y0 =(current->y0 - param.ofs_y) * param.scale; double u[3], v[3]; u[0] = master->u[0] * param.scale; u[1] = master->u[1] * param.scale; u[2] = master->u[2] * param.scale; v[0] = master->v[0] * param.scale; v[1] = master->v[1] * param.scale; v[2] = master->v[2] * param.scale; /* draw bitmap image */ bmp_put(master->img, img, x0, y0, u, v); } /* set the pattern */ patt_change(img, (double[]){1.0,}, 1); /* set the color */ img->frg = validate_color(master->color, param.list, param.subst, param.len_subst); /* set the tickness */ if (master->flags & THICK_CONST) img->tick = (int) round(master->tick) + param.inc_thick; else img->tick = (int) round(master->tick * param.scale) + param.inc_thick; if (master->patt_size > 1) { /* if graph is dashed lines */ int patt_i = 0, patt_a_i = 0, patt_p_i = 0, draw; double patt_len = 0.0, patt_int, patt_part, patt_rem = 0.0, patt_acc, patt_rem_n; double p1x, p1y, p2x, p2y; double last; /* get the pattern length */ for (i = 0; i < master->patt_size && i < 20; i++){ patt_len += fabs(master->pattern[i]); } //patt_len *= param.scale; /*first vertice*/ if (current){ x0 = current->x0; y0 = current->y0; x1 = current->x1; y1 = current->y1; /* get polar parameters of line */ dx = x1 - x0; dy = y1 - y0; modulus = sqrt(pow(dx, 2) + pow(dy, 2)); cosine = 1.0; sine = 0.0; if (modulus > TOLERANCE){ cosine = dx/modulus; sine = dy/modulus; } } /* draw the lines */ while(current){ /*sweep the list content */ x0 = current->x0; y0 = current->y0; x1 = current->x1; y1 = current->y1; /* get polar parameters of line */ dx = x1 - x0; dy = y1 - y0; modulus = sqrt(pow(dx, 2) + pow(dy, 2)); cosine = 1.0; sine = 0.0; if (modulus > TOLERANCE){ cosine = dx/modulus; sine = dy/modulus; } /* initial point */ draw = master->pattern[patt_i] >= 0.0; p1x = ((x0 - param.ofs_x) * param.scale); p1y = ((y0 - param.ofs_y) * param.scale); if (patt_rem <= modulus){ /* current segment needs some iterations over pattern */ /* find how many interations over whole pattern */ patt_part = modf((modulus - patt_rem)/patt_len, &patt_int); patt_part *= patt_len; /* remainder for the next step*/ /* find how many interations over partial pattern */ patt_a_i = 0; patt_p_i = patt_i; if (patt_rem > 0) patt_p_i++; if (patt_p_i >= master->patt_size) patt_p_i = 0; patt_acc = fabs(master->pattern[patt_p_i]); patt_rem_n = patt_part; /* remainder pattern for next segment continues */ if (patt_part < patt_acc) patt_rem_n = patt_acc - patt_part; last = modulus - patt_int*patt_len - patt_rem; /* the last stroke (pattern fractional part) of current segment*/ for (i = 0; i < master->patt_size && i < 20; i++){ patt_a_i = i; if (patt_part < patt_acc) break; last -= fabs(master->pattern[patt_p_i]); patt_p_i++; if (patt_p_i >= master->patt_size) patt_p_i = 0; patt_acc += fabs(master->pattern[patt_p_i]); patt_rem_n = patt_acc - patt_part; } /* first stroke - remainder of past pattern*/ p2x = patt_rem * param.scale * cosine + p1x; p2y = patt_rem * param.scale * sine + p1y; if (patt_rem > 0) { /*------------- complex line type ----------------*/ if (master->cmplx_pat[patt_i] != NULL && /* complex element */ p2x > img->clip_x && p2x < (img->clip_x + img->clip_w) && /* inside bound parameters */ p2y > img->clip_y && p2y < (img->clip_y + img->clip_h) ) { list_node *cplx = master->cmplx_pat[patt_i]->next; graph_obj *cplx_gr = NULL; line_node *cplx_lin = NULL; /* sweep the main list */ while (cplx != NULL){ if (cplx->data){ cplx_gr = (graph_obj *)cplx->data; cplx_lin = cplx_gr->list->next; /* draw the lines */ while(cplx_lin){ /*sweep the list content */ double xd0 = p2x + ((cplx_lin->x0 * cosine - cplx_lin->y0 * sine) * param.scale); double yd0 = p2y + ((cplx_lin->x0 * sine + cplx_lin->y0 * cosine) * param.scale); double xd1 = p2x + ((cplx_lin->x1 * cosine - cplx_lin->y1 * sine) * param.scale); double yd1 = p2y + ((cplx_lin->x1 * sine + cplx_lin->y1 * cosine) * param.scale); bmp_line(img, xd0, yd0, xd1, yd1); cplx_lin = cplx_lin->next; /* go to next */ } } cplx = cplx->next; } } /*------------------------------------------------------*/ patt_i++; if (patt_i >= master->patt_size) patt_i = 0; if (draw){ bmp_line_norm(img, p1x, p1y, p2x, p2y, -sine, cosine); } } patt_rem = patt_rem_n; /* for next segment */ p1x = p2x; p1y = p2y; /* draw pattern */ iter = (int) (patt_int * (master->patt_size)) + patt_a_i; for (i = 0; i < iter; i++){ draw = master->pattern[patt_i] >= 0.0; p2x = fabs(master->pattern[patt_i]) * param.scale * cosine + p1x; p2y = fabs(master->pattern[patt_i]) * param.scale * sine + p1y; if (draw){ bmp_line_norm(img, p1x, p1y, p2x, p2y, -sine, cosine); } p1x = p2x; p1y = p2y; /*------------- complex line type ----------------*/ if (master->cmplx_pat[patt_i] != NULL && /* complex element */ p1x > img->clip_x && p1x < (img->clip_x + img->clip_w) && /* inside bound parameters */ p1y > img->clip_y && p1y < (img->clip_y + img->clip_h) ) { list_node *cplx = master->cmplx_pat[patt_i]->next; graph_obj *cplx_gr = NULL; line_node *cplx_lin = NULL; /* sweep the main list */ while (cplx != NULL){ if (cplx->data){ cplx_gr = (graph_obj *)cplx->data; cplx_lin = cplx_gr->list->next; /* draw the lines */ while(cplx_lin){ /*sweep the list content */ double xd0 = p1x + ((cplx_lin->x0 * cosine - cplx_lin->y0 * sine) * param.scale); double yd0 = p1y + ((cplx_lin->x0 * sine + cplx_lin->y0 * cosine) * param.scale); double xd1 = p1x + ((cplx_lin->x1 * cosine - cplx_lin->y1 * sine) * param.scale); double yd1 = p1y + ((cplx_lin->x1 * sine + cplx_lin->y1 * cosine) * param.scale); bmp_line(img, xd0, yd0, xd1, yd1); cplx_lin = cplx_lin->next; /* go to next */ } } cplx = cplx->next; } } /*------------------------------------------------------*/ patt_i++; if (patt_i >= master->patt_size) patt_i = 0; } p2x = last * param.scale * cosine + p1x; p2y = last * param.scale * sine + p1y; draw = master->pattern[patt_i] >= 0.0; if (draw) bmp_line_norm(img, p1x, p1y, p2x, p2y, -sine, cosine); } else{ /* current segment is in same past iteration pattern */ p2x = modulus * param.scale * cosine + p1x; p2y = modulus * param.scale * sine + p1y; patt_rem -= modulus; if (draw){ bmp_line_norm(img, p1x, p1y, p2x, p2y, -sine, cosine); } p1x = p2x; p1y = p2y; } current = current->next; /* go to next */ } } else{ /* for continuous lines*/ while(current){ /*sweep the list content */ /* apply the scale and offset */ x0 = (current->x0 - param.ofs_x) * param.scale; y0 =(current->y0 - param.ofs_y) * param.scale; x1 = (current->x1 - param.ofs_x) * param.scale; y1 = (current->y1 - param.ofs_y) * param.scale; /* get polar parameters of line */ dx = x1 - x0; dy = y1 - y0; modulus = sqrt(pow(dx, 2) + pow(dy, 2)); cosine = 1.0; sine = 0.0; if (modulus > TOLERANCE){ cosine = dx/modulus; sine = dy/modulus; } if (master->pattern[0] >= 0.0) bmp_line_norm(img, x0, y0, x1, y1, -sine, cosine); current = current->next; /* go to next */ } } if (master->flags & FILLED){ graph_fill(master, img, param.ofs_x, param.ofs_y, param.scale); } } void graph_line_t(bmp_img *img, double x0, double y0, double x1, double y1, double norm_x, double norm_y, double thick){ if (thick > 2){ int x_0 = (int) round(x0), y_0 = (int) round(y0); int x_1 = (int) round(x1), y_1 = (int) round(y1); if ((x_0 == x_1) && (y_0 == y_1)){ /* a dot*/ bmp_circle_fill(img, x_0, y_0, thick/2); } else { int vert_x[4], vert_y[4]; vert_x[0] = (int) round(x0 - norm_x); vert_x[1] = (int) round(x0 + norm_x); vert_x[3] = (int) round(x1 - norm_x); vert_x[2] = (int) round(x1 + norm_x); vert_y[0] = (int) round(y0 - norm_y); vert_y[1] = (int) round(y0 + norm_y); vert_y[3] = (int) round(y1 - norm_y); vert_y[2] = (int) round(y1 + norm_y); bmp_rect_fill(img, vert_x, vert_y); } } else{ if (line_clip(img, &x0, &y0, &x1, &y1)) { int x_0 = (int) round(x0), y_0 = (int) round(y0); int x_1 = (int) round(x1), y_1 = (int) round(y1); if ((x_0 == x_1) && (y_0 == y_1)){ /* a dot*/ bmp_point_raw (img, x_0, y_0); } else bmp_thin_line(img, x_0, y_0, x_1, y_1); } } } void graph_draw_fix(graph_obj * master, bmp_img * img, double ofs_x, double ofs_y, double scale, bmp_color color){ if ((master != NULL) && (img != NULL)){ if(master->list->next){ /* check if list is not empty */ int x0, y0, x1, y1, ok = 1; double xd0, yd0, xd1, yd1; line_node *current = master->list->next; int corners = 0, prev_x, prev_y; /* for fill */ int corner_x[1000], corner_y[1000], stroke[1000]; /* set the pattern */ patt_change(img, master->pattern, master->patt_size); /* set the color */ img->frg = color; /* set the tickness */ if (master->flags & THICK_CONST) img->tick = (int) round(master->tick) + 3; else img->tick = (int) round(master->tick * scale) + 3; /* draw the lines */ while(current){ /*sweep the list content */ /* apply the scale and offset */ ok = 1; ok &= !(isnan(xd0 = round((current->x0 - ofs_x) * scale))); ok &= !(isnan(yd0 = round((current->y0 - ofs_y) * scale))); ok &= !(isnan(xd1 = round((current->x1 - ofs_x) * scale))); ok &= !(isnan(yd1 = round((current->y1 - ofs_y) * scale))); //x0 = (int) round((current->x0 - ofs_x) * scale); //y0 = (int) round((current->y0 - ofs_y) * scale); //x1 = (int) round((current->x1 - ofs_x) * scale); //y1 = (int) round((current->y1 - ofs_y) * scale); if (ok){ x0 = (int) xd0; y0 = (int) yd0; x1 = (int) xd1; y1 = (int) yd1; bmp_line(img, xd0, yd0, xd1, yd1); //bmp_line(img, x0, y0, x1, y1); //printf("%f %d %d %d %d\n", scale, x0, y0, x1, y1); if ((master->flags & FILLED) && (corners < 1000)){ /* check if object is filled */ /*build the lists of corners */ if (((x0 != prev_x)||(y0 != prev_y))||(corners == 0)){ corner_x[corners] = x0; corner_y[corners] = y0; stroke[corners] = 0; corners++; } corner_x[corners] = x1; corner_y[corners] = y1; stroke[corners] = 1; corners++; prev_x = x1; prev_y = y1; } } current = current->next; /* go to next */ } if ((master->flags & FILLED) && corners){ /* check if object is filled */ /* draw a filled polygon */ bmp_poly_fill(img, corners, corner_x, corner_y, stroke); } } } } void graph_arc(graph_obj * master, double c_x, double c_y, double c_z, double radius, double ang_start, double ang_end, int sig){ if (master){ int n = 32; /* number of interpolation vertices - good fit */ double ang; int steps, i; double x0, y0, x1, y1, step; ang_start *= M_PI/180; ang_end *= M_PI/180; ang = (ang_end - ang_start) * sig; /* total angle of arc */ if (ang <= 0){ ang = ang + 2*M_PI;} /* get step increment in loop */ step = ang/(double) n; /* first point */ x0 = c_x + radius * cos(ang_start); y0 = c_y + radius * sin(ang_start); /* starts loop at second point */ for (i = 1; i < n; i++){ x1 = c_x + radius * cos(step * i * sig + ang_start); y1 = c_y + radius * sin(step * i * sig + ang_start); line_add(master, x0, y0, c_z, x1, y1, c_z); x0=x1; y0=y1; } /* last point, from end angle */ x1 = c_x + radius * cos(ang_end); y1 = c_y + radius * sin(ang_end); line_add(master, x0, y0, c_z, x1, y1, c_z); } } void graph_arc_bulge(graph_obj * master, double pt1_x, double pt1_y , double pt1_z, double pt2_x, double pt2_y, double pt2_z, double bulge){ if (fabs(bulge) > TOLERANCE){ /* bulge is non zero */ double theta, alfa, d, radius, ang_c, ang_start, ang_end, center_x, center_y; int sig; theta = 2 * atan(bulge); alfa = atan2(pt2_y-pt1_y, pt2_x-pt1_x); d = sqrt((pt2_y-pt1_y)*(pt2_y-pt1_y) + (pt2_x-pt1_x)*(pt2_x-pt1_x)) / 2; radius = d*(bulge*bulge + 1)/(2*bulge); ang_c = M_PI+(alfa - M_PI/2 - theta); center_x = radius*cos(ang_c) + pt1_x; center_y = radius*sin(ang_c) + pt1_y; /* get start and end angles from input coordinates */ ang_start = atan2(pt1_y-center_y,pt1_x-center_x); ang_end = atan2(pt2_y-center_y,pt2_x-center_x); sig = 1; if (bulge < 0){ ang_start += M_PI; ang_end += M_PI; sig = -1; } /* change angles to degrees */ ang_start *= 180/M_PI; ang_end *= 180/M_PI; graph_arc(master, center_x, center_y, pt1_z, radius, ang_start, ang_end, sig); } else{ line_add(master, pt1_x, pt1_y, pt1_z, pt2_x, pt2_y, pt2_z); } } void graph_ellipse(graph_obj * master, double p1_x, double p1_y, double p1_z, double p2_x, double p2_y, double p2_z, double minor_ax, double ang_start, double ang_end){ if (master){ int n = 32; /* number of interpolation vertices - good fit */ double ang, major_ax, cosine, sine, step; int steps, i; double x0, y0, x1, y1; double xx0, yy0, xx1, yy1; //ang_start *= M_PI/180; //ang_end *= M_PI/180; major_ax = sqrt(pow(p2_x, 2) + pow(p2_y, 2)) ; minor_ax *= major_ax; /* rotation constants */ cosine = cos(atan2(p2_y, p2_x)); sine = sin(atan2(p2_y, p2_x)); ang = (ang_end - ang_start); //angulo do arco if (ang <= 0){ ang = ang + 2*M_PI;} /* get step increment in loop */ //steps = (int) floor(fabs(ang*n/(2*M_PI))); //numero de vertices do arco step = ang/(double) n; /* first vertex */ x0 = p1_x + major_ax * cos(ang_start); y0 = p1_y + minor_ax * sin(ang_start); /* 2nd vertex and so */ for (i = 1; i < n; i++){ x1 = p1_x + major_ax * cos(step * i + ang_start); y1 = p1_y + minor_ax * sin(step * i + ang_start); xx0 = cosine*(x0-p1_x) - sine*(y0-p1_y) + p1_x; yy0 = sine*(x0-p1_x) + cosine*(y0-p1_y) + p1_y; xx1 = cosine*(x1-p1_x) - sine*(y1-p1_y) + p1_x; yy1 = sine*(x1-p1_x) + cosine*(y1-p1_y) + p1_y; line_add(master, xx0, yy0, p1_z, xx1, yy1, p1_z); x0=x1; y0=y1; } /* last vertex obtained from end angle */ x1 = p1_x + major_ax * cos(ang_end); y1 = p1_y + minor_ax * sin(ang_end); xx0 = cosine*(x0-p1_x) - sine*(y0-p1_y) + p1_x; yy0 = sine*(x0-p1_x) + cosine*(y0-p1_y) + p1_y; xx1 = cosine*(x1-p1_x) - sine*(y1-p1_y) + p1_x; yy1 = sine*(x1-p1_x) + cosine*(y1-p1_y) + p1_y; line_add(master, xx0, yy0, p1_z, xx1, yy1, p1_z); } } void graph_ellipse2(graph_obj * master, double major_ax, double minor_ax, double ang_start, double ang_end){ if (master){ int n = 32; /* number of interpolation vertices - good fit */ double ang, step; int steps, i; double x0, y0, x1, y1; //ang_start *= M_PI/180; //ang_end *= M_PI/180; //major_ax = sqrt(pow(p2_x, 2) + pow(p2_y, 2)) ; minor_ax *= major_ax; ang = (ang_end - ang_start); //angulo do arco if (ang <= 0){ ang = ang + 2*M_PI;} /* get step increment in loop */ //steps = (int) floor(fabs(ang*n/(2*M_PI))); //numero de vertices do arco step = ang/(double) n; x0 = major_ax * cos(ang_start); y0 = minor_ax * sin(ang_start); /* 2nd vertex and so */ for (i = 1; i < n; i++){ x1 = major_ax * cos(step * i + ang_start); y1 = minor_ax * sin(step * i + ang_start); line_add(master, x0, y0, 0.0, x1, y1, 0.0); x0=x1; y0=y1; } /* last vertex obtained from end angle */ x1 = major_ax * cos(ang_end); y1 = minor_ax * sin(ang_end); line_add(master, x0, y0, 0.0, x1, y1, 0.0); } } void graph_modify(graph_obj * master, double ofs_x, double ofs_y, double scale_x, double scale_y, double rot){ if ((master != NULL)){ if(master->list->next){ /* check if list is not empty */ double x0, y0, z0, x1, y1, z1; double sine = 0, cosine = 1; double min_x, min_y, min_z, max_x, max_y, max_z; line_node *current = master->list->next; master->flags &= ~(EXT_INI); /* scale line tickness */ if(!(master->flags & THICK_CONST)){ master->tick = master->tick * scale_x; } /* rotation constants */ cosine = cos(rot*M_PI/180); sine = sin(rot*M_PI/180); /* apply changes to each point */ while(current){ /*sweep the list content */ /* apply the scale and offset */ current->x0 = current->x0 * scale_x + ofs_x; current->y0 = current->y0 * scale_y + ofs_y; current->x1 = current->x1 * scale_x + ofs_x; current->y1 = current->y1 * scale_y + ofs_y; x0 = cosine*(current->x0-ofs_x) - sine*(current->y0-ofs_y) + ofs_x; y0 = sine*(current->x0-ofs_x) + cosine*(current->y0-ofs_y) + ofs_y; x1 = cosine*(current->x1-ofs_x) - sine*(current->y1-ofs_y) + ofs_x; y1 = sine*(current->x1-ofs_x) + cosine*(current->y1-ofs_y) + ofs_y; /* TODO*/ z0 = current->z0; z1 = current->z1; /* update the graph */ current->x0 = x0; current->y0 = y0; current->x1 = x1; current->y1 = y1; /*update the extent of graph */ /* sort the coordinates of entire line*/ min_x = (x0 < x1) ? x0 : x1; min_y = (y0 < y1) ? y0 : y1; min_z = (z0 < z1) ? z0 : z1; max_x = (x0 > x1) ? x0 : x1; max_y = (y0 > y1) ? y0 : y1; max_z = (z0 > z1) ? z0 : z1; if (!(master->flags & EXT_INI)){ master->flags |= EXT_INI; master->ext_min_x = min_x; master->ext_min_y = min_y; master->ext_min_z = min_z; master->ext_max_x = max_x; master->ext_max_y = max_y; master->ext_max_z = max_z; } else{ master->ext_min_x = (master->ext_min_x < min_x) ? master->ext_min_x : min_x; master->ext_min_y = (master->ext_min_y < min_y) ? master->ext_min_y : min_y; master->ext_min_z = (master->ext_min_z < min_z) ? master->ext_min_z : min_z; master->ext_max_x = (master->ext_max_x > max_x) ? master->ext_max_x : max_x; master->ext_max_y = (master->ext_max_y > max_y) ? master->ext_max_y : max_y; master->ext_max_z = (master->ext_max_z > max_z) ? master->ext_max_z : max_z; } current = current->next; /* go to next */ } } } } void graph_rot(graph_obj * master, double base_x, double base_y, double rot){ if ((master != NULL)){ if(master->list->next){ /* check if list is not empty */ double x0, y0, z0, x1, y1, z1; double sine = 0, cosine = 1; double min_x, min_y, min_z, max_x, max_y, max_z; line_node *current = master->list->next; master->flags &= ~(EXT_INI); /* rotation constants */ cosine = cos(rot*M_PI/180); sine = sin(rot*M_PI/180); /* apply changes to each point */ while(current){ /*sweep the list content */ x0 = cosine*(current->x0-base_x) - sine*(current->y0-base_y) + base_x; y0 = sine*(current->x0-base_x) + cosine*(current->y0-base_y) + base_y; x1 = cosine*(current->x1-base_x) - sine*(current->y1-base_y) + base_x; y1 = sine*(current->x1-base_x) + cosine*(current->y1-base_y) + base_y; /* update the graph */ current->x0 = x0; current->y0 = y0; current->x1 = x1; current->y1 = y1; /* TODO*/ z0 = current->z0; z1 = current->z1; /*update the extent of graph */ /* sort the coordinates of entire line*/ min_x = (x0 < x1) ? x0 : x1; min_y = (y0 < y1) ? y0 : y1; min_z = (z0 < z1) ? z0 : z1; max_x = (x0 > x1) ? x0 : x1; max_y = (y0 > y1) ? y0 : y1; max_z = (z0 > z1) ? z0 : z1; if (!(master->flags & EXT_INI)){ master->flags |= EXT_INI; master->ext_min_x = min_x; master->ext_min_y = min_y; master->ext_min_z = min_z; master->ext_max_x = max_x; master->ext_max_y = max_y; master->ext_max_z = max_z; } else{ master->ext_min_x = (master->ext_min_x < min_x) ? master->ext_min_x : min_x; master->ext_min_y = (master->ext_min_y < min_y) ? master->ext_min_y : min_y; master->ext_min_z = (master->ext_min_z < min_z) ? master->ext_min_z : min_z; master->ext_max_x = (master->ext_max_x > max_x) ? master->ext_max_x : max_x; master->ext_max_y = (master->ext_max_y > max_y) ? master->ext_max_y : max_y; master->ext_max_z = (master->ext_max_z > max_z) ? master->ext_max_z : max_z; } current = current->next; /* go to next */ } } } } /* int main (void){ bmp_color white = {.r = 255, .g = 255, .b =255, .a = 255}; bmp_color black = {.r = 0, .g = 0, .b =0, .a = 255}; bmp_color red = {.r = 255, .g = 0, .b =0, .a = 255}; bmp_img * img = bmp_new(200, 200, white, black); graph_obj * test = graph_new(); line_add(test, 0,0,100,100); line_add(test, 210,210,100,2); test->tick = 5; test->color = red; graph_draw(test, img); bmp_save("teste2.ppm", img); bmp_free(img); graph_free(test); return 0; } */ void graph_mod_axis(graph_obj * master, double normal[3] , double elev){ if ((master != NULL)){ if(master->list->next){ /* check if list is not empty */ double x_axis[3], y_axis[3], point[3], x_col[3], y_col[3], z_col[3]; double wy_axis[3] = {0.0, 1.0, 0.0}; double wz_axis[3] = {0.0, 0.0, 1.0}; double x0, y0, z0, x1, y1, z1; double min_x, min_y, min_z, max_x, max_y, max_z; line_node *current = master->list->next; master->flags &= ~(EXT_INI); if ((fabs(normal[0]) < 0.015625) && (fabs(normal[1]) < 0.015625)){ cross_product(wy_axis, normal, x_axis); } else{ cross_product(wz_axis, normal, x_axis); } cross_product(normal, x_axis, y_axis); unit_vector(x_axis); unit_vector(y_axis); unit_vector(normal); x_col[0] = x_axis[0]; x_col[1] = y_axis[0]; x_col[2] = normal[0]; y_col[0] = x_axis[1]; y_col[1] = y_axis[1]; y_col[2] = normal[1]; z_col[0] = x_axis[2]; z_col[1] = y_axis[2]; z_col[2] = normal[2]; /* apply changes to each point */ while(current){ /*sweep the list content */ /* apply the scale and offset */ point[0] = current->x0; point[1] = current->y0; point[2] = current->z0; if (fabs(point[2]) < TOLERANCE) point[2] = elev; x0 = dot_product(point, x_col); y0 = dot_product(point, y_col); z0 = dot_product(point, z_col); point[0] = current->x1; point[1] = current->y1; point[2] = current->z1; if (fabs(point[2]) < TOLERANCE) point[2] = elev; x1 = dot_product(point, x_col); y1 = dot_product(point, y_col); z1 = dot_product(point, z_col); /* update the graph */ current->x0 = x0; current->y0 = y0; current->z0 = z0; current->x1 = x1; current->y1 = y1; current->z1 = z1; /*update the extent of graph */ /* sort the coordinates of entire line*/ min_x = (x0 < x1) ? x0 : x1; min_y = (y0 < y1) ? y0 : y1; min_z = (z0 < z1) ? z0 : z1; max_x = (x0 > x1) ? x0 : x1; max_y = (y0 > y1) ? y0 : y1; max_z = (z0 > z1) ? z0 : z1; if (!(master->flags & EXT_INI)){ master->flags |= EXT_INI; master->ext_min_x = min_x; master->ext_min_y = min_y; master->ext_min_z = min_z; master->ext_max_x = max_x; master->ext_max_y = max_y; master->ext_max_z = max_z; } else{ master->ext_min_x = (master->ext_min_x < min_x) ? master->ext_min_x : min_x; master->ext_min_y = (master->ext_min_y < min_y) ? master->ext_min_y : min_y; master->ext_min_z = (master->ext_min_z < min_z) ? master->ext_min_z : min_z; master->ext_max_x = (master->ext_max_x > max_x) ? master->ext_max_x : max_x; master->ext_max_y = (master->ext_max_y > max_y) ? master->ext_max_y : max_y; master->ext_max_z = (master->ext_max_z > max_z) ? master->ext_max_z : max_z; } current = current->next; /* go to next */ } } } } int l_r_isect(double lin_pt1[2], double lin_pt2[2], double rect_pt1[2], double rect_pt2[2]){ /* check if a line instersect a rectangle */ double r_bl_x, r_bl_y, r_tr_x,r_tr_y; double a, b, c, pol1, pol2, pol3, pol4; /* sort the rectangle corners */ r_bl_x = (rect_pt1[0] < rect_pt2[0]) ? rect_pt1[0] : rect_pt2[0]; r_bl_y = (rect_pt1[1] < rect_pt2[1]) ? rect_pt1[1] : rect_pt2[1]; r_tr_x = (rect_pt1[0] > rect_pt2[0]) ? rect_pt1[0] : rect_pt2[0]; r_tr_y = (rect_pt1[1] > rect_pt2[1]) ? rect_pt1[1] : rect_pt2[1]; /* check if line is out of bounds of rectangle */ if (((lin_pt1[0] > r_tr_x) && (lin_pt2[0] > r_tr_x)) || ( /* line in right side */ (lin_pt1[1] > r_tr_y) && (lin_pt2[1] > r_tr_y)) || ( /* line in up side */ (lin_pt1[0] < r_bl_x) && (lin_pt2[0] < r_bl_x)) || ( /* line in left side */ (lin_pt1[1] < r_bl_y) && (lin_pt2[1] < r_bl_y))){ /* line in down side */ return 0;} else{ /* compute the triangle polarizations in each corner of rectangle, relative to line*/ a = lin_pt2[1]-lin_pt1[1]; b = lin_pt1[0]-lin_pt2[0]; c = lin_pt2[0]*lin_pt1[1] - lin_pt1[0]*lin_pt2[1]; pol1 = a*rect_pt1[0] + b*rect_pt1[1] + c; pol2 = a*rect_pt1[0] + b*rect_pt2[1] + c; pol3 = a*rect_pt2[0] + b*rect_pt1[1] + c; pol4 = a*rect_pt2[0] + b*rect_pt2[1] + c; if (((pol1>=0) && (pol2>=0) && (pol3>=0) && (pol4>=0)) ||( (pol1<0) && (pol2<0) && (pol3<0) && (pol4<0))){ return 0;} return 1; } } int graph_isect(graph_obj * master, double rect_pt1[2], double rect_pt2[2]){ if ((master != NULL)){ if(master->list->next){ /* check if list is not empty */ double lin_pt1[2], lin_pt2[2]; line_node *current = master->list->next; while(current){ /*sweep the list content */ /* update the graph */ lin_pt1[0] = current->x0; lin_pt1[1] = current->y0; lin_pt2[0] = current->x1; lin_pt2[1] = current->y1; if (((lin_pt1[0] > rect_pt1[0] && lin_pt1[0] < rect_pt2[0]) && (lin_pt1[1] > rect_pt1[1] && lin_pt1[1] < rect_pt2[1])) || ((lin_pt2[0] > rect_pt1[0] && lin_pt2[0] < rect_pt2[0]) && (lin_pt2[1] > rect_pt1[1] && lin_pt2[1] < rect_pt2[1]))) return 1; if(l_r_isect(lin_pt1, lin_pt2, rect_pt1, rect_pt2)){ return 1; } current = current->next; /* go to next */ } } } return 0; } int graph_in_rect(graph_obj * master, double rect_pt1[2], double rect_pt2[2]){ if (!master) return 0; if(!master->list->next) return 0; /* check if list is not empty */ double lin_pt1[2], lin_pt2[2]; line_node *current = master->list->next; while(current){ /*sweep the list content */ /* update the graph */ lin_pt1[0] = current->x0; lin_pt1[1] = current->y0; lin_pt2[0] = current->x1; lin_pt2[1] = current->y1; if (!(((lin_pt1[0] > rect_pt1[0] && lin_pt1[0] < rect_pt2[0]) && (lin_pt1[1] > rect_pt1[1] && lin_pt1[1] < rect_pt2[1])) && ((lin_pt2[0] > rect_pt1[0] && lin_pt2[0] < rect_pt2[0]) && (lin_pt2[1] > rect_pt1[1] && lin_pt2[1] < rect_pt2[1])))) return -1; current = current->next; /* go to next */ } return 1; } #if(0) int graph_list_draw(list_node *list, bmp_img * img, double ofs_x, double ofs_y, double scale){ list_node *current = NULL; graph_obj *curr_graph = NULL; int ok = 0; if (list != NULL){ current = list->next; /* sweep the main list */ while (current != NULL){ if (current->data){ curr_graph = (graph_obj *)current->data; graph_draw2(curr_graph, img, ofs_x, ofs_y, scale); } current = current->next; } ok = 1; } return ok; } #endif int graph_list_draw(list_node *list, bmp_img * img, struct draw_param param){ list_node *current = NULL; graph_obj *curr_graph = NULL; int ok = 0; if (list != NULL){ current = list->next; /* sweep the main list */ while (current != NULL){ if (current->data){ curr_graph = (graph_obj *)current->data; //print_graph_pdf(curr_graph, buf, param); graph_draw3(curr_graph, img, param); } current = current->next; } ok = 1; } return ok; } #if(0) int graph_list_draw_fix(list_node *list, bmp_img * img, double ofs_x, double ofs_y, double scale, bmp_color color){ list_node *current = NULL; graph_obj *curr_graph = NULL; int ok = 0; if (list != NULL){ current = list->next; /* sweep the main list */ while (current != NULL){ if (current->data){ curr_graph = (graph_obj *)current->data; graph_draw_fix(curr_graph, img, ofs_x, ofs_y, scale, color); } current = current->next; } ok = 1; } return ok; } #endif int graph_list_ext(list_node *list, int *init, double * min_x, double * min_y, double * min_z, double * max_x, double * max_y, double * max_z){ list_node *current = NULL; graph_obj *curr_graph = NULL; int ok = 0; if (list != NULL){ current = list->next; /* sweep the main list */ while (current != NULL){ if (current->data){ curr_graph = (graph_obj *)current->data; if (curr_graph->list->next != NULL){ /*check if graph is not empty */ if (*init == 0){ *init = 1; *min_x = curr_graph->ext_min_x; *min_y = curr_graph->ext_min_y; *min_z = curr_graph->ext_min_z; *max_x = curr_graph->ext_max_x; *max_y = curr_graph->ext_max_y; *max_z = curr_graph->ext_max_z; } else{ *min_x = (*min_x < curr_graph->ext_min_x) ? *min_x : curr_graph->ext_min_x; *min_y = (*min_y < curr_graph->ext_min_y) ? *min_y : curr_graph->ext_min_y; *min_z = (*min_z < curr_graph->ext_min_z) ? *min_z : curr_graph->ext_min_z; *max_x = (*max_x > curr_graph->ext_max_x) ? *max_x : curr_graph->ext_max_x; *max_y = (*max_y > curr_graph->ext_max_y) ? *max_y : curr_graph->ext_max_y; *max_z = (*max_z > curr_graph->ext_max_z) ? *max_z : curr_graph->ext_max_z; } } } current = current->next; } ok = 1; } return ok; } int graph_list_modify(list_node *list, double ofs_x, double ofs_y , double scale_x, double scale_y, double rot){ list_node *current = NULL; graph_obj *curr_graph = NULL; int ok = 0; if (list != NULL){ current = list->next; /* sweep the main list */ while (current != NULL){ if (current->data){ curr_graph = (graph_obj *)current->data; graph_modify(curr_graph, ofs_x, ofs_y, scale_x, scale_y, rot); } current = current->next; } ok = 1; } return ok; } int graph_list_modify_idx(list_node *list, double ofs_x, double ofs_y , double scale_x, double scale_y, double rot, int start_idx, int end_idx){ list_node *current = NULL; graph_obj *curr_graph = NULL; int ok = 0, i = 0; if (list != NULL){ current = list->next; /* sweep the main list */ while (current != NULL){ if (current->data){ curr_graph = (graph_obj *)current->data; if(i >= start_idx){ graph_modify(curr_graph, ofs_x, ofs_y, scale_x, scale_y, rot); } } if(i >= end_idx) break; i++; current = current->next; } ok = 1; } return ok; } int graph_list_rot(list_node *list, double base_x, double base_y , double rot){ list_node *current = NULL; graph_obj *curr_graph = NULL; int ok = 0; if (list != NULL){ current = list->next; /* sweep the main list */ while (current != NULL){ if (current->data){ curr_graph = (graph_obj *)current->data; graph_rot(curr_graph, base_x, base_y, rot); } current = current->next; } ok = 1; } return ok; } int graph_list_rot_idx(list_node *list, double base_x, double base_y , double rot, int start_idx, int end_idx){ list_node *current = NULL; graph_obj *curr_graph = NULL; int ok = 0, i = 0; if (list != NULL){ current = list->next; /* sweep the main list */ while (current != NULL){ if (current->data){ curr_graph = (graph_obj *)current->data; if(i >= start_idx){ graph_rot(curr_graph, base_x, base_y, rot); } } if(i >= end_idx) break; i++; current = current->next; } ok = 1; } return ok; } int graph_list_mod_ax(list_node *list, double normal[3], double elev, int start_idx, int end_idx){ list_node *current = NULL; graph_obj *curr_graph = NULL; int ok = 0, i = 0; if (list != NULL){ current = list->next; /* sweep the main list */ while (current != NULL){ if (current->data){ curr_graph = (graph_obj *)current->data; if(i >= start_idx){ graph_mod_axis(curr_graph, normal, elev); } } if(i >= end_idx) break; i++; current = current->next; } ok = 1; } return ok; } graph_obj * graph_list_isect(list_node *list, double rect_pt1[2], double rect_pt2[2]){ list_node *current = NULL; graph_obj *curr_graph = NULL; if (list != NULL){ current = list->next; /* sweep the main list */ while (current != NULL){ if (current->data){ curr_graph = (graph_obj *)current->data; if(graph_isect(curr_graph, rect_pt1, rect_pt2)){ return curr_graph; } } current = current->next; } } return NULL; } int graph_list_in_rect(list_node *list, double rect_pt1[2], double rect_pt2[2]){ list_node *current = NULL; graph_obj *curr_graph = NULL; int num = 0; if (!list) return 0; current = list->next; /* sweep the main list */ while (current != NULL){ if (current->data){ curr_graph = (graph_obj *)current->data; int ret = graph_in_rect(curr_graph, rect_pt1, rect_pt2); if(ret < 0) return 0; num += ret; } current = current->next; } if (num) return 1; return 0; } int graph_list_color(list_node *list, bmp_color color){ list_node *current = NULL; graph_obj *curr_graph = NULL; int ok = 0; if (list != NULL){ current = list->next; /* sweep the main list */ while (current != NULL){ if (current->data){ curr_graph = (graph_obj *)current->data; curr_graph->color = color; } current = current->next; } ok = 1; } return ok; } int pt_lies_seg (double ax, double ay, double bx , double by, double cx, double cy){ /* https://stackoverflow.com/questions/328107/how-can-you-determine-a-point-is-between-two-other-points-on-a-line-segment */ double crossproduct = (cy - ay) * (bx - ax) - (cx - ax) * (by - ay); if (fabs(crossproduct) > TOLERANCE) return 0; double dotproduct = (cx - ax) * (bx - ax) + (cy - ay) * (by - ay); if (dotproduct < 0) return 0; double squaredlengthba = (bx - ax)*(bx - ax) + (by - ay)*(by - ay); if (dotproduct > squaredlengthba) return 0; return 1; } int graph_is_closed(graph_obj * master){ if (master == NULL) return 0; if (master->list->next == NULL) return 0; /* check if list is not empty */ double curr_x, curr_y, prev_x, prev_y, first_x, first_y; int first = 0; line_node *current = master->list->next; while(current){ /*sweep the list content */ curr_x = current->x0; curr_y = current->y0; if (!first){ first = 1; first_x = current->x0; first_y = current->y0; } else if ((fabs(curr_x - prev_x) > TOLERANCE) || (fabs(curr_y - prev_y) > TOLERANCE)) return 0; prev_x = current->x1; prev_y = current->y1; current = current->next; /* go to next */ } if ((fabs(first_x - prev_x) > TOLERANCE) || (fabs(first_y - prev_y) > TOLERANCE)) return 0; return 1; } int graph_dash(graph_obj * master, double x0, double y0, double x1, double y1, double skew, double dash[], int num_dash){ if (master == NULL) return 0; /* check if list is not empty */ double dx, dy, modulus, sine, cosine; int i, iter, reverse = 0, idx = 0; if (num_dash > 1) { /* if graph is dashed lines */ int patt_i = 0, patt_a_i = 0, patt_p_i = 0, draw; double patt_len = 0.0, patt_int, patt_part, patt_rem = 0.0, patt_acc, patt_rem_n; double patt_start_x = 0, patt_start_y = 0; double patt_start = 0; double p1x, p1y, p2x, p2y; double last; /* get the pattern length */ for (i = 0; i < num_dash && i < 20; i++){ patt_len += fabs(dash[i]); } /* get polar parameters of line */ dx = x1 - x0 + TOLERANCE; dy = y1 - y0 + TOLERANCE; modulus = sqrt(pow(dx, 2) + pow(dy, 2)); cosine = 1.0; sine = 0.0; if (modulus > TOLERANCE){ cosine = dx/modulus; sine = dy/modulus; } patt_start = cosine*x0 + sine*y0 - skew; reverse = patt_start < 0; /* find the pattern initial conditions for the first point*/ patt_start = fabs(fmod(patt_start, patt_len)); iter = get_i(0, num_dash, reverse); patt_acc = fabs(dash[iter]) + TOLERANCE; patt_rem_n = patt_start; for (i = 1; i < num_dash && i < 20; i++){ if (patt_start < patt_acc){ break; } patt_rem_n -= fabs(dash[get_i(i - 1, num_dash, reverse)]); patt_acc += fabs(dash[get_i(i, num_dash, reverse)]); } patt_i = i - 1; if (reverse) patt_rem = patt_rem_n; else patt_rem = (patt_acc - patt_start); /* initial point */ draw = dash[get_i(patt_i, num_dash, reverse)] >= 0.0; p1x = x0; p1y = y0; patt_i = get_i(patt_i, num_dash, reverse); reverse = 0; if (patt_rem < modulus){ /* current segment needs some iterations over pattern */ /* find how many interations over whole pattern */ patt_part = modf((modulus - patt_rem)/patt_len, &patt_int); patt_part *= patt_len; /* remainder for the next step*/ /* find how many interations over partial pattern */ patt_a_i = 0; patt_p_i = patt_i; if (patt_rem > 0) patt_p_i++; if (patt_p_i >= num_dash) patt_p_i = 0; /* calcule the last stroke (pattern fractional part) of current segment*/ patt_acc = fabs(dash[get_i(patt_p_i, num_dash, reverse)]) + TOLERANCE; last = modulus - patt_int*patt_len - patt_rem; for (i = 0; i < num_dash && i < 20; i++){ patt_a_i = i; if (patt_part < patt_acc) break; last -= fabs(dash[get_i(patt_p_i, num_dash, reverse)]); patt_p_i++; if (patt_p_i >= num_dash) patt_p_i = 0; patt_acc += fabs(dash[get_i(patt_p_i, num_dash, reverse)]); } /* do the first stroke - partial dash*/ p2x = patt_rem * cosine + p1x; p2y = patt_rem * sine + p1y; if (patt_rem > 0) { patt_i++; if (patt_i >= num_dash) patt_i = 0; if (draw){ line_add(master, p1x, p1y, 0.0, p2x, p2y, 0.0); } } /* do the dashes */ p1x = p2x; p1y = p2y; /* draw pattern */ iter = (int) (patt_int * (num_dash)) + patt_a_i; for (i = 0; i < iter; i++){ idx = get_i(patt_i, num_dash, reverse); draw = dash[idx] >= 0.0; p2x = fabs(dash[idx]) * cosine + p1x; p2y = fabs(dash[idx]) * sine + p1y; if (draw){ line_add(master, p1x, p1y, 0.0, p2x, p2y, 0.0); } p1x = p2x; p1y = p2y; patt_i++; if (patt_i >= num_dash) patt_i = 0; } /* do the last stroke - partial dash*/ idx = get_i(patt_i, num_dash, reverse); p2x = last * cosine + p1x; p2y = last * sine + p1y; draw = dash[idx] >= 0.0; if (draw) line_add(master, p1x, p1y, 0.0, p2x, p2y, 0.0); } else{ /* current segment is in same past iteration pattern */ p2x = modulus * cosine + p1x; p2y = modulus * sine + p1y; patt_rem -= modulus; if (draw){ line_add(master, p1x, p1y, 0.0, p2x, p2y, 0.0); } p1x = p2x; p1y = p2y; } } else{ /* for continuous lines*/ /* get polar parameters of line */ dx = x1 - x0; dy = y1 - y0; modulus = sqrt(pow(dx, 2) + pow(dy, 2)); cosine = 1.0; sine = 0.0; if (modulus > TOLERANCE){ cosine = dx/modulus; sine = dy/modulus; } if (dash[0] >= 0.0){ line_add(master, x0, y0, 0.0, x1, y1, 0.0); } } } graph_obj * graph_hatch(graph_obj * ref, double angle, double orig_x, double orig_y, double delta_x, double delta_y, double dash[], int num_dash, int pool_idx){ //if (!graph_is_closed(ref)) return NULL; /* verify if reference is a closed path */ graph_obj *ret_graph = NULL;//graph_new(pool_idx); int i, j, idx0, idx1; double min_x, max_x, min_y, max_y; int nodes = 0, steps = 0; double start, end, swap; double node_x[10000], node_y[10000]; double pos[10000]; struct sort_by_idx sort_vert[10000]; double a = sin(angle); double b = -cos(angle); double c = -(a*orig_x+b*orig_y); double sine = sin(-angle); double cosine = cos(-angle); double delta = -(a * delta_x + b * delta_y); /* distance between hatch lines */ double skew = -b * delta_x + a * delta_y; /* dash skew in hatch line direction*/ double curr_skew = (-b * orig_x + a * orig_y); /* find min and max by reference graph rectangle*/ min_x = ref->ext_min_x; max_x = ref->ext_max_x; min_y = ref->ext_min_y; max_y = ref->ext_max_y; /* calcule distances between cornes of graph rectangle and line at orign */ double dist[4], tmp; dist[0] = (a*min_x + b*min_y + c); dist[1] = (a*min_x + b*max_y + c); dist[2] = (a*max_x + b*min_y + c); dist[3] = (a*max_x + b*max_y + c); /* Sort the distances*/ qsort(dist, 4, sizeof(double), cmp_double); start = floor(dist[0]/delta) * (delta); end = ceil(dist[3]/delta) * (delta); if (delta < 0){ /* invert corners */ start = floor(dist[3]/delta) * (delta); end = ceil(dist[0]/delta) * (delta); } /* how many lines are sampled */ steps = (int) fabs(round((end - start)/delta)); if (steps > 0) ret_graph = graph_new(pool_idx); c -= start; /* perpenticular displacement of line */ curr_skew -= start/delta * skew; /* linear displacement of dahes */ for (i = 0; i < steps; i++){ if((ref->list->next) && (ret_graph != NULL)) { /* check if list is not empty */ line_node *current = ref->list->next; while(current){ /*sweep the bondary segments list */ /* get line parameters of current boundary segment*/ double a2 = current->y1 - current->y0; double b2 = -(current->x1 - current->x0); double c2 = current->x1 * current->y0 - current->y1 * current->x0; /* calcule intersections between hatch line and boundary segment*/ double den =b*a2-b2*a; if ( (fabs(den) > TOLERANCE) && (nodes < 10000)){ double x = (b*c2-b2*c)/-den; double y = (a*c2-a2*c)/den; if (pt_lies_seg(current->x0, current->y0, current->x1, current->y1, x, y)){ /* if intersection is in segment, add point to hatch vertices list*/ node_x[nodes] = x; node_y[nodes] = y; /* parameters for sorting vertices */ pos[nodes] = -(x*cosine - y*sine); sort_vert[nodes].idx = nodes; sort_vert[nodes].data = &pos[nodes]; nodes++; } } current = current->next; /* go to next */ } } if (nodes > 1){ /* Sort the hatch vertices */ qsort(sort_vert, nodes, sizeof(struct sort_by_idx), cmp_vert); /* create the hatch segments between vertices pairs */ j = 0; while (j < nodes - 1){ idx0 = sort_vert[j].idx; idx1 = sort_vert[j+1].idx; //if (fabs(*(double *)sort_vert[j].data - *(double *)sort_vert[j+1].data) < TOLERANCE){ // /* ignore duplicated nodes */ // j++; //} //else { graph_dash(ret_graph, node_x[idx0], node_y[idx0], node_x[idx1], node_y[idx1], curr_skew, dash, num_dash); j += 2; //} } } /* update the next line parameters */ curr_skew -= skew; c -= delta; nodes = 0; } return ret_graph; } #define plot_(X,Y,D) do{ unsigned char alfa = img->frg.a; \ img->frg.a = (D) * alfa; \ bmp_point_raw(img, (X), (Y)); \ img->frg.a = alfa; }while(0) /* Xiaolin Wu antialising line algorithm font: http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm#C */ #define ipart_(X) ((int)(X)) #define round_(X) ((int)(((double)(X))+0.5)) #define fpart_(X) (((double)(X))-(double)ipart_(X)) #define rfpart_(X) (1.0-fpart_(X)) #ifdef _MSC_VER //silly,stupid,i know,msvc does not support this feature now #define swap_(a, b) do{ double tmp; tmp = a; a = b; b = tmp; }while(0) #else #define swap_(a, b) do{ __typeof__(a) tmp; tmp = a; a = b; b = tmp; }while(0) #endif void draw_line_antialias( bmp_img * img, double x1, double y1, double x2, double y2){ double dx = x2 - x1; double dy = y2 - y1; if ( fabs(dx) > fabs(dy) ) { if ( x2 < x1 ) { swap_(x1, x2); swap_(y1, y2); } double gradient = dy / dx; double xend = round_(x1); double yend = y1 + gradient*(xend - x1); double xgap = rfpart_(x1 + 0.5); int xpxl1 = xend; int ypxl1 = ipart_(yend); plot_(xpxl1, ypxl1, rfpart_(yend)*xgap); plot_(xpxl1, ypxl1+1, fpart_(yend)*xgap); double intery = yend + gradient; xend = round_(x2); yend = y2 + gradient*(xend - x2); xgap = fpart_(x2+0.5); int xpxl2 = xend; int ypxl2 = ipart_(yend); plot_(xpxl2, ypxl2, rfpart_(yend) * xgap); plot_(xpxl2, ypxl2 + 1, fpart_(yend) * xgap); int x; for(x=xpxl1+1; x < xpxl2; x++) { plot_(x, ipart_(intery), rfpart_(intery)); plot_(x, ipart_(intery) + 1, fpart_(intery)); intery += gradient; } } else { if ( y2 < y1 ) { swap_(x1, x2); swap_(y1, y2); } double gradient = dx / dy; double yend = round_(y1); double xend = x1 + gradient*(yend - y1); double ygap = rfpart_(y1 + 0.5); int ypxl1 = yend; int xpxl1 = ipart_(xend); plot_(xpxl1, ypxl1, rfpart_(xend)*ygap); plot_(xpxl1 + 1, ypxl1, fpart_(xend)*ygap); double interx = xend + gradient; yend = round_(y2); xend = x2 + gradient*(yend - y2); ygap = fpart_(y2+0.5); int ypxl2 = yend; int xpxl2 = ipart_(xend); plot_(xpxl2, ypxl2, rfpart_(xend) * ygap); plot_(xpxl2 + 1, ypxl2, fpart_(xend) * ygap); int y; for(y=ypxl1+1; y < ypxl2; y++) { plot_(ipart_(interx), y, rfpart_(interx)); plot_(ipart_(interx) + 1, y, fpart_(interx)); interx += gradient; } } } #undef swap_ //#undef plot_ #undef ipart_ #undef fpart_ #undef round_ #undef rfpart_ /*int bmp_units (double value, double ofs, double scale){ return (int)round((value - ofs) * scale); }*/ #define BMP_U(value, ofs, scale) (int)round((value - ofs) * scale) int graph_fill(graph_obj * ref, bmp_img * img, double ofs_x, double ofs_y, double scale){ //if (!graph_is_closed(ref)) return 0; /* verify if reference is a closed path */ int i, j; int min_x, max_x, min_y, max_y; int nodes = 0, steps = 0; //double start, end, swap; double x0, y0, x1, y1, swap; double node_x[1000];//, node_y[1000]; int pix_x, pix_y; /* first, draw contour with antialised lines */ line_node *current = ref->list->next; while(current){ /*sweep the list content */ x0 = (current->x0 - ofs_x) * scale; y0 = (current->y0 - ofs_y) * scale; x1 = (current->x1 - ofs_x) * scale; y1 = (current->y1 - ofs_y) * scale; draw_line_antialias(img, x0, y0, x1, y1); current = current->next; /* go to next */ } /* find min and max by reference graph rectangle*/ /* min_x = (int)ceil((ref->ext_min_x - ofs_x) * scale); max_x = (int)floor((ref->ext_max_x - ofs_x) * scale); min_y = (int)ceil((ref->ext_min_y - ofs_y) * scale); max_y = (int)floor((ref->ext_max_y - ofs_y) * scale);*/ min_x = BMP_U(ref->ext_min_x, ofs_x, scale); max_x = BMP_U(ref->ext_max_x, ofs_x, scale); min_y = BMP_U(ref->ext_min_y, ofs_y, scale); max_y = BMP_U(ref->ext_max_y, ofs_y, scale); int w = img->width, h = img->height; if((min_x < w) && (max_x > 0) && (min_y < h) && (max_y > 0 )){ min_x = (min_x > 0) ? min_x : 0; max_x = (max_x < w) ? max_x : w; min_y = (min_y > 0) ? min_y : 0; max_y = (max_y < h) ? max_y : h; for (pix_y = min_y; pix_y < max_y; pix_y++){ /* sweep line in y coordinate*/ if(ref->list->next) { /* check if list is not empty */ current = ref->list->next; while(current){ /*sweep the list content */ x0 = BMP_U(current->x0, ofs_x, scale); y0 = BMP_U(current->y0, ofs_y, scale); x1 = BMP_U(current->x1, ofs_x, scale); y1 = BMP_U(current->y1, ofs_y, scale); if(((y0 < pix_y) && (y1 >= pix_y)) || ((y1 < pix_y) && (y0 >= pix_y))){ /* find x coord of intersection and add to list */ node_x[nodes] = (x1 + (double) (pix_y - y1)/(y0 - y1)*(x0 - x1)); node_x[nodes] = (node_x[nodes] >= 0) ? node_x[nodes] : -1; node_x[nodes] = (node_x[nodes] <= max_x) ? node_x[nodes] : max_x + 1; nodes++; } current = current->next; /* go to next */ } } if (nodes > 1){ /* Sort the nodes */ qsort(node_x, nodes, sizeof(double), cmp_double); /*fill the pixels between node pairs*/ for (i = 0; i < nodes ; i += 2){ if (i+1 < nodes){ for(pix_x = node_x[i]+1; pix_x <= node_x[i + 1]; pix_x++){ bmp_point_raw(img, pix_x, pix_y); } } } } nodes = 0; } } return 1; } void graph_draw_aa(graph_obj * master, bmp_img * img, double ofs_x, double ofs_y, double scale){ if ((master != NULL) && (img != NULL)){ if(master->list->next){ /* check if list is not empty */ double xd0, yd0, xd1, yd1; line_node *current = master->list->next; int ok = 1; /* set the pattern */ patt_change(img, master->pattern, master->patt_size); /* set the color */ img->frg = master->color; /* set the tickness */ //if (master->thick_const) if (master->flags & THICK_CONST) img->tick = (int) round(master->tick); else img->tick = (int) round(master->tick * scale); /* draw the lines */ while(current){ /*sweep the list content */ /* apply the scale and offset */ ok = 1; ok &= !(isnan(xd0 = ((current->x0 - ofs_x) * scale))); ok &= !(isnan(yd0 = ((current->y0 - ofs_y) * scale))); ok &= !(isnan(xd1 = ((current->x1 - ofs_x) * scale))); ok &= !(isnan(yd1 = ((current->y1 - ofs_y) * scale))); //y0 = (int) round((current->y0 - ofs_y) * scale); //x1 = (int) round((current->x1 - ofs_x) * scale); //y1 = (int) round((current->y1 - ofs_y) * scale); if (ok){ //bmp_line(img, xd0, yd0, xd1, yd1); draw_line_antialias(img, xd0, yd0, xd1, yd1); } current = current->next; /* go to next */ } } } } int graph_list_draw_aa(list_node *list, bmp_img * img, double ofs_x, double ofs_y, double scale){ list_node *current = NULL; graph_obj *curr_graph = NULL; int ok = 0; if (list != NULL){ current = list->next; /* sweep the main list */ while (current != NULL){ if (current->data){ curr_graph = (graph_obj *)current->data; graph_draw_aa(curr_graph, img, ofs_x, ofs_y, scale); } current = current->next; } ok = 1; } return ok; } /* https://stackoverflow.com/questions/11907947/how-to-check-if-a-point-lies-on-a-line-between-2-other-points by https://stackoverflow.com/users/688624/imallett This is independent of Javascript. Try the following algorithm, with points p1=point1 and p2=point2, and your third point being p3=currPoint: v1 = p2 - p1 v2 = p3 - p1 v3 = p3 - p2 if (dot(v2,v1)>0 and dot(v3,v1)<0) return between else return not between If you want to be sure it's on the line segment between p1 and p2 as well: v1 = normalize(p2 - p1) v2 = normalize(p3 - p1) v3 = p3 - p2 if (fabs(dot(v2,v1)-1.0)<EPS and dot(v3,v1)<0) return between else return not between Define function PlotAntiAliasedPoint ( number x, number y ) For roundedx = floor ( x ) to ceil ( x ) do For roundedy = floor ( y ) to ceil ( y ) do percent_x = 1 - abs ( x - roundedx ) percent_y = 1 - abs ( y - roundedy ) percent = percent_x * percent_y DrawPixel ( coordinates roundedx, roundedy, color percent (range 0-1) ) */ /* https://gamedev.stackexchange.com/questions/45298/convert-orientation-vec3-to-a-rotation-matrix answered Dec 10 '12 at 12:08 by sam hocevar Your problem is under-constrained, so there are a lot of possible solutions. My suggestion is to see your vec3 as the result of rotating vector [1 0 0] by φ around axis Y then by θ around axis Z. This is the latitude/longitude notation. The corresponding transformation matrix is: |cosθ cosφ -sinθ -cosθ sinφ| |sinθ cosφ cosθ -sinθ sinφ| | sinφ 0 cosφ | See the first column? That’s your vec3, since it’s the image of [1 0 0]. So the good thing is that we already know a lot of the matrix values. The following code computes the remaining values: mat3 rotation_matrix(vec3 v) { // Find cosφ and sinφ float c1 = sqrt(v.x * v.x + v.y * v.y); float s1 = v.z; // Find cosθ and sinθ; if gimbal lock, choose (1,0) arbitrarily float c2 = c1 ? v1.x / c1 : 1.0; float s2 = c1 ? v1.y / c1 : 0.0; return mat3(v.x, -s2, -s1*c2, v.y, c2, -s1*s2, v.z, 0, c1); } */ void vec_2_rot_matrix(double matrix[3][3], double x, double y, double z){ /* Find cos(fi) and sin(fi) */ double c1 = sqrt(x * x + y * y); double s1 = z; /* Find cos(omega) and sin(omega); if gimbal lock, choose (1,0) arbitrarily */ double c2 = c1 ? x / c1 : 1.0; double s2 = c1 ? y / c1 : 0.0; matrix[0][0] = x; matrix[1][0] = y; matrix[2][0] = z; matrix[0][1] = -s2; matrix[1][1] = c2; matrix[2][1] = 0; matrix[0][2] = -s1*c2; matrix[1][2] = -s1*s2; matrix[2][2] = c1; } void graph_matrix(graph_obj * master, double matrix[3][3]){ if ((master != NULL)){ if(master->list->next){ /* check if list is not empty */ double x0, y0, z0, x1, y1, z1; double sine = 0, cosine = 1; double min_x, min_y, min_z, max_x, max_y, max_z; line_node *current = master->list->next; master->flags &= ~(EXT_INI); /* apply changes to each point */ while(current){ /*sweep the list content */ x0 = current->x0 * matrix[0][0] + current->y0 * matrix[0][1] +current->z0 * matrix[0][2]; y0 = current->x0 * matrix[1][0] + current->y0 * matrix[1][1] +current->z0 * matrix[1][2]; z0 = current->x0 * matrix[2][0] + current->y0 * matrix[2][1] +current->z0 * matrix[2][2]; x1 = current->x1 * matrix[0][0] + current->y1 * matrix[0][1] +current->z1 * matrix[0][2]; y1 = current->x1 * matrix[1][0] + current->y1 * matrix[1][1] +current->z1 * matrix[1][2]; z1 = current->x1 * matrix[2][0] + current->y1 * matrix[2][1] +current->z1 * matrix[2][2]; /* update the graph */ current->x0 = x0; current->y0 = y0; current->z0 = z0; current->x1 = x1; current->y1 = y1; current->z1 = z1; /*update the extent of graph */ /* sort the coordinates of entire line*/ min_x = (x0 < x1) ? x0 : x1; min_y = (y0 < y1) ? y0 : y1; min_z = (z0 < z1) ? z0 : z1; max_x = (x0 > x1) ? x0 : x1; max_y = (y0 > y1) ? y0 : y1; max_z = (z0 > z1) ? z0 : z1; if (!(master->flags & EXT_INI)){ master->flags |= EXT_INI; master->ext_min_x = min_x; master->ext_min_y = min_y; master->ext_min_z = min_z; master->ext_max_x = max_x; master->ext_max_y = max_y; master->ext_max_z = max_z; } else{ master->ext_min_x = (master->ext_min_x < min_x) ? master->ext_min_x : min_x; master->ext_min_y = (master->ext_min_y < min_y) ? master->ext_min_y : min_y; master->ext_min_z = (master->ext_min_z < min_z) ? master->ext_min_z : min_z; master->ext_max_x = (master->ext_max_x > max_x) ? master->ext_max_x : max_x; master->ext_max_y = (master->ext_max_y > max_y) ? master->ext_max_y : max_y; master->ext_max_z = (master->ext_max_z > max_z) ? master->ext_max_z : max_z; } current = current->next; /* go to next */ } } } } int graph_list_matrix(list_node *list, double matrix[3][3]){ list_node *current = NULL; graph_obj *curr_graph = NULL; int ok = 0; if (list != NULL){ current = list->next; /* sweep the main list */ while (current != NULL){ if (current->data){ curr_graph = (graph_obj *)current->data; graph_matrix(curr_graph, matrix); } current = current->next; } ok = 1; } return ok; } #if(0) int graph_change_patt (graph_obj * graph, double pattern[20], int size){ /* change the graph line pattern */ if(graph){ int i; graph->patt_size = size; for (i = 0; i < size; i++){ graph->pattern[i] = pattern[i]; /* TODO */ graph->cmplx_pat[i] = NULL; } return 1; } return 0; } int graph_list_change_patt(list_node *list, double pattern[20], int size){ list_node *current = NULL; graph_obj *curr_graph = NULL; int ok = 0; if (list != NULL){ current = list->next; /* sweep the main list */ while (current != NULL){ if (current->data){ curr_graph = (graph_obj *)current->data; graph_change_patt(curr_graph, pattern, size); } current = current->next; } ok = 1; } return ok; } #endif
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXV 1000 #define MAXE 500000 int input[MAXE][3]; void WQY_bedge_fast_sort(int st,int end) { int low, high; int pivotK0, pivotK1, pivotK2; low=st; high=end; if(st>=end) return; pivotK0=input[low][0]; pivotK1=input[low][1]; pivotK2=input[low][2]; while(low<high) { while(low<high && input[high][2]<=pivotK2) { high--; } input[low][0]=input[high][0]; input[low][1]=input[high][1]; input[low][2]=input[high][2]; while(low<high && input[low][2]>=pivotK2) { low++; } input[high][0]=input[low][0]; input[high][1]=input[low][1]; input[high][2]=input[low][2]; } input[low][0]=pivotK0; input[low][1]=pivotK1; input[low][2]=pivotK2; WQY_bedge_fast_sort(st,low-1); WQY_bedge_fast_sort(high+1,end); } int main() { int V, E, u, v; int i, j, m, n; int results[MAXV][MAXV]; int label[MAXV][MAXV]; int group[MAXV]; scanf("%d%d",&V,&E); for(i=0;i<E;i++) { scanf("%d%d%d",&(input[i][0]),&(input[i][1]),&(input[i][2])); } WQY_bedge_fast_sort(0,E-1); for(i=0;i<V;i++) for(j=0;j<V;j++) label[i][j]=-!(results[i][j]=0); for(i=0;i<V;i++) { label[i][0]=i; group[i]=i; } for(i=0;i<E;i++) { if(group[input[i][0]]!=group[input[i][1]]) { u=group[input[i][0]]<group[input[i][1]]?group[input[i][0]]:group[input[i][1]]; v=group[input[i][0]]>group[input[i][1]]?group[input[i][0]]:group[input[i][1]]; for(m=0;label[u][m]!=-1;m++) { for(n=0;label[v][n]!=-1;n++) { results[label[u][m]][label[v][n]]=input[i][2]; results[label[v][n]][label[u][m]]=input[i][2]; } } for(n=0;label[v][n]!=-1;n++,m++) { label[u][m]=label[v][n]; group[label[v][n]]=group[label[u][0]]; } } } for(i=0;i<V;i++) { for(j=0;j<V;j++) printf("%d ",results[i][j]); printf("\n"); } return 0; }
C
#include <stdio.h> void insert_n_display() { int numbers[10], i; for (i = 0; i < 10; i++) { printf("Enter a number:\n"); scanf("%d", &numbers[i]); } printf("The numbers are:\n"); for (i = 0; i < 10; i++) { printf("numbers[%d] has value %d\n", i, numbers[i]); } } void sum_of_arr() { int numbers[10], i, sum = 0; for (i = 0; i < 10; i++) { printf("Enter a number:\n"); scanf("%d", &numbers[i]); sum += numbers[i]; } printf("The sum of elements is: %d\n", sum); } void odd_even_count() { int numbers[10], i, odd = 0, even = 0; for (i = 0; i < 10; i++) { printf("Enter a number:\n"); scanf("%d", &numbers[i]); numbers[i] % 2 == 0 ? even++ : odd++; } printf("The even count is: %d\n", even); printf("The even count is: %d\n", odd); } void high_low_percentage() { int percentage[10], i, high = 0, low = 100000; for (i = 0; i < 10; i++) { printf("Enter a number:\n"); scanf("%d", &percentage[i]); high = percentage[i] > high ? percentage[i] : high; low = percentage[i] < low ? percentage[i] : low; } printf("The highest percentage is %d\n", high); printf("The lowest percentage is %d\n", low); } int main() { // insert_n_display(); sum_of_arr(); // odd_even_count(); // high_low_percentage(); return 0; }
C
// // Created by chengwenjie on 2019/8/29. // #include <stdio.h> #include "jam.h" #include "lock.h" Object *exceptionOccured() { return NULL; } void signalException(char *excep_name, char *message) {} unsigned char *findCatchBlockInMethod(MethodBlock *mb, Class *exception, unsigned char *pc_pntr) { ExceptionTableEntry *table = mb->exception_table; int size = mb->exception_table_size; int pc = pc_pntr - mb->code; int i; for(i = 0; i < size; i++) if((pc >= table[i].start_pc) && (pc < table[i].end_pc)) { /* If the catch_type is 0 it's a finally block, which matches any exception. Otherwise, the thrown exception class must be an instance of the caught exception class to catch it */ if(table[i].catch_type != 0) { Class *caught_class = resolveClass(mb->class, table[i].catch_type, FALSE); if(caught_class == NULL) { clearException(); continue; } if(!isInstanceOf(caught_class, exception)) continue; } return mb->code + table[i].handler_pc; } return NULL; } unsigned char *findCatchBlock(Class *exception) { Frame *frame = getExecEnv()->last_frame; unsigned char *handler_pc = NULL; while(((handler_pc = findCatchBlockInMethod(frame->mb, exception, frame->last_pc)) == NULL) && (frame->prev->mb != NULL)) { if(frame->mb->access_flags & ACC_SYNCHRONIZED) { Object *sync_ob = frame->mb->access_flags & ACC_STATIC ? (Object*)frame->mb->class : (Object*)frame->lvars[0]; objectUnlock(sync_ob); } frame = frame->prev; } getExecEnv()->last_frame = frame; return handler_pc; }
C
#include "sorting.h" /* Helper function for mergeSort */ int merge(Data *arr, int low, int mid, int high) { int l1, l2, i, complexity = 0; Data *tmp = malloc(sizeof(Data) * (high+1)); for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) { if(arr[l1].value <= arr[l2].value) tmp[i] = arr[l1++]; else tmp[i] = arr[l2++]; complexity++; } while(l1 <= mid) { tmp[i++] = arr[l1++]; complexity++; } while(l2 <= high) { tmp[i++] = arr[l2++]; complexity++; } for(i = low; i <= high; i++) { arr[i]= tmp[i]; complexity++; } free(tmp); return complexity; } int mergeSort(Data *arr, int low, int high) { if (low < high) { int mid = (low + high) / 2; int c1 = mergeSort(arr, low, mid); int c2 = mergeSort(arr, mid+1, high); int c3 = merge(arr, low, mid, high); return c1 + c2 + c3; } return 0; } /* Helper function for quickSort */ void swap(Data *arr, int i, int j) { Data tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } /* Helper function for quickSort */ int partition(Data *arr, int low, int high, int *pos) { float pivot = arr[high].value; int lowPointer = low - 1; int highPointer = high; int complexity; while (1) { while (lowPointer < high && arr[++lowPointer].value < pivot) complexity++; while (highPointer > low && arr[--highPointer].value > pivot) complexity++; if (lowPointer >= highPointer) break; else swap(arr, lowPointer, highPointer); complexity++; } swap(arr, lowPointer, high); complexity++; *pos = lowPointer; return complexity; } int quickSort(Data *arr, int low, int high) { if (low < high) { int pos; int c1 = partition(arr, low, high, &pos); int c2 = quickSort(arr, low, pos-1); int c3 = quickSort(arr, pos+1, high); return c1 + c2 + c3; } return 0; } /* Helper function for heapSort */ int heapify(Data *arr, int N) { int parent, current, complexity = 0; for(int i = 1; i <= N; i++) { current = i; parent = (int) current / 2; complexity++; while(parent >= 1) { if(arr[parent].value < arr[current].value) { swap(arr, current, parent); complexity++; } // traverse heap current = parent; parent = (int) current / 2; complexity++; } } return complexity; } int heapSort(Data *arr, int N) { int complexity = 0; for (int i = N; i >= 1; i--) arr[i] = arr[i-1]; for (int i = N; i >= 1; i--) { complexity += heapify(arr, i); swap(arr, 1, i); complexity++; } for (int i = 0; i < N; i++) arr[i] = arr[i+1]; return complexity; } int countSort(Data *arr, int N) { Data *sorted = malloc(sizeof(Data) * N); int i, count[VALUE_RANGE + 1], complexity = 0; memset(count, 0, sizeof(count)); for(i = 0; i < N; i++) count[(int) arr[i].value]++; for (i = 1; i <= VALUE_RANGE; i++) { count[i] += count[i-1]; complexity++; } for (i = 0; i < N; i++) { sorted[count[(int) arr[i].value]-1].time = arr[i].time; sorted[count[(int) arr[i].value]-1].value = arr[i].value; --count[(int) arr[i].value]; complexity++; } for (i = 0; i < N; i++) { arr[i] = sorted[i]; complexity++; } free(sorted); return complexity; } void timestampSort(Data *arr, int N) { for (int i = N; i >= 1; i--) arr[i] = arr[i-1]; for (int i = N; i >= 1; i--) { int parent, current; for(int j = 1; j <= i; j++) { current = j; parent = (int) current / 2; while(parent >= 1) { if (compare(arr[parent].time, arr[current].time) < 0) swap(arr, current, parent); // traverse heap current = parent; parent = (int) current / 2; } } swap(arr, 1, i); } for (int i = 0; i < N; i++) arr[i] = arr[i+1]; }
C
#include <stdio.h> #include "dk_tool.h" int enterNumberIn10(void) { int a; printf("Enter a number in 10-system: "); // 10- do { int theTmp = scanf("%d",&a); if(theTmp == 1) // { break; } printf("Please,try again: "); fflush(stdin); } while(1); return a; // main.c } int enterNumberIn16(void) { int b; printf("Enter a number in 16-system: "); // 16- do { int theTmp = scanf("%x",&b); if(theTmp == 1) { // break; } printf("Please,try again: "); fflush(stdin); } while(1); return b; // main.c } int theSum(int D,int F, int C) { int A; int Q; for( A = 1; A <= D; A++) { Q += A *(F - C); // } return Q; // main.c }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_none.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rhadiats <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/04/27 12:37:02 by rhadiats #+# #+# */ /* Updated: 2017/04/27 12:37:03 by rhadiats ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/ft_printf.h" int print_space(t_flags flags) { char *space; space = (flags.zero == 1 && flags.minus == 0) ? \ fillsmb('0', flags.get_width - 1) : fillsmb(' ', flags.get_width - 1); write(1, space, ft_strlen(space)); free(space); return (ft_strlen(space)); } int ft_none(va_list elem, t_flags flags) { int i; int count; i = 0; count = 0; (void)elem; if (flags.minus == 0) count += print_space(flags); while (flags.str[i++]) { if ((ft_strlenchr(SPECIFICATE, flags.str[i]) == -1) && \ flags.str[i] != 'l' && flags.str[i] != 'h' && flags.str[i] != 'j' \ && flags.str[i] != 'z' && flags.str[i] != ' ' && \ flags.str[i] != '.' && flags.str[i] != '-' && flags.str[i] != '+' \ && flags.str[i] != '#' && !ft_isdigit(flags.str[i])) { count += write(1, &flags.str[i++], 1); if (flags.minus == 1) count += print_space(flags); while ((ft_strlenchr(SPECIFICATE, flags.str[i]) == -1) && \ flags.str[i]) count += write(1, &flags.str[i++], 1); } } return (count); }
C
#include<stdio.h> #include<unistd.h> int main(int argc,char **argv) { char path[128]; char *p=NULL; int ret; char *retp = getcwd(path,sizeof(path)); if(NULL==retp) { perror("getcwd"); return -1; } printf("path=%s\n",path); p = getcwd(NULL,0); printf("p=%s\n",p); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main() { if (puts("hello word!\n") < 0 ) { printf("puts error!\n"); exit(0); } return 0; }
C
struct bool check(struct vll* a, struct vll* b) { int n = a.size(); if(b.size() != n) return false; int ii = 0; for(ii = 0; ii < n; ++ii) { if(a[ii] > b[ii]) return false; } return true; } int main() { int T; cin = T; while(T--) { long long n; cin = n; struct vvvll A; struct vvll r, l, u, d; for(kk = 0; kk < 4; ++kk) { for(ii = 0; ii < n; ++ii) { for(jj = 0; jj < n; ++jj) { cin = A[kk][ii][jj]; if(ii == 0) u[kk][jj] = A[kk][ii][jj]; else if(ii == n - 1) d[kk][jj] = A[kk][ii][jj]; if(jj == 0) l[kk][ii] = A[kk][ii][jj]; else if(jj == n - 1) r[kk][ii] = A[kk][ii][jj]; } } } struct vvb rl , du; for(ii = 0; ii < 4; ++ii) { for(jj = 0; jj < 4; ++jj) { rl[ii][jj] = check(r[ii], l[jj]); du[ii][jj] = check(d[ii], u[jj]); } } struct vll okay = {0, 1, 2, 3}; struct bool final = false; for(ii = 0; ii < 24 && !final; ++ii) { final = ((rl[okay[0]][okay[1]]) && (rl[okay[1]][okay[2]]) && (rl[okay[2]][okay[3]])); final = ((du[okay[0]][okay[1]]) && (du[okay[1]][okay[2]]) && (du[okay[2]][okay[3]])); final = ((rl[okay[0]][okay[1]]) && (du[okay[0]][okay[2]]) && (du[okay[1]][okay[3]]) && (rl[okay[2]][okay[3]])); next_permutation(okay.begin(), okay.end()); } if(final) cout = "YES\n"; else cout = "NO\n"; } }
C
#include <stdio.h> int main (int argc,char *argv[]){ int i=0; if (argc ==1){ printf("You only have one argument. You suck.\n"); } else if (argc >1 && argc<4){ printf("Here's your arguments: \n"); for(int i=0;i<argc;i++){ printf("%s ",argv[i]); } printf("\n"); } else { printf("You have too many arguments. You suck." ); } return 0; }