language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include "formula.h" #include "../eqtypes.h" #include "../common.h" #include "../mul.h" #include "../transform.h" #include "../starmath.h" #include "../debug/debug.h" #ifdef OS_WINDOWS #define swprintf _snwprintf #endif // release memory static void Formula_dealloc(FormulaObject *self) { if( self->equation != 0) eq_delete(self->equation); self->ob_type->tp_free((PyObject*)self); } //alloc memory for Formula static PyObject * Formula_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { FormulaObject *self; self = (FormulaObject *)type->tp_alloc(type, 0); return (PyObject *)self; } // init Formula after creation static int Formula_init(FormulaObject *self, PyObject *args, PyObject *kwds) { int type = EQ_SUMM; static char *kwlist[] = {"type", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i", kwlist, &type)) return -1; if(self != NULL) { self->equation = eq_node_new(type, 1); ((struct eq_node *)(self->equation))->first_child = eq_leaf_new(EQ_NUMBER, 1, NULL, 0); } return 0; } /* * Formula functions */ static PyObject * Formula_toStarMath(FormulaObject *self) { wchar_t star_math[1000]; PyObject *res = NULL; if(self != NULL) { *star_math = 0; sm_to_string((struct eq_node *)(self->equation), SM_DEFAULT, star_math); res = PyUnicode_FromUnicode(star_math, (Py_ssize_t)wcslen(star_math)); if(res == NULL) Py_RETURN_NONE; else return res; } return res; } static PyObject *Formula_mulout(FormulaObject *self) { if(self != NULL) { eq_move_multipliers_out((struct eq_node **)&self->equation); Py_RETURN_TRUE; } return NULL; } static PyObject *Formula_mulin(FormulaObject *self) { if(self != NULL) { eq_move_multiplier_in((struct eq_node **)&self->equation); Py_RETURN_TRUE; } return NULL; } static PyObject *Formula_transform(FormulaObject *self) { if(self != NULL) { eq_transform(&self->equation); Py_RETURN_TRUE; } return NULL; } static PyObject *Formula_calculate(FormulaObject *self) { if(self != NULL) { eq_calculate(&self->equation); Py_RETURN_TRUE; } return NULL; } /* * Number protocol functions */ struct eq_node *getEquation(PyObject *param) { wchar_t tmp[100]; double num = 0.0; char sign = 1; char is_num = 0; *tmp = 0; if(PyObject_TypeCheck(param, &FormulaType)) { struct eq_node *node = ((FormulaObject *)param)->equation; return (struct eq_node *)eq_clone(node); } if(PyUnicode_Check(param)) { if (PyUnicode_AsWideChar((PyUnicodeObject *)param, tmp, 100) < 0) return NULL; return (struct eq_node *)eq_leaf_new(EQ_SYMBOL, 1, tmp, 0); } if(PyString_CheckExact(param)) { char *str = PyString_AsString(param); swprintf(tmp, 100, L"%hs", str); return (struct eq_node *)eq_leaf_new(EQ_SYMBOL, 1, tmp, 0); } if(PyFloat_Check(param)) { num = PyFloat_AsDouble(param); if (num < 0) sign = -1; is_num = 1; } if(PyInt_Check(param) || PyLong_Check(param)) { num = (double)PyInt_AS_LONG(param); if (num < 0) sign = -1; is_num = 1; } if(is_num) return (struct eq_node *)eq_leaf_new(EQ_NUMBER, sign, NULL, sign*num ); return NULL; } static PyObject *Formula_NAdd(PyObject *o1, PyObject *o2) { struct eq_node *obj1; struct eq_node *obj2; FormulaObject *result; obj1 = getEquation(o1); obj2 = getEquation(o2); if(obj1 == NULL || obj2 == NULL) { if(obj1 != NULL) eq_delete(obj1); if(obj2 != NULL) eq_delete(obj2); PyErr_SetString(PyExc_ValueError, "Invalid arguments.\nArguments must be <int>, <float>, <string> or <Formula>."); return NULL; } result = (FormulaObject *)Formula_new(&FormulaType, Py_None, Py_None); result->equation = eq_node_new(EQ_SUMM, 1); obj1->next = obj2; ((struct eq_node *)(result->equation))->first_child = obj1; eq_transform(&result->equation); eq_transform(&result->equation); return (PyObject *)result; } static PyObject *Formula_NSub(PyObject *o1, PyObject *o2) { struct eq_node *obj1; struct eq_node *obj2; FormulaObject *result; obj1 = getEquation(o1); obj2 = getEquation(o2); if(obj1 == NULL || obj2 == NULL) { if(obj1 != NULL) eq_delete(obj1); if(obj2 != NULL) eq_delete(obj2); PyErr_SetString(PyExc_ValueError, "Invalid arguments.\nArguments must be <int>, <float>, <string> or <Formula>."); return NULL; } result = (FormulaObject *)Formula_new(&FormulaType, Py_None, Py_None); result->equation = eq_node_new(EQ_SUMM, 1); obj2->sign *= -1; obj1->next = obj2; ((struct eq_node *)(result->equation))->first_child = obj1; eq_transform(&result->equation); eq_transform(&result->equation); return (PyObject *)result; } static PyObject *Formula_NMul(PyObject *o1, PyObject *o2) { struct eq_node *obj1; struct eq_node *obj2; FormulaObject *result; obj1 = getEquation(o1); obj2 = getEquation(o2); if(obj1 == NULL || obj2 == NULL) { if(obj1 != NULL) eq_delete(obj1); if(obj2 != NULL) eq_delete(obj2); PyErr_SetString(PyExc_ValueError, "Invalid arguments.\nArguments must be <int>, <float>, <string> or <Formula>."); return NULL; } result = (FormulaObject *)Formula_new(&FormulaType, Py_None, Py_None); result->equation = eq_node_new(EQ_MUL, 1); obj1->next = obj2; ((struct eq_node *)(result->equation))->first_child = obj1; eq_transform(&result->equation); eq_transform(&result->equation); return (PyObject *)result; } static PyObject *Formula_NDiv(PyObject *o1, PyObject *o2) { struct eq_node *obj1; struct eq_node *obj2; struct eq_node *div; FormulaObject *result; obj1 = getEquation(o1); obj2 = getEquation(o2); if(obj1 == NULL || obj2 == NULL) { if(obj1 != NULL) eq_delete(obj1); if(obj2 != NULL) eq_delete(obj2); PyErr_SetString(PyExc_ValueError, "Invalid arguments.\nArguments must be <int>, <float>, <string> or <Formula>."); return NULL; } result = (FormulaObject *)Formula_new(&FormulaType, Py_None, Py_None); result->equation = eq_node_new(EQ_MUL, 1); div = eq_node_new(EQ_RECIPROCAL, 1); div->first_child = obj2; obj1->next = div; ((struct eq_node *)(result->equation))->first_child = obj1; eq_transform(&result->equation); eq_transform(&result->equation); return (PyObject *)result; } /* * Module functions */ static PyObject * Formula_sin(PyObject *self, PyObject *param) { wchar_t variable[1000]; char is_num = 0; char sign = 1; double num = 0.0; FormulaObject *result; memset(variable, 0, 1000 * sizeof(wchar_t)); if(PyUnicode_Check(param)) { if (PyUnicode_AsWideChar((PyUnicodeObject *)param, variable, 100) < 0) { PyErr_SetString(PyExc_ValueError, "Error in copy unicode string."); return NULL; } } if(PyString_CheckExact(param)) { char *str = PyString_AsString(param); swprintf(variable, 100, L"%hs", str); } if(*variable != 0) { result = (FormulaObject *)Formula_new(&FormulaType, Py_None, Py_None); result->equation = eq_node_new(EQ_SIN, 1); ((struct eq_node *)(result->equation))->first_child = eq_leaf_new(EQ_SYMBOL, 1, variable, 0); return (PyObject *)result; } if(PyFloat_Check(param)) { num = PyFloat_AsDouble(param); if (num < 0) sign = -1; is_num = 1; } if(PyInt_Check(param) || PyLong_Check(param)) { num = (double)PyInt_AS_LONG(param); if (num < 0) sign = -1; is_num = 1; } if(is_num) { result = (FormulaObject *)Formula_new(&FormulaType, Py_None, Py_None); result->equation = eq_node_new(EQ_SIN, 1); ((struct eq_node *)(result->equation))->first_child = eq_leaf_new(EQ_NUMBER, sign, NULL, sign*num ); return (PyObject *)result; } if(PyObject_TypeCheck(param, &FormulaType)) { result = (FormulaObject *)Formula_new(&FormulaType, Py_None, Py_None); result->equation = eq_node_new(EQ_SIN, 1); struct eq_node *node = ((FormulaObject *)param)->equation; ((struct eq_node *)(result->equation))->first_child = eq_clone(node); return (PyObject *)result; } PyErr_SetString(PyExc_ValueError, "Invalid argument."); return NULL; } static PyObject * Formula_cos(PyObject *self, PyObject *param) { FormulaObject *res = (FormulaObject *)Formula_sin(self, param); if(res != NULL) ((struct eq_node *)(res->equation))->type = EQ_COS; return (PyObject *)res; } static PyObject * Formula_asin(PyObject *self, PyObject *param) { FormulaObject *res = (FormulaObject *)Formula_sin(self, param); if(res != NULL) ((struct eq_node *)(res->equation))->type = EQ_ASIN; return (PyObject *)res; } static PyObject * Formula_acos(PyObject *self, PyObject *param) { FormulaObject *res = (FormulaObject *)Formula_sin(self, param); if(res != NULL) ((struct eq_node *)(res->equation))->type = EQ_ACOS; return (PyObject *)res; } static PyObject * Formula_symbol(PyObject *self, PyObject *args, PyObject *kwargs) { PyObject *name; int sign = 1; wchar_t sym_name[1000]; *sym_name = 0; FormulaObject *result; static char *kwlist[]={"name", "sign", NULL}; if(!PyArg_ParseTupleAndKeywords(args, kwargs, "O|i", kwlist, &name, &sign)) { PyErr_SetString(PyExc_ValueError, "Invalid arguments. \"name\"=<string>, \"sign\" = optional <int>."); return NULL; } if(PyUnicode_Check(name)) { if (PyUnicode_AsWideChar((PyUnicodeObject *)name, sym_name, 100) < 0) { PyErr_SetString(PyExc_ValueError, "Invalid unicode string."); return NULL; } } else if(PyString_CheckExact(name)) { char *str = PyString_AsString(name); swprintf(sym_name, 100, L"%hs", str); } else { PyErr_SetString(PyExc_ValueError, "Invalid arguments. \"name\"=<string>, \"sign\" = optional <int>."); return NULL; } result = (FormulaObject *)Formula_new(&FormulaType, Py_None, Py_None); result->equation = eq_leaf_new(EQ_SYMBOL, sign, sym_name, 0); return (PyObject *)result; } static PyObject * Formula_number(PyObject *self, PyObject *param) { double num = 0.0; char sign = 1; FormulaObject *result; if(PyFloat_Check(param)) { num = PyFloat_AsDouble(param); if (num < 0) sign = -1; } else if(PyInt_Check(param) || PyLong_Check(param)) { num = (double)PyInt_AS_LONG(param); if (num < 0) sign = -1; } else { PyErr_SetString(PyExc_ValueError, "Invalid argument."); return NULL; } result = (FormulaObject *)Formula_new(&FormulaType, Py_None, Py_None); result->equation = eq_leaf_new(EQ_NUMBER, sign, NULL, sign*num ); return (PyObject *)result; } #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif PyMODINIT_FUNC initformula(void) { PyObject* m; FormulaType.tp_new = PyType_GenericNew; if (PyType_Ready(&FormulaType) < 0) return; m = Py_InitModule3("formula", module_methods, "Init formula type."); Py_INCREF(&FormulaType); PyModule_AddObject(m, "Formula", (PyObject *)&FormulaType); PyModule_AddIntConstant(m, "EQ_SYMBOL", EQ_SYMBOL); PyModule_AddIntConstant(m, "EQ_NUMBER", EQ_NUMBER); PyModule_AddIntConstant(m, "EQ_SUMM", EQ_SUMM); PyModule_AddIntConstant(m, "EQ_MUL", EQ_MUL); PyModule_AddIntConstant(m, "EQ_RECIPROCAL", EQ_RECIPROCAL); PyModule_AddIntConstant(m, "EQ_SIN", EQ_SIN); PyModule_AddIntConstant(m, "EQ_COS", EQ_COS); PyModule_AddIntConstant(m, "EQ_ASIN", EQ_ASIN); PyModule_AddIntConstant(m, "EQ_ACOS", EQ_ACOS); PyModule_AddIntConstant(m, "EQ_POW", EQ_POW); }
C
#include <unistd.h> #include <stdio.h> #include <signal.h> void sigroutine(int unused) { printf("Catch a signal SIGINT "); } int main() { signal(SIGINT, sigroutine); pause(); printf("receive a signal "); }
C
/* SPDX-License-Identifier: GPL-2.0 */ int find_first(int v, const int x[], int n) { int l, u; l = -1, u = n; while (l+1 != u) { int m = (l+u)/2; if (x[m] < v) l = m; else u = m; } if (u >= n || x[u] != v) return -1; return u; }
C
#include "pilhaD.h" #include <stdio.h> #include <stdlib.h> int **criaMatriz(int n) { int i; int **matriz; matriz = malloc (n*sizeof(int *)); if(matriz != NULL) for (i=0; i<n; i++) { matriz[i] = malloc (n*sizeof(int)); if(matriz[i] == NULL) printf("\n n alocou"); } return matriz; } void zeraMatriz(int **tab, int n) { int k,t; for(k=0; k< n; k++){ for(t=0; t< n; t++){ tab[k][t] = 0; } } } void destroiMatriz(int **tab, int n){ int i; for(i=0;i < n;i++) free(tab[i]); free(tab); } void imprimeMatriz(int **tab, int n) { int i,j; for (i=0; i<n; i++) { printf("\n"); for(j=0; j<n; j++) { printf("%d ",tab[i][j]); } } return; } int podeMover(int **tabuleiro, int i, int j, int m){ int n=4; if(m==1 && i-1>0) return 1; else if(m==2 && j-1 >0) return 1; else if(m==3 && j+1 < n) return 1; else if(m==4 && i+1 < n) return 1; return 0; } void movePeca (int **tabuleiro,int *l,int *c,int atual){ int aux; if (atual == 1) { aux = tabuleiro[*l-1][*c]; tabuleiro[*l-1][*c] = -1; tabuleiro[*l][*c] = aux; *l-=1; } else if (atual == 2) { aux = tabuleiro[*l][*c-1]; tabuleiro[*l][*c-1] = -1; tabuleiro[*l][*c] = aux; *c-=1; } else if (atual == 3) { aux = tabuleiro[*l+1][*c]; tabuleiro[*l+1][*c] = -1; tabuleiro[*l][*c] = aux; *l+=1; } else { aux = tabuleiro[*l][*c+1]; tabuleiro[*l][*c+1] = -1; tabuleiro[*l][*c] = aux; *c+=1; } return; } void voltaPeca (int **tabuleiro,int *l,int *c,int atual){ int aux; if (atual == 1) { aux = tabuleiro[*l+1][*c]; tabuleiro[*l+1][*c] = -1; tabuleiro[*l][*c] = aux; *l+=1; } else if (atual == 2) { aux = tabuleiro[*l][*c+1]; tabuleiro[*l][*c+1] = -1; tabuleiro[*l][*c] = aux; *c+=1; } else if (atual == 3) { aux = tabuleiro[*l-1][*c]; tabuleiro[*l-1][*c] = -1; tabuleiro[*l][*c] = aux; *l-=1; } else { aux = tabuleiro[*l][*c-1]; tabuleiro[*l][*c-1] = -1; tabuleiro[*l][*c] = aux; *c-=1; } return; } int ordenado (int **tab) { int v[16],k,i,j,n=4; k=0; for (i=0;i<n;i++){ for (j=0;j<n;j++){ v[k] = tab[i][j]; k++; } } printf("\n Tai o vetor que rep. a matriz :\n"); for (i=0;i<16;i++) printf("%d ",v[i]); for (i=0;i<15;i++) { if (v[i] > v[i+1]) return 0; } return 1; } int main(){ int **tabuleiro; pilha *mov; int i,j,ok,atual,l,c,n,ordem; n=4; tabuleiro = criaMatriz(n); if (tabuleiro == NULL) printf("\n Fodeu matriz"); tabuleiro[0][0] = 3; tabuleiro[1][0] = 2; tabuleiro[2][0] = 1; tabuleiro[3][0] = 4; tabuleiro[0][1] = 5; tabuleiro[1][1] = -1; tabuleiro[2][1] = 11; tabuleiro[3][1] = 8; tabuleiro[0][2] = 9; tabuleiro[1][2] = 7; tabuleiro[2][2] = 10; tabuleiro[3][2] = 12; tabuleiro[0][3] = 13; tabuleiro[1][3] = 14; tabuleiro[2][3] = 6; tabuleiro[3][3] = 15; mov = criaPilha(16); if (mov == NULL) printf("\n Fodeu pilha"); for (i=0;i<n;i++) for(j=0;j<n;j++) if(tabuleiro[i][j] == -1) { l=i; c=j; } printf("\n A casa vazia e : %d,%d", l, c); atual = 1; ok=0; printf("\n antes"); ordem = ordenado(tabuleiro); printf("\n depois"); while (atual <= 4 && ordem != 1){ printf("\n Entrou , pos : %d,%d",l,c); atual = 1; ok=0; while (l>=0 && l<n && c>=0 && c<n && l!=3 && c!= 3 && ok == 0 && atual <=4) { printf("\n n ta la em baixo"); if (podeMover(tabuleiro, l, c, atual) == 1) { ok=1; printf("\n moveu com %d",atual); atual++; } else ok =0; } if(ok == 1) { printf("\n movendo"); empilha(mov,atual); movePeca (tabuleiro, &l, &c, atual); atual = 1; ordem = ordenado(tabuleiro); } else { if (pilhaVazia(mov) == 1) { printf("\n Deu ruim"); return 0; } else { printf("\n desempilhando"); atual = desempilha(mov); voltaPeca (tabuleiro, &l, &c, atual); atual++; } } } printf("\n Finish Him!"); imprimeMatriz(tabuleiro,n); return 0; }
C
#include<stdio.h> #include<stdlib.h> typedef struct node{ int data; //node sum int no; //node ka data struct node* next; }link; typedef struct node1{ int data; struct node1* left; struct node1* right; }tree; link* head = NULL; void push(int i, int node) { if(head == NULL) { link* n = (link*)malloc(sizeof(link)); n->data = i; n->no = node; n->next = NULL; head = n; } else { link *b = head; link *c = NULL; while(b != NULL && b->data < i) { c = b; b = b->next; } // case 1 : add at end //add at front //case 2: add at some pos. //case 3: same value exsists if(b == NULL) // reached at end and c is pointing to the last node { link* n = (link*)malloc(sizeof(link)); n->data = i; n->no = node; n->next = NULL; c->next = n; } else if(b->data == i); else if(c == NULL) // add at front { link* n = (link*)malloc(sizeof(link)); n->data = i; n->no = node; n->next = head; head = n; } else if(b->data > i && c->data < i) { link* n = (link*)malloc(sizeof(link)); n->data = i; n->no = node; c->next = n; n->next = b; } } } void print() { link* h = head; while(h != NULL) { printf(" %d ", h->no); h = h->next; } } tree* add_in(tree *root, int data) { if(root == NULL) { tree* t = (tree*)malloc(sizeof(tree)); t->data = data; t->left = NULL; t->right = NULL; return t; } else if(root->data > data) root->left = add_in(root->left, data); else if(root->data < data) root->right = add_in(root->right, data); return root; } void traverse(tree* root, int s) { if(root == NULL) return; traverse(root->left, s-1); push(s,root->data); traverse(root->right,s+1); } int main() { int s = 0; tree* root = NULL; root = add_in(root, 5); root = add_in(root, 10); root = add_in(root, 4); root = add_in(root, 9); root = add_in(root, 8); root = add_in(root, 7); root = add_in(root, 6); root = add_in(root, 11); traverse(root, s); print(); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int teststring(char str1[20], char str2[20]){ int ta, tb, flag=1, i; ta=strlen(str1); tb=strlen(str2); if (ta==tb){ for (i=0 ; i<ta && flag ; i++) if (str1[i]!=str2[i]) flag = 0; } else flag = 0; return flag; } int main(){ char nome1[20], nome2[20], nome3[20]; scanf("%s%s%s", nome1, nome2, nome3); if(teststring(nome1,"vertebrado")) { if (teststring(nome2, "ave")) { if (teststring(nome3, "carnivoro")) printf ("aguia\n"); else printf ("pomba\n"); } if (teststring(nome2, "mamifero")) { if (teststring(nome3, "onivoro")) printf("homem\n"); else printf ("vaca\n"); } } if (teststring(nome1,"invertebrado")) { if (teststring(nome2, "inseto")) { if (teststring(nome3, "hematofago")) printf("pulga\n"); else printf ("lagarta\n"); } if (teststring(nome2, "anelideo")) { if (teststring(nome3, "onivoro")) printf ("minhoca\n"); else printf("sanguessuga\n"); } } return 0; } /* #include <stdio.h> #include <stdlib.h> #include <string.h> int main(){ char nome1[20], nome2[20], nome3[20]; scanf("%s%s%s", nome1, nome2, nome3); if (strcmp(nome1,"vertebrado")==0) { if (strcmp(nome2,"ave")==0) { if (strcmp(nome3,"carnivoro")==0) printf ("aguia\n"); else printf ("pomba\n"); } if (strcmp(nome2,"mamifero")==0) { if (strcmp (nome3,"onivoro")==0) printf("homem\n"); else printf ("vaca\n"); } } if (strcmp(nome1,"invertebrado")==0) { if (strcmp(nome2,"inseto")==0) { if (strcmp(nome3,"hematofago")==0) printf("pulga\n"); else printf ("lagarta\n"); } if (strcmp(nome2,"anelideo")==0) { if (strcmp(nome3,"onivoro")==0) printf ("minhoca\n"); else printf("sanguessuga\n"); } } return 0; } */
C
#include<stdio.h> #include<stdlib.h> #include<string.h> /* BUSCA LINEAR COM STRUCT*/ typedef struct { int matricula; char nome[30]; int nota; } Aluno; int busca_Linear_nome (Aluno *V, int N, char nome[]) { int i; for(i=0; i<N; i++) if (strcmp(nome,V[i].nome)==0){ printf ("\nNome: %s",V[i].nome); printf ("\nMatricula: %d",V[i].matricula); printf ("\nNota: %d\n",V[i].nota); return i; } return -1; } int main() { Aluno *V; int N=4, i, retorna; char nome[30]; V = (Aluno*) malloc(N*sizeof(Aluno)); printf ("Preencha com nomes: \n"); for (i=0; i<N; i++){ scanf (" %[^\n]",V[i].nome); V[i].matricula = rand() % 100; V[i].nota = rand() % 10; } printf("\n"); system("pause"); system("CLS"); printf("\nDigite o nome a ser buscado no vetor: "); scanf(" %[^\n]",nome); retorna = busca_Linear_nome(V, N, nome); if (retorna == -1) printf("\nNao encontrado!\n"); else printf("\nElemento encontrado conforme acima, indice %d \n",retorna); return 0; }
C
extern void __VERIFIER_error(void); extern void __VERIFIER_assume(int); void __VERIFIER_assert(int cond) { if (!(cond)) { ERROR: __VERIFIER_error(); } return; } int __VERIFIER_nondet_int(); void main() { int X; int Y; int r; int l; r = X; __VERIFIER_assume(X >= 0 && Y>=0); if(Y < 0) { l = Y; while(l != 0) { r = r + 1; l = l + 1; } } else { l = Y; while(l != 0) { r = r - 1; l = l - 1; } } __VERIFIER_assert(r == X+Y); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ahammou- <ahammou-@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/11/08 11:38:21 by ahammou- #+# #+# */ /* Updated: 2019/05/23 13:24:10 by ahammou- ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" char *ft_strjoin_free(char *s1, char *s2, int d) { char *ps; unsigned long len; if (s1 == NULL || s2 == NULL || d < 0 || d > 3) return (NULL); len = ft_strlen(s1) + ft_strlen(s2); if (!(ps = ft_strnew(len))) return (NULL); ft_strcpy(ps, s1); ft_strcat(ps, s2); if (d == 1 || d == 3) ft_strdel(&s1); if (d == 2 || d == 3) ft_strdel(&s2); return (ps); } int count_endl(char **endl, const int fd) { int i; i = 0; while (endl[fd][i] && endl[fd][i] != '\n') i++; return (i); } int get_line(char **endl, char **line, const int fd, int ret) { char *tmp; int len; len = count_endl(endl, fd); if (endl[fd][len] == '\n') { *line = ft_strsub(endl[fd], 0, len); tmp = ft_strdup(endl[fd] + len + 1); free(endl[fd]); endl[fd] = tmp; } else if (endl[fd][len] == '\0') { if (ret == BUFF_SIZE) return (get_next_line(fd, line)); *line = ft_strdup(endl[fd]); ft_strdel(&endl[fd]); } return (1); } int get_next_line(const int fd, char **line) { static char *endl[OPEN_MAX]; char buffer[BUFF_SIZE + 1]; char *tmp; int ret; if (fd < 0 || fd > OPEN_MAX || line == NULL) return (-1); while ((ret = read(fd, buffer, BUFF_SIZE)) > 0) { buffer[ret] = '\0'; if (endl[fd] == NULL) endl[fd] = ft_strnew(1); if (!(tmp = ft_strjoin_free(endl[fd], buffer, 1))) return (-1); endl[fd] = ft_strdup(tmp); ft_strdel(&tmp); if (ft_strchr(buffer, '\n')) break ; } if (ret < 0) return (-1); else if (ret == 0 && (endl[fd] == NULL || endl[fd][0] == '\0')) return (0); return (get_line(endl, line, fd, ret)); }
C
/*Thiago Santos Teixeira nUSP 10736987 */ #ifndef __TABELASIMBOLO_VD_H #define __TABELASIMBOLO_VD_H /*esta é uma função de mergeSort que ira ordenar um vetor de uma struct, a *ordenção ira depender da variavel tipoOrd(pode ser por frequencia ou *alfabeticamente). */ void mergeSortVD(int inicio, int fim, stableV *stable, char *tipoOrd); /*função de merge modificada. */ void mergeVD(int inicio, int meio, int fim, stableV *stable, char *tipoOrd); /*esta função recebe uma tabela de simbolos feita com vetor dinamico e a imprime *na saida padrão em ordem alfabetica. */ void imprimeVD_A(stableV *stable); /*esta função recebe uma tabela de simbolos feita com vetor dinamico e a imprime *na saida padrão em ordem de frequencia. */ void imprimeVD_O(stableV *stable); /*Função que ira criar e devolver um ponteiro para uma tabela de simbolos que *usa um vetor desordenado. */ stableV *criaStableVD(); /*Função que receve uma de simbolos que usa um vetor desordenado e ira destruir *ela. */ void destroiStableVD(stableV *stable); /*Função que recebe uma string e uma tamabela de simbolos e ira inserir essa *palavra na tabela, se a palavra já estiver na tabela a função só ira *acrecentar a frequencia dela, se a tabela se encontar cheia a funçao ira chamar *a função realocastableV. */ stableV *insereStableVD(char *key, stableV *stable); /*Função que recebe uma tabela de simbolos e ira criar uma outra tabela de *simbolos com os mesmos itens porem com o dobro so tamanho da original. */ stableV *realocaStableVD(stableV *stable); #endif
C
#define EPS (10E-8) #define K_MAX (100) #include "stdio.h" #include "libs/bspedupack.h" #include "libs/debug.h" #define DUMP( n, a ) for(counter0=0;counter0<n;counter0++) printf("dump array[%d]=%lf\n",counter0, a[counter0]) void cg_test(); int N; int main(int argc, char** argv) { printf("Starting CG, sequential.\n"); cg_test(); return 0; } void neg(double* x) { int i; for(i=0;i<N;i++) x[i] *= -1; } double ip(double* a, double* b) { int i; double tmp = 0; for(i=0;i<N;i++) tmp += a[i]*b[i]; return tmp; } void scale(double factor, double* vec, double* res) { int i; for(i=0;i<N;i++) res[i] = factor * vec[i]; } void add(double *a, double*b, double*res) { int i; for(i=0;i<N;i++) res[i] = a[i]+b[i]; } void copy(double *in, double* out) { int i; for(i=0;i<N;i++) out[i] = in[i]; } void mv(double** A, double *u, double*res) { int i,j; for(i=0;i<N;i++) { res[i] = 0; for(j=0;j<N;j++) { res[i] += A[i][j] * u[j]; //printf("component A[%d][%d]*u[%d]=%lf\n", i,j,j,A[i][j] * u[j]); } } } void find_N() { // temporary N = 10; } void read_A(double** A) { char* filename = "examples/10x10.mtx"; int nz; FILE* fp = fopen(filename, "r"); fscanf(fp, "%d %*d %d %*d", &N, &nz); printf("N = %d, nz = %d\n", N, nz); fscanf(fp, "%*d"); // ignore starting proc index fscanf(fp, "%*d"); // ignore ending proc index int i, j; double val; int c; for(c=0;c<nz; c++) { fscanf(fp, "%d %d %lf", &i,&j,&val); A[i-1][j-1] = val; } fclose(fp); } void read_v(double* v) { char* filename = "examples/10x10.v"; FILE* fp = fopen(filename, "r"); fscanf(fp, "%*d %*d"); int i; double val; int c; for(c=0;c<N; c++) { fscanf(fp, "%d %*d %lf", &i,&val); v[i-1] = val; } fclose(fp); } void cg_test() { int i,j, counter0=0; // remove warning: counter0=counter0; double **A; double *u; double *v; find_N(); A = malloc(sizeof(double*)*N); for(i=0;i<N;i++) A[i] = malloc(sizeof(double)*N); // initialise A to all zeroes. (sparse) for(i = 0; i<N; i++) for(j = 0; j<N; j++) A[i][j] = 0.0; read_A(A); v = malloc(sizeof(double)*N); read_v(v); u = malloc(sizeof(double)*N); //initialise guess of u: for(i=0;i<N;i++) u[i] = 0.0; // start 'heavy lifting' int k = 0; // iteration number double *r; r = malloc(N * sizeof(double)); mv(A,u,r); neg(r); add(v,r,r); double rho, rho_old, beta, alpha, gamma; rho_old = 0; //kill warning rho = ip(r,r); double *p; p = malloc(N*sizeof(double)); double *w; w = malloc(N*sizeof(double)); while(sqrt(rho) > EPS * sqrt(ip(v,v)) && k < K_MAX) { if(k==0) { copy(r,p); } else { beta = rho/rho_old; scale(beta, p, p); add(r,p,p); } mv(A,p,w); gamma = ip(p,w); alpha = rho/gamma; scale(alpha, p, p); add(u,p,u); neg(w); scale(alpha,w,w); add(r,w,r); rho_old = rho; rho = ip(r,r); k++; } printf("after %d iterations, my answer is:\n", k); for(i=0;i<N;i++) printf("u[%d] = %lf\n", i, u[i]); printf("-> Filling in gives:\n"); mv(A,u,p); for(i=0;i<N;i++) printf("A.u[%d] = %lf \t orig_v[%d]=%lf\n", i, p[i], i, v[i]); printf("\nFinal error=%lf\n", rho); free(p); free(w); free(r); free(u); free(v); for(i=0;i<N;i++) free(A[i]); free(A); }
C
#include <stdio.h> int main() { int N, L; scanf("%d %d", &N, &L); int temp, flag, cnt = 0; for (int i = 1;; i++) { temp = i, flag = 1; while (temp != 0) { if(temp%10 == L){ flag = 0; } temp /= 10; } if (flag == 1) { //printf("i : %d\n", i); cnt++; if (cnt == N) { printf("%d\n", i); return 0; } } } }
C
/** * @file Scheduler.h * @brief Scheduler Header File for this program * @author Mohammed Awwad * @date 10/7/2020 * @version 1.0 */ //--------------------- Header Guard ------------------------------- #ifndef SCHEDULER_H_ #define SCHEDULER_H_ // ------------------ File Inclusions ------------------------------- #include <xc.h> #include "Timer.h" // ------------------ Public Constant ------------------------------- /* * The maximum number of tasks required at any one time during the execution of the program * MUST BE ADJUSTED FOR EACH NEW PROJECT */ #define SCH_MAX_TASKS (4) /**< The maximum number of tasks required at any one time during the execution of the program */ // ------------- Public data type declarations ---------------------------- // Store in DATA area, if possible, for rapid access // Total memory per task is 7 bytes typedef struct { void (*pTask)(void); /**< Pointer to the task (must be a 'void (void)' function) */ uint16 Delay; /**< Delay (ticks) until the function will (next) be run */ uint16 Period; /**< Interval (ticks) between subsequent runs. */ uint8 RunMe; /**< Incremented (by scheduler) when task is due to execute*/ } sTask_t; // ---------------- function prototypes ------------------------------- // Core scheduler functions /** * \b Brief: This is the Scheduler initialization function. * Prepares scheduler data structures and sets up timer interrupts at required rate. * You must call this function before using the scheduler. * @param void * @return void */ void SCH_Init_T1(void); /** * \b Brief: This is the the scheduler ISR. * It is called at a rate determined by the timer settings in SCH_Init_T1(). * This version is triggered by Timer 1 interrupts: * @param void * @return void */ void SCH_Update(void); /** * \b Brief: This is the the SCH_Add_Task * Causes a task (function) to be executed at regular intervals or after a user-defined delay * @param pointer to function - The name of the function which is to be scheduled. * NOTE: All scheduled functions must be 'void, void' - that is, they must take no parameters, and have a void return type. * * @param DELAY - The interval (TICKS) before the task is first executed * * @param PERIOD - If 'PERIOD' is 0, the function is only called once, at the time determined by 'DELAY'. * If PERIOD is non-zero,then the function is called repeatedly at an interval determined by the value of PERIOD * * @return Returns the position in the task array at which the task has been added. * If the return value is SCH_MAX_TASKS then the task could not be added to the array (there was insufficient space). * If the return value is < SCH_MAX_TASKS, then the task was added successfully. */ uint8 SCH_Add_Task(void (*pFunction) (void), const uint16, const uint16); /** * \b Brief: This is the 'dispatcher' function. When a task (function) is due to run, SCH_Dispatch_Tasks() will run it. * This function must be called (repeatedly) from the main loop. * @param void * @return void */ void SCH_Dispatch_Tasks(void); /** * \b Brief: This is the Scheduler start function. Starts the scheduler, by enabling interrupts. * NOTE: Usually called after all regular tasks are added,to keep the tasks synchronized. * NOTE: ONLY THE SCHEDULER INTERRUPT SHOULD BE ENABLED!!! * @param void * @return void */ void SCH_Start(void); /** * \b Brief: This is the Go to Sleep function. This scheduler enters 'idle mode' between clock ticks to save power. * The next clock tick will return the processor to the normal operating state. * Note: a slight performance improvement is possible if this function is implemented as a macro, or if the code here is simply * pasted into the 'dispatch' function. * *** ADAPT AS REQUIRED FOR YOUR HARDWARE *** * @param void * @return void */ void SCH_Go_To_Sleep(void); #endif //--------------------- End of File --------------------------------
C
#include "isotp.h" #include <stdio.h> #include <stdarg.h> #include <unistd.h> #include <string.h> #include "sys/time.h" #include <pthread.h> #include "comm_typedef.h" #define CLIENT_ADDRESS 0x766 #define SERVER_ADDRESS 0x706 static ERROR_CODE sender_test_send(struct phy_msg_t *msg); static ERROR_CODE sender_test_receive(struct phy_msg_t *msg); static ERROR_CODE receiver_test_send(struct phy_msg_t *msg); static ERROR_CODE receiver_test_receive(struct phy_msg_t *msg); static ERROR_CODE receiver_set_FS(struct isotp_t* msg); static void debug_out(const char *fmt, ...); static struct isotp_t sender, receiver; static pthread_mutex_t dbg_mutex; static void debug_out(const char *fmt, ...) { va_list vp; pthread_mutex_lock(&dbg_mutex); va_start(vp, fmt); vprintf(fmt, vp); va_end(vp); pthread_mutex_unlock(&dbg_mutex); } void *rx_thread(void *arg) { enum N_Result result; U32 dataLen = 0u; for(;;) { result = isotp_receive(&receiver, 10000u); if (result == N_OK) { debug_out("New data has been received, data len is %d, context:", receiver.DL); dataLen = 0; while (dataLen < receiver.DL) { debug_out("%02X ", receiver.Buffer[dataLen]); dataLen ++; } debug_out("\r\n"); } } return NULL; } static U32 port_platformTickUs(void) { U32 tickUs; struct timeval tv; gettimeofday(&tv,NULL); tickUs = tv.tv_sec * 1000000 + tv.tv_usec; return tickUs; } void main(void) { uint16_t index; pthread_t rc_task; ERROR_CODE retVal = STATUS_NORMAL; retVal = timer_init(port_platformTickUs, TIMER_COUNT_UP, 1u); /* * initialize sender parameters * sender: isotp_send object * CLIENT_ADDRESS: local address * SERVER_ADDRESS: remote address * NULL: don't need to set this parameter,because it is suitable for receiver. * sender_test_send: isotp_send function of the sender at physical layer * sender_test_receive: isotp_receive function of the sender at physical layer */ isotp_init(&sender, CLIENT_ADDRESS, SERVER_ADDRESS, NULL, sender_test_send, sender_test_receive); /* * initialize receiver parameters * receiver: receiver object * CLIENT_ADDRESS: remote address * SERVER_ADDRESS: local address * receiver_set_FS: Consecutive frame status control * receiver_test_send: isotp_send function of the receiver at physical layer * receiver_test_receive: isotp_receive function of the receiver at physical layer */ isotp_init(&receiver, SERVER_ADDRESS, CLIENT_ADDRESS, receiver_set_FS, receiver_test_send, receiver_test_receive); /* * set special parameters of flow control status * receiver: operate object * ISOTP_FS_CTS: Continue To Send * 1UL: (BS) * 10UL: STmin */ fc_set(&receiver, ISOTP_FS_CTS, 10UL, 100UL); /* create isotp_receive service */ pthread_create(&rc_task, /*(const pthread_attr_t *)*/NULL, rx_thread, NULL); /* Test 1,single frame */ sender.DL = 5UL; debug_out("Single Frame test,DL:%d\r\n", sender.DL); for(index = 0; index < sender.DL; index ++) { sender.Buffer[index] = (uint8_t)6UL; } isotp_send(&sender); sleep(1); /* Test 2,consecutive frame */ sender.DL = 256UL; pthread_mutex_init(&dbg_mutex, NULL); debug_out("Consecutive Frame test,DL:%d\r\n", sender.DL); for(index = 0; index < sender.DL; index ++) { sender.Buffer[index] = (uint8_t)index; } isotp_send(&sender); //pthread_cancel(rc_task); /* waitting for ending of the isotp_receive task */ //pthread_join(rc_task, /*(void **)*/NULL); debug_out("Done!\r\n"); sleep(1); } static ERROR_CODE sender_test_send(struct phy_msg_t *msg) { static uint32_t seq = 0UL; if(msg->new_data == TRUE) { msg->new_data = FALSE; seq ++; debug_out("Sder-Tx Seq:%04d Len:%02d Id:0x%04X Data:%02X %02X %02X %02X %02X %02X %02X %02X\r\n", seq, msg->length, msg->id, msg->data[0], msg->data[1], msg->data[2], msg->data[3], msg->data[4], msg->data[5], msg->data[6], msg->data[7]); memcpy(&receiver.isotp.phy_rx, msg, sizeof(*msg)); receiver.isotp.phy_rx.new_data = TRUE; } return STATUS_NORMAL; } static ERROR_CODE sender_test_receive(struct phy_msg_t *msg) { static uint32_t seq = 0UL; ERROR_CODE err = ERR_EMPTY; if(msg->new_data == TRUE) { msg->new_data = FALSE; err = STATUS_NORMAL; seq ++; debug_out("Sder-Rx Seq:%04d Len:%02d Id:0x%04X Data:%02X %02X %02X %02X %02X %02X %02X %02X\r\n", seq, msg->length, msg->id, msg->data[0], msg->data[1], msg->data[2], msg->data[3], msg->data[4], msg->data[5], msg->data[6], msg->data[7]); } return err; } static ERROR_CODE receiver_test_send(struct phy_msg_t *msg) { static uint32_t seq = 0UL; if(msg->new_data == TRUE) { msg->new_data = FALSE; seq ++; debug_out("Rcer-Tx Seq:%04d Len:%02d Id:0x%04X Data:%02X %02X %02X %02X %02X %02X %02X %02X\r\n", seq, msg->length, msg->id, msg->data[0], msg->data[1], msg->data[2], msg->data[3], msg->data[4], msg->data[5], msg->data[6], msg->data[7]); memcpy(&sender.isotp.phy_rx, msg, sizeof(*msg)); sender.isotp.phy_rx.new_data = TRUE; } return STATUS_NORMAL; } static ERROR_CODE receiver_test_receive(struct phy_msg_t *msg) { static uint32_t seq = 0UL; ERROR_CODE err = ERR_EMPTY; if(msg->new_data == TRUE) { msg->new_data = FALSE; err = STATUS_NORMAL; seq ++; debug_out("Rcer-Rx Seq:%04d Len:%02d Id:0x%04X Data:%02X %02X %02X %02X %02X %02X %02X %02X\r\n", seq, msg->length, msg->id, msg->data[0], msg->data[1], msg->data[2], msg->data[3], msg->data[4], msg->data[5], msg->data[6], msg->data[7]); } return err; } static ERROR_CODE receiver_set_FS(struct isotp_t* msg) { /* * set special parameters of flow control status * receiver: operate object * ISOTP_FS_CTS: Continue To Send * 1UL: (BS) * 10UL: STmin */ fc_set(&receiver, ISOTP_FS_CTS, 10UL, 100UL); debug_out("Rcer-FC-reply FS:%d BS:%d STmin:%d\r\n", msg->FS, msg->BS, msg->STmin); return STATUS_NORMAL; }
C
#include <stdio.h> char * strdup (strptr) char *strptr; { char *charptr; charptr = (char *) malloc (sizeof (char) * strlen (strptr) + 1); if (charptr == NULL) return (charptr); strcpy (charptr, strptr); return (charptr); }
C
#include <stdio.h> #include <stdlib.h> typedef struct{ char nombre[50]; int pos; } jugador; typedef struct{ char pregunta[400]; char op[4][1024]; int resp; } quizz; typedef struct { int num_op; int num_preg; int gameOver; //como bandera int turno; int itPreg; int categoria; int numJugadores; }tablero; int main(int argc, char const *argv[]){ FILE *fp; tablero maraton; quizz preguntas[300]; jugador players[4]; int dado; int respJugador; int i,j; maraton.num_op = 3; maraton.num_preg = 8; maraton.gameOver=0; maraton.turno=0; maraton.itPreg=0; printf("***************Bienvendo al maraton******************\n"); printf("Seleccione una categoria\n"); printf(" 1) Musica\n"); printf(" 2) Historia\n"); printf(" 3) matematicas\n"); printf("opcion: "); scanf("%d",&maraton.categoria); switch(maraton.categoria){ case 1: printf("Veamos que tan bueno eres en la musica \n"); fp = fopen("musica.txt", "r"); break; case 2:printf("Veamos que tan bueno eres en historia \n"); fp = fopen("historia.txt", "r"); break; case 3: printf("Veamos que tan bueno eres en el deporte\n"); fp = fopen("matematicas.txt", "r"); break; } if (fp == NULL){ perror("Error al abrir el archivo.\n"); exit(EXIT_FAILURE); } int ptr=0; while (!feof(fp)){ fscanf(fp,"%[^\n]s",preguntas[ptr].pregunta); //leer la pregunta fgetc(fp); for (i = 0; i < maraton.num_op; ++i){ fscanf(fp,"%[^\n]s",preguntas[ptr].op[i]); // le opcion 1,2,3 fgetc(fp); } fscanf(fp,"%d",&preguntas[ptr].resp); // resp correcta fgetc(fp); ptr++; } fclose(fp); printf("Ingresa el numero de jugadores (mx 4): "); scanf("%d",&maraton.numJugadores); printf("Ingrese el nombre los jugadores \n"); for (i = 0; i < maraton.numJugadores; ++i) { printf("\tJugador [%d]: ", i+1); scanf("%s", players[i].nombre); players[i].pos=0; } //El juego do{ printf("\n\t*****TURNO DE %s *********\n",players[maraton.turno].nombre); printf("\tLa posicion actual del jugador es: %d\n",players[maraton.turno].pos); printf("\tCuanto cay tu dado? "); scanf("%d",&dado); printf("\n\t%s\n",preguntas[maraton.itPreg].pregunta); for (i = 0; i < 4; ++i) printf("\t\t%s\n",preguntas[maraton.itPreg].op[i]); printf("\tSu respuesta: "); scanf("%d",&respJugador); //Si esta bien aumenta if (respJugador-1 == preguntas[maraton.itPreg].resp){ players[maraton.turno].pos += dado; printf("\t--->La nueva posicion de %s es: %d\n",players[maraton.turno].nombre,players[maraton.turno].pos); }else printf("El jugador no avanzo :(\n"); //Logica para ver cuando se gana if (players[maraton.turno].pos<50){ maraton.itPreg++; maraton.turno++; }else {maraton.gameOver=1;} if ( maraton.turno == maraton.numJugadores){maraton.turno=0;} }while(maraton.gameOver!=1); printf("El ganador es el jugador %s\n", players[maraton.turno].nombre); return 0; }
C
#include <stdio.h> int main(void){ int v, t; scanf("%d",&t); scanf("%d",&v); printf("%.3lf\n",(v*t/12.0)); return 0; }
C
#include <stdio.h> #include <rpc/rpc.h> /* always needed */ #include "msg.h" /* msg.h wil be generated by rpcgen */ int main(int argc, char *argv[]) { CLIENT *cl; int *result; char *server; char *message; if (argc != 3) { fprintf(stderr, "usage %s host message\n",argv[0]); } server = argv[1]; message = argv[2]; /* Creare client handle for calling MESSAGEPROG on the server * designated on the command line. We tell the RPC package * to use the tcp protocol when contacting the server. */ cl = clnt_create(server, MESSAGEPROG, MESSAGEVERS, "tcp"); if (cl == NULL) { /* * Couldn't establish connection with server. * Print error message and die. */ clnt_pcreateerror(server); exit(1); } /* * Call the remote procedure "printmessage" on the server. */ result = printmessage_1(&message, cl); if (result == NULL) { /* * An error occurred while calling the server. * Print error message and die */ clnt_perror(cl, server); exit(1); } /* * Okay, we successfully called the remote procedure */ if (*result == 0) { /* * Server was unable to print our message. * Print error message and die. */ fprintf(stderr, "%s: %s couldn't print your message\n", argv[0], server); exit(1); } /* * Message got printed at server */ printf("Message delivered to %s!\n", server); exit(0); }
C
#include "compare.h" int search(Element x, Element A[], int N) { int i; for(i=0;i<N;i++) { if(A[i]==x) return i; if(compare(A[i],x)) return -1; } return -1; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_checku.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: syusof <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/03/22 00:43:58 by syusof #+# #+# */ /* Updated: 2016/05/05 14:43:35 by syusof ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" int ft_checku(t_numb *e) { int cnt; int i; cnt = 0; i = ft_count2(e->u); if (e->u == 0) e->valzero = 1; if (e->indminus == 1) cnt = cnt + ft_checku1(e); else if (e->indminus == 0) { if (e->valzero == 1) { cnt = cnt + ft_putunbr(e->u, e); } else { cnt = cnt + ft_countu(e, e->u); cnt = cnt + ft_putunbr(e->u, e); } } ft_initialize(e); return (cnt); } int ft_checku1(t_numb *e) { int cnt; int i; cnt = 0; i = ft_count2(e->u); if (e->indpr == 1) cnt = cnt + ft_checku1a(e); cnt = cnt + ft_putunbr(e->u, e); cnt = cnt + ft_checku1b(e); return (cnt); } int ft_checku1a(t_numb *e) { int cnt; int i; int j; cnt = 0; i = ft_count2(e->u); j = 0; if (i > e->pr) cnt = cnt + ft_checku1a1(e); else if (i <= e->pr) { while (j < e->pr - i) { ft_putchar('0'); cnt++; j++; } } return (cnt); } int ft_checku1a1(t_numb *e) { int cnt; int i; int j; cnt = 0; i = ft_count2(e->u); j = 0; return (cnt); } int ft_checku1b(t_numb *e) { int cnt; int i; int j; cnt = 0; i = ft_count2(e->u); if (i > e->pr) cnt = cnt + ft_checku1b1(e); else if (i <= e->pr) { j = 0; while (j < e->w - e->pr) { ft_putchar(' '); j++; cnt++; } } return (cnt); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <time.h> #include <sys/wait.h> int main(){ printf("START FORKING!\n"); pid_t childA, childB; srand(time(NULL)); printf("parent pid: %d\n", getppid()); childA = fork(); if (childA) childB = fork(); if (childA == 0 || childB == 0) { printf("child pid : %d\n", getpid()); int num = sleep(rand() % 15 + 5); } int status, child; child = wait(&status); printf("parent %d knows child %d slept for %d seconds\n", getppid(), child, WEXITSTATUS(status)); return 0; }
C
#include <stdio.h> #include <string.h> #include <malloc.h> #define APN_STR "Init%d = AT+CGDCONT=1,\"IP\",\"ANETAPN\"\n" int main(int argc, char **argv) { FILE *fp; char *buff = NULL; fp = fopen("m.conf", "r"); if ( fp ) { char *line = NULL; int line_num = 0; int i = 0; int c; char apn_set = 0; while ( (c = fgetc(fp)) > 0 ) { line = (char *)realloc((char *)line, i+1); if ( c == '\n' ) { *(line + i) = 0; i = 0; line_num++; if ( line_num != 1 && !strstr(line, "Init") && !apn_set) { printf(APN_STR, line_num); apn_set = 1; } if ( !strstr(line, "ANETAPN") ) printf("%s\n",line); free(line); line = NULL; } else { *(line + i++) = c; } } fclose(fp); } return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include "disk.h" #include "get.h" /************************************************************************** ADDNOISE.C - PROGRAM TO ADD NOISE TO EXISTING DSP DATA OR CREATE NOISE ONLY. ADDS NOISE TO FIRST RECORD OF INPUT FILE AND GENERATES A ONE RECORD OUTPUT FILE. INPUTS: LENGTH, TYPE AND AMPLITUDE OF NOISE, FILE NAME. OUTPUTS: DSP DATA FILE *************************************************************************/ main() { DSP_FILE *dsp_in,*dsp_out; /* input and output files */ int i,type,length; double nmult; /* noise multiplier */ float *signal; /* pointer to record */ char *file,*trail; static char trailer[300]; double gaussian(),uniform(); file = get_string("input file name (CR for none)"); /* check for file name: either generate or read a record */ if(strlen(file) == 0) { length = get_int("number of samples to generate",2,32767); signal = (float *)calloc(length,sizeof(float)); if(!signal) { printf("\nUnable to allocate noise array\n"); exit(1); } } else { dsp_in = open_read(file); if(!dsp_in) exit(1); /* bad filename */ length = dsp_in->rec_len; trail = read_trailer(dsp_in); if(trail && *trail) printf("\nFile trailer:\n%s\n",trail); signal = read_float_record(dsp_in); /* read first record */ } /* get type of noise and noise amplitude */ type = get_int("noise type (0 = uniform, 1 = Gaussian)",0,1); nmult = get_float("noise multiplier",0.0,1000.0); /* add noise to record */ if(type == 0) for(i = 0 ; i < length ; i++) signal[i] += nmult*uniform(); else for(i = 0 ; i < length ; i++) signal[i] += nmult*gaussian(); dsp_out = open_write(get_string("output file name"),FLOAT,1,length); if(!dsp_out) exit(1); /* write out the noisy data */ write_record((char *)signal,dsp_out); /* make descriptive trailer and write to file */ sprintf(trailer, "\nNoise signal of length %d, %s distribution, Amplitude = %f\n", length,type ? "Gaussian" : "Uniform",nmult); puts(trailer); /* send to display */ if(strlen(file) == 0) { write_trailer(trailer,dsp_out); /* send to file */ } else { /* add on to old trailer and write */ write_trailer(append_trailer(trailer,dsp_in),dsp_out); } } 
C
#include <stdio.h> #include <string.h> /* 12503 - Robot Instructions Sample Input 2 3 LEFT RIGHT SAME AS 2 5 LEFT SAME AS 1 SAME AS 2 SAME AS 1 SAME AS 4 Sample Output 1 -5 */ int main() { int test_cases, i, n, number, instructions[101], robot; char instruction[10]; scanf("%d", &test_cases); while (test_cases--) { scanf("%d", &n); robot = 0; for (i = 1; i <= n; i++) { scanf("%s", instruction); if (strcmp(instruction, "LEFT") == 0) { instructions[i] = -1; robot += -1; } else if (strcmp(instruction, "RIGHT") == 0) { instructions[i] = 1; robot += 1; } else { scanf("%s %d", instruction, &number); robot += instructions[number]; instructions[i] = instructions[number]; } } printf("%d\n", robot); } return 0; }
C
// Вывести количество различных битовых последовательностей заданной длины (не более 32), не содержащих двух единиц подряд. #include <stdio.h> int maxPow(int len) { int base2 = 1; for ( int i = 1; i < len; base2 *= 2, i++ ); return base2; } int bitSequences(int maxValue, int len, int count) { int flag = 1; int maxPower = maxPow(len); int arr[len]; int base = 2; int num = maxValue; if ( maxValue < 0 ) { return count; } for ( int i = 0; maxPower > 0; maxPower /= base, i++ ) { int result = num / maxPower; if ( result != 0 ) { num %= maxPower; } arr[i] = result; printf("%d ",result ); } printf("\n"); for ( int i = 1; i < len; i++ ) { if ( arr[i] == 1 && arr[i-1] == 1 ) { flag = 0; } } if ( flag ) { count += 1; } return bitSequences(maxValue-1, len, count); } int main() { int len; int count = 0; int maxValue; scanf("%d", &len); maxValue = maxPow(len) * 2 - 1; printf("%d\n", bitSequences(maxValue, len, count)); return 0; }
C
#include<stdio.h> #include<string.h> int main() { char s[1000]; int i,a=0,b=0,c=0; gets(s); for (i=0;i<strlen(s);i++) { if ((s[i]<='z' && s[i]>='a')||(s[i]<='Z' && s[i]>='A')) a++; else if (s[i] >= '0' && s[i] <= '9') b++; else c++; } printf("%d %d %d",a,b,c); }
C
#include <stdio.h> void printlist(int v[]); void swap(int v[], int i, int j); void qsort(int v[], int left, int right); int main(void){ int list[]= {5,7,3,6,2,8,1,0,9,4}; printlist(list); qsort(list, 0, 9); printlist(list); } void qsort(int v[], int left, int right) { if (left >= right) return; swap(v, (left + right)/2, left); int last = left; for (int i = left + 1; i <= right; i++) if (v[i] < v[left]) swap(v, ++last, i); swap(v, left, last); printf("complete partition\n"); qsort(v, left, last - 1); qsort(v, last + 1, right); } void swap(int v[], int i, int j){ int temp = v[i]; v[i] = v[j]; v[j] = temp; } void printlist(int v[]){ printf(" 0 1 2 3 4 5 6 7 8 9\n"); for (int i = 0; i < 10; i++) printf("%2d ", v[i]); printf("\n\n"); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define SHL(x,n) (x<<n) #define SHR(x,n) (x>>n) #define ROTL(x,n) ((x<<n)|(x>>(32-n))) #define ROTR(x,n) ((x>>n)|(x<<(32-n))) #define P1(a,b,c,d,e) (P2((a)^(b)^ROTL((c),15))^ROTL((d),7)^e) #define P2(a) ((a)^ROTL((a),15)^ROTL((a),23)) #define P3(a,b) ((a)^(b)) #define P4(a) ((a)^ROTL((a),9)^ROTL((a),17)) #define T1 (0x79cc4519) #define T2 (0x7a879d8a) #define FF1(a,b,c) ((a)^(b)^(c)) #define FF2(a,b,c) (((a)&(b))|((a)&(c))|((b)&(c))) #define GG1(a,b,c) ((a)^(b)^(c)) #define GG2(a,b,c) (((a)&(b))|((~a)&(c))) #define SS1(a,b,c,d) (ROTL((ROTL((a),12)+b+ROTL((c),(d))),7)) #define SS2(a,b,c,d) (SS1((a),(b),(c),(d))^ROTL((a),12)) #define TT1(e,f,g,a,b,c,d) ((e)+(f)+SS2(a,b,c,d)+(g)) #define TT2(e,f,g,a,b,c,d) ((e)+(f)+SS1(a,b,c,d)+(g)) unsigned long H[8]={0x7380166f,0x4914b2b9,0x172442d7,0xda8a0600,0xa96f30bc,0x163138aa,0xe38dee4d,0xb0fb0e4e}; void print_str(unsigned char*str,int len){ int i=0; for(i=0;i<len;i++) printf("%02X",str[i]); } void sm3_long_to_str(unsigned long a,unsigned char*b){ unsigned long x=a; unsigned char *d=(unsigned char*)&x; b[0]=d[3]; b[1]=d[2]; b[2]=d[1]; b[3]=d[0]; } unsigned long sm3_str_to_long(unsigned char*a){ unsigned long x=0; unsigned char *b=(unsigned char*)&x; b[0]=a[3]; b[1]=a[2]; b[2]=a[1]; b[3]=a[0]; return x; } int sm3_pad_message(unsigned char*str, int len){ unsigned long high,low; int u=len%64; high=0; low=len*8; if(u<56){ str[len++]=0x80; u++; while(u<56){ str[len++]=0x00; u++; } } else if(u>56){ str[len++]=0x80; u++; while(u<56+64){ str[len++]=0x00; u++; } } //printf("len=[%08x]\n",low); str[len++]=high>>24; str[len++]=high>>16; str[len++]=high>>8; str[len++]=high; str[len++]=low>>24; str[len++]=low>>16; str[len++]=low>>8; str[len++]=low; return len; } void sm3_group_a(unsigned char*a,unsigned char*b,unsigned char*c,unsigned char*d,unsigned char*e,unsigned char*f){ unsigned long x[6]={0}; x[0]=sm3_str_to_long(a); x[1]=sm3_str_to_long(b); x[2]=sm3_str_to_long(c); x[3]=sm3_str_to_long(d); x[4]=sm3_str_to_long(e); x[5]=P1(x[0],x[1],x[2],x[3],x[4]); sm3_long_to_str(x[5],f); } void sm3_group_b(unsigned char*a, unsigned char*b, unsigned char*c){ unsigned long x[3]={0}; x[0]=sm3_str_to_long(a); x[1]=sm3_str_to_long(b); x[2]=P3(x[0],x[1]); sm3_long_to_str(x[2],c); } int sm3_str_group(unsigned char*str, int len) { unsigned char M[64]; unsigned char W[68][4]; int u=len/64; int v=64/16*64*2; int i=0; int j=0; for(i=u-1;i>=0;i--){ memset(M,0x00,sizeof(M)); memcpy(M,str+i*64,64); for(j=0;j<16;j++) memcpy(W[j],M+4*j,4); for(j=16;j<68;j++) sm3_group_a(W[j-16],W[j-9],W[j-3],W[j-13],W[j-6],W[j]); memset(M,0x00,sizeof(M)); for(j=0;j<64;j++){ sm3_group_b(W[j],W[j+4],M); memcpy(str+i*v+8*j,W[j],4); memcpy(str+i*v+8*j+4,M,4); } } return u*v; } void sm3_str_summ(unsigned char*str,unsigned char*summ,int len){ unsigned char W[128][4]; unsigned long A[8]={0}; unsigned long B[8]={0}; unsigned long C[8]={0}; int u=len/512; int i=0; int j=0; memcpy(B,H,sizeof(B)); for(i=0;i<u;i++){ for(j=0;j<128;j++) memcpy(W[j],str+i*512+j*4,4); A[0]=B[0]; A[1]=B[1]; A[2]=B[2]; A[3]=B[3]; A[4]=B[4]; A[5]=B[5]; A[6]=B[6]; A[7]=B[7]; for(j=0;j<16;j++){ C[0]=sm3_str_to_long(W[2*j+1]); C[1]=sm3_str_to_long(W[2*j]); C[2]=TT1(FF1(A[0],A[1],A[2]),A[3],C[0],A[0],A[4],T1,j); C[3]=TT2(GG1(A[4],A[5],A[6]),A[7],C[1],A[0],A[4],T1,j); A[7]=A[6]; A[6]=ROTL(A[5],19); A[5]=A[4]; A[4]=P4(C[3]); A[3]=A[2]; A[2]=ROTL(A[1],9); A[1]=A[0]; A[0]=C[2]; } for(j=16;j<64;j++){ C[0]=sm3_str_to_long(W[2*j+1]); C[1]=sm3_str_to_long(W[2*j]); C[2]=TT1(FF2(A[0],A[1],A[2]),A[3],C[0],A[0],A[4],T2,j); C[3]=TT2(GG2(A[4],A[5],A[6]),A[7],C[1],A[0],A[4],T2,j); A[7]=A[6]; A[6]=ROTL(A[5],19); A[5]=A[4]; A[4]=P4(C[3]); A[3]=A[2]; A[2]=ROTL(A[1],9); A[1]=A[0]; A[0]=C[2]; //printf("A[0]=[%08X]\n", A[0]); } B[0]^=A[0]; B[1]^=A[1]; B[2]^=A[2]; B[3]^=A[3]; B[4]^=A[4]; B[5]^=A[5]; B[6]^=A[6]; B[7]^=A[7]; } sm3_long_to_str(B[0],summ); sm3_long_to_str(B[1],summ+4); sm3_long_to_str(B[2],summ+8); sm3_long_to_str(B[3],summ+12); sm3_long_to_str(B[4],summ+16); sm3_long_to_str(B[5],summ+20); sm3_long_to_str(B[6],summ+24); sm3_long_to_str(B[7],summ+28); } int main() { unsigned char str[64*8*8]={0}; int i=0; int len=0; printf("请输入消息长度(字节长度):"); scanf("%d",&len); unsigned char str_sm3[32]; printf("请输入消息(十六进制):"); for(i=0;i<len;i++) scanf("%2x",&str[i]); len=sm3_pad_message(str,len); // print_str(str,len); len = sm3_str_group(str,len); // print_str(str, len); sm3_str_summ(str, str_sm3, len); // print_str(str, len); printf("哈希值为:"); print_str(str_sm3, 32); return 0; }
C
#include "holberton.h" /** * reverse_array - reverses the content of an array of integers * * @a: A pointer to first integer in array. * @n: An integer for number of elements in array. * * Return: void */ void reverse_array(int *a, int n) { int i; int temp; int len; temp = 0; len = (n - 1) / 2; n -= 1; for (i = 0; i < len; i++) { temp = a[i]; a[i] = a[n]; a[n] = temp; n--; } }
C
/*Input: Q = {WRITE A, WRITE B, WRITE C, UNDO, READ, REDO, READ} Output: AB ABC Explanation: Perform WRITE A on the document. Therefore, the document contains only A. Perform WRITE B on the document. Therefore, the document contains AB. Perform WRITE C on the document. Therefore, the document contains ABC. Perform UNDO on the document. Therefore, the document contains AB. Print the contents of the document, i.e. AB Perform REDO on the document. Therefore, the document contains ABC. Print the contents of the document, i.e. ABC Input: Q = {WRITE x, WRITE y, UNDO, WRITE z, READ, REDO, READ} Output:xz xzy Initialize two stacks, say Undo and Redo. Traverse the array of strings, Q, and perform the following operations: If WRITE string is encountered, push the character to Undo stack If UNDO string is encountered, pop the top element from Undo stack and push it to Redo stack. If REDO string is encountered, pop the top element of Redo stack and push it into the Undo stack. If READ string is encountered, print all the elements of the Undo stack in reverse order.*/ // C++ Program to implement // the above approach #include <bits/stdc++.h> using namespace std; // Function to perform // "WRITE X" operation void WRITE(stack<char>& Undo, char X) { // Push an element to // the top of stack Undo.push(X); } // Function to perform // "UNDO" operation void UNDO(stack<char>& Undo, stack<char>& Redo) { // Stores top element // of the stack char X = Undo.top(); // Erase top element // of the stack Undo.pop(); // Push an element to // the top of stack Redo.push(X); } // Function to perform // "REDO" operation void REDO(stack<char>& Undo, stack<char>& Redo) { // Stores the top element // of the stack char X = Redo.top(); // Erase the top element // of the stack Redo.pop(); // Push an element to // the top of the stack Undo.push(X); } // Function to perform // "READ" operation void READ(stack<char> Undo) { // Store elements of stack // in reverse order stack<char> revOrder; // Traverse Undo stack while (!Undo.empty()) { // Push an element to // the top of stack revOrder.push(Undo.top()); // Erase top element // of stack Undo.pop(); } while (!revOrder.empty()) { // Print the top element // of the stack cout << revOrder.top(); Undo.push(revOrder.top()); // Erase the top element // of the stack revOrder.pop(); } cout << " "; } // Function to perform the // queries on the document void QUERY(vector<string> Q) { // Stores the history of all // the queries that have been // processed on the document stack<char> Undo; // Stores the elements // of REDO query stack<char> Redo; // Stores total count // of queries int N = Q.size(); // Traverse all the query for (int i = 0; i < N; i++) { if (Q[i] == "UNDO") { UNDO(Undo, Redo); } else if (Q[i] == "REDO") { REDO(Undo, Redo); } else if (Q[i] == "READ") { READ(Undo); } else { WRITE(Undo, Q[i][6]); } } } // Driver Code int main() { vector<string> Q = { "WRITE A", "WRITE B", "WRITE C", "UNDO", "READ", "REDO", "READ" }; QUERY(Q); return 0; }
C
/* exception.c: handle processor exceptions and suprisingly NMIs too */ /* basically started as a hacked around version of irq.c */ /* then I deleted most of that code and instead used irq.c as a model */ #include <kernel/kernel.h> #include <asm/init.h> #include <asm/system.h> #include <asm/lock.h> #include <kernel/task.h> #define __STR(x) #x #define STR(x) __STR(x) asmlinkage void common_exception(long exception); asmlinkage void common_exception_ec(long exception, long errorcode); #define EXCEPTION(nr) do_exception##nr #define BUILD_EXCEPTION(nr) \ asmlinkage void EXCEPTION(nr)(void); \ __asm__(__ALIGN_STR "\n" \ SYMBOL_NAME_STR(do_exception##nr) ":\n\t" \ "movl $" STR(KERNEL_DATA) ", %eax\n\t" \ "movl %eax, %ds\n\t" \ "pushl $" #nr "\n\t" \ "pushl $0\n\t" /* a dummy return address */ \ "jmp common_exception"); #define BUILD_EXCEPTION_EC(nr) \ asmlinkage void EXCEPTION(nr)(void); \ __asm__(__ALIGN_STR "\n" \ SYMBOL_NAME_STR(do_exception##nr) ":\n\t" \ "movl $" STR(KERNEL_DATA) ", %eax\n\t" \ "movl %eax, %ds\n\t" \ "pushl $" #nr "\n\t" \ "pushl $0\n\t" /* a dummy return address */ \ "jmp common_exception_ec"); BUILD_EXCEPTION(0) BUILD_EXCEPTION(1) BUILD_EXCEPTION(2) BUILD_EXCEPTION(3) BUILD_EXCEPTION(4) BUILD_EXCEPTION(5) BUILD_EXCEPTION(6) BUILD_EXCEPTION(7) BUILD_EXCEPTION_EC(8) BUILD_EXCEPTION(9) BUILD_EXCEPTION_EC(10) BUILD_EXCEPTION_EC(11) BUILD_EXCEPTION_EC(12) BUILD_EXCEPTION_EC(13) BUILD_EXCEPTION_EC(14) BUILD_EXCEPTION(15) BUILD_EXCEPTION(16) BUILD_EXCEPTION_EC(17) BUILD_EXCEPTION(18) BUILD_EXCEPTION(19) BUILD_EXCEPTION(20) BUILD_EXCEPTION(21) BUILD_EXCEPTION(22) BUILD_EXCEPTION(23) BUILD_EXCEPTION(24) BUILD_EXCEPTION(25) BUILD_EXCEPTION(26) BUILD_EXCEPTION(27) BUILD_EXCEPTION(28) BUILD_EXCEPTION(29) BUILD_EXCEPTION(30) BUILD_EXCEPTION(31) const char *exception_names[32] = { "de", "db", "NMI", "bp", "of", "br", "ud", "nm", "df", "reserved", "ts", "np", "ss", "gp", "pf", "reserved", "mf", "ac", "mc", "xf", "reserved", "reserved", "reserved", "reserved", "reserved", "reserved", "reserved", "reserved", "reserved", "reserved", "reserved", "reserved" }; void *exception_funcs[32] = { EXCEPTION(0), EXCEPTION(1), EXCEPTION(2), EXCEPTION(3), EXCEPTION(4), EXCEPTION(5), EXCEPTION(6), EXCEPTION(7), EXCEPTION(8), EXCEPTION(9), EXCEPTION(10), EXCEPTION(11), EXCEPTION(12), EXCEPTION(13), EXCEPTION(14), EXCEPTION(15), EXCEPTION(16), EXCEPTION(17), EXCEPTION(18), EXCEPTION(19), EXCEPTION(20), EXCEPTION(21), EXCEPTION(22), EXCEPTION(23), EXCEPTION(24), EXCEPTION(25), EXCEPTION(26), EXCEPTION(27), EXCEPTION(28), EXCEPTION(29), EXCEPTION(30), EXCEPTION(31) }; asmlinkage void common_exception(long exception) { lock_kernel(); printk(KERN_EMERG "exception: #%s", exception_names[exception]); panic("A processor exception occured"); } asmlinkage void common_exception_ec(long exception, long errorcode) { lock_kernel(); printk("exception: #%s error code %08lx, %s%ssegment %04lx\n", exception_names[exception], errorcode, (errorcode & 0x1) ? "external, " : "", (errorcode & 0x2) ? "LDT, " : ((errorcode & 0x4) ? "LDT, " : "GDT, "), errorcode >> 3); panic("A processor exception occured"); } __initfunc(void setup_exceptions(void)) { int i; for (i = 0; i < 32; i++) { set_intr_gate(i, exception_funcs[i]); } }
C
// Shellcode.c // Opens a shell as effective UID of 0 #include <unistd.h> void main(void) { char *name[2]; name[0] = "/bin/sh"; name[1] = NULL; execve(name[0], name, NULL); }
C
#include<stdio.h> #include<math.h> #define MAX 100 #include"headerofsquare.h" void nhap(int a[],int n){ for(int i=0;i<n;i++){ printf("Nhap phan tu thu a[%d]",i+1); scanf("%d",&a[i]); } } void xuat(int a[],int n){ for (int i=0;i<n;i++){ printf("mang la %d \n",a[i]); } } int main(){ int a[MAX] , n; printf("Nhap n"); scanf("%d",&n); printf("nhap mang"); nhap(a,n); printf("xuat mang"); xuat(a,n); int *display=display_square(a,n); printf("so chinh phuong trong mang la %d",*display); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <assert.h> #if defined(_MSC_VER) #include "xxhash.h" //random string #include <windows.h> //sleep #include <intrin.h> //rdtsc #pragma intrinsic(__rdtsc) #else #include <linux/types.h> //rdtsc #include <unistd.h> //sleep #endif // defined(_MSC_VER) #include "hashtable.h" // #define SAMPLE_SIZE 1000000 //ÿkey #define KEY_LEN 16 //ÿvalue #define VALUE_LEN 16 static char key[SAMPLE_SIZE][KEY_LEN], value[SAMPLE_SIZE][VALUE_LEN]; static const char ZEROS[VALUE_LEN] = { 0 }; //򿪻ͳÿεʱ䣨ؾԣ10%20ʧ #ifndef DEBUG //#define DEBUG #endif // !DEBUG #ifdef DEBUG #define BEGIN tlast = rdtsc() #define END if ((tlast = rdtsc() - tlast) > max_time) max_time = tlast #else #define BEGIN #define END #endif #if !defined (__VMS) \ && (defined (__cplusplus) \ || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) # include <stdint.h> typedef uint32_t U32; typedef uint64_t U64; #else typedef unsigned int U32; typedef unsigned long long U64; #endif #if defined(__x86_64__) || defined(_WIN64) #define XXHASH(a, b, c) XXH64(a, b, c) #define XXH_hash_t XXH64_hash_t #else #define XXHASH(a, b, c) XXH32(a, b, c) #define XXH_hash_t XXH32_hash_t #endif #define UNUSED(x) (void)((x)+1) /*ȡʱڣclock()һ*/ #if defined(_MSC_VER) #define rdtsc() __rdtsc() #define sleep(t) Sleep(t*1000) #else __u64 rdtsc() { __u32 lo, hi; __asm__ __volatile__ ( "rdtsc":"=a"(lo), "=d"(hi) ); return (__u64)hi << 32 | lo; } #endif // defined(_MSC_VER) static double DOMINANT_FREQUENCY; //ȡƵһʵ1% U64 get_dominant_frequency() { U64 t1 = rdtsc(); sleep(1); return rdtsc() - t1; } void data_gen() { int i = 0; #if defined(_WIN32) || defined(_WIN32_WCE) #define HASH_LEN sizeof(U32) //xxhashַ XXH_hash_t h, j, k = 0, lens[2] = { KEY_LEN, VALUE_LEN }; for (; k < 2; ++k) { for (; i < SAMPLE_SIZE; ++i) { j = lens[k]; while (j > HASH_LEN) { h = XXHASH(&j, HASH_LEN, rdtsc()); memcpy(&key[i][lens[k] - j], &h, HASH_LEN); j -= HASH_LEN; } h = XXHASH(&j, HASH_LEN, rdtsc()); memcpy(&key[i][lens[k] - j], &h, j); } } #else FILE* f = fopen("/dev/urandom", "r"); while (i != SAMPLE_SIZE) { if (!fgets(key[i], KEY_LEN, f) || !fgets(value[i], VALUE_LEN, f)) continue; i++; } fclose(f); #endif // defined(_WIN32) || defined(_WIN32_WCE) } void test_set(ht_t* table) { U64 max_time = 0, tlast = 0, t0 = rdtsc(); for (U32 i = 0; i < SAMPLE_SIZE; i++) { BEGIN; if (0 != htsetnx(table, key[i], KEY_LEN, value[i], VALUE_LEN)) memset(value[i], 0, VALUE_LEN); // ظvalueȫ0 END; } double t = (double)(rdtsc() - t0) / DOMINANT_FREQUENCY; printf("add %d keys in %fs, %fus on average, and the ht_max simple time is %fus.\n", SAMPLE_SIZE, t, t * 1000000 / SAMPLE_SIZE, (double)max_time * 1000000 / DOMINANT_FREQUENCY); UNUSED(tlast); } void test_lookup(ht_t* table) { U64 max_time = 0, tlast = 0, t0 = rdtsc(); char *res; for (U32 i = 0; i < SAMPLE_SIZE; i++) { BEGIN; res = (char*)htget(table, key[i], KEY_LEN); END; assert(res && (!memcmp(res, value[i], VALUE_LEN) || !memcmp(value[i], ZEROS, VALUE_LEN))); //valueȫΪ0Dzkeyظı } double t = (double)(rdtsc() - t0) / DOMINANT_FREQUENCY; printf("lookup %d times in %fs, %fus on average, and the ht_max simple time is %fus.\n", SAMPLE_SIZE, t, t * 1000000 / SAMPLE_SIZE, (double)max_time * 1000000 / DOMINANT_FREQUENCY); UNUSED(res); UNUSED(tlast); } void test_remove(ht_t* table) { U64 t0 = rdtsc(); ht_elem_t* elems = htgetall(table, REF_MODE); printf("get all of elements in %fs\n", (double)(rdtsc() - t0) / DOMINANT_FREQUENCY); /*ȫԪ¹ϣ*/ t0 = rdtsc(); htrh(table, (U32)t0); printf("rehashing in %fs\n", (double)(rdtsc() - t0) / DOMINANT_FREQUENCY); /*ɾ*/ U64 max_time = 0, tlast = 0;; t0 = rdtsc(); ht_elem_t* p = elems; int ret = 0; while(p) { BEGIN; ret = htrm(table, p->key, KEY_LEN); END; assert(ret == 0 && !htget(table, p->key, KEY_LEN)); p = p->next; } double t = (double)(rdtsc() - t0) / DOMINANT_FREQUENCY; printf("remove all elements in %fs, %fus on average, and the ht_max simple time is %fus.\n" ,t, t * 1000000 / SAMPLE_SIZE, (double)max_time * 1000000 / DOMINANT_FREQUENCY); //ȫɾʱӦΪձ assert(htgetall(table, REF_MODE) == NULL); //ͷԪػȡ htrmall(elems, REF_MODE); UNUSED(ret); UNUSED(tlast); } void test_performance() { DOMINANT_FREQUENCY = (double)get_dominant_frequency(); //ȡ data_gen(); /**/ ht_t* table = htnew(); /**/ test_set(table); /*ѯ*/ test_lookup(table); /*ɾ*/ test_remove(table); int mode = table->mode; /*ͷ*/ htdel(table); static const char* modes[2] = { "REF_MODE", "COPY_MODE" }; printf("%s performance test end.\n", modes[mode]); UNUSED(ZEROS); } int main() { printf("all test start\n"); //ӡѯɢСɾͻȡԪܲ test_performance(); printf("all test end\n"); }
C
// // Created by vitor on 3/28/21. // #include "bridge.h" int bridgeLinked(GrafoLinked grafo) { printf("\nEntre com 1º vertice que deseja: "); int v_one = get_int(); if (v_one <= 0 || v_one > grafo.numVertices) { printf("\n\tNumero de vertice invalido!\n\n"); return 0; } printf("Entre com 2º vertice que deseja: "); int v_two = get_int(); if (v_two <= 0 || v_two > grafo.numVertices) { printf("\n\tNumero de vertice invalido!\n\n"); return 0; } if (!isNodeOfList(&grafo.list[v_one - 1], v_two)) { printf("Os vertices (%d)-(%d) não formam uma aresta\n", v_one, v_two); return 0; } int pre_conexo = ECCLinked(grafo, 0); LinkedList ori[2] = {grafo.list[v_one - 1], grafo.list[v_two - 1]}; grafo.list[v_one - 1] = copyLinkedList(&grafo.list[v_one - 1]); grafo.list[v_two - 1] = copyLinkedList(&grafo.list[v_two - 1]); deleteAresta(&grafo.list[v_one - 1], v_two); deleteAresta(&grafo.list[v_two - 1], v_one); int after_conexo = ECCLinked(grafo, 0); grafo.list[v_one - 1] = ori[0]; grafo.list[v_two - 1] = ori[1]; if (pre_conexo != after_conexo) { printf("A aresta (%d)-(%d) é uma ponte\n", v_one, v_two); } else { printf("A aresta (%d)-(%d) não é uma ponte\n", v_one, v_two); } }
C
/*Write a function setbits that returns x with the n bits at position p set to the rightmost bits of y leaving the other bits unchanged*/ #include <stdio.h> #include <math.h> unsigned getbits(unsigned x, int p, int n); unsigned setbits(unsigned x, int p, int n, unsigned y); void main(char args[]){ //x = 1001101 (77) y = 1000111 (71) //P = 5 N = 4 //1[0011]01 in x //100[0111] in y //Want -> 1011101 (93) printf("%u\n", setbits(77, 5, 4, 71)); //x = 10110 (22) y = 11111 (32) //P = 3 N = 1 //1[0]110 in x //1111[1] in y //Want -> 11110 (30) printf("%u\n", setbits(22, 3, 1, 31)); //x = 11 (3) y = 111100 (60) //P = 1 N = 2 //[11] in x //1111[00] in y //Want -> 00 (0) printf("%u\n", setbits(3,1,2,60)); //x = 1110 (14) y = 1101 (13) //P = 2 N = 2 //1[11]0 in x //11[01] in y //Want -> 1010 (10) printf("%u\n", setbits(14,2,2,13)); } //Returns n bits from position p unsigned getbits(unsigned x, int p, int n){ return(x >> (p + 1 - n)) & ~(~0 << n); //E.g. x = 13 (1101) P = 2 N = 1 //Want this bit -> 1[1]01 //x >> (p + 1 - n) shifts wanted bits to right end of X // x >> 2 = 0011 //~0 = ...1111 //~0 << n clears space to create a mask //~0 << 1 = 1110 //~(1110) = 0001 //Use & to apply the mask 0011 (x) & 0001 (mask) = 0001 (returned bit) } unsigned setbits(unsigned x, int p, int n, unsigned y){ //(p-n)+1) + 1 //Create mask with right n bits as 1 unsigned mask = ~(~0 << n); //Take print of y and retrieve rightmost n bits (same as using getbits method) mask = mask & y; //Push mask bits to align with p in x mask = mask << ((p - n) + 1); //Create masks of trailing 1's before and after the bits being changed //111111[0000]00 //000000[0000]11 unsigned trailing = ~0 & (~0 << (p + 1)); unsigned leading = ~trailing >> n; //Set any 0's to 1's using OR with initial mask 00000[0101]00000 //Giving us partial result E.g. 101111[0111]01001 unsigned result = x | mask; //Update the mask for AND by combining with trailing leading // 000000[0101]00 //OR 111111[0000]00 //OR 000000[0000]11 // 111111[0101]11 mask = mask | trailing; mask = mask | leading; //Update result with new mask to cancel any 1's set by OR leaving rest of bits // 101111[0111]01 //AND 111111[0101]11 // 101111[0101]01 result = result & mask; return result; }
C
#include "cache.h" #include "simerr.h" #include <stdlib.h> cache_t sim_icache; cache_t sim_dcache; int missTime=100; void init_cache(cache_t *cache, int s, int l, int b) { int i; cache->nSetBits = 0; for (i=1; i<s; i<<=1) { cache->nSetBits++; } cache->nLines = l; cache->nBits = b; cache->cache_block = (Cache_Block**)malloc(sizeof(Cache_Block*)*s); for (i=0; i<s; i++) { cache->cache_block[i] = (Cache_Block*)calloc(sizeof(Cache_Block), l); } cache->nHit = cache->nMiss = cache->nVisits = 0; } void cache_access(cache_t *cache, uint32_t addr) { int i, idx; int set = (addr>>cache->nBits)&((1<<cache->nSetBits)-1); unsigned long tag = addr>>(cache->nBits+cache->nSetBits); cache->nVisits++; for (i=0; i<cache->nLines; i++) { Cache_Block *b = &cache->cache_block[set][i]; if (b->valid && b->tag==tag) { if (cache==&sim_dcache) { trace_msg("%x HIT\n", addr); } cache->nHit++; b->lastVisit = cache->nVisits; return; } } // cache miss if (cache==&sim_dcache) { trace_msg("%x MISS\n", addr); } cache->nMiss++; for (i=0; i<cache->nLines; i++) { Cache_Block *b = &cache->cache_block[set][i]; if (!b->valid) { // have place b->valid = 1; b->tag = tag; b->lastVisit = cache->nVisits; return; } } // need to evict one cache line idx = 0; for (i=1; i<cache->nLines; i++) { Cache_Block *b = &cache->cache_block[set][i]; if (b->lastVisit<cache->cache_block[set][idx].lastVisit) { idx = i; } } Cache_Block *b = &cache->cache_block[set][idx]; b->tag = tag; b->lastVisit = cache->nVisits; }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<ctype.h> #include<math.h> int primeOrNot(int num) { for(int i = 2; i <= sqrt(num); i++) { if((num % i) == 0) { return 0; } } return 1; } int armstrongOrNot(int num) { int len = 0, tempNum = num, tempSum = 0; while(tempNum > 0) { len++; tempNum /= 10; } tempNum = num; while(tempNum > 0) { tempSum += pow((tempNum % 10), len); tempNum /= 10; } if(tempSum == num) { return 1; } else { return 0; } } int main(int argc, char const *argv[]) { if(argc != 2) { return 1; } else { int input = 0; const char *str; str = argv[1]; int i = 0; if(str[i] == '-') { return 1; //assuming only positive numbers are prime } for(; i < strlen(str); i++) { if(!isdigit(str[i])) { return 1; } } input = atoi(str); if((primeOrNot(input) == 1) && (armstrongOrNot(input) != 1)) { printf("Prime\n"); } else if((primeOrNot(input) != 1) && (armstrongOrNot(input) == 1)) { printf("Armstrong\n"); } else if((primeOrNot(input) == 1) && (armstrongOrNot(input) == 1)) { printf("Both\n"); } else { printf("None\n"); } } return 0; }
C
// // CLRS_Fibonacci_2.c // algorithms-iOS // // Created by Tonny Xu on 2/6/12. // Copyright (c) 2012 Tonny Xu. All rights reserved. // #include <stdio.h> #include <sys/time.h> #include <limits.h> #include <math.h> #include <stdlib.h> #include <inttypes.h> #import "CLRS_CommonFunctions.h" #import "CLRS_NaiveAlgorithms.h" double calculateFibonacciAtIndexByFomula(unsigned int index); #ifndef TONNY_IOS_APP int main(int args, char* arg_v[]){ if (args != 2) { printf("Usage: ./CLRS index_of_fibonacci\n"); return 0; } char *endptr; int index = strtoimax(arg_v[1], &endptr, 10); if (*endptr != '\0') { printf("Usage: ./CLRS index_of_fibonacci\n\n"); printf(" index_of_fibonacci need to be a number.[%s]\n", endptr); return 0; } doFibonacci_fomula(index); return 0; } #endif void doFibonacci_fomula(unsigned int index){ const char* algorithmName = "Fibonacci(fomula)"; printf("[%s] calculate fibonacci number at [%d] = ", algorithmName, index); struct timeval start; gettimeofday(&start, NULL); double result = calculateFibonacciAtIndexByFomula(index); printf("%.0f\n", result); struct timeval ended; gettimeofday(&ended, NULL); struct timeval sub; timersub(&ended, &start, &sub); printf("[%s] Using %ld.%06d seconds.\n", algorithmName, sub.tv_sec, sub.tv_usec); } double calculateFibonacciAtIndexByFomula(unsigned int index){ /* Fibnacci number to 15 * 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 *--------------------------------------------------------------------------- * 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 */ /* * Fibnacci number at index i = ceil((golden ratio)^i/sqrt(5) + 0.5)) * where golden ratio = (1 + sqrt(5))/2 */ if (index == 0) { return 0.; }else if (index == 1 || index == 2){ return 1.; } double goldenRatio = (1 + sqrt(5.))/2; double resultBeforeCeil = pow(goldenRatio, index)/sqrt(5.0) + 0.5; printf("|_%.3f_| => ", resultBeforeCeil); /* The result is correct before fib(70) */ double result = floor(resultBeforeCeil); return result; } /* Reference, calculate a fibonacci number by using fomula is not safe. Here is a brief list of the correct answers from 0 to 100. Some significant moment, 0 : 0 1 : 1 2 : 1 3 : 2 4 : 3 5 : 5 6 : 8 7 : 13 8 : 21 9 : 34 10 : 55 11 : 89 12 : 144 13 : 233 14 : 377 15 : 610 16 : 987 17 : 1597 18 : 2584 19 : 4181 20 : 6765 21 : 10946 22 : 17711 23 : 28657 24 : 46368 25 : 75025 26 : 121393 27 : 196418 28 : 317811 29 : 514229 30 : 832040 31 : 1346269 32 : 2178309 33 : 3524578 34 : 5702887 35 : 9227465 36 : 14930352 37 : 24157817 38 : 39088169 39 : 63245986 40 : 102334155 41 : 165580141 42 : 267914296 43 : 433494437 44 : 701408733 45 : 1134903170 46 : 1836311903 INT32_MAX: 2147483647 47 : 2971215073 UINT32_MAX:4294967295 48 : 4807526976 49 : 7778742049 50 : 12586269025 51 : 20365011074 52 : 32951280099 53 : 53316291173 54 : 86267571272 55 : 139583862445 56 : 225851433717 57 : 365435296162 58 : 591286729879 59 : 956722026041 60 : 1548008755920 61 : 2504730781961 62 : 4052739537881 63 : 6557470319842 64 : 10610209857723 65 : 17167680177565 66 : 27777890035288 67 : 44945570212853 68 : 72723460248141 69 : 117669030460994 70 : 190392490709135 71 : 308061521170129 72 : 498454011879264 73 : 806515533049393 74 : 1304969544928657 75 : 2111485077978050 76 : 3416454622906707 77 : 5527939700884757 78 : 8944394323791464 79 : 14472334024676221 80 : 23416728348467685 81 : 37889062373143906 82 : 61305790721611591 83 : 99194853094755497 84 : 160500643816367088 85 : 259695496911122585 86 : 420196140727489673 87 : 679891637638612258 88 : 1100087778366101931 89 : 1779979416004714189 90 : 2880067194370816120 91 : 4660046610375530309 92 : 7540113804746346429 INT64_MAX: 9223372036854775807 93 : 12200160415121876738 UINT64_MAX:18446744073709551615 94 : 19740274219868223167 95 : 31940434634990099905 96 : 51680708854858323072 97 : 83621143489848422977 98 : 135301852344706746049 99 : 218922995834555169026 100 : 354224848179261915075 URL: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibtable.html */
C
#include <stdio.h> #include <stdlib.h> //get int pointer as parameter and increment it value by one void inc(int *w) { *w = *w + 1; } int main() { int x = 123; int y = x; //call inc function and pass y memory address inc(&y); printf("%d,%d\n", x, y); return EXIT_SUCCESS; }
C
// // sorting.h // Created by Anjali Malik // // #ifndef sorting_h #define sorting_h #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <time.h> //to store integers typedef struct _Node{ long value; struct _Node *next; }Node; //for multiple linked lists typedef struct _List{ Node *node; struct _List *next; }List; Node *Load_From_File(char *Filename); int Save_To_File(char *Filename, Node *list); int ListSize(Node *list); Node *Shell_Sort(Node *list); #endif /* sorting_h */
C
////////////////////////////////////////////////////////////////////////////// // // // Exemple de communication radio avec un terminal RS232 // //--------------------------------------------------------------------------// // // // Ce programme montre comment tablir une communication entre le PRC // // et un PC quip d'un terlinal RS232. // // Dans ce cas, aucune programmation n'est ncessaire ct PC // // // ////////////////////////////////////////////////////////////////////////////// #include "../PrcLib/PRC.h" // PRC.h contains the prototype of PrcInit() and timing functions #include "../PrcLib/LEDs.h" // LEDs.h contains the prototypes of LEDs functions #include "../PrcLib/anaIn.h" #include "../PrcLib/AMB2300.h" // Radio.h contains the prototypes of Bluetooth radio functions #include <stdlib.h> int main(void) { char c = 0; char str[10]; prcInit(); // Initialisation du PRC radioInit(); // Initialisation de la radio // Main loop while(1) { delay_ms(500); if (radioGetStatus() != RADIO_CONNECTED){ // on attend d'etre connecte au PC (action du terminal RS232) ledToggle(7); // en faisant clignoter une LED } else { ledWriteByte(0); // une fois connect, on teint la LED ledWrite(c,1); itoa(str, anaInRead(c), 10); radioSendString(str); // on envoie une chaine de caractres qui s'imprimera dans le terminal radioSendString("\n"); if (radioGetRxBufferSpace() > 0) { c = radioGetChar() - '0'; // on rcupre la rponse de l'utilisateur (le programme est bloqu en attendant) if (c < 0) { c = 0; } else if (c > 7) { c = 7; } } } } } /* [1] : les terminaux rs232 sont principalement conus pour changer du texte, ils interprtent donc les donnes qu'ils envoient/recoivent * comme du texte en code ASCII : chaque caractre correspond une valeur entre 0 et 255. * Dans le cas des caractres reprsentant les chiffres dcimaux, ils osnt cods par les valeurs allant de 48 (pour '0') 57 (pour '9'). * Pour obtenir un chiffre partir de son code ASCII, il suffit donc de soustraire 48 de ce dernier. * Pour que le code soit plus "parlant", on peut crire '0' la place de 48 (comme la ligne 34). * De manire gnrale, crire un caractre entre '' dans un code en langage C est quivalent crire la valeur de son code ASCII. */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printf_conv_int_hh_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: nforay <nforay@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/03/09 17:17:47 by nforay #+# #+# */ /* Updated: 2020/07/31 16:54:01 by nforay ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" #include "libft.h" void ft_printf_nbr_hhd_fd(signed char n, int size, t_state_machine *m) { if (n < 0) n *= -1; while ((m->preci - size) > 0) { ft_putchar_fd('0', m->fd); m->len++; m->preci--; m->fwidth--; } ft_printf_signed_char(n, m); } int get_intlen_hh(signed char n, int len) { if (n == -128) return (3); if (n <= 0) n = -n; while (n >= 10) { len++; n /= 10; } return (len); } void ft_printf_signed_char(signed char n, t_state_machine *m) { if (n == -128) { ft_putstr_fd("12", m->fd); m->fwidth -= 2; m->len += 2; n = 8; } if (n <= 9 && n >= 0) { ft_putchar_fd(n + 48, m->fd); m->len++; m->fwidth--; } else { ft_printf_signed_char(n / 10, m); ft_putchar_fd(n % 10 + 48, m->fd); m->len++; m->fwidth--; } }
C
/*************************************************************************************** * * * NET DOWN - qualix DEVELOPS - www.qualix.com.ar * * Cliente * **************************************************************************************** * Descripcion: Aplicacion cliente-servidor para ejecutar comandos por el cliente de * * atraves del servidor, de manera remota. * * * **************************************************************************************** * Autor: Fernando Abad - qualix- fabad@qualix.com.ar * Version: 0.1 * **************************************************************************************** * fecha: 26.11.2010 * ***************************************************************************************/ /************************************* Headers *****************************************/ #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <sys/un.h> #include <netdb.h> /* netbd.h es necesitada por la estructura hostent */ /************************************* Define's *****************************************/ #define PORT 3550 /* El Puerto Abierto del nodo remoto */ #define MAXDATASIZE 100 /* El número máximo de datos en bytes */ /*********************************** Funcion Principal **********************************/ int main(int argc, char *argv[]){ int fd, numbytes; /* ficheros descriptores */ char buf[MAXDATASIZE]; /* en donde es almacenará el texto recibido */ struct hostent *he; /* estructura que recibirá información sobre el nodo remoto */ struct sockaddr_in server; /* información sobre la dirección del servidor */ if (argc !=2) { /* el programa sólo necesitará un argumento, (la IP) */ printf("%s%s","Uso: <Dirección IP>\n",argv[0]); /* si no se ingresa el argumento sale de la aplicacion */ return EXIT_FAILURE; } if ((he=gethostbyname(argv[1]))==NULL){ /* llamada a gethostbyname() */ printf("gethostbyname() error\n"); /* si no se puede llamar a la funcion sale de la aplicacion */ return EXIT_FAILURE; } if ((fd=socket(AF_INET, SOCK_STREAM, 0))==-1){ /* llamada a socket(), se crea el socket */ printf("socket() error\n"); /* si no se puede llamar a la funcion sale de la aplicacion */ return EXIT_FAILURE; } server.sin_family = AF_INET; /* inicializacion del socket */ server.sin_port = htons(PORT); /* htons() es necesaria nuevamente */ server.sin_addr = *((struct in_addr *)he->h_addr); /* he->h_addr pasa la información de *he a h_addr" */ bzero(&(server.sin_zero),8); /* escribimos ceros en el reto de la estructura */ if(connect(fd, (struct sockaddr *)&server, sizeof(struct sockaddr))==-1){ /* llamada a connect(), se crea la conexion en una direccion */ printf("connect() error\n"); /* si no se puede llamar a la funcion sale de la aplicacion */ return EXIT_FAILURE; } if ((numbytes=recv(fd,buf,MAXDATASIZE,0)) == -1){ /* llamada a recv(), se crea la conexion en la otra direccion */ printf("Error en recv() \n"); /* si no se puede llamar a la funcion sale de la aplicacion */ return EXIT_FAILURE; } buf[numbytes]='\0'; /* se inicializa el buffer */ printf("%s\n%s","Mensaje del Servidor: ",buf); /* muestra el mensaje del servidor */ close(fd); /* cerramos la conexion */ return EXIT_SUCCESS; /* salimos de la aplicacion */ }
C
# include <stdio.h> # include "gen.h" # include "../h/dbs.h" # include "../h/aux.h" # include "../h/pipes.h" # include "../h/tree.h" # include "../h/symbol.h" # include "parser.h" struct atstash *Freeatt; /* free list of attrib stash */ static struct rngtab Rngtab[MAXVAR + 1]; /* range table */ static struct atstash Attable[MAXATT]; /* attrib stash space, turned into a list later */ /* ** RNGINIT ** initializes the pointers in the range table ** it should be called prior to starting the parsing ** it also initializes the attrib stash stuff because ** the attrib stash is really part of the range table */ rnginit() { register int i; register struct atstash *atptr; register struct rngtab *rptr; rptr = Rngtab; /* ptr to head of range table */ for (i = 0; i <= MAXVAR; i++, rptr++) /* ">=" includes the internal entry */ { rptr->ractiv = 0; rptr->rmark = 0; rptr->rposit = i; AAsmove("", rptr->varname); AAsmove("", rptr->relnm); rptr->rstat = 0; rptr->ratts = 0; rptr->attlist = (struct atstash *) 0; } rngreset(); atptr = Attable; for (i = 0; i < MAXATT - 1; i++) { atptr->atbnext = atptr + 1; atptr++; } atptr->atbnext = (struct atstash *) 0; Freeatt = Attable; } /* ** RNGLOOK ** returns a pointer to the range table entry else 0 ** type = LOOKREL lookup relation ** type = LOOKVAR lookup variable */ struct rngtab *rnglook(p, type) char *p; int type; { register struct rngtab *rptr; register char *param; register int i; param = p; rptr = Rngtab; switch (type) { case LOOKVAR: case LOOKREL: break; default: AAsyserr(18019, type); } for (i = 0; i < MAXVAR; i++, rptr++) /* search external vbles only */ { if (rptr->ractiv == 1 && AAscompare(param, MAXNAME, (type == LOOKVAR ? rptr->varname : rptr->relnm), MAXNAME) == 0) { rptr->rmark = 1; # ifdef xPTR2 AAtTfp(21, 6, "fnd '%s' at '%d'\n", param, rptr->rentno); # endif rngfront(rptr); return (rptr); } } return ((struct rngtab *) 0); } /* ** RNGENT ** Insert variable and relation in range table. */ struct rngtab *rngent(type, var, rel, relown, atts, relstat) int type; char *var; char *rel; char *relown; int atts; int relstat; { register struct rngtab *rptr; extern struct rngtab *rngat(); extern struct rngtab *rngatndx(); # ifdef xPTR2 AAtTfp(21, 0, "RNGENT:\ttyp=%d\tvar=%s\trel=%s\n\town=%.2s\tatts=%d\tstat=0%o\n", type, var, rel, relown, atts, relstat); # endif if (type == R_INTERNAL) rptr = &Rngtab[MAXVAR]; else if (type == R_EXTERNAL) { if (!(rptr = rnglook(var, LOOKVAR))) { /* not in range table */ rptr = rngatndx(MAXVAR - 1); } rngfront(rptr); } else AAsyserr(18020, type); if (AAscompare(rel, MAXNAME, rptr->relnm, MAXNAME) != 0 || !AAbequal(relown, rptr->relnowner, 2)) { attfree(rptr->attlist); rptr->attlist = (struct atstash *) 0; } AApmove(var, rptr->varname, MAXNAME, '\0'); AApmove(rel, rptr->relnm, MAXNAME, '\0'); AAbmove(relown, rptr->relnowner, 2); rptr->ractiv = 1; rptr->ratts = atts; rptr->rstat = relstat; return (rptr); } /* ** RNGDEL ** removes an entry from the range table ** removes all variables for the relation name */ rngdel(rel) char *rel; { register struct rngtab *rptr; while ((rptr = rnglook(rel, LOOKREL))) { AAsmove("", rptr->relnm); AAsmove("", rptr->varname); rptr->rmark = 0; rptr->ractiv = 0; rngback(rptr); attfree(rptr->attlist); rptr->attlist = (struct atstash *) 0; } } /* ** RNGSEND ** Writes range table information needed by DECOMP and OVQP. */ rngsend() { register struct rngtab *rptr; register int i; rptr = Rngtab; for (i = 0; i < MAXVAR; i++, rptr++) { if (rptr->rmark != 0) { rngwrite(rptr); } } /* send result relation range entry if not already sent */ if (Resrng && Resrng->rentno == MAXVAR) { rngwrite(Resrng); } } /* ** RNGFRONT ** move entry 'r' to head of range table list */ rngfront(r) struct rngtab *r; { register struct rngtab *rptr; register struct rngtab *fptr; register int i; fptr = r; rptr = Rngtab; for (i = 0; i < MAXVAR; i++, rptr++) /* check all external vbles */ { if (rptr->rposit < fptr->rposit) rptr->rposit++; } fptr->rposit = 0; } /* ** RNGBACK ** move entry 'r' to back of range table list */ rngback(r) struct rngtab *r; { register struct rngtab *rptr; register struct rngtab *bptr; register int i; bptr = r; rptr = Rngtab; for (i = 0; i < MAXVAR; i++, rptr++) /* check all external vbles */ { if (rptr->rposit > bptr->rposit) rptr->rposit--; } bptr->rposit = MAXVAR - 1; } /* ** RNGRESET ** reset the used marks to '0' */ rngreset() { register struct rngtab *rptr; register int i; rptr = Rngtab; for (i = MAXVAR - 1; i >= 0; i--, rptr++) /* only do external ones */ { rptr->rmark = 0; rptr->rentno = i; } Rngtab[MAXVAR].rentno = MAXVAR; /* internal vble is always MAXVAR */ } /* ** RNGOLD -- find least recently used vble entry */ struct rngtab *rngatndx(ndx) int ndx; { register struct rngtab *rptr; register int i; rptr = Rngtab; for (i = 0; i < MAXVAR; i++, rptr++) /* do external vbles */ { if (rptr->rposit == ndx) return (rptr); } AAsyserr(18021, ndx); } /* ** CHECKUPD ** checks to make sure that the user can update the relation 'name1' ** the 'open' parameter is set if 'Reldesc' contains the AArelopen info ** for the relation in question. */ checkupd(rptr) struct rngtab *rptr; { if (!Noupdt) return; if (rptr->rstat & S_NOUPDT) /* no updates allowed on this relation */ yyerror(CANTUPDATE, rptr->relnm, (char *) 0); } /* ** RNGFRESH -- check the range table relstat information for accuracy ** ** If the command specified could have changed the relstat info ** make the appropriate adjustments to the range table */ rngfresh(op) int op; { register struct rngtab *rptr; register int i; DESC desc; /* search the entire table! */ for (i = 0, rptr = Rngtab; i <= MAXVAR; i++, rptr++) { if (!rptr->ractiv) continue; switch (op) { case mdDESTROY: case mdREMQM: if ((rptr->rstat & (S_VBASE | S_INTEG | S_PROTUPS | S_INDEX)) != 0) { fixordel: /* ** AArelopen the relation, if it doesn't exist make ** sure that all range table entries are gone */ if (!AArelopen(&desc, -1, rptr->relnm)) { /* relation still there, copy bits anyway */ rptr->rstat = desc.reldum.relstat; } else { /* relation not there, purge table */ rngdel(rptr->relnm); } } break; case mdVIEW: if ((rptr->rstat & S_VBASE) == 0) { fixorerr: /* ** if the relation doesn't exist then it is ** a AAsyserr, otherwise, copy the bits. */ if (!AArelopen(&desc, -1, rptr->relnm)) { /* exists, copy bits */ rptr->rstat = desc.reldum.relstat; } else /* not there, AAsyserr */ AAsyserr(18022, rptr->relnm); } break; case mdPROT: if ((rptr->rstat & S_PROTUPS) == 0) goto fixorerr; break; case mdINTEG: if ((rptr->rstat & S_INTEG) == 0) goto fixorerr; break; case mdMODIFY: if ((rptr->rstat & S_INDEX) != 0) goto fixordel; break; default: return; /* command ok, dont waste time on rest of table */ } } } /* ** RNGPRINT ** prints the contents of the range table */ rngprint() { register short i; register short j; register struct rngtab *rptr; printf(" relation\tvariable\n"); printf("----------------------------\n"); for (i = 0; i < MAXVAR; i++) { rptr = Rngtab; for (j = 0; j < MAXVAR; j++, rptr++) { if (!rptr->ractiv || i != rptr->rposit) continue; printf("%12s\t%.12s\n", rptr->relnm, rptr->varname); } } printf("----------------------------\n"); }
C
#include<stdio.h> int p[200]; int judge(int x,int n){ int i; for(i=0;i<n;i++){ if(p[i] == x){ return 1; } } return 0; } int main(){ int x,n; scanf("%d%d",&x,&n); if(n == 0){ printf("%d\n",x); return 0; } int i; for(i=0;i<n;i++){ scanf("%d",&p[i]); } for(i=0;i<n;i++){ if(judge(x-i,n) == 0){ printf("%d\n",x-i); return 0; }else if(judge(x+i,n) == 0){ printf("%d\n",x+i); return 0; } } if(x-n>=0){ printf("%d\n",x-n); }else{ printf("%d\n",x+n); } return 0; }
C
#include<stdio.h> #include<stdlib.h> struct node{ int data; struct node *next; struct node *prev; }; struct node *head=NULL; struct node *tail=NULL; void insertBegg(){ int data; printf("insert a number to insert\n"); scanf("%d",&data); struct node *temp=(struct node*)malloc(sizeof(struct node)); temp->data=data; temp->next=temp; temp->prev=temp; if(head==NULL){ head=temp; } else{ struct node *temp2=head; while(temp2->next!=head){ temp2=temp2->next; } temp->next=head; temp->prev=temp2; head->prev=temp; head=temp; temp2->next=temp; } } void insertsp(){ int data,pos; printf("insert a position to insert\n"); scanf("%d",&pos); printf("insert a number to insert\n"); scanf("%d",&data); struct node *temp=(struct node*)malloc(sizeof(struct node)); int y=1; temp->data=data; temp->next=temp; temp->prev=temp; if(head==NULL){ head=temp; } else{ struct node *temp2=head,*temp3; while((temp2->next!=head)&&(y!=pos)){ temp2=temp2->next; y++; } temp2->next->prev=temp; temp->prev=temp2; temp->next=temp2->next; temp2->next=temp; } } void insertEnd(){ int data; printf("insert a number to insert\n"); scanf("%d",&data); struct node *temp=(struct node*)malloc(sizeof(struct node)); temp->data=data; temp->next=temp; temp->prev=temp; if(head==NULL){ head=temp; } else{ struct node *temp2=head; while(temp2->next!=head){ temp2=temp2->next; } temp->next=head; temp->prev=temp2; temp2->next=temp; head->prev=temp; } } void deleteBegg(){ if(head==NULL){ printf("no data to delete"); } else if(head->next==head){ head=NULL; free(head); } else{ struct node *temp2=head; while(temp2->next!=head){ temp2=temp2->next; } head=head->next; temp2->next=head; head->prev=temp2; } } int present(d){ struct node *link=head; while(link->next!=head){ if(link->data==d){ return 1; } link=link->next; } return 0; } void search(){ int data; printf("insert a number search\n"); scanf("%d",&data); struct node *temp2=head; int y=1; while(temp2->data!=data){ if(temp2->next==head){ y=0; break; } temp2=temp2->next; y++; } if(y==1){ printf("Data Not found\n"); } else{ printf("Data found at : %d\n\n",y); } } void deleteSpec(){ int data; printf("insert a number to insert\n"); scanf("%d",&data); if(present(data)){ if(head==NULL){ printf("no data to delete"); } else if(head->data==data){ deleteBegg(); } else{ struct node *temp2=head,*temp3; while(temp2->data!=data){ temp3=temp2; temp2=temp2->next; } temp3->next=temp2->next; temp2->prev=temp3; } } else{ printf("no data to delete"); } } void deleteEnd(){ if(head==NULL){ printf("no data to delete"); } else if(head->next==head){ head=NULL; free(head); } else{ struct node *temp2=head,*temp3; while(temp2->next!=head){ temp3=temp2; temp2=temp2->next; } head->prev=temp3; temp3->next=head; } } void display(){ struct node *ptr=head; if(head==NULL) printf("no data"); else{ while(ptr->next!=head){ printf("%d\n",ptr->data); ptr=ptr->next; } if(ptr->next==head){ printf("%d\t",ptr->data); } } } int main(){ int c=0; while(1) { printf("\nChoose one option from the following list ...\n"); printf("\n1.Insert in Beginning\n2.Insert at specfic\n3.Insert at last\n4.Delete from Beginning\n5.Delete from specfic\n6.Delete from last\n7.Search\n8.Show\n9.Exit\n"); printf("\nEnter your choice?\n"); scanf("\n%d",&c); switch(c) { case 1: insertBegg(); break; case 2: insertsp(); break; case 3: insertEnd(); break; case 4: deleteBegg(); break; case 5: deleteSpec(); break; case 6: deleteEnd(); break; case 7: search(); break; case 8: display(); break; case 9: exit(0); break; default: printf("Please enter valid choice.."); } } }
C
#ifndef PLAYER_H_ #define PLAYER_H_ #include <map.h> #include <constant.h> #include <bomb.h> #include <game.h> struct player; // Creates a new player with a given number of available bombs struct player* player_init(int bomb_number); void player_free(struct player* player); // Returns the current position of the player int player_get_x(struct player* player); int player_get_y(struct player* player); void player_set_x(struct player* player,int x); void player_set_y(struct player* player,int y); // Set the direction of the next move of the player void player_set_current_way(struct player * player, enum direction direction); // Give the number of key that player can have. int player_get_nb_key(struct player* player); void player_set_nb_keys(struct player* player,int key); // Set, Increase, Decrease the number of life that player can have. int player_get_nb_life(struct player* player); void player_inc_nb_life(struct player* player) ; void player_dec_nb_life(struct player* player) ; void player_set_nb_life(struct player * player, int life) ; // Set, Increase, Decrease the number of bomb that player can put int player_get_nb_bomb(struct player * player); void player_inc_nb_bomb(struct player * player); void player_dec_nb_bomb(struct player * player); void player_set_nb_bomb(struct player* player,int bomb); // Set, Increase, Decrease the number of range that player can have. int player_get_nb_range(struct player * player); void player_inc_nb_range(struct player * player); void player_dec_nb_range(struct player * player); void player_set_nb_range(struct player* player,int range); // Set, Get, Increase, Decrease the wound of the player void player_set_wounds(struct player * player, int zeros); int player_get_wounds(struct player * player); void player_inc_wounds(struct player * player); void player_dec_wounds(struct player * player); // Load the player position from the map void player_from_map(struct player* player, struct map* map); // Move the player according to the current direction int player_move( struct game* game ) ; // Display the player on the screen void player_display(struct player* player); #endif /* PLAYER_H_ */
C
/* 9. Write macros for the following using bitwise operations: a. To find maximum and minimum of 2 numbers b. To clear right most set bit in a number c. To clear left most set bit in a number d. To set right most cleared bit in a number e. To set left most cleared bit in a number f. To set bits from bit position ‘s’ to bit position ‘d’ in a given number and clear rest of the bits g. To clear bits from bit position ‘s’ to bit position ‘d’ in a given number and set rest of the bits h. To toggle bits from bit position ‘s’ to bit position ‘d’ in a given number */ #include<stdio.h> #include<stdlib.h> #define BUF 512 void display(int ); char *remove_n(char *); char *my_fgets(char *); int my_atoi(char *); char *input_validation(char *); int num_validation(int ); #define FIND_MIN(num1, num2) ((num1 - num2) >> 31) ? printf("num1 is less\n") : printf("num2 is less\n") #define FIND_MAX(num1, num2) ((num1 - num2) >> 31) ? printf("num2 is greater\n") : printf("num1 is greater\n") #define CLR_RIGHT_SET_BIT(num1) num1 & (num1 - 1) #define CLR_LEFT_SET_BIT(num1, i) (num1 >> i) & 1 #define SET_RIGHT_CLR_BIT(num1) num1 | (num1 + 1) #define SET_LEFT_CLR_BIT(num1, i) (num1 >> i) & 1 #define SET_S_TO_D_BIT(num1, s, d) ( ~((~0) << ((d - s) + 1))) << s #define CLR_S_TO_D_BIT(num1, s, d) ( ~(( ~((~0) << ((d - s) + 1))) << s) ) int main(void) { int num2,num1,ch,i,s,d; char *str = NULL; if(NULL == (str = (char *)malloc(sizeof(char) * BUF))) { perror("malloc failed"); exit(EXIT_FAILURE); } while(1) { printf("enter your choice\n1. Find the max & min of\n2. clear right most set bit\n3. clear left most set bit\n"); printf("4. set right most clr bit\n5. set left most clr bit\n3. set bits from pos s to d\n"); str = my_fgets(str); str = remove_n(str); if(input_validation(str) == 0) { printf("wrong input\n"); continue; } else break; } ch = my_atoi(str); while(1) { printf("enter the num1\n"); str = my_fgets(str); str = remove_n(str); if(input_validation(str) == 0) { printf("wrong input\n"); continue; } else break; } num1 = my_atoi(str); while(1) { printf("enter the num2\n"); str = my_fgets(str); str = remove_n(str); if(input_validation(str) == 0) { printf("wrong input\n"); continue; } else break; } num2 = my_atoi(str); switch(ch) { case 1 : FIND_MAX(num1, num2); FIND_MIN(num1, num2); break; case 2 : display(num1); num1 = CLR_RIGHT_SET_BIT(num1); display(num1); break; case 3 : for(i = 31; i >= 0; i--) { if(!(CLR_LEFT_SET_BIT(num1, i))) continue; else { num1 = num1 & ~(1 << i); break; } } display(num1); break; case 4 : num1 = SET_RIGHT_CLR_BIT(num1); display(num1); break; case 5 : for(i = 31; i >= 0; i--) { if(SET_LEFT_CLR_BIT(num1, i)) continue; else { num1 = num1 | (1 << i); break; } } display(num1); break; case 6 : printf("enter s & d\n"); scanf("%d %d",&s,&d); num1 = SET_S_TO_D_BIT(num1, s, d); display(num1); break; case 7 : printf("enter s & d\n"); scanf("%d %d",&s,&d); num1 = CLR_S_TO_D_BIT(num1, s, d); display(num1); break; default : break; } return 0; }
C
#include<stdio.h> #include<conio.h> int main() { char name[20]; printf("enter ur name\n"); gets(name); printf("hi u r a good boy\n%s",name); getch(); return 0; }
C
/******************************************************************************/ // Bullfrog Engine Emulation Library - for use to remake classic games like // Syndicate Wars, Magic Carpet or Dungeon Keeper. /******************************************************************************/ /** @file bflib_bufrw.c * Reading/writing values in various bit formats into buffer. * @par Purpose: * Allows writing little-endian and big-endian values. * @par Comment: * These functions are not defined as inline because of C-to-C++ * transition problem with inline functions. * @author Tomasz Lis * @date 04 Jan 2009 - 10 Jan 2009 * @par Copying and copyrights: * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ /******************************************************************************/ #include "bflib_bufrw.h" #include "bflib_basics.h" #ifdef __cplusplus extern "C" { #endif /******************************************************************************/ /** * Writes 2-byte little-endian number into given buffer. */ void write_int16_le_buf (unsigned char *buff, unsigned short x) { buff[0]=(x&255); buff[1]=((x>>8)&255); } /** * Writes 4-byte little-endian number into given buffer. */ void write_int32_le_buf (unsigned char *buff, unsigned long x) { buff[0]=(x&255); buff[1]=((x>>8)&255); buff[2]=((x>>16)&255); buff[3]=((x>>24)&255); } /** * Reads 4-byte little-endian number from given buffer. */ long read_int32_le_buf (const unsigned char *buff) { long l; l = buff[0]; l += buff[1]<<8; l += buff[2]<<16; l += buff[3]<<24; return l; } /** * Reads 2-byte little-endian number from given buffer. */ unsigned short read_int16_le_buf (const unsigned char *buff) { long l; l = buff[0]; l += buff[1]<<8; return l; } /** * Reads 4-byte big-endian number from given buffer. */ long read_int32_be_buf (const unsigned char *buff) { long l; l = buff[3]; l += buff[2]<<8; l += buff[1]<<16; l += buff[0]<<24; return l; } /** * Reads 2-byte big-endian number from given buffer. */ unsigned short read_int16_be_buf (const unsigned char *buff) { long l; l = buff[1]; l += buff[0]<<8; return l; } /** * Writes 2-byte big-endian number into given buffer. */ void write_int16_be_buf (unsigned char *buff, unsigned short x) { buff[1]=(x&255); buff[0]=((x>>8)&255); } /** * Writes 4-byte big-endian number into given buffer. */ void write_int32_be_buf (unsigned char *buff, unsigned long x) { buff[3]=(x&255); buff[2]=((x>>8)&255); buff[1]=((x>>16)&255); buff[0]=((x>>24)&255); } /** * Reads 1-byte number from given buffer. * Simple wrapper for use with both little and big endian files. */ unsigned char read_int8_buf (const unsigned char *buff) { return buff[0]; } /** * Writes 1-byte number into given buffer. * Simple wrapper for use with both little and big endian files. */ void write_int8_buf (unsigned char *buff, unsigned char x) { buff[0]=x; } /******************************************************************************/ #ifdef __cplusplus } #endif
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "casa.h" #include "quadtree.h" #include "ponto.h" typedef struct casa { int n; char face; double w, h, n_x, n_y; ponto coord; } objCasa; casa montaCasa(int n, char *cep, char *face, int num, QuadTree quadras){ double quad_x, quad_y, quad_w, quad_h; objCasa *c; c = (objCasa *) calloc (1, sizeof(objCasa)); c->n = n; c->face = face[0]; nodulo node = getNoQt_byId(quadras, cep); if(node == NULL){ return NULL; } c->w = 10; c->h = 10; Modulo quad = getModulo(getInfoQt(quadras,node)); addCasosCovid(quad, face, n); quad_x = retornaQuadra_X(quad); quad_y = retornaQuadra_Y(quad); quad_w = retornaQuadra_W(quad); quad_h = retornaQuadra_H(quad); if(strcmp(face,"L")==0){ c->n_y = quad_y + num + 3.5; c->n_x = quad_x + c->w/2 + 1; ponto pt = montaPonto(quad_x+1, quad_y+num-c->h/2+1); c->coord = pt; } else if(strcmp(face,"O")==0){ c->n_y = quad_y + num + c->h/2 - 3; c->n_x = quad_x + quad_w - c->w/2 - 1; ponto pt = montaPonto(quad_x + quad_w - c->w - 1, quad_y + num - c->h/2); c->coord = pt; } else if(strcmp(face,"S")==0){ c->n_y = quad_y + c->h/2 + 3.5; c->n_x = quad_x + num; ponto pt = montaPonto(quad_x + num - c->w/2, quad_y + 1); c->coord = pt; } else if(strcmp(face,"N")==0){ c->n_y = quad_y + quad_h - c->h/2 + 1.5; c->n_x = quad_x + num; ponto pt = montaPonto(c->n_x - c->w/2, quad_y + quad_h - c->h - 1); c->coord = pt; } return c; } ponto pontoCentral_Endereco(Quadra quad,char *face, int num){ double quad_x = retornaQuadra_X(quad); double quad_y = retornaQuadra_Y(quad); double quad_w = retornaQuadra_W(quad); double quad_h = retornaQuadra_H(quad); double n_y,n_x,x,y,w=10,h=10; if(strcmp(face,"L")==0){ x = quad_x + 1; y = quad_y + num - h/2 + 1; } else if(strcmp(face,"O")==0){ x = quad_x + quad_w - w - 1; y = quad_y + num - h/2; } else if(strcmp(face,"S")==0){ x = quad_x + num - w/2; y = quad_y + 1; } else if(strcmp(face,"N")==0){ x = quad_x + num - w/2; y = quad_y + quad_h - h - 1; } ponto pc = montaPonto(x+w/2,y+h/2); return pc; } double retornaCasa_Xc(casa c){ objCasa *casa_atual = (objCasa *) c; return retornaPonto_X(casa_atual->coord) + casa_atual->w/2; } double retornaCasa_Yc(casa c){ objCasa *casa_atual = (objCasa *) c; return retornaPonto_Y(casa_atual->coord) + casa_atual->h/2; } int retornaCasa_N(casa c){ objCasa *casa_atual = (objCasa *) c; return casa_atual->n; } double retornaCasa_X(casa c){ objCasa *casa_atual = (objCasa *) c; return retornaPonto_X(casa_atual->coord); } double retornaCasa_Y(casa c){ objCasa *casa_atual = (objCasa *) c; return retornaPonto_Y(casa_atual->coord); } double retornaCasa_W(casa c){ objCasa *casa_atual = (objCasa *) c; return casa_atual->w; } double retornaCasa_H(casa c){ objCasa *casa_atual = (objCasa *) c; return casa_atual->h; } double retornaCasa_Ny(casa c){ objCasa *casa_atual = (objCasa *) c; return casa_atual->n_y; } double retornaCasa_Nx(casa c){ objCasa *casa_atual = (objCasa *) c; return casa_atual->n_x; } void removeCasa(casa c){ objCasa *casa_atual = (objCasa *) c; free(casa_atual->coord); free(casa_atual); } ponto retornaCasaCoord(casa c){ objCasa *casa_atual = (objCasa *) c; return casa_atual->coord; } char retornaCasaFace(casa c){ objCasa *casa_atual = (objCasa *) c; return casa_atual->face; }
C
/* Chef is interested in the history of SnackDown contests. He needs a program to verify if SnackDown was hosted in a given year. SnackDown was hosted by CodeChef in the following years: 2010, 2015, 2016, 2017 and 2019. Input The first line contain the number of test-cases T. The first line of each test-case contains a single integer N. Output For each test case print a single line containing the string "HOSTED" if SnackDown was hosted in year N or "NOT HOSTED" otherwise (without quotes). Constraints 1≤T≤10 2010≤N≤2019 */ #include <assert.h> #include <stdbool.h> bool hosted(int y) { switch (y) { case 2010: case 2015: case 2016: case 2017: case 2019: return true; } return false; } int main(void) { assert(hosted(2019) == true); assert(hosted(2018) == false); return 0; }
C
#include<stdio.h> #include<math.h> #include<string.h> #include<stdlib.h> int main() { int t; scanf("%d",&t); while(t--) { int i,n,k,item[10000],sum=0,total=0; scanf("%d%d",&n,&k); for(i=0;i<n;i++) scanf("%d",&item[i]); for(i=0;i<n;i++) { if(item[i]>k) sum+=item[i]-k; } printf("%d\n",sum); } return 0; }
C
#include <stdio.h> char * find(char *, char); int main(void) { char str[80]; char c; while (scanf("%s %c", str, &c) > 0) { printf("%p %c\n", find(str, c), *find(str, c)); printf("again~\n"); } return 0; } char * find(char * str, char c) { while (*str != '\0') { if (*str == c) return str; str++; } return '\0'; }
C
#include <stdio.h> #include <wiringPi.h> int ultrasonic_R_trig = 24; int ultrasonic_R_echo = 25; int ultrasonic_L_trig = 26; int ultrasonic_L_echo = 27; int ultrasonic_F_trig = 28; int ultrasonic_F_echo = 29; float start_time_R; float start_time_L; float start_time_F; float end_time_R; float end_time_L; float end_time_F; float distance_R; float distance_L; float distance_F; /* void ULTRASONIC(){ while(1){ start_time_R = -1; start_time_L = -1; start_time_F = -1; end_time_R = -1; end_time_L = -1; end_time_F = -1; distance_R = -1; distance_L = -1; distance_F = -1; digitalWrite(ultrasonic_R_trig,LOW); digitalWrite(ultrasonic_L_trig,LOW); digitalWrite(ultrasonic_F_trig,LOW); digitalWrite(ultrasonic_R_trig,HIGH); delayMicroseconds(10); digitalWrite(ultrasonic_L_trig,HIGH); delayMicroseconds(10); digitalWrite(ultrasonic_F_trig,HIGH); delayMicroseconds(10); digitalWrite(ultrasonic_R_trig,LOW); digitalWrite(ultrasonic_L_trig,LOW); digitalWrite(ultrasonic_F_trig,LOW); while(digitalRead(ultrasonic_R_echo) != 1); start_time_R = micros(); while(digitalRead(ultrasonic_L_echo) != 1); start_time_L = micros(); while(digitalRead(ultrasonic_F_echo) != 1); start_time_F = micros(); printf("%f %f %f\n",start_time_R,start_time_L,start_time_F); while(digitalRead(ultrasonic_R_echo) != 0); end_time_R = micros(); while(digitalRead(ultrasonic_L_echo) != 0); end_time_L = micros(); while(digitalRead(ultrasonic_F_echo) != 0); end_time_F = micros(); printf("%f %f %f\n",end_time_R,end_time_L,end_time_F); distance_R = (end_time_R - start_time_R)/58.; distance_L = (end_time_L - start_time_L)/58.; distance_F = (end_time_F - start_time_F)/58.; printf("distance R : %fcm\n", distance_R); printf("distance L : %fcm\n", distance_L); printf("distance F : %fcm\n", distance_F); delay(100); } return; } */ void ULTRASONIC_R(){ digitalWrite(ultrasonic_R_trig,0); digitalWrite(ultrasonic_R_trig,1); delayMicroseconds(10); digitalWrite(ultrasonic_R_trig,0); while(digitalRead(ultrasonic_R_echo) != 1); start_time_R = micros(); while(digitalRead(ultrasonic_R_echo) != 0); end_time_R = micros(); distance_R = (end_time_R - start_time_R)/58.; printf("Distance R : %fcm\n",distance_R); delay(100); return; } void ULTRASONIC_L(){ digitalWrite(ultrasonic_L_trig,0); digitalWrite(ultrasonic_L_trig,1); delayMicroseconds(10); digitalWrite(ultrasonic_L_trig,0); while(digitalRead(ultrasonic_L_echo) != 1); start_time_L = micros(); while(digitalRead(ultrasonic_L_echo) != 0); end_time_L = micros(); distance_L = (end_time_L - start_time_L)/58.; printf("Distance L : %fcm\n",distance_L); delay(100); return; } void ULTRASONIC_F(){ digitalWrite(ultrasonic_F_trig,0); digitalWrite(ultrasonic_F_trig,1); delayMicroseconds(10); digitalWrite(ultrasonic_F_trig,0); while(digitalRead(ultrasonic_F_echo) != 1); start_time_F = micros(); while(digitalRead(ultrasonic_F_echo) != 0); end_time_F = micros(); distance_F = (end_time_F - start_time_F)/58.; printf("Distance F : %fcm\n",distance_F); delay(100); return; } int main(){ if(wiringPiSetup() == -1){ return 0; } pinMode(ultrasonic_R_trig,OUTPUT); pinMode(ultrasonic_R_echo,INPUT); pinMode(ultrasonic_L_trig,OUTPUT); pinMode(ultrasonic_L_echo,INPUT); pinMode(ultrasonic_F_trig,OUTPUT); pinMode(ultrasonic_F_echo,INPUT); while(1){ ULTRASONIC_R(); ULTRASONIC_L(); ULTRASONIC_F(); } return 0; }
C
#include "inline_table.h" static void printInlineTableElement (const InlineTable * table); InlineTable * inlineTableFromKeyPair (KeyPair * pair) { assert (pair != NULL); InlineTable * table = malloc (sizeof (InlineTable)); table->pair = pair; table->next = NULL; return table; } InlineTable * pushPair (InlineTable * root, KeyPair * pair) { assert (root != NULL); assert (pair != NULL); InlineTable * t = inlineTableFromKeyPair (pair); t->next = root; return t; } void printInlineTable (const InlineTable * table) { assert (table != NULL); printf (" { "); printInlineTableElement (table); printf (" } "); } static void printInlineTableElement (const InlineTable * table) { assert (table != NULL); printKeyPair (table->pair); if (table->next != NULL) { printf (", "); printInlineTableElement (table->next); } }
C
#include "km0/device/boardIo.h" #include "km0/device/digitalIo.h" static int8_t pin_led1 = -1; static int8_t pin_led2 = -1; static bool invert_output_logic = false; void boardIo_setupLeds(int8_t pin1, int8_t pin2, bool invert) { pin_led1 = pin1; pin_led2 = pin2; invert_output_logic = invert; if (pin_led1 != -1) { digitalIo_setOutput(pin_led1); digitalIo_write(pin_led1, invert); } if (pin_led2 != -1) { digitalIo_setOutput(pin_led2); digitalIo_write(pin_led2, invert); } } void boardIo_writeLed1(bool value) { if (pin_led1 != -1) { digitalIo_write(pin_led1, invert_output_logic ? !value : value); } } void boardIo_writeLed2(bool value) { if (pin_led2 != -1) { digitalIo_write(pin_led2, invert_output_logic ? !value : value); } } void boardIo_toggleLed1() { if (pin_led1 != -1) { digitalIo_toggle(pin_led1); } } void boardIo_toggleLed2() { if (pin_led2 != -1) { digitalIo_toggle(pin_led2); } } void boardIo_setupLeds_proMicroAvr() { boardIo_setupLeds(P_B0, P_D5, true); }
C
#include <stdio.h> #include <stdlib.h> #include<string.h> int min(int i,int j) { if(i<j) return i; else return j; } int bin_coff(int n,int k) { int c[k+1]; int i,j; memset(c,0,sizeof(c)); c[0]=1; for(i=0;i<=n;i++) { for(j=min(i,k);j>0;j--) { c[j]=c[j]+c[j-1]; printf("%d ",c[j]); } } return c[k]; } int main() { int n,k,f; scanf("%d %d",&n,&k);// 5 3 =10 f=bin_coff(n,k); printf("%d",f); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <fcntl.h> #include <string.h> int dbglvl = 4; #define FUDGE_BUF (100*1024) #define MAX_SPEC_FD 2 struct spec_fd_t { int limit; int len; int pos; unsigned char *buf; } spec_fd[MAX_SPEC_FD]; int spec_init() { int i, j; !dbglvl; /* Allocate some large chunks of memory, we can tune this later */ for (i = 0; i < MAX_SPEC_FD; i++) { spec_fd[i].buf = (unsigned char *) malloc(FUDGE_BUF); } return 0; } int spec_load(char *filename, int size) { #define FILE_CHUNK (128*1024) int fd, rc, i; #ifndef O_BINARY #define O_BINARY 0 #endif fd = open(filename, O_RDONLY | O_BINARY); rc = read(fd, spec_fd[0].buf, FILE_CHUNK); if (rc < 0) { fprintf(stderr, "Error reading from %s: %s\n", filename, strerror(errno)); exit(0); } close(fd); return 0; } #define MB (1024*1024) int main(int argc, char *argv[]) { int input_size = 64; char *input_name = "input.combined"; spec_init(); spec_load(input_name, input_size * MB); return 0; }
C
#include <stdio.h> #include <stdlib.h> int foo(int*a,int*b) { if (*a>*b) return *b; return *a; } int main() { int tab[] = {1,2,-3,2,9,8,1,-2,3,4}; int *wsk=tab-1; int b = *(wsk+=4); //b=2 int c = b+4; // b=2 , c=6 int d = foo(&b,&c); // b=2 , c=6 , d=2 int e = (wsk+=-1)[4]; // b=2 , c=6 , d=2 , e=1 e = (d *= 2) + (c /= 2); // b=2 , c=3 , d=4 , e=7 c = d - (b+=5); // b=7 , c=-3 , d=4 , e=7 b = *wsk + e; // b=4 , c=-3 , d=4 , e=7 return 0; }
C
// Problem 6: Sum square difference // // Find the difference between the sum of the squares and the square of the sum of the first hundred naturals. #include <stdio.h> #define BOUND 100 int main(void) { int squareSum = 0; int sumSquare = 0; for (int i = 1; i <= BOUND; i++) { squareSum += i; sumSquare += i * i; } squareSum *= squareSum; printf("Problem 6 result: %d\n", (squareSum < sumSquare) * (sumSquare - squareSum) + (squareSum > sumSquare) * (squareSum - sumSquare)); return 0; }
C
#ifndef UMSECTIONS_INCLUDED #define UMSECTIONS_INCLUDED /* Full documentation for this interface is at http://tinyurl.com/2uwhhtu */ #include <stdint.h> #include <stdio.h> //#include <stdlib.h> #include <seq.h> #include <table.h> #include <atom.h> #include <mem.h> #include <malloc.h> #include <bitpack.h> #define T Umsections_T const int TABLE_HINT = 500; const int SEQ_HINT = 50; void applyFree(const void *key, void **value, void *cl); void applyWrite(const void *key, void **value, void *cl); // The sequence of sections is represented as a table. Every section is a // sequence of instruction words. Sections are referenced in the table using // Atoms as keys. Pointers to the sections are held as the values of the table. // We implemented an additional sequence that keeps track of the sequential // order of sections (in chronological order). This was done so that the output // of the write function would print sections in order. // Invariants are: // 1) There will never be two sections with the same name // 2) The chornological order of sections is always stored // 3) Instructions are always added to high and pushed from low struct T { Table_T sections; Seq_T currentSection; int (*error)(void *errstate, const char *message); void* errstate; Seq_T sectionOrder; }; typedef struct T *T; T Umsections_new (const char *section, int (*error)(void *errstate, const char *message), void *errstate) { T Umsections = malloc(sizeof(*Umsections)); Umsections->sections = Table_new(TABLE_HINT, NULL, NULL); Seq_T temp; temp = Seq_new(SEQ_HINT); Seq_T temp2; temp2 = Seq_new(SEQ_HINT); Umsections->error = error; Umsections->errstate = errstate; Umsections->currentSection = temp; Umsections->sectionOrder = temp2; Seq_addlo(Umsections->sectionOrder, temp); Table_put(Umsections->sections, Atom_string(section), temp); /* Table_map((Umsections)->sections,applyFree,NULL); Table_free(&((Umsections)->sections)); Seq_free(&((Umsections)->sectionOrder)); // Seq_free(((Umsectinos)->currentSection)); free(Umsections); exit(1);*/ return Umsections; } void Umsections_free(T *asmp) { Table_map((*asmp)->sections,applyFree,NULL); Table_free(&((*asmp)->sections)); Seq_free(&((*asmp)->sectionOrder)); // Seq_free(((*asmp)->currentSection)); free(*asmp); } void applyFree(const void *key,void **value, void *cl){ (void) key; (void) cl; Seq_free((((Seq_T*)value))); } int Umsections_error(T asm, const char *msg){ return asm->error(asm->errstate, msg); } void Umsections_section(T asm, const char *section) { const char* atom; atom = Atom_string(section); Seq_T temp = Table_get(asm->sections,atom); if (temp == NULL){ temp = Seq_new(SEQ_HINT); Table_put(asm->sections, atom, temp); Seq_addhi(asm->sectionOrder, temp); } asm->currentSection = temp; } typedef uint32_t Umsections_word; // Universal Machine word void Umsections_emit_word(T asm, Umsections_word data) { Seq_addhi(asm->currentSection, (void*)(uintptr_t)data); } void Umsections_map(T asm, void apply(const char *name, void *cl), void *cl){ uint32_t length = Seq_length(asm->sectionOrder); length = length * 2; const char* temp = NULL; void **table = Table_toArray(asm->sections, NULL); for(uint32_t i=0; i < length; i += 2){ // increments by 2 since keys temp = table[i]; // are always the even indexes apply(temp,cl); } free(table); } int Umsections_length(T asm, const char *name){ const char* atom = Atom_string(name); Seq_T temp = Table_get(asm->sections, atom); if (temp == NULL) Umsections_error(asm, "Umsections_length out of bounds"); return Seq_length(temp); } Umsections_word Umsections_getword(T asm, const char *name, int i){ const char* atom = Atom_string(name); Seq_T temp = Table_get(asm->sections, atom); if (Seq_length(temp) <= i || i < 0) Umsections_error(asm, "Umsections_word out of bounds"); return (uintptr_t)Seq_get(temp, i); } void Umsections_putword(T asm, const char *name, int i, Umsections_word w){ const char* atom = Atom_string(name); Seq_T temp = Table_get(asm->sections, atom); if (temp == NULL) Umsections_error(asm, "Umsections_putword out of bounds"); Seq_put(temp, i, (void*)(uintptr_t)w); } void Umsections_write(T asm, FILE *output){ Seq_T current = NULL; for(int i = 0; i<Seq_length(asm->sectionOrder);i++){ current = Seq_get(asm->sectionOrder,i); int length = Seq_length(current); for(int j=0; j<length;j++){ uint32_t word = (uintptr_t)Seq_get(current, j); for(int k = 3; k > -1; k--) // shorter way to print out 32/8 bit putc(Bitpack_gets(word, 8, 8*k), output); // words (void) word; (void) output; } } } /* A value of type T represents a nonempty *sequence* of named sections. Each section contains a sequence of Universal Machnine words. In addition, each value of type T identifies one section in the sequence as the ’current’ section, and a value of type T encapsulates an error function. */ /* Callers of procedures in this interface need *not* provide long-lived pointers to strings. Callers may reuse string memory as soon as the call returns. */ #undef T #endif
C
/* --------------------------- */ // Student: Michel Baartman // StuNummer: 1696929 // Docent: Jorn Bunk // Opdracht: week 5 opdracht 1 /* --------------------------- */ /// @file /// w5o1 Week 5 Opdracht 1 /// Checkes if array is sorted or not, counting upwards and starting from the back. #include <stdio.h> #include <stdbool.h> /*! \brief is_sorted * goes by array a[] and returns either a true or false if the array is sorted or not, counting upwards. */ bool is_sorted(int a[], int size) { // size is lengte van a if(size <= 1){ printf("[end found, returning true]"); return true; }else if(size == 2){ if(a[size] < a[size-1]){ printf("\n[aSize-1 %d < aSize %d, return false]", a[size], a[size-1]); return false; } return true; } else { if(a[size] < a[size-1]){ printf("\n[aSize-1 %d < aSize %d, return false]", a[size-1], a[size]); return false; } return is_sorted(a, size-1); } } /*! \brief main * creates 3 arrays with variety of data. checks wether these are sorted. */ int main(int argc, char **argv) { printf("hello world\n"); int s = 5; int a[5] = {1, 2, 3, 5, 6}; bool state = is_sorted(a, s-1); printf("\nstate = %d", state); int a2[5] = {1, 2, 3, 4, 5}; state = is_sorted(a2, s-1); printf("\nstate = %d", state); int a3[5] = {4, 2, 1, 8, 4}; state = is_sorted(a3, s-1); printf("\nstate = %d", state); return 0; }
C
#include <unistd.h> #include <limits.h> #include <syslog.h> #include <stdlib.h> #include <stdbool.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/stat.h> #include <sys/types.h> #include <pwd.h> #include <fcntl.h> #include <dirent.h> /* recommended version, as per fuse.h */ #define FUSE_USE_VERSION 26 #include <fuse.h> #include "../policy/lib.h" #include "../hashmap/lib.h" #include "../list/lib.h" /* * FUSE permits storing a handle to data associated with the filesystem, which * in our case involves the path to the ghosted directory (`root`) and the RBAC * policy structures (`policy`). * * All paths within our filesystem are "redirected" to equivalent paths * relative to `root`, and are only permitted if the access is allowed by the * `policy`. */ struct private_data { char *root; struct policy policy; }; /* * get_private_data * IN: void * OUT: The private data for the filesystem. * DESCRIPTION: A convenience function for accessing the fuse private * data, as it is stored behind a void pointer. */ struct private_data *get_private_data(void) { return (struct private_data *) fuse_get_context()->private_data; } /* * fill_fullpath * IN: A buffer to fill with the full path; the original path * OUT: void * DESCRIPTION: Append the given path to the shadowed root, and write into `fullpath`. * NOTE: Assumes `fullpath` is of at least size PATH_MAX. */ void fill_fullpath(char *fullpath, const char *path) { char *root = get_private_data()->root; strncpy(fullpath, root, PATH_MAX); strncat(fullpath, path, PATH_MAX); } /* * get_pw_name * IN: uid of the user to lookup * OUT: The username of the user, if any, otherwise NULL if the user does * note exist or the lookup failed * DESCRIPTION: Get the username of a user from their uid * NOTE: Is reenterant and thread safe. The returned string is owned by * the caller and must be free'd */ char *get_pw_name(uid_t uid) { struct passwd pwd; struct passwd *result; size_t bufsz = sysconf(_SC_GETPW_R_SIZE_MAX); if (bufsz == -1) return NULL; char *buf = malloc(bufsz); if (buf == NULL) return NULL; int r = getpwuid_r(uid, &pwd, buf, bufsz, &result); if (result == NULL || r != 0) return NULL; char *pw_name = strdup(pwd.pw_name); free(buf); return pw_name; } /* * nu_getattr * DESCRIPTION: Thin wrapper around lstat for the filesystem. No security * decisions are made. */ int nu_getattr(const char *path, struct stat *buf) { char fullpath[PATH_MAX + 1]; fill_fullpath(fullpath, path); return lstat(fullpath, buf); } /* * has_access * DESCRIPTION: Primary mechanism for implementing security policy. * Checks if a given path is available to the current user with the * requested permissions (O_RDONLY, O_WRONLY, O_RDWR). * It searches the policy structure and implements the access controls by * inspecting the open mode requested by the user and comparing it to the * permissions granted to them in the RBAC definitions file. */ bool has_access(const char *path, int accmode) { syslog(LOG_INFO, "entering has_access(\"%s\")\n", path); struct policy policy = get_private_data()->policy; struct fuse_context *fuse_context = fuse_get_context(); char *mpath = NULL; char *pw_name = NULL; bool recursed = false; // We will need to mutate the path to strip components off of it when // checking for recursive permissions. mpath = strdup(path); if (!mpath) goto denied; syslog(LOG_INFO, "mpath=%s\n", mpath); pw_name = get_pw_name(fuse_context->uid); if (!pw_name) goto denied; syslog(LOG_INFO, "pw_name=%s\n", pw_name); // We check for recursive perms by continuing to check the permission of // every path at and above the requested path. We start with the full path // (recursed==false) and so do not require the recursive permission on the // object. After that, we strip off one path component at a time and // require the recursive permission on each object. Finally, if we get down // to the root object ("/") and do not grant access, we deny access. for (;;) { struct hashmap *role_perms; if ((role_perms = hashmap_get(policy.obj_role_perms, mpath))) { struct list *roles; if ((roles = hashmap_get(policy.user_roles, pw_name))) { for (; roles; roles = list_next(roles)) { perms *perms = hashmap_get(role_perms, list_value(roles)); if (!perms) continue; if (recursed && !(*perms & PERM_RECURSIVE)) continue; if (accmode == O_RDONLY && *perms & PERM_READ) goto granted; else if (accmode == O_WRONLY && *perms & PERM_WRITE) goto granted; else if (*perms & PERM_READ && *perms & PERM_WRITE) goto granted; } } } if (strcmp("/", mpath) == 0) { goto denied; } else { recursed = true; char *slash = strrchr(mpath, '/'); // The last case is special because unix reuses the slash character // to both separate paths and to represent the root path. In the // latter case we just null out the character after the root path, // which would only fail for the empty string, which we never // receive. if (slash == mpath) slash++; *slash = '\0'; } } denied: syslog(LOG_INFO, "exiting has_access with access DENIED"); free(mpath); free(pw_name); return false; granted: syslog(LOG_INFO, "exiting has_access with access GRANTED"); free(mpath); free(pw_name); return true; } /* * nu_open * DESCRIPTION: This function is a wrapper around open for the filesystem, * implementing RBAC access control. * RETURN: -EACCESS in the event that the permission is not granted, * otherwise the return value of open for the same parameters. */ int nu_open(const char *path, struct fuse_file_info *ffi) { if (!has_access(path, ffi->flags & O_ACCMODE)) return -EACCES; char fullpath[PATH_MAX + 1]; fill_fullpath(fullpath, path); ffi->fh = open(fullpath, ffi->flags); return ffi->fh < 0 ? -errno : 0; } /* * nu_opendir * DESCRIPTION: A wrapper around opendir for the filesystem, implementing * RBAC access control. * RETURN: -EACCESS in the event that the permission is not granted, * otherwise the return value of opendir for the same parameters. */ int nu_opendir(const char *path, struct fuse_file_info *ffi) { syslog(LOG_INFO, "opendir path=%s", path); if (!has_access(path, ffi->flags & O_ACCMODE)) return -EACCES; char fullpath[PATH_MAX + 1]; fill_fullpath(fullpath, path); ffi->fh = (uintptr_t) opendir(fullpath); return ffi->fh == (uintptr_t) NULL ? -errno : 0; } /* * nu_readdir * DESCRIPTION: Thin wrapper around readdir for the filesystem. No * security decisions are made. */ int nu_readdir(const char *path, void *buf, fuse_fill_dir_t fill, off_t offset, struct fuse_file_info *ffi) { DIR *d = (DIR *) (uintptr_t) ffi->fh; struct dirent *de; while ((de = readdir(d)) != NULL) if (fill(buf, de->d_name, NULL, 0) != 0) return -ENOMEM; return 0; } /* * nu_read * DESCRIPTION: Thin wrapper around pread for the filesystem. No security * decisions are made. */ int nu_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *ffi) { return pread(ffi->fh, buf, size, offset); } /* * nu_write * DESCRIPTION: Thin wrapper around pwrite for the filesystem. No security * decisions are made. */ int nu_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *ffi) { return pwrite(ffi->fh, buf, size, offset); } /* * nu_truncate * DESCRIPTION: Thin wrapper around truncate for the filesystem. * */ int nu_truncate(const char* path, off_t size){ int ret; ret = truncate(path, size); if(ret == -1){ return -errno; } return 0; } /* * nu_ftruncate * DESCRIPTION: Thin wrapper around ftruncate for the filesystem. * */ int nu_ftruncate(const char* path, off_t size, struct fuse_file_info *ffi){ int ret; (void) path; ret = ftruncate(ffi->fh, size); if(ret == -1){ return -errno; } return 0; } /* * nu_release * DESCRIPTION: Thin wrapper around close for the filesystem. No security * decisions are made. */ int nu_release(const char* path, struct fuse_file_info *ffi) { return close(ffi->fh); } /* * fuse_start * DESCRIPTION: Entrypoint into the filesystem. Saves the path arguments * to the main executable and the policy object as FUSE private data and * then enters the fuse main loop. */ int fuse_start(int argc, char *argv[], struct policy policy) { struct fuse_operations fo = { .getattr = nu_getattr, .open = nu_open, .release = nu_release, .read = nu_read, .write = nu_write, .opendir = nu_opendir, .readdir = nu_readdir, .truncate = nu_truncate, .ftruncate = nu_ftruncate }; /* we store the canonical path to the shadowed root as our fuse * private_data, and remove it from argv so fuse_main ignores it */ char *root = realpath(argv[--argc], NULL); if (!root) { perror("invalid root"); exit(1); } argv[argc] = NULL; struct private_data private_data = { .root = root, .policy = policy, }; return fuse_main(argc, argv, &fo, &private_data); }
C
/* * scafContigIndex.c * * Created on: Jan 9, 2014 * Author: zhuxiao */ #include "inc/stdinc.h" #include "inc/extvab.h" /** * Build the scafContigIndex. * @return: * If succeeds, return SUCCESSFUL; otherwise, return FAILED. */ short buildScafContigIndex(scafContigIndex_t **scafContigIndex, contigGraph_t *contigGraph) { // initialize the scafContigIndex if(initScafContigIndex(scafContigIndex)==FAILED) { printf("line=%d, In %s(), cannot initialize the scafContigIndex, error!\n", __LINE__, __func__); return FAILED; } // count the scafKmer occurrences if(countScafKmerOccs(*scafContigIndex, contigGraph)==FAILED) { printf("line=%d, In %s(), cannot count the kmers from read set, error!\n", __LINE__, __func__); return FAILED; } // add the contigpos information if(addScafKmerContigpos(*scafContigIndex, contigGraph)==FAILED) { printf("line=%d, In %s(), cannot count the kmers from read set, error!\n", __LINE__, __func__); return FAILED; } return SUCCESSFUL; } /** * Initialize scafContigIndex. * @return: * If succeeds, return SUCCESSFUL; otherwise, return FAILED. */ short initScafContigIndex(scafContigIndex_t **scafContigIndex) { *scafContigIndex = (scafContigIndex_t *) calloc(1, sizeof(scafContigIndex_t)); if((*scafContigIndex)==NULL) { printf("line=%d, In %s(), cannot allocate memory, error!\n", __LINE__, __func__); return FAILED; } // initialize k-mer block if(initScafKmerBlockInGraph(*scafContigIndex)==FAILED) { printf("line=%d, In %s(), cannot initialize the scafKmer blocks in k-mer hash table, error!\n", __LINE__, __func__); return FAILED; } // initialize kmerseq block if(initScafKmerseqBlockInGraph(*scafContigIndex)==FAILED) { printf("line=%d, In %s(), cannot initialize the kmerseq blocks in k-mer hash table, error!\n", __LINE__, __func__); return FAILED; } return SUCCESSFUL; } /** * Release the contig index. */ void releaseScafContigIndex(scafContigIndex_t **scafContigIndex) { int32_t i; if((*scafContigIndex)==NULL) return; // free k-mer blocks if((*scafContigIndex)->kmerBlockArr) { for(i=0; i<(*scafContigIndex)->blocksNumKmer; i++) free((*scafContigIndex)->kmerBlockArr[i].kmerArr); (*scafContigIndex)->blocksNumKmer = 0; free((*scafContigIndex)->kmerBlockArr); (*scafContigIndex)->kmerBlockArr = NULL; } if((*scafContigIndex)->kmerHashtable) { free((*scafContigIndex)->kmerHashtable); (*scafContigIndex)->kmerHashtable = NULL; } // free kmerseq blocks if((*scafContigIndex)->kmerSeqBlockArr) { for(i=0; i<(*scafContigIndex)->blocksNumKmerSeq; i++) free((*scafContigIndex)->kmerSeqBlockArr[i].kmerSeqArr); (*scafContigIndex)->blocksNumKmerSeq = 0; free((*scafContigIndex)->kmerSeqBlockArr); (*scafContigIndex)->kmerSeqBlockArr = NULL; } // free contigpos blocks if((*scafContigIndex)->contigposBlockArr) { for(i=0; i<(*scafContigIndex)->blocksNumContigpos; i++) free((*scafContigIndex)->contigposBlockArr[i].contigposArr); (*scafContigIndex)->blocksNumContigpos = 0; free((*scafContigIndex)->contigposBlockArr); (*scafContigIndex)->contigposBlockArr = NULL; } // free index node free(*scafContigIndex); *scafContigIndex = NULL; } /** * Initialize scafKmer blocks. * @return: * If succeeds, return SUCCESSFUL; otherwise, return FAILED. */ short initScafKmerBlockInGraph(scafContigIndex_t *scafContigIndex) { scafContigIndex->bytesPerKmer = sizeof(scafKmer_t); scafContigIndex->totalItemNumKmer = 0; scafContigIndex->maxBlocksNumKmer = MAX_BLOCKS_NUM_KMER; scafContigIndex->maxItemNumPerKmerBlock = BLOCK_SIZE_PER_KMER / scafContigIndex->bytesPerKmer; scafContigIndex->hashTableSize = hashTableSize; scafContigIndex->kmerHashtable = (kmerHashBucket_t *) calloc (scafContigIndex->hashTableSize, sizeof(kmerHashBucket_t)); if( scafContigIndex->kmerHashtable == NULL ) { printf("line=%d, In %s(), cannot allocate memory, Error!\n", __LINE__, __func__); return FAILED; } // allocate scafKmer blocks scafContigIndex->kmerBlockArr = (scafKmerBlock_t *) calloc(scafContigIndex->maxBlocksNumKmer, sizeof(scafKmerBlock_t)); if( scafContigIndex->kmerBlockArr == NULL ) { printf("line=%d, In %s(), cannot allocate memory, Error!\n", __LINE__, __func__); return FAILED; } scafContigIndex->blocksNumKmer = 0; // add new scafKmer block if(addNewBlockScafKmer(scafContigIndex)==FAILED) { printf("line=%d, In %s(), cannot allocate memory, Error!\n", __LINE__, __func__); return FAILED; } return SUCCESSFUL; } /** * Add new scafKmer block. * @return: * If succeeds, return SUCCESSFUL; otherwise, return FAILED. */ short addNewBlockScafKmer(scafContigIndex_t *scafContigIndex) { if(scafContigIndex->blocksNumKmer>=scafContigIndex->maxBlocksNumKmer) { scafContigIndex->kmerBlockArr = (scafKmerBlock_t *) realloc (scafContigIndex->kmerBlockArr, scafContigIndex->maxBlocksNumKmer*2*sizeof(scafKmerBlock_t)); if(scafContigIndex->kmerBlockArr==NULL) { printf("line=%d, In %s(), cannot allocate memory, error!\n", __LINE__, __func__); return FAILED; } scafContigIndex->maxBlocksNumKmer *= 2; } scafContigIndex->kmerBlockArr[scafContigIndex->blocksNumKmer].kmerArr = (scafKmer_t *) calloc (scafContigIndex->maxItemNumPerKmerBlock, scafContigIndex->bytesPerKmer); if(scafContigIndex->kmerBlockArr[scafContigIndex->blocksNumKmer].kmerArr==NULL) { printf("line=%d, In %s(), cannot allocate the memory, Error!\n", __LINE__, __func__); return FAILED; } scafContigIndex->kmerBlockArr[scafContigIndex->blocksNumKmer].blockID = scafContigIndex->blocksNumKmer + 1; scafContigIndex->kmerBlockArr[scafContigIndex->blocksNumKmer].itemNum = 0; scafContigIndex->blocksNumKmer ++; return SUCCESSFUL; } /** * Initialize kmerseq blocks in contig index. * @return: * If succeeds, return SUCCESSFUL; otherwise, return FAILED. */ short initScafKmerseqBlockInGraph(scafContigIndex_t *scafContigIndex) { scafContigIndex->entriesPerKmer = entriesPerKmer; scafContigIndex->bytesPerKmerseq = entriesPerKmer * sizeof(uint64_t); scafContigIndex->totalItemNumKmerSeq = 0; scafContigIndex->maxBlocksNumKmerSeq = MAX_BLOCKS_NUM_KMER_SEQ; scafContigIndex->maxItemNumPerKmerSeqBlock = BLOCK_SIZE_PER_KMER_SEQ / scafContigIndex->bytesPerKmerseq; // allocate kmerseq blocks scafContigIndex->kmerSeqBlockArr = (kmerseqBlock_t *) malloc(scafContigIndex->maxBlocksNumKmerSeq * sizeof(kmerseqBlock_t)); if( scafContigIndex->kmerSeqBlockArr == NULL ) { printf("line=%d, In %s(), cannot allocate the kmerSeqBlockArr for the k-mer hash table, Error!\n", __LINE__, __func__); return FAILED; } scafContigIndex->blocksNumKmerSeq = 0; // add new kmerseq block if(addNewBlockScafKmerSeq(scafContigIndex)==FAILED) { printf("line=%d, In %s(), cannot allocate memory, Error!\n", __LINE__, __func__); return FAILED; } return SUCCESSFUL; } /** * Add new kmerseq block in contig index. * @return: * If succeeds, return SUCCESSFUL; otherwise, return FAILED. */ short addNewBlockScafKmerSeq(scafContigIndex_t *scafContigIndex) { if(scafContigIndex->blocksNumKmerSeq>=scafContigIndex->maxBlocksNumKmerSeq) { scafContigIndex->kmerSeqBlockArr = (kmerseqBlock_t *) realloc (scafContigIndex->kmerSeqBlockArr, scafContigIndex->maxBlocksNumKmerSeq*2*sizeof(kmerseqBlock_t)); if(scafContigIndex->kmerSeqBlockArr==NULL) { printf("line=%d, In %s(), cannot allocate memory, error!\n", __LINE__, __func__); return FAILED; } scafContigIndex->maxBlocksNumKmerSeq *= 2; } scafContigIndex->kmerSeqBlockArr[scafContigIndex->blocksNumKmerSeq].kmerSeqArr = (uint64_t *) calloc (scafContigIndex->maxItemNumPerKmerSeqBlock, scafContigIndex->bytesPerKmerseq); if(scafContigIndex->kmerSeqBlockArr[scafContigIndex->blocksNumKmerSeq].kmerSeqArr==NULL) { printf("line=%d, In %s(), cannot allocate the memory, Error!\n", __LINE__, __func__); return FAILED; } scafContigIndex->kmerSeqBlockArr[scafContigIndex->blocksNumKmerSeq].blockID = scafContigIndex->blocksNumKmerSeq + 1; scafContigIndex->kmerSeqBlockArr[scafContigIndex->blocksNumKmerSeq].itemNum = 0; scafContigIndex->blocksNumKmerSeq ++; return SUCCESSFUL; } /** * Count the scafKmer occurrences. * @return: * If succeeds, return SUCCESSFUL; otherwise, return FAILED. */ short countScafKmerOccs(scafContigIndex_t *scafContigIndex, contigGraph_t *contigGraph) { int32_t i, j, contigLen, startContigPos, endContigPos, basePos, baseInt, contigEndFlag; char *contigSeq; uint64_t *pKmerSeqIntDone, *pKmerSeqIntDoing, hashcode; kmerseqBlock_t *pKmerseqBlock; pKmerseqBlock = scafContigIndex->kmerSeqBlockArr + scafContigIndex->blocksNumKmerSeq - 1; scafContigIndex->pKmerSeqAdding = pKmerseqBlock->kmerSeqArr; for(i=0; i<contigGraph->itemNumContigItemArray; i++) { contigSeq = contigGraph->contigItemArray[i].contigSeq; contigLen = contigGraph->contigItemArray[i].contigLen; // 5' end startContigPos = 0; if(contigLen>2*contigAlignRegSize) { endContigPos = contigAlignRegSize - 1; contigEndFlag = 0; contigGraph->contigItemArray[i].alignRegSizeEnd5 = contigAlignRegSize; } else if(contigLen>contigAlignRegSize) { endContigPos = (contigLen - 1) / 2; contigEndFlag = 0; contigGraph->contigItemArray[i].alignRegSizeEnd5 = endContigPos + 1; }else { endContigPos = contigLen - 1; contigEndFlag = 2; // only the 5' end bacause of the short (<=2000 bp) contig contigGraph->contigItemArray[i].alignRegSizeEnd5 = contigLen; } pKmerSeqIntDoing = scafContigIndex->pKmerSeqAdding; // generate the first kmerseqInt if(generateReadseqInt(pKmerSeqIntDoing, contigSeq, kmerSize, entriesPerKmer)==FAILED) { printf("line=%d, In %s(), cannot generate the integer sequence, error!\n", __LINE__, __func__); return FAILED; } pKmerSeqIntDone = pKmerSeqIntDoing; // count the first scafKmer hashcode = kmerhashInt(pKmerSeqIntDoing); if(countScafKmer(hashcode, pKmerSeqIntDoing, scafContigIndex)==FAILED) { printf("line=%d, In %s(), cannot count kmer occurrence, error!\n", __LINE__, __func__); return FAILED; } // process other scafKmers for(basePos=kmerSize; basePos<=endContigPos; basePos++) { switch(contigSeq[basePos]) { case 'A': case 'a': baseInt = 0; break; case 'C': case 'c': baseInt = 1; break; case 'G': case 'g': baseInt = 2; break; case 'T': case 't': baseInt = 3; break; default: printf("line=%d, In %s(), invalid base %c, error!\n", __LINE__, __func__, contigSeq[basePos]); return FAILED; } pKmerSeqIntDoing = scafContigIndex->pKmerSeqAdding; // generate the kmer integer sequence if(entriesPerKmer>=2) { for(j=0; j<entriesPerKmer-2; j++) { pKmerSeqIntDoing[j] = (pKmerSeqIntDone[j] << 2) | (pKmerSeqIntDone[j+1] >> 62); } pKmerSeqIntDoing[entriesPerKmer-2] = (pKmerSeqIntDone[entriesPerKmer-2] << 2) | (pKmerSeqIntDone[entriesPerKmer-1] >> (2*lastEntryBaseNum-2)); } pKmerSeqIntDoing[entriesPerKmer-1] = ((pKmerSeqIntDone[entriesPerKmer-1] << 2) | baseInt) & lastEntryMask; pKmerSeqIntDone = pKmerSeqIntDoing; hashcode = kmerhashInt(pKmerSeqIntDoing); if(countScafKmer(hashcode, pKmerSeqIntDoing, scafContigIndex)==FAILED) { printf("line=%d, In %s(), cannot count kmer occurrence, error!\n", __LINE__, __func__); return FAILED; } } // 3' end if(contigLen<=contigAlignRegSize) { // do not the 3' end contigGraph->contigItemArray[i].alignRegSizeEnd3 = 0; continue; }else if(contigLen<=2*contigAlignRegSize) { // handle the 3' end startContigPos = contigLen - (contigLen - 1) / 2 - 1; contigEndFlag = 1; // the 3' end of the contig contigGraph->contigItemArray[i].alignRegSizeEnd3 = contigLen - startContigPos; }else { // handle the 3' end startContigPos = contigLen - contigAlignRegSize; contigEndFlag = 1; // the 3' end of the contig contigGraph->contigItemArray[i].alignRegSizeEnd3 = contigAlignRegSize; } endContigPos = contigLen - 1; pKmerSeqIntDoing = scafContigIndex->pKmerSeqAdding; // generate the first kmerseqInt if(generateReadseqInt(pKmerSeqIntDoing, contigSeq+startContigPos, kmerSize, entriesPerKmer)==FAILED) { printf("line=%d, In %s(), cannot generate the integer sequence, error!\n", __LINE__, __func__); return FAILED; } pKmerSeqIntDone = pKmerSeqIntDoing; // count the first scafKmer hashcode = kmerhashInt(pKmerSeqIntDoing); if(countScafKmer(hashcode, pKmerSeqIntDoing, scafContigIndex)==FAILED) { printf("line=%d, In %s(), cannot count kmer occurrence, error!\n", __LINE__, __func__); return FAILED; } // process other scafKmers for(basePos=startContigPos+kmerSize; basePos<=endContigPos; basePos++) { switch(contigSeq[basePos]) { case 'A': case 'a': baseInt = 0; break; case 'C': case 'c': baseInt = 1; break; case 'G': case 'g': baseInt = 2; break; case 'T': case 't': baseInt = 3; break; default: printf("line=%d, In %s(), invalid base %c, error!\n", __LINE__, __func__, contigSeq[basePos]); return FAILED; } pKmerSeqIntDoing = scafContigIndex->pKmerSeqAdding; // generate the kmer integer sequence if(entriesPerKmer>=2) { for(j=0; j<entriesPerKmer-2; j++) { pKmerSeqIntDoing[j] = (pKmerSeqIntDone[j] << 2) | (pKmerSeqIntDone[j+1] >> 62); } pKmerSeqIntDoing[entriesPerKmer-2] = (pKmerSeqIntDone[entriesPerKmer-2] << 2) | (pKmerSeqIntDone[entriesPerKmer-1] >> (2*lastEntryBaseNum-2)); } pKmerSeqIntDoing[entriesPerKmer-1] = ((pKmerSeqIntDone[entriesPerKmer-1] << 2) | baseInt) & lastEntryMask; pKmerSeqIntDone = pKmerSeqIntDoing; hashcode = kmerhashInt(pKmerSeqIntDoing); if(countScafKmer(hashcode, pKmerSeqIntDoing, scafContigIndex)==FAILED) { printf("line=%d, In %s(), cannot count kmer occurrence, error!\n", __LINE__, __func__); return FAILED; } } } // the last k-mer block is empty, remove it if(scafContigIndex->kmerBlockArr[scafContigIndex->blocksNumKmer-1].itemNum==0) { free(scafContigIndex->kmerBlockArr[scafContigIndex->blocksNumKmer-1].kmerArr); scafContigIndex->kmerBlockArr[scafContigIndex->blocksNumKmer-1].kmerArr = NULL; scafContigIndex->blocksNumKmer --; } // the last kmerseq block is empty, remove it if(scafContigIndex->kmerSeqBlockArr[scafContigIndex->blocksNumKmerSeq-1].itemNum==0) { free(scafContigIndex->kmerSeqBlockArr[scafContigIndex->blocksNumKmerSeq-1].kmerSeqArr); scafContigIndex->kmerSeqBlockArr[scafContigIndex->blocksNumKmerSeq-1].kmerSeqArr = NULL; scafContigIndex->blocksNumKmerSeq --; } return SUCCESSFUL; } /** * Count the k-mer occurrences. * @return: * If succeeds, return SUCCESSFUL; otherwise, return FAILED. */ short countScafKmer(uint64_t hashcode, uint64_t *kmerSeqInt, scafContigIndex_t *scafContigIndex) { scafKmer_t *kmer; scafKmerBlock_t *pKmerBlock; kmerseqBlock_t *pKmerseqBlock; kmer = getScafKmerByHash(hashcode, kmerSeqInt, scafContigIndex); if(!kmer) { // process k-mer blocks pKmerBlock = scafContigIndex->kmerBlockArr + scafContigIndex->blocksNumKmer - 1; kmer = pKmerBlock->kmerArr + pKmerBlock->itemNum; kmer->kmerseqBlockID = pKmerBlock->blockID; kmer->itemRowKmerseqBlock = pKmerBlock->itemNum; kmer->arraysize = 1; kmer->nextKmerBlockID = scafContigIndex->kmerHashtable[hashcode].kmerBlockID; kmer->nextItemRowKmerBlock = scafContigIndex->kmerHashtable[hashcode].itemRowKmerBlock; scafContigIndex->kmerHashtable[hashcode].kmerBlockID = kmer->kmerseqBlockID; scafContigIndex->kmerHashtable[hashcode].itemRowKmerBlock = kmer->itemRowKmerseqBlock; pKmerBlock->itemNum ++; scafContigIndex->totalItemNumKmer ++; if(pKmerBlock->itemNum >= scafContigIndex->maxItemNumPerKmerBlock) { // add new kmer block if(addNewBlockScafKmer(scafContigIndex)==FAILED) { printf("line=%d, In %s(), cannot add new k-mer block, Error!\n", __LINE__, __func__); return FAILED; } } // process kmerseq blocks pKmerseqBlock = scafContigIndex->kmerSeqBlockArr + scafContigIndex->blocksNumKmerSeq - 1; kmer->kmerseqBlockID = pKmerseqBlock->blockID; kmer->itemRowKmerseqBlock = pKmerseqBlock->itemNum; pKmerseqBlock->itemNum ++; scafContigIndex->totalItemNumKmerSeq ++; scafContigIndex->pKmerSeqAdding += scafContigIndex->entriesPerKmer; if(pKmerseqBlock->itemNum >= scafContigIndex->maxItemNumPerKmerSeqBlock) { // add new kmerseq block if(addNewBlockScafKmerSeq(scafContigIndex)==FAILED) { printf("line=%d, In %s(), cannot add new kmerseq block, Error!\n", __LINE__, __func__); return FAILED; } scafContigIndex->pKmerSeqAdding = scafContigIndex->kmerSeqBlockArr[scafContigIndex->blocksNumKmerSeq-1].kmerSeqArr; } }else { kmer->arraysize ++; } return SUCCESSFUL; } scafKmer_t *getScafKmerByHash(uint64_t hashvalue, uint64_t *kmerSeqInt, scafContigIndex_t *scafContigIndex) { scafKmer_t *kmer; uint64_t *kmerseq; kmerHashBucket_t *pKmerBucket; pKmerBucket = scafContigIndex->kmerHashtable + hashvalue; if(pKmerBucket->kmerBlockID>0) { kmer = scafContigIndex->kmerBlockArr[pKmerBucket->kmerBlockID-1].kmerArr + pKmerBucket->itemRowKmerBlock; while(kmer) { kmerseq = scafContigIndex->kmerSeqBlockArr[kmer->kmerseqBlockID-1].kmerSeqArr + kmer->itemRowKmerseqBlock * scafContigIndex->entriesPerKmer; if(identicalKmerSeq(kmerSeqInt, kmerseq)==YES) break; if(kmer->nextKmerBlockID>0) kmer = scafContigIndex->kmerBlockArr[kmer->nextKmerBlockID-1].kmerArr + kmer->nextItemRowKmerBlock; else kmer = NULL; } }else { kmer = NULL; } return kmer; } /** * Add the k-mer contigpos information. * @return: * If succeeds, return SUCCESSFUL; otherwise, return FAILED. */ short addScafKmerContigpos(scafContigIndex_t *scafContigIndex, contigGraph_t *contigGraph) { int32_t i, j, contigID, contigLen, startContigPos, contigPos, endContigPos, basePos, baseInt, contigEndFlag; char *contigSeq; uint64_t pKmerSeqInt[entriesPerKmer], hashcode; // initialize contigpos blocks and the ridpos regions in that blocks if(initContigposBlocksInContigIndex(scafContigIndex)==FAILED) { printf("line=%d, In %s(), cannot allocate memory, Error!\n", __LINE__, __func__); return FAILED; } for(i=0; i<contigGraph->itemNumContigItemArray; i++) { contigID = contigGraph->contigItemArray[i].contigID; contigSeq = contigGraph->contigItemArray[i].contigSeq; contigLen = contigGraph->contigItemArray[i].contigLen; // 5' end startContigPos = 0; contigPos = 1; endContigPos = contigGraph->contigItemArray[i].alignRegSizeEnd5 - 1; if(contigGraph->contigItemArray[i].alignRegSizeEnd3>0) contigEndFlag = 0; else contigEndFlag = 2; // generate the first kmerseqInt if(generateReadseqInt(pKmerSeqInt, contigSeq, kmerSize, entriesPerKmer)==FAILED) { printf("line=%d, In %s(), cannot generate the integer sequence, error!\n", __LINE__, __func__); return FAILED; } // count the first scafKmer hashcode = kmerhashInt(pKmerSeqInt); if(addScafKmer(hashcode, pKmerSeqInt, contigID, contigPos, contigEndFlag, scafContigIndex)==FAILED) { printf("line=%d, In %s(), cannot add kmer occurrence, error!\n", __LINE__, __func__); return FAILED; } contigPos ++; // process other scafKmers for(basePos=kmerSize; basePos<=endContigPos; basePos++, contigPos++) { switch(contigSeq[basePos]) { case 'A': case 'a': baseInt = 0; break; case 'C': case 'c': baseInt = 1; break; case 'G': case 'g': baseInt = 2; break; case 'T': case 't': baseInt = 3; break; default: printf("line=%d, In %s(), invalid base %c, error!\n", __LINE__, __func__, contigSeq[basePos]); return FAILED; } // generate the kmer integer sequence if(entriesPerKmer>=2) { for(j=0; j<entriesPerKmer-2; j++) { pKmerSeqInt[j] = (pKmerSeqInt[j] << 2) | (pKmerSeqInt[j+1] >> 62); } pKmerSeqInt[entriesPerKmer-2] = (pKmerSeqInt[entriesPerKmer-2] << 2) | (pKmerSeqInt[entriesPerKmer-1] >> (2*lastEntryBaseNum-2)); } pKmerSeqInt[entriesPerKmer-1] = ((pKmerSeqInt[entriesPerKmer-1] << 2) | baseInt) & lastEntryMask; hashcode = kmerhashInt(pKmerSeqInt); if(addScafKmer(hashcode, pKmerSeqInt, contigID, contigPos, contigEndFlag, scafContigIndex)==FAILED) { printf("line=%d, In %s(), cannot count kmer occurrence, error!\n", __LINE__, __func__); return FAILED; } } // 3' end if(contigGraph->contigItemArray[i].alignRegSizeEnd3<=0) { continue; }else { contigEndFlag = 1; // the 3' end of the contig } //startContigPos = contigLen - contigAlignRegSize; startContigPos = contigLen - contigGraph->contigItemArray[i].alignRegSizeEnd3; endContigPos = contigLen - 1; contigPos = startContigPos + 1; // generate the first kmerseqInt if(generateReadseqInt(pKmerSeqInt, contigSeq+startContigPos, kmerSize, entriesPerKmer)==FAILED) { printf("line=%d, In %s(), cannot generate the integer sequence, error!\n", __LINE__, __func__); return FAILED; } // count the first scafKmer hashcode = kmerhashInt(pKmerSeqInt); if(addScafKmer(hashcode, pKmerSeqInt, contigID, contigPos, contigEndFlag, scafContigIndex)==FAILED) { printf("line=%d, In %s(), cannot add kmer occurrence, error!\n", __LINE__, __func__); return FAILED; } contigPos ++; // process other scafKmers for(basePos=startContigPos+kmerSize; basePos<=endContigPos; basePos++, contigPos++) { switch(contigSeq[basePos]) { case 'A': case 'a': baseInt = 0; break; case 'C': case 'c': baseInt = 1; break; case 'G': case 'g': baseInt = 2; break; case 'T': case 't': baseInt = 3; break; default: printf("line=%d, In %s(), invalid base %c, error!\n", __LINE__, __func__, contigSeq[basePos]); return FAILED; } // generate the kmer integer sequence if(entriesPerKmer>=2) { for(j=0; j<entriesPerKmer-2; j++) { pKmerSeqInt[j] = (pKmerSeqInt[j] << 2) | (pKmerSeqInt[j+1] >> 62); } pKmerSeqInt[entriesPerKmer-2] = (pKmerSeqInt[entriesPerKmer-2] << 2) | (pKmerSeqInt[entriesPerKmer-1] >> (2*lastEntryBaseNum-2)); } pKmerSeqInt[entriesPerKmer-1] = ((pKmerSeqInt[entriesPerKmer-1] << 2) | baseInt) & lastEntryMask; hashcode = kmerhashInt(pKmerSeqInt); if(addScafKmer(hashcode, pKmerSeqInt, contigID, contigPos, contigEndFlag, scafContigIndex)==FAILED) { printf("line=%d, In %s(), cannot count kmer occurrence, error!\n", __LINE__, __func__); return FAILED; } } } return SUCCESSFUL; } /** * Initialize contigpos block in contig index. * @return: * If succeeds, return SUCCESSFUL; otherwise, return FAILED. */ short initContigposBlocksInContigIndex(scafContigIndex_t *scafContigIndex) { int64_t i, j, totalNum, sum; scafKmer_t *kmer; uint32_t blocksNumKmer, itemNumKmerBlock; scafContigIndex->bytesPerContigpos = sizeof(scafContigposBlock_t); scafContigIndex->blocksNumContigpos = 0; scafContigIndex->totalItemNumContigpos = 0; scafContigIndex->maxBlocksNumContigpos = MAX_BLOCKS_NUM_RIDPOS; scafContigIndex->maxItemNumPerContigposBlock = BLOCK_SIZE_PER_RIDPOS / scafContigIndex->bytesPerContigpos; // add contigpos block head nodes scafContigIndex->contigposBlockArr = (scafContigposBlock_t *) malloc (scafContigIndex->maxBlocksNumContigpos * sizeof(scafContigposBlock_t)); if(scafContigIndex->contigposBlockArr==NULL) { printf("line=%d, In %s(), cannot allocate memory, error!\n", __LINE__, __func__); return FAILED; } // add new contigpos block if(addNewBlockContigpos(scafContigIndex)==FAILED) { printf("line=%d, In %s(), cannot allocate memory, Error!\n", __LINE__, __func__); return FAILED; } // set start ridpos regions and allocate ridpos blocks totalNum = sum = 0; blocksNumKmer = scafContigIndex->blocksNumKmer; for(i=0; i<blocksNumKmer; i++) { kmer = scafContigIndex->kmerBlockArr[i].kmerArr; itemNumKmerBlock = scafContigIndex->kmerBlockArr[i].itemNum; for(j=0; j<itemNumKmerBlock; j++) { kmer->ppos = scafContigIndex->contigposBlockArr[scafContigIndex->blocksNumContigpos-1].contigposArr + sum; sum += kmer->arraysize; if(sum >= scafContigIndex->maxItemNumPerContigposBlock) { if(sum > scafContigIndex->maxItemNumPerContigposBlock) { sum -= kmer->arraysize; scafContigIndex->contigposBlockArr[scafContigIndex->blocksNumContigpos-1].itemNum = sum; totalNum += sum; // add new ridpos block if(addNewBlockContigpos(scafContigIndex)==FAILED) { printf("line=%d, In %s(), cannot allocate memory, Error!\n", __LINE__, __func__); return FAILED; } kmer->ppos = scafContigIndex->contigposBlockArr[scafContigIndex->blocksNumContigpos-1].contigposArr; sum = kmer->arraysize; }else { scafContigIndex->contigposBlockArr[scafContigIndex->blocksNumContigpos-1].itemNum = sum; totalNum += sum; // add new contigpos block if(addNewBlockContigpos(scafContigIndex)==FAILED) { printf("line=%d, In %s(), cannot allocate memory, Error!\n", __LINE__, __func__); return FAILED; } sum = 0; } } kmer ++; } } // process the last contigpos block if(sum==0) { // remove the last contigpos block if it is empty free(scafContigIndex->contigposBlockArr[scafContigIndex->blocksNumContigpos-1].contigposArr); scafContigIndex->contigposBlockArr[scafContigIndex->blocksNumContigpos-1].contigposArr = NULL; scafContigIndex->contigposBlockArr[scafContigIndex->blocksNumContigpos-1].blockID = 0; scafContigIndex->contigposBlockArr[scafContigIndex->blocksNumContigpos-1].itemNum = 0; scafContigIndex->blocksNumContigpos --; }else { scafContigIndex->contigposBlockArr[scafContigIndex->blocksNumContigpos-1].itemNum = sum; totalNum += sum; } scafContigIndex->totalItemNumContigpos = totalNum; return SUCCESSFUL; } /** * Add new contigpos block. * @return: * If succeeds, return SUCCESSFUL; otherwise, return FAILED. */ short addNewBlockContigpos(scafContigIndex_t *scafContigIndex) { if(scafContigIndex->blocksNumContigpos>=scafContigIndex->maxBlocksNumContigpos) { scafContigIndex->contigposBlockArr = (scafContigposBlock_t *) realloc (scafContigIndex->contigposBlockArr, scafContigIndex->maxBlocksNumContigpos*2*sizeof(scafContigposBlock_t)); if(scafContigIndex->contigposBlockArr==NULL) { printf("line=%d, In %s(), cannot allocate memory, error!\n", __LINE__, __func__); return FAILED; } scafContigIndex->maxBlocksNumContigpos *= 2; } scafContigIndex->contigposBlockArr[scafContigIndex->blocksNumContigpos].contigposArr = (scafContigpos_t *) calloc (scafContigIndex->maxItemNumPerContigposBlock, scafContigIndex->bytesPerContigpos); if(scafContigIndex->contigposBlockArr[scafContigIndex->blocksNumContigpos].contigposArr==NULL) { printf("line=%d, In %s(), cannot allocate the memory, Error!\n", __LINE__, __func__); return FAILED; } scafContigIndex->contigposBlockArr[scafContigIndex->blocksNumContigpos].blockID = scafContigIndex->blocksNumContigpos + 1; scafContigIndex->contigposBlockArr[scafContigIndex->blocksNumContigpos].itemNum = 0; scafContigIndex->blocksNumContigpos ++; return SUCCESSFUL; } /** * Add a kmer to graph. * @return: * If succeeds, return SUCCESSFUL; otherwise, return FAILED. */ short addScafKmer(uint64_t hashcode, uint64_t *kmerSeqInt, int32_t contigID, int32_t contigPos, int32_t contigEndFlag, scafContigIndex_t *scafContigIndex) { scafKmer_t *kmer; scafContigpos_t *contigpos; kmer = getScafKmerByHash(hashcode, kmerSeqInt, scafContigIndex); if(kmer) { contigpos = kmer->ppos + kmer->multiplicity; contigpos->contigID = contigID; contigpos->contigpos = contigPos; contigpos->contigEndFlag = contigEndFlag; kmer->multiplicity ++; }else { printf("line=%d, In %s(), can not get the k-mer %s, error!\n", __LINE__, __func__, getKmerBaseByInt(kmerSeqInt)); return FAILED; } return SUCCESSFUL; }
C
#include <stdio.h> #include <stdlib.h> void remove_duplicates(int n,int *a); void remove_duplicates(int n,int *a) { int c,*b,count=0,d; b=(int*)malloc(n*sizeof(int)); for (c = 0; c < n; c++) { for (d = 0; d < count; d++) { if(a[c] == b[d]) break; } if (d == count) { b[count] = a[c]; count++; } } for (c = 0; c < count; c++) printf("%d\n", b[c]); } int main() { int n, c; int *a; scanf("%d", &n); //no. of elements in array a=(int*)malloc(n*sizeof(int)); for (c = 0; c < n; c++) scanf("%d", &a[c]); remove_duplicates(n,a); return 0; }
C
/****************************************************************************** * tcp_server.c * * CPE 464 - Program 1 * Lance Boettcher *****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/uio.h> #include <sys/time.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <strings.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include "networks.h" #include "tcp_server.h" #include "packets.h" #include "testing.h" struct tcpServer tcpServer; int main(int argc, char *argv[]) { initServer(argc, argv); runServer(); return 0; } void initServer(int argc, char *argv[]) { /* Create server Socket */ if (argc > 1) tcpServer.serverSocket = tcp_recv_setup(atoi(argv[1])); else tcpServer.serverSocket = tcp_recv_setup(0); tcpServer.sequence = 1; addClient(tcp_listen(tcpServer.serverSocket, 5)); } void runServer() { int max, newClient; struct client *clientIterator; while (1) { /* Clear fds */ FD_ZERO(&tcpServer.openFds); /* Add the server socket */ FD_SET(tcpServer.serverSocket, &tcpServer.openFds); max = tcpServer.serverSocket; /* Add all the client sockets */ clientIterator = tcpServer.clientList; while (clientIterator != NULL) { FD_SET(clientIterator->socket, &tcpServer.openFds); if (clientIterator->socket > max) max = clientIterator->socket; clientIterator = clientIterator->next; } /* Wait for something to happen */ if (select(max + 1, &tcpServer.openFds , NULL , NULL , NULL) < 0) { perror("Error with select\n"); exit(-1); } /* If activity on server socket -> new connection */ if (FD_ISSET(tcpServer.serverSocket, &tcpServer.openFds)) { /* Accept the new client */ if ((newClient = accept(tcpServer.serverSocket, (struct sockaddr*) 0, (socklen_t *) 0)) < 0) { perror("Error accepting new client \n"); exit(-1); } /* Add the new client to our list */ addClient(newClient); } /* If other client active -> handle it */ clientIterator = tcpServer.clientList; while (clientIterator != NULL) { if (FD_ISSET(clientIterator->socket, &tcpServer.openFds)) { handleActiveClient(clientIterator->socket); } clientIterator = clientIterator->next; } } } void handleActiveClient(int activeClient) { int messageLength; char buffer[BUFFER_SIZE]; if ((messageLength = recv(activeClient, buffer, BUFFER_SIZE, 0)) < 0) { perror("Error reading active client \n"); exit(-1); } /* Client disconnected */ if (messageLength == 0) removeClient(activeClient); else { /* Read message */ struct header *header = (struct header *)buffer; switch (header->flag) { case 1: /* Client init packet */ handleClientInit(activeClient, buffer); break; case 4: /* Broadcast packet */ handleClientBroadcast(activeClient, buffer); break; case 5: /* Message packet */ handleClientMessage(activeClient, buffer, messageLength); break; case 8: /* Client exit packet */ handleClientExit(activeClient, buffer); break; case 10: /* Client list handle packet */ handleClientListHandles(activeClient, buffer); break; } } } void handleClientInit(int socket, char *packet) { struct initCtoS *initPacket = (struct initCtoS *) packet; char handle[MAX_HANDLE_LENGTH + 1]; int sent; struct header *ackPacket; memcpy(handle, &initPacket->handleLength + 1, initPacket->handleLength); handle[initPacket->handleLength] = '\0'; ackPacket = (struct header *) malloc(sizeof(struct header)); ackPacket->sequence = tcpServer.sequence++; ackPacket->length = htons(sizeof(struct header)); if (existingHandle(handle)) { /* Invalid Handle, send error packet back */ ackPacket->flag = 3; } else { /* Valid handle, update list and send approval to client */ setHandle(socket, handle); ackPacket->flag = 2; } /* Send the response packet */ sent = send(socket, ackPacket, ntohs(ackPacket->length), 0); if (sent < 0) { printf("Error sending ack init \n"); } } void handleClientBroadcast(int socket, char *packet) { char *packetIter = packet; int destSocket, srcSocket, sent; struct client *clientIterator; struct header *packetHeader = (struct header *) packet; packetIter += sizeof(struct header); /* Get the src handle and length from the packet */ uint8_t srcHandleLength = *packetIter++; char srcHandle[MAX_HANDLE_LENGTH]; memcpy(srcHandle, packetIter, srcHandleLength); packetIter += srcHandleLength; srcHandle[srcHandleLength] = '\0'; srcSocket = getClientSocket(srcHandle); /* Forward the packet to all clients */ clientIterator = tcpServer.clientList; while (clientIterator != NULL) { destSocket = clientIterator->socket; /* Don't send message to source */ if (destSocket == srcSocket) { clientIterator = clientIterator->next; continue; } sent = send(destSocket, packet, ntohs(packetHeader->length), 0); if (sent < 0) { printf("Error sending broadcast \n"); } clientIterator = clientIterator->next; } } void handleClientMessage(int socket, char *packet, int lengthReceived) { char *packetIter = packet; char *responsePacket; struct header responseHeader; int validDest; struct header *header = (struct header *) packet; packetIter += sizeof(struct header); /* Get the dest handle and length from the packet */ uint8_t destHandleLength = *packetIter++; char destHandle[MAX_HANDLE_LENGTH]; memcpy(destHandle, packetIter, destHandleLength); packetIter += destHandleLength; destHandle[destHandleLength] = '\0'; /* Prepare a response packet */ responseHeader.sequence = tcpServer.sequence++; responseHeader.length = htons(sizeof(struct header) + destHandleLength + 1); if (!existingHandle(destHandle)) { /* handle does not exist, send flag = 7 back */ responseHeader.flag = 7; validDest = 0; } else { /* valid handle, send flag = 6 back */ responseHeader.flag = 6; validDest = 1; } responsePacket = malloc(sizeof(struct header) + destHandleLength + 1); packetIter = responsePacket; /* Copy the dest handle length and handle */ memcpy(responsePacket, &responseHeader, sizeof(struct header)); packetIter += sizeof(struct header); *packetIter++ = destHandleLength; memcpy(packetIter, &destHandle, destHandleLength); /* Send the response packet */ int sent = send(socket, responsePacket, ntohs(responseHeader.length), 0); if (sent < 0) { printf("Error sending message response \n"); } if (validDest) { /* Forward the message to dest if valid dest handle */ int destSocket = getClientSocket(destHandle); int lengthRemaining = ntohs(header->length) - lengthReceived; int messageLength; char *buffer[BUFFER_SIZE]; sent = send(destSocket, packet, lengthReceived, 0); if (sent < 0) { printf("Error Forwarding message\n"); } while (lengthRemaining > 0) { printf("Length remaining: %d\n", lengthRemaining); if ((messageLength = recv(socket, buffer, BUFFER_SIZE, 0)) < 0) { perror("Error receiving overflow message\n"); exit(-1); } if (messageLength == 0) { perror("Client terminated while receiving overflow\n"); } sent = send(destSocket, buffer, messageLength, 0); if (sent < 0) { perror("Error Forwarding message \n"); } lengthRemaining -= messageLength; } } } void handleClientExit(int socket, char *packet) { int sent; /* Prepare the ack packet */ struct header *ackPacket = (struct header *) malloc(sizeof(struct header)); ackPacket->sequence = tcpServer.sequence++; ackPacket->length = htons(sizeof(struct header)); ackPacket->flag = 9; /* Send the ack packet */ sent = send(socket, ackPacket, ntohs(ackPacket->length), 0); if (sent < 0) { printf("Error sending ack init \n"); } } void handleClientListHandles(int socket, char *packet) { struct header responseHeader; char *responsePacket, *packetIter; int sent, totalHandleLength = 0; uint8_t handleLength; struct client *clientIterator; /* Prepare flag = 11 packet */ responseHeader.sequence = tcpServer.sequence++; responseHeader.length = htons(sizeof(struct header) + sizeof(uint32_t)); responseHeader.flag = 11; responsePacket = malloc(ntohs(responseHeader.length)); packetIter = responsePacket; /* Copy the header */ memcpy(responsePacket, &responseHeader, ntohs(responseHeader.length)); packetIter += sizeof(struct header); /* Copy the number of handles */ *(uint32_t *)packetIter = htonl(tcpServer.numClients); /* Send the num handles packet */ sent = send(socket, responsePacket, ntohs(responseHeader.length), 0); if (sent < 0) { printf("Error sending list handle number message response \n"); } /* Prepare flag = 12 packet */ responseHeader.sequence = tcpServer.sequence++; responseHeader.length = 0; //This is supposed to be zero responseHeader.flag = 12; responsePacket = malloc(BUFFER_SIZE); packetIter = responsePacket; /* Copy the header */ memcpy(responsePacket, &responseHeader, sizeof(struct header)); packetIter += sizeof(struct header); /* Copy the handles and lengths */ clientIterator = tcpServer.clientList; while (clientIterator != NULL) { handleLength = strlen(clientIterator->handle); totalHandleLength += handleLength + 1; *packetIter++ = handleLength; memcpy(packetIter, clientIterator->handle, handleLength); packetIter += handleLength; clientIterator = clientIterator->next; } sent = send(socket, responsePacket, sizeof(struct header) + totalHandleLength, 0); if (sent < 0) { printf("Error sending list handle handles response \n"); } } int existingHandle(char *handle) { struct client *clientIterator; clientIterator = tcpServer.clientList; while (clientIterator != NULL) { if (strcmp(clientIterator->handle, handle) == 0) { return 1; } clientIterator = clientIterator->next; } return 0; } void setHandle(int socket, char *handle) { struct client *clientIterator; clientIterator = tcpServer.clientList; while (clientIterator != NULL) { if (clientIterator->socket == socket) { strcpy(clientIterator->handle, handle); break; } clientIterator = clientIterator->next; } } int getClientSocket(char *handle) { struct client *clientIterator; clientIterator = tcpServer.clientList; while (clientIterator != NULL) { if (strcmp(clientIterator->handle, handle) == 0) { return clientIterator->socket; } clientIterator = clientIterator->next; } return -1; } void addClient(int socket) { struct client *newClient = (struct client *) malloc(sizeof(struct client)); newClient->socket = socket; newClient->next = NULL; *newClient->handle = '\0'; if (tcpServer.clientList == NULL) tcpServer.clientList = newClient; else { struct client *iterator = tcpServer.clientList; while (iterator->next != NULL) iterator = iterator->next; iterator->next = newClient; } tcpServer.numClients++; } void removeClient(int socket) { struct client *iterator = tcpServer.clientList; if (iterator->next == NULL) { if (iterator->socket == socket) tcpServer.clientList = NULL; } else if (iterator->socket == socket) { /* Remove the first item in the list */ tcpServer.clientList = iterator->next; } else { while (iterator->next->socket != socket) iterator = iterator->next; iterator->next = iterator->next->next; } close(socket); tcpServer.numClients--; } /* This function sets the server socket. It lets the system determine the port number. The function returns the server socket number and prints the port number to the screen. */ int tcp_recv_setup(int portNumber) { int server_socket= 0; struct sockaddr_in local; /* socket address for local side */ socklen_t len= sizeof(local); /* length of local address */ /* create the socket */ server_socket= socket(AF_INET, SOCK_STREAM, 0); if(server_socket < 0) { perror("socket call"); exit(1); } local.sin_family= AF_INET; //internet family local.sin_addr.s_addr= INADDR_ANY; //wild card machine address local.sin_port= htons(portNumber); /* bind the name (address) to a port */ if (bind(server_socket, (struct sockaddr *) &local, sizeof(local)) < 0) { perror("bind call"); exit(-1); } //get the port name and print it out if (getsockname(server_socket, (struct sockaddr*)&local, &len) < 0) { perror("getsockname call"); exit(-1); } printf("Server is using port %d\n", ntohs(local.sin_port)); return server_socket; } /* This function waits for a client to ask for services. It returns the socket number to service the client on. */ int tcp_listen(int server_socket, int back_log) { int client_socket= 0; if (listen(server_socket, back_log) < 0) { perror("listen call"); exit(-1); } if ((client_socket= accept(server_socket, (struct sockaddr*)0, (socklen_t *)0)) < 0) { perror("accept call"); exit(-1); } return(client_socket); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> int dp[700][700][700]; int solv(int i, int j, int k) { int first, second, third, forth; int min; if(i==0 || j==0 || k==0) return 1; if(dp[i][j][k]>=0) return dp[i][j][k]; if(dp[i-1][j-1][k-1]>=0) first=dp[i-1][j-1][k-1]; else{ first=solv(i-1, j-1, k-1); dp[i-1][j-1][k-1]=first; } if(dp[i>>1][j-1][k>>1]>=0) second=dp[i>>1][j-1][k>>1]; else{ second=solv(i>>1, j-1, k>>1); dp[i>>1][j-1][k>>1]=second; } if(dp[i>>2][j>>2][k/5]>=0) third=dp[i>>2][j>>2][k/5]; else{ third=solv(i>>2, j>>2, k/5); dp[i>>2][j>>2][k/5]=third; } min=j-1>(third>>1)?(third>>1):j-1; if(dp[i>>1][min][k-1]>=0) forth=dp[i>>1][min][k-1]; else{ forth=solv(i>>1, min, k-1); dp[i>>1][min][k-1]=forth; } dp[i][j][k]=first/3+second+forth; return dp[i][j][k]; } int main() { int i, j, k; int result; scanf("%d%d%d", &i, &j, &k); memset(dp, -1, sizeof(dp)); result=solv(i, j, k); printf("%d\n", result); return 0; }
C
#include <stdio.h> int main(void){ int no; do{ printf("Please enter an integer:"); scanf("%d",&no); if (no<=0){ printf("Do not enter negative number"); }; }while(no<=0); printf("The reverse of the number is:"); while(no>0){ printf("%d",no%10); no/=10; }; puts("."); return 0; }
C
/* * ===================================================================================== * * Filename: getSubSeq.c * * Description: get sequences from a fasta file according to coordinates * * Version: 1.0 * Created: 2015/11/09 22时07分39秒 * Revision: none * Compiler: gcc * * Author: JIN Xiaoyang (jinxiaoyang@jinxiaoyang.cn) * Organization: IBP - CAS * * ===================================================================================== */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAXLEN 255 #define MAX_LINE_LEN 1024 /* #define DEBUG */ typedef struct faidx{ unsigned total_len; unsigned start_pos; unsigned valid_char_per_line; unsigned char_per_line; }faidx; void usage(const char* arg) { printf("Usage: %s [-q Query_String] [-f Fasta_File]\n", arg); printf("\te.g. %s -q chr1:1001-2000 -f genome.fa\n", arg); } /* the main function to read fasta index file */ faidx read_fa_idx(FILE *fp, const char* chr) { char tmp_line[MAX_LINE_LEN]; char tmp_chr[MAXLEN]; faidx idx={0, 0, 0, 0}; /* add a <tab> so as to distinct `xx` from `xxx` */ sprintf(tmp_chr, "%s\t", chr); while(!feof(fp)) { fgets(tmp_line, MAX_LINE_LEN, fp); if(strncmp(tmp_chr, tmp_line, strlen(tmp_chr))==0) { #ifdef DEBUG printf("idx=%s", tmp_line); #endif sscanf(tmp_line, "%s\t%u\t%u\t%u\t%u", tmp_chr, &idx.total_len, &idx.start_pos, &idx.valid_char_per_line, &idx.char_per_line); break; } } return idx; } unsigned get_line_length(const char* str) { char *tmp_p; tmp_p = strchr(str, '\n'); return (tmp_p - str); } /* the main function to read fasta file */ int read_seq(FILE *fp, faidx idx, unsigned pos1, unsigned pos2) { #ifdef DEBUG printf("faidx.total_len=%u\n", idx.total_len); printf("faidx.start_pos=%u\n", idx.start_pos); printf("faidx.valid_char_per_line=%u\n", idx.valid_char_per_line); printf("faidx.char_per_line=%u\n", idx.char_per_line); #endif char tmp_line[MAX_LINE_LEN]; unsigned output_len=0; unsigned max_inc=idx.valid_char_per_line; if(pos1 > idx.total_len) { fprintf(stderr, "Error: invalid start position, must < %u.\n", idx.total_len); return 1; } if(pos2 > idx.total_len) { fprintf(stderr, "Warning: invalid end position, should < %u.\n", idx.total_len); pos2 = idx.total_len; } unsigned offset = idx.start_pos + pos1 / idx.valid_char_per_line * idx.char_per_line + pos1 % idx.valid_char_per_line - 1; if(pos1 % idx.valid_char_per_line == 0) { offset -= 1; } #ifdef DEBUG printf("offset=%u\n", offset); #endif fseek(fp, offset, SEEK_SET); while(!feof(fp)) { fgets(tmp_line, MAX_LINE_LEN, fp); max_inc = get_line_length(tmp_line) < max_inc ? get_line_length(tmp_line) : idx.valid_char_per_line; #ifdef DEBUG printf("\nmax_inc=%u\n", max_inc); #endif if(output_len + max_inc >= pos2 - pos1 + 1) { tmp_line[pos2-pos1+1-output_len]='\0'; printf("%s\n", tmp_line); break; } else { output_len += max_inc; tmp_line[max_inc]='\0'; printf("%s", tmp_line); } } return 0; } int main(int argc, char * argv[]) { int idx, query_n=-1, fafile_n=-1; char fafile[MAXLEN]; char query[MAXLEN]; char faidxfile[MAXLEN]; char chr[MAXLEN]; char tmp_p0[MAXLEN]; char *tmp_p1, *tmp_p2; unsigned pos1, pos2; if(argc==1) { usage(argv[0]); return 0; } for(idx=1; idx<argc; idx++) { if(strcmp(argv[idx], "-q")==0) { query_n = ++idx; /* if `-q` is the last parament */ if(query_n >= argc) { usage(argv[0]); return 1; } } else if(strcmp(argv[idx], "-f")==0) { fafile_n = ++idx; /* if `-f` is the last parament */ if(fafile_n >= argc) { usage(argv[0]); return 1; } } /* if `query_n` isn't set, then use the remained parament */ else if(query_n == 0) { query_n = idx; } } if(query_n < 0 || fafile_n < 0) { usage(argv[0]); return 1; } else { /* `.fa` file */ strcpy(fafile, argv[fafile_n]); /* `.fa.fai` file */ strcpy(faidxfile, argv[fafile_n]); strcat(faidxfile, ".fai"); /* get `chr:pos1-pos2` */ strcpy(query, argv[query_n]); if ((tmp_p1 = strchr(query, ':')) && (tmp_p2 = strchr(tmp_p1, '-'))) { strncpy(chr, query, tmp_p1 - query); strncpy(tmp_p0, tmp_p1 + 1, tmp_p2 - tmp_p1 - 1); pos1=atoi(tmp_p0); pos2=atoi(tmp_p2 + 1); } else { usage(argv[0]); return 1; } #ifdef DEBUG printf("chr=%s\n", chr); printf("pos1=%d\n", pos1); printf("pos2=%d\n", pos2); printf("fafile=%s\n", fafile); printf("faidxfile=%s\n", faidxfile); #endif } FILE *fp_fa, *fp_faidx; if((fp_faidx = fopen(faidxfile, "r"))) { faidx idx=read_fa_idx(fp_faidx, chr); if (idx.total_len == 0) { fprintf(stderr, "Error: invalid CHR name - %s\n", chr); return 1; } if((fp_fa = fopen(fafile, "r"))) { if(read_seq(fp_fa, idx, pos1, pos2)) { fprintf(stderr, "FAIL\n"); } } else { fprintf(stderr, "Error: cannot open file %s\n", fafile); return 1; } } else { fprintf(stderr, "Error: cannot open file %s\n", faidxfile); fprintf(stderr, "You may use command 'samtools faidx %s' first\n", fafile); return 1; } return 0; }
C
/** * \file vccrypt_suite_buffer_init_for_cipher_key_agreement_private_key.c * * Initialize a crypto buffer sized appropriately for the suite cipher key * agreement private key. * * \copyright 2017 Velo Payments, Inc. All rights reserved. */ #include <cbmc/model_assert.h> #include <string.h> #include <vccrypt/suite.h> #include <vpr/abstract_factory.h> #include <vpr/parameters.h> /** * \brief Create a buffer sized appropriately for the private key of this crypto * suite's key agreement algorithm for ciphers. * * \param options The options structure for this crypto suite. * \param buffer The buffer instance to initialize. * * \returns a status indicating success or failure. * - \ref VCCRYPT_STATUS_SUCCESS on success. * - a non-zero return code on failure. */ int vccrypt_suite_buffer_init_for_cipher_key_agreement_private_key( vccrypt_suite_options_t* options, vccrypt_buffer_t* buffer) { MODEL_ASSERT(buffer != NULL); MODEL_ASSERT(options != NULL); MODEL_ASSERT(options->alloc_opts != 0); MODEL_ASSERT(options->key_cipher_opts.private_key_size > 0); return vccrypt_buffer_init( buffer, options->alloc_opts, options->key_cipher_opts.private_key_size); }
C
#include<stdio.h> #include<conio.h> int main() { int n,a,b; printf("\n********CHOICES********\n"); printf("1.) Addition\n"); printf("2.) Substraction\n"); printf("3.) Multiplication\n"); printf("4.) Division\n"); printf("Enter your choice: "); scanf("%d",&n); switch(n) { case 1: printf("Enter the value of a and b: "); scanf("%d%d",&a,&b); printf("Addition : %d",a+b); break; case 2: printf("Enter the value of a and b: "); scanf("%d%d",&a,&b); printf("Substraction : %d",a-b); break; case 3: printf("Enter the value of a and b: "); scanf("%d%d",&a,&b); printf("Multiplication : %d",a*b); break; case 4: printf("Enter the value of a and b: "); scanf("%d%d",&a,&b); printf("Division : %d",a/b); break; default: printf("Wrong Choice...plz enter correct choice\n"); } }
C
#include <stdio.h> #include "instruction.h" #include "helper_procedures.h" #include "register.h" #include "thumb_add_sub_cmp_mov_imm8.h" void thumb_add_sub_cmp_mov_imm8(short ins) { func p; *((short *)&DataAddSubCmpMovImm8)=ins; p=(func)data_add_sub_cmp_mov_imm8_process[(int)DataAddSubCmpMovImm8.opc]; (p)(ins); } void thumb_add_sub_cmp_mov_imm8_err(short ins) { printf("add_sub_cmp_mov_imm8_err: ins is %d\n",ins); } void thumb_mov_imm8(short ins) { unsigned result=(unsigned)DataAddSubCmpMovImm8.imm8; int carry=get_flag_c(); *((short *)&DataAddSubCmpMovImm8)=ins; set_general_register((int)DataAddSubCmpMovImm8.Rdn,result); if(!InITBlock()) { if((result & 0x8000) !=0) set_flag_n(); else cle_flag_n(); if(result == 0) set_flag_z(); else cle_flag_z(); if(carry)//whether carry set_flag_c(); else cle_flag_c(); } //printf("*********thumb_mov_imm8***********\n"); } void thumb_cmp_imm8(short ins) { struct CALCULATECO *result = (struct CALCULATECO*)malloc(sizeof(struct CALCULATECO)); unsigned imm; unsigned Rdn; *((short *)&DataAddSubCmpMovImm8)=ins; imm =(unsigned)DataAddSubCmpMovImm8.imm8; Rdn=(unsigned)get_general_register(DataAddSubCmpMovImm8.Rdn); addwithcarry(Rdn,~imm,1,result); if(!InITBlock()) { if((result->result & 0x8000) !=0) set_flag_n(); else cle_flag_n(); if(result->result == 0) set_flag_z(); else cle_flag_z(); if(result->carry_out)//whether carry set_flag_c(); else cle_flag_c(); if(result->overflow) set_flag_v(); else cle_flag_v(); } //printf("*********thumb_cmp_imm8***********\n"); free(result); } void thumb_add_imm8(short ins) { struct CALCULATECO *result = (struct CALCULATECO*)malloc(sizeof(struct CALCULATECO)); unsigned imm; unsigned Rdn; *((short *)&DataAddSubCmpMovImm8)=ins; imm=(unsigned)DataAddSubCmpMovImm8.imm8; Rdn=(unsigned)get_general_register(DataAddSubCmpMovImm8.Rdn); addwithcarry(Rdn,imm,0,result); set_general_register((int)DataAddSubCmpMovImm8.Rdn,result->result); if(!InITBlock()) { if((result->result & 0x8000) !=0) set_flag_n(); else cle_flag_n(); if(result->result == 0) set_flag_z(); else cle_flag_z(); if(result->carry_out)//whether carry set_flag_c(); else cle_flag_c(); if(result->overflow) set_flag_v(); else cle_flag_v(); } //printf("*********thumb_add_imm8***********\n"); free(result); } void thumb_sub_imm8(short ins) { struct CALCULATECO *result = (struct CALCULATECO*)malloc(sizeof(struct CALCULATECO)); unsigned imm; unsigned Rdn; *((short *)&DataAddSubCmpMovImm8)=ins; imm=(unsigned)DataAddSubCmpMovImm8.imm8; Rdn=(unsigned)get_general_register(DataAddSubCmpMovImm8.Rdn); addwithcarry(Rdn,~imm,1,result); set_general_register((int)DataAddSubCmpMovImm8.Rdn,result->result); if(!InITBlock()) { if((result->result & 0x8000) !=0) set_flag_n(); else cle_flag_n(); if(result->result == 0) set_flag_z(); else cle_flag_z(); if(result->carry_out)//whether carry set_flag_c(); else cle_flag_c(); if(result->overflow) set_flag_v(); else cle_flag_v(); } //printf("*********thumb_sub_imm8***********\n"); free(result); }
C
#include "lists.h" /** * pop_listint - function that deletes the head node of a listint_t linked list * @head: double pointer * Return: returns the head node's data (n) if the linked * list is empty return 0 */ int pop_listint(listint_t **head) { listint_t *temp = NULL; int count = 0; if (*head == NULL) { return (0); } temp = *head; count = temp->n; *head = temp->next; free(temp); return (count); }
C
#include "libft.h" int ft_strclen(char *str, char c) { int i; i = 0; while(str[i] && str[i] != c) i++; return (i); }
C
#include "myLib.h" void myFunc (int * array1, int * array2, int * array3, int N) { int i; for(i=0;i<N;i++) array3[i] = array1[i] + array2[i]; } int main (int argc, char ** argv) { assert(argv[1]!=NULL); int N = atoi (argv[1]); assert(N>=1); assert(argv[2]!=NULL); int I = atoi (argv[2]); assert(I>=1); printf("Array size = %d\n", N); int * array1 = (int*)malloc(sizeof(int)*N); assert(array1!=NULL); int * array2 = (int*)malloc(sizeof(int)*N); assert(array2!=NULL); srand(0); // 1. To get reproducible results int i; int T = 10; for(i=0;i<N;i++) { int randVal = rand()%(T+1); int val1 = randVal; int val2 = T - randVal; assert(val1+val2 == T); array1[i] = val1; array2[i] = val2; // 2. To check against the waveform if(i<10) { printf("array1[%d] = %d\tarray2[%d] = %d\n", i, array1[i], i, array2[i]); } } /****************************************/ /* Part 1: Reference Software Execution */ /****************************************/ int * array3_sw = (int*)malloc(sizeof(int)*N); assert(array3_sw!=NULL); /* correctness check */ myFunc (array1, array2, array3_sw, N); for(i=0;i<N;i++) { assert(array3_sw[i]==T); } /* timing */ double totalTime_sw=0.0; struct timespec timerStart_sw; struct timespec timerStop_sw; clock_gettime(CLOCK_REALTIME, &timerStart_sw); for(i=0;i<I;i++) myFunc (array1, array2, array3_sw, N); clock_gettime(CLOCK_REALTIME, &timerStop_sw); totalTime_sw = (timerStop_sw.tv_sec-timerStart_sw.tv_sec)+ (timerStop_sw.tv_nsec-timerStart_sw.tv_nsec) / BILLION; printf("Software execution time: %f\n", totalTime_sw); /******************************/ /* Part 2: Hardware Execution */ /******************************/ int * array3_hw = (int*)malloc(sizeof(int)*N); assert(array3_hw!=NULL); /* correctness check */ myFunc_hw (array1, array2, array3_hw, N); for(i=0;i<N;i++) { assert(array3_hw[i]==T+i); // 3. To check in the waveform } /* timing */ double totalTime_hw=0.0; struct timespec timerStart_hw; struct timespec timerStop_hw; clock_gettime(CLOCK_REALTIME, &timerStart_hw); for(i=0;i<I;i++) myFunc_hw (array1, array2, array3_hw, N); clock_gettime(CLOCK_REALTIME, &timerStop_hw); totalTime_hw = (timerStop_hw.tv_sec-timerStart_hw.tv_sec)+ (timerStop_hw.tv_nsec-timerStart_hw.tv_nsec) / BILLION; printf("Hardware execution time: %f\n", totalTime_hw); free(array1); free(array2); free(array3_sw); free(array3_hw); return 0; }
C
// // main.c // 2-60c // // Created by Bin Li on 1/19/17. // Copyright © 2017 Bin Li. All rights reserved. // #include <stdio.h> unsigned replace_byte (unsigned x, int i, unsigned char b); int main(){ //printf("%u", replace_byte(0x12345678, 2, 0xAB)); int a = 0xAB; printf("%x/n", a << 8); } unsigned replace_byte(unsigned x, int i, unsigned char b){ int shift = (b << (8 * i)); int mask = 0xff << shift; return (mask & x) | shift; }
C
#include <stdio.h> #include <string.h> #include <unistd.h> // write,close #include <sys/stat.h> // fifo #include <fcntl.h> // O_WRONLY int main() { int ret = -1; char *fifo = "./fifo"; // Just write to FIFO, no need to create FIFO char *msg = "This is message"; int fd = open(fifo, O_WRONLY); printf("Write message to fifo read\n"); int len = write(fd, msg, strlen(msg)); close(fd); ret = 0; exit: return ret; }
C
/*************************************************************************** * File: main.c * Author: Toby * Modification History: * Toby - 4 October 2020 * Procedures: * main - main function that will call the necessary amount of producers and consumers, and simulate the 'market' * consumer - Creatse a consumer that will buy from the producer * producer - Creates a producer that will make the max amount of items within the limitations of the buffer ***************************************************************************/ #include <semaphore.h> #include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <sys/types.h> #include <unistd.h> #include <stdbool.h> //initialize the correct amount for the buffer and the maximum items #define max 1000000 #define bufSize 1000 //initialize semaphores and buffers sem_t em; sem_t f; int total; int in = 0; int out = 0; int buffer[bufSize]; pthread_mutex_t m; /*************************************************************************** * void *producer(void *args) * Author: Toby * Date: Toby - 4 October 2020 * Modification History: * Toby - 4 October 2020 * Description: makes a producer that will make a number of items for the market/consumers * * Parameters: * none **************************************************************************/ void *producer(){ int item; int x = 0; while(true) { if(total == max) break;//if max items made, then break item = x+1; //makes some item that is one more than the last sem_wait(&em);//wait for empty signal pthread_mutex_lock(&m); buffer[in] = item;//add item to the buffer in = (in+1)%bufSize; total++;//increase total items made pthread_mutex_unlock(&m); sem_post(&f);//send full signal } } /*************************************************************************** * void *consumer(void *args) * Author: Toby * Date: 4 October 2020 * Modification History: * Toby - 4 October 2020 * Description: creates a consumer function that will consume from the buffer * * Parameters: * *args I/P void used to save the number of the consumer * main O/P int Print the Consumer and the amount consumed/bought **************************************************************************/ void *consumer(void *args){ int counter =0;//counter to track amount consumed while(true) { sem_wait(&f);//wait until full signal pthread_mutex_lock(&m); int item = buffer[out];//remove item from buffer counter++;//item has been consumed out = (out+1)%bufSize; pthread_mutex_unlock(&m); sem_post(&em);//send empty signal if(total == max) break;//if all items are gone break } printf("Consumer %d: %d items\n",*((int *)args),counter);//print the consumer and the number of their items } /*************************************************************************** * int main() * Author: Toby * Date: 4 October 2020 * Modification History: * Toby - 4 October 2020 * Description: calls uname to print the name and information about the current kernel by creating a utsname struct * * Parameters: * main O/P int Print the Consumer and the amount consumed/bought using the consumer function **************************************************************************/ int main(){ pthread_t pro,con[10];//initialize the threads pthread_mutex_init(&m, NULL); sem_init(&em,0,bufSize);//initalize the semaphores sem_init(&f,0,0); total=0;//reset total int num[10] = {1,2,3,4,5,6,7,8,9,10}; //storing the number of the consumer int pid[11]; for(int i = 0; i < 11; i++) {//11 total for the 1 producer and the 10 consumers pid[i] = 0; pid[i] = fork();//fork the process if(i==0){//if the first process, create the producer pthread_create(&pro, NULL, (void *)producer, (void *)&num[i]); }//else create the consumers i++; pthread_create(&con[i], NULL, (void *)consumer, (void *)&num[i]); } //join the threads so that they end pthread_join(pro, NULL); for(int i = 0; i < 10; i++) { pthread_join(con[i], NULL); } //necessary destruction methods pthread_mutex_destroy(&m); sem_destroy(&em); sem_destroy(&f); printf("%d",total); return 0; }
C
#include<stdio.h> int main() { int c=1,n,SOP[22] ={0,1, 1, 1, 3, 8, 21, 43, 69, 102, 145,197, 261, 336, 425, 527, 645, 778, 929, 1097, 1285,1492}; while(scanf("%d",&n)==1 &&n) printf("Case #%d: %d\n",c++,SOP[n]); return 0; }
C
#include <stdio.h> int main(void) { int a[100]; int n;//so luong phan tu cua mang do{ printf("\nnhap n = "); scanf("%d", &n); }while( n <= 0 || n > 100); for(int i = 0; i < n; i++){ printf("\nnhap a[%d] = ",i); scanf("%d", &a[i]); } for(int i = 0;i < n;i++){ printf("a[%d] = %d\n",i,a[i]); } int tong = 0; for(int i = 0;i < n;i++){//hien thi tong tong = tong + a[i]; }printf("tong = %d",tong); return 0; }
C
#include "BandpassFilter.h" float BandpassFilter_init(BandpassFilter_t* filter, float lk, float hk){ filter->highPassK = hk; filter->lowPassK = lk; filter->lowPassVal = 0; filter->highPassVal = 0; } float BandpassFilter_update(BandpassFilter_t* filter, float in){ filter->lowPassVal = filter->lowPassVal + filter->lowPassK * (in - filter->lowPassVal); filter->highPassVal = filter->highPassVal + filter->highPassK * (filter->lowPassVal - filter->highPassVal); return filter->lowPassVal - filter->highPassVal; }
C
/* ============================================================================ Name : median.c Author : shinu shaji,stebin yohannan Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> int main(void) { int A[20], j, n, i, temp,test; float median=0,m; printf("enter the total no of elements"); scanf("%d",&n); printf("enter the elements"); for(i=0;i<n;i++) { scanf("%d",&A[i]); } for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if (A[i]> A[j]){ temp=A[i]; A[i]=A[j]; A[j]=temp; } } } printf("sorted array: "); for(i=0;i<n;i++){ printf("%d ",A[i]); } if(n%2==0) { m = (A[n/2]+A[(n-2)/2]); median = m/2; } else { median = A[n/2]; } printf("median is %f ",median); }
C
//triangulo.c #include <stdio.h> #define base 10 * 1 //equilatero #define altura (base/2) * 1 void triangulo(char caracter){ int i, j; int restar = altura, espacios = 0; while(restar > 0){ for(i = 0; i < restar; i++) printf(" "); restar--; printf("%c", caracter); if(espacios > 0){ for(j = 0; j < espacios; j++){ printf(" "); } printf("%c", caracter); espacios = espacios + 2; }else espacios = 1; printf("\n"); } for(i = 0; i <= (espacios+1); i++){ printf("%c", caracter); } } void main(){ char caracter = 'X'; triangulo(caracter); printf("\n"); }
C
/* cs194-24 Lab 1 */ #include <stdbool.h> #include <string.h> #include <sys/epoll.h> #include <unistd.h> #include <pthread.h> #include <sys/sysinfo.h> #include <sys/syscall.h> #include <sys/types.h> #include <errno.h> #include "http.h" #include "mimetype.h" #include "palloc.h" #include "cache.h" #define PORT 8088 #define LINE_MAX 1024 #define DEFAULT_BUFFER_SIZE 256 static int event_loop(struct http_server *server); extern int process_session_line(struct http_session *session, const char *data); extern int process_session_data(struct http_session *session); //static pthread_mutex_t lock; int main(int argc, char **argv) { palloc_env env; struct http_server *server; int num_threads; int i, ret; env = palloc_init("httpd root context"); cache_init(env); /* create socket, bind, make non-blocking, listen */ /* also set up epoll events */ server = http_server_new(env, PORT); if (server == NULL) { perror("main(): Unable to open HTTP server"); return 1; } /* Create N threads, where N is the number of cores */ num_threads = get_nprocs(); //num_threads = 2; pthread_t * thread = malloc(sizeof(pthread_t)*num_threads); for (i = 0; i < num_threads; i++) { ret = pthread_create(&thread[i], NULL, (void *)&event_loop, server); if(ret != 0) { fprintf (stderr, "Create pthread error!\n"); exit (1); } } /* Now that each thread should be running the event loop, we wait... */ for (i = 0; i < num_threads; i++) { pthread_join(thread[i], NULL); } return 0; } int event_loop(struct http_server *server) { while (true) /* main event loop */ { struct http_session *session; int num_events_ready; int i, ret; /* Apparently epoll in edge-triggered mode, it only wakes up one thread at a time */ num_events_ready = epoll_wait(server->efd, server->events_buf, 5, -1); for (i = 0; i < num_events_ready; i++) { // loop through available events struct epoll_event ev = server->events_buf[i]; struct http_event *he = (struct http_event *)ev.data.ptr; /* Handle any weird errors */ if ((ev.events & EPOLLERR) || (ev.events & EPOLLHUP) || (!(ev.events & EPOLLIN))) { /* An error occured on this fd.... */ ////fprintf(stderr, "epoll error\n"); (he->session) ? close(((struct http_session *)he->ptr)->fd) : close(((struct http_server *)he->ptr)->fd); continue; } /* We got a notification on the listening socket, which means 1+ incoming connection reqs */ else if (!he->session && server->fd == ((struct http_server *)he->ptr)->fd) { /* accept() extracts the first connection request on the queue of pending connections * for the listening socket, creates a new connected socket, * and returns a new file descriptor referring to that socket. * While loop drains the pending connection buffer, important if concurrent requests are being made. * Can't just accept 1 connection per run */ if (ev.events & EPOLLIN) { while ((session = server->wait_for_client(server)) != NULL) { //fprintf(stderr, "Thread %ld: accepted a new client connection\n", tid); } } } else { // it is not the listening socket fd, but one of the accept'd session fd's session = (struct http_session *)he->ptr; /* points to a http_session struct */ //fprintf(stderr, "Thread %ld: Session fd received event from session %d\n", tid, session->fd); /* Ensure only one thread processes a session fd at a time */ if (pthread_mutex_trylock(&session->fd_lock) == 0) { if ((ev.events & EPOLLOUT) && !(ev.events & EPOLLIN)) { // If I had only registered EPOLLOUT events // retry the request and see if you can write to session fd now int mterr = session->mt_retry->http_get(session->mt_retry, session); if (mterr != 0) { perror("unrecoverable error while processing a client"); abort(); } } /* Read everything available from sess->fd until we hit EAGAIN*/ if (((ev.events & EPOLLIN) == EPOLLIN) && session->fd > 0) { // htf did a -1 sess->fd get in epoll??? /* when session->gets() encounters EAGAIN it returns null */ /* read lines from session->fd until we get no more lines */ ret = process_session_data(session); if (ret < 0) { perror("process_session_data failed"); abort(); } } // We got notified but the session was not ready for reading??? /* We are done processing this session fd for now. Release it. */ pthread_mutex_unlock(&session->fd_lock); } } } } } int process_session_line(struct http_session *session, const char *line) { char *method, *file, *version, *http_field, *http_field_value; struct mimetype *mt; int ret; /* What if 2 session fd's signaled events? */ /* What if 2 threads are handling the same session fd? */ method = palloc_array(session, char, strlen(line)); file = palloc_array(session, char, strlen(line)); version = palloc_array(session, char, strlen(line)); /* for other http header fields */ http_field = palloc_array(session, char, strlen(line)); http_field_value = palloc_array(session, char, strlen(line)); if (sscanf(line, "%s %s %s", method, file, version) != 3 || strcasecmp(method, "GET") != 0) { /* read until colon reached */ ret = sscanf(line, "%[^:]: %[^\n]", http_field, http_field_value); if (ret == 2) { fprintf(stderr, "http field: %s http_field_value: %s\n", http_field, http_field_value); /* If Cache-Control is set */ if (strcasecmp(http_field, "Cache-Control") == 0) { // for no-cache cases session->get_req->cache_control = http_field_value; fprintf(stderr, "Setting session->get_req->cache_control %s\n", session->get_req->cache_control); } /*If we had sent an etag, the client sends that etag back through If-None-Match */ if (strcasecmp(http_field, "If-None-Match") == 0) { // etag session->get_req->if_none_match = http_field_value; fprintf(stderr, "Setting session->get_req->if_none_match %s\n", session->get_req->if_none_match); } } return 0; } else { fprintf(stderr, " < '%s' '%s' '%s' from session %d \n", method, file, version, session->fd); mt = mimetype_new(session, file); if (strcasecmp(method, "GET") == 0) { /* http_get involves writing back to session fd, reading file from disk, * writing file contents to session fd */ /* We need to be able to: * write to session fd (s->puts(s, <response>)) * write to session fd (s->write(s, buffer of read bytes from file, length of file) */ /* We found a GET. process it. */ // mterr = mt->http_get(mt, session); session->get_req->mt = mt; fprintf(stderr, "FOUND A GET, SETTING SESSION->GET_REQ->MT\n"); session->get_req->request_string = palloc_strdup(session, line); // shouldn't need to memcpy as process_session_line is called for each line.. } else { fprintf(stderr, "Unknown method: '%s'\n", method); goto cleanup; } return 0; } cleanup: /* should call palloc destructor close_session * which closes the session fd and should automatically be * removed from the epoll set */ pfree(session); return -1; } int process_session_data(struct http_session* session) { const char *line; int ret; int mterr; struct mimetype *mt; while ((line = session->gets(session)) != NULL) { // readed = read(session->fd, buf + buf_used, DEFAULT_BUFFER_SIZE - buf_used); /* Process each line we receive */ ret = process_session_line(session, line); if (ret != 0) { perror("process_session_data encountered a problem"); //abort(); return ret; } } // after this while loop ends, should have read everything we could have if (session->get_req->mt != NULL) { mt = session->get_req->mt; // session->get_response->response_string set in http_get() mterr = mt->http_get(mt, session); if (mterr < 0) { perror("mt->http_get failed"); } } else { perror("Null mimetype in session->get_req->mt"); } close(session->fd); fprintf(stderr, "Finished parsing client request: (%s) (%s)", session->get_req->cache_control, session->get_req->if_none_match); //fprintf(stderr, "Thread %ld closing session fd %d \n", tid, session->fd); return 0; }
C
/* demonstration of unions */ #include<stdio.h> #include<string.h> union car { char name[25]; int price; }; int main(int argc, char const *argv[]) { union car c1; strcpy(c1.name, "GTX"); c1.price = 98000; // retains only the latest declrared value printf("\n\n%s \t %d\n\n", c1.name, c1.price); return 0; }
C
#include<stdio.h> int fib(int n) { if(n<=1) { return n; } return fib(n+1)+fib(n+2); } int main() { int n; scanf("%d",&n); fi=fib(n); printf("%d",fi); } Input: 6 Output: 8
C
#include "holberton.h" /** * _strspn - get leng. * @s: string 1. * @accept: for scan in the s. * Return: Always 0. */ unsigned int _strspn(char *s, char *accept) { int rec, comp, sum; sum = 0; rec = 0; while (s[rec] != ',') { comp = 0; while (accept[comp] != '\0') { if (s[rec] == accept[comp]) { sum++; break; } comp++; } if (s[rec] != accept[comp]) { break; } rec++; } return (sum); }
C
#include <stdio.h> int main() { /* Escribe los numeros del 1 al 10 */ int numero, suma, impares; float promedio; suma = 0; for (numero=0;numero < 10;numero++) { if (numero % 2 != 0) { printf("%d\n",numero); impares++; } suma = suma + numero; } promedio = suma / numero; printf ("Condicion de salida %d\n",numero); printf ("Cant. Impares: %d\n", impares); printf ("Suma de todos: %d\n",suma); printf ("Promedio: %f\n",promedio); return 0; }
C
#include <pthread.h> #include "buffer.h" static buffer_t buffer[BUFSIZE]; static pthread_mutex_t bufferlock = PTHREAD_MUTEX_INITIALIZER; static int bufin = 0; static int bufout = 0; int getitem(buffer_t *itemp) { /* remove item from buffer and put in *itemp */ int error; if (error = pthread_mutex_lock(&bufferlock)) /* no mutex, give up */ return error; *itemp = buffer[bufout]; bufout = (bufout + 1) % BUFSIZE; return pthread_mutex_unlock(&bufferlock); } int putitem(buffer_t item) { /* insert item in the buffer */ int error; if (error = pthread_mutex_lock(&bufferlock)) /* no mutex, give up */ return error; buffer[bufin] = item; bufin = (bufin + 1) % BUFSIZE; return pthread_mutex_unlock(&bufferlock); }
C
#include <stdio.h> #include <stdlib.h> int main() { float x; scanf("%f", &x); //輸入攝氏溫度 printf("%.2f\n", x * 9 / 5 + 32); //印出華氏溫度 return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "rthread.h" #define WHISTLER 0 #define LISTENER 1 struct device { /* These three semaphores should always sum to 1. */ rthread_sema_t mutex; rthread_sema_t whistlerSema; rthread_sema_t listenerSema; /* Variables to keep track of the state. */ int nWhistlersEntered, nWhistlersWaiting; int nListenersEntered, nListenersWaiting; }; /* Initialize semaphores and state. */ void dev_init(struct device *dev){ rthread_sema_init(&dev->mutex, 1); rthread_sema_init(&dev->whistlerSema, 0); rthread_sema_init(&dev->listenerSema, 0); dev->nWhistlersEntered = dev->nWhistlersWaiting = 0; dev->nListenersEntered = dev->nListenersWaiting = 0; } /* Implementation of 'V hat' */ void dev_vacateOne(struct device *dev){ /* If there are no listeners in the critical section and there are whistlers waiting, * release one of the waiting whistlers. */ if (dev->nListenersEntered == 0 && dev->nWhistlersEntered >= 0 && dev->nWhistlersWaiting > 0) { dev->nWhistlersWaiting--; rthread_sema_vacate(&dev->whistlerSema); } /* If there's nobody in the critical section and there are listeners waiting, * release one of the listeners. */ else if (dev->nWhistlersEntered == 0 && dev->nListenersEntered >= 0 && dev->nListenersWaiting > 0) { dev->nListenersWaiting--; rthread_sema_vacate(&dev->listenerSema); } /* If neither is the case, just stop protecting the shared variables. */ else { rthread_sema_vacate(&dev->mutex); } } void dev_enter(struct device *dev, int which){ if(which==1){ rthread_sema_procure(&dev->mutex); if (dev->nListenersEntered > 0) { dev->nWhistlersWaiting++; dev_vacateOne(dev); rthread_sema_procure(&dev->whistlerSema); } assert(dev->nListenersEntered == 0); dev->nWhistlersEntered++; dev_vacateOne(dev); } else { rthread_sema_procure(&dev->mutex); if (dev->nWhistlersEntered > 0) { dev->nListenersWaiting++; dev_vacateOne(dev); rthread_sema_procure(&dev->listenerSema); } assert(dev->nWhistlersEntered == 0); dev->nListenersEntered++; dev_vacateOne(dev); } } void dev_exit(struct device *dev, int which){ if(which==1){ rthread_sema_procure(&dev->mutex); assert(dev->nListenersEntered == 0); dev->nWhistlersEntered--; dev_vacateOne(dev); }else{ rthread_sema_procure(&dev->mutex); assert(dev->nWhistlersEntered == 0); dev->nListenersEntered--; dev_vacateOne(dev); } } #define NWHISTLERS 3 #define NLISTENERS 3 #define NEXPERIMENTS 2 char *whistlers[NWHISTLERS] = { "w1", "w2", "w3" }; char *listeners[NLISTENERS] = { "l1", "l2", "l3" }; void worker(void *shared, void *arg){ struct device *dev = shared; char *name = arg; for (int i = 0; i < NEXPERIMENTS; i++) { printf("worker %s waiting for device\n", name); dev_enter(dev, name[0] == 'w'); printf("worker %s has device\n", name); rthread_delay(random() % 3000); printf("worker %s releases device\n", name); dev_exit(dev, name[0] == 'w'); rthread_delay(random() % 3000); } printf("worker %s is done\n", name); } int main(){ struct device dev; dev_init(&dev); for (int i = 0; i < NWHISTLERS; i++) { rthread_create(worker, &dev, whistlers[i]); } for (int i = 0; i < NLISTENERS; i++) { rthread_create(worker, &dev, listeners[i]); } rthread_run(); return 0; }
C
// // Calculator.c // PostfixCalculator // // Created by 이동영 on 10/09/2019. // Copyright © 2019 부엉이. All rights reserved. // #include "Calculator.h" #include "string.h" #include "Stack.h" double calculate(char* postfixExpression) { long length = strlen(postfixExpression); int i = 0; Stack *operand = createStack(length); int operand1; int operand2; while (i < length) { char popped = postfixExpression[i]; i++; switch (popped) { case '+': operand2 = (int)(pop(operand)-48); operand1 = (int)(pop(operand)-48); printf("%d + %d = %d\n", operand1, operand2, operand1 + operand2); push(operand, (char)((operand1 + operand2)+48)); break; case '-': operand2 = (int)(pop(operand)-48); operand1 = (int)(pop(operand)-48); printf("%d - %d = %d\n", operand1, operand2, operand1 - operand2); push(operand, (char)((operand1 - operand2)+48)); break; case '*': operand2 = (int)(pop(operand)-48); operand1 = (int)(pop(operand)-48); printf("%d * %d = %d\n", operand1, operand2, operand1 * operand2); push(operand, (char)((operand1 * operand2)+48)); break; case '/': operand2 = (int)(pop(operand)-48); operand1 = (int)(pop(operand)-48); printf("%d / %d = %d\n", operand1, operand2, operand1 / operand2); push(operand, (char)((operand1 / operand2)+48)); break; default: push(operand, popped); break; } } return pop(operand)-48; }
C
/* * El programa crea un vector int de n números dados por el usuario * utilizando memoria dinámica. */ #include <stdio.h> #include <stdlib.h> int main() { // *p -> puntero // n -> número de elementos int *p, n; printf("\nIngrese el número de elementos > "); scanf("%d",&n); p=(int*)malloc(n*sizeof(int)); // Memoria dinámica para 'n' elementos // Condición para asignar memoria if ( p == NULL) {printf("\nERROR al asignar memoria\n"); exit(-1);} printf("\n\n"); for (int i = 0 ; i < n ; i++) { printf("Elemento[%d] > ",i); scanf("%d",(p+i)); } printf("\n----Elementos de arreglo----\n"); for (int i = 0 ; i < n ; i++) { printf(" %d ", *(p+i)); } printf("\n\n"); free(p); // Liberamos memoria asignada return 0; }
C
#include <stdio.h> #define VERSION "1.0.0" void print_version() { char ver[]=VERSION; printf(" Version %s \n", ver); }
C
#include <stdio.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include "inodeinc.h" extern int init(char *disk); extern int getInodesPerGroup(); extern int getBlockSize(); extern int getInodeSize(); void readInode(int inode, FILE *fp) { printf("----- BEGIN INODE READING -----\n"); struct ext3_inode Inode; struct ext3_group_desc GroupDes; int inodesPerGroup = getInodesPerGroup(); int blockSize = getBlockSize(); printf("Inodes per block group: %d\n", inodesPerGroup); int bgNumber = (inode - 1) / inodesPerGroup; int offset = (inode - 1) % inodesPerGroup; offset *= getInodeSize(); printf("Target block group: %d\n", bgNumber); // add block size to skip the superblock int groupDescriptorOffset = bgNumber * sizeof(struct ext3_group_desc) + blockSize; printf("Group Descriptor offset: %d\n", groupDescriptorOffset); fseek(fp, groupDescriptorOffset, SEEK_SET); fread(&GroupDes, sizeof(GroupDes), 1, fp); int inodeTableLoc = GroupDes.bg_inode_table * blockSize; printf("Inode table location: %d\n", inodeTableLoc); printf("Inode offset into table: %d\n", offset); fseek(fp, inodeTableLoc + offset, SEEK_SET); fread(&Inode, sizeof(Inode), 1, fp); int i = 0; printf("File size: %d\n", Inode.i_size); for(; i < EXT3_N_BLOCKS; i++) { printf("Block pointer %d: %d\n", i, Inode.i_block[i]); } } int main(int argc, char **argv) { if (argc != 3) { printf("Error: %s\n", strerror(errno)); return -1; } FILE *fp = fopen(argv[1], "rb"); if (fp < 0) { printf("Error %s\n", strerror(errno)); return -1; } int inode = atoi(argv[2]); printf("Target Inode %d\n", inode); init(fp); readInode(inode, fp); fclose(fp); return 0; }
C
/* * Copyright (c) 2019 Team 3555 * * 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 <stdint.h> #include <math.h> #include <stdio.h> #include "org_aluminati3555_aluminativision_hsl_HSL.h" /* See this link for fast min and max https://www.geeksforgeeks.org/compute-the-minimum-or-maximum-max-of-two-integers-without-branching/ */ int max(int a, int b) { return a ^ ((a ^ b) & -(a < b)); } int min(int a, int b) { return b ^ ((a ^ b) & -(a < b)); } void rgb_to_hsl(float r, float g, float b, float* h, float* s, float* l) { float max_value = ((float) max(r, max(g, b))) / 255; float min_value = ((float) min(r, min(g, b))) / 255; r /= 255; g /= 255; b /= 255; *l = (max_value + min_value) / 2; if (max_value == min_value) { *h = 0; *s = 0; } else { float d = max_value - min_value; *s = *l > 0.5 ? d / (2 - d) : d / (max_value + min_value); if (r == max_value) { *h = (g - b) / d + (g < b ? 6: 0); } else if (g == max_value) { *h = (b - r) / d + 2; } else if (b == max_value) { *h = (r - g) / d + 4; } else { *h = 0; } *h /= 6; } *h *= 255; *s *= 255; *l *= 255; } JNIEXPORT void JNICALL Java_org_aluminati3555_aluminativision_hsl_HSL_nativeRGBToHLS(JNIEnv* env, jobject obj, jlong address, jint width, jint height) { long data_address = (long) address; uint8_t* data = (uint8_t*) data_address; int frame_width = (int) width; int frame_height = (int) height; int pixels = width * height; int length = pixels * 3; int r; int g; int b; float h; float s; float l; for (int i = 0; i < length; i += 3) { r = data[i]; g = data[i + 1]; b = data[i + 2]; rgb_to_hsl(r, g, b, &h, &s, &l); data[i] = (uint8_t) roundf(h); data[i + 1] = (uint8_t) roundf(l); data[i + 2] = (uint8_t) roundf(s); } }
C
#include <stdio.h> /* * Faça um método recursivo que retorne a sequência de fibonacci. */ int fib(int n){ int resp; if(n == 0 || n == 1 || n == 2) resp = 1; else resp = fib(n - 1) + fib(n - 2); return resp; } int main(){ int n; printf("Digite qual termo da série de Fibonacci deseja visualisar: "); scanf("%d", &n); printf("O termo %d da série de Fibonacci é = %d\n", n, fib(n)); return 0; }
C
#define _GNU_SOURCE #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <sys/mount.h> #include <sys/wait.h> #include <unistd.h> /* keep special_exit_code in sync with container_top_linux.go */ int special_exit_code = 255; char **argv = NULL; void create_argv (int len) { /* allocate one extra element because we need a final NULL in c */ argv = malloc (sizeof (char *) * (len + 1)); if (argv == NULL) { fprintf (stderr, "failed to allocate ps argv"); exit (special_exit_code); } /* add final NULL */ argv[len] = NULL; } void set_argv (int pos, char *arg) { argv[pos] = arg; } /* We use cgo code here so we can fork then exec separately, this is done so we can mount proc after the fork because the pid namespace is only active after spawning childs. */ void fork_exec_ps () { int r, status = 0; pid_t pid; if (argv == NULL) { fprintf (stderr, "argv not initialized"); exit (special_exit_code); } pid = fork (); if (pid < 0) { fprintf (stderr, "fork: %m"); exit (special_exit_code); } if (pid == 0) { r = mount ("proc", "/proc", "proc", 0, NULL); if (r < 0) { fprintf (stderr, "mount proc: %m"); exit (special_exit_code); } /* use execve to unset all env vars, we do not want to leak anything into the container */ execve (argv[0], argv, NULL); fprintf (stderr, "execve: %m"); exit (special_exit_code); } r = waitpid (pid, &status, 0); if (r < 0) { fprintf (stderr, "waitpid: %m"); exit (special_exit_code); } if (WIFEXITED (status)) exit (WEXITSTATUS (status)); if (WIFSIGNALED (status)) exit (128 + WTERMSIG (status)); exit (special_exit_code); }