language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* delete_struct.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dhuber <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/06/14 17:43:28 by dhuber #+# #+# */ /* Updated: 2018/06/28 15:10:04 by mkamel ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/lem_in.h" static void delete_link(t_link **link) { t_link *tmp; if (!link || !(*link)) return ; tmp = (*link); while (tmp) { tmp = (*link)->next; ft_memdel((void**)link); (*link) = tmp; } } void delete_arg(char **arg) { int i; i = 0; if (!arg && !*arg) return ; while (arg[i]) ft_memdel((void**)&arg[i++]); free((void*)arg); arg = NULL; } void delete_info(t_info **data) { size_t i; i = 0; if ((*data)->room) { while (i <= (*data)->nb_room) { if ((*data)->room[i]->links) delete_link(&(*data)->room[i]->links); ft_memdel((void**)&(*data)->room[i]->name); ft_memdel((void**)&(*data)->room[i]); i++; } } ft_memdel((void*)&(*data)->room); ft_memdel((void*)&(*data)); } void delete_list(t_check **list) { t_check *tmp; if ((*list)) { tmp = (*list); while (tmp) { tmp = tmp->next; ft_memdel((void**)&(*list)->line); ft_memdel((void**)list); (*list) = tmp; } } }
C
// // main.c // 01数据类型 // // Created by FCNA01 on 2018/12/18. // Copyright © 2018年 FCNA01. All rights reserved. // #include <stdio.h> int main(int argc, const char * argv[]) { /** 基本类型 1.整型 2.浮点型 unsigned:无符号,即没有负数部分 char 1 字节 short 2 字节 int 4 字节 long 8 字节 long long 8 字节 float 4 字节 double 8 字节 long double 16 字节 */ int a1 = 1; printf("size: %lu",sizeof(a1)); /** 枚举类型 */ /** void类型 1.函数返回为空 2.函数参数为空 3.指针指向 void */ /** 派生类型 1.指针 2.数组 3.结构体 4.共用体 5.函数 */ return 0; }
C
#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int a[50],b[50],c[100],l1,l2,l3,i,j,k; // input in first array start printf("please enter the length of the first array:-"); scanf("%d",&l1); printf("please enter values in first array\n"); for(i=0;i<l1;i++) scanf("%d",&a[i]); //input in second array start printf("please enter the length of the second array:-"); scanf("%d",&l2); printf("please enter values in second array\n"); for(i=0;i<l2;i++) scanf("%d",&b[i]); i=0;j=0;k=0; while(i<l1 && j<l2) { if(a[i]<b[j]) { c[k]=a[i]; i++;k++; } else { c[k]=b[j]; j++;k++; } } while(i<l1) { c[k]=a[i]; i++;k++; } while(j<l2) { c[k]=b[j]; j++;k++; } l3=k; printf("\n"); for(i=0;i<l3;i++) { printf("%d ",c[i]); } return 0; }
C
#include <stdio.h> int arr[500001], temp[500001]; void mergesort(int s, int e); void merge(int s1, int e1, int s2, int e2); int main() { int n, ans; scanf("%d %d", &n, &ans); getchar(); for(int i=0; i<n; i++) { scanf("%d", &arr[i]); getchar(); } mergesort(0, n-1); printf("%d\n", arr[ans-1]); return 0; } void mergesort(int s, int e) { if(s == e) return; mergesort(s, (s+e)/2); mergesort((s+e)/2 + 1, e); merge(s, (s+e)/2, (s+e)/2 + 1, e); return; } void merge(int s1, int e1, int s2, int e2) { int fs = s1, fe = e1, bs = s2, be = e2, i = s1; while(fs <= fe && bs <= be) { if(arr[fs] < arr[bs]) { temp[i] = arr[fs]; i++; fs++; } else { temp[i] = arr[bs]; i++; bs++; } } if(fs > fe) { while(bs <= be) { temp[i] = arr[bs]; i++; bs++; } } else { while(fs <= fe) { temp[i] = arr[fs]; i++; fs++; } } for(int j=s1; j<=e2; j++) { arr[j] = temp[j]; } return; }
C
#ifndef GLSL_ALGO_RW_TYPES_H #define GLSL_ALGO_RW_TYPES_H #ifdef __cplusplus extern "C"{ #endif typedef enum { GARWTint1, GARWTint2, GARWTint4, GARWTuint1, GARWTuint2, GARWTuint4, GARWTfloat1, GARWTfloat2, GARWTfloat4, GARWTundefined } GLSL_ALGO_READ_WRITE_TYPE; static inline unsigned glsl_algo_convert_rw_type(GLSL_ALGO_READ_WRITE_TYPE type) { switch(type) { case GARWTint1: case GARWTint2: case GARWTint4: return 0u; case GARWTuint1: case GARWTuint2: case GARWTuint4: return 1u; case GARWTfloat1: case GARWTfloat2: case GARWTfloat4: return 2u; default: break; } return GARWTundefined; } static inline unsigned glsl_algo_get_rw_num_elements(GLSL_ALGO_READ_WRITE_TYPE type) { switch(type) { case GARWTint1: case GARWTuint1: case GARWTfloat1: return 1; case GARWTint2: case GARWTuint2: case GARWTfloat2: return 2; case GARWTint4: case GARWTuint4: case GARWTfloat4: return 4; default: GLSL_ALGO_ERROR("Read/write type not defined"); } return 0; } static inline const char *const glsl_algo_get_rw_type_name(GLSL_ALGO_READ_WRITE_TYPE type) { switch(type) { case GARWTint1: return "int"; case GARWTint2: return "ivec2"; case GARWTint4: return "ivec4"; case GARWTuint1: return "uint"; case GARWTuint2: return "uvec2"; case GARWTuint4: return "uvec4"; case GARWTfloat1: return "float"; case GARWTfloat2: return "vec2"; case GARWTfloat4: return "vec4"; default: GLSL_ALGO_ERROR("Read/write type not defined"); } return NULL; } static inline GLSL_ALGO_READ_WRITE_TYPE get_equivalent_scalar_type(GLSL_ALGO_READ_WRITE_TYPE type) { switch(type) { case GARWTint1: return GARWTint1; case GARWTint2: return GARWTint1; case GARWTint4: return GARWTint1; case GARWTuint1: return GARWTuint1; case GARWTuint2: return GARWTuint1; case GARWTuint4: return GARWTuint1; case GARWTfloat1: return GARWTfloat1; case GARWTfloat2: return GARWTfloat1; case GARWTfloat4: return GARWTfloat1; default: GLSL_ALGO_ERROR("Read/write type not defined"); } return GARWTundefined; } static inline GLSL_ALGO_READ_WRITE_TYPE get_equivalent_vector_type(GLSL_ALGO_READ_WRITE_TYPE type, unsigned elements) { switch(elements) { case 1: case 2: case 4: break; default: GLSL_ALGO_ERROR("Vector size can be only of size 1,2 and 4."); } switch(type) { case GARWTfloat1: case GARWTfloat2: case GARWTfloat4: { switch(elements) { case 1: return GARWTfloat1; case 2: return GARWTfloat2; case 4: return GARWTfloat4; } break; } case GARWTint1: case GARWTint2: case GARWTint4: { switch(elements) { case 1: return GARWTint1; case 2: return GARWTint2; case 4: return GARWTint4; } break; } case GARWTuint1: case GARWTuint2: case GARWTuint4: { switch(elements) { case 1: return GARWTuint1; case 2: return GARWTuint2; case 4: return GARWTuint4; } break; } } return GARWTundefined; } #ifdef __cplusplus } #endif #endif // GLSL_ALGO_RW_TYPES_H
C
/* * leetcode * 9. Palindrome Number AC * zhao xiaodong */ bool isPalindrome(int x) { int a = x; int num =0; while(a>0){ num = num*10 + a%10; a = a/10; } return num==x?true:false; } /* * Note: * c版: * 三目运算符竟然比if else还要快好多 */
C
#include <stdio.h> #define MAX 20 int binary(int array[], int low, int high, int key); int main() { int i, n = MAX - 1, key, index, low, high; int array[MAX]; printf("\nEnter Size of Array : "); scanf("%d", &n); printf("\nEnter Elements of Array in sorted order : "); for (i = 0; i < n; i++) { scanf("%d", &array[i]); } printf("\nEnter element to search : "); scanf("%d", &key); low = 0; high = n - 1; index = binary(array, low, high, key); if (index != -1) { printf("Found %d at pos %d", key, index + 1); } else { printf("\nGiven Array Doesnt Contain Element %d ", key); } printf("\n"); return 0; } int binary(int array[], int low, int high, int key) { int mid = low + (high - low) / 2; // prevents overflow if (low > high) { return -1; } else if (array[mid] == key) { return mid; } else if (array[mid] < key) { return binary(array, mid + 1, high, key); } else { // array[mid] > key return binary(array, low, mid - 1, key); } }
C
//QUESTAO 1 //dado um intervalo definido por a e b, desenvolver uma funcao que determine quantas potencias de 2 existem nesse intervalo e qual a ultima potencia #include<stdio.h> int funcao(int a, int b,int *pos); void main() { int a, b,pos,resp; printf("Digite um numero para iniciar o intervalo : \n"); scanf("%d",&a); printf("Digite um numero para finalizar o intervalo : \n"); scanf("%d",&b); resp=funcao(a,b,&pos);//mandar pos por referencia pq o retorno ja vai ser o numero de potencias existentes, entao pos vai como ponteiro printf("resp : %d\n",resp); printf("pos : %d\n",pos); } int funcao(int a, int b,int *pos) { int i,pot=1,cont=0;//inicializando o pot em 1 pq a primeira potencia de 2./cont o numero de potenciass q aparecem nesse intervalo e que no fim vai ser retornado while(pot<=b)// { if(pot>=a && pot<=b)//if pra achar uma potencia q esteja dentro do intervalo ab { cont++;//se achar, aumenta o cont em 1 } (*pos)=pot;//pos vai receber sempre a ultima pot de 2 antes do incremento e do teste que o while faz pra continuar rodando. pot*=2;//a potencia de 2 sendo multiplicada por 2 a cada vez q o while roda } return cont;//retornando o numero de vezes que foram achadas potencias de 2 dentro do intervalo ab }
C
#include <stdio.h> /* getchar, printf */ #include <stdlib.h> /* NULL, malloc, free */ #include <string.h> /* strcpy */ #include <ctype.h> /* isspace, isdigit, isapotEqha, isalnum */ #include <assert.h> /* assert */ #include "scanner.h" #include "evalExp.h" #include "recognizeExp.h" /* to do: * - variables with multiple letters * - make acceptFactor */ int valueIdentifier(List *potEq, char *c) { if (*potEq != NULL && (*potEq)->tt == Identifier) { c = ((*potEq)->t).identifier; *potEq = (*potEq)->next; return 1; } return 0; } int differentIdentifier (char *s, char *variable) { printf("we used differentIdentifier\n\n"); printf("%s\n",&variable); printf("%s\n",&s); if (*variable == 0) { printf("We encountered the first identifier\n\n"); *variable = *s; } else if (*s == *variable) { printf("this identifier is same as the first one we encountered\n\n"); return 0; } return 1; // When *variable == NULL or *variable != *s, they are not the same identifiers } int isIdentifier (List *potEq, char *variable, int *var) { printf("we used isIdentifier\n\n"); int i = 0; char s[100]; if( valueIdentifier(potEq, &s[i]) ){ printf("This is an identifier\n\n"); do{ i++; } while ( valueIdentifier(potEq, &s[i]) ); s[i] = '\0'; *var += differentIdentifier(s, variable); printf("%d\n\n", *var ); return 1; } return 0; } // Returns 1 when 1) there is no power (^) or 2) if there is a valid power int hasValidPower (List *potEq, int *maxDeg) { double degree; if ( acceptCharacter(potEq,'^') ) { printf("Power Detected\n\n"); if ( valueNumber(potEq, &degree) ) { printf("Has a power of %d\n\n",(int) degree ); if ((int) degree > *maxDeg){ *maxDeg = (int) degree; printf("maxDegree == %d\n\n",*maxDeg); } } else { printf("Power is not valid\n\n"); return 0; } } return 1; } int isTerm (List *potEq, int *var, int *maxDeg, char *variable) { if ( !acceptNumber(potEq) ) { if ( !isIdentifier(potEq, variable, var) ) { return 0; } else { if ( !hasValidPower(potEq, maxDeg) ) return 0; } } else { if ( isIdentifier(potEq, variable, var) ) { if ( !hasValidPower(potEq, maxDeg) ) return 0; } } return 1; } int isExpression (List *potEq, int *var, int *maxDeg, char *variable) { acceptCharacter(potEq,'-'); if ( !isTerm(potEq, var, maxDeg, variable) ) { printf("is not term\n\n"); return 0; } while ( acceptCharacter(potEq,'+') || acceptCharacter(potEq,'-') ) { printf("+ or - is read\n\n" ); if ( !isTerm(potEq, var, maxDeg, variable) ) { printf("is not term 2\n\n"); return 0; } } /* no + or -, so we reached the end of the expression */ return 1; } // Recognizer function. int isEquation(List *potEq, int *var, int *maxDeg) { char variable = 0; if ( !isExpression(potEq, var, maxDeg, &variable) ) { printf("First part of isEquation\n\n" ); return 0; } if ( !acceptCharacter(potEq,'=') ) { printf("Second part of isEquation\n\n" ); return 0; } if ( !isExpression(potEq, var, maxDeg, &variable) ) { printf("Third part of isEquation\n\n" ); return 0; } if ( acceptCharacter(potEq,'=') ) { printf("Fourth part of isEquation\n\n"); return 0; } return 1; } int main(int argc, char *argv[]) { printf("give an equation: "); char *s = readInput(); int variablecount = 0; int maxDegree = 0; while (s[0] != '!') { List potentialEquation = tokenList(s); if (isEquation(&potentialEquation, &variablecount, &maxDegree)) { printf("\nthis is an equation"); if (variablecount == 1) { // variable undefined printf(" in 1 variable of degree %d\n\n", maxDegree); // degree undefined } else if (variablecount > 1) { printf(", but not in 1 variable\n\n"); } else { printf(", but something went wrong in counting variables\n\n"); } } else { printf("this is not an equation\n\n"); } free(s); freeTokenList(potentialEquation); variablecount = 0; printf("give an equation: "); s = readInput(); } printf("good bye"); return 0; }
C
/* shows the ternary operations on function call & input variable */ #include <stdio.h> int f1(int n); int f2(void); int main (void) { int t; printf("enter a number : \n"); scanf("%d", &t); t? f1(t)+f2() : printf("Zero has been entered\n"); return 0; } int f1(int n) { printf("%d:",n); return 0; } int f2(void) { printf("entered\n"); return 0; }
C
/* Elaborar un programa que obtenga la suma de dos vectores de 100 elementos enteros utilizando 5 hilos */ #include <pthread.h> #include <stdio.h> #include <unistd.h> int array1[100]; int array2[100]; int arrayR[100]; void *sumaArreglos (void *indice); void llenaVectores(); void main() { pthread_t hilos[5]; int error, i; int indiceIni; llenaVectores(); for (i = 0 ; i < 5 ; i++) { indiceIni = i*20; error = pthread_create(&hilos[i], NULL, sumaArreglos, &indiceIni); } for (i = 0 ; i < 5 ; i++) { error = pthread_join(hilos[i], NULL); } for (i = 0; i < 100; i++) { printf("%d \n", arrayR[i]); } } void *sumaArreglos (void *indice) { int inicial = *(int *)indice; for (int i = inicial; i < (inicial+20) ; i++) { arrayR[i] = array1[i] +array2[i]; } pthread_exit(NULL); } void llenaVectores() { for (int i = 0 ; i < 100 ; i++) { array1[i] = i; array2[i] = i; } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "Employee.h" #include "utn2.h" /** \brief Reserva espacio de memoria para la estructura Empleado. * \return Employee* retorna la direccion de memoria reservada. */ Employee* empleado_new(void) { return (Employee*) malloc(sizeof(Employee)); } /** \brief Reserva espacio de memoria para la estructura Empleado y setea sus valores recibidos como texto por parametro . * \param char* recibe el id como string * \param char* recibe el nombre como string * \param char* recibe las horas trabajadas como string * \param char* recibe el salario como string * \return Employee* retorna un puntero a empleado con los valores seteados. */ Employee* employee_newParametrosTxt(char* idStr,char* nombreStr,char* horasTrabajadas,char* salario) { Employee* auxEmpleado = empleado_new(); if(auxEmpleado != NULL) { if ( employee_setNombre(auxEmpleado,nombreStr) != 0 || employee_setHorasTrabajadas(auxEmpleado,atoi(horasTrabajadas)) != 0 || employee_setSueldo(auxEmpleado,atoi(salario)) != 0 || employee_setId(auxEmpleado,atoi(idStr)) != 0 ) { employee_delete(auxEmpleado); auxEmpleado = NULL; } } return auxEmpleado; } /** \brief Reserva espacio de memoria para la estructura Empleado y setea sus valores recibidos por parametro. * \param int recibe el id como entero * \param char* recibe el nombre como string * \param int recibe las horas trabajadas como entero * \param int recibe el salario como entero * \return Employee* retorna un puntero a empleado con los valores seteados. */ Employee* employee_newParametros(int idStr,char* nombreStr,int horasTrabajadas,int salario) { Employee* auxEmpleado = empleado_new(); if(auxEmpleado != NULL) { if ( employee_setNombre(auxEmpleado,nombreStr) != 0 || employee_setHorasTrabajadas(auxEmpleado,horasTrabajadas) != 0 || employee_setSueldo(auxEmpleado,salario) != 0 || employee_setId(auxEmpleado,idStr) != 0 ) { employee_delete(auxEmpleado); auxEmpleado = NULL; } } return auxEmpleado; } /** \brief Baja de empleados. * \param Employee* Puntero de empleado a eliminar. * \return int 0 si salio bien y -1 si salio mal. */ int employee_delete(Employee* this) { int retorno = -1; if(this != NULL) { free(this); this=NULL; retorno = 0; } return retorno; } /** \brief Setea el valor del id en la estructura empleado. * \param Employee* empleado al cual se le seteara el id. * \param Int id a setear. * \return int devuelve 0 si salio todo bien y -1 si salio algo mal. */ int employee_setId(Employee* this, int idEmpleado) { int retorno = -1; if(this != NULL && isValidId(idEmpleado)==0) { this->id = idEmpleado; retorno = 0; } return retorno; } /** \brief Pide y retorna el valor del Id de un empleado. * \param Employee* puntero a empleado a utilizar. * \param int* puntero a int que almacena -1 si algo salio mal y 0 si salio bien. * \return int retorta el ID. */ int employee_getId(Employee* this,int* flagError) { *flagError = -1; int auxId = -1; if(this != NULL && flagError != NULL ) { auxId=this->id; *flagError = 0; } return auxId; } /** \brief Alta de empleados * * \param path char* * \param pArrayListEmployee LinkedList* * \return int * */ Employee* buscarPorId(LinkedList* pArrayListEmployee,int idABuscar) { int i; int lenLista ; Employee* pEmpEdit; Employee* pRet=NULL; int idEncontrado; int flag; if(pArrayListEmployee!=NULL) { lenLista = ll_len(pArrayListEmployee); for(i=0; i<lenLista; i++) { pEmpEdit = (Employee*)ll_get(pArrayListEmployee, i); idEncontrado = employee_getId(pEmpEdit, &flag); if(idABuscar == idEncontrado) { pRet = pEmpEdit; break; } } } return pRet; } /** \brief Funcion que valida el id * \param int Valor del id a validar * \return 0 si salio todo bien y -1 si algo salio mal */ int isValidId(int idEmpleado) { int retorno = -1; if(idEmpleado>=0) { retorno = 0; } return retorno; } /** \brief Setea el valor del nombre en la estructura empleado. * \param Employee* empleado al cual se le seteara el nombre * \param char* nombre a setear. * \return int devuelve 0 si salio todo bien y -1 si salio algo mal. */ int employee_setNombre(Employee* this, char* nombre) { int retorno = -1; if(this != NULL && nombre != NULL && isValidNombre(nombre)==0) { strcpy(this->nombre,nombre); retorno = 0; } return retorno; } /** \brief Pide y retorna como puntero a char el nombre de un empleado. * \param Employee* puntero a empleado a utilizar. * \param int* puntero a int que almacena -1 si algo salio mal y 0 si salio bien. * \return int retorta el nombre como char*. */ char* employee_getNombre(Employee* this,int* flagError) { *flagError = -1; char* auxNombre=NULL; if(this != NULL && flagError != NULL ) { auxNombre = this->nombre; *flagError = 0; } return auxNombre; } /** \brief Funcion que valida el nombre * \param char* puntero a char que representa el nombre a validar. * \return 0 si salio todo bien y -1 si algo salio mal */ int isValidNombre(char* nombre) { int retorno=-1; if(isName(nombre)==0) { retorno=0; } return retorno; } /** \brief Setea el valor del Horas Trabajadas en la estructura empleado. * \param Employee* empleado al cual se le setearan las horas trabajadas. * \param Int Horas trabajadas a setear. * \return int devuelve 0 si salio todo bien y -1 si salio algo mal. */ int employee_setHorasTrabajadas(Employee* this, int horasTrabajadas) { int retorno = -1; if(this != NULL && isValidHorasTrabajadas(horasTrabajadas)==0) { this->horasTrabajadas = horasTrabajadas; retorno = 0; } return retorno; } /** \brief Pide y retorna la cantidad de horas trabajadas de un empleado. * \param Employee* puntero a empleado a utilizar. * \param int* puntero a int que almacena -1 si algo salio mal y 0 si salio bien. * \return int retorta las horas trabajadas del empleado. */ int employee_getHorasTrabajadas(Employee* this,int* flagError) { *flagError = -1; int auxId = -1; if(this != NULL && flagError != NULL ) { auxId=this->horasTrabajadas; *flagError = 0; } return auxId; } /** \brief Alta de empleados * * \param path char* * \param pArrayListEmployee LinkedList* * \return int * */ int isValidHorasTrabajadas(int horasTrabajadas) { int retorno = -1; if(horasTrabajadas>=35 && horasTrabajadas<=730) { retorno=0; } return retorno; } /** \brief Setea el valor del sueldo en la estructura empleado. * \param Employee* empleado al cual se le seteara el sueldo. * \param Int sueldo a setear. * \return int devuelve 0 si salio todo bien y -1 si salio algo mal. */ int employee_setSueldo(Employee* this, int sueldo) { int retorno = -1; if(this != NULL && isValidSueldo(sueldo)==0) { this->sueldo = sueldo; retorno = 0; } return retorno; } /** \brief Pide y retorna el valor del salario de un empleado. * \param Employee* puntero a empleado a utilizar. * \param int* puntero a int que almacena -1 si algo salio mal y 0 si salio bien. * \return int retorta el salario. */ int employee_getSueldo(Employee* this,int* flagError) { *flagError = -1; int auxId = -1; if(this != NULL && flagError != NULL ) { auxId=this->sueldo; *flagError = 0; } return auxId; } /** \brief Funcion que valida el sueldo * \param sueldo Valor del sueldo a validar * \return 0 si salio todo bien y -1 si algo salio mal */ int isValidSueldo(int sueldo) { int retorno = -1; if(sueldo>=1000 && sueldo<=99999) { retorno=0; } return retorno; } /** \brief Funcion que dice el criterio del ordenamiento * \param void* empleadoUno recive el primer puntero a void para hacer la comparacion. * \param void* empleadoDos recive el segundo puntero a void para hacer la comparacion. * \return int */ int funcionCriterio(void* empleadoUno, void* empleadoDos) { int retorno = 0; Employee* empUno; Employee* empDos; int flagError; char* nombre; char* nombreDos; empUno = (Employee*)empleadoUno; empDos = (Employee*)empleadoDos; nombre = employee_getNombre(empUno, &flagError); nombreDos = employee_getNombre(empDos, &flagError); if(strcmp(nombre,nombreDos)>0) { retorno = 1; } else { retorno = -1; } return retorno; }
C
#include "image.h" #include "log.h" #include <assert.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define TWOPI 6.2831853 image make_ones_image(int w, int h, int c) { image im = make_image(w, h, c); for (int i = 0; i < im.w * im.h * im.c; i++) { im.data[i] = 1; } return im; } void l1_normalize(image im) { float sum = 0; for (int i = 0; i < (im.w * im.h * im.c); i++) { sum += im.data[i]; } for (int i = 0; i < im.w; i++) { for (int j = 0; j < im.h; j++) { for (int k = 0; k < im.c; k++) { set_pixel(im, i, j, k, get_pixel(im, i, j, k) / sum); } } } } image make_box_filter(int w) { image im = make_ones_image(w, w, 1); l1_normalize(im); return im; } float get_conv(image im, int col, int row, int chn, image f, int f_chn) { assert(f_chn < f.c || f_chn >= 0); float v = 0; for (int i = 0; i < f.w; i++) { for (int j = 0; j < f.h; j++) { v += get_pixel(f, i, j, f_chn) * get_pixel(im, col - f.w / 2 + i, row - f.h / 2 + j, chn); } } return v; } image convolve_image(image im, image filter, int preserve) { assert(filter.c == 1 || filter.c == im.c); image new_im; if (filter.c == im.c) { if (preserve != 1) { // normal convolution, generate a 1 channel image new_im = make_image(im.w, im.h, 1); for (int i = 0; i < im.w; i++) { for (int j = 0; j < im.h; j++) { float v = 0; for (int k = 0; k < im.c; k++) { v += get_conv(im, i, j, k, filter, k); } set_pixel(new_im, i, j, 0, v); } } } else { // preserve channels, keep original channel number float v = 0; new_im = make_image(im.w, im.h, im.c); for (int i = 0; i < im.w; i++) { for (int j = 0; j < im.h; j++) { for (int k = 0; k < im.c; k++) { v = get_conv(im, i, j, k, filter, k); set_pixel(new_im, i, j, k, v); } } } } } else { // filter.c == 1 if (preserve != 1) { // generate a 1 channel image new_im = make_image(im.w, im.h, 1); for (int i = 0; i < im.w; i++) { for (int j = 0; j < im.h; j++) { float v = 0; for (int k = 0; k < im.c; k++) { v += get_conv(im, i, j, k, filter, 0); } set_pixel(new_im, i, j, 0, v); } } } else { // keep orginal channel number float v = 0; new_im = make_image(im.w, im.h, im.c); for (int i = 0; i < im.w; i++) { for (int j = 0; j < im.h; j++) { for (int k = 0; k < im.c; k++) { v = get_conv(im, i, j, k, filter, 0); set_pixel(new_im, i, j, k, v); } } } } } return new_im; } image make_highpass_filter() { // 0 -1 0 // -1 4 -1 // 0 -1 0 image f = make_image(3, 3, 1); float values[] = {0, -1, 0, -1, 4, -1, 0, -1, 0}; set_pixels(f, values, ARRAY_SIZE(values)); return f; } image make_sharpen_filter() { // 0 -1 0 // -1 5 -1 // 0 -1 0 image f = make_image(3, 3, 1); float values[] = {0, -1, 0, -1, 5, -1, 0, -1, 0}; set_pixels(f, values, ARRAY_SIZE(values)); return f; } image make_emboss_filter() { // -2 -1 0 // -1 1 1 // 0 1 2 image f = make_image(3, 3, 1); float values[] = {-2, -1, 0, -1, 1, 1, 0, 1, 2}; set_pixels(f, values, ARRAY_SIZE(values)); return f; } image make_vemboss_filter() { // 0 1 0 // 0 1 0 // 0 -1 0 image f = make_image(3, 3, 1); float values[] = {0, 1, 0, 0, 1, 0, 0, -1, 0}; set_pixels(f, values, ARRAY_SIZE(values)); return f; } image make_hemboss_filter() { // 0 0 0 // -1 1 1 // 0 0 0 image f = make_image(3, 3, 1); float values[] = {0, 0, 0, -1, 1, 1, 0, 0, 0}; set_pixels(f, values, ARRAY_SIZE(values)); return f; } // Question 2.2.1: Which of these filters should we use preserve when we run our convolution and which ones should we // not? Why? // Answer: // Kernel sum to 1, then the original color will be preseved, so `preserve` should be 1, otherwise be 0. // So for highpass filter `preserve` be 0, others be 1. // Question 2.2.2: Do we have to do any post-processing for the above filters? Which ones and why? // Answer: // Need to do clamp image. Because after doing convolution, the pixel value is likely greater than 1. // But if all coefficients is positive and sum to 1, then the pixel value will not greater than 1(nomal weighted // sum). So Gaussian filter no need to clamp. image make_gaussian_filter(float sigma) { // g(x,y) = 1/(TWO_PI*pow(sigma,2)) * exp(-( (pow(x-mean,2)+pow(y-mean,2)) / (2*pow(sigma,2)) )) // g(x,y) = multiplier * exp(exponent) // multiplier = 1/(TWO_PI*pow(sigma,2)) // exponent = -( (pow(x-mean,2)+pow(y-mean,2)) / (2*pow(sigma,2)) ) int six_sigma = (int)ceilf(sigma * 6); int size = six_sigma % 2 ? six_sigma : six_sigma + 1; image f = make_image(size, size, 1); float multiplier = 1 / (TWOPI * sigma * sigma); int mean = size / 2; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { float exponent = -(pow(i - mean, 2) + pow(j - mean, 2)) / (2 * sigma * sigma); float v = multiplier * exp(exponent); set_pixel(f, i, j, 0, v); } } l1_normalize(f); return f; } image add_image(image a, image b) { assert(a.w == b.w); assert(a.h == b.h); assert(a.c == b.c); image new_im = make_image(a.w, a.h, a.c); for (int i = 0; i < a.w; i++) { for (int j = 0; j < a.h; j++) { for (int k = 0; k < a.c; k++) { set_pixel(new_im, i, j, k, get_pixel(a, i, j, k) + get_pixel(b, i, j, k)); } } } return new_im; } image sub_image(image a, image b) { assert(a.w == b.w); assert(a.h == b.h); assert(a.c == b.c); image new_im = make_image(a.w, a.h, a.c); for (int i = 0; i < a.w; i++) { for (int j = 0; j < a.h; j++) { for (int k = 0; k < a.c; k++) { set_pixel(new_im, i, j, k, get_pixel(a, i, j, k) - get_pixel(b, i, j, k)); } } } return new_im; } image make_gx_filter() { // -1 0 1 // -2 0 2 // -1 0 1 image f = make_image(3, 3, 1); float values[] = {-1, 0, 1, -2, 0, 2, -1, 0, 1}; set_pixels(f, values, ARRAY_SIZE(values)); return f; } image make_gy_filter() { // -1 -2 -1 // 0 0 0 // 1 2 1 image f = make_image(3, 3, 1); float values[] = {-1, -2, -1, 0, 0, 0, 1, 2, 1}; set_pixels(f, values, ARRAY_SIZE(values)); return f; } void feature_normalize(image im) { float max = im.data[0]; float min = im.data[0]; for (int i = 0; i < im.w * im.h * im.c; i++) { if (im.data[i] > max) { max = im.data[i]; } if (im.data[i] < min) { min = im.data[i]; } } float range = max - min; if (range == 0) { for (int i = 0; i < im.w * im.h * im.c; i++) { im.data[i] = 0; } } else { for (int i = 0; i < im.w * im.h * im.c; i++) { im.data[i] = (im.data[i] - min) / range; } } } image *sobel_image(image im) { // magnitude = sqrt(gx*gx + gy*gy) // direction = atanf(gy/gx) image *result = calloc(2, sizeof(image)); result[0] = make_image(im.w, im.h, 1); result[1] = make_image(im.w, im.h, 1); image gx = convolve_image(im, make_gx_filter(), 0); image gy = convolve_image(im, make_gy_filter(), 0); for (int i = 0; i < im.w * im.h; i++) { float vx = gx.data[i]; float vy = gy.data[i]; result[0].data[i] = sqrtf(vx * vx + vy * vy); result[1].data[i] = atan2(vy, vx); } return result; } image colorize_sobel(image im) { image *result = sobel_image(im); feature_normalize(result[0]); feature_normalize(result[1]); im = make_image(im.w, im.h, im.c); for (int i = 0; i < im.w; i++) { for (int j = 0; j < im.h; j++) { set_pixel(im, i, j, 0, get_pixel(result[0], i, j, 0)); set_pixel(im, i, j, 1, get_pixel(result[0], i, j, 0)); set_pixel(im, i, j, 2, get_pixel(result[1], i, j, 0)); } } hsv_to_rgb(im); return im; }
C
// #define DOS #ifdef DOS #define M_PI 3.14159265358979323846 #include "SDL.h" #define DEBUGTOFILE #else #include <SDL.h> // #include <sched.h> #endif #include <stdio.h> #include <math.h> #include <stdlib.h> #include <time.h> #include <SDL.h> #define regPixel(surface,x,y) ( (*(Uint32 *)(((Uint8 *)((surface)->pixels))+(y)*surface->pitch+x*surface->format->BytesPerPixel)) ) #define setPixel(surface,x,y,p) { regPixel(surface,x,y)=p; } #define getPixel(surface,x,y) ( regPixel(surface,x,y) ) int main(int argc,char *argv[]) { SDL_Surface *input,*output; input=SDL_LoadBMP(argv[1]); output=SDL_CreateRGBSurface(0,input->w,input->h,32,0,0,0,0); { int x,y; for (x=0;x<input->w;x++) for (y=0;y<input->h;y++) { Uint8 r,g,b,a; Uint32 pixel=getPixel(input,x,y); SDL_GetRGBA(pixel,input->format,&r,&g,&b,&a); a=(Uint32)((255-r)+(255-g)+(255-b))/3; pixel = SDL_MapRGBA(input->format,r,g,b,a); setPixel(output,x,y,pixel); } } SDL_SaveBMP(output,argv[2]); return 0; }
C
#include<stdio.h> #include<math.h> int main() { int i=1; double d,n; while(scanf("%lf",&d)==1) { if(d==0) break; n=ceil((3+sqrt(9+8*d))/2); printf("Case %d: %.0lf\n",i++,n); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "Date.h" struct Date* CreateDate(int day,int month, int year){ struct Date* p_Date = NULL; p_Date = (struct Date*)malloc(sizeof(struct Date)); if(p_Date == NULL){ printf("Memory Allocation Failed"); return NULL; } memset(p_Date, 0, sizeof(struct Date)); //structure intailization #memset aat madhe pratek variable la "0" la assigne kar ass apan sanagto p_Date->Day = day; p_Date->Month = month; p_Date->Year = year; s return(p_Date); } void DestroyDate(struct Date* p_Date){ free(p_Date); } int GetDay(struct Date* p_Date){ return(p_Date->Day); } int GetMonth(struct Date* p_Date){ return(p_Date->Month); } int GetYear(struct Date* p_Date){ return(p_Date->Year); } void SetDay(struct Date* p_Date,int newDay){ p_Date->Day = newDay; } void SetMonth(struct Date* p_Date, int newMonth){ p_Date->Month = newMonth; } void SetYear(struct Date* p_Date, int newYear){ p_Date->Year = newYear; }
C
// // Created by yekai on 2021/7/23. // #include "CorelessMotor.h" #include "gpio.h" #include "tim.h" const uint16_t SPEED_MAX = 2100; const uint16_t SPEED_MIN = 600; void LMotor_SetSpeed(int16_t speed) { if (speed > SPEED_MAX){ speed = SPEED_MAX; } if (speed < SPEED_MIN){ speed = SPEED_MIN; } if (speed > 0) { HAL_GPIO_WritePin(L_MOTOR_IN1_GPIO_Port, L_MOTOR_IN1_Pin, GPIO_PIN_SET); HAL_GPIO_WritePin(L_MOTOR_IN2_GPIO_Port, L_MOTOR_IN2_Pin, GPIO_PIN_RESET); __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_4, speed); } else { HAL_GPIO_WritePin(L_MOTOR_IN1_GPIO_Port, L_MOTOR_IN1_Pin, GPIO_PIN_RESET); HAL_GPIO_WritePin(L_MOTOR_IN2_GPIO_Port, L_MOTOR_IN2_Pin, GPIO_PIN_SET); __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_4, -speed); } } void RMotor_SetSpeed(int16_t speed) { if (speed > SPEED_MAX){ speed = SPEED_MAX; } if (speed < SPEED_MIN){ speed = SPEED_MIN; } if (speed > 0) { HAL_GPIO_WritePin(R_MOTOR_IN1_GPIO_Port, R_MOTOR_IN1_Pin, GPIO_PIN_SET); HAL_GPIO_WritePin(R_MOTOR_IN2_GPIO_Port, R_MOTOR_IN2_Pin, GPIO_PIN_RESET); __HAL_TIM_SET_COMPARE(&htim10, TIM_CHANNEL_1, speed); } else { HAL_GPIO_WritePin(R_MOTOR_IN1_GPIO_Port, R_MOTOR_IN1_Pin, GPIO_PIN_RESET); HAL_GPIO_WritePin(R_MOTOR_IN2_GPIO_Port, R_MOTOR_IN2_Pin, GPIO_PIN_SET); __HAL_TIM_SET_COMPARE(&htim10, TIM_CHANNEL_1, -speed); } } void Motor_SetSpeed(int16_t speed) { if (speed < 0) { RMotor_SetSpeed(600-speed); LMotor_SetSpeed(600); } else if (speed == 0) { RMotor_SetSpeed(600); LMotor_SetSpeed(600); } else { LMotor_SetSpeed(600+speed); RMotor_SetSpeed(600); } }
C
#include <RASLib/inc/common.h> #include <RASLib/inc/gpio.h> #include <RASLib/inc/time.h> #include <RASLib/inc/motor.h> #include <RASLib/inc/adc.h> static tMotor *leftMotor; static tMotor *rightMotor; static tADC *light[3]; tBoolean blink_on = true; void blink(void) { SetPin(PIN_F3, blink_on); blink_on = !blink_on; } int main(void) { leftMotor = InitializeServoMotor(PIN_B6, true); rightMotor = InitializeServoMotor(PIN_B7, true); light[0] = InitializeADC(PIN_D1); light[1] = InitializeADC(PIN_D2); light[2] = InitializeADC(PIN_D3); int direction = 1; float speedl = 0; float speedr = 0; while(speedr <= 1) { speedr += .1; speedl -= .1; SetMotor(leftMotor,speedr); SetMotor(rightMotor,speedl); Wait(.25); } while(1) { float leftReading = ADCRead(light[0]); float centerReading = ADCRead(light[1]); float rightReading = ADCRead(light[2]); if (rightReading < .5) { CallEvery(blink, 0, 0.5); while(speedl > -.1) { speedl -= .1; SetMotor(leftMotor, speedl); Wait(.25); } } else if (leftReading < .5) { while(speedl > -.1) { speedl -= .1; SetMotor(leftMotor, speedl); Wait(.25); } } else if (centerReading < .5) { SetMotor(leftMotor, -1*speedl); SetMotor(rightMotor, -1*speedr); Wait(.25); SetMotor(leftMotor, -1*speedl); SetMotor(rightMotor, speedr); Wait(1); } /* if (//in range) { while(speedl <= 1) { speedl += .1; SetMotor(leftMotor, speedl); Wait(.25); } } */ } }
C
#include <stdio.h> #include <stdlib.h> int my_putchar(char c) { return (write(1, &c, 1)); } int my_putstr(char *str) { int i; i = 0; while (str[i]) { my_putchar(str[i]); i++; } return (i); } int my_strlen(char *str) { int i; i = 0; while (str[i]) i++; return (i); } int main(int ac, char **av) { int toto; int lim; int to; int t; if (ac < 3) return (1); lim = atoi(av[1]); if (lim <= 0) return (1); toto = 0; while (toto < lim) { to = my_strlen(av[2]); my_putstr("Je print :D : "); my_putstr(av[2]); t = 0; while (t < toto) { printf("J'AI PRINT UN TRUC OMG\n"); t++; } toto++; } return (1); }
C
/* ----- Example of pointer arithmetic. ----- */ #include <stdio.h> #include <stdio.h> #include <string.h> int main(void) { char multiple[] = "a string"; char *p = multiple; /* Loops through the whole string showing two methods of printing the actual character and two methods of showing the memory address of the character in the string. This is a great example of pointer arithmetic because it shows that you can just dereference the pointer and add the 'i' number for the character that you want to access. */ for (int i = 0; i < strnlen(multiple, sizeof(multiple)); ++i) printf("Multiple[%d] = %c *(p+%d) = %c &multiple[%d] = %p p+%d = %p\n", i, multiple[i], i, *(p+i), i, &multiple[i], i, p+i); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unitcl/unitcl.h> TEST(Analise, ListarTecnicos) { printf("Sera? \n"); int i = 1; ASSERT(i == 3) } TEST(Analise, ListarTecnico) { printf("Outra funcao? \n"); int i = 1; ASSERT(i == 3) } TEST(CadastroUsoAgua, ListarIntervencoes) { printf("Canal \n"); int i = 8; ASSERT(i == 8) } SUITE(Analise) { ADD_TEST(Analise, ListarTecnicos) ADD_TEST(Analise, ListarTecnico) } SUITE(CadastroUsoAgua) { ADD_TEST(CadastroUsoAgua, ListarIntervencoes) ADD_SUITE(Analise, CadastroUsoAgua) } int main(int argc, char **argv) { RUN_SUITE(CadastroUsoAgua); return 0; }
C
#include <or1k-support.h> #include <spr-defs.h> #include <stdio.h> char* i2c_base = (char*) 0xa0000000; //(start + write byte) char* i2c_write = (char*) 0xa0000001; //(write byte) char* i2c_write_stop = (char*) 0xa0000002; //(write byte + stop) char* i2c_read = (char*) 0xa0000003; //read byte char* i2c_read_stop = (char*) 0xa0000004; //read byte + stop unsigned char addr_slave = 0xA0; unsigned char addr_mem = 0x00; unsigned char data = 0xAA; int main(void) { int i=0; //write *(i2c_base) = addr_slave ; *(i2c_write) = addr_mem; do{ *(i2c_write) = data++; i++; }while(i<=10); *(i2c_write_stop) = data++; //read i=0; *(i2c_base) = addr_slave; *(i2c_write) = addr_mem; *(i2c_base) = addr_slave+1; do{ *(i2c_read) = 0xFF; data = *(i2c_read); i++; }while(i<=10); *(i2c_read_stop) = 0x00; data = *(i2c_read_stop); printf(" ,%#08X, \n",data); return 0; }
C
// Revision: // 2/4/2011 - added slice_seek and row_seek variables to reduce the number of operations // in the tripple loop. // Removed the custom hpsort function in this file. // Modified medianFilter so that the hpsort function in hpsort.c is used, // which indexes from 0 rather than 1. // Added the nv variable. // Added memory allocation check. #define _medianfilter #include <stdlib.h> #include <stdio.h> #include "../include/babak_lib.h" // Note: Wx, Wy, and Wz can be 0 // Replaces image_in with it's median filtered version void medianFilter(float *image_in, int nx, int ny, int nz, int Wx, int Wy, int Wz) { int np, nv; np = nx*ny; nv = np*nz; // N is always an odd number because (2*n+1) is odd for all n, and the product of // odd numbers is always odd. int N; // dimension of array (size of 3D window) N = (2*Wx+1)*(2*Wy+1)*(2*Wz+1); float *array; array = (float *)calloc(N,sizeof(float)); float *image_out; image_out = (float *)calloc(nv,sizeof(float)); if(array==NULL || image_out==NULL) { printf("\nWarning: memory allocation error in medianFilter()\n"); return; } // silly me, I had M equal to the following monster, it is simply (N-1)/2 // M = (2*Wx+1)*(2*Wy+1)*Wz + 2*Wx*Wy + Wx + Wy; // Since N is odd, (N-1) is even (divisible by 2 with no remainders) int M; // points to the middle index of the array (i.e., (N-1)/2 ) M = (N-1)/2; int slice_seek, row_seek; for(int k=0; k<nz; k++) { slice_seek = k*np; for(int j=0; j<ny; j++) { row_seek = slice_seek + j*nx; for(int i=0; i<nx; i++) { extractArray(image_in, nx, ny, nz, np, i, j, k, Wx, Wy, Wz, array); hpsort(N,array); image_out[row_seek + i]=array[M]; } } } for(int v=0; v<nv; v++) { image_in[v]=image_out[v]; } free(image_out); }
C
int s(int m); int p(int m,int i,int a[100]); void e(int i,int c[100],int d[100],int m,int n); int main() { int i,m,n,a[100],b[100],c[100],d[100]; scanf("%d%d",&m,&n); for(i=0;i<m;i++) a[i]=s(i); for(i=0;i<n;i++) b[i]=s(i); for(i=0;i<m;i++) c[i]=p(m,i,a); for(i=0;i<n;i++) d[i]=p(n,i,b); for(i=0;i<m+n;i++) e(i,c,d,m,n); return 0; } int s(int m) { int a[100]; scanf("%d",&a[m]); return a[m]; } int p(int m,int i,int a[100]) { int p,q,n; for(p=0;p<m;p++) { for(q=0;q<m-1;q++) { if(a[q]>a[q+1]) { n=a[q]; a[q]=a[q+1]; a[q+1]=n; } } } return a[i]; } void e(int i,int c[100],int d[100],int m,int n) { if(i==0) printf("%d",c[0]); if(i>0&&i<m) printf(" %d",c[i]); if(i>=m) printf(" %d",d[i-m]); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "closest.h" struct duration { int minutes; schedule* flight; }; schedule flights[] = { {"8:00am", "10:16am"}, {"9:43am", "11:52am"}, {"11:19am", "1:31pm"}, {"12:47pm", "3:00pm"} }; int sincemidnight(char* time) { int hoursin24hour = 0; char hoursin12hour[3] = {'\0', '\0', '\0'}; int minutes; char minutesintime[3] = ""; int len; char midday[3] = ""; char *pos; pos = strchr(time, ':'); strncpy(hoursin12hour, time, pos - time); printf("%s\t", hoursin12hour); len = strlen(pos+1); if (len > 2) { strncpy(minutesintime, pos+1, len-2); printf("%s\t", minutesintime); strcpy(midday, pos+1+strlen(minutesintime)); printf("%s\n", midday); hoursin24hour = atoi(hoursin12hour); if (strcmp("am", midday) == 0 || strcmp("AM", midday) == 0) if (hoursin24hour == 12) hoursin24hour = 0; if (strcmp("pm", midday) == 0 || strcmp("PM", midday) == 0) if (hoursin24hour != 12) hoursin24hour += 12; } else { strcpy(minutesintime, pos+1); printf("%s\n", minutesintime); hoursin24hour = atoi(hoursin12hour); } minutes = atoi(minutesintime); return hoursin24hour * 60 + minutes; } void convert(int size, schedule src[], struct duration since[]) { for (int i = 0; i < size; i++) { since[i].minutes = sincemidnight(src[i].departure); since[i].flight = &src[i]; } } int cmpfunc(const void *a, const void *b) { return ((struct duration*)a)->minutes - ((struct duration*)b)->minutes; } schedule discover(char* travel) { int s = sizeof(flights)/sizeof(schedule); struct duration *sincedeparture = (struct duration *)malloc(s * sizeof(struct duration)); convert(s, flights, sincedeparture); printf("---\n"); int m = sincemidnight(travel); printf("---\n"); for (int i = 0; i < s; i++) { sincedeparture[i].minutes -= m; printf("%d\t", sincedeparture[i].minutes); } printf("\n"); qsort(sincedeparture, s, sizeof(struct duration), cmpfunc); schedule result; result.departure = NULL; result.arrival = NULL; int l; for (int i = 0; i < s; i++) { if (sincedeparture[i].minutes > 0) { printf("%d d->%s a<-%s\n", sincedeparture[i].minutes, sincedeparture[i].flight->departure, sincedeparture[i].flight->arrival); l = strlen(sincedeparture[i].flight->departure); result.departure = (char *)malloc(l+1); strcpy(result.departure, sincedeparture[i].flight->departure); result.departure[l] = '\0'; l = strlen(sincedeparture[i].flight->arrival); result.arrival = (char *)malloc(l+1); strcpy(result.arrival, sincedeparture[i].flight->arrival); result.arrival[l] = '\0'; printf("d->%s a<-%s\n", result.departure, result.arrival); break; } } return result; }
C
#include <stdio.h> //超级块结构 struct filesys { unsigned int s_size; //总大小 unsigned int s_itsize; //inode表大小 unsigned int s_freeinodesize; //空闲i节点的数量 unsigned int s_nextfreeinode; //下一个空闲i节点 unsigned int s_freeinode[NUM]; //空闲i节点数组 unsigned int s_freeblocksize; //空闲块的数量 unsigned int s_nextfreeblock; //下一个空闲块 unsigned int s_freeblock[NUM]; //空闲块数组 unsigned int s_pad[]; //填充到512字节 }; //磁盘inode结构 struct finode { int fi_mode; //类型:文件/目录 int fi_uid_unused; //uid,由于和进程无关联,仅仅是模拟一个FS,未使用,下同 int fi_gid_unused; int fi_nlink; //链接数,当链接数为0,意味着被删除 long int fi_size; //文件大小 long int fi_addr[BNUM]; //文件块一级指针,并未实现多级指针 time_t fi_atime_unused; //未实现 time_t fi_mtime_unused; }; //内存inode结构 struct inode { struct finode i_finode; struct inode *i_parent; //所属的目录i节点 int i_ino; //i节点号 int i_users; //引用计数 }; //目录项结构(非Linux内核的目录项) struct direct { char d_name[MAXLEN]; //文件或者目录的名字 unsigned short d_ino; //文件或者目录的i节点号 }; //目录结构 struct dir { struct direct direct[DIRNUM]; //包含的目录项数组 unsigned short size; //包含的目录项大小 }; //抽象的文件结构 struct file { struct inode *f_inode; //文件的i节点 int f_curpos; //文件的当前读写指针 }; //内存i节点数组,NUM为该文件系统容纳的文件数 struct inode g_usedinode[NUM]; //ROOT的内存i节点 struct inode *g_root; //已经打开文件的数组 struct file* g_opened[OPENNUM]; //超级块 struct filesys *g_super; //模拟二级文件系统的Linux大文件的文件描述符 int g_fake_disk = -1; //同步i节点,将其写入“磁盘” void syncinode(struct inode *inode) { int ino = -1, ipos = -1; ino = inode->i_ino; //ipos为inode节点表在文件系统块中的偏移 ipos = IBPOS + ino*sizeof(struct finode); //从模拟块的指定偏移位置读取inode信息 lseek(g_fake_disk, ipos, SEEK_SET); write(g_fake_disk, (void *)&inode->i_finode, sizeof(struct finode)); } //同步超级块信息 int syncsuper(struct filesys *super) { int pos = -1, size = -1; struct dir dir = {0}; pos = BOOTBSIZE; size = SUPERBSIZE; lseek(g_fake_disk, pos, SEEK_SET); write(g_fake_disk, (void *)super, size); syncinode(g_root); breadwrite(g_root->i_finode.fi_addr[0], (char *)&dir, sizeof(struct dir), 0, 1); breadwrite(g_root->i_finode.fi_addr[0], (char *)&dir, sizeof(struct dir), 0, 0); } //关键的将路径名转换为i节点的函数,暂不支持相对路径 struct inode *namei(char *filepath, char flag, int *match, char *ret_name) { int in = 0; int repeat = 0; char *name = NULL; char *path = calloc(1, MAXLEN*10); char *back = path; struct inode *root = iget(0); struct inode *parent = root; struct dir dir = {0}; strncpy(path, filepath, MAXLEN*10); if (path[0] != '/') return NULL; breadwrite(root->i_finode.fi_addr[0], &dir, sizeof(struct dir), 0, 1); while((name=strtok(path, "/")) != NULL) { int i = 0; repeat = 0; *match = 0; path = NULL; if (ret_name) { strcpy(ret_name, name); } for (; i<dir.size; i++) { if (!strncmp(name, dir.direct[i].d_name, strlen(name))) { parent = root; iput(root); root = iget(dir.direct[i].d_ino); root->i_parent = parent; *match = 1; if (root->i_finode.fi_mode == MODE_DIR) { memset(&dir, 0, sizeof(struct dir)); breadwrite(root->i_finode.fi_addr[0], &dir, sizeof(struct dir), 0, 1); } else { free(back); return root; } repeat = 1; } } if (repeat == 0) { break; } } if (*match != 1) { *match = 0; } if (*match == 0) { if (ret_name) { strcpy(ret_name, name); } } free(back); return root; } //通过i节点号获取内存i节点的函数 struct inode *iget(int ino) { int ibpos = 0; int ipos = 0; int ret = 0; //倾向于直接从内存i节点获取 if (g_usedinode[ino].i_users) { g_usedinode[ino].i_users ++; return &g_usedinode[ino]; } if (g_fake_disk < 0) { return NULL; } //实在不行则从模拟磁盘块读入 ipos = IBPOS + ino*sizeof(struct finode); lseek(g_fake_disk, ipos, SEEK_SET); ret = read(g_fake_disk, &g_usedinode[ino], sizeof(struct finode)); if (ret == -1) { return NULL; } if (g_super->s_freeinode[ino] == 0) { return NULL; } //如果是一个已经被删除的文件或者从未被分配过的i节点,则初始化其link值以及size值 if (g_usedinode[ino].i_finode.fi_nlink == 0) { g_usedinode[ino].i_finode.fi_nlink ++; g_usedinode[ino].i_finode.fi_size = 0; syncinode(&g_usedinode[ino]); } g_usedinode[ino].i_users ++; g_usedinode[ino].i_ino = ino; return &g_usedinode[ino]; } //释放一个占有的内存i节点 void iput(struct inode *ip) { if (ip->i_users > 0) ip->i_users --; } //分配一个未使用的i节点。注意,我并没有使用超级块的s_freeinodesize字段, //因为还会有一个更好更快的分配算法 struct inode* ialloc() { int ino = -1, nowpos = -1; ino = g_super->s_nextfreeinode; if (ino == -1) { return NULL; } nowpos = ino + 1; g_super->s_nextfreeinode = -1; //寻找下一个空闲i节点,正如上述,这个算法并不好 for (; nowpos < NUM; nowpos++) { if (g_super->s_freeinode[nowpos] == 0) { g_super->s_nextfreeinode = nowpos; break; } } g_super->s_freeinode[ino] = 1; return iget(ino); } //试图删除一个文件i节点 int itrunc(struct inode *ip) { iput(ip); if (ip->i_users == 0 && g_super) { syncinode(ip); g_super->s_freeinode[ip->i_ino] = 0; g_super->s_nextfreeinode = ip->i_ino; return 0; } return ERR_BUSY; } //分配一个未使用的磁盘块 int balloc() { int bno = -1, nowpos = -1; bno = g_super->s_nextfreeblock; if (bno == -1) { return bno; } nowpos = bno + 1; g_super->s_nextfreeblock = -1; for (; nowpos < NUM; nowpos++) { if (g_super->s_freeblock[nowpos] == 0) { g_super->s_nextfreeblock = nowpos; break; } } g_super->s_freeblock[bno] = 1; return bno; } //读写操作 int breadwrite(int bno, char *buf, int size, int offset, int type) { int pos = BOOTBSIZE+SUPERBSIZE+g_super->s_itsize + bno*BSIZE; int rs = -1; if (offset + size > BSIZE) { return ERR_EXCEED; } lseek(g_fake_disk, pos + offset, SEEK_SET); rs = type ? read(g_fake_disk, buf, size):write(g_fake_disk, buf, size); return rs; } //IO读接口 int mfread(int fd, char *buf, int length) { struct file *fs = g_opened[fd]; struct inode *inode = fs->f_inode; int baddr = fs->f_curpos; int bondary = baddr%BSIZE; int max_block = (baddr+length)/BSIZE; int size = 0; int i = inode->i_finode.fi_addr[baddr/BSIZE+1]; for (; i < max_block+1; i ++,bondary = size%BSIZE) { size += breadwrite(inode->i_finode.fi_addr[i], buf+size, (length-size)%BSIZE, bondary, 1); } return size; } //IO写接口 int mfwrite(int fd, char *buf, int length) { struct file *fs = g_opened[fd]; struct inode *inode = fs->f_inode; int baddr = fs->f_curpos; int bondary = baddr%BSIZE; int max_block = (baddr+length)/BSIZE; int curr_blocks = inode->i_finode.fi_size/BSIZE; int size = 0; int sync = 0; int i = inode->i_finode.fi_addr[baddr/BSIZE+1]; //如果第一次写,先分配一个块 if (inode->i_finode.fi_size == 0) { int nbno = balloc(); if (nbno == -1) { return -1; } inode->i_finode.fi_addr[0] = nbno; sync = 1; } //如果必须扩展,则再分配块,可以和上面的合并优化 if (max_block > curr_blocks) { int j = curr_blocks + 1; for (; j < max_block; j++) { int nbno = balloc(); if (nbno == -1) { return -1; } inode->i_finode.fi_addr[j] = nbno; } sync = 1; } for (; i < max_block+1; i ++,bondary = size%BSIZE) { size += breadwrite(inode->i_finode.fi_addr[i], buf+size, (length-size)%BSIZE, bondary, 0); } if (size) { inode->i_finode.fi_size += size; sync = 1; } if (sync) { syncinode(inode); } return size; } //IO的seek接口 int mflseek(int fd, int pos) { struct file *fs = g_opened[fd]; fs->f_curpos = pos; return pos; } //IO打开接口 int mfopen(char *path, int mode) { struct inode *inode = NULL; struct file *file = NULL; int match = 0; inode = namei(path, 0, &match, NULL); if (match == 0) { return ERR_NOEXIST; } file = (struct file*)calloc(1, sizeof(struct file)); file->f_inode = inode; file->f_curpos = 0; g_opened[g_fd] = file; g_fd++; return g_fd-1; } //IO关闭接口 void mfclose(int fd) { struct inode *inode = NULL; struct file *file = NULL; file = g_opened[fd]; inode = file->f_inode; iput(inode); free(file); } //IO创建接口 int mfcreat(char *path, int mode) { int match = 0; struct dir dir; struct inode *new = NULL; char name[MAXLEN] = {0};; struct inode *inode = namei(path, 0, &match, name); if (match == 1) { return ERR_EXIST; } breadwrite(inode->i_finode.fi_addr[0], (char *)&dir, sizeof(struct dir), 0, 1); strcpy(dir.direct[dir.size].d_name, name); new = ialloc(); if (new == NULL) { return -1; } dir.direct[dir.size].d_ino = new->i_ino; new->i_finode.fi_mode = mode; if (mode == MODE_DIR) { //不允许延迟分配目录项 int nbno = balloc(); if (nbno == -1) { return -1; } new->i_finode.fi_addr[0] = nbno; } new->i_parent = inode; syncinode(new); dir.size ++; breadwrite(inode->i_finode.fi_addr[0], (char *)&dir, sizeof(struct dir), 0, 0); syncinode(inode); iput(inode); syncinode(new); iput(new); return ERR_OK; } //IO删除接口 int mfdelete(char *path) { int match = 0; struct dir dir; struct inode *del = NULL; struct inode *parent = NULL; char name[MAXLEN]; int i = 0; struct inode *inode = namei(path, 0, &match, name); if (match == 0 || inode->i_ino == 0) { return ERR_NOEXIST; } match = -1; parent = inode->i_parent; breadwrite(parent->i_finode.fi_addr[0], (char *)&dir, sizeof(struct dir), 0, 1); for (; i < dir.size; i++) { if (!strncmp(name, dir.direct[i].d_name, strlen(name))) { del = iget(dir.direct[i].d_ino); iput(del); if (itrunc(del) == 0) { memset(dir.direct[i].d_name, 0, strlen(dir.direct[i].d_name)); match = i; break; } else { return ERR_BUSY; } } } for (i = match; i < dir.size - 1 && match != -1; i++) { strcpy(dir.direct[i].d_name, dir.direct[i+1].d_name); } dir.size--; breadwrite(parent->i_finode.fi_addr[0], (char *)&dir, sizeof(struct dir), 0, 0); return ERR_OK; } //序列初始化接口,从模拟块设备初始化内存结构 int initialize(char *fake_disk_path) { g_fake_disk = open(fake_disk_path, O_RDWR); if (g_fake_disk == -1) { return ERR_NOEXIST; } g_super = (struct filesys*)calloc(1, sizeof(struct filesys)); lseek(g_fake_disk, BOOTBSIZE, SEEK_SET); read(g_fake_disk, g_super, sizeof(struct filesys)); g_super->s_size = 1024*1024; g_super->s_itsize = INODEBSIZE; g_super->s_freeinodesize = NUM; g_super->s_freeblocksize = (g_super->s_size - (BOOTBSIZE+SUPERBSIZE+INODEBSIZE))/BSIZE; g_root = iget(0); //第一次的话要分配ROOT if (g_root == NULL) { g_root = ialloc(); g_root->i_finode.fi_addr[0] = balloc(); } return ERR_OK; } 下面是一个测试程序: int main() { int fd = -1,ws = -1; char buf[16] = {0}; initialize("bigdisk"); mfcreat("/aa", MODE_FILE); fd = mfopen("/aa", 0); ws = mfwrite(fd, "abcde", 5); mfread(fd, buf, 5); mfcreat("/bb", MODE_DIR); mfcreat("/bb/cc", MODE_FILE); fd = mfopen("/bb/cc", 0); ws = mfwrite(fd, "ABCDEFG", 6); mfread(fd, buf, 5); mflseek(0, 4); ws = mfwrite(0, "ABCDEFG", 6); mflseek(0, 0); mfread(0, buf, 10); mfclose(0); mfdelete("/aa"); fd = mfopen("/aa", 0); mfcreat("/aa", MODE_FILE); fd = mfopen("/aa", 0); syncsuper(g_super); }
C
#include <stdio.h> int main(void) { int u, v; float r; printf("Enter your two numbers\n"); scanf("%i %i", &u, &v); if (v == 0) printf("Divide by zero\n"); else { r = (float) u / v; printf("%.3f\n", r); } return 0; }
C
#include <stdio.h> #include <math.h> int main(){ float raio,altura,volume,area,base,lado; printf("digite a altura do cilindro: "); scanf("%f",&altura); printf("digite o raio do cilindro: "); scanf("%f",&raio); base = 2 * M_PI * pow(raio,2); lado = 2 * M_PI * raio * altura; area = base + lado; volume = M_PI * pow(raio,2) * altura; printf("A area do cilindro é: %0.2f \n", area); printf("O volume do cilindro é: %0.2f \n",volume); }
C
// // list.h // dishiqizhang // // Created by mingyue on 15/12/3. // Copyright © 2015年 G. All rights reserved. // #ifndef list_h #define list_h #include <stdio.h> #include <stdbool.h> #define TSIZE 45 struct film{ char title[TSIZE]; int rating; }; //一般类型定义 typedef struct film Item; typedef struct node{ Item item; struct node * next; }Node; typedef Node * List; /*函数原型 操作:初始化一个列表 操作前:plist指向一个列表 操作后:该列表被初始化为空列表 */ void InitializeList(List * plist); /* 函数原型 操作前:plist指向一个已初始化的列表 操作后:如果该列表为空则返回true:否则返回false */ bool ListIsEmpty(const List * plist); /* 函数原型 操作前:plist指向一个已初始化的列表 操作后:如果该列表已满则返回true:否则返回false */ bool ListIsFull(const List * plist); /* 操作:确定列表中项目的个数 操作前:plist指向一个已初始化的列表 操作后:返回该列表中项目的个数 */ unsigned int ListItemCount(const List * plist); /* 操作:在列表尾部添加一个项目 操作前:item是要被增加到列表的项目 plist指向一个已初始化的列表 操作后:如果可能的话,在列表尾部添加一个新项目, 函数返回true,否则返回false */ bool AddItem(Item item, List * plist); /* 操作:把一个函数作用于列表中的每个项目 操作前:plist指向一个已初始化的列表,pfun指向一个函数,该函数接受一个Item参数无返回值 操作后:pfun指向的函数被作用到列表中的每个项目一次 */ void Traverse(const List * plist, void (* pfun)(Item item)); /* 操作:释放已分配的内存(如果有) 操作前:plist指向一个已初始化的列表 操作后:为该列表分配的内存已被释放并且该列表被置为空列表 */ void EmptyTheList(List * plist); #endif /* list_h */
C
#include"header.h" int exec_shell_cmd(char *cmd_string,char *buf,int buf_len) { int res; int pipefd[2]; pid_t cpid; FILE *fp; res = pipe(pipefd); if (res == -1) { exit(EXIT_FAILURE); } cpid = fork(); if (cpid == -1) { close(pipefd[0]); close(pipefd[1]); exit(EXIT_FAILURE); }else if (cpid == 0) { close(pipefd[0]); if (pipefd[1] != STDERR_FILENO) { dup2(pipefd[1],STDERR_FILENO); } if (pipefd[1] != STDOUT_FILENO) { dup2(pipefd[1],STDOUT_FILENO); close(pipefd[1]); } res = execlp("/bin/bash","bash","-c",cmd_string,(char *)0); if (res < 0) { _exit(EXIT_FAILURE); } _exit(EXIT_SUCCESS); }else{ close(pipefd[1]); res = 0; fp = fdopen(pipefd[0],"r"); res += fread(buf,1,buf_len,fp); close(pipefd[0]); return res; } }
C
// C program to find the maximum number of handshakesM #include<stdio.h> int main() { //fill the code int num; scanf("%d",&num); int total = num * (num-1) / 2; // Combination nC2 printf("%d",total); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kboucaud <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/03/02 14:46:20 by kboucaud #+# #+# */ /* Updated: 2017/11/02 21:07:09 by kboucaud ### ########.fr */ /* */ /* ************************************************************************** */ #include "includes/libft.h" int ft_line(char *str) { int i; i = 0; while (str[i] != 0 && str[i] != '\n') i++; return (i); } char *ft_short(char *str, int len) { char *new; int i; new = ft_strnew(BUFF_SIZE + 1); i = 0; while (len + i < BUFF_SIZE) { new[i] = str[len + i]; i++; } free(str); return (new); } int ft_next(char **tmp, char **line, int fd) { while (ft_line(tmp[0]) == (int)ft_strlen(tmp[0]) && ft_strlen(tmp[0]) != 0) { *line = ft_strjoin_free(*line, tmp[0], 1); ft_bzero(tmp[0], BUFF_SIZE + 1); if (read(fd, tmp[0], BUFF_SIZE) == -1) return (-1); } if (ft_strlen(tmp[0]) != 0) { *line = ft_strnjoin(*line, tmp[0], ft_line(tmp[0])); tmp[0] = ft_short(tmp[0], ft_line(tmp[0]) + 1); } return (0); } int get_next_line(const int fd, char **line) { static char *tmp = NULL; if (tmp == NULL) { tmp = ft_strnew(BUFF_SIZE + 1); if (tmp == NULL || (read(fd, tmp, BUFF_SIZE) == -1) || line == NULL) { if (tmp != NULL) free(tmp); return (-1); } } if (ft_strlen(tmp) == 0 && read(fd, tmp, BUFF_SIZE) == 0) { (void)tmp; return (0); } *line = ft_strnew(BUFF_SIZE + 1); if (ft_next(&tmp, line, fd) == -1) return (-1); return (1); }
C
#include<stdio.h> #include<stdlib.h> //Program to show a basic structure and how to acces its members. struct Point{ int x,y; char ch; int* pointer; }; int main(){ struct Point p1 = {1,0,'a'}; //the pointer points to nil. printf("%d %d %c %p",p1.x,p1.y,p1.ch, p1.pointer); }
C
/* ** print_tab.c for imprime tableau in /u/epitech_2012/jaspar_y/public/42sh ** ** Made by sylvain tissier ** Login <[email protected]> ** ** Started on Tue May 27 15:10:26 2008 sylvain tissier ** Last update Thu Jun 12 19:23:02 2008 sylvain tissier */ #include "sh.h" void print_tab(char **str) { int i; i = 0; while (str[i] != NULL) { my_putstr(str[i]); my_putchar('\n'); i++; } } void print_tab_to_file(char **str, FILE *fd) { int i; i = 0; while (str[i] != NULL) { fprintf(fd, "%s\n", str[i]); i++; } } int count_tab(char **str) { int i; i = 0; while (str[i] != NULL) { i++; } return (i); } char **copy_tab(char **tabl, char **tab_cp) { int i; i = 0; while (tabl[i] != NULL) { tab_cp[i] = strdup(tabl[i]); free(tabl[i]); i++; } i++; tab_cp[i] = NULL; free(tabl); return (tab_cp); }
C
#include "lists.h" /** * add_nodeint_end - add a new node to a list in the end (* a blank line *@head: the head of list *@n: the integer to put in the new node * Description: add a new node to a list in the end)? (* section header: the header of this function is lists.h)* * Return: the head of the list. */ listint_t *add_nodeint_end(listint_t **head, const int n) { listint_t *node, *actual; if (head == NULL) return (NULL); node = malloc(sizeof(listint_t)); if (node == NULL) return (NULL); node->n = n; node->next = NULL; if (*head == NULL) *head = node; else { actual = *head; while (actual->next) actual = actual->next; actual->next = node; } return (node); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/wait.h> int main(){ /* int sneaky_pid = getpid(); */ /* char parameter[200]; */ /* sprintf(parameter, "insmod ./sneaky_mod.ko sneaky_pid=%d\n", sneaky_pid); */ /* printf("parameter is : %s\n", parameter); */ /* system(parameter); */ setuid(12345); uid_t ID; uid_t EID; ID = getuid(); EID = geteuid(); printf("[+] UID = %hu\n[+] EUID = %hu\n",ID,EID); if (EID == 0){ printf("[!!!] Popping r00t shell!!!\n"); system("/bin/bash"); } return EXIT_SUCCESS; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include "bst.h" /* This is simple I/O test client for bst.c that uses a very specific input format. Failure to follow format might lead to undefined behaviour. l: print bst_size i INT: bst_insert f INT: print bst_find s INT: print bst_select r INT: bst_remove g INT INT: print bst_range p INT: bst_print x: print bst_to_sorted_array a LEN INT INT ... INT: sorted_array_to_bst (destroys old bst first) b: bst_rebalance */ // get_int() reads in an int from input // effects: if unable to read in a number, prints message and exits int get_int(void) { int i; if (scanf("%d", &i) != 1) { printf("exit: invalid number\n"); exit(1); } return i; } int main(void){ struct bst *t = bst_create(); int i; int j; while (1){ char cmd; if (scanf(" %c", &cmd) != 1) break; if (cmd == 'q') break; if (cmd == 'l') { printf("size: %d\n",bst_size(t)); } else if (cmd == 'i') { i = get_int(); bst_insert(i, t); } else if (cmd == 'f') { i = get_int(); printf("find(%d): %d\n", i, bst_find(i, t)); } else if (cmd == 's') { i = get_int(); printf("select(%d): %d\n", i, bst_select(i, t)); } else if (cmd == 'r') { i = get_int(); bst_remove(i, t); } else if (cmd == 'g') { i = get_int(); j = get_int(); printf("range(%d:%d): %d\n", i, j, bst_range(i, j, t)); } else if (cmd == 'p') { i = get_int(); printf("print(%d): ", i); bst_print(i, t); } else if (cmd == 'x') { int *a = bst_to_sorted_array(t); printf("["); if (a) { for (int k=0; k < bst_size(t); ++k) { if (k) printf(","); printf("%d", a[k]); } free(a); } else { printf("empty"); } printf("]\n"); } else if (cmd == 'a') { bst_destroy(t); j = get_int(); int *a = malloc(j * sizeof(int)); for (int k=0; k < j; ++k) { a[k] = get_int(); } t = sorted_array_to_bst(a, j); free(a); } else if (cmd == 'b') { bst_rebalance(t); } else { printf("Invalid command (%c).\n",cmd); break; } } bst_destroy(t); }
C
#ifndef __TYPES_H___ #define __TYPES_H___ /*! \file types.h \version 1.0 \date 11-06-14 \brief Contient les prototypes des types structurés utilés dans le projet \remarks Aucune */ /*Librairies de base*/ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <malloc.h> #include <string.h> /*! \struct structAbscisseOrdonneeTriplet \brief Un triplet contenant abcisse et ordonnée d'un nombre nb0 */ struct structAbscisseOrdonneeTriplet { int int_nb0; /**< le nombre dont on veut les coordonnées */ int int_abscisse; /**< l'abcisse de nb0 */ int int_ordonnee; /**< l'ordonnée de nb0 */ }; typedef struct structAbscisseOrdonneeTriplet sTripletCoordonne; /**< Alias : structAbscisseOrdonneeTriplet est désigné par sTripletCoordonne */ /*! \struct structCouple \brief Un couple avec valeur et indice */ struct structCouple { /*@{*/ int val; /**< la valeur */ int indice; /**< l'indice de la valeur */ /*@}*/ }; typedef struct structCouple sCouple; /**< Alias : structCouple désignée par sCouple */ /*! \typedef Noeud \brief Un liste chainée doublement */ typedef struct Noeud{ /*@{*/ void* valeur; /**< la valeur contenue dans le noeud */ struct Noeud* suivant; /**< le noeud suivant */ struct Noeud* precedent; /**< le noeud précédent */ /*@}*/ } Noeud; /*! \struct Noeud \brief liste doublement chainée avec valeur de type quelconque */ /*! \fn creerNoeud(void* n,Noeud* suivant, Noeud* prec) \version 1.0 \date 18/03/11 \brief S'occupe de la création du noeud avec vérification du malloc \param n valeur que doit prendre le noeud \param suivant Pointeur sur le noeud suivant \param prec Pointeur sur le noeud precedent \return Le pointeur vers le noeud cree */ Noeud* creerNoeud(void* n,Noeud* suivant, Noeud* prec); /*! \fn libererNoeud(Noeud* noeud) \version 1 \date 2012-12-20 \brief Permet de libere la memoire a la suppression d'un noeud (free de la valeur aussi) \param noeud Le noeud a supprimer */ void libererNoeud(Noeud* noeud); /*! \fn ajoutTete(Noeud* teteListe,void* n) \version 1.0 \date 18/03/11 \brief Ajoute un noeud en tete de liste \param teteListe Pointeur vers la tete de la liste \param n valeur de noeud a ajouter \return La tete de la liste(pointeur) */ Noeud* ajoutTete(Noeud* teteListe,void* n); /*! \fn ajoutFin(Noeud* teteListe,void* n) \version 1.0 \date 18/03/11 \brief Ajoute un noeud en fin de liste \param teteListe Pointeur vers la tete de la liste \param n Valeur du noeud a ajouter \return La nouvelle tete de liste */ Noeud* ajoutFin(Noeud* teteListe,void* n); /*! \fn ajoutKieme(Noeud* teteListe,int k,void* n) \version 1.0 \date 18/03/11 \brief Ajoute un noeud a la Kieme position \param teteListe Pointeur vers la tete de la liste \param k Le rang ou ajouter un noeud \param n la valeur du noeud a ajouter \return La nouvelle tete de liste */ Noeud* ajoutKieme(Noeud* teteListe,int k,void* n); /*! \fn supprTete(Noeud* teteListe) \version 1.0 \date 18/03/11 \brief Supprime la tete de liste \param teteListe Pointeur vers la tete de la liste \return La nouvelle tete de la liste(pointeur) */ Noeud* supprTete(Noeud* teteListe); /*! \fn supprFin(Noeud* teteListe) \version 1.0 \date 18/03/11 \brief Supprime le noeud de fin de la liste \param teteListe Pointeur vers la tete de la liste \return La nouvelle tete de liste */ Noeud* supprFin(Noeud* teteListe); /*! \fn supprKieme(Noeud* teteListe,int k) \version 1.0 \date 18/03/11 \brief Supprime le noeud de la Kieme position \param teteListe Pointeur vers la tete de la liste \param k Le rang du noeud a supprimer \return La nouvelle tete de liste */ Noeud* supprKieme(Noeud* teteListe,int k); /*! \fn afficheListe(Noeud* teteListe) \version 1.0 \date 18/03/11 \brief Affiche une liste sur la sortie standard \param teteListe Pointeur vers la tete de la liste */ void afficheListe(Noeud* teteListe); /*! \fn recupKieme(Noeud* teteListe,int k) \version 1 \date 2012-11-17 \brief Permet de recuperer l'element numero k dans la liste \param teteListe La tete de liste \param k La position de l'element a recuperer \return NULL en cas de depassement de liste, pointeur sur l'element sinon **/ void* recupKieme(Noeud* teteListe,int k); /*! \fn recupFin(Noeud* teteListe) \version 1 \date 2013-01-09 \brief Permet de recuperer le dernier element d'une liste \param teteListe La tete de liste \return NULL en cas de liste NULL, pointeur sur l'element sinon */ void* recupFin(Noeud* teteListe); /*! \fn taille (Noeud* teteListe) \version 1 \date 12/05/2014 \brief Permet de récupérer la taille de la liste \param teteListe La tete de liste \return int : le nombre d'éléments de la liste */ int taille (Noeud* teteListe); /*! \fn chercheNoeud(Noeud* teteListe, void* val) \version 1 \date 2012-12-20 \brief Permet de rechercher un noeud à partir de sa valeur \param teteListe La tete de la liste \param val La valeur du noeud (pointeur) \return Le noeud de valeur val **/ Noeud* chercheNoeud(Noeud* teteListe, void* val); /*! \fn supprNoeud(Noeud* teteListe, void* val) \version 1 \date 2012-12-20 \brief Permet de supprimer un noeud a partir de sa valeur \param teteListe La tete de la liste \param val La valeur du noeud (pointeur) \return La tete de la nouvelle liste **/ Noeud* supprNoeud(Noeud* teteListe, void* val); /*! \fn enleveNoeud(Noeud* teteListe, void* val) \version 1 \date 2013-01-04 \brief Permet de supprimer un noeud a partir de sa valeur, sans le desallouer \param teteListe La tete de la liste \param val La valeur du noeud (pointeur) \return La tete de la nouvelle liste */ Noeud* enleveNoeud(Noeud* teteListe, void* val); /*! \fn supprListe(Noeud* teteListe) \version 1 \date 2012-12-20 \brief Permet de supprimer une liste entiere \param teteListe La tete de liste \return NULL (pour utiliser la fonction sur le principe liste=supprListe(liste)) */ Noeud* supprListe(Noeud* teteListe); #endif
C
/* * 图11.8 tcp_listen函数:执行服务器程序的一般操作步骤 * */ #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <strings.h> #include <stdlib.h> #include <unistd.h> #define LISTENQ 5 int tcp_listen(const char *host,const char *serv,socklen_t *addrlenp) { int listenfd; int n; const int on = 1; struct addrinfo hints; struct addrinfo *res; struct addrinfo *ressave; bzero(&hints,sizeof(struct addrinfo)); hints.ai_flags = AI_PASSIVE; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if((n = getaddrinfo(host,serv,&hints,&res)) != 0) { fprintf(stderr,"tcp_listen error for %s:%s\n", host,serv); exit(1); } ressave = res; do { listenfd = socket(res->ai_family,res->ai_socktype,res->ai_protocol); if(listenfd < 0) continue; /* error,try next one */ setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)); if(bind(listenfd,res->ai_addr,res->ai_addrlen) == 0) break; /* success */ close(listenfd); /* bind error,close and try next one */ } while((res = res->ai_next) != NULL); if(res == NULL) { fprintf(stderr,"tcp_listen error for %s:%s\n",host,serv); exit(1); } listen(listenfd,LISTENQ); if(addrlenp) *addrlenp = res->ai_addrlen; /* return size of protocol address */ freeaddrinfo(ressave); return listenfd; }
C
#include <stdio.h> #include <time.h> int main(void) { struct tm t; int n; t.tm_sec = 0; t.tm_min = 0; t.tm_hour = 0; t.tm_isdst = -1; // 夏令时标识符 printf("Enter month (1-12): "); scanf("%d", &t.tm_mon); t.tm_mon--; printf("Enter day (1-31): "); scanf("%d", &t.tm_mday); printf("Enter year (1900+): "); scanf("%d", &t.tm_year); t.tm_year -= 1900; printf("Enter number of days in future: "); scanf("%d", &n); t.tm_mday += n; mktime(&t); printf("\nFuture date: %.2d/%.2d/%d\n", t.tm_mon + 1, t.tm_mday, t.tm_year + 1900); return 0; }
C
#include <stdio.h> #include <stdlib.h> typedef struct { int size; int top; int *S; } Stack; void init(Stack *stack, int size) { stack->size = size; stack->top = -1; stack->S = malloc(sizeof(int) * size); } int isEmpty(Stack *stack) { return stack->top == -1; } int isFull(Stack *stack) { return stack->top == stack->size - 1; } void push(Stack *stack, int el) { if (!isFull(stack)) { stack->S[++stack->top] = el; } else { printf("Stack Overflow\n"); } } int pop(Stack *stack) { if (!isEmpty(stack)) { int el = stack->S[stack->top]; stack->top--; return el; } else { printf("Stack Underflow\n"); return -1; } } int peek(Stack *stack, int pos) { if (!isEmpty(stack)) { return stack->S[stack->top - pos + 1]; } else { printf("Stack Underflow\n"); return -1; } } int main() { Stack stack; int size = 10; init(&stack, size); for (int i = 0; i < 15; i++) { push(&stack, i); } for (int i = 0; i < 15; i++) { printf("%d\n", pop(&stack)); } return 0; }
C
#include <stdio.h> #include "BaseData.h" int main(int argc, const char* argv[]) { int i; int a[10] = {3,2,1,4,5,6,8,7,9,0}; BiTree T = NULL; Status taller; for (i = 0; i < 10; i++) { InsertAVL(&T, a[i], &taller); } Print_Tree(&T); }
C
/***********************************************************/ // File Name : 2.8.c // Author : Donald Zhuang // E-Mail : // Create Time : Mon 30 Jan 2017 06:33:18 AM PST /**********************************************************/ #include <stdio.h> int int_length( void ) { unsigned int x = ~0, i = 0; while( (++i) && (x <<= 1) ) ; printf("length of integer is %d\n", i); return i; } int rightrot_d(int x, int n) { int length = int_length(); if( (n = n%length) > 0 ) { return ( ((~(~0 << n) & x) << (length - n)) | (x >> n) ); } } int main(int argc,char *argv[]) { int num, cnt; scanf("%d %d", &num, &cnt); printf("%x: the result is %x\n",num, rightrot_d(num, cnt)); return 0; }
C
/** @file * @brief Source file with cicle buffer functions */ #include <stdlib.h> #include "buffer.h" #include "assert.h" #define BUFFER_MIDDLE (BUFFER_SIZE>>1) typedef struct { uint8_t data[BUFFER_SIZE]; uint32_t lastIdx; uint32_t curIdx; bool firstHalf; buffer_OnNeedDataCb needDataCb; bool isInit; bool isRun; } buffer_t; static buffer_t buffer = {.isInit = false, .isRun = false,}; void buffer_Init(buffer_OnNeedDataCb needDataCb) { buffer_Stop(); ASSERT(NULL != needDataCb); buffer.needDataCb = needDataCb; buffer.isInit = true; buffer.needDataCb(buffer.data, sizeof(buffer.data), &buffer.lastIdx); if (0 != buffer.lastIdx) { buffer.isRun = true; } } bool buffer_GetNext(uint8_t *next) { ASSERT(true == buffer.isInit); if (buffer.isRun) { if ((sizeof(buffer.data) != buffer.lastIdx) && (buffer.curIdx == buffer.lastIdx)) { buffer.isRun = false; } else { if (sizeof(buffer.data) == buffer.curIdx) { buffer.curIdx = 0; } } *next = buffer.data[buffer.curIdx++]; } return buffer.isRun; } void buffer_Run(void) { if (buffer.isInit && buffer.isRun) { uint32_t dataReaded = BUFFER_MIDDLE; if (buffer.firstHalf) { if (buffer.curIdx >= BUFFER_MIDDLE) /* pointer is outside first half */ { buffer.needDataCb(&buffer.data[0], BUFFER_MIDDLE, &dataReaded); /* populate it */ buffer.firstHalf = !buffer.firstHalf; if (BUFFER_MIDDLE != dataReaded) { buffer.lastIdx = dataReaded; } } } else { if (buffer.curIdx < BUFFER_MIDDLE) /* pointer is outside second half */ { buffer.needDataCb(&buffer.data[BUFFER_MIDDLE], BUFFER_MIDDLE, &dataReaded); /* populate it */ buffer.firstHalf = !buffer.firstHalf; if (BUFFER_MIDDLE != dataReaded) { buffer.lastIdx = dataReaded; } } } } } void buffer_Stop(void) { buffer.lastIdx = sizeof(buffer.data); buffer.curIdx = 0; buffer.firstHalf = true; buffer.needDataCb = NULL; buffer.isRun = false; buffer.isInit = true; }
C
#include <string.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/wait.h> #define RANDOM "/dev/urandom" #define SIZE 8 #define ESIZE 10 static const char en85[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '!', '#', '$', '%', '&', '(', ')', '*', '+', '-', ';', '<', '=', '>', '?', '@', '^', '_', '`', '{', '|', '}', '~' }; void encode_85(char *buf, int *out_bytes, const unsigned char *data, int bytes) { *out_bytes = 0; while (bytes) { unsigned acc = 0; int cnt; for (cnt = 24; cnt >= 0; cnt -= 8) { unsigned ch = *data++; acc |= ch << cnt; if (--bytes == 0) break; } for (cnt = 4; cnt >= 0; cnt--) { int val = acc % 85; acc /= 85; buf[cnt] = en85[val]; } buf += 5; *out_bytes += 5; } *buf = 0; } int perform_challenge(int sock) { int result; unsigned char rand[SIZE]; unsigned char buff[64] = { 0 }; char * why85 = NULL; why85 = malloc((SIZE * 5) / 4); if (why85 == NULL) { printf("unable to allocate memory!\n"); return -1; } FILE * f = fopen(RANDOM, "r"); if (f == NULL) { printf("unable to open random ...\n"); return -1; } result = fread(rand, 1, SIZE, f); if (result != SIZE) { printf("unable to read proper # of bytes\n"); return -1; } int outlen = 0; encode_85(why85, &outlen, rand, SIZE); if (outlen != (SIZE * 5)/4) { printf("encoding error!\n"); return -1; } printf("solution: %s\n", why85); send(sock, "Guess the random number!\n", strlen("Guess the random number!\n"), 0); while (1) { int res = recv(sock, buff, 64, 0); if (res <= 0) { printf("Unable to read input!\n"); return -1; } else { printf("Received: %s vs Have: %s\n", buff, why85); int i; for (i = 0; i < ESIZE; i++) { // If the passwords don't match, no point in continuing. if ((int)buff[i] != (int)why85[i]) break; sleep(1); // easy way to prevent brute force attacks } if (i == ESIZE) { #ifdef FLAG send(sock, FLAG, strlen(FLAG), 0); #else send(sock, "Wow, you did it!, now try it on the server!\n", strlen("Wow, you did it!, now try it on the server!\n"), 0); #endif return 0; } else { send(sock, "Better luck next time!\n", strlen("Better luck next time!\n"), 0); } } } } int main(int argc, char * argv) { int serverSocket, newSocket; struct sockaddr_in serverAddr; struct sockaddr_storage serverStorage; socklen_t addr_size; pid_t pid[50]; //Create the socket. serverSocket = socket(PF_INET, SOCK_STREAM, 0); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(7799); serverAddr.sin_addr.s_addr = INADDR_ANY; memset(serverAddr.sin_zero, '\0', sizeof(serverAddr.sin_zero)); bind(serverSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr)); if(listen(serverSocket,50)==0) printf("Listening\n"); else printf("Error\n"); pthread_t tid[60]; int i = 0; while(1) { addr_size = sizeof(serverStorage); newSocket = accept(serverSocket, (struct sockaddr *) &serverStorage, &addr_size); int pid_c = 0; if ((pid_c = fork())==0) { perform_challenge(newSocket); close(newSocket); } else { pid[i++] = pid_c; if( i >= 49) { i = 0; while(i < 50) waitpid(pid[i++], NULL, 0); i = 0; } } } return 0; }
C
#include "final.h" void historial (User * onlineUser){ char * string=malloc(sizeof(char)*150); MYSQL_RES * resGeneral=NULL; MYSQL_ROW rowGeneral; MYSQL_RES * res=NULL; MYSQL_ROW row; int anio; sprintf(string,"SELECT id, titulo, estreno, valor, fecha FROM peliculas, votos WHERE votos.user=%d AND peliculas.id=votos.pelicula ORDER BY fecha DESC",onlineUser->id); resGeneral=mandarQuery(string); system("clear"); if (mysql_num_rows(resGeneral)) printf("Titulo\t\t\tAnio\tPuntaje\tPromedio\tVotos\tFecha"); else printf("No ha votado\n"); while ((rowGeneral = mysql_fetch_row(resGeneral)) != NULL){ strcpy(string,rowGeneral[2]); *(string+4)=0; anio=atoi(string); sprintf(string,"SELECT AVG(votos.valor) AS rating, COUNT(votos.valor) AS votos FROM votos WHERE pelicula=%d",atoi(rowGeneral[0])); res=mandarQuery(string); row=mysql_fetch_row(res); strcpy(string,displayFecha(atofec(rowGeneral[4]))); printf("\n%s\t%d\t%d\t%.1f\t\t%d\t%s",longerString(rowGeneral[1],24),anio,atoi(rowGeneral[3]),atof(row[0]),atoi(row[1]),string); } printf("\n"); if (resGeneral!=NULL) free(resGeneral); if (res!=NULL) free(res); if (string!=NULL) free(string); }
C
#include<stdio.h> #include<string.h> int isprime(int n) { int i; if(n<=1)return 0; for(i=2;i*i<=n;i++) if(n%i==0)return 0; return 1; } int main() { int m,n; scanf("%d %d",&m,&n); char a[m+1]; scanf("%s",a); int i,j; int count=0,t=0; for(i=0;i<strlen(a);i++) { count++; t=t*10+a[i]-48; if(count==n) { if(isprime(t)) { for(j=i-count+1;j<=i;j++) printf("%c",a[j]); return 0; } else { i=i-count+1; t=0; count=0; } } } if(isprime(t)) { printf("%s",a); return 0; } printf("%d",404); }
C
#include<stdio.h> int main() { // Ʈ // << : ǿ 2 ȯϰ, ̵Ų // 10 << 1 : ڴ 2 Ű, 2 ( ) ڿ Ѵ // >> : ǿ 2 ȯϰ, ̵Ų // ݴ printf("%d\n", 10 << 1); printf("%d\n", 10 << 2); printf("%d\n", 10 << 3); printf("%d\n", 10 << 4); printf("\n"); printf("%d\n", 10 >> 1); printf("%d\n", 10 >> 2); printf("%d\n", 10 >> 3); printf("%d\n", 10 >> 4); }
C
/** * A simple (non-standards-compliants?) 'yes' implementation for fun **/ #include <stdlib.h> #include <stdio.h> #include <string.h> #define EVER ;; int main(int argc, char **argv) { int current_arg; if (argc < 2) for (EVER) { if (puts("y") == EOF) goto err; } else for (EVER) { for (current_arg = 1; current_arg < argc - 1; current_arg++) if (fputs(argv[current_arg], stdout) == EOF || putchar(' ') == EOF) goto err; if (puts(argv[argc - 1]) == EOF) goto err; } err: return EXIT_FAILURE; /* should never happen */ }
C
/* * Ted Meyer */ #include<stdio.h> typedef enum { false, true } bool; int main(void) { // function declarations void printMonth(int days, int first); bool isLeap(int year); int getNextStartDay(int currentStart, int month); int year; printf("Please enter year for this calendar:- "); scanf("%i", &year); printf(" *** CALENDAR for %i ***\n",year); int month = 1; bool leap = isLeap(year); int daystart = (37 + (year-1) + (year-1)/4 + (year-1)/400 -(year-1)/100) % 7; if (daystart == 0){ daystart = 7; } while(month <= 12) { switch(month) { case 1: printf("January %i\n\n", year); printMonth(31, daystart); daystart = getNextStartDay(daystart, 31); break; case 2: printf("February %i\n\n", year); printMonth(leap?29:28, daystart); daystart = getNextStartDay(daystart, leap?29:28); break; case 3: printf("March %i\n\n", year); printMonth(31, daystart); daystart = getNextStartDay(daystart, 31); break; case 4: printf("April %i\n\n", year); printMonth(30, daystart); daystart = getNextStartDay(daystart, 30); break; case 5: printf("May %i\n\n", year); printMonth(31, daystart); daystart = getNextStartDay(daystart, 31); break; case 6: printf("June %i\n\n", year); printMonth(30, daystart); daystart = getNextStartDay(daystart, 30); break; case 7: printf("July %i\n\n", year); printMonth(31, daystart); daystart = getNextStartDay(daystart, 31); break; case 8: printf("August %i\n\n", year); printMonth(31, daystart); daystart = getNextStartDay(daystart, 31); break; case 9: printf("September %i\n\n", year); printMonth(30, daystart); daystart = getNextStartDay(daystart, 30); break; case 10: printf("October %i\n\n", year); printMonth(31, daystart); daystart = getNextStartDay(daystart, 31); break; case 11: printf("November %i\n\n", year); printMonth(30, daystart); daystart = getNextStartDay(daystart, 30); break; case 12: printf("December %i\n\n", year); printMonth(31, daystart); daystart = getNextStartDay(daystart, 31); break; } month++; } return 0; } int getNextStartDay(int currentStart, int month){ int k = (currentStart+month)%7; return k==0 ? 7 : k; } bool isLeap(int year){ return ((year%4 == 0) && (year%100 != 0)) || (year%400 == 0); } void printMonth(int days, int first) { //where first=1 corresponds to monday printf("%5s%5s%5s%5s%5s%5s%5s\n", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"); int i = 1; while( i < first ){ printf(" "); i++; } i = 1; while( i <= days ){ printf("%5i", i); if ((i+first-1)%7==0){ printf("\n"); } i++; } printf("\n\n"); }
C
#ifndef UASDKIOBASE_H_ #define UASDKIOBASE_H_ #include <termios.h> #include <stdint.h> #include <time.h> #include <stdlib.h> #ifdef __cplusplus extern "C" { #endif #pragma region baudrate typedef enum { UASDKbyteformat_N1, // no parity, 1 stop bit UASDKbyteformat_E1, // even parity, 1 stop bit UASDKbyteformat_O1, // odd parity, 1 stop bit UASDKbyteformat_N2, // no parity, 2 stop bit UASDKbyteformat_E2, // even parity, 2 stop bit UASDKbyteformat_O2, // odd parity, 2 stop bit } UASDKbyteformat_t; // this macro defines an instance of UASDKbaudrate_t. // e.g. UASDKBAUD(1200) ==> { B1200, 1200, (1.0f/1200.0f) } #define UASDKBAUD(BRNUM) {B ## BRNUM , BRNUM , (1.0f/ BRNUM ## .0f)} typedef struct { int id; // identifier defined in unix header; e.g. B9600, B1200, etc. int bps; // baudrate represented by bits/sec float bittime; // period of 1 bit in represented by seconds } UASDKbaudrate_t, *pUASDKbaudrate_t; typedef const UASDKbaudrate_t *pcUASDKbaudrate_t; /*! \brief estimate time for transferring the specified bytes. \param baudate [in] baudrate \param byte_count [in] \param format [in] byte format \param time [out] estimate of the time */ void UASDKbaudrate_estimatetime(pcUASDKbaudrate_t baudrate, int byte_count, UASDKbyteformat_t format, struct timespec* time); #pragma endregion baudrate #pragma region unified_buffer // void* buffer transferred to standard C APIs typedef struct { void* buf; size_t byte_count; size_t filled_bytes; } UASDKvoidbuf_t, *pUASDKvoidbuf_t; typedef const UASDKvoidbuf_t *pcUASDKvoidbuf_t; // byte buffer for byte-by-byte access typedef struct { uint8_t* buf; size_t byte_count; size_t filled_bytes; } UASDKbytebuf_t, *pUASDKbytebuf_t; typedef const UASDKbytebuf_t *pcUASDKbytebuf_t; // unified buffer typedef union { UASDKvoidbuf_t voidbuf; UASDKbytebuf_t bytebuf; } UASDKunibuf_t, *pUASDKunibuf_t; typedef const UASDKunibuf_t *pcUASDKunibuf_t; #define UASDKunibuf_byte_count(ub) ub->bytebuf.byte_count #define UASDKunibuf_void(ub) ub->voidbuf.buf #define UASDKunibuf_byte(ub) ub->bytebuf.buf #define UASDKunibuf_initdef { { NULL, 0, 0 } } /*! \brief initialize as a byte buffer \param ub [in,out] object to initialize \param total_byte_count [in] total byte count of byte_count.buf \return unix errno compatible number */ int UASDKunibuf_initbyte(pUASDKunibuf_t ub, uint16_t total_byte_count); /*! \brief extract specified bytes \param ub [in,out] unified buffer object \param ext_bytes [in] byte count to extract. \param outbuf [out] output buffer \return unix errno compatible number */ int UASDKunibuf_extract(pUASDKunibuf_t ub, uint16_t ext_bytes, void* outbuf); /*! \brief clean up allocated memory block \param ub [in,out] object to clean up \return unix errno compatible number */ void UASDKunibuf_destroy(pUASDKunibuf_t ub); #pragma endregion unified_buffer #pragma region init_uart typedef struct { UASDKbaudrate_t baudrate; UASDKbyteformat_t byteformat; int fd; } UASDKuartdescriptor_t, *pUASDKuartdescriptor_t; typedef const UASDKuartdescriptor_t *pcUASDKuartdescriptor_t; #define UASDKUARTDEF0 { UASDKBAUD(9600), UASDKbyteformat_N1, -1 } /*! \brief open serialport \param uart [out] UART descriptor \param name [in] device name \param br [in] baudrate \param bf [in] byte format; currently not supported, reserved; current byte format is only 8N1. \return errno compatible code */ int UASDKiobase_open(pUASDKuartdescriptor_t uart, const char* name, pcUASDKbaudrate_t br, UASDKbyteformat_t bf); /*! \brief write data \param uart [in] UART descriptor \param ub [in] unified buffer \param actually_written [out] actually written byte count \return unix errno compatible number */ int UASDKiobase_write(pcUASDKuartdescriptor_t uart, pcUASDKunibuf_t ub, int* actually_written); /*! \brief read data \param uart [in] UART descriptor \param ub [in] unified buffer \return unix errno compatible number */ int UASDKiobase_read(pcUASDKuartdescriptor_t uart, pUASDKunibuf_t ub); int UASDKiobase_enableinterrupt(int signum); #pragma endregion init_uart #ifdef __cplusplus } #endif #endif /* UASDKIOBASE_H_ */
C
#include <stdio.h> // 迷宫问题指的是:在给定区域内,找到一条甚至所有从某个位置到另一个位置的移动路线。 // 迷宫问题就可以采用回溯算法解决,即从起点开始,采用不断“回溯”的方式逐一试探所有的移动路线,最终找到可以到达终点的路线。 typedef enum { false, true } bool; #define ROW 5 #define COL 5 // 假设当前迷宫中没有起点到终点的路线 bool find = false; // 回溯算法查找可行路线 void maze_puzzle(char maze[ROW][COL], int row, int col, int outrow, int outcol); // 判断(row,col)区域是否可以移动 bool canMove(char maze[ROW][COL], int row, int col); // 输出行走路线 void printmaze(char maze[ROW][COL]); int main() { char maze[ROW][COL] = {{'1', '0', '1', '1', '1'}, {'1', '1', '1', '0', '1'}, {'1', '0', '0', '1', '1'}, {'1', '0', '0', '1', '0'}, {'1', '0', '0', '1', '1'}}; maze_puzzle(maze, 0, 0, ROW - 1, COL - 1); if (find == false) { printf("未找到可行线路\n"); } return 0; } // (row,col)表示起点,(outrow,outcol)表示终点 void maze_puzzle(char maze[ROW][COL], int row, int col, int outrow, int outcol) { maze[row][col] = 'Y'; // 将各个走过的区域标记为Y // 如果行走至终点,表明有从起点到终点的路线 if (row == outrow && col == outcol) { find = true; printf("成功走出迷宫,路线图为:\n"); printmaze(maze); return; } // 尝试向上移动 if (canMove(maze, row - 1, col)) { maze_puzzle(maze, row - 1, col, outrow, outcol); // 如果程序不结束,表明此路不通,恢复该区域的标记 maze[row - 1][col] = '1'; } // 尝试向左移动 if (canMove(maze, row, col - 1)) { maze_puzzle(maze, row, col - 1, outrow, outcol); // 如果程序不结束,表明此路不通,恢复该区域的标记 maze[row][col - 1] = '1'; } // 尝试向下移动 if (canMove(maze, row + 1, col)) { maze_puzzle(maze, row + 1, col, outrow, outcol); // 如果程序不结束,表明此路不通,恢复该区域的标记 maze[row + 1][col] = '1'; } // 尝试向右移动 if (canMove(maze, row, col + 1)) { maze_puzzle(maze, row, col + 1, outrow, outcol); // 如果程序不结束,表明此路不通,恢复该区域的标记 maze[row][col + 1] = '1'; } } // 判断(row,col)区域是否可以移动 bool canMove(char maze[ROW][COL], int row, int col) { // 如果目标区域位于地图内,不是黑色区域,且尚未行走过,返回true,反之,返回false return row >= 0 && row <= ROW - 1 && col >= 0 && col <= COL - 1 && maze[row][col] != '0' && maze[row][col] != 'Y'; } // 输出可行的路线 void printmaze(char maze[ROW][COL]) { int i, j; for (i = 0; i < ROW; i++) { for (j = 0; j < COL; j++) { printf("%c ", maze[i][j]); } printf("\n"); } }
C
/* Find Minimum Cost Spanning Tree of a given undirected graph using Kruskals algorithm.*/ #include<stdio.h> int parent[30]; int find(int i) { while (parent[i]!=i) i = parent[i]; return i; } void unionv(int i, int j) { int a = find(i); int b = find(j); parent[a] = b; } void kruskals(int a[][30], int n) { int mincost = 0,c = 0,i,j; for(i=0;i<n;i++) parent[i] = i; while(c<n-1) { int min = 10000,it = -1,jt = -1; for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(find(i)!=find(j) && a[i][j]<min) { min = a[i][j]; it = i; jt = j; } } } unionv(it,jt); c++; printf("( %d,%d)\t%d\n",it+1,jt+1,min); mincost += min; } printf("\nMinimum cost = %d",mincost); } int main() { int a[30][30],n,i,j; printf("Enter the number of vertices="); scanf("%d",&n); printf("Enter the weight matrix of the graph (Enter 9999 for infinity(i.e. if there is no edge))\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) scanf("%d",&a[i][j]); } printf("\nThe Minimum Spanning Tree is :\n"); printf("Edges\tWeight\n"); kruskals(a,n); return 0; } /* output Enter the number of vertices 6 Enter the weight matrix of the graph (Enter 9999 for infinity(i.e. if there is no edge)) 0 30 10 9999 9999 9999 30 0 9999 20 20 25 10 9999 0 9999 15 9999 9999 20 9999 0 15 10 9999 20 15 15 0 35 9999 25 9999 10 35 0 The Minimum Spanning Tree is : Edges Weight (1,3) 10 (4,6) 10 (3,5) 15 (4,5) 15 (2,4) 20 Minimum cost = 70 */
C
/* Purpose: sub function f(x) = x^3 + 2x^2 + 1, and return result to main */ /* File Name: hw07_05 */ /* Completion Date: 20210530 */ #include <stdio.h> #include <stdlib.h> int FofX(int); int main(void) { int input, result; printf("Please input an integer x for f(x) = f(x) = x^3 + 2x^2 + 1\n"); scanf("%d", &input); result = FofX(input); printf("The result is %d\n", result); system("pause"); return 0; } int FofX(int input) { int result; result = input * input * input + 2 * input * input + 1; return result; }
C
#include "TimerService.h" #include "asuro.h" #include <stdbool.h> #define MAX_TIMERS 5 struct _timer_entry { unsigned int duration; unsigned int current; timer_func func; void *data; }; volatile timer_entry timers[MAX_TIMERS]; volatile bool did_init; void init_timer() { TCCR0 = 0b011; TCNT0 = 130; TIMSK |= 1; did_init = true; } timer_entry* add_timer(unsigned int duration, timer_func func, void *data) { if (!did_init) init_timer(); timer_entry *entry = NULL; for (int i = 0; i < MAX_TIMERS; i++) { if (timers[i].func == NULL) { entry = timers + i; break; } } if (entry == NULL) return NULL; entry->duration = duration; entry->current = 0; entry->func = func; entry->data = data; return entry; } void remove_timer(timer_entry *timer) { timer->func = NULL; } ISR(TIMER0_OVF_vect, ISR_NOBLOCK) { for (int i = 0; i < MAX_TIMERS; i++) { if (timers[i].func && ++timers[i].current == timers[i].duration) { timers[i].func(timers[i].data); timers[i].current = 0; } } init_timer(); }
C
/** * Here we implement the Simulated Annealing algorithm with * exponential temperature schedule with iterative restarts. * * The problem with simulated annealing is that it has several * parameters that need to be configured well in order for it * to work. * The proper configuration of the parameters depends on the * scale of the objective function value as well as on the * available computation budget, and even stuff like, e.g., * the expected differences in objective values of local optima. * * This makes it very complicated to properly use it for * black-box settings where absolutely nothing is known * about the objective function. * * The dependency on the budget is reduced here by performing * internal restarts. The first restart has a budget of 1024 * FEs, the second one of 2048 FEs, and so on: the "inner" * runs always double in budget. Thus, the advantages of SA * can be obtained faster by wasting about half of the * computational budget. * * Still, to be able to do some experiments, we need to also * configure the temperatures. We propose the following * automatic setup based on the number 'n' of variables of * the problem and the budgets of the single internal runs: * * - the temperature schedule is exponential * - the start temperature is such that it time 1 the * probability to accept a solution which is n/4 worse * than the current solution would be 0.1 * - the end temperature is such that the probability to * accept a solution which is 1 worse than the current * solution is 1/sqrt(n) * - the value of the epsilon parameter of the schedule * is computed accordingly * * This will have several implications: * * - Problems that can be solved easily (OneMax, * LeadingOnes) will be _still_ solved late in the runs. * This is normal for simulated annealing, as the goal * is to transcend from random walk to hill climbing * behavior. * - Problems whose objective value range differs largely * from n (e.g., LARS) will probably not be solved well. * * Author: Thomas Weise * Institute of Applied Optimization * Hefei University * Hefei, Anhui, China * Email: [email protected], [email protected] */ #ifndef _SARS_H_ #define _SARS_H_ #include "common.h" void run_simulated_annealing_exp_rs(const string folder_path, shared_ptr<IOHprofiler_suite<int>> suite, const unsigned long long eval_budget, const unsigned long long independent_runs, const unsigned long long rand_seed); #endif
C
#include "main.h" /** * * add - add two numbers from input * * @a: first aparamet * * @b: second parameter * * * * Description: adds two numbers * * Return: Always (0). * */ int add(int a, int b) { return (a + b); }
C
#include <stdio.h> #include "interpreter.h" #include "parser.h" #include "tokens.h" #include "tree.h" // TODO: message d'erreur static void match(enum token_type first, Token *lookahead); static Tree statement(Token *lookahead); static Tree expression(Token *lookahead); static Tree id_followup(Token *lookahead, Tree node); static void param_list(Token *lookahead, Tree parent); static void param(Token *lookahead, Tree parent); static void optparam(Token *lookahead, Tree parent); static void list(Token *lookahead, Tree parent); bool valid_tree = true; Tree parser(Token *lookahead) { valid_tree = true; Tree root = statement(lookahead); if (valid_tree) { return root; } else { return NULL; } } static void match(enum token_type first, Token *lookahead) { if (lookahead->type == first) { *lookahead = gettoken(); } else { fprintf(stderr, "Syntax error\n"); valid_tree = false; } } static Tree statement(Token *lookahead) { Tree node; switch (lookahead->type) { case TOK_EOF: valid_tree = false; return NULL; case TOK_SEMI_COLON: valid_tree = false; return NULL; case TOK_ID:// Fall through!! case TOK_NUMBER: node = expression(lookahead); //TODO: s'occuper de cette vérification //match(TOK_SEMI_COLON, lookahead); return node; default: valid_tree = false; return NULL; } } static Tree expression(Token *lookahead) { Tree node = newTree(); Token vec = {.type = TOK_LIST}; switch (lookahead->type) { case TOK_ID: setValue(node, *lookahead); match(TOK_ID, lookahead); node = id_followup(lookahead, node); return node; case TOK_NUMBER: setValue(node, *lookahead); match(TOK_NUMBER, lookahead); return node; case TOK_LEFT_BRACKET: setValue(node, vec); list(lookahead, node); return node; default: valid_tree = false; return NULL; } } static Tree id_followup(Token *lookahead, Tree node) { Tree assign = NULL; Tree rvalue = NULL; switch(lookahead->type) { case TOK_LEFT_PARENTHESE: node->token.type = TOK_FUNCTION; match(TOK_LEFT_PARENTHESE, lookahead); param_list(lookahead, node); match(TOK_RIGHT_PARENTHESE, lookahead); return node; case TOK_COLON: assign = newTree(); setValue(assign, *lookahead); setNbChild(assign, 2); match(TOK_COLON, lookahead); rvalue = expression(lookahead); addChild(assign, node); addChild(assign, rvalue); return assign; default: // Empty token return node; } } static void param_list(Token *lookahead, Tree parent) { switch (lookahead->type) { case TOK_ID: case TOK_NUMBER: case TOK_LEFT_BRACKET: param(lookahead, parent); optparam(lookahead, parent); break; default: // Empty param_list break; } } static void param(Token *lookahead, Tree parent) { Tree child = expression(lookahead); addChild(parent, child); } static void optparam(Token *lookahead, Tree parent) { switch (lookahead->type) { case TOK_COMMA: match(TOK_COMMA, lookahead); param(lookahead, parent); optparam(lookahead, parent); break; default: // Empty token break; } } static void list(Token *lookahead, Tree parent) { switch (lookahead->type) { case TOK_LEFT_BRACKET: match(TOK_LEFT_BRACKET, lookahead); param_list(lookahead, parent); match(TOK_RIGHT_BRACKET, lookahead); break; default: valid_tree = false; break; } }
C
#include <stdio.h> #include <stdlib.h> int main() { int num, *arr, i; scanf("%d", &num); arr = (int*) malloc(num * sizeof(int)); for(i = 0; i < num; i++) { scanf("%d", arr + i); } //Array Reversal for (size_t j = 0; j < num/2; j++) { int temp = *(arr+j); *(arr+j) = *(arr+(num-j-1)); *(arr+(num-j-1)) = temp; } for(i = 0; i < num; i++) printf("%d ", *(arr + i)); return 0; }
C
#include <rmath.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include <math.h> #include <assert.h> matf* matf_new(const size_t rows, const size_t cols) { matf *C = malloc(sizeof(matf)); C->rows = rows; C->cols = cols; C->v = calloc(rows * cols, sizeof(float)); return C; } matf* matf_cpy(matf *M) { matf *R = matf_new(M->rows, M->cols); memcpy(R->v, M->v, M->rows * M->cols * sizeof(float)); return R; } void matf_cpyi(matf *Dst, const matf *Src) { assert(Dst != NULL && Src != NULL); assert(Dst->rows == Src->rows && Dst->cols == Src->cols); memcpy(Dst->v, Src->v, Src->rows * Src->cols * sizeof(float)); } matf* matf_new_val(size_t rows, size_t cols, float v) { matf *C = matf_new(rows, cols); for (size_t i = 0; i < rows * cols; C->v[i] = v, i++); return C; } matf* matf_eye(const size_t rows) { matf *C = matf_new(rows, rows); for (size_t i = 0; i < rows; i++) C->v[M_IDX(i,i,rows)] = 1; return C; } void matf_norm_r1(matf *M, size_t r) { float sum = 0.0f; for (size_t c = 0; c < M->cols; c++) sum += MIDX(M, r, c); if (sum == 0.0f) return; for (size_t c = 0; c < M->cols; c++) MIDX(M, r, c) /= sum; } void matf_norm_r(matf *M) { assert(M != NULL); for (size_t r = 0; r < M->rows; r++) matf_norm_r1(M, r); } void matf_norm_c1(matf *M, size_t c) { float sum = 0.0f; for (size_t r = 0; r < M->rows; r++) sum += MIDX(M, r, c); if (sum == 0.0f) return; for (size_t r = 0; r < M->rows; r++) MIDX(M, r, c) /= sum; } void matf_norm_c(matf *M) { assert(M != NULL); for (size_t c = 0; c < M->rows; c++) matf_norm_c1(M, c); } void matf_set(matf *A, const float v) { assert(A != NULL); for (size_t i = 0; i < A->rows * A->cols; i++) A->v[i] = v; } void matf_free(matf *A) { if (!A) return; free(A->v); free(A); } float dotp(float *p1, int s1, float *p2, int s2, unsigned int n) { float s = 0.0f; for (size_t i = 0; i < n; i++, p1 += s1, p2 += s2) s += p1[0] * p2[0]; return s; } matf* matf_apply(matf *A, float (*fp)(float)) { assert(A != NULL && fp != NULL); matf *C = matf_new(A->rows, A->cols); for (size_t i = 0; i < A->rows * A->cols; i++) C->v[i] = fp(A->v[i]); return C; } void matf_applyd(matf *Dst, const matf *A, float (*fp)(float)) { assert(Dst != NULL && A != NULL && fp != NULL); for (size_t i = 0; i < A->rows * A->cols; i++) Dst->v[i] = fp(A->v[i]); } void matf_applyi(matf *A, float (*fp)(float)) { assert(A != NULL && fp != NULL); for (size_t i = 0; i < A->rows * A->cols; i++) A->v[i] = fp(A->v[i]); } matf* matf_add(const matf *A, const matf *B) { assert(A->cols == B->cols && A->rows == B->rows); matf *C = matf_new(A->rows, B->rows); for (size_t i = 0; i < A->rows * A->cols; i++) C->v[i] = A->v[i] + B->v[i]; return C; } void matf_addi(matf *A, const matf *B) { assert(A->cols == B->cols && A->rows == B->rows); for (size_t i = 0; i < A->rows * A->cols; i++) A->v[i] += B->v[i]; } matf* matf_sub(const matf *A, const matf *B) { assert(A->cols == B->cols && A->rows == B->rows); matf *C = matf_new(A->rows, B->rows); for (size_t i = 0; i < A->rows * A->cols; i++) C->v[i] = A->v[i] - B->v[i]; return C; } void matf_subi(matf *A, const matf *B) { assert(A->cols == B->cols && A->rows == B->rows); for (size_t i = 0; i < A->rows * A->cols; i++) A->v[i] -= B->v[i]; } matf* matf_mul(const matf *A, const matf *B) { assert(A != NULL && B != NULL); assert(A->cols == B->rows); matf *C = matf_new(A->rows, B->cols); matf_muld(C, A, B); return C; } void matf_muld(matf *Dst, const matf *A, const matf *B) { assert(Dst != NULL); assert(A != NULL); assert(B != NULL); for (size_t r = 0; r < Dst->rows; r++) { for (size_t c = 0; c < Dst->cols; c++) { MIDX(Dst, r, c) = dotp(&A->v[r * A->cols], 1, &B->v[c], B->cols, B->rows); } } } void matf_muli(matf *A, const matf *B) { // TODO: implement smarter version matf* C = matf_mul(A, B); for (size_t r = 0; r < A->rows; r++) { for (size_t c = 0; c < A->cols; c++) { MIDX(A, r, c) = MIDX(C, r, c); } } matf_free(C); } inline static float matf_transposed_v(const matf *M, size_t r, size_t c) { assert(M != NULL); return M->v[M_IDX_T(r, c, M->cols)]; } matf* matf_transpose(const matf *A) { assert(A != NULL); matf *B = matf_new(A->cols, A->rows); for (size_t r = 0; r < A->cols; r++) for (size_t c = 0; c < A->rows; c++) MIDX(B, r, c) = matf_transposed_v(A, r, c); return B; } matf* matf_mul_elems(const matf *A, const matf *B) { assert(A != NULL); assert(B != NULL); assert(A->rows == B->rows); assert(A->cols == B->cols); matf *C = matf_new(A->rows, A->cols); for (size_t i = 0; i < A->rows * A->cols; i++) C->v[i] = A->v[i] * B->v[i]; return C; } void matf_mul_elemsi(matf *A, const matf *B) { assert(A->rows == B->rows && A->cols == B->cols); for (size_t i = 0; i < A->rows * A->cols; i++) A->v[i] *= B->v[i]; } matf* matf_mul_scalar(const matf *A, const float s) { assert(A != NULL); matf *C = matf_new(A->rows, A->cols); for (size_t i = 0; i < A->rows * A->cols; i++) C->v[i] = A->v[i] * s; return C; } void matf_mul_scalari(matf *A, const float s) { assert(A != NULL); for (size_t i = 0; i < A->rows * A->cols; i++) A->v[i] *= s; } matf* matf_diag(const matf *A) { assert(A != NULL && A->cols == A->rows); matf *C = matf_new(A->rows, 1); for (size_t i = 0; i < A->rows; i++) C->v[i] = MIDX(A, i, i); return C; } void matf_dump_linear(matf *A) { printf("[ "); for (size_t r = 0; r < A->rows; r++) { for (size_t c = 0; c < A->cols; c++) { printf("%.3f", MIDX(A, r, c)); if (c != A->cols - 1) printf(", "); } if (r != A->rows - 1) printf("; "); } printf("]\n"); } void matf_dump(matf *A) { printf("[ "); for (size_t r = 0; r < A->rows; r++) { for (size_t c = 0; c < A->cols; c++) printf("%.3f ", MIDX(A, r, c)); if (r != A->rows - 1) printf("\n "); } printf("]\n"); } void matf_dump_transposed(matf *A) { for (size_t r = 0; r < A->cols; r++) { for (size_t c = 0; c < A->rows; c++) printf("%.3f ", matf_transposed_v(A, r, c)); printf("\n"); } } float _randf() { return 10 * (float)rand() / (float)RAND_MAX; } matf* matf_rand(size_t rows, size_t cols) { matf *C = matf_new(rows, cols); for (size_t i = 0; i < rows * cols; i++) C->v[i] = _randf(); return C; }
C
#include <core/types.h> #include <core/spinlock.h> #include <core/startup.h> #include <core/string.h> void spinlock_init(struct spinlock *lock, const char *name, unsigned flags) { ASSERT((flags & SPINLOCK_FLAG_VALID) == 0, "Must not set valid flag."); lock->s_name = name; lock->s_owner = CPU_ID_INVALID; lock->s_nest = 0; lock->s_flags = flags | SPINLOCK_FLAG_VALID; } void spinlock_lock(struct spinlock *lock) { ASSERT((lock->s_flags & SPINLOCK_FLAG_VALID) != 0, "Cowardly refusing to lock invalid spinlock."); if (startup_early) return; #ifndef UNIPROCESSOR critical_enter(); cpu_id_t self = mp_whoami(); while (!atomic_cmpset64(&lock->s_owner, CPU_ID_INVALID, self)) { if (atomic_load64(&lock->s_owner) == (uint64_t)self) { if ((lock->s_flags & SPINLOCK_FLAG_RECURSE) != 0) { atomic_increment64(&lock->s_nest); critical_exit(); return; } panic("%s: cannot recurse on spinlock (%s)", __func__, lock->s_name); } critical_exit(); /* * If we are not already in a critical section, allow interrupts * to fire while we spin. */ critical_enter(); self = mp_whoami(); } #else critical_enter(); if (lock->s_owner == mp_whoami()) { lock->s_nest++; critical_exit(); } else { lock->s_owner = mp_whoami(); } #endif } void spinlock_unlock(struct spinlock *lock) { ASSERT((lock->s_flags & SPINLOCK_FLAG_VALID) != 0, "Cowardly refusing to unlock invalid spinlock."); if (startup_early) return; #ifndef UNIPROCESSOR cpu_id_t self = mp_whoami(); if (atomic_load64(&lock->s_owner) == (uint64_t)self) { if (atomic_load64(&lock->s_nest) != 0) { atomic_decrement64(&lock->s_nest); return; } else { if (atomic_cmpset64(&lock->s_owner, self, CPU_ID_INVALID)) { critical_exit(); return; } } } panic("%s: not my lock to unlock (%s)", __func__, lock->s_name); #else if (lock->s_owner != mp_whoami()) panic("%s: cannot lock %s (owner=%lx)", __func__, lock->s_name, lock->s_owner); if (lock->s_nest == 0) { critical_exit(); lock->s_owner = CPU_ID_INVALID; } else lock->s_nest--; #endif }
C
#include<linux/module.h> #include<linux/kernel.h> #include<linux/proc_fs.h> /* use the proc fs */ #include<asm/uaccess.h> /* for copy_from_user */ #include<linux/init.h> #include<linux/vmalloc.h> #include<linux/string.h> #define PROCFS_MAX_SIZE 1024 #define PROCFS_NAME "buffer1k" static struct proc_dir_entry *my_proc_file, *dir; static char procfs_buffer[PROCFS_MAX_SIZE]; static unsigned long procfs_buffer_size = 0; int procfile_read(char *buffer, char **buffer_location, off_t offset, int buffer_length, int *eof, void *data){ int ret; printk("procfile_read(/proc/%s)called\n", PROCFS_NAME); if(offset > 0){ ret = 0; } else{ memcpy(buffer, procfs_buffer, procfs_buffer_size); ret = procfs_buffer_size; } return ret; } int procfile_write(struct file *file, const char *buffer, unsigned long count, void *data){ procfs_buffer_size = count; if(procfs_buffer_size > PROCFS_MAX_SIZE){ procfs_buffer_size = PROCFS_MAX_SIZE; } if(copy_from_user(procfs_buffer, buffer, procfs_buffer_size)){ return -EFAULT; } return procfs_buffer_size; } int init_my_proc(void) { dir = proc_mkdir("mydir", NULL); my_proc_file = create_proc_entry(PROCFS_NAME, 0644, dir); if(my_proc_file == NULL){ remove_proc_entry(PROCFS_NAME, dir); /* remove files under mydir */ remove_proc_entry("mydir", NULL); /* remove mydir */ printk("error: could not initialize /proc/%s\n",PROCFS_NAME); return -ENOMEM; } my_proc_file->read_proc = procfile_read; my_proc_file->write_proc = procfile_write; // my_proc_file->owner = THIS_MODULE; my_proc_file->mode = S_IFREG|S_IRUGO; my_proc_file->uid = 0; my_proc_file->gid = 0; my_proc_file->size = 37; printk("/proc/%s created\n", PROCFS_NAME); return 0; /* everything is ok */ } void cleanup_my_proc(void) { remove_proc_entry(PROCFS_NAME, dir); remove_proc_entry("mydir", NULL); printk("/proc/%s removed\n", PROCFS_NAME); } module_init(init_my_proc); module_exit(cleanup_my_proc); MODULE_LICENSE("GPL");
C
/* $Id: serpent-test.c,v 1.13 1998/06/07 08:11:09 fms Exp $ # This file is part of the C reference implementation of Serpent. # # Written by Frank Stajano, # Olivetti Oracle Research Laboratory <http://www.orl.co.uk/~fms/> and # Cambridge University Computer Laboratory <http://www.cl.cam.ac.uk/~fms27/>. # # (c) 1998 Olivetti Oracle Research Laboratory (ORL) # # Original (Python) Serpent reference development started on 1998 02 12. # C implementation development started on 1998 03 04. # # Serpent cipher invented by Ross Anderson, Eli Biham, Lars Knudsen. # Serpent is a candidate for the Advanced Encryption Standard. */ /* -------------------------------------------------- */ #include "serpent-api.h" #include "serpent-aux.h" /* -------------------------------------------------- */ EMBED_RCS(serpent_test_c, "$Id: serpent-test.c,v 1.13 1998/06/07 08:11:09 fms Exp $") /* Stuff to exercise the NIST API */ int doOneBlockViaNIST(BLOCK source, char* rawUserKey, BLOCK dest, BYTE direction, int printKey) { /* Using the functions exported by the NIST API, take the binary 'source' block, encrypt it or decrypt it (as indicated by 'direction', which must be one of DIR_ENCRYPT or DIR_DECRYPT) under the key described in ASCII by 'rawUserKey' and yield the binary 'dest' block. If printKey is TRUE, print out the key after having converted it from its ascii representation. Return TRUE for successful operation or one of the codes returned by the NIST API functions in case of error. */ keyInstance key; cipherInstance cipher; int result; result = makeKey(&key, direction, strlen(rawUserKey)*4, rawUserKey); if (result != TRUE) { goto cleanUp; } if (printKey) { render("userKey=", key.userKey, 8); } result = cipherInit(&cipher, MODE_ECB, 0); if (result != TRUE) { goto cleanUp; } if (key.direction == DIR_ENCRYPT) { result = blockEncrypt(&cipher, &key, (BYTE*)source, BITS_PER_BLOCK, (BYTE*)dest); } else { result = blockDecrypt(&cipher, &key, (BYTE*)source, BITS_PER_BLOCK, (BYTE*)dest); } if (result >= 0) { /* It's actually number of bits processed instead of an error code */ if (result == 128) { result = TRUE; } else { result = BAD_NUMBER_OF_BITS_PROCESSED; } } cleanUp: /* Yes, I am shamelessly using a goto. Better that, and providing a clean single-point-of-exit, than to repeat the following code after every NIST API function. Of course if we were writing this in C++ we'd have destructors to do the job for us behind the scenes...*/ return result; } /* -------------------------------------------------- */ /* WARNING: No clever crypto stuff below this line. Just boring command line option parsing. It's a dirty job, but someone must do it if we want a program YOU can use straight away, without having to edit main() to poke in your own values. */ void help(void) { printf( "Serpent Reference Implementation\n" "Simple manual one-block ECB test\n" "\n" "Encrypts or decrypts one block of data using the Serpent cipher.\n" "\n" "\n" "SYNTAX: serpent-test mode [options]\n" "\n" "MODE is one of the following:\n" "-e -> encrypt\n" "-d -> decrypt\n" "-h -> help (the text you're reading right now)\n" "\n" "OPTIONS are:\n" "-p plainText -> The 128-bit value to be encrypted.\n" " Required in mode -e. Ignored otherwise.\n" "-c cipherText -> The 128-bit value to be decrypted.\n" " Required in mode -d. Ignored otherwise.\n" "-k key -> The 256-bit value of the key. Required in modes\n" " -e and -d.\n" "\n" "I/O FORMAT:\n" "Each value is read/printed as one long big-endian hexadecimal\n" "number (the leftmost hex digit is the most significant),\n" "with a fixed number of digits depending on its intended size\n" "(e.g. 32 digits for 128-bit values).\n" "To help you catching typos, the program\n" "insists that the exact number of digits be entered,\n" "so values must be left-filled with 0s where appropriate.\n" ); } void exitMentioningHelp(void) { printf("Try 'serpent-test -h | more' for help.\n"); exit(1); } void assignStringToUniqueOption(char** p, char* target, char* key) { /* The idea is to make a string variable (say, plainTextString) point to a value inside argv[]. 'p' points to that string variable; 'target' points to the relevant argv entry; 'key' (say, -p) is the name of the option whose value is held in 'target'. If 'target' is null, complain and exit (it should never be, because the 'key' option is supposed to have a value). If the char* pointed by 'p' is null, make 's' point to 'target'; otherwise, complain that the option 'key' has already been seen, and exit. */ if (!target) { printf("Option without value: %s\n", key); exitMentioningHelp(); } if (*p) { printf("Multiple occurrences of %s\n", key); exitMentioningHelp(); } else { *p = target; } } int main(int argc, char* argv[]) { /* Process the command line options, point out the errors if they're badly formed and obey them if they're ok. WARNING: this accesses, and even writes to, the global variables 'tag*'. */ int i; char* userKeyString = 0; char* plainTextString = 0; char* cipherTextString = 0; char* formatString = 0; char* mode = 0; char* msg = 0; WORD plainText[4], cipherText[4]; int result=TRUE; if (sizeof(WORD) < 4) { printf("ERROR: on this architecture 'WORD' is %d bits (need at least 32)\n", (int) (sizeof(WORD)*8)); exit(1); } i = 1; while (argv[i]) { if (strcmp(argv[i], "-k") == 0) { assignStringToUniqueOption(&userKeyString, argv[++i], "-k"); } else if (strcmp(argv[i], "-p") == 0) { assignStringToUniqueOption(&plainTextString, argv[++i], "-p"); } else if (strcmp(argv[i], "-c") == 0) { assignStringToUniqueOption(&cipherTextString, argv[++i], "-c"); } else if (strcmp(argv[i], "-f") == 0) { assignStringToUniqueOption(&formatString, argv[++i], "-f"); } else if (strcmp(argv[i], "-e") == 0 || strcmp(argv[i], "-d") == 0 || strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "-h") == 0) { if (mode) { printf("You can only specify one mode\n"); exitMentioningHelp(); } else { mode = argv[i]; } } else if (strcmp(argv[i], "-t") == 0) { if (!argv[++i]) { printf("Option without value\n"); exitMentioningHelp(); } } else { printf("Unrecognised option: '%s'\n", argv[i]); exitMentioningHelp(); } i++; } if (!mode) { printf("Mode required.\n"); exitMentioningHelp(); } if (strcmp(mode, "-h") == 0) { help(); exit(0); } if ((strcmp(mode, "-e") == 0) || (strcmp(mode, "-d") == 0)) { if (!userKeyString) { printf("-k (key) required when doing -e (encrypt) or -d (decrypt)\n"); exitMentioningHelp(); } } if (strcmp(mode, "-e") == 0) { if (plainTextString) { result = stringToWords(plainTextString, plainText, 4); if (result != TRUE) { printf("Error while converting -p parameter\n"); exitMentioningHelp(); } } else { printf("-p (plaintext) required when doing -e (encrypt)\n"); exitMentioningHelp(); } } if (strcmp(mode, "-d") == 0) { if (cipherTextString) { result = stringToWords(cipherTextString, cipherText, 4); if (result != TRUE) { printf("Error while converting -c parameter\n"); exitMentioningHelp(); } } else { printf("-c (ciphertext) required when doing -d (decrypt)\n"); exitMentioningHelp(); } } /* At last we're ready to DO the thing! */ if (strcmp(mode, "-e") == 0) { render("plainText=", plainText, 4); result = doOneBlockViaNIST(plainText, userKeyString, cipherText, DIR_ENCRYPT, TRUE); if (result == TRUE) { render("cipherText=", cipherText, 4); } } else if (strcmp(mode, "-d") == 0) { render("cipherText=", cipherText, 4); result = doOneBlockViaNIST(cipherText, userKeyString, plainText, DIR_DECRYPT, TRUE); if (result == TRUE) { render("plainText=", plainText, 4); } } switch(result) { case TRUE: msg = 0; break; case BAD_KEY_DIR: msg = "BAD_KEY_DIR"; break; case BAD_KEY_MAT: msg = "BAD_KEY_MAT"; break; case BAD_KEY_INSTANCE: msg = "BAD_KEY_INSTANCE"; break; case BAD_CIPHER_MODE: msg = "BAD_CIPHER_MODE"; break; case BAD_CIPHER_STATE: msg = "BAD_CIPHER_STATE"; break; case BAD_IV: msg = "BAD_IV"; break; case BAD_HEX_DIGIT: msg = "BAD_HEX_DIGIT"; break; case BAD_LENGTH: msg = "BAD_LENGTH"; break; case BAD_NUMBER_OF_BITS_PROCESSED: msg = "BAD_NUMBER_OF_BITS_PROCESSED"; break; default: msg = "UNRECOGNISED_RESULT"; break; } if (msg) { printf("Error %d: %s\n", result, msg); } return 0; }
C
// Lab 3.1 Questin 1 // Inbasekaran.P 201EC226 /*To determine whether a character entered is in lowercase, uppercase, digit or a special character.*/ // For printf() and scanf() #include <stdio.h> // Including stdlib for system("clear") to clear the screen in the terminal. #include <stdlib.h> int main() { // To clear the console. system("clear"); printf("Enter the character: "); char ch; scanf("%c", &ch); if (ch >= 'a' && ch <= 'z') { printf("The character is lower case letter.\n"); } else if (ch >= 'A' && ch <= 'Z') { printf("The character is upper case letter.\n"); } else if (ch >= '0' && ch <= '9') { printf("The character is a digit.\n"); } else { printf("The character is a special character.\n"); } system("pause"); return 0; }
C
#include<stdio.h> void main() { char usr[20], pwd[20]; printf("Enter your username : "); gets(usr); printf("Enter your password : "); gets(pwd); if((strcmp(usr,"admin")==0)&&(strcmp(pwd,"123")==0)) { printf("login successful!"); } else { printf("login failed!"); } }
C
#include <stdio.h> int main(){ int n, ans = 0, num; scanf("%d",&n); for(int i = 0; i < n; i++){ scanf("%d",&num); ans ^= num; } printf("%d\n",ans); }
C
/* Autor : Linda von Groote Klasse : FI12 Dateiname : SpielerBewertung.c Datum : 16. Mrz 2009 */ #include "Funktionen.h" void spielerBewertung( int iSpielTyp, int iGewonnen) /* Ruft die Berechnung der neuen Elo-Zahlen fr den jeweiligen Gewinner des Spiels auf. 1. iSpielTyp : Typ des gespielten Spiels (z. B. Vier gewinnt) 2. iGewonnen : Gewinner des Spiels (z. B Spieler 2) */ { double dElo1; /* Alte Elo-Zahl fr Spieler1 */ double dElo2; /* Alte Elo-Zahl fr Spieler2 */ double dBNeu1=0; /* Neue Elo-Zahl fr Spieler1 */ double dBNeu2=0; /* Neue Elo-Zahl fr Spieler2 */ double dPunkte=0; /* erreichte Punkte pro Spiel */ /* Alte Elo-Zahlen aus Statistik-Datei auslesen */ dElo1 = StatistikLeseWert(1, iSpielTyp, 4); dElo2 = StatistikLeseWert(2, iSpielTyp, 4); switch(iGewonnen){ /* Spieler1 gewinnt */ case 1: dBNeu1 = eloBerechnungSp1(dElo1, dElo2, 1.0); dBNeu2 = eloBerechnungSp2(dElo2, dElo1, 0.0); if(dBNeu1 < 0) { dBNeu1 = 0; } if(dBNeu2 < 0) { dBNeu2 = 0; } /* neue Werte im User array speichern: */ StatistikAenderElo(1,iSpielTyp,dBNeu1); StatistikAenderElo(2,iSpielTyp,dBNeu2); break; /* Spiel unentschieden */ case 0: dBNeu1 = eloBerechnungSp1(dElo1, dElo2, 0.5); dBNeu2 = eloBerechnungSp2(dElo2, dElo1, 0.5); if(dBNeu1 < 0) { dBNeu1 = 0; } if(dBNeu2 < 0) { dBNeu2 = 0; } /* neue Werte im User array speichern: */ StatistikAenderElo(1,iSpielTyp,dBNeu1); StatistikAenderElo(2,iSpielTyp,dBNeu2); break; /* Spieler2 gewinnt */ case -1: dBNeu1 = eloBerechnungSp1(dElo1, dElo2, 0.0); dBNeu2 = eloBerechnungSp2(dElo2, dElo1, 1.0); if(dBNeu1 < 0) { dBNeu1 = 0; } if(dBNeu2 < 0) { dBNeu2 = 0; } /* neue Werte im User array speichern: */ StatistikAenderElo(1,iSpielTyp,dBNeu1); StatistikAenderElo(2,iSpielTyp,dBNeu2); break; } } double eloBerechnungSp1(double dElo1, double dElo2, double dPunkte) /* Berechnet die neuen Elo-Zahlen und schreibt sie in die Statistik-Datei. 1. dElo1 : Alte Elo-Zahl von Spieler1 2. dElo2 : Alte Elo-Zahl von Spieler2 3. dPunkte : erreichte Punkte fr das aktuelle Spiel */ { double dBDelta=0; /* Differenz der Elo-Zahlen beider Spieler */ double dErgErwartet=0; /* erwarteter Elo-Wert */ double dBNeu1=0; /* neue errechneter Elo-Wert */ double dTest=0; /* Bewertungsdifferenz */ dBDelta = dElo1 - dElo2; /* Erwartungswert */ if(dBDelta <0){ dErgErwartet = pow(0.5, (-dBDelta/201)); } else{ dErgErwartet = 1-(pow(0.5, dBDelta/201)); } dTest=dBDelta/201; /* Berechnung der neuen Bewertung */ dBNeu1 = dElo1 + (50*(dPunkte - dErgErwartet)); return dBNeu1; } double eloBerechnungSp2(double dElo2, double dElo1, double dPunkte){ double dBDelta=0; /* Differenz der Elo-Zahlen beider Spieler */ double dErgErwartet=0; /* erwarteter Elo-Wert */ double dBNeu2=0; /* neue errechneter Elo-Wert */ /* Bewertungsdifferenz */ dBDelta = dElo2 - dElo1; /* Erwartungswert */ if(dBDelta <0){ dErgErwartet = pow(0.5, (-dBDelta/201)); } else{ dErgErwartet = 1-(pow(0.5, dBDelta/201)); } /* Berechnung der neuen Bewertung */ dBNeu2 = dElo2 + 50*(dPunkte - dErgErwartet); return dBNeu2; }
C
//2015041050 허준수 임베디드 시스템 과제 #include<stdio.h> //입출력을 위한 라이브러리 선언 #include<stdlib.h> //atoi, exit을 위한 라이브러리 선언 #include<unistd.h> //서버 소켓을 닫기 위한 라이브러리 선언 #include<string.h> //문자열 처리를 위한 라이브러리 선언 #include<arpa/inet.h> //ip주소 처리를 위한 라이브러리 선언 #include<sys/socket.h> //소켓 처리를 위한 라이브러리 선언 #include<pthread.h> //쓰레드 처리를 위한 라이브러리 선언 #include<fcntl.h> //O_RDONLY를 사용하기 위한 헤더 #define BUFSIZE 1024 //메세지 최대 길이 1024byte로 제한 typedef struct Client{ //클라이언트의 정보를 저장해놓을 구조체 int sock; //소켓 번호 char ip[16]; //ip 주소 }Client; void *thread_func(void *arg); //클라이언트별 생성한 쓰레드를 서버에서 처리할 함수 정의 void request_handling(char buf[BUFSIZE], Client *client_info); //클라이언트의 요청을 int calc_cgi(char *buf); //cgi 계산후 리턴해주는 함수 정의 void make_log(char *addr, char *file_name, int file_size); //로그 생성 함수 정의 void error_handling(char *message); //에러 처러 함수 정의 pthread_mutex_t m_lock; char path[256] = ""; //프로그램 실행시 지정한 경로를 저장해놓는 변수 int main(int argc, char **argv) //메인함수 시작 { int nSockOpt = 1; //소켓 옵션을 변경하기 위한 변수 int server_sock; //서버소켓과 클라이언트 소켓 변수 struct sockaddr_in server_addr, client_addr; //서버와 클라이언트 주소 변수 int client_addr_size; //클라이언트의 주소 크기 변수 pthread_t client_id; //쓰레드로 처리할 클라이언트 변수 int thread_return; //쓰레드 종료후 리턴값을 받기 위한 변수 char *client_ip; //클라이언트 ip주소를 담기위한 변수 int pid; //스레드 id를 저장하기 위한 변수 char buf[BUFSIZE]; //요청을 읽기위한 변수 Client *clinet_info; //클라이언트가 생성될때마다 저장하기 위한 구조체 포인터 FILE *fp; //log.txt를 열기 위한 변수 if (argc != 3) //입력을 잘못했을때 사용방법을 알려주고 프로그램을 종료한다. { printf(" Usage : %s <path> <port>\n", argv[0]); //실행방법 출력 exit(1); //프로그램 종료 } fp = fopen("log.txt", "w"); //log.txt를 w모드로 연다. fclose(fp); //파일을 바로 닫아서 안에있는 내용을 전부 지운다 pthread_mutex_init(&m_lock, NULL); strcpy(path, argv[1]); //프로그램 실행시 지정한 경로를 path에 저장한다 if(path[strlen(path) - 1] == '/'){ //파일 경로 맨 뒷글자가 /로 끝나면 path[strlen(path) - 1] = 0; //없애준다. } if((server_sock=socket(PF_INET, SOCK_STREAM, 0)) == -1) //서버 소켓을 생성한 뒤, 생성이 되었는지 판별 error_handling("socket() error"); //소켓이 생성되지 않는다면 에러를 출력 memset(&server_addr, 0, sizeof(server_addr)); //서버 주소 변수 모두 0으로 초기화 server_addr.sin_family=AF_INET; //IPv4주소체계 사용 server_addr.sin_addr.s_addr=inet_addr("0.0.0.0"); //IP를 모든 NIC에서 바인딩할 수 있도록 설정 server_addr.sin_port=htons(atoi(argv[2])); //포트번호 설정 setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &nSockOpt, sizeof(nSockOpt)); //서버 소켓을 재사용할수있게 바꿔준다. //소켓에 주소를 할당하고 오류가 발생하면 에러를 출력 if (bind(server_sock, (struct sockaddr*)&server_addr, sizeof(server_addr))==-1) error_handling("bind() error"); //에러 출력 부분 //서버 소켓에서 클라이언트의 접속 요청을 기다리도록 설정 if (listen(server_sock, 100)==-1) error_handling("listen() error"); //에러 출력 부분 while(1) //클라이언트가 접속했을때 처리해주는 반복문 { //클라이언트가 생성될때마다 새로 할당해준다. clinet_info = (Client *)malloc(sizeof(Client)); //클라이언트 주소의 크기를 저장시켜놓는다. client_addr_size=sizeof(client_addr); //accept함수를 통해 클라이언트의 접속 요청을 받는다. clinet_info->sock=accept(server_sock, (struct sockaddr*)&client_addr, &client_addr_size); //클라이언트의 ip주소를 저장해놓는다 client_ip = inet_ntoa(client_addr.sin_addr); //저장된 클라이언트 ip주소를 구조체 문자형 배열에 옮겨넣는다. strncpy(clinet_info->ip, client_ip, strlen(client_ip) + 1); //접속에 성공한다면 if(clinet_info->sock != -1){ //서버가 클라이언트를 제어할 쓰레드를 생성한다. pid = pthread_create(&client_id, NULL, thread_func, (void*)clinet_info); if(pid < 0){ //스레드가 생성되지 못했다면 close(clinet_info->sock); //클라이언트 소켓을 닫아주고 error_handling("Thread create() error\n"); //스레드 생성 오류라고 에러 출력 } pthread_detach(client_id); } else{ //접속에 실패한다면 close(clinet_info->sock); //클라이언트 소켓을 닫아준다. return 0; } } //프로그램이 종료되면 서버소켓을 닫는다. close(server_sock); //0값을 반환하며 프로그램 종료 return 0; } void request_handling(char buf[BUFSIZE], Client *client_info){ //요청을 처리하는 함수 char file_name[256] = ""; //요청한 파일의 이름을 저장하는 변수 (ex. /images/05_01.gif) char file_path[256] = ""; //요청한 파일의 경로를 저장하는 변수 (ex. ./html/images/05_01.gif) char cgi_len[15]; //total.cgi의 정수 리턴값을 문자열로 받기위한 변수 char file_extension[5]; //파일의 확장자를 저장하기 위한 변수 (ex. .jpg, .gif, .htm) int filed, size; //filed : 파일을 열기위한 변수, size : 파일 크기 계산을 위한 변수 unsigned long long int n = 0; //total.cgi를 처리하고 받아올 변수 int i = 0; //반복문을 위한 변수 unsigned long int sum = 0; //총 파일 크기를 계산하기 위한 변수 //buf : GET 파일경로 HTTP/1.1 buf[1024] = 0; for(i = 4; i < 1024; i++){ //버퍼의 4번째 인덱스부터 탐색 if(buf[i] == ' '){ //공백이 있다면 buf[i] = 0; //NULL값으로 만든다 break; //NULL값으로 만들고 종료하면 buf : GET 파일경로 이렇게 바뀜 } } strncpy(file_name, &buf[4], 256); //파일의 이름을 file_name에 받아놓는다. strcpy(file_path, path); //파일 경로를 file_path에 복사해놓는다. if(strncmp(buf, "GET /", 6) == 0){ //index.html을 처리해야할때 sprintf(buf, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"); //요청에 대한 응답을 보낼 문자열 저장 write(client_info->sock, buf, strlen(buf)); //응답을 클라이언트 소켓에 보낸다. strcat(file_path, "/index.html"); //file_path에 /index.html을 붙여서 파일경로/index.html로 만든다. filed = open(file_path, O_RDONLY); //file_path에 있는 파일을 열어서 파일 디스크립터인 filed에 저장한다. while((size = read(filed, buf, BUFSIZE)) > 0){ //filed에 있는 내용을 계속 읽어온다. (size : 읽어온 크기) write(client_info->sock, buf, size); //읽어오면서 클라이언트 소켓에 읽어온 내용을 전달한다. sum += size; //파일의 크기를 계속 추가시킨다. } make_log(client_info->ip, "/index.html", sum); //로그 작성 close(filed); //filed를 닫아준다. } strcat(file_path, file_name); //file_path에 file_name을 붙여 파일경로/파일이름 으로 만든다. filed = open(file_path, O_RDONLY); //file_path에 있는 파일을 열어서 파일 디스크립터인 filed에 저장한다. strcpy(file_extension, &file_name[strlen(file_name) - 4]); //파일 이름 뒤의 4개 문자를 추출하여 파일 확장자 이름을 file_extension에 저장한다. if(strcmp(file_extension, ".jpg") == 0){ //jpg file일때 sprintf(buf, "HTTP/1.1 200 OK\r\nContent-Type: image/jpg\r\n\r\n"); //요청에 대한 응답을 보낼 문자열 저장 write(client_info->sock, buf, strlen(buf)); //응답을 클라이언트 소켓에 보낸다. sum = 0; //파일의 크기를 0으로 초기화한다. while((size = read(filed, buf, BUFSIZE)) > 0){ //filed에 있는 내용을 계속 읽어온다. (size : 읽어온 크기) write(client_info->sock, buf, size); //읽어오면서 클라이언트 소켓에 읽어온 내용을 전달한다. sum += size; //파일의 크기를 계속 추가시킨다. } make_log(client_info->ip, file_name, sum); //로그 작성 } else if(strcmp(file_extension, ".gif") == 0){ //gif file일때 sprintf(buf, "HTTP/1.1 200 OK\r\nContent-Type: image/gif\r\n\r\n"); //요청에 대한 응답을 보낼 문자열 저장 write(client_info->sock, buf, strlen(buf)); //응답을 클라이언트 소켓에 보낸다. sum = 0; //파일의 크기를 0으로 초기화한다. while((size = read(filed, buf, BUFSIZE)) > 0){ //filed에 있는 내용을 계속 읽어온다. (size : 읽어온 크기) write(client_info->sock, buf, size); //읽어오면서 클라이언트 소켓에 읽어온 내용을 전달한다. sum += size; //파일의 크기를 계속 추가시킨다. } make_log(client_info->ip, file_name, sum); //로그 작성 } else if(strstr(file_name, "?from=") != NULL){ //cgi request일때 n = calc_cgi(file_name); //n에다가 total.cgi 계산한 값을 넣어준다. //요청에 대한 응답을 보낼 문자열 저장과 동시에 n의 값을 전달해준다. sprintf(buf, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<HTML><BODY>%lld</BODY></HTML>\r\n", n); write(client_info->sock, buf, strlen(buf)); //응답을 클라이언트 소켓에 보낸다. sprintf(cgi_len, "%lld", n); //cgi_len에 n의값을 문자열로 저장한다. make_log(client_info->ip, file_name, strlen(cgi_len)); //로그 작성 } else if(strcmp(file_extension, ".htm") == 0){ //htm file일때 sprintf(buf, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"); //요청에 대한 응답을 보낼 문자열 저장 write(client_info->sock, buf, strlen(buf)); //응답을 클라이언트 소켓에 보낸다. sum = 0; //파일의 크기를 0으로 초기화한다. while((size = read(filed, buf, BUFSIZE)) > 0){ //filed에 있는 내용을 계속 읽어온다. (size : 읽어온 크기) write(client_info->sock, buf, size); //읽어오면서 클라이언트 소켓에 읽어온 내용을 전달한다. sum += size; //파일의 크기를 계속 추가시킨다. } make_log(client_info->ip, file_name, sum); //로그 작성 } else{ //Not Found일때 sprintf(buf, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<HTML><BODY>NOT FOUND</BODY></HTML>\r\n"); //요청에 대한 응답을 보낼 문자열 저장 write(client_info->sock, buf, strlen(buf)); //응답을 클라이언트 소켓에 보낸다. make_log(client_info->ip, file_name, 9); //로그 작성 } close(filed); //파일 디스크립터를 종료시킨다. } //클라이언트별 생성한 쓰레드를 서버에서 처리할 함수 void *thread_func(void *arg) { Client *client_info=(Client*)arg; //접속한 클라이언트의 소켓 정보를 저장하는 변수 int str_len=0; //클라이언트에게 수신된 문자의 길이를 저장하는 변수 (-1이면 수신 실패) char buf[BUFSIZE]; //클라이언트의 이름과 메세지를 저장하는 변수 str_len = read(client_info->sock, buf, BUFSIZE); if(str_len != -1){ //수신에 성공했다면 request_handling(buf, client_info); //요청을 처리해주는 함수 실행 } else{ //수신에 실패한다면 error_handling("recieve() error"); //에러 처리 } close(client_info->sock); //스레드가 끝나면 클라이언트 소켓을 닫아준다. } int calc_cgi(char *buf){ //total.cgi기능을 처리하기 위한 함수 char *tok; //문자열을 토큰 단위로 분리하기 위해 사용하는 변수 int n,m; //NNN : n , MMM : m int num; //NNN부터 MMM까지의 갯수를 저장하기 위한 변수 unsigned long long int sum = 0; //총 합을 저장하는 변수 //토큰 분리하기 위한 변수를 우선 받아온 버퍼만큼 크기를 할당한다. tok = (char *)malloc(sizeof(char) * strlen(buf)); strcpy(tok, buf); //buf의 내용을 tok에 저장 (/total.cgi?from=NNN&to=MMM) tok = strtok(tok, "="); //tok에 /total.cgi?from 분리 tok = strtok(NULL, "&"); //tok에 NNN 분리 n = atoi(tok); //NNN을 숫자로 변환 tok = strtok(NULL, "="); //tok에 &to 분리 tok = strtok(NULL, "\0"); //tok에 MMM 분리 m = atoi(tok); //MMM을 숫자로 변환 num = m - n + 1; //n부터 m까지의 갯수를 저장 if(num % 2 == 0){ //갯수가 짝수이면 sum = (n + m) * (num / 2); //n + m 한 다음 갯수의 절반을 곱하여 합을 구한다. } else{ //갯수가 홀수이면 sum = (n + m) * (num / 2) + (n + (num / 2)); //n+m 한 다음 갯수의 절반을 곱하고 가장 가운데있는 수를 한번 더 더해준다. } return sum; //합을 리턴한다. } void make_log(char *addr, char *file_name, int file_size){ //로그작성을 위한 함수 FILE *log; //로그 파일을 열기 위한 파일포인터 char buf[BUFSIZE] = ""; //로그 파일에 저장을 하기 위한 문자열 변수 if((log = fopen("log.txt", "a")) != NULL){ //로그 파일을 열고 파일이 열린다면 sprintf(buf, "%s %s %d\n", addr, file_name, file_size); //버퍼에 로그에 작성할 문자열을 저장한다 (IP 파일이름 파일크기) fprintf(log, "%s", buf); //로그에 작성을 한다. fclose(log); //파일포인터를 닫는다. } else{ fclose(log); error_handling("log open error"); //파일이 열리지 않는다면 에러처리 } } //에러 처리를 위한 함수(에러문을 출력한 뒤 프로그램을 종료한다.) void error_handling(char *message) { fputs(message, stderr); //에러 메세지를 출력을 해준다. fputc('\n', stderr); //깔끔하게 보이게 하기 위한 줄바꿈 exit(1); //프로그램 종료 }
C
#include<stdio.h> struct node { int player_id; struct node *next; }; struct node *start,*ptr,*new_node; int main() { int n,k,i,count; printf("\nEnter the number of players:"); scanf("%d",&n); printf("\nEnter the value of k (every kth players gets eliminated):"); scanf("%d",&k); start=malloc(sizeof(struct node)); start->player_id=1; ptr=start; for(i=2;i<=n;i++) { new_node=malloc(sizeof(struct node)); ptr->next=new_node; new_node->player_id=i; new_node->next=start; ptr=new_node; } for(count=n;count>1;count--) { for(i=0;i<k-1;++i) ptr=ptr->next; ptr->next=ptr->next->next; } printf("\nTHE WINNER IS PLAYER %d",ptr->player_id); }
C
#include "Display_Time.h" #include <string.h> #include "../Scenes.h" void Display_Time_ctor(Display_Time* self, char* prefix, float* display_times, grText_Renderer* text_r, float x) { *self = (Display_Time){ .prefix = strdup(prefix), .prefix_length = strlen(prefix), .display_times = display_times, .text_r = text_r, .x = x }; geComponent_ctor(&self->_super); geSet_Sub_Component(self, Update_Display_Time, Display_Time_Sub_Component_dtor, &self->_super); } Display_Time* Display_Time_new(char* prefix, float* display_times, grText_Renderer* text_r, float x) { Display_Time* dt = malloc(sizeof *dt); if (dt == NULL) { return NULL; } Display_Time_ctor(dt, prefix, display_times, text_r, x); geSet_Sub_Component(dt, dt->_super._update, Display_Time_Sub_Component_del, &dt->_super); return dt; } void Update_Display_Time(geComponent* component) { Display_Time* dt = component->_sub; char* to_set; char s[100]; strcpy(s, dt->prefix); if (dt->display_times[focused_level_num] < 0) { to_set = ""; } else { sprintf(s + dt->prefix_length,"%.2f",dt->display_times[focused_level_num]); to_set = s; } grSet_Text_Contents(to_set, dt->text_r->text); // dt->text_r->frame->position.i[0] = dt->x + focused_level_num*60; }; void Display_Time_Sub_Component_dtor(geComponent* component) { Display_Time* dt = component->_sub; if (dt->prefix != NULL) { free(dt->prefix); } } void Display_Time_Sub_Component_del(geComponent* component) { Display_Time* dt = component->_sub; Display_Time_Sub_Component_dtor(&dt->_super); free(dt); }
C
#include <stdio.h> #include <unistd.h> #include <getopt.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <dirent.h> #include <signal.h> #include <fcntl.h> #include <errno.h> #define FIFO_NAME "fifo-sp06" char file_path[PATH_MAX + 1]; int id_ = 0; int child(){ int fifo; fprintf(stderr, "Zadajte cestu k priecinku:"); scanf("%100s", (char*)&file_path); if(kill(getppid(), SIGUSR1) != 0 ){ perror("kill"); exit(EXIT_FAILURE); } //FIFO umask(0); if( mkfifo(FIFO_NAME, 0660) == -1 && errno != EEXIST){ perror("mkfifo"); exit(EXIT_FAILURE); } if((fifo = open(FIFO_NAME, O_WRONLY)) == -1 ){ perror("open"); exit(EXIT_FAILURE); } if(unlink(FIFO_NAME) != 0){ perror("unlink"); exit(EXIT_FAILURE); } write(fifo, &file_path, sizeof(file_path)); if(close(fifo) != 0) { perror("close"); exit(EXIT_FAILURE); } return 1; } void printHelpAndExit(FILE* stream, int exitCode){ fprintf(stream, "Usage: parametre [-h] [-i | --id] [<dir>]\n"); fprintf(stream, "Program vypise zoznam vsetkych poloziek adresara v adresarovej strukture. Ak je definovany prepinac, zobrazi sa aj gid a uid\n"); exit(exitCode); } void getPath(){ char buffer[50]; fprintf(stderr, "Zadajte cestu k novemu priecinku:"); scanf("%49s", (char*)&buffer); strncpy(file_path, buffer, sizeof(file_path)); } void getPathFromChild(){ int fifo; pid_t pid; int sig_num; sigset_t set; sigemptyset(&set); sigaddset(&set, SIGUSR1); if(sigprocmask(SIG_SETMASK, &set, NULL) != 0){ perror("sigprocmask"); exit(EXIT_FAILURE); } pid = fork(); switch(pid){ case 0: child(file_path); exit(EXIT_SUCCESS); case -1: perror("fork"); exit(EXIT_FAILURE); default: if(sigwait(&set, &sig_num) != 0){ perror("sigwait"); exit(EXIT_FAILURE); } break; } //FIFO umask(0); if( mkfifo(FIFO_NAME, 0660) == -1 && errno != EEXIST){ perror("mkfifo"); exit(EXIT_FAILURE); } if((fifo = open(FIFO_NAME, O_RDONLY)) == -1) { perror("open"); exit(EXIT_FAILURE); } if(read(fifo, &file_path, sizeof(file_path)) != sizeof(file_path)) { fprintf(stderr, "Error occured while reading from FIFO"); exit(EXIT_FAILURE); } if(close(fifo) != 0) { perror("close"); exit(EXIT_FAILURE); } } void parseArgs(int argc, char * argv[]) { int opt; static struct option long_options[] = { {"help", 0, NULL, 'h'}, {"id", 0, NULL, 'i'}, {0, 0, 0, 0} }; int option_index = 0; do { opt = getopt_long(argc, argv, "hi", long_options, &option_index); switch (opt) { case 'h': printHelpAndExit(stderr, EXIT_SUCCESS); break; case 'i': id_ = 1; break; case '?': fprintf(stderr,"Neznama volba -%c\n", optopt); printHelpAndExit(stderr, EXIT_FAILURE); default: break; } } while(opt != -1); if(optind < argc ) { strncpy(file_path, argv[argc - 1], sizeof(file_path)); } else { getPathFromChild(); } } void readDir(char* dir){ DIR* directory; struct dirent* entry; size_t length; length = strlen(dir); if (dir[length - 1] != '/') { dir[length] = '/'; dir[length + 1] = '\0'; ++length; } if((directory = opendir(dir)) == NULL){ perror("opendir"); exit(EXIT_FAILURE); } struct stat st; char file[PATH_MAX + 1]; strcpy(file, dir); fprintf(stderr, "%s\n", dir); while(( entry = readdir(directory)) != NULL) { if(strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0){ strncpy(file + length, entry->d_name, sizeof(file) - length); lstat (file, &st); if(id_) fprintf(stderr, "\tuid:%i gid:%i %s\n", st.st_uid, st.st_gid, entry->d_name); //vypisem kazdu polozku else fprintf(stderr, "\t%s\n", entry->d_name); //vypisem kazdu polozku } } if(closedir(directory) != 0 ) { perror("closedir"); exit(EXIT_FAILURE); } //Jednoduchie ako posielat signaly a pamatat si pocet deti... if((directory = opendir(dir)) == NULL){ perror("opendir"); exit(EXIT_FAILURE); } strcpy(file, dir); while(( entry = readdir(directory)) != NULL) { if(strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0){ strncpy(file + length, entry->d_name, sizeof(file) - length); lstat (file, &st); if(S_ISDIR (st.st_mode)){ pid_t pid = fork(); //musi byt aby sme mohli rekurzivne volat(nemoze byt otvorenzch tolko dir jednym porcesom if(!pid){ readDir(file); exit(EXIT_SUCCESS); } else { wait(NULL); } } } } if(closedir(directory) != 0 ) { perror("closedir"); exit(EXIT_FAILURE); } } int main(int argc, char * argv[]){ parseArgs(argc, argv); while(1){ readDir(file_path); getPath(); } return EXIT_SUCCESS; }
C
/* Author: Rodolfo Reyes * Lab Section: 23 * Assignment: Lab 2 Exercise 2 * Exercise Description: Parking space counter * * I acknowledge all content contained herein, excluding template or example * code, is my own original work. */ #include <avr/io.h> #ifdef _SIMULATE_ #include "simAVRHeader.h" #endif int main(void) { DDRA = 0x00; PORTA = 0xFF; // Configure port A's 8 pins as inputs DDRB = 0xFF; PORTB = 0x00; // Configure port B's 8 pins as outputs unsigned char tmpA = 0x00; // Temporary variable to hold the value of A unsigned char cntavail = 0x00; while(1) { tmpA = PINA;//temp value hold input if (tmpA != 0x00) //true if input greater than 1 { while(tmpA != 0x00)//will run as long as input contains greater than 0 { count=count+1; tmpA=tmpA>>1;//fills in temp value with 0 } PORTB = cntavail; // sets output to number counted cntavail=0x00; } else //resets count and output when no input { cntavail=0x00; PORTB = 0x00; } } return 1; }
C
Bug report on Kyle's: Bug 1: Date: 2/20/2016 Reported By: Ava Petley email: [email protected] File: dominion.c Function: smithy Description: Two tests revealed an error with smithy function. The test are cardtest1 and randomtestcard. The handcount of the current player is incorrect and another players status is effected cardtest1: expected: hand to increase by 2 after 3 cards are added and one is discarded. actual : the hand count remained the same( 5 before and 5 after) randomtestcard: expected: current players hand to increase by 2 and other players hand to not be effected actual: the players hands not increased by the correct amount the hand count is too low the other players status has been effected. Bug report on Kyle's: Bug 2: Date : 2 / 20 / 2016 Reported By : Ava Petley email : [email protected] File: dominion.c Function: Adventurer Description: Two tests revealed an error with the adventurer card, cardtest4 and randomtestadventurer. The error is that not enough treasure cards are being added to the players hand. cardtest4: expected: two treasure cards to be added to players hand actual: players hand is short cards after play randomtestadventurer: expected: two treasure cards to be added to players hand actual: incorrect number of treasure cards added. Bug Report on Kyle's: Bug 3: Date 2/20/2016 Reported By:Ava Petley email: [email protected] File: dominion.c Function: village Description: an error was discoved with the village function actions were not added cardtest2: expected: 2 actions to be added actual: actions not added Test Results: fragments of the results for each test on Kyle's code: unittest1 on updateCoins: no errors unittest2 on discardCard: no error unittest3 on gainCardL no error unittest4 on isGameOver: Pass: game not ended correctly identified Pass: Correctly identified end of game due to provinces out Pass: Correctly identified end of game for three piles empty cardtest1 on smithy: Fail: The players hand should be increase by 2, 3 added 1 discarded hand Count: 5 hc:5 cardtest2 on village: Pass: the hand count doesn't change Fail: actions should be added cardtest3 on steward: no error cardtest4 on adventurer: Pass: no treasure cards were discarded Fail: The player hand increases by at least one card randomtestcard Fail: The players hand not increased by the correct amount hand count is too low. should increase by two Fail: The other players status have been effected randomtestadventurer: Fail: incorrect number of treasure cards added Fail: handcount is : 9 and hcbefore is 8
C
/* Zachary Osborne Lab02 */ #include <stdio.h> #include <string.h> #include <stdlib.h> void stringToNum() { char clearBuffer[10]; fgets(clearBuffer, 10, stdin); char input[10]; printf("Enter a string: \n"); fgets(input, 10, stdin); int len = strlen(input); printf(".-----------------.\n| char| dec| hex|\n|-----+-----+-----|\n"); for (int i = 0; i < len - 1; i++) { int val = input[i]; printf("|%5c|%5d|%5x|\n", input[i], input[i], input[i]); } printf(".-----------------.\n"); userInput(); } void numToString() { char output[10]; printf("Convert ASCII decimal values to string (press 'Enter' after each integer).\nPress 'Enter' twice to finish.\n"); int i = 0; while(1) { char input[10]; fgets(input, 10, stdin); int num = atoi(input); output[i] = (char)num; if ((output[i] == NULL)&&(output[i-1] == NULL)&&(i>1)) { break; } i++; } printf("Converted string: "); for (int j = 0; j <= i; j++) { printf("%c", output[j]); } printf("\n"); userInput(); } void userInput() { char selection; printf("Select an option: \n string -> numerical values: 1\n numerical values -> string: 2\n Exit: 3\n"); selection = getchar(); if (selection == '3') return; else if (selection == '1') stringToNum(); else if (selection == '2') numToString(); else { printf("Invalid selection %c", selection); userInput(); } } int main() { userInput(); return 0; }
C
#include "libmx.h" void *mx_memrchr(const void *s, int c, size_t n) { char *str = NULL; int len; if (s) { str = (char *) s; len = mx_strlen(str) - 1; while (len >= 0 && n != 0) { if (str[len] == c) return &str[len]; n--; len--; } return NULL; } return NULL; }
C
#include "kernel/types.h" #include "kernel/stat.h" #include "user/user.h" int main(int argc, char *argv[]){ if(argc<2) { fprintf(2,"error:no argument\n"); exit(1); } const char * ticksStr=argv[1]; int ticks=atoi(ticksStr); sleep(ticks); exit(0); }
C
#include<stdio.h> #include<string.h> void main() { char str[100]; int i,len; len=strlen(str); for(i=len-1;i>0;i++) { printf("%c",str[i]); } }
C
// PA2 // CMPS 101 Tantalo Spring 2019 // Aaron Nguyen // anguy200 // 1585632 #include<stdio.h> #include<stdlib.h> #include<string.h> #include"List.h" #define MAX_LEN 180 int main(int argc, char* argv[]){ int linecount = 0; FILE *in, *out; char line[MAX_LEN]; // check command line for correct number of arguments if( argc != 3 ){ printf("Usage: %s <input file> <output file>\n", argv[0]); exit(1); } // open files for reading and writing in = fopen(argv[1], "r"); out = fopen(argv[2], "w"); if( in==NULL ){ printf("Unable to open file %s for reading\n", argv[1]); exit(1); } if( out==NULL ){ printf("Unable to open file %s for writing\n", argv[2]); exit(1); } //printf("Hello"); while(fgets(line, MAX_LEN, in) != NULL){ linecount++; //printf("%d", linecount); } rewind(in); char words[linecount][MAX_LEN]; for(int i = 0; i < linecount; i++){ fgets(line, MAX_LEN, in); strcpy(words[i], line); //printf("%s", line); } List sorted = newList(); for(int x = 0; x < linecount; x++){ if(length(sorted) == 0){ append(sorted, x); }else{ int inserted = 0; moveFront(sorted); while(index(sorted) != -1){ int comp = strcmp(words[x], words[get(sorted)]); if(comp == 0){ insertAfter(sorted, x); inserted++; break; }else if(comp < 0){ insertBefore(sorted, x); inserted++; break; }else{ moveNext(sorted); } } if(inserted == 0){ append(sorted,x); } } } //printList(stdout, sorted); moveFront(sorted); for(int x = 0; x < linecount; x++){ fprintf(out, "%s", words[get(sorted)]); moveNext(sorted); } freeList(&sorted); fclose(in); fclose(out); return(0); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* libft.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: oupside <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/10/17 19:34:18 by oupside #+# #+# */ /* Updated: 2021/10/17 19:34:22 by oupside ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef LIBFT_H # define LIBFT_H # include <stdlib.h> # include <unistd.h> int ft_atoi(const char *str); void ft_bzero(void *s, size_t n); void *ft_calloc(size_t n, size_t size); int ft_isalnum(int d); int ft_isalpha(int d); int ft_isascii(int d); int ft_isdigit(int d); int ft_isprint(int d); char *ft_itoa(int n); void *ft_memchr(const void *str, int d, size_t n); int ft_memcmp(const void *str1, const void *str2, size_t n); void *ft_memcpy(void *dest, const void *src, size_t count); void *ft_memmove(void *dest, const void *src, size_t len); void *ft_memset(void *s, int d, size_t len); void ft_putchar_fd(char c, int fd); void ft_putendl_fd(char *s, int fd); void ft_putnbr_fd(int n, int fd); void ft_putstr_fd(char *s, int fd); char **ft_split(char const *s, char c); char *ft_strchr(const char *str, int s); char *ft_strdup(const char *str); void ft_striteri(char *s, void (*f)(unsigned int, char*)); char *ft_strjoin(char const *s1, char const *s2); size_t ft_strlcat(char *dest, const char *src, size_t size); size_t ft_strlcpy(char *dest, const char *src, size_t size); size_t ft_strlen(const char *s); char *ft_strmapi(char const *s, char (*f)(unsigned int, char)); int ft_strncmp(const char *str1, const char *str2, size_t n); char *ft_strnstr(const char *s1, const char *s2, size_t n); char *ft_strrchr(const char *str, int s); char *ft_strtrim(char const *s1, char const *set); char *ft_substr(char const *s, unsigned int start, size_t len); int ft_tolower(int d); int ft_toupper(int d); #endif
C
#include "world.h" #include <stdlib.h> #include <stdint.h> #include <float.h> typedef struct { AbsolutePoint pos; AbsolutePoint vel; } VelocityPoint; // Points at which we discovered an arena border. static AbsolutePoint arena_border_points[MAX_BORDER_POINTS]; static unsigned num_arena_border_points; static unsigned arena_border_evict_row; // Points at which we know the area is clear. static VariancePoint clear_points[WORLD_CLEAR_POINTS]; static unsigned num_clear_points; static unsigned clear_points_evict_row; // Points at which we know the area is occupied. static VariancePoint occupied_points[WORLD_OCCUPIED_POINTS]; static unsigned num_occupied_points; static unsigned occupied_points_evict_row; static OrientPoint rover; // Points at which we think there is a target. static VelocityPoint targets[WORLD_TARGET_POINTS_MAX]; static VariancePoint target_stat_points[WORLD_TARGET_POINTS_MAX]; static unsigned num_targets; bool intersection_point(AbsolutePoint a0, AbsolutePoint a1, AbsolutePoint b0, AbsolutePoint b1, AbsolutePoint *intersection) { float x1 = a0.x; float x2 = a1.x; float x3 = b0.x; float x4 = b1.x; float y1 = a0.y; float y2 = a1.y; float y3 = b0.y; float y4 = b1.y; float denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); if (denom > MIN_INTERSECTION_DENOM) { intersection->x = ((x1*y2 - y1*x2) * (x3 - x4) - (x1 - x2) * (x3*y4 - y3*x4)) / denom; intersection->y = ((x1*y2 - y1*x2) * (y3 - y4) - (y1 - y2) * (x3*y4 - y3*x4)) / denom; // Check if the intersection point is on the line. return between(x1, x2, intersection->x) && between(x3, x4, intersection->x) && between(y1, y2, intersection->y) && between(y3, y4, intersection->y); } return false; } AbsolutePoint point_projection(AbsolutePoint p, AbsolutePoint l0, AbsolutePoint l1) { // Line vector AbsolutePoint v = {l1.x - l0.x, l1.y - l0.y}; // Point relative to line beginning AbsolutePoint rp = {p.x - l0.x, p.y - l0.y}; float dis_square = delta_distance_squared(v); float projection_length = vector_dot(rp, v) / dis_square; if (projection_length < 0) { return l0; } else if (powf(projection_length, 2) > dis_square) { return l1; } else { // Project the point "vector" onto the line vector and then move it back. AbsolutePoint pp = {v.x * projection_length + l0.x, v.y * projection_length + l0.y}; return pp; } } void add_evict(VariancePoint *points, unsigned *current, unsigned max, unsigned *evict_row, VariancePoint npoint) { if (*current < max) { points[(*current)++] = npoint; return; } else { float smallest_distance = point_distance_squared((points + 0)->p, (points + 1)->p); unsigned evict_index = 0; unsigned i, j; for (i = *evict_row; i < max; i += ADD_EVICT_ROWS) { for (j = i + 1; j < max; j++) { float current_distance = point_distance_squared((points + i)->p, (points + j)->p); if (current_distance < smallest_distance) { smallest_distance = current_distance; evict_index = i; } } } // Move to the next evict row. (*evict_row)++; *evict_row %= ADD_EVICT_ROWS; for (i = 0; i < max; i++) { float current_distance = point_distance_squared((points + i)->p, npoint.p); if (current_distance < smallest_distance) { // The new point has the smallest distance, so dont add it. return; } } points[evict_index] = npoint; } } void evict_close_points(VariancePoint *points, unsigned *current, unsigned max, VariancePoint npoint, float threshold_distance) { unsigned i; for (i = 0; i < *current; ) { float delta_squared = point_distance_squared(points[i].p, npoint.p); if (delta_squared < threshold_distance) { *current -= 1; points[i] = points[*current]; } else { i++; } } } void world_init(OrientPoint _rover, unsigned _num_targets, float initial_target_spawn_radius, AbsolutePoint *borders, unsigned total_border_points) { arena_border_evict_row = 0; clear_points_evict_row = 0; occupied_points_evict_row = 0; num_arena_border_points = total_border_points; unsigned i; for (i = 0; i < total_border_points; i++) arena_border_points[i] = borders[i]; num_clear_points = 0; num_occupied_points = 0; rover = _rover; num_targets = _num_targets; // TODO: Intialize these to be in a uniform circle around the center. for (i = 0; i < num_targets; i++) { float angle = i * 2 * (float)M_PI / num_targets; VelocityPoint p = {{initial_target_spawn_radius * cosf(angle), initial_target_spawn_radius * sinf(angle)}, {0.0, 0.0}}; targets[i] = p; } } void world_add_front_right_ir_sensor_reading(float distance) { static const float longest_ir_distance = 0.5f; AbsolutePoint start = rover.vp.p; AbsolutePoint initial_spacing = angle_delta(rover.angle - 0.2915f, 0.2175f); start.x += initial_spacing.x; start.y += initial_spacing.y; float distance_effective; if (distance < longest_ir_distance) { distance_effective = distance; } else { distance_effective = longest_ir_distance; } AbsolutePoint point_spacing = angle_delta(rover.angle, distance_effective / WORLD_IR_SENSOR_POINTS); unsigned i; for (i = 0; i < WORLD_IR_SENSOR_POINTS; i++) { // TODO: Compute variance. VariancePoint p = {start, 0.0, {0, 0, 0, 0}}; add_evict(clear_points, &num_clear_points, WORLD_CLEAR_POINTS, &clear_points_evict_row, p); evict_close_points(occupied_points, &num_occupied_points, WORLD_OCCUPIED_POINTS, p, CLOSE_EVICT_OCCUPIED); start.x += point_spacing.x; start.y += point_spacing.y; } if (distance < longest_ir_distance) { VariancePoint p = {start, 0.0, {0, 0, 0, 0}}; add_evict(occupied_points, &num_occupied_points, WORLD_OCCUPIED_POINTS, &occupied_points_evict_row, p); evict_close_points(clear_points, &num_clear_points, WORLD_CLEAR_POINTS, p, CLOSE_EVICT_CLEAR); } } void world_add_front_left_ir_sensor_reading(float distance) { static const float longest_ir_distance = 0.5f; AbsolutePoint start = rover.vp.p; AbsolutePoint initial_spacing = angle_delta(rover.angle + 0.197395f, 0.212459f); start.x += initial_spacing.x; start.y += initial_spacing.y; float distance_effective; if (distance < longest_ir_distance) { distance_effective = distance; } else { distance_effective = longest_ir_distance; } AbsolutePoint point_spacing = angle_delta(rover.angle, distance_effective / WORLD_IR_SENSOR_POINTS); unsigned i; for (i = 0; i < WORLD_IR_SENSOR_POINTS; i++) { // TODO: Compute variance. VariancePoint p = {start, 0.0, {0, 0, 0, 0}}; add_evict(clear_points, &num_clear_points, WORLD_CLEAR_POINTS, &clear_points_evict_row, p); evict_close_points(occupied_points, &num_occupied_points, WORLD_OCCUPIED_POINTS, p, CLOSE_EVICT_OCCUPIED); start.x += point_spacing.x; start.y += point_spacing.y; } if (distance < longest_ir_distance) { VariancePoint p = {start, 0.0, {0, 0, 0, 0}}; add_evict(occupied_points, &num_occupied_points, WORLD_OCCUPIED_POINTS, &occupied_points_evict_row, p); evict_close_points(clear_points, &num_clear_points, WORLD_CLEAR_POINTS, p, CLOSE_EVICT_CLEAR); } } void world_add_left_ir_sensor_reading(float distance) { static const float longest_ir_distance = 0.5f; AbsolutePoint start = rover.vp.p; AbsolutePoint initial_spacing = angle_delta(rover.angle + (float)M_PI / 2, 0.125f); start.x += initial_spacing.x; start.y += initial_spacing.y; float distance_effective; if (distance < longest_ir_distance) { distance_effective = distance; } else { distance_effective = longest_ir_distance; } AbsolutePoint point_spacing = angle_delta(rover.angle + (float)M_PI / 2, distance_effective / WORLD_IR_SENSOR_POINTS); unsigned i; for (i = 0; i < WORLD_IR_SENSOR_POINTS; i++) { // TODO: Compute variance. VariancePoint p = {start, 0.0, {0, 0, 0, 0}}; add_evict(clear_points, &num_clear_points, WORLD_CLEAR_POINTS, &clear_points_evict_row, p); evict_close_points(occupied_points, &num_occupied_points, WORLD_OCCUPIED_POINTS, p, CLOSE_EVICT_OCCUPIED); start.x += point_spacing.x; start.y += point_spacing.y; } if (distance < longest_ir_distance) { VariancePoint p = {start, 0.0, {0, 0, 0, 0}}; add_evict(occupied_points, &num_occupied_points, WORLD_OCCUPIED_POINTS, &occupied_points_evict_row, p); evict_close_points(clear_points, &num_clear_points, WORLD_CLEAR_POINTS, p, CLOSE_EVICT_CLEAR); } } void world_update_movement(OrientPoint movement) { rover = movement; } AbsolutePoint arena_border_index_closest(unsigned i) { AbsolutePoint *a = &arena_border_points[i]; AbsolutePoint *b = &arena_border_points[(i+1) % num_arena_border_points]; return point_projection(rover.vp.p, *a, *b); } void world_rover_aligned() { // Initial assumption: Assume the latest movement has the correct alignment. // Iterate over all border edges. unsigned i; AbsolutePoint best_position = arena_border_index_closest(0); float best_distance = point_distance_squared(best_position, rover.vp.p); unsigned best_index = 0; // NOTE: This has undefined behavior if num_arena_border_points is 1, but otherwise does not. for (i = 1; i < num_arena_border_points; i++) { AbsolutePoint current_position = arena_border_index_closest(i); float current_distance = point_distance_squared(current_position, rover.vp.p); if (current_distance < best_distance) { best_index = i; best_distance = current_distance; best_position = current_position; } } AbsolutePoint *a = &arena_border_points[best_index]; AbsolutePoint *b = &arena_border_points[(best_index+1) % num_arena_border_points]; // Get the atan2 of the border delta (which is counterclockwise). float border_angle = atan2(b->y - a->y, b->x - a->x); // Set the rover's angle to be the border angle turned right by pi/2. rover.angle = border_angle - M_PI_2; // Go the amount backwards by which the alignment sensor is forwards AbsolutePoint rover_backwards = angle_delta(-rover.angle, 0.21f); best_position.x += rover_backwards.x; best_position.y += rover_backwards.y; // Set this as the new rover position. rover.vp.p = best_position; } void world_update() { // TODO: Look for targets. } unsigned world_retrieve_arena_border_points(AbsolutePoint **points) { *points = arena_border_points; return num_arena_border_points; } unsigned world_retrieve_clear_points(VariancePoint **points) { *points = clear_points; return num_clear_points; } unsigned world_retrieve_occupied_points(VariancePoint **points) { *points = occupied_points; return num_occupied_points; } OrientPoint* world_retrieve_rover() { return &rover; } unsigned world_retrieve_targets(VariancePoint **_targets) { unsigned i; for (i = 0; i < num_targets; i++) { target_stat_points[i].p = targets[i].pos; // TODO: Calculate variance. target_stat_points[i].v = 0.1f; } *_targets = target_stat_points; return num_targets; }
C
#include <stdio.h> #include <malloc.h> int** matMult(int **a, int **b, int size){ // (4) Implement your matrix multiplication here. You will need to create a new matrix to store the product. //int** result; int** result = (int**)malloc(size * sizeof(int*)); for(int i = 0; i<size; i++){ *(result+i)=(int*)malloc(size*sizeof(int)); for(int j=0; j<size; j++){ *(*(result+i)+j)=0; } } for(int row =0; row<size; row++){ for(int col =0; col <size; col++){ //result[row][col] =0; *(*(result+row)+col) = 0; for(int idx=0; idx<size;idx++){ *(*(result+row)+col) += *(*(a+row)+idx) * *(*(b+idx)+col); //result[row][col] += a[row][idx]*b[idx][col]; } } } return result; } void printArray(int **arr, int n){ // (2) Implement your printArray function here int ** array = arr; int size =n; for(int i = 0; i < size; i++){ //each row for(int j =0; j < size; j++){ printf("%d " , *(*(arr+i) +j)); } printf("\n"); } printf("\n"); } int main() { int n = 2; int **matA = (int**)malloc(n * sizeof(int*)); int **matB = (int**)malloc(n * sizeof(int*)); int **matC = (int**)malloc(n * sizeof(int*)); // (1) Define 2 n x n arrays (matrices). printf("Input values for n \n"); printf("A: \n"); for(int i=0; i<n; i++){ *(matA+i) = (int*)malloc(n* sizeof(int)); //**matA for(int j=0; j<n; j++){ scanf("%d",&(*(*(matA+i) +j))); } } printf("B: \n"); for(int i=0; i<n; i++){ *(matB+i) = (int*)malloc(n* sizeof(int)); //**matA for(int j=0; j<n; j++){ scanf("%d",&(*(*(matB+i) +j))); } } // (3) Call printArray to print out the 2 arrays here. printf("A: \n"); printArray(matA, n); printf("B: \n"); printArray(matB, n); //(5) Call matMult to multiply the 2 arrays here. matC = matMult(matA, matB, n); //(6) Call printArray to print out resulting array here. printf("out:\n"); printArray(matC, n); return 0; }
C
void main() { int n,a=0,b=0,c=0,d=0,i,m; double a1,b1,c1,d1; scanf("%d",&n); for(i=0;i<n;i++){ scanf("%d",&m); if(m<=18) a++; else if(m>18&&m<36) b++; else if(m>35&&m<61) c++; else d++; } a1=(double)a/n*100; b1=(double)b/n*100; c1=(double)c/n*100; d1=(double)d/n*100; printf("1-18: %.2lf%%\n",a1); printf("19-35: %.2lf%%\n",b1); printf("36-60: %.2lf%%\n",c1); printf("60??: %.2lf%%\n",d1); }
C
// Histogram Equalization #include <wb.h> #define HISTOGRAM_LENGTH 256 //@@ insert code here __global__ void floattochar(float *im, unsigned char *imc) { int i = blockDim.x*blockIdx.x + threadIdx.x; int j = blockDim.y*blockIdx.y + threadIdx.y; imc[j][i] = (unsigned char) (255 * im[j][i]); } __global__ void rgb2gray(unsigned char *im, unsigned char gray, int w) { int i = blockDim.x*blockIdx.x + threadIdx.x; int j = blockDim.y*blockIdx.y + threadIdx.y; int r = im[j][3*i] int g = im[j][3*i + 1] int b = im[j][3*i + 2] gray[(j*w)+i] = (unsigned char) (0.21*r + 0.71*g + 0.07*b) } __global__ void histogram(unsigned char *im, unsigned int *histo, int size) { int i = blockDim.x*blockIdx.x + threadIdx.x; int stride =blockDim.y * gridDim.x; while(i < size) { atomicAdd(&(histo[im[index]])),1); i+= stride; } } __global__ void scan(float * input, float * output, float *tempout, int len) { //@@ Modify the body of this function to complete the functionality of //@@ the scan on the device //@@ You may need multiple kernel calls; write your kernels before this //@@ function and call them from here __shared__ float xy[2*BLOCK_SIZE]; int i=threadIdx.x + (blockDim.x*blockIdx.x*2); if(i<len) xy[threadIdx.x] = input[i]; if(i+BLOCK_SIZE<len) xy[threadIdx.x+BLOCK_SIZE] = input[i+BLOCK_SIZE]; __syncthreads(); for(int stride=1; stride<= BLOCK_SIZE; stride*=2) { int index=(threadIdx.x +1)*stride*2 -1; if(index < 2*BLOCK_SIZE) xy[index] += xy[index-stride]; __syncthreads(); } for(int stride=BLOCK_SIZE/2; stride>0; stride/=2) { __syncthreads(); int index=(threadIdx.x +1)*stride*2 -1; if(index+stride < 2*BLOCK_SIZE) xy[index+stride] += xy[index]; __syncthreads(); } if (i < len) output[i] = xy[threadIdx.x]; if (i+ BLOCK_SIZE< len) output[i + BLOCK_SIZE] = xy[BLOCK_SIZE + threadIdx.x]; if (len/(BLOCK_SIZE*2) > 1) tempout[blockIdx.x] = xy[2 * BLOCK_SIZE - 1]; } __global__ void add(float *input, float *temp, int len) { int i=threadIdx.x + (blockDim.x*blockIdx.x*2); if (blockIdx.x) { if (i < len) input[i] += temp[blockIdx.x - 1]; if (i + BLOCK_SIZE < len) input[i + BLOCK_SIZE] += temp[blockIdx.x - 1]; } } int main(int argc, char ** argv) { wbArg_t args; int imageWidth; int imageHeight; int imageChannels; wbImage_t inputImage; wbImage_t outputImage; float * hostInputImageData; float * hostOutputImageData; const char * inputImageFile; unsigned char *deviceinputchar; unsigned char *devicegray; unsigned int *devicehisto; float * deviceInputImageData; float * deviceOutputImageData; //@@ Insert more code here args = wbArg_read(argc, argv); /* parse the input arguments */ inputImageFile = wbArg_getInputFile(args, 0); wbTime_start(Generic, "Importing data and creating memory on host"); inputImage = wbImport(inputImageFile); imageWidth = wbImage_getWidth(inputImage); imageHeight = wbImage_getHeight(inputImage); imageChannels = wbImage_getChannels(inputImage); outputImage = wbImage_new(imageWidth, imageHeight, imageChannels); wbTime_stop(Generic, "Importing data and creating memory on host"); hostInputImageData = wbImage_getData(inputImage); hostOutputImageData = wbImage_getData(outputImage); wbTime_start(GPU, "Doing GPU Computation (memory + compute)"); cudaMalloc((void **) &deviceInputImageData, imageWidth * imageHeight * imageChannels * sizeof(float)); cudaMalloc((void **) &deviceOutputImageData, imageWidth * imageHeight * imageChannels * sizeof(float)); cudaMalloc((void **) &deviceinputchar, imageWidth * imageHeight * imageChannels * sizeof(unsigned char)); cudaMalloc((void **) &devicegray, imageWidth * imageHeight * sizeof(unsigned char)); cudaMalloc((void **) &devicehisto, imageWidth * imageHeight * sizeof(unsigned char)); cudaMemcpy(deviceInputImageData, hostInputImageData, imageWidth * imageHeight * imageChannels * sizeof(float), cudaMemcpyHostToDevice); wbTime_stop(GPU, "Doing GPU memory allocation"); wbTime_start(Compute, "Doing the computation on the GPU"); //@@ INSERT CODE HERE floattochar<<<((imageHeight-1 )/16 )+1, (imageWidth * imageChannels -1)/16 +1, 1), (16,16,1)>>>(DeviceInputImage, deviceinputchar); rgb2gray<<<((imageHeight-1) /16 )+1, (imageWidth -1)/16 +1, 1), (16,16,1)>>>(deviceinputchar, devicegray, imageWidth); histogram<<<((imageWidth*imageHeight-1) /HISTOGRAM_LENGTH )+1, 1, 1), (HISTOGRAM_LENGTH,1,1)>>>(devicegray, devicehisto, (imageWidth*imageHeight) ); wbTime_stop(Compute, "Doing the computation on the GPU"); wbTime_start(Copy, "Copying data from the GPU"); cudaMemcpy(hostOutputImageData, deviceOutputImageData, imageWidth * imageHeight * imageChannels * sizeof(float), cudaMemcpyDeviceToHost); wbTime_stop(Copy, "Copying data from the GPU"); wbTime_stop(GPU, "Doing GPU Computation (memory + compute)"); wbSolution(args, outputImage); cudaFree(deviceInputImageData); cudaFree(deviceOutputImageData); wbImage_delete(outputImage); wbImage_delete(inputImage); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include "lz-dict.h" #include "debug.h" #include "compress.h" #include "hash.h" #include "parse.h" int compress(const char *inBuf,int inBufLen,unsigned char *outBuf,int outBufLen,int *pNumParsed) { char tempBuf[256]; char tempOutBuf[256]; int Len=inBufLen; int maxOutLen=outBufLen; int numParsed=0; int hitCount=0; int totalParsed=0; const char *curInPtr=inBuf; char *curOutPtr=outBuf; int bucketId=-1; int numIterations=0; int numBytesEncoded=0; int totalEncoded=0; while(totalParsed<Len && totalEncoded<maxOutLen) { if(numIterations >400) { break; } else { numIterations++; } while(parse_is_delimiter(*curInPtr) ) { numBytesEncoded=encode_ws(curOutPtr,maxOutLen-totalEncoded,curInPtr); /*TODO: if numBytesEncoded is <= 0 what happens?*/ totalEncoded+=numBytesEncoded; curOutPtr+=numBytesEncoded; curInPtr++; totalParsed++; if(totalParsed>=Len || totalEncoded>=maxOutLen) { break; } } bucketId=lzDictLookup(curInPtr,Len-totalParsed,&numParsed,&hitCount); if(bucketId<0) { if(COMPRESS_DEBUG_ENABLED) { printf("[COMPR1]:dictionary return: %d\n",bucketId); } *pNumParsed=totalParsed; return totalEncoded; } else { if(COMPRESS_DEBUG_ENABLED) { strncpy(tempBuf,curInPtr,numParsed); tempBuf[numParsed]='\0'; printf("[COMPR2]:bucket id:0x%x,num parsed:%d,hit count:%d,token:%s\n", bucketId,numParsed,hitCount,tempBuf); } numBytesEncoded=encode(curOutPtr,maxOutLen-totalEncoded,curInPtr,numParsed,hitCount,bucketId); if(numBytesEncoded <= 0) { break; } totalParsed+=numParsed; curInPtr+=numParsed; totalEncoded+=numBytesEncoded; curOutPtr+=numBytesEncoded; while(parse_is_delimiter(*curInPtr) ) { numBytesEncoded=encode_ws(curOutPtr,maxOutLen-totalEncoded,curInPtr); /*TODO: if numBytesEncoded is <= 0 what happens?*/ totalEncoded+=numBytesEncoded; curOutPtr+=numBytesEncoded; curInPtr++; totalParsed++; if(totalParsed>=Len || totalEncoded>=maxOutLen) { break; } } } } *pNumParsed=totalParsed; return totalEncoded; }
C
// Analog accelerometer app // // Reads data from the ADXL327 analog accelerometer #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include "app_error.h" #include "nrf.h" #include "nrf_delay.h" #include "nrf_gpio.h" #include "nrf_log.h" #include "nrf_log_ctrl.h" #include "nrf_log_default_backends.h" #include "nrf_pwr_mgmt.h" #include "nrf_serial.h" #include "nrfx_gpiote.h" #include "nrfx_saadc.h" #include "buckler.h" // ADC channels #define X_CHANNEL 0 #define Y_CHANNEL 1 #define Z_CHANNEL 2 // callback for SAADC events void saadc_callback (nrfx_saadc_evt_t const * p_event) { // don't care about adc callbacks } // sample a particular analog channel in blocking mode nrf_saadc_value_t sample_value (uint8_t channel) { nrf_saadc_value_t val; ret_code_t error_code = nrfx_saadc_sample_convert(channel, &val); APP_ERROR_CHECK(error_code); return val; } int main (void) { ret_code_t error_code = NRF_SUCCESS; // initialize RTT library error_code = NRF_LOG_INIT(NULL); APP_ERROR_CHECK(error_code); NRF_LOG_DEFAULT_BACKENDS_INIT(); // initialize analog to digital converter nrfx_saadc_config_t saadc_config = NRFX_SAADC_DEFAULT_CONFIG; saadc_config.resolution = NRF_SAADC_RESOLUTION_12BIT; error_code = nrfx_saadc_init(&saadc_config, saadc_callback); APP_ERROR_CHECK(error_code); // initialize analog inputs // configure with 0 as input pin for now nrf_saadc_channel_config_t channel_config = NRFX_SAADC_DEFAULT_CHANNEL_CONFIG_SE(0); channel_config.gain = NRF_SAADC_GAIN1_6; // input gain of 1/6 Volts/Volt, multiply incoming signal by (1/6) channel_config.reference = NRF_SAADC_REFERENCE_INTERNAL; // 0.6 Volt reference, input after gain can be 0 to 0.6 Volts // specify input pin and initialize that ADC channel channel_config.pin_p = BUCKLER_ANALOG_ACCEL_X; error_code = nrfx_saadc_channel_init(X_CHANNEL, &channel_config); APP_ERROR_CHECK(error_code); // specify input pin and initialize that ADC channel channel_config.pin_p = BUCKLER_ANALOG_ACCEL_Y; error_code = nrfx_saadc_channel_init(Y_CHANNEL, &channel_config); APP_ERROR_CHECK(error_code); // specify input pin and initialize that ADC channel channel_config.pin_p = BUCKLER_ANALOG_ACCEL_Z; error_code = nrfx_saadc_channel_init(Z_CHANNEL, &channel_config); APP_ERROR_CHECK(error_code); // initialization complete printf("Buckler initialized!\n"); // loop forever while (1) { // sample analog inputs nrf_saadc_value_t x_val = sample_value(X_CHANNEL); nrf_saadc_value_t y_val = sample_value(Y_CHANNEL); nrf_saadc_value_t z_val = sample_value(Z_CHANNEL); // display results printf("x: %d\ty: %d\tz:%d\n", x_val, y_val, z_val); nrf_delay_ms(250); } }
C
// Copyright: Ramiro Polla // License: WTFPL // text to image converter #include <inttypes.h> #include <limits.h> #include <float.h> #include "algo_txt2img.h" #include "font.c" void txt2img_convert(uint8_t *out_data, const char *in_data, size_t in_w, size_t in_h) { size_t out_stride = in_w * TXT2IMG_CHAR_W; for ( size_t y = 0; y < in_h; y++ ) { for ( size_t x = 0; x < in_w; x++ ) { char c = in_data[y * (in_w+1) + x]; for ( size_t i = 0; i < TXT2IMG_CHAR_H; i++ ) { for ( size_t j = 0; j < TXT2IMG_CHAR_W; j++ ) { uint8_t *inpt = &font[(size_t) c][i][j]; size_t idx_y = y * TXT2IMG_CHAR_H + i; size_t idx_x = x * TXT2IMG_CHAR_W + j; uint8_t *outp = &out_data[idx_y * out_stride + idx_x]; *outp = *inpt; } } } } }
C
#include <stdio.h> main() { int contador, n, altura=0, distancia=0, direcao=0; char comando; scanf("%i", &n); for(contador=1; contador<=n; contador++) { if(comando == 'V') { //Se direcao = 0, O balão está indo para frente. //Se direcao = 1, O balão está voltando. if(direcao=0) { direcao = 1; } else if(direcao=1) { direcao = 0; } } scanf("%s", &comando); if(comando!='S' && altura>0) { if(comando == 'D') { altura-=10; } else if(comando == 'F') { if(direcao = 0) { distancia+=10; } else if(direcao = 1) { distancia-=10; } } else if(comando == 'V') { if(direcao = 0) { distancia+=10; } else if(direcao = 1) { distancia-=10; } } if(altura>200) { altura = 200; } else if(altura<0) { altura = 0; } if(distancia>2000) { distancia = 2000; } else if(distancia<0) { distancia = 0; } } if(comando == 'S') { altura+=10; } } printf("%i %i\n", altura, distancia); }
C
#include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #define BUFFER_SIZE 40 int map[50][50] = {0}; void valid (int turn, int cx, int cy, int *nx, int *ny) { int dir[4][2] = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}}; int x, y; *nx = *ny = -1; for (int d = 0; d < 4; d++) { x = cx + dir[d][0]; y = cy + dir[d][1]; if (0 <= x && x < 50 && 0 <= y && y < 50 && map[x][y] == 0) { *nx = x; *ny = y; map[x][y] = turn+1; break; } } } int run (int *turn, int lx, int ly, int *x, int *y) { valid(*turn, lx, ly, x, y); if (*x == -1 && *y == -1) { *turn = *turn ? 3 : 2; } else { *turn = 1 - *turn; printf("%d %d\n", *x, *y); } } int main (int argc, char* argv[]) { const char path[20] = "named_pipe"; char str[BUFFER_SIZE] = ""; int fd; int game_over = 0; int turn = 0; char output[20]; int x, y; int lx, ly; srand(time(NULL)); x = rand() % 50; y = rand() % 50; map[x][y] = 2; pid_t cpid; if ( mkfifo(path, 0666) < 0 ) { perror("mkfifo failed."); return -1; } cpid = fork(); if ( cpid < 0 ) { perror("Fork failed."); return -1; } else if ( cpid == 0 ) { // child first sprintf(output, "%d_FIFO.txt", getpid()); freopen(output, "w", stdout); puts("1"); } else { fd = open(path, O_WRONLY); sprintf(str, "%d %d %d", turn, x, y); write(fd, str, sizeof(char)*(strlen(str)+1)); close(fd); sprintf(output, "%d_FIFO.txt", getpid()); freopen(output, "w", stdout); puts("0"); } // game loop while (turn < 2) { fd = open(path, O_RDONLY); read(fd, str, sizeof(char)*BUFFER_SIZE); sscanf(str, "%d%d%d", &turn, &lx, &ly); close(fd); x = lx; y = ly; if (cpid == 0) { if (turn == 0) { // child's turn map[lx][ly] = 2; run(&turn, lx, ly, &x, &y); fd = open(path, O_WRONLY); sprintf(str, "%d %d %d", turn, x, y); write(fd, str, sizeof(char)*(strlen(str)+1)); close(fd); if (turn >= 2) { break; } } } else { if (turn == 1) { // parent's turn map[lx][ly] = 1; run(&turn, lx, ly, &x, &y); fd = open(path, O_WRONLY); sprintf(str, "%d %d %d", turn, x, y); write(fd, str, sizeof(char)*(strlen(str)+1)); close(fd); if (turn >= 2) { break; } } } } if (cpid == 0) { printf("%c\n", turn == 2 ? '0' : '1'); } else { printf("%c\n", turn == 3 ? '0' : '1'); } if (turn >= 2 && cpid != 0) { remove(path); } return 0; }
C
/* ** EPITECH PROJECT, 2017 ** struct.h ** File description: ** struct declaration file */ #ifndef TOOLS_H_ #define TOOLS_H_ #include "main.h" typedef struct spec_s { char spec_pf; int (*spec_p)(va_list ap, int ct, char *str, char *str_temp); } spec_t; typedef struct length_s { char *sep_pf; int (*sep_p)(va_list ap, int ct, char *str, char *str_temp); } length_t; typedef struct flag_s { char flag_pf; int (*flag_p)(char *str, int ctp, long long temp, char *str_temp); } flag_t; typedef struct flag_char_s { char flag_c_pf; int (*flag_c_p)(char *str, int ctp, char *temp, char *str_temp); } flag_char_t; char *int_to_char(int nb); void free_tab(char **tab); void my_putchar(char c); int my_put_nbr(int nb); int my_putstr(char *str, int len); char *my_revstr(char *str); char *my_strcat(char *dest, char *src, int b); int my_strcmp(char *s1, char *s2); char *my_strdup(char *src); int my_strlen(char *str); char *my_strncat(char *dest, char *src, int n); int my_putstr_err(char *str, char *msg); void my_putchar_err(char c); int my_strncmp(char *s1, char *s2, int n); char *my_strcpy(char *dest, char const *src); char *my_strncpy(char *dest, char *src, int n); void my_swap(int *a, int *b); char *swap_output(char *base, int nb); long long my_put_long_long(long long nb); void my_put_unsg_ll(unsigned long long nb); int my_long_long_len(long long nb); int flag_x(va_list ap, int ct, char *str, char *str_temp); int flag_xx(va_list ap, int ct, char *str, char *str_temp); int flag_o(va_list ap, int ct, char *str, char *str_temp); int flag_long(va_list ap, int ct, char *str, char *str_temp); int flag_h_nbr(va_list ap, int ct, char *str, char *str_temp); int flag_long_long(va_list ap, int ct, char *str, char *str_temp); int flag_unsg_short(va_list ap, int ct, char *str, char *str_temp); int flag_unsg_l(va_list ap, int ct, char *str, char *str_temp); int flag_unsg_ll(va_list ap, int ct, char *str, char *str_temp); int flag_p(va_list ap, int ct, char *str, char *str_temp); int flag_s(va_list ap, int ct, char *str, char *str_temp); int flag_c(va_list ap, int ct, char *str, char *str_temp); int flag_b(va_list ap, int ct, char *str, char *str_temp); int flag_ll_x(va_list ap, int ct, char *str, char *str_temp); int flag_ll_xx(va_list ap, int ct, char *str, char *str_temp); int flag_ll_o(va_list ap, int ct, char *str, char *str_temp); int flag_ll_b(va_list ap, int ct, char *str, char *str_temp); int flag_plus(char *str_temp, long long rst, int b, int nbr); int flag_plus_bis(char *str_temp, long long rst, int b); int nbr_disp(int temp_len, char *str_temp, int nbr, int b); int nbr_disp_bis(int temp_len, char *str_temp, int nbr_f, int b); int nbr_disp_bis(int temp_len, char *str_temp, int nbr_f, int b); int nbr_disp_thd(long long rst); void base(unsigned long long nbr, char *str); void separator_flag(char *str, va_list ap, int ct, char *str_temp); void flag_one(char *str, va_list ap, int ct, char *str_temp); int choise_flag(char *str, int ct, int b); char *copy_flag(char *str, char *temp, int ct); char *copy_str(char *str, char *str_temp, int ct); void my_printf(char *str, ...); int len_flag(char *str, int ct); void flag_sign(long long rst); int flag_flag(char *str, int ct); int choise_flag_flag(char *str, int ctp, long long temp, char *str_temp); int choise_flg_flg_c(char *str, int ctp, char* temp, char *str_temp); void flag_nbr_disp(int nbr, int len_f); int flag_nbr(char *str, char *str_temp, int ctp, int temp); void flag_zero_disp(int nbr, int len_f); int flag_long_long_d(va_list ap, int ct, char *str, char *str_temp); int flag_hh_x(va_list ap, int ct, char *str, char *str_temp); int flag_hh_xx(va_list ap, int ct, char *str, char *str_temp); int flag_hh_o(va_list ap, int ct, char *str, char *str_temp); int flag_hh_b(va_list ap, int ct, char *str, char *str_temp); int flag_hh_u(va_list ap, int ct, char *str, char *str_temp); int flag_ss(va_list ap, int ct, char *str, char *str_temp); int flag_hh_d(va_list ap, int ct, char *str, char *str_temp); void flag_has_o(char *str_temp); void flag_has_x(char *str_temp); void flag_has_xx(char *str_temp); char *my_calloc(int nbchars); char **word_array(char *line); char *malloc_str(int ct, int b, int ctb, char **str); #endif
C
#include <stdio.h> int main(int argc, char *argv[]){ printf("El programa que estas ejecutando es: %s\n",argv[0]); char *datos; FILE *fp; if(argc==2){ datos=argv[1]; printf("El nombre del archivo a abrir es: %s\n",datos); fp=fopen(datos,"W+");//aqui se pondra todo lo que se quiere hacer... fclose(fp); } else if(argc>2){ printf("Mas argumentos de los necesarios\n"); } else{ printf("Se requiere de al menos 1 argumento\n"); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <sys/time.h> #include <time.h> #define X 640 #define Y 480 #define YMIN 0 #define YMAX 1 // #define XMAX 1.166 // #define XMIN -0.166 #define XMAX 1.166 #define XMIN -0.166 #define EPSILON 0.00000000001 #define AMBIENT .2 #define REFLECT .4 #define BGR 150 #define BGG 150 #define BGB 255 #define CBR1 255 #define CBB1 0 #define CBG1 150 #define CBR2 150 #define CBB2 255 #define CBG2 0 #define REF_DEPTH_LIMIT 100 typedef struct { double x; double y; double z; } triple; typedef struct { int r; int g; int b; } color; typedef struct { color* c; double x; double y; double z; double radius; } sphere; int num_shapes; int offset; double quad[3]; sphere** s; double xsize = XMAX - XMIN; double ysize = YMAX - YMIN; // triple e = { 0.50 , 0.50 , .10 } ; // the eye triple e = { 0.50 , 0.50 , -1.00 } ; // the eye double zcam; triple l = { 0.00 , 1.25 , -.50 } ; // the light double lmag; triple lunit; double square(double d) { return d*d; } double calcDisc() { return square(quad[1]) - 4*quad[0]*quad[2]; } double calcT() { return (-1 * quad[1] - sqrt(square(quad[1]) - 4 * quad[0]*quad[2])) / (2 * quad[0]); } double mag(triple v) { return sqrt(square(v.x) + square(v.y) + square(v.z)); } void normalize(triple trip) { double magn = mag(trip); trip.x /= magn; trip.y /= magn; trip.z /= magn; } triple normal(triple pos, double cx, double cy, double cz, double r) { triple ret = {(pos.x-cx)/r,(pos.y-cy)/r,(pos.z-cz)/r}; // triple ret = {(cx-pos.x)/r,(cy-pos.y)/r,(cz-pos.z)/r}; /* double magn = mag(ret); ret.x /= magn; ret.y /= magn; ret.z /= magn; */ return ret; } triple getUV(triple dir, triple t) { triple subt = {dir.x-t.x,dir.y-t.y,dir.z-t.z}; double magn = mag(subt); subt.x /= magn; subt.y /= magn; subt.z /= magn; // normalize(subt); return subt; } triple add(triple pos1, triple pos2) { triple ret = {pos1.x + pos2.x, pos1.y + pos2.y, pos1.z + pos2.z}; return ret; } triple addscaled(triple pos1, triple pos2, double scalar) { triple ret = {pos1.x + pos2.x*scalar, pos1.y + pos2.y*scalar, pos1.z + pos2.z*scalar}; return ret; } triple sub(triple pos1, triple pos2) { triple ret = {pos1.x - pos2.x, pos1.y - pos2.y, pos1.z-pos2.z}; return ret; } double dotp(triple one, triple two) { return one.x * two.x + one.y * two.y + one.z * two.z; } color getShadow(color* c, triple vec, int shape, double pmag, triple evec) { // triple posne = {vec.x*pmag,vec.y*pmag,vec.z*pmag}; triple pos = {evec.x + vec.x*pmag, evec.y + vec.y*pmag, evec.z + vec.z*pmag}; double ocx = s[shape]->x; double ocy = s[shape]->y; double ocz = s[shape]->z; // pos = addscaled(pos,norm,EPSILON); // Calculate vector to light // triple vtl = sub(pos,l); triple vtl = sub(l,pos); // printf("%f %f %f : %f %f %f\n",pos.x,pos.y,pos.z,vtl.x,vtl.y,vtl.z); double magn = mag(vtl); double rx = vtl.x/magn; double ry = vtl.y/magn; double rz = vtl.z/magn; triple vtln = {rx,ry,rz}; register int i; double min_t = 1.0/0.0; int min_shape = -1; for(i=0;i<num_shapes+offset;i++) { if(i == shape) continue; double cx = s[i]->x; double cy = s[i]->y; double cz = s[i]->z; quad[0] = 1.0; // rx*rx + ry*ry + rz*rz; // quad[1] = 2*(pos.x*rx + pos.y*ry + pos.z*rz - (rx*cx + ry*cy + rz*cz)); // quad[2] = square(rx-cx) + square(ry-cy) + square(rz-cz) - square(shapes[i]->radius); // quad[1] = 2*(e.x*rx + e.y*ry + e.z*rz - (rx*cx + ry*cy + rz*cz)); // quad[2] = square(e.x-cx) + square(e.y-cy) + square(e.z-cz) - square(shapes[i]->radius); quad[1] = 2*(pos.x*rx + pos.y*ry + pos.z*rz - (rx*cx + ry*cy + rz*cz)); quad[2] = square(pos.x-cx) + square(pos.y-cy) + square(pos.z-cz) - square(s[i]->radius); // quad[1] = 2*(l.x*rx + l.y*ry + l.z*rz - (rx*cx + ry*cy + rz*cz)); // quad[2] = square(l.x-cx) + square(l.y-cy) + square(l.z-cz) - square(shapes[i]->radius); if(calcDisc() < 0.0) continue; double t = calcT(); if(t<EPSILON) continue; if(t < min_t) { min_t = t; min_shape = i; } } if(min_shape > -1) { int r = c->r*AMBIENT; int g = c->g*AMBIENT; int b = c->b*AMBIENT; return (color){r,g,b}; } triple norm = normal(pos, ocx, ocy, ocz, s[shape]->radius); double dp = dotp(norm, vtln); // if(shape == 3) printf("%f %f %f : %f %f %f : %f\n",norm.x,norm.y,norm.z,pos.x,pos.y,pos.z,dp); if(dp < 0) dp = 0; // dp = .5; return (color){(int)((AMBIENT + (1- AMBIENT)*dp) * c->r),(int)((AMBIENT + (1-AMBIENT)*dp) * c->g),(int)((AMBIENT + (1-AMBIENT)*dp) * c->b)}; } void getColor(color* loc, triple trip, triple dir, int depth) { loc->r = BGR*AMBIENT; loc->g = BGG*AMBIENT; loc->b = BGB*AMBIENT; double cx; double cy; double cz; register int i; double t; /* double tx; double ty; double mag; tx = (x-X/2)*xscale; ty = (y-Y/2)*yscale; rx = tx / mag; ry = ty / mag; rz = Z / mag; */ double min_t = 1.0/0.0; int min_shape = -1; double rx = dir.x; double ry = dir.y; double rz = dir.z; for(i=0;i<num_shapes+offset;i++) { cx = s[i]->x; cy = s[i]->y; cz = s[i]->z; quad[0] = 1.0; // rx*rx + ry*ry + rz*rz; quad[1] = 2*(trip.x*rx + trip.y*ry + trip.z*rz - (rx*cx + ry*cy + rz*cz)); quad[2] = square(trip.x-cx) + square(trip.y-cy) + square(trip.z-cz) - square(s[i]->radius); // quad[1] = -2*cx*rx + 2*e.x*rx - 2*cy*ry + 2*e.y*ry - 2*cz*rz + 2*e.z*rz; // quad[2] = cx*cx + cy*cy + cz*cz - 2*cx*e.x + e.x*e.x - 2*cy*e.y + e.y*e.y -2*cz*e.z + square(e.z) - square(shapes[i]->radius); if(calcDisc() < 0.0) continue; t = calcT(); if(t < 0) continue; // if(y > .48 && y < .49) printf("%f %f %f : %f %f : %d :::: %f\n",quad[0],quad[1],quad[2],x,y,i,t); if(t < min_t) { // if(y > .48 && y < .49) printf("!! %f %f %f : %f %f : %d :::: %f\n",quad[0],quad[1],quad[2],x,y,i,t); min_t = t; min_shape = i; // printf("\tShaped\n"); // printf("\t%d %f %f %f %f %f\n",min_shape,x,y,quad[0],quad[1],quad[2]); } } sphere* mins = s[min_shape]; if(min_shape > -1) { int freec = 0; color* c; triple nv = {dir.x*min_t, dir.y*min_t, dir.z*min_t}; triple rvp = {nv.x + trip.x, nv.y + trip.y, nv.z + trip.z}; if(min_shape) c = mins->c; else { c = (color*)malloc(sizeof(color)); freec = 1; int nx = rvp.x < 0 ? (int)(rvp.x*10) : (int)(rvp.x*10)+1; int nz = rvp.z < 0 ? (int)(rvp.z*10) : (int)(rvp.z*10)+1; int booly = nx + nz; if(booly % 2) { c->r = CBR1; c->b = CBB1; c->g = CBG1; } else { c->r = CBR2; c->b = CBB2; c->g = CBG2; } } color s; if(depth < REF_DEPTH_LIMIT) { color* r = (color*)malloc(sizeof(color)); triple norm = normal(rvp, mins->x, mins->y, mins->z, mins->radius); double dp = dotp(dir,norm); triple n2 = (triple){2*dp*norm.x, 2*dp*norm.y, 2*dp*norm.z}; triple nvd = sub(dir,n2); //rvp double nmag = mag(nvd); nvd = (triple){nvd.x/nmag,nvd.y/nmag,nvd.z/nmag}; getColor(r,rvp,nvd,depth+1); s = getShadow(c,dir,min_shape,min_t,trip); s.r = s.r*(1-REFLECT) + r->r*(REFLECT); s.g = s.g*(1-REFLECT) + r->g*(REFLECT); s.b = s.b*(1-REFLECT) + r->b*(REFLECT); free(r); } else { s = getShadow(c,dir,min_shape,min_t,trip); } loc->r = s.r; loc->g = s.g; loc->b = s.b; if(freec) free(c); } } void init(sphere** s) { s[0] = (sphere*)malloc(sizeof(sphere)); s[1] = (sphere*)malloc(sizeof(sphere)); s[2] = (sphere*)malloc(sizeof(sphere)); s[3] = (sphere*)malloc(sizeof(sphere)); s[0]->c = (color*)malloc(sizeof(color)); // Floor s[0]->c->r = 205; s[0]->c->g = 133; s[0]->c->b = 63; s[0]->radius = 20000.25; s[0]->x = 0.5; s[0]->y = -20000.0; s[0]->z = 0.5; s[1]->c = (color*)malloc(sizeof(color)); // Blue s[1]->c->r = 0; s[1]->c->g = 0; s[1]->c->b = 255; s[1]->radius = .25; s[1]->x = 1.0; s[1]->y = 0.5; s[1]->z = 0.5; s[2]->c = (color*)malloc(sizeof(color)); // Green s[2]->c->r = 0; s[2]->c->g = 255; s[2]->c->b = 0; s[2]->radius = .25; s[2]->x = 0.65; s[2]->y = 0.50; s[2]->z = 2.00; s[3]->c = (color*)malloc(sizeof(color)); // Red s[3]->c->r = 255; s[3]->c->g = 0; s[3]->c->b = 0; s[3]->radius = .50; s[3]->x = 0.00; s[3]->y = 0.75; s[3]->z = 1.25; } double gettime() { struct timeval tv; gettimeofday(&tv,NULL); return tv.tv_sec + tv.tv_usec*1000000.0; } int saveppm(const char* filename) { // shapes = (sphere**)malloc(sizeof(sphere*) * num_shapes); // init(shapes); color* rgb[Y][X]; // red-green-blue for each pixel int y , x , iy; double xs; double ys; FILE* fout ; register int iter = 0; int total = Y*X; /* double it = gettime(); double dt = 1/30.0; // 30 FPS double ct; */ for( y = 0 ; y < Y ; y++ ) { for( x = 0 ; x < X ; x++) { iy = Y-y-1; rgb[iy][x] = (color*)malloc(sizeof(color)); xs = XMIN + (double)x/X*xsize; ys = YMIN + (double)y/Y*ysize; // printf("%d %d : %f %f\n",x,y,xs,ys); triple dir = {xs,ys,zcam}; triple uv = getUV(dir,e); getColor(rgb[iy][x],e,uv,0); printf("Progress: %f%c \r",100.0*(++iter)/total,'%'); fflush(stdout); } } fout = fopen( filename , "w" ) ; fprintf( fout , "P3\n" ) ; fprintf( fout , "%d %d\n" , X , Y ) ; fprintf( fout , "255\n" ) ; for( y = 0 ; y < Y ; y++ ) { for( x = 0 ; x < X ; x++) { fprintf( fout , "%d %d %d\n" , rgb[y][x]->r , rgb[y][x]->g , rgb[y][x]->b ) ; } } printf("Progress: Done \n"); fclose( fout ) ; return 0 ; } int main(int argc, char* argv[]) { lmag = mag(l); lunit = (triple){l.x/lmag,l.y/lmag,l.z/lmag}; zcam = e.z + 1.0; //z location of the "image" layer num_shapes = 0; const char* filename = "SAVE.ppm"; FILE* fin = NULL; register int j,k; offset = 4; // num_shapes = 6000; // fin=fopen("wire.txt","r"); // num_shapes = 12350; // fin=fopen("tree.txt","r"); s = (sphere**)malloc(sizeof(sphere*) * (num_shapes+offset)); init(s); double x,y,z,r; int totalbytes = (num_shapes+offset) * (sizeof(sphere*) + sizeof(color) + sizeof(sphere)) + Y*X*sizeof(color); register int res; printf("Allocating and populating %d bytes (%f MB)... ",totalbytes,totalbytes/1024.0/1024.0); fflush(stdout); for(j=0;j<num_shapes;j++) { k = j + offset; res = fscanf(fin,"%lf %lf %lf %lf",&x,&y,&z,&r); if(!res) { fprintf(stderr,"Error reading coordinatesn\n"); } s[k] = (sphere*)malloc(sizeof(sphere)); s[k]->c=(color*)malloc(sizeof(color)); s[k]->c->r = 255; s[k]->c->g = 0; s[k]->c->b = 255; s[k]->radius = r; s[k]->x=x; s[k]->y=y - .1; s[k]->z=z; } printf("Done\n"); if(fin != NULL) fclose(fin); int st = time(NULL); printf("Rendering...\n"); fflush(stdout); saveppm(filename); printf("Rendered in %d seconds\n",(int)(time(NULL)-st)); char cmd[100]; sprintf(cmd,"display %s",filename); res = system(cmd); if(res) { fprintf(stderr,"Error displaying image\n"); } return 0; }
C
// An intro to functions #include <stdio.h> int get_larger(int first_num, int second_num); int main(void) { //int num; //int scanf_return = scanf("%d", &num); int num1 = 7; int num2 = 2; int bigger_num = get_larger(num1, num2); printf("%d\n", bigger_num); return 0; } int get_larger(int first_num, int second_num) { int larger = first_num; if (second_num > first_num) { larger = second_num; } return larger; }
C
#include <stdio.h> void do_loop(void) { static int loop = 0; printf("-- %d --\n",loop); switch(loop) { case 7: loop = 0; break; default: loop++; break; } } int main(void) { while(1) { do_loop(); sleep(1); } }
C
#include<stdio.h> void main() { int n,k; scanf("%d%d",&n,&k); if((n+k)%2==0) printf("Even"); else printf("Odd"); }
C
#include <stdio.h> #include <stdlib.h> #define tSize 100 // Tree Size typedef struct _node { char data; struct _node *left; struct _node *right; } node; int front = 0, rear = 0; // Init with 0 - Queue Initializing node *nBuf[2]; // nBuf[0] for Head_Node, nBuf[1] for End_Node node *nTree[3]; // nTree[0] for parent, nTree[1] for Left_Child, nTree[2] for Right_Child node *Queue[tSize]; void InitNode(void) { for (char i = 0; i < 2; ++i) nBuf[i] = (node *)malloc(sizeof(node)); for (char i = 0; i < 2; ++i) { nBuf[i]->left = nBuf[1]; // head_node->left = end_node, end_node->left = end_node nBuf[i]->right = nBuf[1]; // head_node->right = end_node, end_node->right = end_node } } void InitTree(void) { /* Now Path : parent */ for (char i = 0; i < 3; ++i) { nTree[i] = (node *)malloc(sizeof(node)); nTree[i]->data = 'A' + i; // parent : A, left_child : B, right_child : C } nTree[0]->left = nTree[1]; // parent->left = left_child nTree[0]->right = nTree[2]; // parent->right = right_child nBuf[0]->left = nTree[0]; // head->left = parent nBuf[0]->right = nTree[0]; // head->right = parent /* Now Path : parent->left_child */ nTree[0] = nTree[0]->left; for (char i = 1; i < 3; ++i) { nTree[i] = (node *)malloc(sizeof(node)); nTree[i]->data = 'C' + i; // parent->left_child->left->date = D, parent-left_child->rigth->date = E nTree[i]->left = nBuf[1]; // parent->left_child->left(right)->left = end_node nTree[i]->right = nBuf[1]; // parent->left_child->left(right)->right = end_node } nTree[0]->left = nTree[1]; // parent->left_child->left = left_child' nTree[0]->right = nTree[2]; // parent->rigth_child->right = right_child' /* Now Path : parent->right_child */ nTree[0] = nBuf[0]->right->right; for (char i = 1; i < 3; ++i) { nTree[i] = (node *)malloc(sizeof(node)); nTree[i]->data = 'E' + i; // parent->right_child->left->date = F, parent-right_child->rigth->date = G nTree[i]->left = nBuf[1]; // parent->right_child->left(right)->left = end_node nTree[i]->right = nBuf[1]; // parent->right_child->left(right)->right = end_node } nTree[0]->left = nTree[1]; nTree[0]->right = nTree[2]; } int IsQueueEmpty(void) { if (front == rear) return 1; else return 0; } void Put(node *ptr) { Queue[rear] = ptr; rear = (rear++) % tSize; } node *Get(void) { if (!IsQueueEmpty()) return Queue[front++ % tSize]; else printf("Queue is Empty!\n"); return NULL; } void Display(node *ptr) { printf("%2c -> ", ptr->data); } void Queue_Traverse(node *ptr) { Put(ptr); while (!IsQueueEmpty()) { ptr = Get(); Display(ptr); if (ptr->left != nBuf[1]) Put(ptr->left); if (ptr->right != nBuf[1]) Put(ptr->right); } } int main(int argc, char *argv[]) { InitNode(); InitTree(); printf("- Level-Order Tree Traversal\n"); Queue_Traverse(nBuf[0]->left); // head_node->left => parent }
C
/* serPASE_ver01 Interface: Linear-Algebraic (IJ) Compile with: make serPASE_ver01 Sample run: serPASE_ver01 -blockSize 20 -n 100 -maxLevels 6 Description: This example solves the 2-D Laplacian eigenvalue problem with zero boundary conditions on an nxn grid. The number of unknowns is N=n^2. The standard 5-point stencil is used, and we solve for the interior nodes only. We use the same matrix as in Examples 3 and 5. The eigensolver is PASE (Parallels Auxiliary Space Eigen-solver) with LOBPCG and AMG preconditioner. Created: 2017.08.26 Author: Li Yu ([email protected]). */ #include <math.h> #include "_hypre_utilities.h" #include "krylov.h" #include "HYPRE.h" #include "HYPRE_parcsr_ls.h" /* lobpcg stuff */ #include "HYPRE_lobpcg.h" #include "interpreter.h" #include "HYPRE_MatvecFunctions.h" #include "temp_multivector.h" #include "_hypre_parcsr_mv.h" #include "_hypre_parcsr_ls.h" static int cmp( const void *a , const void *b ) { return *(double *)a > *(double *)b ? 1 : -1; } int main (int argc, char *argv[]) { int i, k; int myid, num_procs; int N, n; int blockSize, maxLevels; int ilower, iupper; int local_size, extra; double h, h2; int level, num_levels; // int time_index; int global_time_index; /* -------------------------矩阵向量声明---------------------- */ /* 最细矩阵 */ HYPRE_IJMatrix A; HYPRE_ParCSRMatrix parcsr_A; HYPRE_IJMatrix B; HYPRE_ParCSRMatrix parcsr_B; HYPRE_IJVector b; HYPRE_ParVector par_b; HYPRE_IJVector x; HYPRE_ParVector par_x; /* 线性方程组求解 */ HYPRE_ParVector* pvx; /* 最粗矩阵A_Hh */ HYPRE_IJMatrix A_Hh; HYPRE_ParCSRMatrix parcsr_A_Hh; HYPRE_IJMatrix B_Hh; HYPRE_ParCSRMatrix parcsr_B_Hh; HYPRE_IJVector x_Hh; HYPRE_ParVector par_b_Hh; HYPRE_IJVector b_Hh; HYPRE_ParVector par_x_Hh; /* 特征值求解 */ HYPRE_ParVector* pvx_Hh; /* 插值到细空间 */ HYPRE_ParVector* pvx_h; /* -------------------------求解器声明---------------------- */ HYPRE_Solver amg_solver, precond, lobpcg_solver, pcg_solver; /* Initialize MPI */ MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &myid); MPI_Comm_size(MPI_COMM_WORLD, &num_procs); printf("=============================================================\n" ); printf("PASE (Parallels Auxiliary Space Eigen-solver), serial version\n"); printf("Please contact [email protected], if there is any bugs.\n"); printf("=============================================================\n" ); global_time_index = hypre_InitializeTiming("PASE Solve"); hypre_BeginTiming(global_time_index); /* Default problem parameters */ n = 33; blockSize = 3; maxLevels = 5; /* Parse command line */ { int arg_index = 0; int print_usage = 0; while (arg_index < argc) { if ( strcmp(argv[arg_index], "-n") == 0 ) { arg_index++; n = atoi(argv[arg_index++]); } else if ( strcmp(argv[arg_index], "-blockSize") == 0 ) { arg_index++; blockSize = atoi(argv[arg_index++]); } else if ( strcmp(argv[arg_index], "-maxLevels") == 0 ) { arg_index++; maxLevels = atoi(argv[arg_index++]); } else if ( strcmp(argv[arg_index], "-help") == 0 ) { print_usage = 1; break; } else { arg_index++; } } if ((print_usage) && (myid == 0)) { printf("\n"); printf("Usage: %s [<options>]\n", argv[0]); printf("\n"); printf(" -n <n> : problem size in each direction (default: 33)\n"); printf(" -blockSize <n> : eigenproblem block size (default: 3)\n"); printf(" -maxLevels <n> : max levels of AMG (default: 5)\n"); printf("\n"); } if (print_usage) { MPI_Finalize(); return (0); } } /* Preliminaries: want at least one processor per row */ if (n*n < num_procs) n = sqrt(num_procs) + 1; N = n*n; /* global number of rows */ h = 1.0/(n+1); /* mesh size*/ h2 = h*h; /* Each processor knows only of its own rows - the range is denoted by ilower and iupper. Here we partition the rows. We account for the fact that N may not divide evenly by the number of processors. */ local_size = N/num_procs; extra = N - local_size*num_procs; ilower = local_size*myid; ilower += hypre_min(myid, extra); iupper = local_size*(myid+1); iupper += hypre_min(myid+1, extra); iupper = iupper - 1; /* How many rows do I have? */ local_size = iupper - ilower + 1; /* -------------------最细矩阵赋值------------------------ */ /* Create the matrix. Note that this is a square matrix, so we indicate the row partition size twice (since number of rows = number of cols) */ HYPRE_IJMatrixCreate(MPI_COMM_WORLD, ilower, iupper, ilower, iupper, &A); HYPRE_IJMatrixCreate(MPI_COMM_WORLD, ilower, iupper, ilower, iupper, &B); /* Choose a parallel csr format storage (see the User's Manual) */ HYPRE_IJMatrixSetObjectType(A, HYPRE_PARCSR); HYPRE_IJMatrixSetObjectType(B, HYPRE_PARCSR); /* Initialize before setting coefficients */ HYPRE_IJMatrixInitialize(A); HYPRE_IJMatrixInitialize(B); /* Now go through my local rows and set the matrix entries. Each row has at most 5 entries. For example, if n=3: A = [M -I 0; -I M -I; 0 -I M] M = [4 -1 0; -1 4 -1; 0 -1 4] Note that here we are setting one row at a time, though one could set all the rows together (see the User's Manual). */ { int nnz; double values[5]; int cols[5]; for (i = ilower; i <= iupper; i++) { nnz = 0; /* The left identity block:position i-n */ if ((i-n)>=0) { cols[nnz] = i-n; values[nnz] = -1.0; nnz++; } /* The left -1: position i-1 */ if (i%n) { cols[nnz] = i-1; values[nnz] = -1.0; nnz++; } /* Set the diagonal: position i */ cols[nnz] = i; values[nnz] = 4.0; nnz++; /* The right -1: position i+1 */ if ((i+1)%n) { cols[nnz] = i+1; values[nnz] = -1.0; nnz++; } /* The right identity block:position i+n */ if ((i+n)< N) { cols[nnz] = i+n; values[nnz] = -1.0; nnz++; } /* Set the values for row i */ HYPRE_IJMatrixSetValues(A, 1, &nnz, &i, cols, values); } } { int nnz; double values[5]; int cols[5]; for (i = ilower; i <= iupper; i++) { nnz = 1; cols[0] = i; values[0] = 1.0; /* Set the values for row i */ HYPRE_IJMatrixSetValues(B, 1, &nnz, &i, cols, values); } } /* Assemble after setting the coefficients */ HYPRE_IJMatrixAssemble(A); HYPRE_IJMatrixAssemble(B); /* Get the parcsr matrix object to use */ HYPRE_IJMatrixGetObject(A, (void**) &parcsr_A); HYPRE_IJMatrixGetObject(B, (void**) &parcsr_B); /* Create sample rhs and solution vectors */ HYPRE_IJVectorCreate(MPI_COMM_WORLD, ilower, iupper,&b); HYPRE_IJVectorSetObjectType(b, HYPRE_PARCSR); HYPRE_IJVectorInitialize(b); HYPRE_IJVectorAssemble(b); HYPRE_IJVectorGetObject(b, (void **) &par_b); HYPRE_IJVectorCreate(MPI_COMM_WORLD, ilower, iupper,&x); HYPRE_IJVectorSetObjectType(x, HYPRE_PARCSR); HYPRE_IJVectorInitialize(x); HYPRE_IJVectorAssemble(x); HYPRE_IJVectorGetObject(x, (void **) &par_x); /* -------------------------- 利用AMG生成各个层的矩阵------------------ */ /* Using AMG to get multilevel matrix */ hypre_ParAMGData *amg_data; hypre_ParCSRMatrix **A_array; hypre_ParCSRMatrix **B_array; hypre_ParCSRMatrix **P_array; /* P0P1P2 P1P2 P2 */ hypre_ParCSRMatrix **Q_array; /* (P0P1P2)^T*A0 (P1P2)^T*A1 (P2)^T*A2 */ hypre_ParCSRMatrix **S_array; /* (P0P1P2)^T*M0 (P1P2)^T*M1 (P2)^T*M2 */ hypre_ParCSRMatrix **T_array; /* rhs and x */ hypre_ParVector **F_array; hypre_ParVector **U_array; /* Create solver */ HYPRE_BoomerAMGCreate(&amg_solver); /* Set some parameters (See Reference Manual for more parameters) */ HYPRE_BoomerAMGSetPrintLevel(amg_solver, 0); /* print solve info + parameters */ HYPRE_BoomerAMGSetOldDefault(amg_solver); /* Falgout coarsening with modified classical interpolaiton */ HYPRE_BoomerAMGSetRelaxType(amg_solver, 3); /* G-S/Jacobi hybrid relaxation */ HYPRE_BoomerAMGSetRelaxOrder(amg_solver, 1); /* uses C/F relaxation */ HYPRE_BoomerAMGSetNumSweeps(amg_solver, 1); /* Sweeeps on each level */ HYPRE_BoomerAMGSetMaxLevels(amg_solver, maxLevels); /* maximum number of levels */ HYPRE_BoomerAMGSetTol(amg_solver, 1e-7); /* conv. tolerance */ /* Now setup */ HYPRE_BoomerAMGSetup(amg_solver, parcsr_A, par_b, par_x); /* Get A_array, P_array, F_array and U_array of AMG */ amg_data = (hypre_ParAMGData*) amg_solver; A_array = hypre_ParAMGDataAArray(amg_data); P_array = hypre_ParAMGDataPArray(amg_data); F_array = hypre_ParAMGDataFArray(amg_data); U_array = hypre_ParAMGDataUArray(amg_data); num_levels = hypre_ParAMGDataNumLevels(amg_data); printf ( "The number of levels = %d\n", num_levels ); B_array = hypre_CTAlloc(hypre_ParCSRMatrix*, num_levels); Q_array = hypre_CTAlloc(hypre_ParCSRMatrix*, num_levels); S_array = hypre_CTAlloc(hypre_ParCSRMatrix*, num_levels); T_array = hypre_CTAlloc(hypre_ParCSRMatrix*, num_levels); /* B0 P0^T B0 P0 P1^T B1 P1 P2^T B2 P2 */ B_array[0] = parcsr_B; for ( level = 1; level < num_levels; ++level ) { hypre_ParCSRMatrix *tmp_parcsr_mat; tmp_parcsr_mat = hypre_ParTMatmul(P_array[level-1], B_array[level-1]); B_array[level] = hypre_ParMatmul (tmp_parcsr_mat, P_array[level-1]); hypre_ParCSRMatrixDestroy(tmp_parcsr_mat); } /* P0P1P2 P1P2 P2 */ Q_array[num_levels-2] = P_array[num_levels-2]; for ( level = num_levels-3; level >= 0; --level ) { Q_array[level] = hypre_ParMatmul(P_array[level], Q_array[level+1]); } for ( level = 0; level < num_levels-1; ++level ) { S_array[level] = hypre_ParTMatmul(Q_array[level], A_array[level]); T_array[level] = hypre_ParTMatmul(Q_array[level], B_array[level]); } /* ---------------------创建A_Hh B_Hh-------------------------- */ int N_H = hypre_ParCSRMatrixGlobalNumRows(A_array[num_levels-1]); N = N_H+blockSize; local_size = N/num_procs; extra = N - local_size*num_procs; ilower = local_size*myid; ilower += hypre_min(myid, extra); iupper = local_size*(myid+1); iupper += hypre_min(myid+1, extra); iupper = iupper - 1; /* How many rows do I have? */ local_size = iupper - ilower + 1; HYPRE_IJMatrixCreate(MPI_COMM_WORLD, ilower, iupper, ilower, iupper, &A_Hh); HYPRE_IJMatrixCreate(MPI_COMM_WORLD, ilower, iupper, ilower, iupper, &B_Hh); HYPRE_IJMatrixSetObjectType(A_Hh, HYPRE_PARCSR); HYPRE_IJMatrixSetObjectType(B_Hh, HYPRE_PARCSR); HYPRE_IJMatrixInitialize(A_Hh); HYPRE_IJMatrixInitialize(B_Hh); /* Initialize A_Hh and B_Hh */ { int nnz; double *values = calloc(N, sizeof(double)); int *cols = calloc(N, sizeof(int)); hypre_CSRMatrix* local_diag = hypre_ParCSRMatrixDiag(A_array[num_levels-1]); HYPRE_Complex *matrix_data = hypre_CSRMatrixData(local_diag); HYPRE_Int *matrix_i = hypre_CSRMatrixI(local_diag); HYPRE_Int *matrix_j = hypre_CSRMatrixJ(local_diag); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(local_diag); /* 将A_H赋给A_Hh, 将B_H赋给B_Hh */ for (i = 0; i < num_rows; ++i) { nnz = matrix_i[i+1]-matrix_i[i]; /* Set the values for row i */ HYPRE_IJMatrixSetValues(A_Hh, 1, &nnz, &i, &matrix_j[ matrix_i[i] ], &matrix_data[ matrix_i[i] ]); nnz = blockSize; for (k = 0; k < nnz; ++k) { cols[k] = num_rows+k; values[k] = 0.0; } HYPRE_IJMatrixSetValues(A_Hh, 1, &nnz, &i, cols, values); } for (i = num_rows; i < N; ++i) { nnz = N; for (k = 0; k < N; ++k) { cols[k] = k; values[k] = 0.0; } HYPRE_IJMatrixSetValues(A_Hh, 1, &nnz, &i, cols, values); } hypre_TFree(values); hypre_TFree(cols); } { int nnz; double *values = calloc(N, sizeof(double)); int *cols = calloc(N, sizeof(int)); HYPRE_ParCSRMatrix B_H = B_array[num_levels-1]; hypre_CSRMatrix* local_diag = hypre_ParCSRMatrixDiag(B_H); HYPRE_Complex *matrix_data = hypre_CSRMatrixData(local_diag); HYPRE_Int *matrix_i = hypre_CSRMatrixI(local_diag); HYPRE_Int *matrix_j = hypre_CSRMatrixJ(local_diag); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(local_diag); for (i = 0; i < num_rows; ++i) { nnz = matrix_i[i+1]-matrix_i[i]; /* Set the values for row i */ HYPRE_IJMatrixSetValues(B_Hh, 1, &nnz, &i, &matrix_j[ matrix_i[i] ], &matrix_data[ matrix_i[i] ]); nnz = blockSize; for (k = 0; k < nnz; ++k) { cols[k] = num_rows+k; values[k] = 0.0; } HYPRE_IJMatrixSetValues(B_Hh, 1, &nnz, &i, cols, values); } for (i = num_rows; i < N; ++i) { nnz = N; for (k = 0; k < N; ++k) { cols[k] = k; values[k] = 0.0; } HYPRE_IJMatrixSetValues(B_Hh, 1, &nnz, &i, cols, values); } hypre_TFree(values); hypre_TFree(cols); } /* Assemble after setting the coefficients */ HYPRE_IJMatrixAssemble(A_Hh); HYPRE_IJMatrixAssemble(B_Hh); HYPRE_IJVectorCreate(MPI_COMM_WORLD, ilower, iupper,&x_Hh); HYPRE_IJVectorSetObjectType(x_Hh, HYPRE_PARCSR); HYPRE_IJVectorInitialize(x_Hh); HYPRE_IJVectorAssemble(x_Hh); HYPRE_IJVectorCreate(MPI_COMM_WORLD, ilower, iupper,&b_Hh); HYPRE_IJVectorSetObjectType(b_Hh, HYPRE_PARCSR); HYPRE_IJVectorInitialize(b_Hh); HYPRE_IJVectorAssemble(b_Hh); int idx_eig; /* eigenvalues - allocate space */ double *eigenvalues = (double*) calloc( blockSize, sizeof(double) ); /* 辅助空间 */ double **aux; aux = calloc(blockSize, sizeof(double*)); for (i = 0; i < blockSize; ++i) { aux[i] = calloc(blockSize, sizeof(double)); } /* Laplace精确特征值 */ int nn = (int) sqrt(blockSize) + 1; double *exact_eigenvalues = (double*) calloc(nn*nn, sizeof(double)); for (i = 0; i < nn; ++i) { for (k = 0; k < nn; ++k) { exact_eigenvalues[i*nn+k] = M_PI*M_PI*(pow(i+1, 2)+pow(k+1, 2)); } } qsort(exact_eigenvalues, nn*nn, sizeof(double), cmp); /* -----------------------特征向量存储成MultiVector--------------------- */ mv_MultiVectorPtr eigenvectors_Hh = NULL; mv_MultiVectorPtr constraints_Hh = NULL; mv_InterfaceInterpreter* interpreter_Hh; HYPRE_MatvecFunctions matvec_fn; /* define an interpreter for the ParCSR interface */ interpreter_Hh = hypre_CTAlloc(mv_InterfaceInterpreter,1); HYPRE_ParCSRSetupInterpreter(interpreter_Hh); HYPRE_ParCSRSetupMatvec(&matvec_fn); /* 从粗到细, 最粗特征值, 细解问题 */ for ( level = num_levels-2; level >= 0; --level ) { /* pvx_Hh (特征向量) pvx_h(上一层解问题向量) pvx(当前层解问题向量) */ printf ( "Current level = %d\n", level ); /* 最粗层时, 直接就是最粗矩阵, 否则生成Hh矩阵 */ printf ( "Set A_Hh and B_Hh\n" ); if ( level == num_levels-2 ) { par_x_Hh = U_array[num_levels-1]; par_b_Hh = F_array[num_levels-1]; parcsr_A_Hh = A_array[num_levels-1]; parcsr_B_Hh = B_array[num_levels-1]; } else { HYPRE_IJVectorGetObject(x_Hh, (void **) &par_x_Hh); HYPRE_IJVectorGetObject(b_Hh, (void **) &par_b_Hh); HYPRE_ParVector* tmp; tmp = pvx_h; /* pvx_h是level+1层的特征向量 */ pvx_h = pvx; /* 释放上一层解问题向量的空间 */ if (level < num_levels-3) { for (idx_eig = 0; idx_eig < blockSize; ++idx_eig) { HYPRE_ParVectorDestroy(tmp[idx_eig]); } } /* N == A_Hh的大小 */ int nnz; int row; double *values; int *cols = calloc(N, sizeof(int)); /* 更新A_Hh中的辅助空间 */ for (i = 0; i < N_H; ++i) { cols[i] = i; } for (idx_eig = 0; idx_eig < blockSize; ++idx_eig) { /* 将上一层解问题的向量乘以A, 再投影到最粗层 y = alpha*A*x + beta*y */ HYPRE_ParCSRMatrixMatvec ( 1.0, S_array[level+1], pvx_h[idx_eig], 0.0, U_array[num_levels-1] ); /* 重置给A_Hh对应的行和列 */ nnz = N_H; row = N_H+idx_eig; values = hypre_VectorData( hypre_ParVectorLocalVector(U_array[num_levels-1]) ); HYPRE_IJMatrixSetValues(A_Hh, 1, &nnz, &row, cols, values); nnz = 1; for (i = 0; i < N_H; ++i) { HYPRE_IJMatrixSetValues(A_Hh, 1, &nnz, &i, &row, &values[i]); } } for (i = 0; i < blockSize; ++i) { cols[i] = N_H+i; } for (i = 0; i < blockSize; ++i) { for (k = 0; k < blockSize; ++k) { /* pvx_h A_array[level+1] pvx_h 不记得是aux[i][k] 还是反过来 */ HYPRE_ParCSRMatrixMatvec ( 1.0, A_array[level+1], pvx_h[k], 0.0, F_array[level+1] ); HYPRE_ParVectorInnerProd (pvx_h[i], F_array[level+1], &aux[i][k]); } /* 重置给A_Hh */ nnz = blockSize; row = N_H+i; HYPRE_IJMatrixSetValues(A_Hh, 1, &nnz, &row, cols, aux[i]); } /* 更新B_Hh中的辅助空间 */ for (i = 0; i < N_H; ++i) { cols[i] = i; } for (idx_eig = 0; idx_eig < blockSize; ++idx_eig) { /* 将上一层解问题的向量乘以M, 再投影到最粗层 y = alpha*A*x + beta*y */ HYPRE_ParCSRMatrixMatvec ( 1.0, T_array[level+1], pvx_h[idx_eig], 0.0, U_array[num_levels-1] ); /* 重置给B_Hh */ nnz = N_H; row = N_H+idx_eig; values = hypre_VectorData( hypre_ParVectorLocalVector(U_array[num_levels-1]) ); HYPRE_IJMatrixSetValues(B_Hh, 1, &nnz, &row, cols, values); nnz = 1; for (i = 0; i < N_H; ++i) { HYPRE_IJMatrixSetValues(B_Hh, 1, &nnz, &i, &row, &values[i]); } } for (i = 0; i < blockSize; ++i) { cols[i] = N_H+i; } for (i = 0; i < blockSize; ++i) { for (k = 0; k < blockSize; ++k) { /* pvx_h B_array[level+1] pvx_h 不记得是aux[i][k] 还是反过来 */ HYPRE_ParCSRMatrixMatvec ( 1.0, B_array[level+1], pvx_h[k], 0.0, F_array[level+1] ); HYPRE_ParVectorInnerProd (pvx_h[i], F_array[level+1], &aux[i][k]); } /* 重置给B_Hh */ nnz = blockSize; row = N_H+i; HYPRE_IJMatrixSetValues(B_Hh, 1, &nnz, &row, cols, aux[i]); } HYPRE_IJMatrixAssemble(A_Hh); HYPRE_IJMatrixAssemble(B_Hh); /* Get the parcsr matrix object to use */ HYPRE_IJMatrixGetObject(A_Hh, (void**) &parcsr_A_Hh); HYPRE_IJMatrixGetObject(B_Hh, (void**) &parcsr_B_Hh); } /*------------------------Create a preconditioner and solve the eigenproblem-------------*/ /* AMG preconditioner */ { HYPRE_BoomerAMGCreate(&precond); HYPRE_BoomerAMGSetPrintLevel(precond, 0); /* print amg solution info */ HYPRE_BoomerAMGSetNumSweeps(precond, 2); /* 2 sweeps of smoothing */ HYPRE_BoomerAMGSetTol(precond, 0.0); /* conv. tolerance zero */ HYPRE_BoomerAMGSetMaxIter(precond, 1); /* do only one iteration! */ } printf ( "LOBPCG solve A_Hh U_Hh = lambda_Hh B_Hh U_Hh\n" ); /* LOBPCG eigensolver */ { int maxIterations = 100; /* maximum number of iterations */ int pcgMode = 1; /* use rhs as initial guess for inner pcg iterations */ int verbosity = 0; /* print iterations info */ double tol = 1.e-8; /* absolute tolerance (all eigenvalues) */ int lobpcgSeed = 775; /* random seed */ if (myid != 0) verbosity = 0; if (level == num_levels-3) { for ( idx_eig = 0; idx_eig < blockSize; ++idx_eig) { HYPRE_ParVectorDestroy(pvx_Hh[idx_eig]); } } /* 最开始par_x_Hh是最粗空间的大小, 之后变成Hh空间的大小 */ if (level >= num_levels-3) { /* eigenvectors - create a multivector */ eigenvectors_Hh = mv_MultiVectorCreateFromSampleVector(interpreter_Hh, blockSize, par_x_Hh); mv_TempMultiVector* tmp = (mv_TempMultiVector*) mv_MultiVectorGetData(eigenvectors_Hh); pvx_Hh = (HYPRE_ParVector*)(tmp -> vector); mv_MultiVectorSetRandom (eigenvectors_Hh, lobpcgSeed); } HYPRE_LOBPCGCreate(interpreter_Hh, &matvec_fn, &lobpcg_solver); HYPRE_LOBPCGSetMaxIter(lobpcg_solver, maxIterations); HYPRE_LOBPCGSetPrecondUsageMode(lobpcg_solver, pcgMode); HYPRE_LOBPCGSetTol(lobpcg_solver, tol); HYPRE_LOBPCGSetPrintLevel(lobpcg_solver, verbosity); /* use a preconditioner */ HYPRE_LOBPCGSetPrecond(lobpcg_solver, (HYPRE_PtrToSolverFcn) HYPRE_BoomerAMGSolve, (HYPRE_PtrToSolverFcn) HYPRE_BoomerAMGSetup, precond); HYPRE_LOBPCGSetup(lobpcg_solver, (HYPRE_Matrix)parcsr_A_Hh, (HYPRE_Vector)par_b_Hh, (HYPRE_Vector)par_x_Hh); HYPRE_LOBPCGSetupB(lobpcg_solver, (HYPRE_Matrix)parcsr_B_Hh, (HYPRE_Vector)par_x_Hh); // time_index = hypre_InitializeTiming("LOBPCG Solve"); // hypre_BeginTiming(time_index); HYPRE_LOBPCGSolve(lobpcg_solver, constraints_Hh, eigenvectors_Hh, eigenvalues ); /* for ( idx_eig = 0; idx_eig < blockSize; ++idx_eig) { printf ( "eig = %lf, error = %lf\n", eigenvalues[idx_eig]/h2, fabs(eigenvalues[idx_eig]/h2-exact_eigenvalues[idx_eig]) ); } */ // hypre_EndTiming(time_index); // hypre_PrintTiming("Solve phase times", MPI_COMM_WORLD); // hypre_FinalizeTiming(time_index); // hypre_ClearTiming(); /* clean-up */ HYPRE_BoomerAMGDestroy(precond); HYPRE_LOBPCGDestroy(lobpcg_solver); } /*------------------------Create a preconditioner and solve the linear system-------------*/ printf ( "PCG solve A_h U = lambda_Hh B_h U_Hh\n" ); /* PCG with AMG preconditioner */ { mv_MultiVectorPtr eigenvectors = NULL; mv_InterfaceInterpreter* interpreter; interpreter = hypre_CTAlloc(mv_InterfaceInterpreter,1); HYPRE_ParCSRSetupInterpreter(interpreter); /* eigenvectors - create a multivector */ eigenvectors = mv_MultiVectorCreateFromSampleVector(interpreter, blockSize, U_array[level]); /* eigenvectors - get a pointer */ { mv_TempMultiVector* tmp = (mv_TempMultiVector*) mv_MultiVectorGetData(eigenvectors); pvx = (HYPRE_ParVector*)(tmp -> vector); } for (idx_eig = 0; idx_eig < blockSize; ++idx_eig) { if ( level == num_levels-2 ) { HYPRE_ParCSRMatrixMatvec ( 1.0, Q_array[level], pvx_Hh[idx_eig], 0.0, pvx[idx_eig] ); } else { double *v_H; double *v_Hh; /* 利用最粗层的U将Hh空间中的H部分的向量投影到上一层 */ v_H = hypre_VectorData( hypre_ParVectorLocalVector(U_array[num_levels-1]) ); /* Q pvx_Hh[0:N_H-1] + alpha[0] pvx_h[0] + ... + alpha[blockSize-1] pvx_h[blockSize-1] */ v_Hh = hypre_VectorData( hypre_ParVectorLocalVector(pvx_Hh[idx_eig]) ); hypre_VectorData( hypre_ParVectorLocalVector(U_array[num_levels-1]) ) = v_Hh; HYPRE_ParCSRMatrixMatvec ( 1.0, Q_array[level+1], U_array[num_levels-1], 0.0, U_array[level+1] ); for (k = 0; k < blockSize; ++k) { /* y = a x + y */ HYPRE_ParVectorAxpy(v_Hh[N_H+k], pvx_h[k], U_array[level+1]); } /* 生成当前网格下的特征向量 */ HYPRE_ParCSRMatrixMatvec ( 1.0, P_array[level], U_array[level+1], 0.0, pvx[idx_eig] ); /* 还原U */ hypre_VectorData( hypre_ParVectorLocalVector(U_array[num_levels-1]) ) = v_H; } } /* Create solver */ HYPRE_ParCSRPCGCreate(MPI_COMM_WORLD, &pcg_solver); /* Set some parameters (See Reference Manual for more parameters) */ HYPRE_PCGSetMaxIter(pcg_solver, 1000); /* max iterations */ HYPRE_PCGSetTol(pcg_solver, 1e-8); /* conv. tolerance */ HYPRE_PCGSetTwoNorm(pcg_solver, 1); /* use the two norm as the stopping criteria */ HYPRE_PCGSetPrintLevel(pcg_solver, 0); /* print solve info */ HYPRE_PCGSetLogging(pcg_solver, 1); /* needed to get run info later */ /* Now set up the AMG preconditioner and specify any parameters */ HYPRE_BoomerAMGCreate(&precond); HYPRE_BoomerAMGSetPrintLevel(precond, 0); /* print amg solution info */ HYPRE_BoomerAMGSetCoarsenType(precond, 6); HYPRE_BoomerAMGSetOldDefault(precond); HYPRE_BoomerAMGSetRelaxType(precond, 6); /* Sym G.S./Jacobi hybrid */ HYPRE_BoomerAMGSetNumSweeps(precond, 1); HYPRE_BoomerAMGSetTol(precond, 0.0); /* conv. tolerance zero */ HYPRE_BoomerAMGSetMaxIter(precond, 1); /* do only one iteration! */ /* Set the PCG preconditioner */ HYPRE_PCGSetPrecond(pcg_solver, (HYPRE_PtrToSolverFcn) HYPRE_BoomerAMGSolve, (HYPRE_PtrToSolverFcn) HYPRE_BoomerAMGSetup, precond); /* Now setup and solve! */ HYPRE_ParCSRPCGSetup(pcg_solver, A_array[level], F_array[level], U_array[level]); // time_index = hypre_InitializeTiming("PCG Solve"); // hypre_BeginTiming(time_index); for (idx_eig = 0; idx_eig < blockSize; ++idx_eig) { /* 生成右端项 y = alpha*A*x + beta*y */ HYPRE_ParCSRMatrixMatvec ( eigenvalues[idx_eig], B_array[level], pvx[idx_eig], 0.0, F_array[level] ); HYPRE_ParCSRPCGSolve(pcg_solver, A_array[level], F_array[level], pvx[idx_eig]); } // hypre_EndTiming(time_index); // hypre_PrintTiming("Solve phase times", MPI_COMM_WORLD); // hypre_FinalizeTiming(time_index); // hypre_ClearTiming(); if (level == 0) { for (idx_eig = 0; idx_eig < blockSize; ++idx_eig) { double tmp_double; HYPRE_ParCSRMatrixMatvec ( 1.0, A_array[level], pvx[idx_eig], 0.0, F_array[level] ); HYPRE_ParVectorInnerProd (F_array[level], pvx[idx_eig], &eigenvalues[idx_eig]); HYPRE_ParCSRMatrixMatvec ( 1.0, B_array[level], pvx[idx_eig], 0.0, F_array[level] ); HYPRE_ParVectorInnerProd (F_array[level], pvx[idx_eig], &tmp_double); eigenvalues[idx_eig] = eigenvalues[idx_eig] / tmp_double; printf ( "eig = %f, error = %f\n", eigenvalues[idx_eig]/h2, fabs(eigenvalues[idx_eig]/h2-exact_eigenvalues[idx_eig]) ); } } /* Destroy solver and preconditioner */ HYPRE_ParCSRPCGDestroy(pcg_solver); HYPRE_BoomerAMGDestroy(precond); hypre_TFree(interpreter); } } /* Clean up */ for ( level = 1; level < num_levels; ++level ) { hypre_ParCSRMatrixDestroy(B_array[level]); hypre_ParCSRMatrixDestroy(S_array[level-1]); hypre_ParCSRMatrixDestroy(T_array[level-1]); } for ( level = 0; level < num_levels-2; ++level ) { hypre_ParCSRMatrixDestroy(Q_array[level]); } hypre_TFree(B_array); hypre_TFree(Q_array); hypre_TFree(S_array); hypre_TFree(T_array); hypre_TFree(eigenvalues); hypre_TFree(exact_eigenvalues); for (i = 0; i < blockSize; ++i) { hypre_TFree(aux[i]); } hypre_TFree(aux); HYPRE_IJMatrixDestroy(A); HYPRE_IJMatrixDestroy(B); HYPRE_IJVectorDestroy(b); HYPRE_IJVectorDestroy(x); HYPRE_IJMatrixDestroy(A_Hh); HYPRE_IJMatrixDestroy(B_Hh); HYPRE_IJVectorDestroy(b_Hh); HYPRE_IJVectorDestroy(x_Hh); /* Destroy amg_solver */ HYPRE_BoomerAMGDestroy(amg_solver); hypre_TFree(interpreter_Hh); hypre_EndTiming(global_time_index); hypre_PrintTiming("Solve phase times", MPI_COMM_WORLD); hypre_FinalizeTiming(global_time_index); hypre_ClearTiming(); /* Finalize MPI*/ MPI_Finalize(); return(0); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #define PORT 9034 // port we’re listening on #define STDIN 0 char* get_ip(char* to){ if(strcmp(to,"shivam")==0)return "192.168.1.102"; if(strcmp(to,"shashi")==0)return "192.168.1.104"; if(strcmp(to,"lad")==0)return "192.168.1.105"; } char* get_user(char* to){ if(strcmp(to,"192.168.1.102")==0)return "shivam"; if(strcmp(to,"192.168.1.104")==0)return "shashi"; if(strcmp(to,"192.168.1.105")==0)return "lad"; } int main(void) { struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 500000; fd_set master; char s[121]; char to[20]; char msg[100]; fd_set read_fds; fd_set write_fds; struct hostent *he; char buf[256]; struct sockaddr_in myaddr; struct sockaddr_in remoteaddr; // client address struct sockaddr_in their_addr; // client address int fdmax; int listener; int sender[4]; int sender_count=0; int newfd; int nbytes; int yes=1; int addrlen; int i, j; FD_ZERO(&master); FD_ZERO(&read_fds); if ((listener = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } for(int i=0;i<4;i++){ if ((sender[i] = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } } if (setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } myaddr.sin_family = AF_INET; myaddr.sin_addr.s_addr = INADDR_ANY; myaddr.sin_port = htons(PORT); memset(&(myaddr.sin_zero), '\0', 8); if (bind(listener, (struct sockaddr *)&myaddr, sizeof(myaddr)) == -1) { perror("bind"); exit(1); } if (listen(listener, 10) == -1) { perror("listen"); exit(1); } FD_SET(listener, &master); fdmax = listener; FD_SET(STDIN, &master); if(STDIN > fdmax) fdmax =STDIN; for(;;) { read_fds = master; // copy it if (select(fdmax+1, &read_fds, NULL, NULL, &tv) == -1) { perror("select"); exit(1); } for(i = 0; i <= fdmax; i++) { if (FD_ISSET(i, &read_fds)) { // we got one!! if (i == listener) { addrlen = sizeof(remoteaddr); if ((newfd = accept(listener, &remoteaddr, &addrlen)) == -1) { perror("accept"); } else { FD_SET(newfd, &master); // add to master set if (newfd > fdmax) { fdmax = newfd; } printf("selectserver: new connection from %s on " "socket %d\n", inet_ntoa(remoteaddr.sin_addr), newfd); } } else if (i == STDIN){ bzero(s,121); bzero(to,20); bzero(msg,100); scanf(" %[^\n]*c",s); int i; for( i=0;i<strlen(s);i++){ if(s[i]=='/')break; to[i]=s[i]; } int j=0; i++; while(i<strlen(s)){ msg[j]=s[i]; i++; j++; } struct sockaddr_in addr; int len=sizeof(addr); char *ip; int flag=1; for(int j=0;j<sender_count;j++){ if(getpeername(sender[j],&addr,&len)!=-1){ ip = inet_ntoa(addr.sin_addr); if(strcmp(ip,get_ip(to))==0){ flag=0; int m = send(sender[j],msg,strlen(msg),0); } } } if(flag){ if(sender_count==4){ perror("connection linit exceed "); exit(1); } if ((he=gethostbyname(get_ip(to))) == NULL) { perror("gethostbyname"); exit(1); } their_addr.sin_family = AF_INET; // host byte order their_addr.sin_port = htons(PORT); // short, network byte order their_addr.sin_addr = *((struct in_addr *)he->h_addr); bzero(&(their_addr.sin_zero), 8); // zero the rest of the struct if (connect(sender[sender_count], (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) { perror("connect"); exit(1); } int m = getpeername(sender[sender_count],&addr,&len); int n = send(sender[sender_count],msg,strlen(msg),0); sender_count++; } } else { bzero(buf,256); if ((nbytes = recv(i, buf, sizeof(buf), 0)) <= 0) { if (nbytes == 0) { printf("selectserver: socket %d hung up\n", i); } else { perror("recv"); } close(i); // bye! FD_CLR(i, &master); // remove from master set } else { struct sockaddr_in addr; int len=sizeof(addr); char *ip; int flag=1; if(getpeername(i,&addr,&len)!=-1){ ip = inet_ntoa(addr.sin_addr); printf("%s : %s\n",get_user(ip),buf); } else { perror("error"); exit(1); } bzero(buf,256); } } } } } return 0; }
C
/* INSTRUCTIONS Write a program that asks for the students' exam scores (using integers 4 to 10) and calculates the average. The program must accept scores until entry is terminated by a negative integer. Finally, the program prints out the number of scores and the calculated average with two decimal places of precision. Hint: You can write your program using either the while or do...while statement. Example output: The program calculates the average of scores you enter. End with a negative integer. Enter score (4-10):7 Enter score (4-10):8 Enter score (4-10):9 Enter score (4-10):10 Enter score (4-10):4 Enter score (4-10):4 Enter score (4-10):5 Enter score (4-10):-1 You entered 7 scores. Average score: 6.71 */ #include <stdio.h> int main() { int input_number; float score_average, score_sum, score_amount = 0; printf("The program calculates the average of scores you enter.\nEnd with a negative integer.\n"); do { printf("Enter score (4-10):"); scanf("%d", &input_number); if (input_number >= 0) { score_sum = input_number + score_sum; score_amount++; } } while (input_number >= 0); score_average = score_sum / score_amount; printf("You entered %.0f scores.\nAverage score: %.2f\n", score_amount, score_average); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <time.h> #include <sys/time.h> #include "pcie_memmap.h" //#define N 13 // qtd de coeficientes #define VERBOSO int main() { unsigned int qtde_nums = 128; FILE * fp_entrada = fopen("entrada.dat", "r"); if(!fp_entrada) { printf("Fornecer o arquivo \"entrada.dat\".\n"); exit(1); } int i; int numeros[qtde_nums]; u32 resultados[qtde_nums]; for(i=0 ; i<qtde_nums ; i++) { fscanf(fp_entrada, "%i", (numeros+i) ); } for(i=0 ; i<qtde_nums ; i++) { resultados[i] = (u32)0; } struct timeval inicio; struct timeval fim; // FPGA u32* ptr = get_device(); gettimeofday(&inicio, NULL); /// T_zero move(ptr, (u32*) numeros, qtde_nums); executar(ptr); get(ptr, resultados, qtde_nums); gettimeofday(&fim, NULL); /// T_final close_device(ptr); // END FPGA long tempo = ((fim.tv_sec * 1000000 + fim.tv_usec) - (inicio.tv_sec * 1000000 + inicio.tv_usec)); #ifdef VERBOSO printf("\nTeste da operacao em FPGA:\n\n"); printf("Entrada = "); for(i=0 ; i<qtde_nums ; ++i) { printf("%i ; ", numeros[i]); } printf("\n\nSaida = "); for(i=0 ; i<qtde_nums ; ++i) { printf("%i ; ", ((int*)resultados)[i] ); } printf("\n\nTEMPO GASTO (FPGA): %ld (us)\n", tempo ); printf("\n\n"); #endif #ifndef VERBOSO printf("%ld\n", tempo ); #endif fclose(fp_entrada); return 0; }
C
#include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> unsigned char ubuf[6]; void led_on(int fd, int num) { if (num == 1) ioctl(fd, 0, num); else if (num == 2) ioctl(fd, 0, num); else if (num == 3) ioctl(fd, 0, num); else if (num == 4) ioctl(fd, 0, num); } void led_off(int fd, int num) { if (num == 1) ioctl(fd, 1, num); else if (num == 2) ioctl(fd, 1, num); else if (num == 3) ioctl(fd, 1, num); else if (num == 4) ioctl(fd, 1, num); } /* * 2nd param = status(1:off; 0:on) * */ void leds_all_off(int fd) { ioctl(fd, 1, 1); ioctl(fd, 1, 2); ioctl(fd, 1, 3); ioctl(fd, 1, 4); } void leds_all_on(int fd) { ioctl(fd, 0, 1); ioctl(fd, 0, 2); ioctl(fd, 0, 3); ioctl(fd, 0, 4); } int main(int argc, char **argv) { int fd_buttons, fd_leds; memset(ubuf, 0, sizeof(ubuf)); fd_buttons = open("/dev/buttonsPoll", O_RDWR); if (fd_buttons < 0) { printf("Error: open \"/dev/buttonsPoll\" is failed!\n"); return -1; } fd_leds = open("/dev/leds", O_RDWR); if (fd_leds < 0) { printf("Error: open \"/dev/leds\" is failed!\n"); return -1; } leds_all_off(fd_leds); /* Read buttons info by using polling method */ while (1) { read(fd_buttons, ubuf, sizeof(ubuf)); if (!ubuf[0]) { printf("key1 is pressed down!\n"); led_on(fd_leds, 1); }else if (!ubuf[1]) { printf("key2 is pressed down!\n"); led_on(fd_leds, 2); }else if (!ubuf[2]) { printf("key3 is pressed down!\n"); led_on(fd_leds, 3); }else if (!ubuf[3]) { printf("key4 is pressed down!\n"); led_on(fd_leds, 4); }else if (!ubuf[4]) { printf("key5 is pressed down!\n"); leds_all_off(fd_leds); }else if (!ubuf[5]) { printf("key6 is pressed down!\n"); leds_all_on(fd_leds); } } return 0; }