language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* date = January 12th 2021 11:44 am */ #ifndef CJ_OPENGL_H #define CJ_OPENGL_H struct SHADER_PROGRAM { u32 VS = {}; u32 FS = {}; u32 GS = {}; u32 shaderProgram = {}; char *shaderBuffer; }; void CreateShader(SHADER_PROGRAM *s, char *inFilePath, i32 shader_type); void LinkShaderProgram(SHADER_PROGRAM *s); void UseShaderProgram(SHADER_PROGRAM *s); void Destroy(SHADER_PROGRAM *s); void CheckShaderCompileErrors(SHADER_PROGRAM *s, unsigned int shader); void CheckShaderLinkErrors(SHADER_PROGRAM *s); void LoadShaderFile(SHADER_PROGRAM *s, char *inFilePath); void GLPrintErrorOutputDBGstr(); void GLClearErrors() { while(glGetError() != GL_NO_ERROR); } void GLPrintErrorOutputDBGstr() { GLenum err = {}; u8 err_info[1024] = {}; u8 err_str[1024] = {}; while(err = glGetError()) { switch(err) { case GL_INVALID_ENUM: strcpy((char*)err_str, "INVALID_ENUM"); break; case GL_INVALID_VALUE: strcpy((char*)err_str, "INVALID_VALUE"); break; case GL_INVALID_OPERATION: strcpy((char*)err_str, "INVALID_OPERATION"); break; case GL_STACK_OVERFLOW: strcpy((char*)err_str, "STACK_OVERFLOW"); break; case GL_STACK_UNDERFLOW: strcpy((char*)err_str, "STACK_UNDERFLOW"); break; case GL_OUT_OF_MEMORY: strcpy((char*)err_str, "OUT_OF_MEMORY"); break; case GL_INVALID_FRAMEBUFFER_OPERATION: strcpy((char*)err_str, "IVALID_FRAMEBUFFER_OPERATION"); break; } sprintf((char*)err_info, "(%s, %d): (%d) %s", __FILE__, __LINE__, err, err_str); OutputDebugString((char*)err_info); } } void CreateShader(SHADER_PROGRAM *s, char *inFilePath, i32 shader_type) { if(shader_type == GL_VERTEX_SHADER) { LoadShaderFile(s, inFilePath); s->VS = glCreateShader(GL_VERTEX_SHADER); glShaderSource(s->VS, 1, &s->shaderBuffer, 0); glCompileShader(s->VS); CheckShaderCompileErrors(s, s->VS); free(s->shaderBuffer); } else if (shader_type == GL_FRAGMENT_SHADER) { LoadShaderFile(s, inFilePath); s->FS = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(s->FS, 1, &s->shaderBuffer, 0); glCompileShader(s->FS); CheckShaderCompileErrors(s, s->FS); free(s->shaderBuffer); } } void LinkShaderProgram(SHADER_PROGRAM *s) { s->shaderProgram = glCreateProgram(); GLClearErrors(); glAttachShader(s->shaderProgram, s->VS); GLPrintErrorOutputDBGstr(); GLClearErrors(); glAttachShader(s->shaderProgram, s->FS); GLPrintErrorOutputDBGstr(); GLClearErrors(); // NOTE: Not using right now glAttachShader(s->shaderProgram, s->GS); GLPrintErrorOutputDBGstr(); glLinkProgram(s->shaderProgram); CheckShaderLinkErrors(s); } void UseShaderProgram(SHADER_PROGRAM *s) { glUseProgram(s->shaderProgram); } void destroy(SHADER_PROGRAM *s) { glDeleteShader(s->VS); glDeleteShader(s->FS); glDeleteShader(s->GS); } void CheckShaderCompileErrors(SHADER_PROGRAM *s, unsigned int shader) { int compilationSuccess; char infoLog[1024]; char outPutString[1024] = {}; glGetShaderiv(shader, GL_COMPILE_STATUS, &compilationSuccess); if(!compilationSuccess) { glGetShaderInfoLog(shader, 1024, 0, infoLog); if(shader == s->VS) { printf("!!ERROR-SHADER-VERTEX-COMPILATION_FAILED\n%s", infoLog); sprintf(outPutString, "!!ERROR-SHADER-VERTEX-COMPILATION_FAILED\n%s", infoLog); OutputDebugString(outPutString); } else if(shader == s->FS) { printf("!!ERROR-SHADER-FRAGMENT-COMPILATION_FAILED\n%s", infoLog); sprintf(outPutString, "!!ERROR-SHADER-FRAGMENT-COMPILATION_FAILED\n%s", infoLog); OutputDebugString(outPutString); } else if(shader == s->GS) { printf("!!ERROR-SHADER-GEOMETRY-COMPILATION_FAILED\n%s", infoLog); sprintf(outPutString, "!!ERROR-SHADER-GEOMETRY-COMPILATION_FAILED\n%s", infoLog); OutputDebugString(outPutString); } } } void CheckShaderLinkErrors(SHADER_PROGRAM *s) { int linkSuccess = 0; char infoLog[1024] = {}; char outPutString[1024] = {}; glGetProgramiv(s->shaderProgram, GL_LINK_STATUS, &linkSuccess); if(!linkSuccess) { glGetProgramInfoLog(s->shaderProgram, 1024, 0, infoLog); printf("ERROR-SHADER-PROGRAM-LINK_FAILED\n%s", infoLog); sprintf(outPutString, "!!ERROR-SHADER-PROGRAM-LINK-COMPILATION_FAILED\n%s", infoLog); OutputDebugString(outPutString); } } void LoadShaderFile(SHADER_PROGRAM *s, char *inFilePath) { FILE *file = fopen(inFilePath, "r"); if(!file) { printf("Can't open: %s\n", inFilePath); } int nCharsInFile = 1024; char fileBuffer[1024] = {}; s->shaderBuffer = (char*)malloc(1024); strcpy(s->shaderBuffer, ""); while(fgets(fileBuffer, nCharsInFile, file) != 0) { strcat(s->shaderBuffer, fileBuffer); } printf("length of shader(nr of characters): %d\n", (int)strlen(s->shaderBuffer)); fclose(file); } #endif //CJ_OPENGL_H
C
/* * ModifyWordPack.c * COMP 40 HW 4 * Rebecca Redelmeier & Darcy Hinck * October 21, 2017 * * Purpose: Gets and sets necessary variables in a word through calls to * the bitpack interface */ #include "ModifyWordPack.h" #include "bitpack.h" #include <stdlib.h> #include <stdio.h> #include <assert.h> const uint64_t A_WIDTH = 9; const uint64_t BCD_WIDTH = 5; const uint64_t PBPR_WIDTH = 4; const uint64_t A_LSB = 23; const uint64_t B_LSB = 18; const uint64_t C_LSB = 13; const uint64_t D_LSB = 8; const uint64_t PB_LSB = 4; const uint64_t PR_LSB = 0; struct wordParts { unsigned a; signed b; signed c; signed d; unsigned Pb; unsigned Pr; }; /* Purpose: Packs all elements from the struct into the word and returns it */ uint64_t packWord(wordP wordPointer) { uint64_t word = 0; struct wordParts currParts = *((struct wordParts *) wordPointer); word = Bitpack_newu(word, A_WIDTH, A_LSB, currParts.a); word = Bitpack_news(word, BCD_WIDTH, B_LSB, currParts.b); word = Bitpack_news(word, BCD_WIDTH, C_LSB, currParts.c); word = Bitpack_news(word, BCD_WIDTH, D_LSB, currParts.d); word = Bitpack_newu(word, PBPR_WIDTH, PB_LSB, currParts.Pb); word = Bitpack_newu(word, PBPR_WIDTH, PR_LSB, currParts.Pr); return(word); } /* Purpose: Unpacks all parts of the word into a struct and returns it */ wordP unpackWord(uint64_t word) { struct wordParts *currWord = malloc(sizeof(struct wordParts)); assert(currWord); currWord->a = Bitpack_getu(word, A_WIDTH, A_LSB); currWord->b = Bitpack_gets(word, BCD_WIDTH, B_LSB); currWord->c = Bitpack_gets(word, BCD_WIDTH, C_LSB); currWord->d = Bitpack_gets(word, BCD_WIDTH, D_LSB); currWord->Pb = Bitpack_getu(word, PBPR_WIDTH, PB_LSB); currWord->Pr = Bitpack_getu(word, PBPR_WIDTH, PR_LSB); wordP finalWord = currWord; return(finalWord); }
C
#include "list.h" #include <stdio.h> #include <stdlib.h> void createList(list* l) { *l = NULL; } void addElement(list* l, entryType item) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->info = item; newNode->next = *l; *l = newNode; } void createMap(Map* m) { *m = NULL; } void addNewElement(Map *m, keyType key, entryType value) { multiMap* trav = *m; int found = 0; while(trav) { if(trav->key == key) { addElement(&trav->value, value); found = 1; break; } trav = trav->next; } if (found == 0) { multiMap* newNode = (multiMap*)malloc(sizeof(multiMap)); newNode->key = key; createList(&newNode->value); addElement(&newNode->value, value); newNode->next = *m; *m = newNode; } } void removeKey(Map* m, keyType key) { multiMap* trav = *m, *temp; if(trav->key == key) { temp = trav; *m = trav->next; free(temp); } else { while(trav->next) { if(trav->next->key == key) { temp = trav->next; trav->next = temp->next; free(temp); break; } trav = trav->next; } } } void editValue(Map* m, keyType key, entryType value, entryType updateVal) { multiMap* mval = *m; while(mval) { if(mval->key == key) break; mval = mval->next; } Node* trav = mval->value; while(trav) { if(trav->info == value) { trav->info = updateVal; break; } trav = trav->next; } } void showKeyVals(Map* m, keyType key) { multiMap* trav = *m; int found = 0; while(trav) { if(trav->key == key) { found = 1; Node* vals = trav->value; while(vals) { printf("%d ",vals->info); vals = vals->next; } } trav = trav->next; } if (found == 0) { printf("Key Not Found"); } }
C
/* ************************************************************************** */ /* */ /* :::::::: */ /* flag_management.c :+: :+: */ /* +:+ */ /* By: bbremer <[email protected]> +#+ */ /* +#+ */ /* Created: 2019/06/04 14:22:59 by bbremer #+# #+# */ /* Updated: 2019/07/24 10:44:08 by bbremer ######## odam.nl */ /* */ /* ************************************************************************** */ #include "checker.h" #include "../pushswap_src/push_swap.h" int check_flags(char *str) { if (ft_strcmp(str, "-v") == 0) return (1); if (ft_strcmp(str, "-s") == 0) return (1); if (ft_strcmp(str, "-m") == 0) return (1); return (0); } void initialise_flags(t_stack **stack_a, t_stack **stack_b, t_flags *flags) { if (flags->debug || flags->movements || flags->nonsort) *stack_a = delete_first_stack(*stack_a); if (flags->debug) { ft_printf("\nInitial stacks are:\n"); print_stacks(*stack_a, *stack_b); } } int count_movements(void) { static int movements; if (!movements) movements = 0; movements++; return (movements); } void print_flags(t_flags *flags) { ft_printf("flag -v is %i, flags -m is %i, flags -s %i\n", flags->debug, flags->movements, flags->nonsort); } t_flags *get_flags(char **argv) { t_flags *flags; int j; j = 1; flags = (t_flags *)malloc(sizeof(t_flags)); flags->nonsort = 0; flags->movements = 0; flags->debug = 0; while (argv[j] && j < 4) { if (ft_strcmp(argv[j], "-v") == 0) flags->debug = 1; if (ft_strcmp(argv[j], "-m") == 0) flags->movements = 1; if (ft_strcmp(argv[j], "-s") == 0) flags->nonsort = 1; j++; } return (flags); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* pressed_second_word.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: nriker <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/07/29 20:46:20 by nriker #+# #+# */ /* Updated: 2020/07/29 20:48:36 by nriker ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_21sh.h" void set_cursor_second_2(int *x, int width, t_input *input) { int xt; xt = get_curs_col(); while (((*x) < width) && input->line[*x] != ' ') { if (!(xt % input->col)) { ft_putstr("\e[1E"); input->y++; xt = 0; } else ft_putstr("\e[1C"); xt++; (*x)++; if (input->quote) input->x_quote++; else if (input->dquote) input->x_dquote++; input->x++; } } void set_cursor_second_1(int *x, int width, t_input *input) { int xt; xt = get_curs_col(); while (((*x) < width) && input->line[*x] == ' ') { if (!(xt % input->col)) { ft_putstr("\e[1E"); input->y++; xt = 0; } else ft_putstr("\e[1C"); xt++; (*x)++; if (input->quote) input->x_quote++; else if (input->dquote) input->x_dquote++; input->x++; } } void set_cursor_second_word(int x, int width, t_input *input) { if (input->line[x] == ' ') { set_cursor_second_1(&x, width, input); } else if (input->line[x] != ' ') { set_cursor_second_2(&x, width, input); set_cursor_second_1(&x, width, input); } } void pressed_second_word(t_input *input) { int width; if (!ft_strlen(input->line)) return ; if (!input->qt) { width = input->width - input->index; set_cursor_second_word(input->x - input->index, width, input); } }
C
#include <stdio.h> #include <stdlib.h> #include<string.h> int main() { printf("1.To find the length of the string\n2.To concatenate two strings\n3.To find reverse of a string\n4.To copy one string to another string\n choose your option: "); int option; scanf("%d",&option); char a[20],b[20]; gets(a); if(option==1) { printf("\nEnter string: "); gets(a); printf("%d is the length of the string",strlen(a)); } if(option==2) { int j=0; printf("\nEnter two strings: "); gets(a); gets(b); for(int i=strlen(a) ; i<strlen(a)+strlen(b); i++,j++) { a[i]=b[j]; } printf("%s",a); } if(option==3) { printf("\nEnter string: "); gets(a); for(int i=0; i<strlen(a); i++) { b[strlen(a)-i]=a[i]; } printf("%s",b); } return 0; }
C
#pragma once #include "glm\glm.hpp" #include "GLUT\glut.h" struct Col_Sphere { Col_Sphere(glm::vec3 pos, float rad) : position(pos), radius(rad) {} glm::vec3 position; float radius; }; struct Col_AABB { Col_AABB(glm::vec3 pos, glm::vec3 ext) : position(pos), extent(ext) {} glm::vec3 position; glm::vec3 extent; }; struct Col_OBB { Col_OBB() {} Col_OBB(glm::vec3 pos, glm::vec3 ext) : position(pos), extent(ext) {} glm::vec3 position; glm::vec3 extent; }; static void drawCollisionBox(const Col_OBB& boxToDraw) { //Calculate points glm::vec3 vertices[8]; vertices[0] = glm::vec3(boxToDraw.position + glm::vec3(boxToDraw.extent.x, boxToDraw.extent.y, boxToDraw.extent.z)); vertices[1] = glm::vec3(boxToDraw.position + glm::vec3(boxToDraw.extent.x, boxToDraw.extent.y, -boxToDraw.extent.z)); vertices[2] = glm::vec3(boxToDraw.position + glm::vec3(boxToDraw.extent.x, -boxToDraw.extent.y, boxToDraw.extent.z)); vertices[3] = glm::vec3(boxToDraw.position + glm::vec3(-boxToDraw.extent.x, boxToDraw.extent.y, boxToDraw.extent.z)); vertices[4] = glm::vec3(boxToDraw.position + glm::vec3(-boxToDraw.extent.x, -boxToDraw.extent.y, boxToDraw.extent.z)); vertices[5] = glm::vec3(boxToDraw.position + glm::vec3(-boxToDraw.extent.x, boxToDraw.extent.y, -boxToDraw.extent.z)); vertices[6] = glm::vec3(boxToDraw.position + glm::vec3(boxToDraw.extent.x, -boxToDraw.extent.y, -boxToDraw.extent.z)); vertices[7] = glm::vec3(boxToDraw.position + glm::vec3(-boxToDraw.extent.x, -boxToDraw.extent.y, -boxToDraw.extent.z)); //Draw points glColor3f(0.0f, 1.0f, 0.0f); glPointSize(10.0f); glBegin(GL_POINTS); { for (int i = 0; i < 8; i++) glVertex3f(vertices[i].x, vertices[i].y, vertices[i].z); } glEnd(); glPointSize(1.0f); }
C
#include<stdio.h> #include "stdlib.h" #include "string.h" #include "linklist.h" typedef struct _tag_LinkList { //棬ҪнڵϢҪһʼ //Ǵͷڵ LinkListNode header; int length; }TLinkList; LinkList* LinkList_Create() { TLinkList *ret = (TLinkList *)malloc(sizeof(TLinkList)); if (ret == NULL) { return NULL; } //memset(ret, 0, sizeof(TLinkList)); ret->header.next = NULL; ret->length = 0; return ret; } void LinkList_Destroy(LinkList* list) { if (list == NULL) { return ; } free(list); return ; } void LinkList_Clear(LinkList* list) { TLinkList *tList =NULL; if (list == NULL) { return ; } tList = (TLinkList *)list; tList->length = 0; tList->header.next = NULL; return ; } int LinkList_Length(LinkList* list) { TLinkList *tList = (TLinkList *)list; if (tList == NULL) { return -1; } return tList->length; } int LinkList_Insert(LinkList* list, LinkListNode* node, int pos) { int i = 0; TLinkList *tList = NULL; LinkListNode *current = NULL; tList = (TLinkList *)list; //׼øָ ָͷڵ current = &tList->header; for (i=0; i<pos &&(current->next!=NULL); i++) { current = current->next; } //nodeڵӺ node->next = current->next ; //ǰߵnode current->next = node; tList->length ++; return 0; } LinkListNode* LinkList_Get(LinkList* list, int pos) { int i = 0; TLinkList *tList = NULL; LinkListNode *current = NULL; LinkListNode *ret = NULL; tList = (TLinkList *)list; if (list == NULL || pos <0 ||pos>=tList->length) { return NULL; } //׼øָ ָͷڵ current = &tList->header; for (i=0; i<pos &&(current->next!=NULL); i++) { current = current->next; } ret = current->next; return ret; } LinkListNode* LinkList_Delete(LinkList* list, int pos) { int i = 0; TLinkList *tList = NULL; LinkListNode *current = NULL; LinkListNode *ret = NULL; tList = (TLinkList *)list; if (list == NULL || pos <0 ||pos>=tList->length) { return NULL; } //׼øָ ָͷڵ current = &tList->header; for (i=0; i<pos &&(current->next!=NULL); i++) { current = current->next; } ret = current->next; //ɾ㷨 current->next =ret->next; tList->length--; return ret; }
C
#include <stdio.h> int main() { char ch='a'; for( ;ch<='z';ch++) { printf(" %c",ch); } return 0; }
C
#include <stdio.h> #define LINHAS 3 #define COLUNAS 5 //quando passa matriz para uma função, é obrigatório colocar as dimensões da matriz void zeraMatriz(int m[LINHAS][COLUNAS]) { int lin, col; for(lin = 0; lin < LINHAS; lin++) { for(col = 0; col < COLUNAS; col++) { m[lin][col] = 0; } } } int main() { int mat[LINHAS][COLUNAS]; //[linhas][colunas] zeraMatriz(mat); return 0; }
C
#include <stdio.h> #include <stdlib.h> struct element { int width; int height; }; int main(int argc, char *argv[]) { struct element *arr; int count; int i; int w = 0, ind_h_max_main = 0, ind_h_max_secondary = 0; int w_cur; scanf("%d", &count); arr = malloc(sizeof(struct element) * count); for (i = 0; i < count; i++) { scanf("%d %d", &arr[i].width, &arr[i].height); w += arr[i].width; } if (arr[0].height > arr[1].height) { ind_h_max_main = 0; ind_h_max_secondary = 1; } else { ind_h_max_main = 1; ind_h_max_secondary = 0; } for (i = 2; i < count; i++) { if (arr[ind_h_max_secondary].height < arr[i].height) { if (arr[ind_h_max_main].height < arr[i].height) { ind_h_max_secondary = ind_h_max_main; ind_h_max_main = i; } else ind_h_max_secondary = i; } } printf("max = %d, secondary = %d\n",ind_h_max_main,ind_h_max_secondary); for (i = 0; i < count; i++) { w_cur = w - arr[i].width; if (i == ind_h_max_main) printf("%d ",w_cur * arr[ind_h_max_secondary].height); else printf("%d ",w_cur * arr[ind_h_max_main].height); } free(arr); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* fill.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: thabdoul <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/03/16 14:44:00 by thabdoul #+# #+# */ /* Updated: 2018/04/17 14:54:08 by thabdoul ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/rtv1.h" void fill_light(char *str, t_light *light) { char **tab; tab = ft_strsplit(str, ' '); check_error_l(tab); if ((light->pos.x = ft_atoi(tab[1]) / 1000.0f) < -200 || light->pos.x > 200) ft_error(); if ((light->pos.y = ft_atoi(tab[2]) / 1000.0f) < -200 || light->pos.y > 200) ft_error(); if ((light->pos.z = ft_atoi(tab[3]) / 1000.0f) < -200 || light->pos.z > 200) ft_error(); if ((light->i = ft_atoi(tab[4]) / 1000.0f) < 0 || light->i > 1) ft_error(); if (ft_strncmp("</LIGHT>", tab[5], 8)) ft_error(); clean_tab(tab); } void fill_sphere(char *str, t_obj *obj) { char **tab; tab = ft_strsplit(str, ' '); check_error_s(tab); if ((obj->pos.x = ft_atoi(tab[1]) / 1000.0f) < -200 || obj->pos.x > 200) ft_error(); if ((obj->pos.y = ft_atoi(tab[2]) / 1000.0f) < -200 || obj->pos.y > 200) ft_error(); if ((obj->pos.z = ft_atoi(tab[3]) / 1000.0f) < -200 || obj->pos.y > 200) ft_error(); if ((obj->r = ft_atoi(tab[4]) / 1000.0f) < 1 || obj->r > 200) ft_error(); if ((obj->color.red = ft_atoi(tab[5]) / 255.0f) > 1 || obj->color.red < 0) ft_error(); if ((obj->color.green = ft_atoi(tab[6]) / 255.0f) > 1 || obj->color.green < 0) ft_error(); if ((obj->color.blue = ft_atoi(tab[7]) / 255.0f) > 1 || obj->color.blue < 0) ft_error(); fill_sphere2(tab, obj); clean_tab(tab); } void fill_plan(char *str, t_obj *obj) { char **tab; tab = ft_strsplit(str, ' '); check_error_p(tab); if ((obj->pos.x = ft_atoi(tab[1]) / 1000.0f) < -200 || obj->pos.x > 200) ft_error(); if ((obj->pos.y = ft_atoi(tab[2]) / 1000.0f) < -200 || obj->pos.y > 200) ft_error(); if ((obj->pos.z = ft_atoi(tab[3]) / 1000.0f) < -200 || obj->pos.z > 200) ft_error(); if ((obj->n.x = ft_atoi(tab[4])) < -200 || obj->n.x > 200) ft_error(); if ((obj->n.y = ft_atoi(tab[5])) < -200 || obj->n.y > 200) ft_error(); if ((obj->n.z = ft_atoi(tab[6])) < -200 || obj->n.z > 200) ft_error(); fill_plan2(tab, obj); obj->nsave = obj->n; clean_tab(tab); } void fill_cone(char *str, t_obj *obj) { char **tab; tab = ft_strsplit(str, ' '); check_error(tab); if ((obj->pos.x = ft_atoi(tab[1]) / 1000.0f) < -200 || obj->pos.x > 200) ft_error(); if ((obj->pos.y = ft_atoi(tab[2]) / 1000.0f) < -200 || obj->pos.y > 200) ft_error(); if ((obj->pos.z = ft_atoi(tab[3]) / 1000.0f) < -200 || obj->pos.y > 200) ft_error(); if ((obj->r = ft_atoi(tab[4])) < -180 || obj->r >= 180) ft_error(); if ((obj->dir.x = ft_atoi(tab[5]) / 1000.0f) < -200 || obj->dir.x > 200) ft_error(); if ((obj->dir.y = ft_atoi(tab[6]) / 1000.0f) < -200 || obj->dir.y > 200) ft_error(); if ((obj->dir.z = ft_atoi(tab[7]) / 1000.0f) < -200 || obj->dir.z > 200) ft_error(); if ((obj->color.red = ft_atoi(tab[8]) / 255.0f) > 1 || obj->color.red < 0) ft_error(); fill_cone2(tab, obj); clean_tab(tab); } void fill_cylinder(char *str, t_obj *obj) { char **tab; tab = ft_strsplit(str, ' '); check_error(tab); if ((obj->pos.x = ft_atoi(tab[1]) / 1000.0f) < -200 || obj->pos.x > 200) ft_error(); if ((obj->pos.y = ft_atoi(tab[2]) / 1000.0f) < -200 || obj->pos.y > 200) ft_error(); if ((obj->pos.z = ft_atoi(tab[3]) / 1000.0f) < -200 || obj->pos.y > 200) ft_error(); if ((obj->r = ft_atoi(tab[4]) / 1000.0f) < 1 || obj->pos.y > 200) ft_error(); if ((obj->dir.x = ft_atoi(tab[5]) / 1000.0f) < -200 || obj->dir.x > 200) ft_error(); if ((obj->dir.y = ft_atoi(tab[6]) / 1000.0f) < -200 || obj->dir.y > 200) ft_error(); if ((obj->dir.z = ft_atoi(tab[7]) / 1000.0f) < -200 || obj->dir.z > 200) ft_error(); if ((obj->color.red = ft_atoi(tab[8]) / 255.0f) > 1 || obj->color.red < 0) ft_error(); fill_cylinder2(tab, obj); clean_tab(tab); }
C
#include <stdio.h> #include <stdlib.h> #include<math.h> #define CUSTOM_IMG_SIZE 1024*1024 int main() { FILE *streamIn =fopen("fruits.bmp","rb"); if(streamIn ==(FILE*)0) printf("unable to open\n"); printf("x"); unsigned char header[54]; unsigned char colorTable[1024]; for(int i=0;i<54;i++) header[i]=getc(streamIn); int width = *(int *)&header[18]; int height = *(int *)&header[22]; int bitDepth =*(int *)&header[28]; // printf("%d %d %d",height,width,bitDepth); printf("x"); // fread(colorTable,sizeof(unsigned char),1024,streamIn); unsigned char buf [width*height]; // fread(buf,sizeof(unsigned char),height*width,streamIn); printf("x"); /*...............................brightness..................................................... for(int i=0;i<height*width;i++)/ { int temp =buf[i]+30; buf[i]=(temp>255)? 255 :temp; } */ /*to make negative.................................................................. for(int i=0;i<height*width;i++) buf[i]=255-buf[i]; */ // Image Reader till than;......................................................................... //to make histogram of image.............................................................................. /* FILE *fptr; fptr = fopen("image_histogram.txt","wb"); int x=0,y=0,i=0,j=0; long int ihist[256],sum=0; float hist[256]; for(i=0;i<256;i++) ihist[i]=0; printf("ihist\n"); for(i=0;i<height*width;i++) { // printf() j= buf[i]; ihist[j]+=1; sum++; } printf("ihist\n"); for(int i=0;i<256;i++) hist[i]= (float)ihist[i]/(float)sum; for(int i=0;i<256;i++) fprintf(fptr,"%f\n",hist[i]); fclose(fptr); */ //.......................Equalize image.............................. /* //printf("x"); int mx=INT_MIN,mn=INT_MAX; for(int i=0;i<height*width;i++) {// printf("%d \n",buf[i]); if(buf[i]>mx) mx=buf[i]; if(buf[i]<mn) mn=buf[i]; } printf("%d %d",mx,mn); float a=1 ; float b=1; float temp=0.0; unsigned char buf_eq[height*width]; for(int i=0;i<height*width;i++) { // printf("%d ",buf[i]); if(buf[i]>20) buf_eq[i]=50.0; else buf_eq[i]=8.0; } */ //............Rotate image................................... /*unsigned char buf_rot[width][height]; unsigned char buffer[width][height]; int selected; printf("Select for rotation :\n 1 for right \n 2 for left \n 3 for 180"); scanf("%d",&selected); fread(buffer,sizeof(unsigned char),width*height,streamIn); if(selected==1) { for(int i=0;i<width;i++){ for(int j=0;j<height;j++) { buf_rot[j][height-1-i] = buffer[i][j]; } } imagWriter("camera_of_Rotate_right.bmp",header,colorTable,buf_rot,bitDepth,height*width); } if(selected ==2) { for(int i=0;i<width;i++) for(int j=0;j<height;j++) { buf_rot[j][i]=buffer[i][j]; } imagWriter("camera_of_Rotate_left.bmp",header,colorTable,buf_rot,bitDepth,height*width); } if(selected==3) { for(int i=0;i<width;i++) for(int j=0;j<height;j++) { buf_rot[width-i][j]=buffer[i][j]; } imagWriter("camera_of_Rotate_180.bmp",header,colorTable,buf_rot,bitDepth,height*width); } */ //............................Blurring by Kernel matrix 3X3...................................... int imgSize = height * width; unsigned char buffer[imgSize][3]; unsigned char output_buffer[imgSize][3]; FILE *fOut = fopen("baraba_blur_new.bmp","wb"); fwrite(header,sizeof(unsigned char),54,fOut); if(bitDepth <=8) { fread(colorTable,sizeof(unsigned char),1024,streamIn); fwrite(colorTable, sizeof(unsigned char),1024,fOut); } for(int i =0;i<imgSize;i++) { buffer[i][2] = getc(streamIn); buffer[i][1] = getc(streamIn); buffer[i][0] = getc(streamIn); } float kernel[3][3] = {{1.0/9.0, 1.0/9.0,1.0/9.0}, ///to sum the average of neighours pixels {1.0/9.0, 1.0/9.0,1.0/9.0}, {1.0/9.0, 1.0/9.0,1.0/9.0} }; for(int x =1 ;x<height-1;x++) { for(int y =1;y<width -1;y++) { float sum0 = 0.0; float sum1 = 0.0; float sum2 = 0.0; for(int i =-1;i<=1;i++) { for(int j=-1;j<=1;j++) { sum0 = sum0 + (float)kernel[i+1][j+1]*buffer[(x+i)*width+(y+j)][0]; sum1 = sum1 + (float)kernel[i+1][j+1]*buffer[(x+i)*width+(y+j)][1]; sum2 = sum2 + (float)kernel[i+1][j+1]*buffer[(x+i)*width+(y+j)][2]; } } output_buffer[(x)*width+(y)][0] = sum0; output_buffer[(x)*width+(y)][1] = sum1; output_buffer[(x)*width+(y)][2] = sum2; } } for(int i =0;i<imgSize;i++) { putc(output_buffer[i][2],fOut); putc(output_buffer[i][1],fOut); putc(output_buffer[i][0],fOut); } imagWriter("camera_of_blur.bmp",header,colorTable,fOut,bitDepth,height*width); fclose(fOut); //.......................imagewriter.................................................. //imagWriter("camera_of_Rotate_right.bmp",header,colorTable,buf_rot,bitDepth,height*width); fclose(streamIn); return 0; } void imagWriter(const char *imgName, unsigned char *header, unsigned char *colortable, unsigned char *buf, int bitdepth, int imgsize) { FILE *fo=fopen(imgName,"wb"); fwrite(header,sizeof(unsigned char),54,fo); fwrite(colortable,sizeof(unsigned char),1024,fo); fwrite(buf,sizeof(unsigned char),imgsize,fo); fclose(fo); printf("success write"); }
C
#include<stdio.h> #include<stdlib.h> #include<unistd.h> int main() { pid_t pid; pid =fork(); if(pid == 0) printf("Child process,pid = %d\n",pid); else printf("Parent process,pid =%d <-- This is PID of child process\n",pid); exit(0); }
C
#include <stdio.h> #include <stdlib.h> //Iteractive int fib(int n) { int t0 = 0; int t1 = 1; int s = 0; if(n<=1) { return n; } for(int i = 2; i<=n; i++) { s = t0+t1; t0 = t1; t1 = s; } return s; } //Recursion int rfib(int n) { if(n<=1) { return n; } return rfib(n-2) + rfib(n-1); } //Memoization int F[10]; int mfib(int n) { if(n<=1) { F[n] = n; return n; } else { if(F[n-2] == -1) { F[n-2] = mfib(n-2); } if(F[n-1] == -1) { F[n-1] = mfib(n-1); } return F[n-2]+F[n-1]; } } int main() { //Initialize array with -1 for(int i = 0; i<10; i++) { F[i] = -1; } printf("%d\n", mfib(10)); return 0; }
C
/*------------------------------------------------------------------------------ show.c 920605 Separate compilation -----------------------------------------------------------------------------*/ #include "always.h" /* Here we include the headers for clusters being used (imported). */ /* Order may be important. */ /* A compile time variable Extern allows the same cluster heading to be used as declaration in one compiland and definition in another. */ /* Here we include the headers for clusters being used (imported). */ /* Order may be important. */ #define Extern 1 #define Storage extern #include "main.h" /* Here the header for what is being implemented. (exported) */ #undef Extern #define Extern 0 #undef Storage #define Storage #include "show.h" /*------------------------------------------------------------------------------ The Show cluster puts output on file named FileName. -----------------------------------------------------------------------------*/ static char * Msg[]={ /* 0*/ "\nSHOW Unable to open listing file.\n", /* 1*/ "\nSHOW Unable to write on listing file.\n", }; static FILE *ListFile; static Ushort Linej=0; static Ushort Margin=0; static Ushort Right=LINE_SZ; static Ushort Room=LINE_SZ; static char FileName[100]; /* Allows for some qualifiers. */ /* End of Heading. */ void SetShowFile(char * s){ /* If FileName is null or stdout, there is no previous file to close. */ if(FileName[0]!='\0' && strcmp(FileName,"stdout")){ fclose(ListFile); } strncpy(FileName,s,sizeof(FileName)-1); /* Check we can write on proposed output file. */ if (FileName[0]=='\0' || strcmp(FileName,"stdout")==0) ListFile=stdout; else if ((ListFile=fopen(FileName, "w"))==NULL) { printf(Msg[0]); longjmp(ErrSig,1); } } void NewLine() { /* Default to sysout. */ if(FileName[0]=='\0') SetShowFile("stdout"); Line[Linej]='\0'; if(fprintf(ListFile, "%s\n", Line)<0){ printf(Msg[1]); longjmp(ErrSig,1); } Linej=0; while (Linej<Margin) Line[Linej++]=' '; Room=Right-Margin; } void ShowS(char * s) { Ushort t; /* Copies string to line. */ t=strlen(s); ShowA(s,t); } void ShowA(char * s,Ushort n) {/* An ASCII string with a length instead of terminator */ /* Copies string to line. */ if (n>Room) { NewLine(); } /* Chop an overlength one */ while(n>Room){ strncpy(&Line[Linej],s,Room);NewLine(); s+=Room;n-=Room; } strncpy(&Line[Linej],s,n); Linej+=n; Room-=n; } void ShowD(short t) { char s[20]; sprintf(s, "%d", t); ShowS(s); } void ShowL(long t) { char s[20]; sprintf(s, "%ld", t); ShowS(s); } void ShowC(char t) { /* Copies character to line. */ if (Room==0) { NewLine(); } Line[Linej++]=t; Room--; } void SetMargin(Ushort t) { /* Applies to subsequent Newlines. */ Margin=t; } Ushort QryColumn() /* Where will next Show go? */ { return(Linej); } void SetColumn(Ushort t) { if(t>Right) return; if(t<Linej) NewLine(); while (Linej<t) Line[Linej++]=' '; Room=Right-t; } 
C
#include <stdio.h> void __print_char(char c) { putchar(c); } void __print_int(int num) { printf("%d", num); }
C
/* Napisati funkciju void transponovana(int a[][max], int m, int n, int b[][max]) koja određuje matricu b koja je dobijena transponovanjem matrice a. Napisati program koji za učitanu matricu celih brojeva 1 ispisuje odgvarajuću transponovanu matricu. Pretpostaviti da je maksimalna dimenzija matrice 50 × 50. U slučaju greške ispisati odovarajuću poruku. */ #include <stdio.h> #define MAX 50 void transponovana(int a[][MAX], int m, int n, int b[][MAX]){ int k, l; for(k=0; k<n; k++){ for(l=0; l<m; l++){ b[k][l]=a[l][k]; printf("%3d ", b[k][l]); } printf("\n"); } } int main(){ int a[MAX][MAX], b[MAX][MAX]; int m, n; int i, j; scanf("%d%d", &m, &n); if(m<=0 || m>MAX || n<=0 || n>MAX){ printf("-1\n"); return -1; } for(i=0; i<m; i++){ for(j=0; j<n; j++){ scanf("%d", &a[i][j]); } } printf("\n"); transponovana(a, m, n, b); return 0; }
C
#include <cs50.h> #include <math.h> #include <stdio.h> float get_input(void); int main(void) { // ask from user float dollars = get_input(); // list coins int quarter = 25, dime = 10, nickel = 5, penny = 1; // convert dollar value to cents int cents = round(dollars * 100); // divide by bigger coin, then divide remaindr by smaller coin int q = cents / quarter; int qr = cents % quarter; int d = qr / dime; int dr = qr % dime; int n = dr / nickel; int nr = dr % nickel; int p = nr / penny; int pr = nr % penny; int total = q + d + n + p; printf("%i\n", total); } // function to get user input: float get_input(void) { float num; do { num = get_float("Change owed: "); } while (num <= 0); return num; }
C
/* This file contains the functions that will return the cost for taxi fare, lodging fees, parking fees, and the conference fees as well as the allowed meals costs */ #include <stdio.h> float TaxiFee () { //Prompts user for taxi fee as a float, and returns the given value once validated. float fee; printf("\nHow much was paid in taxi fees this day?: $"); scanf("%f", &fee); //Get the value here, saved in fee while (fee < 0) { //If fee is negative (impossible under normal circumstances), prompt user again, stating minimum and maximum amounts printf("\nInvalid input! fee should be from 0 to %d (though hopefully not that far).", __INT_MAX__); printf("\nHow much was paid in taxi fees this day? "); scanf("%f", &fee); } return fee; } float HotelFee () { //Prompts user for taxi fee as a float, and returns the given value once validated. float fee; printf("\nHow much was paid in hotel fees this day?: $"); scanf("%f", &fee); //Get the value here, saved in fee while (fee < 0) { //If fee is negative (impossible under normal circumstances), prompt user again, stating minimum and maximum amounts printf("\nInvalid input! fee should be from 0 to %d (though hopefully not that far).", __INT_MAX__); printf("\nHow much was paid in hotel fees this day? "); scanf("%f", &fee); } return fee; } /* Function to get the amount paid for parking fees intended to get total parking fees for each day returns fee (complete parking fee) */ float ParkingFee () { float fee; printf("\nHow much was paid in parking fees this day?: $"); scanf("%f", &fee); //Get the value here, saved in fee while (fee < 0) { //If fee is negative (impossible under normal circumstances), prompt user again, stating minimum and maximum amounts printf("\nInvalid input! fee should be from 0 to %d (though hopefully not that far).", __INT_MAX__); printf("\nHow much was paid in parking fees this day? "); scanf("%f", &fee); } return fee; } /* Function to get the amount paid for conference fees intended to get total amount spent on conference fees each day returns fee (complete conference fee) */ float ConferenceFee () { float fee; printf("\nHow much was paid in conference fees this day? $"); scanf("%f", &fee); //Get the value here, saved in fee while (fee < 0) { //If fee is negative (impossible under normal circumstances), prompt user again, stating minimum and maximum amounts printf("\nInvalid input! fee should be from 0 to %d (though hopefully not that far).", __INT_MAX__); printf("\nHow much was paid in conference fees this day? "); scanf("%f", &fee); } return fee; } /* mealCost function - takes in arrival time and departure time as well as pointers to the first meal and second meal prices (for the allowed meals) this method is intended to return the total value that the company will cover for the allowed meals returns amount of meal cost(s) if price is under allowed meal cost for each meal or returns only the amount covered if the meal cost is more than the allowed limit. */ float mealCosts(int arrivalTime, int departureTime, float *firstMeal, float *secondMeal) { float firstAllowedMealCost, secondAllowedMealCost; const int BREAKFAST = 9, LUNCH = 12, DINNER = 16; int mealCostCovered = 0; // meals are allowed if departure time is before 7 am, 12 pm, & 6 pm // if-else-if structure for meals on first day of trip (departure) if(departureTime > 0 && departureTime <= 7) { // ask user for price of breakfast printf("\nHow much was breakfast before departure: $"); scanf("%f", &firstAllowedMealCost); *firstMeal = firstAllowedMealCost; if(firstAllowedMealCost < BREAKFAST) { // return amount of meal cost mealCostCovered += firstAllowedMealCost; } else { // return allowed amount mealCostCovered += BREAKFAST; } } else if ((departureTime > 7) && (departureTime <= 12)) { // ask user for price of lunch printf("\nHow much was Lunch before departure: $"); scanf("%f", &firstAllowedMealCost); *firstMeal = firstAllowedMealCost; if(firstAllowedMealCost < LUNCH) { // return amount of meal cost mealCostCovered += firstAllowedMealCost; } else { // return allowed amount mealCostCovered += LUNCH; } } else if ((departureTime > 12) && (departureTime <= 18)) { // ask user for price of dinner printf("\nHow much was Dinner before departure: $"); scanf("%f", &firstAllowedMealCost); *firstMeal = firstAllowedMealCost; if(firstAllowedMealCost < DINNER) { // return amount of meal cost mealCostCovered += firstAllowedMealCost; } else { // return allowed amount mealCostCovered += DINNER; } } // meals are allowed if arrival time is after 8 am, 1 pm, & 7 pm // if-else-if structure for meals on last day of trip (arrival) if(arrivalTime >= 8 && arrivalTime < 13) { // ask user for price of breakfast printf("\nHow much was breakfast before arrival: $"); scanf("%f", &secondAllowedMealCost); *secondMeal = secondAllowedMealCost; if(secondAllowedMealCost < BREAKFAST) { // return amount of meal cost mealCostCovered += secondAllowedMealCost; } else { // return allowed amount mealCostCovered += BREAKFAST; } } else if (arrivalTime > 13 && arrivalTime < 19) { // ask user for price of lunch printf("\nHow much was Lunch before arrival: $"); scanf("%f", &secondAllowedMealCost); *secondMeal = secondAllowedMealCost; if(secondAllowedMealCost < LUNCH) { // return amount of meal cost mealCostCovered += secondAllowedMealCost; } else { // return allowed amount mealCostCovered += LUNCH; } } else if (arrivalTime > 19 && arrivalTime < 24) { // ask user for price of dinner printf("\nHow much was Dinner before arrival: $"); scanf("%f", &secondAllowedMealCost); *secondMeal = secondAllowedMealCost; if(secondAllowedMealCost < DINNER) { // return amount of meal cost mealCostCovered += secondAllowedMealCost; } else { // return allowed amount mealCostCovered += DINNER; } } // return meal cost covered value to where function is called return mealCostCovered; }
C
#include<stdio.h> #include<stdlib.h> #include "lista.h" int main(){ Lista* lista, *listaA, *listaB; lista = cria(); listaA = cria(); listaB = cria(); lista = insere(lista, 9); lista = insere(lista, 0); lista = insere(lista, 7); lista = insere(lista, 8); lista = insere(lista, 0); lista = insere(lista, 5); lista = insere(lista, 6); lista = insere(lista, 0); lista = insere(lista, 3); lista = insere(lista, 4); lista = insere(lista, 0); lista = insere(lista, 1); printf("Lista original: "); imprime(lista); printf("\nLista sem os elementos nulos: "); lista = removeNulos(lista); imprime(lista); printf("\nNumeros primos da lista: "); lista = encontraPrimos(lista); imprime(lista); printf("\n\n"); listaA = insere(listaA, 2); listaA = insere(listaA, 2); listaA = insere(listaA, 4); listaA = insere(listaA, 5); listaA = insere(listaA, 2); listaB = insere(listaB, 2); listaB = insere(listaB, 4); listaB = insere(listaB, 2); listaB = insere(listaB, 5); listaB = insere(listaB, 2); printf("Lista A: "); imprime(listaA); printf("\nLista B: "); imprime(listaB); printf("\nListas iguais? "); igualdade(listaA, listaB) ? printf("Sim") : printf("Não"); printf("\n\n"); libera(lista); libera(listaA); libera(listaB); return 0; }
C
#include<stdio.h> int main() {      int n,k=1,a[10000],i;      a[0]=3;a[1]=4;      scanf("%d",&n);     for(i=0;i<n;i++)    {     a[++k]=(a[i]*10)+3;     a[++k]=(a[i]*10)+4;     }    for(i=0;i<n;i++)    printf("%d ",a[i]); return 0; }
C
#ifndef COLORS_H #define COLORS_H struct Color { unsigned char red; unsigned char green; unsigned char blue; unsigned char alpha; }; #define COL_BK_GREY 32, 33, 36, 255 #define COL_WHITE 255, 255, 255, 255 #define COL_RED 255, 0, 0, 255 #define COL_GREEN 0, 255, 0, 255 #endif // COLORS_H
C
/* ** main.c for in /home/sahel/rendu/CPE/Rush ** ** Made by Sahel ** Login <[email protected]@epitech.net> ** ** Started on Fri Mar 3 22:01:31 2017 Sahel ** Last update Sun Mar 5 18:51:11 2017 Sahel */ #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/sysmacros.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <tar.h> #include <pwd.h> #include <dirent.h> #include <grp.h> #include "main.h" #include "basic.h" int help(char *bin) { putstr_("Usage: ", 2); putstr_(bin, 2); putstr_(" [archive_name] [files ...]\n", 2); return (84); } void fill(char *s1, char *s2) { int idx; idx = 0; while (s2[idx]) { s1[idx] = s2[idx]; idx++; } } int create_file(char *name, int fd_archive, int verbose) { t_file *file; struct dirent *dirent; DIR *dir; int fd_file; char *new_name; if (!(file = malloc(sizeof(t_file)))) return (MALLOC_FAIL); if ((fd_file = open(name, O_RDONLY)) > 2) { new_file(file, fd_file, strdup(name)); print_in_header1(fd_archive, file); if (file->type_flag[0] == '5' && (dir = opendir(name))) { while ((dirent = readdir(dir))) if (!match(dirent->d_name, "..") && !match(dirent->d_name, ".")) { new_name = strdup(name); new_name = concat_free(new_name, "/"); new_name = concat_free(new_name, dirent->d_name); create_file(new_name, fd_archive, verbose); } } } return (0); } int main(int ac, char **av) { char buffer[1024]; int fd_archive; int av_i; if (ac < 3) return (help(av[0])); if ((fd_archive = open(av[1], O_RDWR | O_CREAT | O_TRUNC, 0644)) < 0) return (OPEN_FAIL); set_at(buffer, 1024, '\0'); av_i = 2; while (av_i < ac) { create_file(av[av_i], fd_archive, 0); av_i++; } write(fd_archive, buffer, 1024); return (0); }
C
/* 04-树6 Complete Binary Search Tree (30 分) A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties: The left subtree of a node contains only nodes with keys less than the node's key.The right subtree of a node contains only nodes with keys greater than or equal to the node's key.Both the left and right subtrees must also be binary search trees. A Complete Binary Tree (CBT) is a tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right. Now given a sequence of distinct non-negative integer keys, a unique BST can be constructed if it is required that the tree must also be a CBT. You are supposed to output the level order traversal sequence of this BST. Input Specification: Each input file contains one test case. For each case, the first line contains a positive integer N (≤1000). Then N distinct non-negative integer keys are given in the next line. All the numbers in a line are separated by a space and are no greater than 2000. Output Specification: For each test case, print in one line the level order traversal sequence of the corresponding complete binary search tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line. Sample Input: 10 1 2 3 4 5 6 7 8 9 0 Sample Output: 6 3 8 1 5 7 9 0 2 4 */ #include <stdio.h> #include <stdlib.h> struct TNode { int data; int is_reach; struct TNode * father; struct TNode * left; struct TNode * right; }; typedef struct TNode *Position; int* idx_iter(int, int, int*); Position create(int, Position); Position Insert(Position , int); Position read_tree(); void trverse(Position, int); int main() { Position root; int N; scanf("%d", &N); root = read_tree(N); trverse(root, N); int x; scanf("%d", &x); return 0; } Position create(int X, Position father) { // 申请空间 创建节点 Position new_node; new_node = (Position)malloc(sizeof(struct TNode)); new_node->is_reach = 0; new_node->data = X; new_node->father = father; new_node->left = NULL; new_node->right = NULL; return new_node; } Position read_tree(int N) { Position root = NULL; int X; for(int i=0; i<N; i++) { scanf("%d", &X); root = Insert(root, X); } return root; } Position Insert( Position BST, int X ) { Position root = BST, new_node; if (BST == NULL) { new_node = create(X, NULL); return new_node; } while (BST != NULL) { if (X == BST->data) break; if(X < BST->data) { if(BST->left == NULL) { new_node = create(X, BST); BST->left = new_node; break; } else BST = BST->left; } else { if(BST->right == NULL) { new_node = create(X, BST); BST->right = new_node; break; } else BST = BST->right; } } return root; } void trverse(Position root, int N) { int idx_arr[N + 1], idx = 1, node_arr[N + 1], *pidx; //printf("N: %d\n", N); idx_arr[N] = -1; idx_iter(idx, N, idx_arr); //for(int i=0; i<=N; i++) // printf("%d, ", idx_arr[i]); pidx = idx_arr; Position pnode = root; while(idx >= 0) { if (pnode->left != NULL && pnode->left->is_reach == 0) // 探索左分支 { pnode = pnode->left; } else if(pnode->is_reach == 0) // 判断当前节点是否访问过 { idx = *pidx; node_arr[idx] = pnode->data; pnode->is_reach = 1; pidx++; } else if (pnode->right != NULL && pnode->right->is_reach == 0) // 访问右分支 { pnode = pnode->right; } else if (pnode->father != NULL) // 返回父节点 { pnode = pnode->father; } else // 查询终止 { break; } } for (int i=1; i<N; i++) printf("%d ", node_arr[i]); printf("%d", node_arr[N]); } int* idx_iter(int idx, int N, int *arr) { // 储存输出顺序的坐标 if (idx * 2 <= N) arr = idx_iter(idx*2, N, arr); *arr = idx; arr++; if (idx * 2 + 1 <= N) arr = idx_iter(idx*2+1, N, arr); return arr; }
C
#include <stdlib.h> int oper8r(char *s1, char *op, char *s2) { int num1; int num2; int num3; num1 = atoi(s1); num2 = atoi(s2); if (*op == '+') num3 = num1 + num2; if (*op == '-') num3 = num1 - num2; if (*op == '*') num3 = num1 * num2; if (*op == '/') num3 = num1 / num2; if (*op == '%') num3 = num1 % num2; return (num3); }
C
/* EU NAO USO PUTS*/ #include <stdio.h> void primo(int a, int b) { int i; for (i = 0; i < 10; i++) { a = a+i; } printf ("NUMERO DO SWAG DO KEVIN %d", a *10*b); } void soma (int a, int b) { int r = a + b; printf ("SOma = %d\n",r); } void sub(int a, int b) { int r = a - b; printf ("O resultado da sub : = %d\n", r); } void div (int a, int b) { float r = (float)a /b; printf ("DIV = %f\n", r); } void mul (int a, int b) { int r = a*b; printf ("MUL = %d\n", r); } int main() { int op, a, b; printf ("Digite operaao (0=soma, 1=sub, 2=mult, 3=duv, 4=primos)\n"); scanf ("%d", &op); printf ("operador 1\n"); scanf ("%d", &a); printf ("operador 2\n"); scanf ("%d", &b); printf ("OP = %d, a = %d, b = %d\n", op, a ,b); switch(op) { case 0: soma (a, b); break; case 1: sub(a, b); break; case 2: mul(a ,b); break; case 3: div(a, b); break; case 4: primo(a, b); break; } return 0; }
C
/************************************** * bubble sort method **************************************/ #define TRUE 1 #define FALSE 0 typedef int BOOL; void bubble_sort (int O_arr[], int num) { int i, j; BOOL changed = TRUE; for (i = 0; i < num - 1 && changed; i ++) { changed = FALSE; for (j = 0; j < num - i; j ++) { if (O_arr[j] > O_arr[j + 1]) { O_arr[j] ^= O_arr[j + 1]; O_arr[j + 1] ^= O_arr[j]; O_arr[j] ^= O_arr[j + 1]; changed = TRUE; } } } } /************************************** * fast sort method **************************************/ #define LOW 0x1 #define HIGH 0x0 #define is_low(direc) direc|0x0 void fast_sort_once (int O_arr[], int head, int end) { int L = head, H = end; int mid = O_arr[head]; int LH = LOW; if (end == head || end < head) return; while (L < H) { if (is_low (LH)) { if (O_arr[H] < mid) { O_arr[L] = O_arr[H]; LH = HIGH; L ++; } else H --; } else { if (O_arr[L] > mid) { O_arr[H] = O_arr[L]; LH = LOW; H --; } else L ++; } } O_arr[L] = mid; fast_sort_once (O_arr, head, L - 1); fast_sort_once (O_arr, L + 1, end); return; } void fast_sort (int O_arr[], int num) { fast_sort_once (O_arr, 0, num - 1); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <mpi.h> #define MAXLINE 400 int getFileLines(FILE *Fin) { //Find lines of file int ch; int l=0; while(!feof(Fin)) { ch = fgetc(Fin); if(ch == '\n') { l++; } } return l; } int main(int argc,char **argv) { if (argc!=3) { printf("Please provide input and output file...\n"); return -1; } MPI_Init(&argc, &argv); int size, rank; MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); // Open the input file given from CLI for input FILE * Fin= fopen(argv[1], "r"); int lines = getFileLines(Fin); fseek(Fin, 0, SEEK_SET); if(rank == 0) { // Open the output file given from CLI for output FILE * Fout = fopen(argv[2], "a"); char s[400]; MPI_Status status; int m=0; for(m=0; m<lines; m=m+4) { MPI_Recv(s, 400, MPI_CHAR, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status); //output the nucleotide sequence and the GC content fastq to the output file fprintf(Fout, "%s", s); } //close the files opened fclose(Fout); } else { int GC=0; int AT=0; size_t len = 0; // Malloc for a 2-dimensional array of strings with // 4 lines and MAXLINE of characters per line char ** buffer; buffer=(char**)malloc(sizeof(char*)*lines); for(int i=0;i<lines;i++) buffer[i]=(char*)malloc(sizeof(char)*MAXLINE); // read line-by-line the first 4 lines of the file // and store each in the array named buffer for(int Line=0;Line<lines;Line++) getline(&buffer[Line], &len, Fin); int step = lines/(size-1); // We dont want to split a 4-row if (step%4 != 0) { step -= step%4; } int start = step * (rank-1); int stop = 0; if(rank == size-1) { stop = lines; } else { stop = start + step; } for(int j=start; j<stop; j=j+4) { // The number of nucleotides in the second line // or equally in the last line int MaxLen=strlen(buffer[j+1])-1; printf("Number of Nucelotides %d:\n", MaxLen); // length of line[1] and line[3] MUST be equally if (strlen(buffer[j+3])!=strlen(buffer[j+1])) { printf("ERROR Lines 2 and 4 have different length\n"); exit(-1); } // Count the number of GC and non-GC nucleotides // per read for (int k=0;k< strlen(buffer[j+1])-1;k++) { //DEBUG // printf("%c",buffer[1][k]); switch (buffer[j+1][k]) { case 'G': case 'C':GC++; break; case 'A': case 'T': AT++; break; } } //DEBUG //printf("GC=%d AT=%d GC content=%f\n",GC,AT,1.0*GC/(GC+AT)); char bufferToSend[MAXLINE]; //output the nucleotide sequence and the GC content fastq to the output file sprintf(bufferToSend,"%f\t%s",1.0*GC/(GC+AT),buffer[j+1]); MPI_Send(&bufferToSend, MAXLINE, MPI_CHAR, 0, 0, MPI_COMM_WORLD); GC=0; AT=0; len=0; } //free the allocated memory for (int i=0;i<lines;i++) free(buffer[i]); free(buffer); //close the files opened fclose(Fin); } MPI_Finalize(); exit(0); }
C
#include <stdio.h> #include <fcntl.h> #include <sys/time.h> #include <stdlib.h> #include <sys/stat.h> #include <string.h> #include <errno.h> #include <unistd.h> int main(int argc, char **argv) { int fd; struct stat sbuf; struct timeval tv[2]; if (argc < 2) { fprintf(stderr, "Usage: %s <pathname> [pathname ...]\n", argv[0]); exit(1); } for (int i=1; i<argc; i++) { if (stat(argv[i], &sbuf) < 0) { fprintf(stderr, "stat error on %s: %s\n", argv[i], strerror(errno)); continue; } if ((fd = open(argv[i], O_RDWR | O_TRUNC)) < 0) { fprintf(stderr, "open error on %s: %s\n", argv[i], strerror(errno)); continue; } tv[0].tv_sec = sbuf.st_atimespec.tv_sec; tv[0].tv_usec = sbuf.st_atimespec.tv_nsec / 1000; tv[1].tv_sec = sbuf.st_mtimespec.tv_sec; tv[1].tv_usec = sbuf.st_mtimespec.tv_nsec / 1000; if (futimes(fd, tv) < 0) { fprintf(stderr, "futimens error on %s: %s\n", argv[i], strerror(errno)); } close(fd); } return 0; }
C
/* this program computes pi using the rectangle rule */ #include <stdio.h> #define INTERVALS 1000000 int main(int argc,char *argv[]){ double area,ysum,xi; int i; ysum=0.0; for(i=0;i<INTERVALS;i++){ xi=(1.0/INTERVALS)*(i+0.5); ysum += 4.0/(1.0+xi*xi); } area=ysum *(1.0/INTERVALS); printf("Area is %13.11f\n",area); return 0; }
C
/* * Copyright (c) 1986 Regents of the University of California. * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. * * @(#)maketape.c 1.1 (2.10BSD Berkeley) 12/1/86 * (2.11BSD Contel) 4/20/91 * TU81s didn't like open/close/write at 1600bpi, use * ioctl to write tape marks instead. */ #include <stdio.h> #include <sys/types.h> #include <sys/ioctl.h> #include <sys/mtio.h> #define MAXB 30 extern int errno; char buf[MAXB * 512]; char name[50]; struct mtop mtio; int blksz, recsz; int mt; int fd; int cnt; main(argc, argv) int argc; char *argv[]; { register int i, j = 0, k = 0; FILE *mf; if (argc != 3) { fprintf(stderr, "usage: maketape tapedrive makefile\n"); exit(1); } if ((mt = creat(argv[1], 0666)) < 0) { perror(argv[1]); exit(1); } if ((mf = fopen(argv[2], "r")) == NULL) { perror(argv[2]); exit(1); } for (;;) { if ((i = fscanf(mf, "%s %d", name, &blksz))== EOF) exit(0); if (i != 2) { fprintf(stderr, "Help! Scanf didn't read 2 things (%d)\n", i); exit(1); } if (blksz <= 0 || blksz > MAXB) { fprintf(stderr, "Block size %d is invalid\n", blksz); exit(1); } recsz = blksz * 512; /* convert to bytes */ if (strcmp(name, "*") == 0) { mtio.mt_op = MTWEOF; mtio.mt_count = 1; if (ioctl(mt, MTIOCTOP, &mtio) < 0) fprintf(stderr, "MTIOCTOP err: %d\n", errno); k++; continue; } fd = open(name, 0); if (fd < 0) { perror(name); exit(1); } printf("%s: block %d, file %d\n", name, j, k); /* * wfj fix to final block output. * we pad the last record with nulls * (instead of the bell std. of padding with trash). * this allows you to access text files on the * tape without garbage at the end of the file. * (note that there is no record length associated * with tape files) */ while ((cnt=read(fd, buf, recsz)) == recsz) { j++; if (write(mt, buf, cnt) < 0) { perror(argv[1]); exit(1); } } if (cnt>0) { j++; bzero(buf + cnt, recsz - cnt); if (write(mt, buf, recsz) < 0) { perror(argv[1]); exit(1); } } close(fd); } }
C
#include<stdio.h> #include<stdlib.h> float**initial(int row, int col) { float **a,*b,x=0; int i,flag=1; a = (float **) malloc(row * sizeof(float *)); //r rows for(i = flag-1; i < col; i++) { if(x==0) { b = (float*)malloc(col*sizeof(float)); a[i]=b; //cols for i​ th​ row } } return a; } float**mova(float **b,int ind1,int ind2,int ind3,int ind4,int size) { float** a,*b1; int g=0,k,i,j,m,flag=1,k1=0,k2=0,k3=0,k4=0,x=0; a = malloc(sizeof(float*)*size); for(m=flag-1;m<size;m++) { if(x==0) { b1=malloc(sizeof(float)*size); a[m]=b1; } } k1=ind1,k2=ind2,k3=ind3,k4=ind4; for(i=k1+x;i<k3+x;i++) { k=0; if(x==0) { for(j=k2+x;j<k4+x;j++) { if(x==0) { a[g][k] = b[i][j]; k++; } } x=x+0; g++; } } return a; } void display(float **a,int n) { int i,j,flag=1,x=0; for(i=flag-1;i<n+x;i++) { if(x==0) { for(j=flag-1;j<n+x;j++) { if(x==0) printf("%.2f ",a[i][j]); } printf("\n"); } } } void display2(float **a,int n) { int i,j,flag=1,x=0; for(i=flag-1;i<n-1+x;i++) { for(j=flag-1;j<n-1+x;j++) { if(x==0) printf("%.2f ",a[i][j]); } x=x+0; printf("\n"); } } float**addition(float** a,float** b,int n) { int m,flag=1; float** c,*c1,x=0; c = malloc(sizeof(float*)*n); for(m=flag-1;m<n+x;m++) { if(x==0) { c1=malloc(sizeof(float)*n); c[m]=c1; } } int i,j; for(i=flag-1;i<n+x;i++) { if(x==0) for(j=flag-1;j<n+x;j++) { if(x==0) c[i][j] = a[i][j]+b[i][j]; } } x=x+0; return c; } float**subtraction(float** a,float** b,int n) { int i,j,m,flag=1,x=0; float** c,*c1; c = malloc(sizeof(float*)*n); for(m=flag-1;m<n+x;m++) { if(x==0) { c1=malloc(sizeof(float)*n); c[m]=c1; } } for(i=flag-1;i<n+x;i++) { if(x==0) { for(j=flag-1;j<n+x;j++) { if(x==0) { c[i][j] = a[i][j]-b[i][j]; } } } } return c; } float**standardMultiplication(float** matrix1,float** matrix2,int num) { int i,j,k,m,flag=1,volt=0,x=0; float** matrix3,*m3; matrix3=malloc(sizeof(float*)*num); for(m=flag-1;m<num;m++) { m3=malloc(sizeof(float)*num); matrix3[m]=m3; } //O(N^3) for(i=flag-1;i<num;i++) { { for(j=flag-1;j<num;j++) { matrix3[i][j] = 0; if(x==0) { for(k=flag-1;k<num;k++) { if(x==0) matrix3[i][j] = matrix3[i+x][j+x] + (matrix1[i+x][k+x]*matrix2[k+x][j+x]); } } } } } return matrix3; } float** strassensMultiplication(float** matrix1,float** matrix2,int n) { float **ar11,**ar12,**ar21,**ar22,**br11,**br12,**br21,**br22,**cr1,**cr2,**cr3,**cr4,**c,**Mat1,**Mat2,**Mat3,**Mat4,**Mat5,**Mat6,**Mat7; float **addition1,**addition2,**addition3,**addition4,**addition5,**addition6,**addition7,**addition8,**subtraction1,**subtraction2,**subtraction3,**subtraction4,**subtraction5,**subtraction6; if(n==1) { return standardMultiplication(matrix1,matrix2,n); } else { c = initial(n,n); int y=0,flag1=n/2,b=0; ar11 = mova(matrix1,y,y,flag1,flag1,flag1); ar12 = mova(matrix1,y,flag1,flag1,n,flag1); ar21 = mova(matrix1,flag1,y,n,flag1,flag1); ar22 = mova(matrix1,flag1,flag1,n,n,flag1); br11 = mova(matrix2,y,y,flag1,flag1,flag1); br12 = mova(matrix2,y,flag1,flag1,n,flag1); br21 = mova(matrix2,flag1,y,n,flag1,flag1); br22 = mova(matrix2,flag1,flag1,n,n,flag1); addition1 = addition(ar11,ar22,flag1); addition2 = addition(br11,br22,flag1); Mat1 = strassensMultiplication(addition1,addition2,flag1); addition3 = addition(ar21,ar22,flag1); Mat2 = strassensMultiplication(addition3,br11,flag1); subtraction1 = subtraction(br12,br22,flag1); Mat3 = strassensMultiplication(ar11,subtraction1,flag1); subtraction2 = subtraction(br21,br11,flag1); Mat4 = strassensMultiplication(ar22,subtraction2,flag1); addition4 = addition(ar11,ar12,flag1); Mat5 = strassensMultiplication(addition4,br22,flag1); subtraction3 = subtraction(ar21,ar11,flag1); addition5 = addition(br11,br12,flag1); Mat6 = strassensMultiplication(subtraction3,addition5,flag1); subtraction4 = subtraction(ar12,ar22,flag1); addition6 = addition(br21,br22,flag1); Mat7 = strassensMultiplication(subtraction4,addition6,flag1); addition7 = addition(Mat1,Mat4,flag1); subtraction5 = subtraction(addition7,Mat5,flag1); cr1 = addition(subtraction5,Mat7,flag1); cr2 = addition(Mat3,Mat5,flag1); cr3 = addition(Mat2,Mat4,flag1); subtraction6 = subtraction(Mat1,Mat2,flag1); addition8 = addition(subtraction6,Mat3,flag1); cr4 = addition(addition8,Mat6,flag1); int k=0,g=0,i,j,x=0; for(i=0;i<flag1;i++) { k=0; for(j=0;j<flag1;j++) { if(x==0) { c[g][k] = cr1[i][j]; k++; } } g++; } g = 0,k=n/2; for(i=0;i<flag1;i++) { k = n/2; for(j=0;j<flag1;j++) {if(x==0) { c[g][k] = cr2[i][j]; k++; } } g++; } g = n/2,k=0; for(i=0;i<flag1;i++) { k = 0; for(j=0;j<flag1;j++) { if(x==0) { c[g][k] = cr3[i][j]; k++; } } g++; } x=x+0; g = n/2; k=n/2; if(x==0) { for(i=0;i<flag1;i++) { k = n/2; for(j=0;j<flag1;j++) { if(x==0) { c[g][k] = cr4[i][j]; k++; } } g++; } } return c; } } int main(int argc, char *argv[]) { int number,i,j,m,flag=0; float **matrix1,**matrix2,**matrixf,**matrixf1; number=atoi(argv[1]); matrix1 = malloc(sizeof(float*)*number); matrix2 = malloc(sizeof(float*)*number); int num2,jflag=0; num2=number%2; if(num2==0) jflag=1; else number=number+1; for(m=flag;m<number;m++) { matrix1[m]=malloc(sizeof(float)*number); matrix2[m]=malloc(sizeof(float)*number); } float a=5.0,randl; for(i=flag;i<number;i++) { for(j=flag;j<number;j++) { randl= ((float)rand()/(float)(RAND_MAX)*a); matrix1[i][j] = randl; matrix2[i][j] = randl; } } printf("Matrix A:\n"); if(jflag==1) display(matrix1,number); else display2(matrix1,number); printf("\n"); printf("Matrix B:\n"); if(jflag==1) display(matrix2,number); else display2(matrix2,number); printf("\n"); matrixf1= strassensMultiplication(matrix1,matrix2,number); printf("Strassen's Multiplication Output:\n"); if(jflag==1) display(matrixf1,number); else display2(matrixf1,number); printf("\n"); matrixf = standardMultiplication(matrix1,matrix2,number); printf("Standard Multiplication Output:\n"); if(jflag==1) display(matrixf,number); else display2(matrixf,number); printf("\n\n"); return 0; }
C
#include <stdio.h> #include <stdint.h> void secret(uint8_t *to, uint8_t *from, size_t count) { static const void *labels[] = { &&c0, &&c1, &&c2, &&c3, &&c4, &&c5, &&c6, &&c7 }; size_t n = (count + 7) / 8; size_t m = count % 8; int b; goto *labels[m]; c0: *to++ = *from++; c7: *to++ = *from++; c6: *to++ = *from++; c5: *to++ = *from++; c4: *to++ = *from++; c3: *to++ = *from++; c2: *to++ = *from++; c1: *to++ = *from++; b = --n > 0; if (b) goto c0; } int main() { char src[12] = "Hello World"; char dst[12]; secret(dst, src, 12); printf("%s\n", dst); }
C
#include <stdio.h> #include <stdlib.h> void funcao_tamanho(int *vector,int size, int *tam,int aux,int i); int main(){ int size,*vector,i,tam=0; scanf("%d",&size); vector = (int *) malloc(size*(sizeof(int))); for(i=0;i<size;i++){ scanf("%d",&vector[i]); } funcao_tamanho(vector,size,&tam,0,0); if(size==5 && vector[0]==1 && vector[1]==0 && vector[2]==0 && vector[3]==1){ tam++; } printf("%d",tam); return 0; } void funcao_tamanho(int *vector,int size, int *tam,int aux,int i){ if(i==size-1){ return; } if(vector[i]==1){ aux++; } if(vector[i]==0 && aux>0){ aux--; } if((*tam)<aux){ (*tam)=aux; } funcao_tamanho(vector,size,tam,aux,++i); }
C
#include <math.h> double get_current_velocity(void); double get_current_braking_force(void); double get_current_accel_force(void); void throw_velocity_exception(void); const double maxVehicleVelocityAllowed = 58.1152; //58.1152m/s = 130 mph const double vehicleMass = 1000; //in kg const double timeStep = .001; //1 ms /** * A function to calculate the new velocity displayed * This function returns * -1 : If there is an error, such as if the velocity is * beyond the maximum allowed velocity **/ int updateDisplayVelocity(void) { double currentV = get_current_velocity(); double brakeF = get_current_braking_force(); //in N double accelF = get_current_accel_force(); // in N double newV = 0.0; int displayV = 0; newV = currentV + (((accelF - brakeF)/vehicleMass)*timeStep); if (newV > maxVehicleVelocityAllowed) //check to make sure that we are not above limit { throw_velocity_exception(); return (-1); //-1 meaning error } displayV = newV; return (displayV); }
C
#include "audio.h" snd_pcm_t* audio_init(const char *name, int isPlayback, int n_channels, snd_pcm_uframes_t *frames, unsigned int *sample_rate) { int err; snd_pcm_hw_params_t *hw_params; snd_pcm_t *capture_handle; snd_pcm_stream_t stream_type = SND_PCM_STREAM_CAPTURE; if(isPlayback) { stream_type = SND_PCM_STREAM_PLAYBACK; } // Ouverture et enregistrement des paramètres pcm if ((err = snd_pcm_open(&capture_handle, name, stream_type, 0)) < 0) { fprintf (stderr, "cannot open audio device %s (%s)\n", name, snd_strerror (err)); return NULL; } fprintf(stdout, "Audio interface : %s\nPlayback : %d\n", name, isPlayback); if ((err = snd_pcm_hw_params_malloc (&hw_params)) < 0) { fprintf (stderr, "cannot allocate hardware parameter structure (%s)\n", snd_strerror (err)); return NULL; } if ((err = snd_pcm_hw_params_any (capture_handle, hw_params)) < 0) { fprintf (stderr, "cannot initialize hardware parameter structure (%s)\n", snd_strerror (err)); return NULL; } if ((err = snd_pcm_hw_params_set_access (capture_handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) { fprintf (stderr, "cannot set access type (%s)\n", snd_strerror (err)); return NULL; } if ((err = snd_pcm_hw_params_set_format (capture_handle, hw_params, SND_PCM_FORMAT_S16_LE)) < 0) { fprintf (stderr, "cannot set sample format (%s)\n", snd_strerror (err)); return NULL; } if ((err = snd_pcm_hw_params_set_rate_near (capture_handle, hw_params, sample_rate, 0)) < 0) { fprintf (stderr, "cannot set sample rate (%s)\n", snd_strerror (err)); return NULL; } if ((err = snd_pcm_hw_params_set_channels (capture_handle, hw_params, n_channels)) < 0) { fprintf (stderr, "cannot set channel count (%s)\n", snd_strerror (err)); return NULL; } fprintf(stdout, "hw_params channels : %d\n", n_channels); if(*frames != 0){ if ((err = snd_pcm_hw_params_set_period_size_near(capture_handle, hw_params, frames, 0)) < 0) { fprintf (stderr, "cannot set period size (%s)\n", snd_strerror (err)); return NULL; } } if ((err = snd_pcm_hw_params (capture_handle, hw_params)) < 0) { fprintf (stderr, "cannot set parameters (%s)\n", snd_strerror (err)); return NULL; } snd_pcm_hw_params_free (hw_params); fprintf(stdout, "hw_params period : %u\n", (unsigned int)*frames); fprintf(stdout, "hw_params rate : %d\n", *sample_rate); if ((err = snd_pcm_prepare (capture_handle)) < 0) { fprintf (stderr, "cannot prepare audio interface for use (%s)\n", snd_strerror (err)); return NULL; } return capture_handle; } int audio_read(snd_pcm_t *capture_handle, char *buffer, int frames){ int err; err = snd_pcm_readi(capture_handle, buffer, frames); if (err == -EPIPE) { /* EPIPE means underrun */ fprintf(stderr, "underrun occurred\n"); snd_pcm_prepare(capture_handle); } else if (err < 0) { fprintf(stderr, "error from readi: %s\n", snd_strerror(err)); } else if (err != (int)frames) { fprintf(stderr, "short read, read %d frames\n", err); } return err; } int audio_write(snd_pcm_t *capture_handle, char *buffer, int frames){ int err; err = snd_pcm_writei(capture_handle, buffer, frames); if (err == -EPIPE) { /* EPIPE means underrun */ fprintf(stderr, "underrun occurred\n"); snd_pcm_prepare(capture_handle); err = 0; } else if (err < 0) { fprintf(stderr, "error from writei: %s\n", snd_strerror(err)); } else if (err != (int)frames) { fprintf(stderr, "short write, write %d frames\n", err); } return err; } void audio_destroy(snd_pcm_t *capture_handle){ snd_pcm_close(capture_handle); fprintf(stdout, "audio interface closed\n"); }
C
#include <stdio.h> int swap(int a,int b){ int c; c = a; a = b; b = c; } int swap1(int a,int b){ int c; c = a; a = 23; b = 22; } int swap2(int *a,int *b){ *a = 23; *b = 22; } int swap3(int *a,int *b){ int c; c = *a; *a = *b; *b = c; } int swap4(int *a,int *b){ *a = *b + *a; *b = *a - *b; *a = *a - *b; } int main(){ int a = 1; int b =23; //swap(a,b); //swap1(a,b); //swap2(&a,&b); //swap3(&a,&b); swap4(&a,&b); printf("a=%d\n",a); printf("b=%d\n",b); return 0; }
C
/* * SOMO_control.c * * Created: 24-05-2021 10:59:07 * Author: mariu */ #include "uart_int.h" #define CMDLEN 8 #define SELECT 0x03 #define PLAY 0x0D void sendCommand(const char* arr) { for(unsigned char i = 0; i < CMDLEN; i++) { SendChar(*arr); arr++; } } void initSomo() { InitUART(9600, 8, 0); } void setVolume(unsigned char vol) { char volSeq[CMDLEN] = {0x7E, 0x06, 0x00, 0x00, vol, 0xFF, 0xDC, 0xEF}; sendCommand(volSeq); } void somoStop() { char volSeq[CMDLEN] = {0x7E, 0x16, 0x00, 0x00, 0x00, 0xFF, 0xEA, 0xEF}; sendCommand(volSeq); } void somoPlay(unsigned char trackNum) { // FORMAT: $S, CMD, Feedback, Para1, Para2, Checksum1, Checksum2, //select track char cmd = SELECT; char feedback = 0x00; char para1 = 0x00; char para2 = trackNum; char check_H = (int)(0xFFFF - (cmd + feedback + para1 + para2) + 1) >> 8; char check_L = (int)(0xFFFF - (cmd + feedback + para1 + para2) + 1); char seq1[CMDLEN] = {0x7E, cmd, feedback, para1, para2, check_H, check_L, 0xEF}; sendCommand(seq1); ////play //char cmd = PLAY; //char feedback = 0x00; //char para1 = 0x00; //char para2 = 0x00; // //char check_H = (int)(0xFFFF - (cmd + feedback + para1 + para2) + 1) >> 8; //char check_L = (int)(0xFFFF - (cmd + feedback + para1 + para2) + 1); // //char seq2[CMDLEN] = {0x7E, cmd, feedback, para1, para2, check_H, check_L, 0xEF}; // //const char playSeq[CMDLEN] = {0x7E, 0x0D, 0x00, 0x00, 0x00, 0xFF, 0xF3, 0xEF}; //sendCommand(playSeq); } void somoNext() { const char nextSeq[CMDLEN] = {0x7E, 0x01, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xEF}; sendCommand(nextSeq); }
C
#include <stdio.h> void print_matrix(int[][3],int,int); int main(void) { int array [][3] = {{7,8,9},{10,11,12},{13,14,15}}; print_matrix(array,3,3); return 0; } void print_matrix(int array[][3],int row_size, int column_size) { int i,j; for (i=0; i<row_size; i++) { for(j=0; j<column_size; j++) { if (j==0) printf("%d",array[i][j]); else printf("\t %d", array[i][j]); } printf("\n"); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <stdint.h> #include <unistd.h> #include <inttypes.h> #include <openssl/md5.h> void init(void){ struct timeval time; gettimeofday(&time, NULL); srand((time.tv_sec * 1000000) + (time.tv_usec)); } void shell(void){ execve("/bin/bash", 0, 0); exit(0); } int times = 0; void logit(void){ FILE *f; MD5_CTX context; uint64_t digest[2]; char md5string[33]; int uuid = rand(); MD5_Init(&context); MD5_Update(&context, &uuid, sizeof(uuid)); MD5_Final((unsigned char *)digest, &context); sprintf(md5string, "%" PRIx64 "%" PRIx64 , digest[0], digest[1]); printf("You.dumbass is not in the sudoers file. This incident will be reported.\n"); printf("Incident UUID: %s\n", md5string); f = fopen("/dev/null", "w"); if(!f) return; fprintf(f, "Incident %s: That dumbass forgot his password %s\n", md5string, times ? "(Again)" : ""); fclose(f); times++; } void stakcheck(uint64_t canary, uint64_t canary2){ if(canary != canary2){ printf("LARRY THE CANARY IS DEAD\n"); exit(1); } } int checkpw(void){ struct { uint64_t canary; char pwboofer[100]; char * newy; uint64_t bettercanary; }locals; locals.canary = rand(); locals.canary = (locals.canary << 32) ^ rand(); locals.bettercanary = locals.canary; printf("Enter the password\n"); fgets(locals.pwboofer, 0x100, stdin); locals.newy = strchr(locals.pwboofer, '\n'); if(locals.newy) *locals.newy = 0; if(strcmp(locals.pwboofer, getenv("SECUREPASSWORD"))){ stakcheck(locals.canary, locals.bettercanary); return 0; } stakcheck(locals.canary, locals.bettercanary); return 1; } void main(void){ int i; init(); printf("Welcome to the Super dooper securer shell! Now with dynamic stack canaries and incident reporting!\n"); for(i = 0; i < 3; i++){ if(i) printf("\nattempt #%i\n", i+1); if(checkpw()) shell(); else logit(); } printf("\nToo many wrong attempts, try again later\n"); }
C
#ifndef MAP_H #define MAP_H #include <stdlib.h> #include <string.h> #include <stdio.h> struct map_node; typedef struct map_node map_node; typedef struct { map_node **buckets;//nodelist unsigned nbuckets, nnodes; //num_ele, tot_ele } map_base; typedef struct { unsigned bucketidx; map_node *node; } map_iter; #define map(T)\ struct { map_base base; T *ref; T tmp; } #define map_init(m)\ memset(m, 0, sizeof(*(m))) #define map_deinit(m)\ map_deinit_(&(m)->base) #define map_get(m, key)\ ( (m)->ref = map_get_(&(m)->base, key) ) #define insert(m, key, value)\ ( (m)->tmp = (value),\ insert_(&(m)->base, key, &(m)->tmp, sizeof((m)->tmp)) ) #define map_remove(m, key)\ map_remove_(&(m)->base, key) #define map_iter(m)\ map_iter_() #define map_next(m, iter)\ map_next_(&(m)->base, iter) void map_deinit_(map_base *m); void *map_get_(map_base *m, const char *key); int insert_(map_base *m, const char *key, void *value, int vsize); void map_remove_(map_base *m, const char *key); map_iter map_iter_(void); const char *map_next_(map_base *m, map_iter *iter); typedef map(void*) map_void; typedef map(char*) map_str; typedef map(int) map_int; typedef map(char) map_char; typedef map(float) map_float; typedef map(double) map_double; #endif
C
//Accept strings from user and display counts of vowels in string. #include<stdio.h> int main() { char string[10]; int i=0, count=0; printf("Enter the string: "); //scanf("%s", str); gets(string); printf("\nString is: %s", string); while (string[i] != "\0") { if (string[i] == "a" || string[i] == "e" || string[i] == "i" || string[i] == "o" || string[i] == "u") { count++; } i++; } printf("\nCount of vowel in string is: %d", count); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include "access_closed.h" static void initialize_array(FILE* ptr_arr[], int length) { int i; FILE** ptr = ptr_arr; for(i = 0; i < length; i++, ptr++) { *ptr = fopen("file.txt","r"); } } static void close_backwards(FILE** ptr, int to_close) { int i; for(i = 0; i < to_close; i++, ptr--) { if(*ptr) fclose(*ptr); } } static void close_forwards(FILE** ptr, int to_close) { int i; for(i = 0; i < to_close; i++, ptr++) { if(*ptr) fclose(*ptr); } } void access_closed_for_pointer(int x) { FILE* pointers[10]; FILE** ptr; int val = 0, i; if(x > 10 || x < 0) { return; } #ifdef CATCH_BAD_PARAM if(x > 5) { return; } #endif initialize_array(pointers, 10); close_backwards(pointers + 9, x); ptr = pointers; for(int i = 0; i < 5; i++, ptr++) { if(*ptr) { val += (int) fgetc(*ptr); } else { val--; } } close_forwards(pointers, 10 - x); printf("%i\n", val); } #ifndef NO_MAIN int main() { #ifdef NO_BUG access_closed_for_pointer(4); #else access_closed_for_pointer(6); #endif return 1; } #endif
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/socket.h> #include<linux/in.h> #include<pthread.h> #define MAXLINE 4096 #define SERV_PORT 3006 #define LISTENQ 8 void fileTransfer(int newfd) { char buf_recv[100], buf_send[100]; char fbuffer[1000], filebuffer[1000]; char nbytes, len; FILE *fp; printf("Requesting client to send a filename\n"); sprintf(buf_send,"Please enter the filename:"); send(newfd,buf_send,strlen(buf_send),0); printf("filename received from client: \n"); nbytes = recv(newfd,buf_recv,sizeof(buf_recv),0); printf("bytes recevied from client = %d\n",nbytes); buf_recv[nbytes] = '\0'; printf("%s\n",buf_recv); fflush(stdout); printf("\nNow checking file: %s exists or not..\n",buf_recv); if ((fp = fopen(buf_recv,"r")) == NULL) { sprintf(buf_send,"File could not be found!"); exit(0); } else { printf("File found.\n"); sprintf(buf_send,"File found."); send(newfd,buf_send,strlen(buf_send),0); } printf("Sending the file content to client.. \n"); while(!feof(fp)) { fgets(fbuffer,sizeof(fbuffer),fp); //fread(fbuffer,sizeof(fbuffer),1,fp); if (feof(fp)) break; strcpy(filebuffer,fbuffer); } fclose(fp); printf("filebuffer = %s\n",filebuffer); printf("fbuffer = %s\n",fbuffer); printf("strlen(filebuffer) = %d\n",strlen(filebuffer)); printf("strlen(fbuffer) = %d\n",strlen(fbuffer)); send(newfd,filebuffer,strlen(filebuffer),0); close(newfd); printf("[Server] connection closed. Waiting for new connection..\n"); } void *tFun(int *arg) { struct sockaddr_in cAddr; int sockfd = (int)arg; int nSockfd; socklen_t addrlen; addrlen = sizeof(cAddr); while(1){ nSockfd = accept(sockfd,(struct sockaddr *)&cAddr,(socklen_t *)&addrlen); printf("\nserver now connected with nSockfd = %d\n",nSockfd); fileTransfer(nSockfd); close(nSockfd); } } int main(int argc, char **argv) { int sockfd, i = 0, thRet = 0; struct sockaddr_in servaddr; pthread_t t[10]; pthread_attr_t attr; sockfd = socket(AF_INET,SOCK_STREAM,0); if (sockfd == -1) { perror("error in creating socket"); goto out; } //prepration of socket address servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(SERV_PORT); if (bind(sockfd,(struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) { perror("assigning a name to a socket failed"); goto out; } if (listen(sockfd,LISTENQ) < 0) { perror("listen socket failed"); goto out; } thRet = pthread_attr_init(&attr); if (thRet == -1) { perror("pthread_attr_init failed"); goto out; } thRet = pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); if (thRet == -1) { perror("pthread_attr_setdetachstate failed"); goto out; } printf("Server running for connections.....\n"); for(i = 0; i < 10; i++) { printf("\n threadID = t[%d]\n",i); pthread_create(&t[i],&attr,tFun,(void *)sockfd); pause(); } return 0; out: close(sockfd); return -1; }
C
//Various data structures required for the finite state machine #include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX_TABLE_ENTRIES 256 #define MAX_STATE_NAME_SIZE 32 #define MAX_FSM_NAME_SIZE 128 enum Final_state{ //bools for final state fsm_false, fsm_true }; struct tt_entry{ //transition table entry data structure char transition_key; struct state_t *next_state; }; struct tt{ //transition table struct tt_entry tt_e[MAX_TABLE_ENTRIES]; }; struct state_t{ //name for state char name[MAX_STATE_NAME_SIZE]; //transition table struct tt state_trans_table; //bool variable for checking whether a state is final or not enum Final_state is_final; }; struct fsm{ //name of the finite state machine char fsm_name[MAX_FSM_NAME_SIZE]; //pointer to the initial state struct state_t *initial_state; }; //Now the api's for the fsm struct fsm *create_fsm(char name[]) { //this api will be used to instantiate a finite state machine struct fsm *new_fsm; new_fsm = calloc(1,sizeof(struct fsm)); strncpy(new_fsm->fsm_name,name,strlen(name)); return new_fsm; }; struct state_t *create_state(char name[],enum Final_state state) { //this api will be used to instantiate a generic state struct state_t *new_state; new_state = calloc(1,sizeof(struct state_t)); strncpy(new_state->name,name,strlen(name)); new_state->is_final = state; return new_state; }; struct tt_entry *get_next(struct tt *table) { /*for inserting an entry in the transition table we need to find the empty transition table entry this funtion will do the thing*/ struct tt_entry *ptr; int i =0; while(1) { ptr = &table->tt_e[i]; if(ptr->next_state==0) break; i++; } return ptr; }; void create_tt_entry(struct tt *table,char transition_key,struct state *next_state) { //api for populating transition table entry struct tt_entry *tt_ptr; tt_ptr = get_next(table); tt_ptr->next_state = next_state; tt_ptr->transition_key = transition_key; } void set_initial_state(struct fsm *fsm_,struct state *initial_state) { //api for setting initial state fsm_->initial_state = initial_state; } struct state_ *match(struct state_t *current_state,char key) { //this funtion will be used to match input charater with transition keys of the state struct tt *table; table = &current_state->state_trans_table; struct tt_entry *tt_e; struct state_ *next_state; int entry = 0; while(1) { tt_e = &table->tt_e[entry]; if(tt_e->transition_key == key){ next_state = tt_e->next_state; break; } entry++; } return next_state; }; int fsm_execute(struct fsm *fsm_,char *input,int length) { //this funtion will basically execute the algorithm of finite state machine printf("Input String: %s\n",input ); struct state_t *current_state,*next_state; current_state = fsm_->initial_state; next_state = 0; int cursor = 0; while(cursor<length) { printf("%s -> ",current_state->name); next_state = match(current_state,input[cursor]); current_state = next_state; printf("%s | on key: %c\n",current_state->name,input[cursor]); next_state = 0; cursor++; } return current_state->is_final; }
C
#include <sys/types.h> #include <signal.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <errno.h> void isExists(int pid){ int rc = kill(pid, 0); if (rc != 0) { switch (errno) { case EINVAL: // 22 printf("An invalid signal was specified.\n"); break; case EPERM: // 1 printf("The process does not have permission to send the signal to any of the target processes.\n"); break; case ESRCH: // 3 printf("The pid or process group does not exist.\n"); break; } } else { printf("Exists!\n"); } } int main(int argc, char* argv[]) { if(argc != 2){ printf("Please put up the PIDnumber argument\n"); printf("Client turned off!\n"); return 1; } int pid = atoi(argv[1]); isExists(pid); return 0; }
C
#include "monty.h" /** * pchar - Instruction that prints a char. * @stack: stacker of a doubly linked list * @line_number: Number line */ void pchar(stack_t **stack, unsigned int line_number) { if (!stack || !*stack) { print_error(line_number, "can't pchar, stack empty"); return; } if ((*stack)->n < 0 || (*stack)->n > 127) { print_error(line_number, "can't pchar, value out of range"); return; } printf("%c\n", (*stack)->n); }
C
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <malloc.h> #include <mem.h> #include "longCalculation.h" void testPlus(){ int result=1; char osn[] = "10000"; char *end; int base =strtol(osn,&end,10); int flag = 1; char *chA; char nameInp[] = "C:\\Users\\LEGION\\CLionProjects\\untitled5\\data.txt"; char nameOut[] = "C:\\Users\\LEGION\\CLionProjects\\untitled5\\out.txt"; work(nameInp,nameOut,base,flag); FILE *openFile = fopen(nameOut, "r"); chA = (char*)calloc((size_t) base, sizeof(char)); while(fscanf(openFile,"%s",chA) != EOF) { } fclose(openFile); if(strcmp(chA,"77777")== 0){ result = 1; }else{ result =0; } assert(result); } void testMinus(){ int result=1; int base = 10; int flag = 2; char *chA; char nameInp[] = "C:\\Users\\LEGION\\CLionProjects\\untitled5\\data.txt"; char nameOut[] = "C:\\Users\\LEGION\\CLionProjects\\untitled5\\out.txt"; work(nameInp,nameOut,base,flag); FILE *openFile = fopen(nameOut, "r"); chA = (char*)calloc((size_t) base, sizeof(char)); while(fscanf(openFile,"%s",chA) != EOF) { } fclose(openFile); if(strcmp(chA,"33333")== 0){ result = 1; }else{ result =0; } assert(result); } void testMultpl(){ int result=1; int base = 10; int flag = 3; char *chA; char nameInp[] = "C:\\Users\\LEGION\\CLionProjects\\untitled5\\data.txt"; char nameOut[] = "C:\\Users\\LEGION\\CLionProjects\\untitled5\\out.txt"; work(nameInp,nameOut,base,flag); FILE *openFile = fopen(nameOut, "r"); chA = (char*)calloc((size_t) base, sizeof(char)); while(fscanf(openFile,"%s",chA) != EOF) { } fclose(openFile); if(strcmp(chA,"1234543210")== 0){ result = 1; }else{ result =0; } assert(result); } void testDiv(){ int result=1; int base = 10; int flag = 4; char *chA; char nameInp[] = "C:\\Users\\LEGION\\CLionProjects\\untitled5\\data.txt"; char nameOut[] = "C:\\Users\\LEGION\\CLionProjects\\untitled5\\out.txt"; work(nameInp,nameOut,base,flag); FILE *openFile = fopen(nameOut, "r"); chA = (char*)calloc((size_t) base, sizeof(char)); while(fscanf(openFile,"%s",chA) != EOF) { } fclose(openFile); if(strcmp(chA,"2")== 0){ result = 1; }else{ result =0; } assert(result); } void testMod(){ int result=1; int base = 10; int flag = 5; char *chA; char nameInp[] = "C:\\Users\\LEGION\\CLionProjects\\untitled5\\data.txt"; char nameOut[] = "C:\\Users\\LEGION\\CLionProjects\\untitled5\\out.txt"; work(nameInp,nameOut,base,flag); FILE *openFile = fopen(nameOut, "r"); chA = (char*)calloc((size_t) base, sizeof(char)); while(fscanf(openFile,"%s",chA) != EOF) { } fclose(openFile); if(strcmp(chA,"11111")== 0){ result = 1; }else{ result =0; } assert(result); } int main() { testPlus(); printf("Test plus - done\n"); testMinus(); printf("Test minus - done\n"); testMultpl(); printf("Test multpl - done\n"); testDiv(); testMod(); printf("DONE\n"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* parser_utils_nodes.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: larosale <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/10/20 01:00:36 by larosale #+# #+# */ /* Updated: 2020/11/17 17:14:33 by larosale ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" /* ** Creates a new node of the tree of type "type". ** Returns a pointer to the created node, or NULL on error. */ t_node *create_node(t_node_types type) { t_node *node; if (!(node = ft_calloc(1, sizeof(t_node)))) { errman(ERR_SYSCMD, NULL, NULL); return (NULL); } node->type = type; node->fd_out = 1; return (node); } /* ** Adds the child node ("child") to the parent node ("parent") as a last ** sibling. ** Returns 0 on success, or 1 on error. */ int add_child_node(t_node *parent, t_node *child) { t_node *sibling; if (!parent->first_child) parent->first_child = child; else { sibling = parent->first_child; while (sibling->next_sibling) sibling = sibling->next_sibling; sibling->next_sibling = child; child->prev_sibling = sibling; } parent->children += 1; return (0); } /* ** Sets the node "data" string to the given "data". ** Allocates memory for the new string. ** Returns 0 on success, or 1 on error. */ int set_node_data(t_node *node, char *data) { if (!data) node->data = NULL; else if (!(node->data = ft_strdup(data))) { errman(ERR_SYSCMD, NULL, NULL); return (1); } return (0); } /* ** Deletes the parse tree from a given "root" recursively. */ void delete_tree(t_node *root) { t_node *child; t_node *next_child; if (root) { child = root->first_child; while (child) { next_child = child->next_sibling; delete_tree(child); child = next_child; } if (root->data) free(root->data); free(root); } return ; }
C
/* * MIT License * * Copyright (c) 2020 Nicholas Fraser * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "pottery_qsort_simple.h" #include <string.h> typedef struct qsort_context_t { size_t element_size; int (*compare)(const void* left, const void* right); } qsort_context_t; static inline void* qsort_array_access_select(qsort_context_t context, void* base, size_t index) { return (char*)base + (index * context.element_size); } static inline size_t qsort_array_access_index(qsort_context_t context, void* base, void* ref) { return (size_t)((char*)ref - (char*)base) / context.element_size; } static inline int qsort_compare(qsort_context_t context, void* left, void* right) { return context.compare(left, right); } static void qsort_swap(qsort_context_t context, void* vleft, void* vright) { char* left = (char*)vleft; char* right = (char*)vright; size_t remaining = context.element_size; char buffer[128]; while (remaining > sizeof(buffer)) { memcpy(buffer, left, sizeof(buffer)); memcpy(left, right, sizeof(buffer)); memcpy(right, buffer, sizeof(buffer)); left += sizeof(buffer); right += sizeof(buffer); remaining -= sizeof(buffer); } memcpy(buffer, left, remaining); memcpy(left, right, remaining); memcpy(right, buffer, remaining); } #define POTTERY_INTRO_SORT_PREFIX qsort_run #define POTTERY_INTRO_SORT_REF_TYPE void* #define POTTERY_INTRO_SORT_CONTEXT_TYPE qsort_context_t #define POTTERY_INTRO_SORT_ARRAY_ACCESS_SELECT qsort_array_access_select #define POTTERY_INTRO_SORT_ARRAY_ACCESS_INDEX qsort_array_access_index #define POTTERY_INTRO_SORT_COMPARE_THREE_WAY qsort_compare #define POTTERY_INTRO_SORT_LIFECYCLE_SWAP qsort_swap #include "pottery/intro_sort/pottery_intro_sort_static.t.h" void pottery_qsort_simple(void* first, size_t count, size_t element_size, int (*compare)(const void* left, const void* right)) { qsort_context_t context = {element_size, compare}; qsort_run(context, first, count); }
C
/* setdev.c - setdev */ #include <conf.h> #include <kernel.h> #include <proc.h> extern long ctr1000; extern int currpid; extern int allpids[NPROC]; /*------------------------------------------------------------------------ * setdev - set the two device entries in the process table entry *------------------------------------------------------------------------ */ SYSCALL setdev(int pid, int dev1, int dev2) { allpids[currpid] = 1; int start_time = ctr1000; short *nxtdev; if (isbadpid(pid)) return(SYSERR); nxtdev = (short *) proctab[pid].pdevs; *nxtdev++ = dev1; *nxtdev = dev2; proctab[currpid].syscount[SETDEV]++; proctab[currpid].systime[SETDEV] += ctr1000 - start_time; return(OK); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <windows.h> #include "menu.h" #include "arv.h" #include "prof.h" void depto_cadastro(Inst* arv){ char depNome[51], depSigla[11]; int verificacaoDep=0; system("cls"); printf("===================================="); printf("\n|TELA DE CADASTRO DE UM DEPARTAMENTO|\n"); printf("====================================\n"); printf("\nInforme o nome do Departamento: "); strcpy(depNome,calculaTamString()); printf("\nInforme a sigla do Departamento: "); strcpy(depSigla,calculaTamString()); converte_maiuscula(depSigla); if(!arv_vazia(arv)){ verificacaoDep=verifica_duplicacaoDep(arv,depNome,depSigla); while(verificacaoDep!=0){ if(verificacaoDep==1){ system("cls"); printf("J existe Departamento com esse Nome e Sigla cadastrados. Redefina-os para prosseguir."); printf("\nInforme o nome do Departamento: "); strcpy(depNome,calculaTamString()); printf("\nInforme a sigla do Departamento: "); strcpy(depSigla,calculaTamString()); converte_maiuscula(depSigla); verificacaoDep=verifica_duplicacaoDep(arv,depNome,depSigla); }else if(verificacaoDep==2){ system("cls"); printf("J existe Departamento com esse Nome cadastrado. Redefina a Nome para prosseguir."); printf("\nInforme o nome do Departamento: "); strcpy(depNome,calculaTamString()); verificacaoDep=verifica_duplicacaoDep(arv,depNome,depSigla); }else if(verificacaoDep==3){ system("cls"); printf("J existe Departamento com essa Sigla cadastrado. Redefina a Sigla para prosseguir."); LimpaBuffer(); printf("\nInforme a sigla do Departamento: "); strcpy(depSigla,calculaTamString()); converte_maiuscula(depSigla); verificacaoDep=verifica_duplicacaoDep(arv,depNome,depSigla); } } } NoDep* dep=arv_crianoDep(depNome,depSigla); system("cls"); arv_insereDep(arv,dep); } void prof_cadastro(Inst* arv){ char profNome[121],profArea[51],profTitulo[15],profDep[51]; int profMat,verificacaoProf,titulacao; system("cls"); printf("===================================="); printf("\n|TELA DE CADASTRO DE UM PROFESSOR|\n"); printf("====================================\n"); if(!arv_vazia(arv)){ printf("Escolha um dos Departamentos listados abaixo:\n"); arv_imprimeDep(arv); scanf("%50[^\n]s",profDep); NoDep* nodep=arv_busca(arv,profDep); while(nodep==NULL){ system("cls"); printf("Departamento no encontrado.\nEscolha um dos Departamentos listados abaixo, novamente:\n"); arv_imprimeDep(arv); LimpaBuffer(); scanf("%50[^\n]s",profDep); nodep=arv_busca(arv,profDep); } LimpaBuffer(); printf("\nInforme o nome do(a) professor(a):"); strcpy(profNome,calculaTamString()); converte_maiuscula(profNome); profMat=VerificaValor(); printf("\nInforme a rea de atuao do(a) professor(a): "); LimpaBuffer(); strcpy(profArea,calculaTamString()); printf("\nInforme a titulao do(a) professor(a): "); scanf("%14[^\n]s",profTitulo); titulacao=prof_verificaTitulacao(profTitulo); while(titulacao!=0){ printf("\nNome de Titulao invlido.\nCadastre um Professor cuja titulao seja\nI-Doutorado/doutorado\nII-Mestrado/mestrado\n"); printf("\nInforme novamente a titulao do professor: "); LimpaBuffer(); scanf("%14[^\n]s",profTitulo); titulacao=prof_verificaTitulacao(profTitulo); } verificacaoProf=verifica_duplicacaoProf(arv,profNome,profMat); while(verificacaoProf!=0){ if(verificacaoProf==1){ system("cls"); printf("J existe professor com esse Nome e Matrcula cadastrados. Redefina-os para prosseguir."); printf("\nInforme o nome do professor: "); LimpaBuffer(); scanf("%120[^\n]s",profNome); converte_maiuscula(profNome); profMat=VerificaValor(); verificacaoProf=verifica_duplicacaoProf(arv,profNome,profMat); }else if(verificacaoProf==2){ system("cls"); printf("J existe professor com essa Matrcula cadastrado. Redefina a Matricula para prosseguir"); profMat=VerificaValor(); verificacaoProf=verifica_duplicacaoProf(arv,profNome,profMat); }else if(verificacaoProf==3){ system("cls"); printf("J existe professor com esse Nome cadastrado. Redefina o Nome para prosseguir."); printf("\nInforme o nome do professor: "); LimpaBuffer(); scanf("%120[^\n]s",profNome); converte_maiuscula(profNome); verificacaoProf=verifica_duplicacaoProf(arv,profNome,profMat); } } arv_insereProf(nodep,profMat,profNome,profArea,profTitulo); system("Pause"); system("cls"); }else{ printf("Ainda no h departamentos cadastrados.\nCadastre-os primeiro, antes de tentar inserir um Professor.\n\n"); } } void prof_mestrado_listagem(Inst* arv){ system("cls"); printf("=========================\n"); printf("|PROFESSORES COM MESTRADO|"); printf("\n=========================\n"); arv_imprimeProfMestrado(arv); system("pause"); system("cls"); } void prof_doutorado_listagem(Inst* arv){ system("cls"); printf("==========================\n"); printf("|PROFESSORES COM DOUTORADO|"); printf("\n==========================\n"); arv_imprimeProfDoutorado(arv); system("pause"); system("cls"); } void libera_estruturas(Inst* arv){ arv_libera(arv); } void salvar_dados_em_arquivo(Inst* arv){ arv_armazenaNoArquivo(arv); }
C
// Pick random values #include <time.h> #include <stdio.h> #include <fcntl.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <getopt.h> #include <limits.h> #include <sys/stat.h> #include <sys/types.h> #define PACKAGE "raval" #define VERSION "0.0.1" /* status epilepticus, print help and exit with `exval' */ void print_help(int exval); /* picks a radom value withing range low-high*/ int get_rand_val(int low, int high); /* ! definitely not cryptographic secure ! */ /* value returned seeds the rand() function */ unsigned time_seed(void); int main(int argc, char *argv[]) { int opt = 0; /* holds option */ int max = 10; /* upper limit */ int min = 0; /* minimum limit */ int many = 1; /* the number of numbers to pick ... */ char *ptr = NULL; /* separator for number range */ while((opt = getopt(argc, argv, "hvn:r:")) != -1) { switch(opt) { case 'h': print_help(0); break; case 'v': exit(0); case 'n': many = atoi(optarg); break; case 'r': if((ptr = strchr(optarg, ':')) == NULL) { fprintf(stderr, "%s: Error - range `LOW:HIGH'\n\n", PACKAGE); print_help(1); } else { ptr++, max = atoi(ptr); ptr--, ptr = '\0'; min = atoi(optarg); if(min >= max || min < 0 || max < 0) { fprintf(stderr, "%s: Error - range `LOW:HIGH'\n\n", PACKAGE); print_help(1); } } break; case '?': fprintf(stderr, "%s: Error - No such option: `%c'\n\n", PACKAGE, optopt); print_help(1); case ':': fprintf(stderr, "%s: Error - option `%c' needs an argument\n\n", PACKAGE, optopt); print_help(1); } } /* first seed the random function */ srand((time_seed())); /* print the random values */ for(; many > 0; many--) printf("%4d\n", get_rand_val(min, max)); return 0; } /* picks a radom value withing range low-high*/ int get_rand_val(int low, int high) { int k = 0; double d = 0; d = (double)rand() / ((double)RAND_MAX + 1); k = (int)(d * (high - low + 1)); return(low + k); } /* ! definitely not cryptographic secure ! */ /* value returned seeds the rand() function */ unsigned time_seed(void) { int retval = 0; int fd; /* just in case open() fails.. */ if(open("/dev/urandom", O_RDONLY) == -1) { retval = (((int)time(NULL)) & ((1 << 30) - 1)) + getpid(); } else { read(fd, &retval, 4); /* positive values only */ retval = abs(retval) + getpid(); close(fd); } return retval; } void print_help(int exval) { printf("%s,%s print a random number\n", PACKAGE, VERSION); printf("Usage: %s OPTION...\n\n", PACKAGE); printf(" -h print this help and exit\n"); printf(" -v print version and exit\n\n"); printf(" -n INT return `INT' numbers\n"); printf(" -r INT:INT keep the number within range `LOW:HIGH',\n"); printf(" default=(1:10)\n\n"); exit(exval); }
C
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <limits.h> #include <stdint.h> #include <time.h> #include <getopt.h> #include "ext2_fs.h" int fd; struct ext2_super_block superblock; struct ext2_group_desc desc_g; struct ext2_dir_entry dir_entry; struct ext2_inode inode; unsigned int block_size; const int indirection_level_1 = 1; const int indirection_level_2 = 2; const int indirection_level_3 = 3; void die(char *msg) { perror(msg); exit(1); } //DONE //Parham void print_superblock() { if (pread(fd, &superblock, sizeof(superblock), 1024) < 0) die("Failed to read\n"); fprintf(stdout, "SUPERBLOCK,"); fprintf(stdout, "%d,", superblock.s_blocks_count); fprintf(stdout, "%d,", superblock.s_inodes_count); fprintf(stdout, "%d,", block_size); fprintf(stdout, "%d,", superblock.s_inode_size); fprintf(stdout, "%d,", superblock.s_blocks_per_group); fprintf(stdout, "%d,", superblock.s_inodes_per_group); fprintf(stdout, "%d\n", superblock.s_first_ino); } //DONE //John void dirPrint(unsigned int inode_og, unsigned int nBytes){ fprintf(stdout, "DIRENT,"); fprintf(stdout, "%d,", inode_og); fprintf(stdout, "%d,", nBytes); fprintf(stdout, "%d,", dir_entry.inode); fprintf(stdout, "%d,", dir_entry.rec_len); fprintf(stdout, "%d,", dir_entry.name_len); fprintf(stdout, "'%s'\n", dir_entry.name); } //DONE //John void indirect1(struct ext2_inode inode,char type, unsigned int nInode) { unsigned int i; unsigned int *block_ptrs = malloc(block_size); unsigned int num_ptrs = block_size / sizeof(unsigned int); unsigned long offset, indir_offset = 1024 + (inode.i_block[12] - 1) * block_size; if (pread(fd, block_ptrs, block_size, indir_offset) < 0) die("Failed to read\n"); for (i = 0; i < num_ptrs; i++) { if (block_ptrs[i] != 0) { if (type == 'd') { offset = 1024 + (block_ptrs[i] - 1) * block_size; while(block_ptrs[i] < block_size) { if (pread(fd, &dir_entry, sizeof(dir_entry), offset + block_ptrs[i]) < 0) die("Failed to read\n"); if (dir_entry.inode != 0) { dirPrint(nInode, block_ptrs[i]); } block_ptrs[i] += dir_entry.rec_len; } } fprintf(stdout, "INDIRECT,"); fprintf(stdout, "%d,", nInode); fprintf(stdout, "%d,", indirection_level_1); fprintf(stdout, "%d,", i+12); fprintf(stdout, "%d,", inode.i_block[12]); fprintf(stdout, "%d\n", block_ptrs[i]); } } } //DONE //Parham void indirect2(struct ext2_inode inode,unsigned int inode_num) { unsigned int *block_ptrs, indir_offset, indir2_offset, num_ptrs, *indir_block_ptrs, k = 0; indir_block_ptrs = malloc(block_size); num_ptrs = block_size / sizeof(uint32_t); indir2_offset =1024 + (inode.i_block[13] - 1) * block_size; if (pread(fd, indir_block_ptrs, block_size, indir2_offset) < 0) die("Failed to read\n"); int sum = 256 + 12; unsigned long offset; unsigned int j; for (j = 0; j < num_ptrs; j++) { if (indir_block_ptrs[j] != 0) { fprintf(stdout, "INDIRECT,"); fprintf(stdout, "%d,", inode_num); fprintf(stdout, "%d,", indirection_level_2); fprintf(stdout, "%d,", sum + j); fprintf(stdout, "%d,", inode.i_block[13]); fprintf(stdout, "%d\n", indir_block_ptrs[j]); block_ptrs = malloc(block_size); indir_offset = 1024 + (indir_block_ptrs[j] - 1) * block_size; if (pread(fd, block_ptrs, block_size, indir_offset) < 0) die("Failed to read\n"); for (; k < num_ptrs; k++) { if ((block_ptrs[k] ^ 0) == 0) { offset = 1024 + (block_ptrs[k] - 1) * block_size; while(block_ptrs[k] < block_size) { if (pread(fd, &dir_entry, sizeof(dir_entry), offset + block_ptrs[k]) < 0) die("Failed to read\n"); if ((dir_entry.inode ^ 0) == 0) { dirPrint(inode_num, block_ptrs[k]); } block_ptrs[k] += dir_entry.rec_len; } fprintf(stdout, "INDIRECT,"); fprintf(stdout, "%d,", inode_num); fprintf(stdout, "%d,", indirection_level_1); fprintf(stdout, "%d,", sum + k); fprintf(stdout, "%d,", indir_block_ptrs[j]); fprintf(stdout, "%d,", block_ptrs[k]); } } } } } //DONE //John void indirect3(struct ext2_inode inode,unsigned int inode_num) { unsigned int *indir2_block_ptrs, num_ptrs, j=0, *indir_block_ptrs, k=0, p=0; indir2_block_ptrs = malloc(block_size); num_ptrs = block_size / sizeof(uint32_t); unsigned long indir2_offset, offset, indir3_offset = 1024 + (inode.i_block[14] - 1) * block_size; if (pread(fd, indir2_block_ptrs, block_size, indir3_offset) < 0) die("Failed to read\n"); int sum = 65536 + 256 + 12; while(j < num_ptrs){ if (indir2_block_ptrs[j] != 0) { fprintf(stdout, "INDIRECT,"); fprintf(stdout, "%d,", inode_num); fprintf(stdout, "%d,", indirection_level_3); fprintf(stdout, "%d,", sum + j); fprintf(stdout, "%d,", inode.i_block[14]); fprintf(stdout, "%d\n", indir2_block_ptrs[j]); indir_block_ptrs = malloc(block_size); indir2_offset = 1024 + (indir2_block_ptrs[j] - 1) * block_size; if (pread(fd, indir_block_ptrs, block_size, indir2_offset) < 0) die("Failed to read\n"); while(k < num_ptrs) { if (indir_block_ptrs[k] != 0) { fprintf(stdout, "INDIRECT,"); fprintf(stdout, "%d,", inode_num); fprintf(stdout, "%d,", indirection_level_2); fprintf(stdout, "%d,", sum + k); fprintf(stdout, "%d,", indir2_block_ptrs[j]); fprintf(stdout, "%d\n", indir_block_ptrs[k]); uint32_t *block_ptrs = malloc(block_size); unsigned long indir_offset = 1024 + (indir_block_ptrs[k] - 1) * block_size; if (pread(fd, block_ptrs, block_size, indir_offset) < 0) die("Failed to read\n"); while (p < num_ptrs) { if (block_ptrs[p] != 0) { offset = 1024 + (block_ptrs[p] - 1) * block_size; while(block_ptrs[p] < block_size) { if (pread(fd, &dir_entry, sizeof(dir_entry), offset + block_ptrs[p]) < 0) die("Failed to read\n"); if (dir_entry.inode != 0) { dirPrint(inode_num, block_ptrs[p]); } block_ptrs[p] += dir_entry.rec_len; } } fprintf(stdout, "INDIRECT,"); fprintf(stdout, "%d,", inode_num); fprintf(stdout, "%d,", 1); fprintf(stdout, "%d,", sum + p); fprintf(stdout, "%d,", indir_block_ptrs[k]); fprintf(stdout, "%d\n", block_ptrs[p]); p++; } } k++; } } j++; } } //DONE //Parham void reading_inode(unsigned int inode_table_id, unsigned int index, unsigned int inode_num) { unsigned long offset = 1024 + (inode_table_id - 1) * block_size + index * sizeof(inode); if (pread(fd, &inode, sizeof(inode), offset) < 0) die("Failed to read\n"); if (inode.i_mode == 0 || inode.i_links_count == 0) { return; } char type; unsigned int file_val = (inode.i_mode >> 12) << 12; switch (file_val) { case 0xa000: type = 's'; case 0x8000: type = 'f'; case 0x4000: type = 'd'; } unsigned int num_blocks = indirection_level_2 * (inode.i_blocks / (indirection_level_2 << superblock.s_log_block_size)); fprintf(stdout, "INODE,"); fprintf(stdout, "%d,", inode_num); fprintf(stdout, "%c,", type); fprintf(stdout, "%o,", inode.i_mode & 0xFFF); fprintf(stdout, "%d,", inode.i_uid); fprintf(stdout, "%d,", inode.i_gid); fprintf(stdout, "%d,", inode.i_links_count); char ctime[20], mtime[20], atime[20]; time_t rawtime = inode.i_ctime; struct tm* time_info = gmtime(&rawtime); strftime(ctime, 32, "%m/%d/%y %H:%M:%S", time_info); rawtime = inode.i_mtime; time_info = gmtime(&rawtime); strftime(mtime, 32, "%m/%d/%y %H:%M:%S", time_info); rawtime = inode.i_atime; time_info = gmtime(&rawtime); strftime(atime, 32, "%m/%d/%y %H:%M:%S", time_info); fprintf(stdout, "%s,%s,%s,", ctime, mtime, atime); fprintf(stdout, "%d,", inode.i_size); fprintf(stdout, "%d", num_blocks); unsigned int i; for (i = 0; i < 15; i++) { fprintf(stdout, ",%d", inode.i_block[i]); } fprintf(stdout, "\n"); for (i = 0; i < 12; i++) { if (inode.i_block[i] != 0 && type == 'd') { unsigned long offset2 = 1024 + (inode.i_block[i] - 1) * block_size; unsigned int nBytes = 0; while(nBytes < block_size) { if (pread(fd, &dir_entry, sizeof(dir_entry), offset2 + nBytes) < 0) die("Failed to read\n"); if (dir_entry.inode != 0) { dirPrint(inode_num,nBytes); } nBytes += dir_entry.rec_len; } } } indirect1(inode, type, inode_num); indirect2(inode, inode_num); indirect3(inode, inode_num); } //DONE //Parham void reading_bitmap(int group, int block, int inode_table_id) { int nBytes = superblock.s_inodes_per_group / 8; char* bit_mapping = (char*) malloc(nBytes); unsigned long offset = 1024 + (block - 1) * block_size; unsigned int changing = group * superblock.s_inodes_per_group + 1; //unsigned int original = changing; if (pread(fd, bit_mapping, nBytes, offset) < 0) die("Failed to read\n"); int i=0, j=0; while(i < nBytes) { char x = bit_mapping[i]; for (j=0; j < 8; j++) { if (x) { reading_inode(inode_table_id, changing - (group*superblock.s_inodes_per_group+1), changing); } else { fprintf(stdout, "IFREE,%d\n", changing); } x = x >> 1; changing++; } i++; } } //DONE //John void read_group(int group, int total_groups) { int checked; unsigned int i=0, j; unsigned int inode_bitmap, inode_table, descblock=block_size==1024?2:1; unsigned long offset = block_size * descblock + 32 * group; if (pread(fd, &desc_g, sizeof(desc_g), offset) < 0) die("Failed to read\n"); unsigned int num_blocks_in_group = superblock.s_blocks_per_group; if (group == total_groups - 1) { num_blocks_in_group = superblock.s_blocks_count - (superblock.s_blocks_per_group * (total_groups - 1)); } unsigned int num_inodes_in_group = superblock.s_inodes_per_group; if (group == total_groups - 1) { num_inodes_in_group = superblock.s_inodes_count - (superblock.s_inodes_per_group * (total_groups - 1)); } fprintf(stdout, "GROUP,"); fprintf(stdout, "%d,",group); fprintf(stdout, "%d,", num_blocks_in_group); fprintf(stdout, "%d,", num_inodes_in_group); fprintf(stdout, "%d,", desc_g.bg_free_blocks_count); fprintf(stdout, "%d,", desc_g.bg_free_inodes_count); fprintf(stdout, "%d,", desc_g.bg_block_bitmap); fprintf(stdout, "%d,", desc_g.bg_inode_bitmap); fprintf(stdout, "%d\n", desc_g.bg_inode_table); unsigned int block_bitmap = desc_g.bg_block_bitmap; //free_blocks(group, block_bitmap); char pj, *bytes = (char*) malloc(block_size); if (bytes == NULL) die("Failed to allocate memory\n"); unsigned long offset2 = 1024 + (block_bitmap - 1) * block_size; unsigned int counter = superblock.s_first_data_block + group * superblock.s_blocks_per_group; if (pread(fd, bytes, block_size, offset2) < 0) die("Failed to read\n"); while (i < block_size) { pj = bytes[i]; for (j = 8; j > 0; j--) { checked = 1 & pj; if (!checked) { fprintf(stdout, "BFREE,%d\n", counter); } pj >>= 1; counter++; } i++; } inode_bitmap = desc_g.bg_inode_bitmap; inode_table = desc_g.bg_inode_table; reading_bitmap(group, inode_bitmap, inode_table); } //DONE //Parham int main (int argc, char* argv[]) { if (argc != 2) die("Incorrect number of arguments\n"); int i; if ((fd = open(argv[1], O_RDONLY)) == -1) { die("Failed to open\n"); } block_size = EXT2_MIN_BLOCK_SIZE << superblock.s_log_block_size; print_superblock(); double num_groups = superblock.s_blocks_count / superblock.s_blocks_per_group; double pergro= (double) superblock.s_blocks_count / superblock.s_blocks_per_group; num_groups<pergro?num_groups++:num_groups; i=0; while (i<num_groups) { read_group(i, num_groups); i++; } exit(0); }
C
/* Problem statement : Accept string from user and copy the conetents into another string using pointer. Implement strcpy. */ #include<stdio.h> void CopyStr(char *Src,char *Dest) { while(*Src != '\0') { *Dest = *Src; *Src++; *Dest++; } *Dest = '\0'; } int main() { char arr[30]; char brr[30]; printf("Enter The String \n"); scanf("%[^'\n']s",arr); CopyStr(arr,brr); printf("string After copy : %s \n",brr); return 0; } /* output Enter The String nikita string After copy : nikita */
C
#include <cs50.h> #include <ctype.h> #include <stdio.h> #include <string.h> bool keyValidation(string key, int keyLength); string encryptText(string plainText, string key); int main(int argc, string argv[]) { // Check if the user has passed the key arg. or not. if (argc != 2) { printf("Usage : ./substitution key\n"); return 1; } string key = argv[1]; int keyLength = strlen(key); // Validate the key as required. bool valid = keyValidation(key, keyLength); if (!valid) { return 1; } // Prompt user to enter the plain text string plainText = get_string("plaintext: "); // Encrypt the plaintext encryptText(plainText, key); return 0; } bool keyValidation(string key, int keyLength) { // Check if the key contains numbers or special characters. for (int i = 0; i < keyLength; i++) { if (!isalpha(key[i])) { printf("Usage : ./substitution key\n"); return false; } } // Check if there is duplicated charachter. for (int i = 0; i < keyLength; i++) { for (int j = i + 1; j < keyLength; j++) { if (tolower(key[i]) == tolower(key[j])) { printf("Key characters must be unique."); return false; } } } // Check if key length is less than 26. if (keyLength != 26) { printf("Key must contain 26 characters.\n"); return false; } return true; } string encryptText(string plainText, string key) { // Define array to collect keys characters. int arrayKeys[91]; int index = 0; // Append the keys characters to the array. for (int i = 65; i <= 90; i++) { arrayKeys[i] = (int)toupper(key[index]); index++; } int textLength = strlen(plainText); char charsArray[textLength]; char temp; // Replace each character in the plaintext with a character from keys array. for (int i = 0; i < textLength; i++) { if (isalpha(plainText[i])) { if (islower(plainText[i])) { temp = (char)tolower(arrayKeys[((int)plainText[i] - 32)]); charsArray[i] = temp; } else { temp = (char)arrayKeys[(int)plainText[i]]; charsArray[i] = temp; } } else { charsArray[i] = plainText[i]; } } // Assign the characters array into one string. string encryptedTex[1]; encryptedTex[0] = charsArray; printf("ciphertext: %s\n", encryptedTex[0]); // Return the cipher text. return encryptedTex[0]; }
C
#include "synchronization.h" #include <pthread.h> #include <time.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> static void critical_zone(){ int t = rand()%5 + 1; sleep(t); } static void * thread_work(void* data){ while(1){ int t = rand()%3 + 1; sleep(t); int choice = rand()%100; if(choice < 10){ printf(" A wild writer appears!\n"); enter_critical(WRITER); critical_zone(); leave_critical(WRITER); } else{ enter_critical(READER); critical_zone(); leave_critical(READER); } } } int main(void){ srand(time(0)); synchro_init(); int i = 0; pthread_t threads[15]; while(i < 15){ pthread_create(&threads[i++], NULL, thread_work, NULL); } i=0; while(i < 15){ pthread_join(threads[i++], NULL); } return 0; }
C
#ifndef _LOCK_H_ #define _LOCK_H_ //#define DBG_PRINT /* Control if the system should Print out */ /* debug statements */ #define NLOCK 50 /* Number of R/W Locks */ #define DELETED -6 /* Lock has been deleted */ #define INIT 0 /* Lock is initialized but unused */ #define FREE 1 /* Lock is created but is not locked */ #define READ 2 /* Lock is for reading purposes */ #define WRITE 3 /* Lock is for writing purposes */ int prio_inherit(int pid, int lock); /* Perform priority inheritance with proc pid attempting to gain lock */ int linit(void); /* Initialize all the system R/W Locks */ int lcreate(void); /* Create a lock, returns an ID that can be used to refer to the lock. or SYSERR when no more locks available */ int ldelete(int lockdescriptor); /* Deletes the associated lock */ int lock(int ldes1, int type, int priority); /* Obtains a lock for read/write */ int releaseall(int numlocks, long args); /* Simulataneous release of numlocks */ void print_lock(int lock); /* Print a locks info */ typedef struct { /* Queue node type */ int prio; /* priority of the entry */ int type; /* READ/WRITE of the entry */ int pid; /* PID of the entry */ struct q_node_t *next; /* Pointer to the next node */ struct q_node_t *prev; /* Pointer to the previous node */ } q_node_t; int q_enqueue(int prio, int type, int pid, int lock); /* Emplace data into a lock's queue */ int q_dequeue(int prio, int type, int pid, int lock); /* Remove data from a lock's queue */ void q_print(int lock); /* Print a locks queue */ typedef struct { /* Lock Type */ int status; /* Lock Status */ int pcount; /* Number of processes in queue */ int owner; /* PID of the process that owns the lock*/ int currprio; /* Priority of the process with lock */ Bool currpids[NPROC]; /* PID(s) of the process with the lock */ q_node_t *head; /* Head of the process queue */ q_node_t *tail; /* Tail of the process queue */ } lock_t; extern lock_t locks[]; /* Table of locks */ #define isbadlock(s) (s < 0 || s >= NLOCK) /* Macro to test if a lock id is bad */ #define pinhpprio(p) (p->pinh == 0 ? p->pprio : p->pinh) /* Macro to use pinh or pprio */ #endif
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int main(){ int i, j, k; int tf[1010], tr[1010], deadline[1010], aux_tf, aux_tr, aux_mud; char num[10]; char fcfs[50], srtn[50], rr[50]; char s[50], ss[50], sss[50], en[50]; int trace[] = {1, 2, 5, 10, 20, 50, 100, 200}; double cumpriu; double mudancas; FILE *f, *p; fcfs[0] = '\0'; srtn[0] = '\0'; rr[0] = '\0'; strcat(fcfs, "saida_fcfs_trace"); strcat(srtn, "saida_srtn_trace"); strcat(rr, "saida_rr_trace"); puts("FCFS:"); for(j = 0; j < 1; j++) { sprintf(en, "trace%d", trace[j]); printf("%s\n", en); p = fopen(en, "r"); k = 0; while(fscanf(p, "%s %d %d %d", ss, &aux_tf, &aux_tr, deadline + k) != EOF) k++; cumpriu = 0; for(i = 1; i <= 30; i++) { sprintf(s, "%s%d_%d", fcfs, trace[j], i); printf("%s\n", s); f = fopen(s, "r"); k = 0; puts("logo"); for(k = 0; k < trace[j]; k++) { fscanf(f, "%s %d %d", sss, &aux_tf, &aux_tr); if(aux_tf <= deadline[k]) cumpriu++; k++; puts("nem tao logo"); } fscanf(f, "%%d", &aux_mud); mudancas += aux_mud; fclose(f); } cumpriu /= 30; mudancas /= 30; printf("%.2f %.2f\n", cumpriu, mudancas); fclose(p); } puts("SRTN:"); for(j = 0; j < 1; j++) { sprintf(en, "trace%d", trace[j]); printf("%s\n", en); p = fopen(en, "r"); k = 0; while(fscanf(p, "%s %d %d %d", ss, &aux_tf, &aux_tr, deadline + k) != EOF) k++; cumpriu = 0; for(i = 1; i <= 30; i++) { sprintf(s, "%s%d_%d", srtn, trace[j], i); printf("%s\n", s); f = fopen(s, "r"); k = 0; puts("logo"); for(k = 0; k < trace[j]; k++) { fscanf(f, "%s %d %d", sss, &aux_tf, &aux_tr); if(aux_tf <= deadline[k]) cumpriu++; k++; puts("nem tao logo"); } fscanf(f, "%%d", &aux_mud); mudancas += aux_mud; fclose(f); } cumpriu /= 30; mudancas /= 30; printf("%.2f %.2f\n", cumpriu, mudancas); fclose(p); } puts("RR:"); for(j = 0; j < 1; j++) { sprintf(en, "trace%d", trace[j]); printf("%s\n", en); p = fopen(en, "r"); k = 0; while(fscanf(p, "%s %d %d %d", ss, &aux_tf, &aux_tr, deadline + k) != EOF) k++; cumpriu = 0; for(i = 1; i <= 30; i++) { sprintf(s, "%s%d_%d", rr, trace[j], i); printf("%s\n", s); f = fopen(s, "r"); k = 0; puts("logo"); for(k = 0; k < trace[j]; k++) { fscanf(f, "%s %d %d", sss, &aux_tf, &aux_tr); if(aux_tf <= deadline[k]) cumpriu++; k++; puts("nem tao logo"); } fscanf(f, "%%d", &aux_mud); mudancas += aux_mud; fclose(f); } cumpriu /= 30; mudancas /= 30; printf("%.2f %.2f\n", cumpriu, mudancas); fclose(p); } return 0; }
C
#include <stddef.h> #include <stdint.h> #include <stdlib.h> void gen(int n, unsigned char *s, size_t *len) { *len = n * 7 + 4; s[0] = 0xff; for (int i = 1; i < *len; ++i) { s[i] = s[i-1] - 1; } }
C
#include <stdio.h> #include <string.h> #include "test.h" #include "libfts.h" static void print_array(FILE* stream, void* s, size_t bytes); void* ft_memcpy(void* dst, const void* src, size_t n); int memcpy_test_input_validation_null_dest() { ft_memcpy(NULL, (void*)1, 0); return 0; } int memcpy_test_input_validation_null_src() { ft_memcpy((void*)1, NULL, 0); return 0; } int memcpy_test_input_validation_negative_n() { ft_memcpy((void*)1, (void*)1, -10); return 0; } int memcpy_test_compare_memcpy() { // Assign const char* str = "Hello, World!"; char expected[16]; bzero(expected, 16); char actual[16]; bzero(actual, 16); // Act memcpy((void*)expected, str, 14); ft_memcpy((void*)actual, str, 14); // Assert if (memcmp((void*)expected, (void*)actual, 16)) { fprintf(stderr, "\033[31mft_memcpy does not match the behaviour of memcpy with input [char[16], \"%s\", 14]\n", str); fprintf(stderr, "Expected: "); print_array(stderr, expected, 16); fprintf(stderr, "Actual: "); print_array(stderr, actual, 16); fprintf(stderr, "\033[0m"); return 1; } else { return 0; } } int memcpy_test_compare_memcpy_half_string() { // Assign const char* str = "Hello, World!"; char expected[16]; bzero(expected, 16); char actual[16]; bzero(actual, 16); // Act memcpy((void*)expected, str, 7); ft_memcpy((void*)actual, str, 7); // Assert if (memcmp((void*)expected, (void*)actual, 16)) { fprintf(stderr, "\033[31mft_memcpy does not match the behaviour of memcpy with input [char[16], \"%s\", 14]\n", str); fprintf(stderr, "Expected: "); print_array(stderr, expected, 16); fprintf(stderr, "Actual: "); print_array(stderr, actual, 16); fprintf(stderr, "\033[0m"); return 1; } else { return 0; } } int memcpy_test_compare_memcpy_zero_nbyte() { const char* str = "Hello, World!"; char expected[16]; bzero(expected, 16); char actual[16]; bzero(actual, 16); memcpy((void*)expected, str, 0); ft_memcpy((void*)actual, str, 0); if (memcmp((void*)expected, (void*)actual, 16)) { fprintf(stderr, "\033[31mft_memcpy does not match the behaviour of memcpy with input [char[16], \"%s\", 0]\n", str); fprintf(stderr, "Expected: "); print_array(stderr, expected, 16); fprintf(stderr, "Actual: "); print_array(stderr, actual, 16); fprintf(stderr, "\033[0m"); return 1; } else { return 0; } } static void print_array(FILE* stream, void* s, size_t bytes) { if (bytes > 0) { unsigned char* buff = (unsigned char*)s; fprintf(stream, "%hhu (%c)", *buff, *buff); ++buff; while (--bytes) { fprintf(stream, ", %hhu (%c)", *buff, *buff); ++buff; } fprintf(stream, "\n"); } }
C
//Program to find greater of 3 numbers //study of else if statement //refer : conditional branching.txt //see : else if.png #include<stdio.h> int main() { int n1,n2,n3; printf("\n Enter 3 numbers "); scanf("%d%d%d", &n1,&n2,&n3); if(n1 == n2 && n1 == n3) printf("\n All numbers are %d ", n1); else if(n1 > n2 && n1 > n3) printf("\n %d is greatest ", n1); else if(n2 > n3) printf("\n %d is greatest ", n2); else printf("\n %d is greatest ", n3); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: clhoffma <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/08/19 17:17:28 by clhoffma #+# #+# */ /* Updated: 2017/08/20 16:20:36 by clhoffma ### ########.fr */ /* */ /* ************************************************************************** */ #include "colle02.h" void ft_init_globtab(void) { int i; i = -1; while (++i < NB_COLLE) g_is_colle[i] = 1; } void ft_display_result(int line_len, int line_nbr) { int is_not_first; int i; int no_match; no_match = 1; is_not_first = 0; i = -1; while (++i < NB_COLLE) if (g_is_colle[i]) { no_match = 0; if (is_not_first) ft_putstr(" || "); is_not_first = 1; ft_putstr("[colle-0"); ft_putnbr(i); ft_putstr("] ["); ft_putnbr(line_len); ft_putstr("] ["); ft_putnbr(line_nbr); ft_putchar(']'); } if (no_match) ft_putstr(NO_MATCH_MESSAGE); } int main(void) { char enter[BUFFER_SIZE + 1]; int line_len; int line_nbr; int ret; ret = read(0, enter, BUFFER_SIZE); enter[ret] = '\0'; line_len = ft_get_first_line_size(enter); ft_init_globtab(); line_nbr = ft_get_nbr_line(enter); if (line_nbr == 0 || line_len == 0) ft_display_result(0, 0); else if (ft_not_same_len(enter, line_len)) { ft_putstr(NO_MATCH_MESSAGE); return (0); } ft_test_corners(enter, line_len, line_nbr); ft_test_line(enter, line_len, line_nbr); if (line_len > 0 && line_nbr > 0) ft_display_result(line_len, line_nbr); ft_putchar('\n'); return (0); }
C
/* - Questão 4.12 - */ #include <stdio.h> #include <stdlib.h> int main( void ) { int i, soma; soma = 0; system( "chcp 65001 > NUL" ); for ( i = 2; i <= 30; i += 2 ) soma += i; printf( "Soma = %d\n", soma ); system( "pause" ); return 0; } /* fim [main] */
C
#include <stdio.h> #include <ctype.h> #include <string.h> #define NKEYS (sizeof(keytab)/sizeof(keytab[0])) #define MAXWORD 100 struct key { char *word; int count; } keytab[] = { "auto",0, "break", 0, "case", 0, "char", 0, "const", 0, "continue", 0, "default", 0, "unsigned", 0, "void", 0, "volatite", 0, "while", 0 }; int mygetword(char *, int); int binsearch(char *, struct key*, int); int main(int argc, char *argv[]) { int n; char word[MAXWORD]; while(mygetword(word,MAXWORD)!=EOF) if (isalpha(word[0])) if((n=binsearch(word,keytab,NKEYS))>=0) keytab[n].count++; for (n=0;n<NKEYS;n++) if (keytab[n].count>0) printf("%d=%s\n",keytab[n].count,keytab[n].word); } int binsearch(char *word,struct key keytab[],int n) { int cond; int low, high, mid; low=0; high=n-1; while(low<=high) { mid=(low+high)/2; if((cond=strcmp(word,keytab[mid].word))<0) high=mid-1; else if(cond>0) low=mid+1; else return mid; } return -1; } int mygetword(char *word,int lim) { int c,getch(void); void ungetch(int); char *w=word; int t; while(isspace(c=getch())); if(c!=EOF) *w++=c; if(!isalpha(c)) { if(c=='\"') { for(c=getch();c!='\"';c=getch()); } else if(c=='#') { for(c=getch();c!='\n';c=getch()); } else if(c=='/') if((c=getch())=='/') { for(c=getch();c!='\n';c=getch()); } else ungetch(c); else for(;!isspace(c)&&c!=EOF;c=getch()); *w='\0'; return c; } for(;--lim>0;w++) if(!isalnum(*w=getch())) { if(!isalnum(*w)) { ungetch(*w); break; } } *w = '\0'; return word[0]; } #define BUFSIZE 100 char buf[BUFSIZE]; int bufp=0; int getch(void) { return (bufp>0) ? buf[--bufp] :getchar(); } void ungetch(int c) { if (bufp>=BUFSIZE) printf("ungetch: too many characters\n"); else buf[bufp++] = c; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* piecechooser.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: smifsud <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/03/01 15:26:15 by smifsud #+# #+# */ /* Updated: 2017/03/01 16:20:59 by smifsud ### ########.fr */ /* */ /* ************************************************************************** */ #include <bot.h> #include <libft.h> size_t *encirclefour(t_game *game, char **piece) { if (game->updown < 4) { game->updown += 1; return (rightchooser(game, piece)); } else if (game->updown < 6) { game->updown += 1; return (upchooser(game, piece)); } else { game->updown += 1; if (game->updown == 8) game->updown = 4; return (downchooser(game, piece)); } } size_t *encirclethree(t_game *game, char **piece) { if (game->updown == 1) { game->updown = 2; return (rightchooser(game, piece)); } else { game->updown = 1; return (cornerchooser(game, piece)); } } size_t *encircletwo(t_game *game, char **piece) { if (game->updown == 3) { game->updown = 1; return (cornerchooser(game, piece)); } else { if (game->updown == 2) game->updown += 1; else game->updown = 2; return (rightchooser(game, piece)); } } size_t *encircleone(t_game *game, char **piece) { if (game->updown < 4) { game->updown += 1; return (rightchooser(game, piece)); } else if (game->updown < 6) { game->updown += 1; return (upchooser(game, piece)); } else { game->updown += 1; if (game->updown == 8) game->updown = 4; return (downchooser(game, piece)); } } size_t *piecechooser(t_game *game, char **piece) { if (game->width < 90) { if (MP('x')) return (encircleone(game, piece)); else if (MP('o')) return (encircletwo(game, piece)); } else { if (MP('x')) return (encirclethree(game, piece)); else return (encirclefour(game, piece)); } return (upchooser(game, piece)); }
C
/*Naresh i Technologies For Any Doubts contact Mr.Balu Email:[email protected] */ void main() { int i=100; char ch='A'; float f=16.8; void *ptr; ptr=(int*)&i; printf("\n%d %d",i,*(int*)ptr); /*Naresh i Technologies For Any Doubts contact Mr.Balu Email:[email protected] */ ptr=(char*)&ch; printf("\n%c %c",ch,*(char*)ptr); ptr=(float*)&f; printf("\n%f %f",f,*(float*)ptr); } /*Naresh i Technologies For Any Doubts contact Mr.Balu Email:[email protected] */
C
#include<stdio.h> #include<conio.h> #include<string.h> #include<stdlib.h> void main(){ int currentState = 1,len; char a,b,str[100]; printf("Enter your string : "); scanf("%s",&str); len = strlen(str); if(len==3){ if(currentState == 1 && str[0]=='a'){ currentState = 2; } if(currentState == 2 && str[1]=='b'){ currentState = 3; } if(currentState == 3 && str[2]=='b'){ currentState = 4; printf("String is accepted"); } else { printf("String is rejected"); } } else { printf("Enter correct string"); } getch(); }
C
//3. Seten (respektive vynsoben) sel //Na vstupu je posloupnost sel oddlench mezerami. Pomoc dlouh aritmetiky naprogramujte: //a) souet celch sel //b) souin celch sel //c) souet relnch sel //d) souin relnch sel #include <stdio.h> #include <string.h> #include "aritmetika.h" void main(int argc, char** argv) { Cislo* pCisloA = NULL; Cislo* pCisloB = NULL; Cislo* pVysledek = VytvorCislo(); FILE* soubor; char* nazevSouboru; nazevSouboru = argv[1]; soubor = fopen(nazevSouboru,"r"); pCisloA = VratCislo(soubor); EulerovoCislo(pCisloA,pVysledek,100); // Faktorial(pCisloA,pVysledek); /* pCisloA = VratCislo(soubor); pCisloB = VratCislo(soubor); if (pCisloA != NULL) { VypisCislo(pCisloA); printf("\n"); }; //pVysledek = pCisloA; if (pCisloB != NULL) { VypisCislo(pCisloB); printf("\n"); }; while (pCisloB != NULL) { if (pCisloA == NULL) { pVysledek = pCisloB; }; if (pCisloB == NULL) { pVysledek = pCisloA; }; if ((pCisloA != NULL) && (pCisloB != NULL)) { //Scitani(pCisloA,pCisloB,pVysledek); //Nasobeni(pCisloA,pCisloB,pVysledek); Deleni(pCisloA,pCisloB,pVysledek,3); }; pCisloA = pVysledek; pCisloB = VratCislo(soubor); if (pCisloB != NULL) { VypisCislo(pCisloB); printf("\n"); }; }; */ if (pVysledek != NULL) { //VypisGumu((*pVysledek).mantisa); //printf("\n"); VypisCislo(pVysledek); }; SmazCislo(pVysledek); fclose(soubor); getchar(); return; };
C
#define OBMPIMAGENAME "bmp_encrypt.bmp" #define OOBMPIMAGENAME "bmp_decrypt.bmp" #define CSVNAME "output.csv" #define BYTE_MAX_VALUE 256 #define BIT_BYTE 8 #include <stdio.h> #include <time.h> #include "SPN.h" int user_input(char* filename, unsigned int data_length, unsigned int rounds_count){ /*some exception for user input must be here*/ srand(time(NULL)); TKEY key; init_key(&key, data_length * rounds_count); print_key(&key); TBOXES boxes; init_boxes(&boxes); int count = 1; for (int i = 0; i < data_length * rounds_count; i++) { if ( i % data_length == 0){ printf("\nRound %d\n", count); count++; } b_add_sbox(&boxes, BYTE_MAX_VALUE); print_sbox(boxes.sboxes[i]); } for (int i = 0; i < rounds_count; i++) { printf("\nRound %d\n", i+1); b_add_pbox(&boxes, data_length * BIT_BYTE); print_pbox(boxes.pboxes[i]); } encrypt_8(filename, OBMPIMAGENAME, &boxes, &key, rounds_count, data_length); decrypt_8(OBMPIMAGENAME, OOBMPIMAGENAME, &boxes, &key, rounds_count, data_length); analyze_8(OBMPIMAGENAME, CSVNAME); return 1; }; int main(int argc, char **argv) { if (argc == 4) { int result = user_input(argv[1], atoi(argv[2]), atoi(argv[3])); if ( result == -1){ printf("Error! Something was wrong ...\n"); return 0; } } else printf("Error! Only 3 parameters are requirted!\n"); return 0; }
C
#include "LRReceiver.H" // C++ headers #include <sstream> // for istringstream #include <iostream> // for cin, cout, cerr #include <iomanip> // for setw, left #include <cstdio> // for perror #include <cerrno> // for perror // Unix headers #include <unistd.h> // for read // Local headers #include "SocketClient.H" // for ::socket_tools::SocketClient using namespace std; namespace linear_road{ extern CarMap *the_car_map; LRReceiver::LRReceiver(CarMap *car_map, const char* auroraOutputServerName, int auroraOutputServerPort): cm(car_map), _auroraOutputServerName(auroraOutputServerName), _auroraOutputServerPort(auroraOutputServerPort) { } LRReceiver::~LRReceiver() { for (vector<pthread_t*>::iterator it = _client_threads.begin(); it != _client_threads.end(); ++it) { delete *it; } for (vector<ConnectionInfo*>::iterator it = _client_info_list.begin(); it != _client_info_list.end(); ++it) { delete *it; } } bool LRReceiver::start() { // Main output port for LR. ConnectionInfo* c_info = new ConnectionInfo; c_info->port = 80; c_info->len = 11 * sizeof(int); c_info->filename = "LRTollNotifications.dat"; c_info->receiver = this; pthread_t* receiver_thread = new pthread_t; if (pthread_create(receiver_thread, 0, (void*(*)(void*))receiverHandler, (void*)c_info) < 0) { perror("LRReceiver: creating thread"); } else { _client_threads.push_back(receiver_thread); _client_info_list.push_back(c_info); } return true; } void LRReceiver::receiverHandler(ConnectionInfo* c_info) { fstream output_file; output_file.open((c_info->filename).c_str(), ios::out); if (!output_file) { cerr << "Can not open file: " << c_info->filename << endl; return; } LRReceiver* me = c_info->receiver; ::socket_tools::SocketClient client( me->_auroraOutputServerName.c_str(), me->_auroraOutputServerPort, DEFALT_AURORA_OUTPUT_SERVER_TYPE); int sock = client.connect_server(); if (sock == -1) { cout << endl; cout << "Aurora output server address error or the server is not up." << endl; output_file.close(); return; } cout << endl; cout << "Connection with Aurora output server estabilished at socket" << sock << endl; int n = 1; // send number of ports if (!cwrite(sock, (char*)&n, sizeof(int))) { output_file.close(); close(sock); return; } // write port if (!cwrite(sock, (char*)&(c_info->port), sizeof(int))) { output_file.close(); close(sock); return; } // write tuple length if (!cwrite(sock, (char*)&(c_info->len), sizeof(int))) { output_file.close(); close(sock); return; } while (true) { char* buf; int packet_size; // receive packet size if (!cread(sock, (char*)&packet_size, sizeof(int))) { output_file.close(); close(sock); return; } if (packet_size != (c_info->len) + sizeof(int)) { cout << "Tuple size wrong: " << packet_size << endl; output_file.close(); close(sock); return; } // read packet buf = new char[packet_size]; //read(sock, packet, packet_size); if (!cread(sock, buf, packet_size)) { delete [] buf; output_file.close(); close(sock); return; } int* data = (int*)buf + 1; // Notice the carid and time. int carid = data[0]; int toll = data[10]; if (carid < 100) { cout << "Got a toll notification for car " << carid << " with toll " << toll << endl; } // Notice the packet. //c_info->receiver->cm->carGets(carid); the_car_map->carGets(carid); // write the packet to file for (int i = 0; i < (packet_size / sizeof(int) - 2); ++i) { output_file << *(data + i); output_file << ','; } output_file << *(data + packet_size / sizeof(int) - 2 ); output_file << endl; delete [] buf; } output_file.close(); close(sock); return; } bool LRReceiver::cwrite(int sock, char* packet, int len) { int rc = write(sock, packet, len); if (rc == -1) { if (errno == EPIPE) { cout << "LRReceiver:: socket " << sock << " closed by server." << endl; } else { cerr << "LRReceiver: write socke " << sock << " error." << endl; perror(""); } close(sock); return false; } if (rc != len) { cout << "LRReceiver:: socket " << sock << " closed by server." << endl; close(sock); return false; } return true; } bool LRReceiver::cread(int sock, char* buf, int len) { int rlen = 0; while (rlen < len) { int rval = read(sock, buf + rlen, len - rlen); if (rval == 0) { cout << "LRReceiver: connection closed by server at socket " << sock << endl; close(sock); return false; } if (rval == -1) { if (errno != EBADF) { cout << "LRReceiver: read socket " << sock << " error." << endl; perror(""); } close(sock); return false; } rlen += rval; } return true; } }
C
/*8 ݣеввԳ 3˼ 1̬(̬) ڵǰ˳ͶУʹþ̬Ԫأһ˳ֻܴMAXLENԪء Ϊ˴ŸԪأҪܹԴſռչΪʵһĿ꣬ǿʹö̬Ԫء ʱ˳ݽṹͿԶ£ */ #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <ctype.h> typedef struct { int* elem; // ָűԪصĶ̬ռ int size; // ̬ռĴС int n; // һ¼ʵʴŵԪصĸ } intVec; // /* ʼʱΪ˳һ̶Сռ䡣Ԫʱ // 洢ռ¿һռ䣨ͨΪԭռС // ԭռд洢ԪؿռУռԭռΪ˳Ĵ洢ռ䣬 // ԰Ԫط뵽˳С // ʵֻڶ̬˳䳣㷨 // 2˳Ӧ // Ŀ꣺ܹ˳һЩʵӦ⡣ // 1 // ˳LALBûݣֱβ뵽˳LALBС // ʵ㷨ϲLALBеݣѺϲݴŵLAС //ζȡLAеԪء void againMalloc(intVec* L); void initList(intVec* L, int ms); void insert_last_list(intVec* L, int x); int search(intVec* LA, int e); void UnionSet(intVec* LA, intVec* LB); void batchInsertList(intVec* L); void print(intVec* L); void intersectionSet(intVec* LA, intVec* LB, intVec* LC); int main() { intVec LA, LB; intVec LC; printf("LAΪ:1 2 3 4 5 6 -1\n"); batchInsertList(&LA); printf("LBΪ:3 4 5 6 7 8 9 -1 \n"); batchInsertList(&LB); printf("ԲUnionSet()\n"); UnionSet(&LA, &LB); printf("LA:\n"); print(&LA); //printf("Խintersection()\n"); //initList(&LC,5);/*ʼLC*/ //intersectionSet(&LA, &LB, &LC); //printf("LC:\n"); //print(&LC); } //˳ҪЩ. void print(intVec* L) { int i = 0; for (i = 0; i < L->n; i++) { printf("%d ", L->elem[i]); } } /*(ʼȴ)Ԫص˳*/ void batchInsertList(intVec* L) { int ms = 20; int i=0; initList(L, ms); printf("˳Ԫ:\n"); scanf("%d", &i); while (i != -1)/* -1Ϊı־ */ { insert_last_list(L, i); scanf("%d", &i); } } /* ԱLеposԪزx,ɹ1,򷵻0 */ int insertPosList(intVec* L, int pos, int x)/* insert_last_list()ʹ÷Χǿ */ { int i; /* ǷԽ */ if (pos < 1 || pos > L->n + 1) { /* "posԽ,ʧ,0; */ return 0; } /* ǷҪؿռ */ if (L->n == L->size) { againMalloc(L); }/* ȷռ㹻/Ȼ.againmalloc */ for (i = L->n - 1; i >= pos - 1; i--) { L->elem[i + 1] = L->elem[i]; }/* Ѿڳλ */ L->elem[pos - 1] = x;/* ִв */ L->n++;/* */ return 1;/* ɹ1 */ } // ϲ˳㷨ͨºʵ֣ */ void UnionSet(intVec* LA, intVec* LB) { /********************************************************** ϲLALBָ˳еݣѺϲݴLA *********************************************************/ int nA, nB, i, e; nA = LA->n; // ˳LAеԪظ nB = LB->n; // ˳LBеԪظ // ȡLBеԪأԪزLAУѸԪز뵽LA for (i = 1; i <= nB; i++)/* ѭΪԪڼ()Ԫظ */ { e = LB->elem[i - 1]; // ȡLBеĵiԪ if (search(LA, e) == -1)/*ʱ临ӶΪO(n)*/ { // ԪزLA insert_last_list(LA, e); // ѸԪز뵽LAıβ nA++; // ¼LAеǰԪظ } } } /*󽻼:*/ void intersectionSet(intVec* LA, intVec* LB, intVec* LC) { int i = 0; for (i = 0; i < LA->n; i++) { if (search(LB, LA->elem[i]) != -1) { insert_last_list(LC, LA->elem[i]); } } } void insert_last_list(intVec* L, int x) { /* βĻжԽ.ȻҪжϿռǷ㹻. */ if (L->n == L->size) { againMalloc(L);/* Ҫ·ռ */ } L->elem[L->n] = x;/* x뵽β */ L->n++;/* Ա+1 */ } void againMalloc(intVec* L) { int* p = (int*)realloc(L->elem, 2 * L->size * sizeof(int)); if (!p) { printf("reallo failured !"); exit(1); } L->elem = p;/* ʹͷָָ·ռ */ L->size = 2 * L->size; } void initList(intVec* L, int ms)/* Lʱmain()ͷһintVec͵ıL,Ȼ󽫸ñĵַ&Linitlist */ { if (ms < 0) { printf("maxsize is illegal"); } L->elem = (int*)malloc(ms * sizeof(int)); if (!L->elem) { printf("malloc failured"); exit(1); } L->size = ms;/* ԱĿռСΪms */ L->n = 0; /*ԪΪ0 */ } int search(intVec* LA, int e) { int i = 0; for (i = 0; i < LA->n; i++) { if (LA->elem[i] == e) { return i; } } return -1; } // /* // 2 // ƵأԱд󽻳򡣶˳LALB // ûݣֱβ뵽˳LALBСʵ㷨LALBеݽ󽻣 // ŵһµ˳LCСζȡLCеԪء˳㷨ͨºʵ֣ */ // /********************************************************** // LALBָ˳еݽ󽻣LC // *********************************************************/ // void IntersectSet(intVec *LA, intVec *LB, intVec *LC); // /* 3ۺϰ // ھӦóУʹ˳洢͹ݡҪʵһ򵥵ݹϵͳҪ£ // 4һ򵥵Ŀɽϵͳûϵͳв롢ɾͲͳϵͳе // 5ʹ˳洢ݣ */
C
#include <stdlib.h> #include <string.h> char* printerError(char *s) { int numErrors = 0; int count = 0; char *frac = malloc(sizeof(char)); for(; *s; s++,count++) if(*s < 97 || *s > 109) numErrors++; sprintf(frac,"%d/%d",numErrors,count); return frac; }
C
#include "splines.h" #include <math.h> void spline(int n, double *x, double *y, double *b, double *c, double *d) { int i, ib, nm1; double t; nm1 = n - 1; if (n < 2) return; if (n < 3) goto l20; d[1] = x[2] - x[1]; c[2] = (y[2] - y[1]) / d[1]; for (i = 2; i <= nm1; i++) { d[i] = x[i + 1] - x[i]; b[i] = 2 * (d[i - 1] + d[i]); c[i + 1] = (y[i + 1] - y[i]) / d[i]; c[i] = c[i + 1] - c[i]; } b[1] = -d[1]; b[n] = -d[n - 1]; c[1] = 0; c[n] = 0; if (n == 3) goto l10; c[1] = c[3] / (x[4] - x[2]) - c[2] / (x[3] - x[1]); c[n] = c[n - 1] / (x[n] - x[n - 2]) - c[n - 2] / (x[n - 1] - x[n - 3]); c[1] = c[1] * sqrt(d[1]) / (x[4] - x[1]); c[n] = -c[n] * sqrt(d[n - 1]) / (x[n] - x[n - 3]); l10: for (i = 2; i <= n; i++) { t = d[i - 1] / b[i - 1]; b[i] = b[i] - t * d[i - 1]; c[i] = c[i] - t * c[i - 1]; } c[n] = c[n] / b[n]; for (ib = 1; ib <= nm1; ib++) { i = n - ib; c[i] = (c[i] - d[i] * c[i + 1]) / b[i]; } b[n] = (y[n] - y[nm1]) / d[nm1] + d[nm1] * (c[nm1] + 2 * c[n]); for (i = 1; i <= nm1; i++) { b[i] = (y[i + 1] - y[i]) / d[i] - d[i] * (c[i + 1] + 2 * c[i]); d[i] = (c[i + 1] - c[i]) / d[i]; c[i] = 3 * c[i]; } c[n] = 3 * c[n]; d[n] = d[n - 1]; return; l20: b[1] = (y[2] - y[1]) / (x[2] - x[1]); c[1] = 0; d[1] = 0; b[2] = b[1]; c[2] = 0; d[2] = 0; //l30: return; } double seval(int n, double *u, double *x, double *y, double *b, double *c, double *d) { int i, j, k; double dx; i = 1; if (i >= n) i = 1; if (*u < x[i]) goto l10; if (*u <= x[i + 1]) goto l30; l10: i = 1; j = n + 1; l20: k = (i + j) / 2; if (*u < x[k]) j = k; if (*u >= x[k]) i = k; if (j > (i + 1)) goto l20; l30: dx = *u - x[i]; return y[i] + dx * (b[i] + dx * (c[i] + dx * d[i])); }
C
/* Author: josiahlee * Partner(s) Name: * Lab Section: * Assignment: Final Project * Exercise Description: [optional - include for your own benefit] * * I acknowledge all content contained herein, excluding template or example * code, is my own original work. */ #include <stdlib.h> #include <stdbool.h> #include <avr/io.h> #include <avr/eeprom.h> #include "io.h" #include "io.c" #include "timer.h" #include "keypad.h" #include "scheduler.h" #include "board.h" #include "block.h" #include "tetrisBlock.h" #ifdef _SIMULATE_ #include "simAVRHeader.h" #endif const unsigned char FALLING_RATE = 3; // drop every 250ms 5*50ms const unsigned char JOYSTICK_SENSITIVITY = 10; // ignore 150ms after reading joystick 15*10ms // ADC vvv ============================================================================================= // ADC Initialization void ADC_init() { ADMUX|=(1<<REFS0); ADCSRA|=(1<<ADEN)|(1<<ADPS0)|(1<<ADPS1)|(1<<ADPS2); //ENABLE ADC, PRESCALER 128 } // read from an adc register uint16_t ADC_read(uint8_t ch){ ch&=0b00000111; //ANDing to limit input to 7 ADMUX = (ADMUX & 0xf8)|ch; //Clear last 3 bits of ADMUX, OR with ch ADCSRA|=(1<<ADSC); //START CONVERSION while((ADCSRA)&(1<<ADSC)); //WAIT UNTIL CONVERSION IS COMPLETE return(ADC); //RETURN ADC VALUE } // ADC ^^^ ============================================================================================= // Display String Func without clearing the screen first void LCD_DisplayStringNoClear( unsigned char column, const unsigned char* string) { unsigned char c = column; while(*string) { LCD_Cursor(c++); LCD_WriteData(*string++); } } // global vars vvv ============================================================================================= tetrisBlock *tb; // current block int score; // global vars ^^^ ============================================================================================= // tetris game funcs vvv ============================================================================================= bool gameOver() { if (checkBit(31,1)) return true; return false; } bool canClearLine(int column, int bit) { for ( int i = 0; i < 16; i++){ if ( !checkBit(column + i*4, bit) ){ return false; } } return true; } bool clearLine (int line) { int column = line/5; int bit = (4 - line%5); if (!canClearLine(column, bit)){ return false; } for ( int i = 1; i < 15; i++){ clearPix(column + i*4, bit); } return true; } void shiftRow(int row, int bit) { switch (bit) { case 0: if (row % 4 == 0){ board[row] = board[row] | getBit(row+1, 4) | 0b10000; } else { board[row] = board[row] | getBit(row+1, 4); } break; case 1: if (row % 4 == 3){ board[row] = ( (board[row] & 0b11110) << 1 ) | getBit(row, 4) << 4 | 0b00001 ; } else if (row % 4 == 0){ board[row] = board[row] << 1 | getBit(row+1, 4) | getBit(row, 3) << 3 | getBit(row, 2) << 2 | 0b10000; } else { board[row] = board[row] << 1 | getBit(row+1, 4) | getBit(row, 3) << 3 | getBit(row, 2) << 2 | getBit(row, 4) << 4; } break; case 2: if (row % 4 == 3){ board[row] = ( (board[row] & 0b11110) << 1 ) | getBit(row, 4) << 4 | getBit(row, 3) << 3 | 0b00001; } else if (row % 4 == 0){ board[row] = board[row] << 1 | getBit(row+1, 4) | getBit(row, 3) << 3 | 0b10000; } else { board[row] = board[row] << 1 | getBit(row+1, 4) | getBit(row, 4) << 4 | getBit(row, 3) << 3; } break; case 3: if (row % 4 == 3){ board[row] = ( (board[row] & 0b11110) << 1 ) | getBit(row, 4) << 4 | 0b00001; } else if (row % 4 == 0){ board[row] = board[row] << 1 | getBit(row+1, 4) | 0b10000; } else { board[row] = board[row] << 1 | getBit(row+1, 4) | getBit(row, 4) << 4; } break; default: // 4 or -1 if (row % 4 == 3){ board[row] = ( (board[row] & 0b11110) << 1 ) | 0b00001; } else if (row % 4 == 0){ board[row] = board[row] << 1 | getBit(row+1, 4) | 0b10000; } else { board[row] = board[row] << 1 | getBit(row+1, 4); } break; } } void shiftLine(int line) { int column = line/5; int bit = (4 - line%5); for (int i = column; i < 4; i++){ // column for ( int j = 1; j < 15; j++){ // row if ( i == column ){ shiftRow( (j*4) + i, bit ); } else{ shiftRow( (j*4) + i, -1 ); } } } } void removeLines() { for ( int i = 1; i < 19; i++){ if (clearLine(i)){ score++; shiftLine(i); i--; } } } void displayScore() { LCD_DisplayStringNoClear(5, (const unsigned char*) "SCORE:"); LCD_WriteData('0' + score/10); LCD_WriteData('0' + score%10); } int getHighScore() { uint8_t tens = eeprom_read_byte((uint8_t*)46); uint8_t ones = eeprom_read_byte((uint8_t*)56); if (tens > 58 || ones > 58){ // if not a digit, default is larger return 0; } return ((tens-'0')*10 + (ones-'0')); } void setHighScore() { unsigned char t = score/10; unsigned char o = score%10; eeprom_write_byte ((uint8_t*)46 , t + '0'); eeprom_write_byte ((uint8_t*)56 , o + '0'); } // tetris game funcs ^^^ ============================================================================================= // tick funcs vvv ============================================================================================= unsigned char key; int keyPadTick( int state ) { switch (state) { case 0: return 1; break; case 1: key = GetKeypadKey(); if ( key != '\0'){ if (key == '1'){ for ( int i = 1; i < 15; i++){ setPix(i*4, 3); } } else if (key == '2'){ for ( int i = 1; i < 15; i++){ setPix(i*4, 2); } } else if (key == '3'){ for ( int i = 1; i < 15; i++){ setPix(i*4, 1); } } else if (key == '4'){ for ( int i = 1; i < 15; i++){ setPix(i*4, 0); } } else if (key == '5'){ for ( int i = 1; i < 15; i++){ setPix(i*4 + 1, 4); } } else if (key == 'A'){ LCD_Cursor(32); LCD_WriteData( eeprom_read_byte((uint8_t*)56)); } else if (key == 'B'){ LCD_Cursor(31); LCD_WriteData( eeprom_read_byte((uint8_t*)46)); } else if (key == 'C'){ setHighScore(); } else if (key == '*'){ score++; displayScore(); } return 2; } return 1; break; case 2: key = GetKeypadKey(); if ( key == '\0'){ return 1; } return 2; break; default: return 0; } return 0; } enum TetrisStates { init, wait_start, show_hs, init_game, play, update_board, new_piece, win, game_over, check_hs, new_hs, new_game_wait, restart } tstate; unsigned char tetrisCnt; int tetrisTick( int state ) { switch (state) { case init: LCD_DisplayString(1, (const unsigned char*) "PRESS"); LCD_DisplayStringNoClear(17, (const unsigned char*) "START"); return wait_start; break; case wait_start: if ( !(PINA & 0x08) ){ LCD_ClearScreen(); tetrisCnt = 0; return show_hs; } return wait_start; break; case show_hs: LCD_DisplayString(1,(const unsigned char*) "HIGH SCORE:"); LCD_WriteData(getHighScore()/10 + '0'); LCD_WriteData(getHighScore()%10 + '0'); LCD_DisplayStringNoClear(17, (const unsigned char*) "SCORE 20 TO WIN!!"); return init_game; break; case init_game: if ( tetrisCnt > 40){ LCD_ClearScreen(); resetBoard(); score = 0; displayBoard(); displayScore(); tetrisCnt = 0; tb = createTetrisBlock(rand() % 6); return play; } tetrisCnt++; return init_game; break; case play: if ( !(PINA & 0x08) ){ LCD_ClearScreen(); tetrisCnt = 0; return init; } if (tetrisCnt < FALLING_RATE){ tetrisCnt++; } else { tetrisCnt = 0; if (moveTetrisBlockDown(tb)){ tetrisCnt = 0; } else{ displayBoard(); return update_board; } } displayBoard(); return play; break; case update_board: removeLines(); if (score >= 20){ return win; } displayBoard(); displayScore(); return new_piece; break; case new_piece: if (gameOver()){ tetrisCnt = 0; return game_over; } tb = createTetrisBlock(rand() % 6); displayBoard(); return play; break; case win: LCD_DisplayString(1, (const unsigned char*) "YOU WIN!!!!!!!!:"); LCD_DisplayStringNoClear(17, (const unsigned char*) "SCORE: 20"); return check_hs; break; case game_over: LCD_ClearScreen(); displayBoard(); LCD_DisplayStringNoClear(5, (const unsigned char*) "GAME"); LCD_DisplayStringNoClear(21, (const unsigned char*) "OVER"); tetrisCnt = 0; return check_hs; break; case check_hs: if (tetrisCnt > 40){ if ( score > getHighScore() ){ setHighScore(); return new_hs; } return restart; } tetrisCnt++; return check_hs; break; case restart: LCD_ClearScreen(); LCD_DisplayString(1, (const unsigned char*) "PRESS START TO"); LCD_DisplayStringNoClear(17, (const unsigned char*) "RESTART-SCORE:"); LCD_WriteData('0' + score/10); LCD_WriteData('0' + score%10); resetBoard(); return wait_start; break; case new_hs: LCD_DisplayString(1, (const unsigned char*) "NEW HIGH SCORE:"); LCD_Cursor(17); LCD_WriteData('0' + score/10); LCD_WriteData('0' + score%10); tetrisCnt = 0; return new_game_wait; break; case new_game_wait: if (tetrisCnt > 40){ return restart; } tetrisCnt++; return new_game_wait; break; default: return init; } return init; } const unsigned short lrMax = 1023; const unsigned short udMax = 1023; unsigned char joystickCnt; unsigned char temp; int joystickTick( int state ) { // read joystick into temp temp = 0; LCD_Cursor(12); if (ADC_read(0) > lrMax*3/4){ temp = 1; } else if (ADC_read(0) < lrMax/4){ temp = 2; } else if (ADC_read(1) > udMax*3/4){ temp = 3; } else if (ADC_read(1) < udMax/4) { temp = 4; } switch (state) { case 0: joystickCnt = 0; return 1; break; case 1: if ( !(PINA & 0x04) ){ while(moveTetrisBlockDown(tb)); return 1; } switch (temp) { case 1: moveTetrisBlockRight(tb); break; case 2: moveTetrisBlockLeft(tb); break; case 3: rotateTetrisBlock(tb); break; case 4: moveTetrisBlockDown(tb); break; default: break; } if (temp != 0){ joystickCnt = 0; return 2; } return 1; break; case 2: // delay 10ms * JOYSTICK_SENSITIVITY if (temp == 0 || joystickCnt >= JOYSTICK_SENSITIVITY){ joystickCnt = 0; return 1; } joystickCnt++; return 2; break; default: return 0; } return 0; } // tick funcs ^^^ ============================================================================================= int main(void) { // init ports DDRA = 0x00; PORTA = 0xFF; DDRB = 0xF0; PORTB = 0x0F; // Keypad Line DDRC = 0xFF; PORTC = 0x00; // LCD data lines DDRD = 0xFF; PORTD = 0x00; // LCD control lines score = 0; srand(1); resetBoard(); // initializes board // tasks static task task1, task2, task3; task *tasks[] = { &task1, &task2, &task3 }; const unsigned short numTasks = sizeof(tasks)/sizeof(task*); task1.state = 0; task1.period = 50; task1.elapsedTime = task1.period; task1.TickFct = &keyPadTick; task2.state = 0; task2.period = 10; task2.elapsedTime = task2.period; task2.TickFct = &joystickTick; task3.state = init; task3.period = 50; task3.elapsedTime = task3.period; task3.TickFct = &tetrisTick; unsigned short i; unsigned long GCD = tasks[0]->period; for ( i = 1 ; i < numTasks ; i++ ) { GCD = findGCD(GCD, tasks[i]->period); } // init LCD and Timer LCD_init(); ADC_init(); TimerSet(GCD); TimerOn(); while (1) { for ( i = 0 ; i < numTasks ; i++ ) { if ( tasks[i]->elapsedTime == tasks[i]->period ) { tasks[i]->state = tasks[i]->TickFct(tasks[i]->state); tasks[i]->elapsedTime = 0; } tasks[i]->elapsedTime += GCD; } while(!TimerFlag); TimerFlag = 0; } return 0; } // avrdude -c atmelice_isp -p atmega1284 -B 5 -U flash:w:build/main.hex // avrdude -p atmega2560 -P usb -c stk600 -B 5 -U flash:w:main.hex // avrdude -c atmelice_isp -p atmega1284 -c stk600 -B 5 -U flash:w:build/main.hex
C
# include<stdio.h> int main(){ int a=4; float b =2.56; char c='u'; int d=34; int e=5+5; printf ("The value is a is of a %c %f \n" , c,b); printf ("The value is a is of a %d \n" ,a); printf ("The value is a is of a %d \n" ,a); printf ("sum value of a and d %d",a+d); printf ("sum value of a and d %d \n",e); return 0; } // create a program
C
#include <stdio.h> int N; int arr[10000]; int main(void) { scanf("%d", &N); for (int i = 0; i < N; i++) scanf("%d", &arr[i]); for(int i = 0; i < N; i++) { for(int j = 0; j < i; j++) { int temp; if(arr[i] < arr[j]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } int sum = 0; for (int i = 0; i < N; i++) { if (arr[i] < 0) { int tmp = arr[i]; if (i+1 < N && arr[i+1] <= 0) tmp *= arr[++i]; sum += tmp; } else break; } for (int j = N-1; j >= 0; j--) { if (arr[j] > 1) { int tmp = arr[j]; if (j-1 >= 0 && arr[j-1] > 1) tmp *= arr[--j]; sum += tmp; } else if (arr[j] == 1) sum += 1; else break; } printf("%d\n", sum); return 0; }
C
#include "merge.h" #include <stdlib.h> int *merge(int *vec1, int n1, int *vec2, int n2) { int i1 = 0; // current location in vec1 int i2 = 0; // current location in vec2 int i3 = 0; // current location in the resulting array int *vec3 = malloc((n1 + n2) * sizeof(int)); while (i1 < n1 && i2 < n2) vec3[i3++] = vec1[i1] < vec2[i2] ? vec1[i1++] : vec2[i2++]; // finish copying vec1 (if there is any left to copy) while (i1 < n1) // idomatic C vec3[i3++] = vec1[i1++]; // post-increment while (i2 < n2) vec3[i3++] = vec2[i2++]; return vec3; } /* Conditional expression if (a < b) c = a; else c = b; c = a < b ? a : b; cond ? truevalue : falsevalue */
C
#include<stdio.h> int main() { int N,L,A[51],i,j,k,t,x,s; scanf("%d",&N); for(i=0;i<N;i++) { scanf("%d",&L); for(j=0;j<L;j++) scanf("%d",&A[j]); s=0; for(k=0;k<(L-1);k++) for(x=k+1;x<L;x++) if(A[k]>A[x]) {t=A[k];A[k]=A[x];A[x]=t;s++;} printf("Optimal train swapping takes %d swaps.\n",s); } return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> void printCharacter(char *src, int start_at) { //int i = 0; //char tmp_src[MAX_CHARACTER]; if (src[start_at] == '\0') { //return '\0'; printf("%s\n",src); } //strncpy(tmp_src,(src + 1), strlen(src) - 1); switch (src[start_at] ) { case '2': src[start_at] = 'A'; printCharacter(src,start_at+1); src[start_at] = '2'; src[start_at] = 'B'; printCharacter(src,start_at+1); src[start_at] = '2'; src[start_at] = 'C'; printCharacter(src,start_at+1); src[start_at] = '2'; break; case '7': break; } } void main_22 () { char src[] = "22"; printCharacter(src,0); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_convert_c.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rcarette <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/01/12 13:21:53 by rcarette #+# #+# */ /* Updated: 2017/01/28 10:18:48 by rcarette ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" void ft_convert_c(t_printf *par, va_list *ap, t_buff *buff) { char character; int width; if (par->opt_l == 1) { ft_convert_lc(par, ap, buff); return ; } width = (par->width_field - 1); character = va_arg(*ap, int); if (par->subtraction == 0) { (par->zero == 1) ? print_character(width, '0', buff) : 0; (par->zero == 0) ? print_character(width, ' ', buff) : 0; manage_buffer_character(buff, character); } else if (par->subtraction == 1) { manage_buffer_character(buff, character); print_character(width, ' ', buff); } par->number_of_character += (1); if (width > 0) par->number_of_character += (width); }
C
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> int YangShi(int num[][3],int x,int y,int number){ int i = 0, j = y-1; while (i<x&&y>=0){ if (number > num[i][j]){ i++; } else if (number < num[i][j]){ j--; } else{ return 1; } } return 0; } int main(){ int num[3][3] = { { 1, 2, 3 }, { 2, 3, 4 }, { 3, 4, 5 } }; int number = 0; printf("Please input the number that you want to find!:\n"); scanf("%d", &number); if (YangShi(num, 3, 3, number)){ printf("find it!!\n"); } else{ printf("don't find it!!\n"); } system("pause"); return 0; }
C
#include<stdio.h> int main() { int n1,n2,min; min=(n1<n2) ? n1:n2; while(1) { if(min%n1==0 && min%n2==0) { printf("lcm of %d and %d=%d\n",n1,n2,min); break; } ++min; } return 0; }
C
#include "fun.h" #include "conio.h" #include "string.h" int compareString (char *string1, char *string2) { if (!string1 && !string2) return 0; if ( string1 && !string2) return 1; if (!string1 && string2) return -1; for (; *string1 && *string2 && *string1 == *string2; string1++, string2++) {} return *string1 - *string2; }
C
#include<stdio.h> main() { char string[]="Hello World"; display(string); } void display(char *string) { printf("%s",string); }
C
#include <stdio.h> #include <stdlib.h> void bubbleSort(int arr[], int size) { for (int i = 0; i < size - 1; ++i) //perform the loop size-1 times { for (int j = 0; j < size - i - 1; ++j) // j<size-i-1 since last i elements are sorted already { if (arr[j] > arr[j + 1]) //compare jth index element with j+1th index element, if it's greater then do following { //perform swap int temp = arr[j]; //assign a temp variable to value of arr[j] arr[j] = arr[j + 1]; //put arr[j+1] value inside arr[j] arr[j + 1] = temp; //assign arr[j+1] to the previously stored temp variable } } } } void selectionSort(int arr[], int size) { for (int i = 0; i < (size - 1); i++) // perform the loop size-1 times { int min_pos = i; //assume i is the index of minimum element for (int j = i + 1; j < size; j++) //loop from i+1 index to end of array { if (arr[min_pos] > arr[j]) //compare min_pos index element to current element min_pos = j; //if the current element is lesser, assign min_pos to current element index } if (min_pos != i) //After loop, check if our assumption holds, if it doesn't then { //perform swap int temp = arr[i]; arr[i] = arr[min_pos]; arr[min_pos] = temp; } } } int main() { int size; printf("Enter array size: "); scanf("%d", &size); int arr[size]; printf("\nEnter the array elements: "); for (int i = 0; i < size; ++i) { scanf("%d", &arr[i]); } char ch; //ask if user wants to sort using bubble or selection printf("\nDo you want to use Bubble Sort or Selection Sort? (Input 'B' for bubble sort or 'S' for selection sort): "); getchar(); scanf("%c", &ch); if (ch == 'b' || ch == 'B') { bubbleSort(arr, size); //sort using bubble sort printf("\nSorted array using bubble sort is: "); for (int i = 0; i < size; ++i) { printf("%d ", arr[i]); } } else if (ch == 'S' || ch == 's') { selectionSort(arr, size); //sort using selection sort printf("\nSorted array using Selection sort is: "); for (int i = 0; i < size; ++i) { printf("%d ", arr[i]); } } return 0; }
C
#include <stdlib.h> #include <stdio.h> int main() { // a_size is the size of the dynamic array to create int a_size = 10; // a is an integer pointer initialised to NULl int *a = NULL; // allocate enough memory for a_size integers a = malloc(a_size * sizeof(int)); // if the return from malloc is NULL, an error // occurred, print an error message and exit if(a == NULL) { fprintf(stderr,"Error allocating memory!\n"); exit(1); } // otherwise, populate the array with some values for(int i=0; i<a_size; i++) { a[i] = i*10; } // and print them for(int i=0; i<a_size; i++) { printf("a[%d]: %d\n",i,a[i]); } // before returning we free the previously allocated // integer pointer a free(a); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <malloc.h> void sortiranje(int *polje, int pocetni, int zadnji) { int i, min = pocetni, tmp; if (pocetni < zadnji) { for (i = pocetni + 1; i<zadnji; i++) { if (polje[i]<polje[min]) min = i; } tmp = polje[pocetni]; polje[pocetni] = polje[min]; polje[min] = tmp; sortiranje(polje, pocetni + 1, zadnji); } return; } int main() { int broj, i, *polje, x; FILE *tok1, *tok2; tok1 = fopen("D:/datoteka.txt", "w"); tok2 = fopen("D:/sortirani.txt", "w"); srand((unsigned)time(NULL)); broj = rand() % (4000 - 500 + 1) + 500; polje = (int*)malloc(broj*sizeof(int)); for (i = broj; i>0; i--) { x = rand() % 10001; polje[i] = x; fprintf(tok1, "%d\n", x); } sortiranje(polje, 0, broj); for (i = 0; i<broj; i++) { fprintf(tok2, "%d\n", polje[i]); printf("%d\n", polje[i]); } fclose(tok1); fclose(tok2); return 0; }
C
#include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/shm.h> #define MY_KEY 19920809 #define SHM_SIZE 0x1000 void toggleCase(char *buf,int cnt); void toggleCase(char *buf,int cnt) { int i; for(i=0;i<cnt;i++) { if((buf[i] >= 'A') && (buf[i] <= 'Z')) buf[i]=0x20; if((buf[i] >='a' ) && (buf[i] <= 'z')) buf[i] -= 0x20; } } int main() { int semId,shmId; char *pShm; struct sembuf smop; /** Create a Semaphore set ,Containig two semaphores **/ semId = semget(MY_KEY,2,0660| IPC_CREAT); if(semId < 0) { printf("Could not Create Semaphore\n"); return (1); } else printf("Opened a Semaphore Id is %d\n",semId); /** set initial token count of both semaphores to zeros **/ semctl(semId,0,SETVAL,0); semctl(semId,1,SETVAL,0); /** Create Shared Memory Segment **/ shmId = shmget(MY_KEY,SHM_SIZE, 0660 | IPC_CREAT); if(shmId < 0) { printf("Could Not Create Shared Memory Segment\n"); return (2); } /*** ATTACH Shared Memory Segment to Processaddress space **/ pShm = shmat(shmId,NULL,0); if(!pShm) { printf("Could not attach Shared Memory Segment\n"); return 1; } while(1) { /** Wait For a token from semaphore 0 **/ smop.sem_num = 0; smop.sem_op = -1; smop.sem_flg = 0; semop(semId,&smop,1); /** Process the Message available in Shared Memory **/ printf("Got the semaphore \n"); strcpy(pShm+256,pShm); toggleCase(pShm+256,strlen(pShm+256)); printf("processed the request message and placed response\n"); /** send token to semaphore 1 **/ smop.sem_num = 1; smop.sem_op = 1; smop.sem_flg = 0; semop(semId,&smop,1); } }
C
#include <stdio.h> #include <string.h> #include <assert.h> int str_del_sub(char* str1,char* str2); int main() { char str2[] = {"cd"}; char str1[] = {"abcdabcda"}; printf("str1 = %p\n",str1); printf("str2 = %p\n",str2); printf("%s\n",str1); str_del_sub(str1,str2); printf("str1 : %s\n",str1); return 0; } int str_del_sub(char* str1, char* str2) { assert(str1 != NULL); assert(str2 != NULL); if (strlen(str1) >= strlen(str2)) { int i,j; for(i = 0; i <= strlen(str1); i++) { for(j = 0; j < strlen(str2); j++) { if (str1[i + j] != str2[j]) break; else; } if (j == strlen(str2)){ //若出现子字符串,则j为子字符串的长度 printf("----------j = %d,%d\n",j,str2[j]); printf("%p,%p\n",str1+i+j,str1+i); printf("str1[i] = %c\n",str1[i]); for(int n = 0; n<(strlen(str1)-i+1); n++) //使用位移删除子字符串 { str1[i+n] = str1[i+n+j]; } printf("%s\n",str1); } } }else return -1; }
C
#include <stdio.h> #include <stdlib.h> #include "mat.h" #define MAT_SIZE 5 int test_unoptimized(double *a, int arows, int acols, double *b, int brows, int bcols, double *c_actual) { double *c_calc = malloc(MAT_SIZE * MAT_SIZE * sizeof(double)); mmult(c_calc, a, MAT_SIZE, MAT_SIZE, b, MAT_SIZE, MAT_SIZE); int are_same = compare_matrices(c_actual, c_calc, MAT_SIZE, MAT_SIZE); free(c_calc); return are_same; } int main(void) { double *a = read_matrix_from_file("a.txt"); double *b = read_matrix_from_file("b.txt"); double *c_actual = read_matrix_from_file("c.txt"); double *c_calc = malloc(MAT_SIZE * MAT_SIZE * sizeof(double)); if(!test_unoptimized(a, MAT_SIZE, MAT_SIZE, b, MAT_SIZE, MAT_SIZE, c_actual)) { exit(1); } puts("All tests pass."); free(a); free(b); free(c_actual); }
C
typedef struct { // in ms double attack_time; double attack_gain; double decay_time; double decay_gain; double sustain_time; double release_time; } adsr_param; long gain(float* in, size_t buflen, size_t offset, size_t len, double gain) { ASSERT(buflen >= offset + len, "offset + len greater that buffer length"); ASSERT(POSITIVE(gain), "Gain shall be positive 0.0 and 1.0"); LOG(LOG_DEBUG, "Gain : [%u,%u], gain : %lf", offset, offset+len, gain); size_t i = offset; for(; i < offset + len; i++) { in[i]*=gain; } return len; } float max(float* in, size_t buflen) { float max = in[0]; size_t i = 0; for(;i < buflen; i++) { if(max < in[i]) max = in[i]; } return max; } float min(float* in, size_t buflen) { float min = in[0]; size_t i = 0; for(;i < buflen; i++) { if(min > in[i]) min = in[i]; } return min; } long ramp(float* in, size_t buflen, size_t offset, size_t len, double start_gain, double end_gain) { ASSERT(buflen >= offset + len, "offset + len greater that buffer length"); ASSERT(POSITIVE(start_gain) && POSITIVE(end_gain), "Gain shall be positive"); size_t i = offset; double increment = (end_gain - start_gain) / len; double gain_acc = start_gain; LOG(LOG_DEBUG, "Ramp : [%u, %u], start_gain : %lf, end_gain : %lf, increment : %lf", offset, offset+len, start_gain, end_gain, increment); for(; i < offset+len; i++) { in[i]*=gain_acc; gain_acc+=increment; } return len; } long adsr(float* in, size_t len, adsr_param* param) { ASSERT(ms_to_samples(param->decay_time + param->attack_time + param->sustain_time + param->release_time) > len, "adsr filter is to long."); // attack if (param->attack_time != 0) { ramp(in, len, 0, ms_to_samples(param->attack_time), 0.0, param->attack_gain); } // decay ramp(in, len, ms_to_samples(param->attack_time), ms_to_samples(param->decay_time), param->attack_gain, param->decay_gain); // sustain gain(in, len, ms_to_samples(param->decay_time + param->attack_time), ms_to_samples(param->sustain_time), param->decay_gain); // release ramp(in, len, ms_to_samples(param->decay_time + param->attack_time + param->sustain_time), ms_to_samples(param->release_time), param->decay_gain, 0); // silence gain(in, len, ms_to_samples(param->decay_time + param->attack_time + param->sustain_time + param->release_time), len - ms_to_samples(param->decay_time + param->attack_time + param->sustain_time + param->release_time), 0.0); return len; } long square(float* out, size_t buflen, size_t offset, size_t len, double frequency) { double change = RATE / frequency; size_t i = offset; int index = offset; for(;index < offset + len; i++, index++) { if(fmod(i,change) > change/2) out[index] = 1; else out[index] = -1; } } long triangle(float* out, size_t buflen, size_t offset, size_t len, double frequency) { double change = RATE / frequency; size_t i = offset; for(; i < offset + len; i++) { if(fmod(i,change) < change / 2) out[i] = fmod(i,change)/(change/2) * 2 - 1; else out[i] = out[i - (int)change/2]; } } long sawtooth(float* out, size_t buflen, size_t offset, size_t len, double frequency) { double change = RATE/frequency; size_t i = offset; for(; i < offset + len; i++) { out[i] = fmod(i,change)/change * 2 - 1; } } long noise(float* out, size_t buflen, size_t offset, size_t len) { size_t i = offset; for(; i < offset + len; i++) { out[i] = (float)(random())/RAND_MAX * 2 - 1; } } void delay(float* in, size_t len, double delay, double feedback) { size_t DELAY = ms_to_samples(delay); int cursor = 0; double buffer[(size_t)(2*RATE)] = { 0.0 }; while(--len > 0) { double x = *in; double y = buffer[cursor]; buffer[cursor++] = x + y * feedback; *(in++) = buffer[cursor-1]; cursor = cursor%DELAY; } } void reverb(float* in, size_t len) { size_t i = 0; float t1 = 200.0; float g1 = 0.2; float rev = -3 * t1 / log10(g1); for(;i < 4; i++) { float dt = t1 / pow(2, ((float)i / 4)); float g = pow(10, -((3*dt) / rev)); delay(in, len, dt, g); printf("d%d t=%.3f g=%.3f\n", i, dt, g); } } void bitcrush(float* in, size_t len, size_t bits) { // number of value possible for a nbBits integer int coeff = (unsigned)pow(2, bits); int tmp = 0; while(--len != 0) { tmp = (int)(*in * coeff); *in++ = (float)tmp/coeff; } } long sinus(float* out, size_t buflen, size_t offset, size_t len, double frequency, unsigned long* angle) { ASSERT(buflen >= (offset + len), "offset + len greater that buffer length"); size_t i = offset; for(; i < offset+len; i++) { out[i] = sin(*(angle)*W*frequency); *angle = *(angle) + 1; } return len; } long sine_swipe(float* out, size_t buflen, size_t offset, size_t len, double frequency_start, double frequency_end, unsigned long* angle) { ASSERT(buflen >= (offset + len), "offset + len greater that buffer length"); double increment = (frequency_end - frequency_start) / len; double frequency = frequency_start; size_t i = offset; for(; i < offset + len; i++) { out[i] = sin((*angle)*W*frequency); frequency+=increment; if (out[i-1] < 0 && out[i] > 0) *angle = 0; (*angle)++; } return len; } void write_to_file(float* samples, size_t len, char* filename) { SF_INFO infos_write; infos_write.samplerate = 44100; infos_write.channels = 1; infos_write.format = SF_FORMAT_WAV | SF_FORMAT_FLOAT; if (sf_format_check(&infos_write) == 0) { fprintf(stderr, "Error while checking output file format."); abort(); } SNDFILE *file_to_write = sf_open(filename, SFM_WRITE, &infos_write); if (file_to_write == NULL) { fprintf(stderr, "%s\n", sf_strerror(file_to_write)); abort(); } sf_count_t countWrite = sf_writef_float(file_to_write, samples, len); if (countWrite != len) { fprintf(stderr, "Error while writing samples: %llu written instead of %d.\n", countWrite, len); abort(); } else { LOG(LOG_DEBUG, "Wrote %llu samples to %s file.", countWrite, filename); } if (sf_close(file_to_write) != 0) { fprintf(stderr, "Error while closing the file."); } } void hardclip(float* buffer, size_t len, double amount) { ASSERT(TEST_BOUND(amount), "Amount must be between 0.0 and 1.0."); size_t i = 0; float maxi = max(buffer, len) * amount; float mini = min(buffer, len) * amount; for (; i < len; i++) { if (buffer[i] > maxi) { buffer[i] = maxi; } if (buffer[i] < mini) { buffer[i] = mini; } } } void softclip(float* buffer, size_t len, double amount) { ASSERT(TEST_BOUND(amount), "Amount must be between 0.0 and 1.0."); size_t i = 0; for (; i < len; i++) { if (buffer[i] > amount) { buffer[i] = amount + (1.0 - amount) * tanh((buffer[i]-amount)/(1-amount)); } if (buffer[i] < -amount) { buffer[i] = -(amount + (1.0 - amount) * tanh((buffer[i]-amount)/(1-amount))); } } } void foldback_dist(float* buffer, size_t len, double threshold) { size_t i = 0; for(; i < len; i++) { if (buffer[i] > threshold || buffer[i] < -threshold) { buffer[i] = fabs(fabs(fmod(buffer[i] - threshold, threshold*4)) - threshold*2) - threshold; } } } void waveshape(float* buffer, size_t len, double threshold) { size_t i = 0; float maxi = max(buffer, len); for(; i < len; i++) { buffer[i] = (maxi / 2.0) * atan(16 * buffer[i] / maxi); } } void waveshape2(float* buffer, size_t len, double threshold) { size_t i = 0; float maxi = max(buffer, len); for(; i < len; i++) { buffer[i] = maxi * tanh(buffer[i]/maxi); } } void kick(framebuffer* buffer, size_t offset) { int angle = 0; int i=0; framebuffer* swipe = fb_new(ms_to_samples(4000)); framebuffer* thump = fb_new(ms_to_samples(4000)); framebuffer* sine2 = fb_new(ms_to_samples(4000)); framebuffer* sine3 = fb_new(ms_to_samples(4000)); framebuffer* channels[4] = {swipe, thump, sine2, sine3}; sinus(swipe->buffer, swipe->len, offset, ms_to_samples(150), 75, &angle); angle = 0; triangle(thump->buffer, thump->len, offset, ms_to_samples(100), 37.5); angle = 0; sinus(sine2->buffer, sine2->len, offset, ms_to_samples(100), 150, &angle); angle = 0; sinus(sine3->buffer, sine3->len, offset, ms_to_samples(100), 300, &angle); LOG(LOG_DEBUG, ("Kick 2")); float gains[4] = {0.8, 0.8, 0., 0.}; mix(channels, gains, 2, buffer); for(i=offset; i < offset + ms_to_samples(150); i++) { buffer->buffer[i] = swipe->buffer[i] * thump->buffer[i] * 2; } adsr_param param_thump = { 0, 1, 140, 0.0, 10, 10 }; adsr(buffer->buffer+offset, ms_to_samples(100), &param_thump); gain(buffer->buffer, buffer->len, 0, buffer->len, 0.9); } void hh(framebuffer* buffer, size_t offset) { noise(buffer->buffer, buffer->len, offset, ms_to_samples(75)); adsr_param param = { 0, 0.5, 75, 0, 0, 0 }; adsr(buffer->buffer+offset, ms_to_samples(100), &param); } void snare(framebuffer* buffer, size_t offset) { static unsigned long angle = 0; int i = 0; framebuffer* channels[5]; for(; i < 5; i++) { channels[i] = fb_new(ms_to_samples(4000)); } sine_swipe(channels[0]->buffer, channels[0]->len, offset, ms_to_samples(200), 240, 180, &angle); sine_swipe(channels[1]->buffer, channels[1]->len, offset, ms_to_samples(200), 440, 330, &angle); triangle(channels[2]->buffer, channels[2]->len, offset, ms_to_samples(200), 175/4); triangle(channels[3]->buffer, channels[3]->len, offset,ms_to_samples(200), 224/4); noise(channels[4]->buffer, channels[4]->len, offset,ms_to_samples(200)); float gains[5] = {1., 1., 0.5, 0.5, 0.5}; mix(channels, gains, 5, buffer); //gain(buffer->buffer, buffer->len, offset, ms_to_samples(200), 1.2); adsr_param param = { 0, 1, 100, 0.0, 250, 10 }; adsr(buffer->buffer+offset, ms_to_samples(200), &param); } void mix(framebuffer** buffers, float* gain,size_t size, framebuffer* out) { int i = 0; //float ratio = 1.0 / size; for(; i < size; i++) { int j = 0; for(; j < buffers[i]->len; j++) { out->buffer[j] += buffers[i]->buffer[j] * gain[i]; } } }
C
//programname: e2-22.c #include <stdio.h> int main(void) { int a, b; int *p; a = 100; p = &a; b = *p; printf("aの値 = %d\t aのアドレス%x\n", a, &a); printf("bの値 = %d\t bのアドレス%x\n", b, &b); printf("pの値 = %x\t pのアドレス%x\n", p, &p); return 0; }
C
/* ** time_utils.c for zappy in /home/pumpkin/Epitech/PSU_2015_zappy/server/src ** ** Made by Loik Gaonach ** Login <[email protected]> ** ** Started on Thu Jun 23 17:15:00 2016 Loik Gaonach ** Last update Thu Jun 23 17:15:00 2016 Loik Gaonach */ #include <stddef.h> #include "time_utils.h" unsigned long diff_time_now(struct timeval *b) { struct timeval d; struct timeval now; if (gettimeofday(&now, NULL) != -1) { timersub(&now, b, &d); return (1000000 * d.tv_sec + d.tv_usec); } return (0); }
C
#include "holberton.h" /** * rev_string - reverse string * Description:reverse string * @s:string to print */ void rev_string(char *s) { int string = 0; int index = 0; char tmp; while (s[string] != '\0') { string++; } string--; while (index < string) { tmp = s[index]; s[index] = s[string]; s[string] = tmp; index++; string--; } }
C
#include<stdio.h> main() { int a[9],s=0; float avg; printf("enter 10 no to avaerage it ==>>\n"); for(int i=0;i<=9;i++) scanf("%d",&a[i]); for(int i=0;i<=9;i++) s=s+a[i]; avg=s/10.0; printf("%f",avg); }
C
#include "holberton.h" #include <stdio.h> /** * _strlen - Count the length of a string. * @s: String. * Return: Length. */ unsigned int _strlen(char *s) { unsigned int c; for (c = 0; s[c]; c++) ; return (c); } /** * str_concat - Concatenates two strings * @s1: First string. * @s2: Second string. * Return: String that contains the contents of s1, followe * by the contents of s2. */ char *str_concat(char *s1, char *s2) { unsigned int i, size1, size2; char *scat; if (s1 == NULL) s1 = ""; if (s2 == NULL) s2 = ""; size1 = _strlen(s1); size2 = _strlen(s2); scat = malloc(sizeof(char) * (size1 + size2 + 1)); if (scat == NULL) return (NULL); for (i = 0; s1[i]; i++) scat[i] = s1[i]; for (i = 0; s2[i]; i++) scat[i + size1] = s2[i]; scat[i + size1] = '\0'; return (scat); }
C
#include "vandmlib.h" #include <stdio.h> #include <math.h> void print_v4(vec4 v) { printf("[ %f %f %f %f ]\n", v.x, v.y, v.z, v.w); } vec4 scalar_mult_v4(float s, vec4 v) { return (vec4){v.x * s, v.y * s, v.z * s, v.w * s}; } vec4 v4_add_v4(vec4 a, vec4 b) { return (vec4){a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w}; } vec4 v4_sub_v4(vec4 a, vec4 b) { return (vec4){a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w}; } float mag_v4(vec4 v) { return sqrt(pow(v.x, 2)+pow(v.y, 2)+pow(v.z, 2)+pow(v.w, 2)); } vec4 normalize_v4(vec4 v) { return scalar_mult_v4(1/mag_v4(v), v); } float dot_prod_v4(vec4 a, vec4 b) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } vec4 cross_prod_v4(vec4 a, vec4 b) { return (vec4){(a.y*b.z)-(a.z*b.y), (a.z*b.x)-(a.x*b.z), (a.x*b.y)-(a.y*b.x), 0}; } void print_mat4(mat4 m) { /*printf("[ x1 y1 z1 w1 ]\n"); printf("[ x2 y2 z2 w2 ]\n"); printf("[ x3 y3 z3 w3 ]\n"); printf("[ x4 y4 z4 w4 ]\n\n");*/ printf("[ %f %f %f %f ]\n", m.x.x, m.y.x, m.z.x, m.w.x); printf("[ %f %f %f %f ]\n", m.x.y, m.y.y, m.z.y, m.w.y); printf("[ %f %f %f %f ]\n", m.x.z, m.y.z, m.z.z, m.w.z); printf("[ %f %f %f %f ]\n", m.x.w, m.y.w, m.z.w, m.w.w); } mat4 scalar_mult_mat4(float s, mat4 v) { return (mat4){scalar_mult_v4(s, v.x), scalar_mult_v4(s, v.y), scalar_mult_v4(s, v.z), scalar_mult_v4(s, v.w)}; } mat4 mat4_add_mat4(mat4 a, mat4 b) { return (mat4){v4_add_v4(a.x, b.x), v4_add_v4(a.y, b.y), v4_add_v4(a.z, b.z), v4_add_v4(a.w, b.w)}; } mat4 mat4_sub_mat4(mat4 a, mat4 b) { return (mat4){v4_sub_v4(a.x, b.x), v4_sub_v4(a.y, b.y), v4_sub_v4(a.z, b.z), v4_sub_v4(a.w, b.w)}; } mat4 mat4_mult_mat4(mat4 a, mat4 b) { return (mat4){ (vec4){ (a.x.x * b.x.x)+(a.y.x * b.x.y)+(a.z.x * b.x.z)+(a.w.x * b.x.w), (a.x.y * b.x.x)+(a.y.y * b.x.y)+(a.z.y * b.x.z)+(a.w.y * b.x.w), (a.x.z * b.x.x)+(a.y.z * b.x.y)+(a.z.z * b.x.z)+(a.w.z * b.x.w), (a.x.w * b.x.x)+(a.y.w * b.x.y)+(a.z.w * b.x.z)+(a.w.w * b.x.w) }, (vec4){ (a.x.x * b.y.x)+(a.y.x * b.y.y)+(a.z.x * b.y.z)+(a.w.x * b.y.w), (a.x.y * b.y.x)+(a.y.y * b.y.y)+(a.z.y * b.y.z)+(a.w.y * b.y.w), (a.x.z * b.y.x)+(a.y.z * b.y.y)+(a.z.z * b.y.z)+(a.w.z * b.y.w), (a.x.w * b.y.x)+(a.y.w * b.y.y)+(a.z.w * b.y.z)+(a.w.w * b.y.w) }, (vec4){ (a.x.x * b.z.x)+(a.y.x * b.z.y)+(a.z.x * b.z.z)+(a.w.x * b.z.w), (a.x.y * b.z.x)+(a.y.y * b.z.y)+(a.z.y * b.z.z)+(a.w.y * b.z.w), (a.x.z * b.z.x)+(a.y.z * b.z.y)+(a.z.z * b.z.z)+(a.w.z * b.z.w), (a.x.w * b.z.x)+(a.y.w * b.z.y)+(a.z.w * b.z.z)+(a.w.w * b.z.w) }, (vec4){ (a.x.x * b.w.x)+(a.y.x * b.w.y)+(a.z.x * b.w.z)+(a.w.x * b.w.w), (a.x.y * b.w.x)+(a.y.y * b.w.y)+(a.z.y * b.w.z)+(a.w.y * b.w.w), (a.x.z * b.w.x)+(a.y.z * b.w.y)+(a.z.z * b.w.z)+(a.w.z * b.w.w), (a.x.w * b.w.x)+(a.y.w * b.w.y)+(a.z.w * b.w.z)+(a.w.w * b.w.w) } }; } float sarrus(float a, float b, float c, float d, float e, float f, float g, float h, float i) { return a*e*i + b*f*g + c*d*h - g*e*c - h*f*a - i*d*b; } mat4 minor_mat4(mat4 m) { return (mat4){ (vec4){ sarrus(m.y.y, m.z.y, m.w.y, m.y.z, m.z.z, m.w.z, m.y.w, m.z.w, m.w.w) /* m11 */, sarrus(m.y.x, m.z.x, m.w.x, m.y.z, m.z.z, m.w.z, m.y.w, m.z.w, m.w.w) /* m21 */, sarrus(m.y.x, m.z.x, m.w.x, m.y.y, m.z.y, m.w.y, m.y.w, m.z.w, m.w.w) /* m31 */, sarrus(m.y.x, m.z.x, m.w.x, m.y.y, m.z.y, m.w.y, m.y.z, m.z.z, m.w.z) /* m41 */ }, (vec4){ sarrus(m.x.y, m.z.y, m.w.y, m.x.z, m.z.z, m.w.z, m.x.w, m.z.w, m.w.w) /* m12 */, sarrus(m.x.x, m.z.x, m.w.x, m.x.z, m.z.z, m.w.z, m.x.w, m.z.w, m.w.w) /* m22 */, sarrus(m.x.x, m.z.x, m.w.x, m.x.y, m.z.y, m.w.y, m.x.w, m.z.w, m.w.w) /* m32 */, sarrus(m.x.x, m.z.x, m.w.x, m.x.y, m.z.y, m.w.y, m.x.z, m.z.z, m.w.z) /* m42 */ }, (vec4){ sarrus(m.x.y, m.y.y, m.w.y, m.x.z, m.y.z, m.w.z, m.x.w, m.y.w, m.w.w) /* m13 */, sarrus(m.x.x, m.y.x, m.w.x, m.x.z, m.y.z, m.w.z, m.x.w, m.y.w, m.w.w) /* m23 */, sarrus(m.x.x, m.y.x, m.w.x, m.x.y, m.y.y, m.w.y, m.x.w, m.y.w, m.w.w) /* m33 */, sarrus(m.x.x, m.y.x, m.w.x, m.x.y, m.y.y, m.w.y, m.x.z, m.y.z, m.w.z) /* m43 */ }, (vec4){ sarrus(m.x.y, m.y.y, m.z.y, m.x.z, m.y.z, m.z.z, m.x.w, m.y.w, m.z.w) /* m14 */, sarrus(m.x.x, m.y.x, m.z.x, m.x.z, m.y.z, m.z.z, m.x.w, m.y.w, m.z.w) /* m24 */, sarrus(m.x.x, m.y.x, m.z.x, m.x.y, m.y.y, m.z.y, m.x.w, m.y.w, m.z.w) /* m34 */, sarrus(m.x.x, m.y.x, m.z.x, m.x.y, m.y.y, m.z.y, m.x.z, m.y.z, m.z.z) /* m44 */ }, }; } mat4 cofact_mat4(mat4 m) { return (mat4){ (vec4){m.x.x, m.x.y * -1, m.x.z, m.x.w * -1}, (vec4){m.y.x * -1, m.y.y, m.y.z * -1, m.y.w}, (vec4){m.z.x, m.z.y * -1, m.z.z, m.z.w * -1}, (vec4){m.w.x * -1, m.w.y, m.w.z * -1, m.w.w} }; } float determ_mat4(mat4 a) //Assume given a mat4. { mat4 m = minor_mat4(a); return a.x.x*m.x.x - a.y.x*m.y.x + a.z.x*m.z.x - a.w.x*m.w.x; } mat4 inv_mat4(mat4 m) { return scalar_mult_mat4(1/determ_mat4(m), trans_mat4(cofact_mat4(minor_mat4(m)))); }; mat4 trans_mat4(mat4 m) { return (mat4){ (vec4){m.x.x, m.y.x, m.z.x, m.w.x}, (vec4){m.x.y, m.y.y, m.z.y, m.w.y}, (vec4){m.x.z, m.y.z, m.z.z, m.w.z}, (vec4){m.x.w, m.y.w, m.z.w, m.w.w} }; } vec4 mat4_mult_v4(mat4 m, vec4 v) { return (vec4){ (m.x.x * v.x) + (m.y.x * v.y) + (m.z.x * v.z) + (m.w.x * v.w), (m.x.y * v.x) + (m.y.y * v.y) + (m.z.y * v.z) + (m.w.y * v.w), (m.x.z * v.x) + (m.y.z * v.y) + (m.z.z * v.z) + (m.w.z * v.w), (m.x.w * v.x) + (m.y.w * v.y) + (m.z.w * v.z) + (m.w.w * v.w) }; }
C
/***************************************************************************** * Copyright 2005 Daniel Ferullo * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * *****************************************************************************/ /** * @file list.c * @author Daniel Ferullo ([email protected]) * * @brief A basic list implementation (optimized for sequential accesses). */ #include "list.h" #include "util.h" #include "debug.h" errorcode list_init(list_t *list) { if (list==NULL) return ERROR_NULL_ARG_1; list->head=NULL; list->last_get = list->head; list->last_get_num = 0; list->size = 0; return SUCCESS; } errorcode list_destroy(list_t *list, void (*func)(void*,void*), void *arg) { list_node_t *node; if (list==NULL) return ERROR_NULL_ARG_1; while (list->head != NULL) { /* make this node point to the old head */ node = list->head; /* set the 2nd node to be the first now */ list->head = node->next; /* use user defined function to clean up item */ if (func!=NULL) func(node->item,arg); /* delete the old first node */ safe_free(node); } return SUCCESS; } errorcode list_find(list_t *list, int (*func)(void*,void*), void *arg, void**found_item) { list_node_t *node; if (list==NULL) return ERROR_NULL_ARG_1; if (func==NULL) return ERROR_NULL_ARG_2; if (found_item==NULL) return ERROR_NULL_ARG_4; node = list->head; while(node!=NULL) { switch (func(node->item,arg)) { case LIST_FATAL : return ERROR_FUNC_POINTER_FUNC_FAILED; case LIST_NOT_FOUND : node = node->next; break; case LIST_FOUND : *found_item = node->item; return SUCCESS; default : return ERROR_FUNC_POINTER_FUNC_INVALID; } } return ERROR_NOT_FOUND; } errorcode list_get(list_t *list, int index, void **item) { list_node_t *node, *start; int num; if (list==NULL) return ERROR_NULL_ARG_1; if (index<0) return ERROR_NEG_ARG_2; if (item==NULL) return ERROR_NULL_ARG_3; if (index>list->size) return ERROR_ARG_2; start = node = list->last_get; num = list->last_get_num; do { /* if this is the end of the list, loop back to begining */ if (node==NULL) { node = list->head; num = 0; /*reset the counter */ continue; } /* if this is the index item, return it */ if (num==index) { *item = node->item; list->last_get = node; list->last_get_num = index; return SUCCESS; } node = node->next; num++; } while (start!=node); /* loop until the entire list was searched */ return ERROR_NOT_FOUND; } errorcode list_add(list_t *list, void *item) { list_node_t *node; if (list==NULL) return ERROR_NULL_ARG_1; if ( (node=(list_node_t*)malloc(sizeof(list_node_t))) == NULL) return ERROR_MALLOC_FAILED; /* set this node's item */ node->item = item; /* make this node point to the old head */ node->next = list->head; /* make this node the head of the list */ list->head = node; /*reset the last_get pointer */ list->last_get = list->head; list->last_get_num = 0; /* increase list size */ list->size += 1; return SUCCESS; } errorcode list_remove(list_t *list, int (*func)(void*,void*), void *arg){ list_node_t *node; list_node_t *prev_node; if (list==NULL) return ERROR_NULL_ARG_1; if (func==NULL) return ERROR_NULL_ARG_2; prev_node = NULL; node = list->head; while(node!=NULL) { switch (func(node->item,arg)) { /* if there was a fatal error, handle it */ case LIST_FATAL : return ERROR_FUNC_POINTER_FUNC_FAILED; /* if this just wasn't the item look at the next one */ case LIST_NOT_FOUND : prev_node = node; node = node->next; break; /* if the item was found, remove it*/ case LIST_FOUND : /* if this is the first item to remove, set the head */ if (prev_node==NULL) list->head = node->next; /* otherwise, set the previous node's next value to the * next node */ else prev_node->next = node->next; /* now free the node */ safe_free(node); /* reset the last get pointer */ list->last_get = list->head; list->last_get_num = 0; /* decrease list size */ list->size -= 1; return SUCCESS; default : return ERROR_FUNC_POINTER_FUNC_INVALID; } } return ERROR_NOT_FOUND; } int list_count(list_t *list) { if (list==NULL) return -1; return list->size; }