language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/*- * Copyright (c) 2017-2018 Razor, Inc. * All rights reserved. * * See the file LICENSE for redistribution information. */ #include "rate_stat.h" void rate_stat_init(rate_stat_t* rate, int wnd_size, float scale) { rate->wnd_size = wnd_size; rate->scale = scale; rate->buckets = calloc(wnd_size, sizeof(rate_bucket_t)); rate->accumulated_count = 0; rate->sample_num = 0; rate->oldest_index = 0; rate->oldest_ts = -1; } void rate_stat_destroy(rate_stat_t* rate) { if (rate == NULL) return; if (rate->buckets != NULL){ free(rate->buckets); rate->buckets = NULL; } } void rate_stat_reset(rate_stat_t* rate) { int i; rate->accumulated_count = 0; rate->sample_num = 0; rate->oldest_index = 0; rate->oldest_ts = -1; for (i = 0; i < rate->wnd_size; ++i){ rate->buckets[i].sum = 0; rate->buckets[i].sample = 0; } } /*ɾڵͳ*/ static void rate_stat_erase(rate_stat_t* rate, int64_t now_ts) { int64_t new_oldest_ts; rate_bucket_t* bucket; if (rate->oldest_ts == -1) return; new_oldest_ts = now_ts - rate->wnd_size + 1; if (new_oldest_ts <= rate->oldest_ts) return; while (rate->sample_num > 0 && rate->oldest_ts < new_oldest_ts){ bucket = &rate->buckets[rate->oldest_index]; rate->sample_num -= bucket->sample; rate->accumulated_count -= bucket->sum; bucket->sum = 0; bucket->sample = 0; if (++rate->oldest_index >= rate->wnd_size) rate->oldest_index = 0; ++rate->oldest_ts; } rate->oldest_ts = new_oldest_ts; } void rate_stat_update(rate_stat_t* rate, size_t count, int64_t now_ts) { int ts_offset, index; if (rate->oldest_ts > now_ts) return; rate_stat_erase(rate, now_ts); if (rate->oldest_ts == -1){ rate->oldest_ts = now_ts; } ts_offset = (int)(now_ts - rate->oldest_ts); index = (rate->oldest_index + ts_offset) % rate->wnd_size; rate->sample_num++; rate->buckets[index].sum += count; rate->buckets[index].sample++; rate->accumulated_count += count; } /*ȡͳƵ*/ int rate_stat_rate(rate_stat_t* rate, int64_t now_ts) { int ret, active_wnd_size; rate_stat_erase(rate, now_ts); active_wnd_size = (int)(now_ts - rate->oldest_ts + 1); if (rate->sample_num == 0 || active_wnd_size <= 1 || (active_wnd_size < rate->wnd_size)) return -1; ret = (int)(rate->accumulated_count * 1.0f * rate->scale / rate->wnd_size + 0.5); return ret; }
C
/* * 编码生成汇编代码 test: leaq (%rdi,%rsi), %rax addq %rdx, %rax cmpq $-3, %rdi jge .L2 cmpq $1, %rsi jle .L5 movq %rsi, %rax imulq %rdx, %rax ret .L5: movq %rdi, %rax imulq %rsi, %rax ret .L2: cmpq $2, %rdi jle .L1 leaq (%rdi,%rdi), %rax .L1: ret */ long test(long x, long y, long z) { long val = x + y + z; if (x < -3) { if(y < 2) { val = x * y; } else { val = y * z; } } else if (x > 2) { val = x * 2; } return val; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* file_reader.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jgabelho <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/25 15:55:08 by jgabelho #+# #+# */ /* Updated: 2019/03/05 15:32:54 by jgabelho ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/fdf.h" #include "../includes/libft.h" #include <errno.h> int file_len(char *file) { int i; int fd; char *lines; i = 0; if ((fd = open(file, O_RDONLY)) == -1) { write(1, "open failed", 11); return (0); } while (get_next_line(fd, &lines)) { free(lines); i++; } close(fd); ft_strdel(&lines); return (i); } int file_width(char *file) { int fd; char *lines; char **split; int i; i = 0; if ((fd = open(file, O_RDONLY)) == -1) { write(1, "open failed", 11); return (0); } if (get_next_line(fd, &lines) == -1) { perror("fdf"); exit(0); } close(fd); split = ft_strsplit(lines, ' '); while (split[i] != 0) ft_strdel(&split[i++]); free(split); ft_strdel(&lines); return (i); } int *xyz(char *line, int xmax) { char **split; int *z; int i; i = 0; split = ft_strsplit(line, ' '); if ((z = malloc(sizeof(int) * xmax)) == 0) { write(1, "malloc failed", 13); return (0); } i = 0; while (split[i] != 0) { z[i] = ft_atoi(split[i]); ft_strdel(&split[i]); i++; } free(split); return (z); } int **coords(int fd, int xmax, int ymax) { int **co; char *lines; int i; if ((co = malloc(sizeof(int *) * ymax)) == 0) { write(1, "malloc failed", 13); return (0); } i = 0; while (get_next_line(fd, &lines)) { co[i] = xyz(lines, xmax); free(lines); i++; } ft_strdel(&lines); return (co); } int **file_reader(char *file, int xmax, int ymax) { int fd; int **c; fd = open(file, O_RDONLY); if (fd == -1) { write(1, "open failed", 11); return (NULL); } c = coords(fd, xmax, ymax); close(fd); return (c); }
C
/** @file utility.h @author Cristina Fabris @author Raffaele Di Nardo Di Maio @brief Header of utility functions. */ #ifndef UTILITY #define UTILITY #include "tsp.h" #define LINE "----------------------------------------------------------------------------------\n" #define STAR_LINE "**********************************************************************************\n" #define LINE_SIZE 180 //size of the line gets from the input #define NAME_SIZE 30 //size of the variable name in the cplex model //Check if the solution is an integer vector and respect constraints #define SOLUTION_CORRECTNESS 1 //Approximation value for the cplex result values in pre-solution #define EPS 1e-5 #define GP_DEFAULT_STYLE "style.txt" //name of the style file needed by Gnuplot #define DEFAULT_DAT "solution.dat" //name of the file where to print the solution of the default algoritm #define CPLEX_DAT "solutionCPLEX.dat" //name of the file where to print the cplex solution #define GP_CPLEX_STYLE "styleCPLEX.txt" //name of the style file for the cplex solution needed by Gnuplot #define LP_FILENAME "model.lp" //name fo the file that conteins the cplex model #define GNUPLOT_EXE "%GNUPLOT%/bin/gnuplot.exe -persistent" //path of where is gnuplot.exe #define PLOT_HEURISTIC_DAT "plot_cost.dat" #define HEURISTIC_STYLE "styleHEURISTIC.txt" #define CAST_PRECISION 0.4999999999 //quantity to add to correctly approximate double into int #define DEFAULT_SOLLIM_VALUE 2147483647 //Colors #define BLUE "\033[1;34m" #define GREEN "\033[1;32m" #define RED "\033[1;31m" #define WHITE "\033[0m" #define YELLOW "\033[1;33m" #define CYAN "\033[1;36m" /** @brief Compute the distance between two nodes, looking to the specified way of computing distances in tsp_in. @param node1 index of first node (index of the node specified in TSP file) @param node2 index of second node (index of the node specified in TSP file) @param tsp_in reference to tsp instance structure @param dist container of the distance computed (coherent with costInt) */ void dist(int, int, tsp_instance*, void*); /** @brief Print value of the solution of TSP problem. @param tsp_in reference to tsp instance structure */ void print_cost(tsp_instance* tsp_in); /** @brief Return the position of the element (i,j) in the matrix of corresponding edges, created from the nodes in the graph. @param tsp_in reference to tsp instance structure @param i first index @param j second index */ int xpos(tsp_instance* tsp_in, int i, int j); /** @brief Return the position of the element (i,j) in the matrix of corresponding edges, created from the nodes in the graph. Don't need the use of a reference to tsp instance structure @param i first index @param j second index param num_nodes number of nodes in the instance */ int generic_xpos(int i, int j, int num_nodes); /** @brief Define the tour of the non-compact solution. @param tsp_in reference to tsp instance structure @param x array of the point in the solution @param succ array of the successor of each node @param comp array with the component of each node @param n_comps number of components */ void define_tour(tsp_instance* tsp_in, double* x, int* succ, int* comp, int* n_comps); /** @brief Plot the solution. @param tsp_in reference to tsp instance structure @param succ array of the successor of each node @param comp array with the component of each node @param n_comps number of components */ void plot(tsp_instance* tsp_in, int* succ, int* comp, int* n_comps); #endif
C
/* * gossip.h * * Created on: Dec 12, 2017 * Author: dmcl216 */ #ifndef GOSSIP_H_ #define GOSSIP_H_ #include <string.h> #include <stdint.h> #include "networking.h" #include "util.h" #define GOSSIP_HEADER "gossip" #define G_HEADER_SIZE 6 // strlen(HEADER) enum HOST_STATE { ONLINE = 0x01, OFFLINE = 0x10, }; /** * 记录对应host的状态信息 * @host 主机ip * @status 状态,ONLINE or OFFLINE * @generation 每次重新启动后自增1 * @version 每一轮gossip加1 */ struct host_state_s { char host[16]; int status; uint32_t generation; uint32_t version; }; /** * 记录所有host的状态,更新时比较顺序 * generation->version * @states 所有host的状态 * @size states的大小 * @n_host states保存的host的个数,当n_host >= size时调用realloc扩容 */ struct gossiper_s { struct host_state_s *states; uint32_t size; uint32_t n_host; /* 初始化gossiper */ void (*gossiper_init) (struct gossiper_s *this); /* states扩容,每次扩大之前size的1/2 */ int (*gossiper_realloc) (struct gossiper_s *this); /* 更新host信息 */ void (*gossiper_update) (struct host_state_s hs, int idx, struct gossiper_s *this); /* 新的节点信息插入 */ int (*gossiper_push) (struct host_state_s hs, struct gossiper_s *this); /* 发起新一轮gossip,每次选三个节点 */ void (*gossiper_start) (struct gossiper_s *this); /* 当前gossip信息 */ struct str_s* (*gossiper_cur_msg) (struct gossiper_s *this); /* 比较gossip */ int (*gossiper_compare_update) (struct host_state_s cur, struct gossiper_s *this); /* 打印gossip信息 */ void (*gossiper_print) (struct gossiper_s *this); /* 析构函数 */ void (*gossiper_destructor) (struct gossiper_s *this); }; void gossiper_open(struct gossiper_s *this); void g_init(struct gossiper_s *this); int g_realloc(struct gossiper_s *this); void g_update(struct host_state_s hs, int idx, struct gossiper_s *this); int g_push(struct host_state_s hs, struct gossiper_s *this); void g_start(struct gossiper_s *this); struct str_s* g_cur_msg(struct gossiper_s *this); int g_compare_update(struct host_state_s cur, struct gossiper_s *this); void g_print(struct gossiper_s *this); void g_destructor(struct gossiper_s *this); void handle_gossip_msg(struct gossiper_s *gs, struct raw_data *msg); // handle_gossip_msg(struct gossiper_s *gs, char *msg) #endif /* GOSSIP_H_ */
C
#include <stdio.h> #include <string.h> int main(){ int origen[] = { 1,2,3,4,5,6,7,8 }; int numero_elementos = sizeof(origen)/sizeof(int); int destino[numero_elementos]; reverti_dos(origen, destino, numero_elementos); } void reverti_dos(int* origen, int*destino,int numero_elementos){ int* ultima_posicion = origen+numero_elementos-1; for(int i=numero_elementos;i>0;i--){ destino = ultima_posicion; printf("destino %d\n",*destino); ultima_posicion--; destino++; } }
C
#include <stdlib.h> #include <string.h> #include <stdio.h> #include "hash_tables.h" /** * main - check the code for Holberton School students. * * Return: Always EXIT_SUCCESS. */ int main(void) { char *value; value = hash_table_get(NULL, "Canada"); printf("%s:%s\n", "Canada", value); return (EXIT_SUCCESS); }
C
#include <stdio.h> #include <time.h> int main() { time_t start, end; double diff; printf("Começando o programa...\n"); time(&start); printf("Dormir por 5 segundos...\n"); sleep(5); time(&end); diff = difftime(end, start); printf("Tempo de execução = %f\n", diff); printf("Saindo do programa...\n"); return 0; } /* DESCRIÇÃO: - A função double difftime(time_t time1, time_t time2) devolve a diferença de segundos entre a time1 e time2 isto é (time1 - time2). - Os dois times estão especificados no tempo do calendário, que representa o tempo decorrido desde a Epoch (00:00:00 de 1 de janeiro de 1970, Tempo Universal Coordenado (UTC)). DECLARAÇÃO: double difftime(time_t time1, time_t time2) PARAMETROS: time1 -- É um objeto do tipo time_t para finalizar o tempo. time2 -- É um objeto do tipo time_t para iniciar o tempo. RETORNO: - Esta função retorna a diferença entre time1 e time2 (time2 - time1) devolvendo um double. */
C
#include <stdio.h> int main() { int a, b, dist; dist = (&b - &a); printf("La distanza tra a e b è: %d byte", (unsigned)dist); *(&b - dist)=34; printf("Valore a: %d", a); return 0; }
C
#include "ErrorHandler.h" /** * 作用: * 显示最后一次函数调用产生的错误消息。 * * 参数: * lpszFunction * 最后一次调用的函数名称。 * * hParent * 弹出消息窗体的父窗体,通常情况下, * 应该指定为我们应用程序的主窗体,这样 * 当消息弹出时,将禁止用户对主窗体进行 * 操作。 * * 返回值: * 无 */ VOID DisplayError(LPWSTR lpszFunction, HWND hParent) { LPVOID lpMsgBuff = NULL; LPVOID lpDisplayBuff = NULL; DWORD errCode = GetLastError(); if (!FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuff, 0, NULL )) { return; } lpDisplayBuff = LocalAlloc( LMEM_ZEROINIT, (((lstrlenW((LPCTSTR)lpMsgBuff))) + lstrlenW((LPCTSTR)lpszFunction) + 40 ) * sizeof(TCHAR) ); if (NULL == lpDisplayBuff) { MessageBox( hParent, TEXT("LocalAlloc failed."), TEXT("ERR"), MB_OK ); goto RETURN; } if (FAILED( StringCchPrintf( (LPTSTR)lpDisplayBuff, LocalSize(lpDisplayBuff) / sizeof(TCHAR), TEXT("%s failed with error code %d as follows:\n%s"), lpszFunction, errCode, (LPTSTR)lpMsgBuff ) )) { goto EXIT; } MessageBox(hParent, lpDisplayBuff, TEXT("ERROR"), MB_OK); EXIT: LocalFree(lpDisplayBuff); RETURN: LocalFree(lpMsgBuff); }
C
/** * Мы знаем, что функции - это поименованные блоки * кода. Функции могут принимать данные и могут возвращать * данные. Функции могут использовать общие данные * посредством глобальных переменных. * Далее рассмотрим: * 1 - использование ключевого слова return для прерывания * работы функции * 2 - передачу массива в качестве параметра */ #include <stdio.h> #include <stdbool.h> /** * Если мы хотим вернуть какое-либо значение из * функции, то внутри функции мы используем * ключевое слово return. Важно знать, что * ключевое слово return не просто устанавливает * желаемые результат, но и полностью завершает * работу функции. Рассмотрим функцию, которая * находит площать треугольника по трём сторонам. * Если три значения не удовлетворяют неравенству * треугольника, то функция возвращает ноль. */ #include <math.h> float triangle_area(float a, float b, float c) { //формулу Герона можно использовать только тогда, когда выполнено неравество треугольника! if (a+b>c && b+c>a && a+c>b) { float p = (a+b+c)/2.f; return sqrt((p-a)*(p-b)*(p-c)*p); } //если неравенство невыполнено, возвращаем ноль else return 0; } /** * Функцию triangle_area можно переписать короче, * воспользовавшись тем, что ключевое слово * return сразу прерывает исполнение, как только * исполнение его достигает. */ float triangle_area_variation(float a, float b, float c) { if (a+b<=c || b+c<=a || a+c<=b)//неравенство треугольника не выполнено return 0; //сработает return, исполнение будут преостановлено, и код не достигнет строчке 46-47, т.е. не будет пытаться вычислять площадь float p = (a+b+c)/2.f; return sqrt((p-a)*(p-b)*(p-c)*p); } /** * return можно использовать для мгновенного * прерывания циклов внутри функции. Рассмотрим * алгоритм "грубой силы" для проверки числа на * простоту. */ bool is_prime(unsigned N) { bool isp = true; //предполагаем, что число простое for (unsigned p = 2; p*p < N; ++p) if(0 == N%p) { isp = false; //раз N делится на p, то оно составное break; //далее проверять делимость смысла нет, число уже составное } return isp; } /** * Вместо создания временного значения isp можно * сразу при обнаружении делителя вернуть false * в качестве результата. */ bool is_prime_variation(unsigned N) { for (unsigned p=2; p*p < N; ++p) if(0 == N%p) return false; //если делитель обнаружен, сразу прерываем функцию и возвращаем false return true; //если ни одного делителя не обнаружено, то число простое } /** * В случае, если функция ничего не возвращает, * то можно прервать её работу с помощью return * без выражения. Рассмотрим задачу: напечатать * число, если оно чётное. */ void print_even(unsigned N) { if (N%2) return; //если число нечётное, то ничего не делаем, покидаем функцию printf("%d\n",N); //чётное число печатаем } /** * Не стоит злоупотреблять такой возможностью! * Если в функции будет много "точек выхода", * то анализ ошибок в такой функции может оказаться * крайне затруднительным! */ /** * Рассмотрим вопрос о передаче массива в функцию. * При работе с массивами мы очень часто совершаем * одни и те же действия, например, печать массива. * Хотелось бы вынести эти действия в функцию, чтобы * можно было просто писать print_arr(numbers). * Для того, чтобы определить массив параметром функции * можно использовать один из трёх способов. */ /** * Точно указать тип элементов и их количество. */ void print_int_arr10(int arr[10]) { //объявление параметра добавляет переменную в блок функции, в данном случае массив из 10 элементов for (unsigned idx = 0; idx != 10; ++idx) printf("%d ",arr[idx]); printf("\n"); } /** * Такая функция сможет принимать массивы из 10 элементов. * Многие компиляторы будут предупреждать о том, что число * элементов не совпадает, однако код по прежнему будет * выполняться. Если в такую функцию передать массив с большим * количеством элементов, то ничего страшного не произойдёт, * просто напечатается часть элементов. Но если массив содержит * меньше элементов, то возникнет Undefined behavior (UB), * неопределённое поведение, вызванное выходом за пределы * массива. Кроме того, в функцию с таким параметром не получится * передать массив, размещённый в динамической памяти. */ /** * Во многих случаях более выгодным является не указывать * длину массива в описании параметра массива, а передать * длину вторым параметром. * Обратим внимание на то, что зная только имя массива нет * возможности узнать его размер, количество элементов! * Необходимо так или иначе передавать его в функцию, * либо указав в описании параметра-массива, либо во * втором параметре! */ void print_int_arr(int arr[], unsigned size) { for (unsigned idx = 0; idx != size; ++idx) printf("%d ",arr[idx]); printf("\n"); } /** * Третий способ - поставить в качестве формального параметра * указатель, адрес. При этом код функции никак не изменится. * Этим способом мы будем часто пользоваться в будущем. */ void print_int_arr_ptr(int *arr, unsigned size) { for (unsigned idx = 0; idx != size; ++idx) printf("%d ",arr[idx]); printf("\n"); } /** * При передаче массива в функцию, следует учитывать, что * работа с массивом несколько отличается от работы с * другими переменными. Если обычные переменные копируются * в функцию, то массивы передаются косвенно, т.к. функция * может не только прочитать данные массива, но и изменить * их! */ void arr_int_double(int arr[], unsigned size) { for (unsigned idx = 0; idx != size; ++idx) arr[idx] *= 2; //мутирующая арифметика перезаписывает данные массива } /** * Функции, которые помимо генерации результата совершают * действия, связанные с косвенным изменением данных, * называются "функции с побочным эффектом". Например, все * функции печати - это функции с побочным эффектом, т.к. * они косвенно меняют данные буфера вывода. * С побочными эффектами следует быть осторожным! * Так как функция может менять данные массива косвенно, * то передать в функцию массив неизменяемых, константных * значений описанными выше способами нельзя. Нужно указать * в параметре, что массив ожидается именно с константными * данными. */ void print_int_arr_const(int const arr[], unsigned size) { for (unsigned idx = 0; idx != size; ++idx) printf("%d ",arr[idx]); printf("\n"); } /** * Иногда наличие побочных эффектов очень удобно! * Например при сортировке. * Или при перестановке элементов между собой. */ void arr_swap_elements(int arr[], unsigned idx1, unsigned idx2) { int tmp = arr[idx1]; arr[idx1] = arr[idx2]; arr[idx2] = tmp; } int main() { if (false) { int a = 1.f, b = 2.f, c = 3.f; printf("area is %f\n",triangle_area(a,b,c)); printf("area is %f\n",triangle_area_variation(a,b,c)); } if(false) { unsigned N = 7179; printf("%u %s prime\n",N,is_prime(N)?"is":"is not"); printf("%u %s prime\n",N,is_prime_variation(N)?"is":"is not"); } if (false) { int arr[10] = {1,2,3,4,5,6,7,8,9,0}; print_int_arr10(arr); //мы указываем только имя массива, никаких дополнительных значков print_int_arr(arr,10); //в параметр массива передаём имя массива, вторым параметром передём размер print_int_arr_ptr(arr,10); //если в качестве формального параметра в функции стоит указатель, то вызов не меняется - передаём имя массива } //вызов функции, косвенно меняющей данные if (false) { int arr[10] = {1,2,3,4,5,6,7,8,9,0}; print_int_arr(arr,10); //массив до вызова функции arr_int_double arr_int_double(arr,10); print_int_arr(arr,10); //массив после вызова функции arr_int_double } if (false) { int const arr[10] = {1,2,3,4,5,6,7,8,9,0}; //print_int_arr(arr,10);//ошибка компиляции! массив неизменяемых данных передаётся в функцию, которая не даёт гарантий неизменяемости print_int_arr_const(arr,10);//всё правильно, функция ожидает массив неизменяемых данных и не сможет поменять данные в массиве } return 0; }
C
#ifndef __PTHREADPOOL_H_ #define __PTHREADPOOL_H_ #include <stdio.h> #include <pthread.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <errno.h> #define DEFAULT_THREAD_VARY 10 #define true 1 #define false 0 typedef struct threadpool_t threadpool_t; typedef struct{ void *(*function)(void *); //函数指针 void *arg; }threadpool_task_t; struct threadpool_t{ pthread_mutex_t lock; pthread_mutex_t thread_counter; pthread_cond_t queue_not_full; pthread_cond_t queue_not_empty; pthread_t *threads; pthread_t adjust_tid; int min_thr_num; int max_thr_num; int live_thr_num; int busy_thr_num; int wait_exit_thr_num; threadpool_task_t *task_queue; int queue_front; int queue_rear; int queue_size; int queue_max_size; int shutdown; }; /** * @function threadpool_create */ extern threadpool_t *threadpool_create(int min_thr_num, int max_thr_num, int queue_max_size); /** * @function */ extern int threadpool_add(threadpool_t *pool, void *(*function)(void *arg), void *arg); /** * @function */ extern int threadpool_destroy(threadpool_t *pool); #endif
C
#include "defs.h" #include "passenger.h" #include "busstop.h" #include <stdlib.h> /*guarantees that every bus has a busstop associated with it*/ extern uint32_t global_bus_busstop; extern pthread_mutex_t lock_bus_busstop; extern uint32_t nthreads_passengers; extern pthread_mutex_t lock_global_passengers; extern pthread_cond_t cond_global_passengers; extern uint32_t passengers_has_busstop; extern pthread_mutex_t lock_passengers_busstop; extern pthread_cond_t cond_passengers_busstop; /** * init_passenger - the main function of the thread passenger. * * @arg: the id of thread passenger. */ void *init_passenger(void *arg) { uint32_t id_pass = (uint32_t) arg; bus_t *src_to_dst = NULL, *dst_to_src = NULL; sched_yield(); /* barrier 1: passenger is entering the wait queue*/ while(passenger_s[id_pass]->status == PASS_BLOCKED_SRC) { acquire_passenger(passenger_s[id_pass]->src, passenger_s[id_pass], PASS_WAIT_SRC); sched_yield(); } down_passengers_bus(); #ifdef DEBUG fprintf(stderr, "thread passenger[%d] created.\n", id_pass); #endif sched_yield(); while (passengers_has_busstop != 0) { pthread_cond_wait(&cond_passengers_busstop, &lock_passengers_busstop); sched_yield(); } /*barrier 2: wait for _all_ bus to be at a busstop*/ while (global_bus_busstop != 0) { pthread_cond_wait(&(cond_bus_busstop), &lock_bus_busstop); sched_yield(); } #ifdef DEBUG fprintf(stderr, "thread passenger[%d]: all bus has been allocated.\n", id_pass); #endif /*just waiting for my time to enter the bus*/ passenger_s[id_pass]->status = PASS_WAIT_SRC; while (passenger_s[id_pass]->status == PASS_WAIT_SRC) { pthread_cond_wait(&(passenger_s[id_pass]->cond_pass_status), &(passenger_s[id_pass]->lock_pass_status)); src_to_dst = acquire_bus(passenger_s[id_pass]->src, passenger_s[id_pass], PASS_BUS_DST); if (src_to_dst) { pthread_cond_signal(&(src_to_dst->cond_counter_seats)); } sched_yield(); } /* * now, the current thread is at bus, for sure * it must sleep until reaches its destiny */ while (passenger_s[id_pass]->status == PASS_BUS_DST) { pthread_cond_wait(&(passenger_s[id_pass]->cond_pass_status), &(passenger_s[id_pass]->lock_pass_status)); sched_yield(); } /* now, the current thread is at destiny, for sure * it must sleep for a random time */ //passenger_s[id_pass]->status = PASS_DST; sleep(passenger_s[id_pass]->sleep_time); /*the travel was pretty good. * but now its time to come back * hell, wait... this queue is so damn big, i _must_ wait for an * empty space for me :( */ passenger_s[id_pass]->status = PASS_BLOCKED_DST; while(passenger_s[id_pass]->status == PASS_BLOCKED_DST) { acquire_passenger(passenger_s[id_pass]->src, passenger_s[id_pass], PASS_WAIT_DST); sched_yield(); } /*hell, finally i got a place to be in taht queue*/ /*now, i am gonna take a nap until bus arrives*/ while (passenger_s[id_pass]->status == PASS_WAIT_DST) { pthread_cond_wait(&(passenger_s[id_pass]->cond_pass_status), &(passenger_s[id_pass]->lock_pass_status)); dst_to_src = acquire_bus(passenger_s[id_pass]->src, passenger_s[id_pass], PASS_BUS_SRC); sched_yield(); } while (passenger_s[id_pass]->status == PASS_BUS_SRC) { pthread_cond_wait(&(passenger_s[id_pass]->cond_pass_status), &(passenger_s[id_pass]->lock_pass_status)); sched_yield(); } /*thanks god i finally cambe back home.*/ /*corresponding struct assumes the KILL status*/ //passenger_s[id_pass]->status = PASS_KILL; /*decrementing global counter of active passengers*/ pthread_mutex_lock(&lock_global_passengers); nthreads_passengers--; pthread_mutex_unlock(&lock_global_passengers); /*thread exited*/ pthread_exit(NULL); return NULL; } /** * passenger_create - allocates and initializes the passenger struct * corresponding to @passenger_thread. * * @passenger_thread: the corresponding thread of to be created struct * * returns a pointer to the created struct or NULL, if any error * occured. */ passenger_t *passenger_create(pthread_t *passenger_thread, uint32_t _id_passenger) { passenger_t *new_pass = NULL; uint32_t pass_src = 0, pass_dst = 0; /*checking parameters*/ CHECK_NULL(passenger_thread, "passenger.c:23: "); if (_id_passenger < 0) { fprintf(stderr, "passenger.c:23: invalid parameter.\n"); return NULL; } new_pass = (passenger_t *) malloc(sizeof(passenger_t)); CHECK_MEMORY(new_pass, "passenger.c:33: "); /*initializng condition variables of passenger status*/ pthread_mutex_init(&(new_pass->lock_pass_status), NULL); pthread_cond_init(&(new_pass->cond_pass_status), NULL); /*initially, passenger is not at bus*/ new_pass->at_bus = ENOATBUS; /*setting initial status of passenger - blocked queue*/ new_pass->status = PASS_BLOCKED_SRC; new_pass->id_passenger = _id_passenger; /*selecting, ramdomly, origin and destin*/ new_pass->src = NULL; new_pass->dst = NULL; while (pass_src == pass_dst) { pass_src = (uint32_t) (random_value() % s); pass_dst = (uint32_t) (random_value() % s); } new_pass->src = (busstop_s[pass_src]); new_pass->dst = (busstop_s[pass_dst]); new_pass->exec_passenger = passenger_thread; /*selecting sleep time at destiny - randomly*/ srand(time(NULL)); new_pass->sleep_time = (uint32_t) (random_value() % 3); /*pointer initialization for time retrive*/ new_pass->in_src_busstop = NULL; new_pass->in_src_bus = NULL; new_pass->in_dst_busstop = NULL; new_pass->out_dst_bus = NULL; new_pass->out_src_bus = NULL; time_t rawtime; time(&rawtime); new_pass->in_src_busstop = localtime(&rawtime); /*mutex and condvar creation - block goint to dst*/ pthread_mutex_init(&(new_pass->lock_bus_dst), NULL); pthread_cond_init(&(new_pass->slp_bus_dst), NULL); return new_pass; } /** * * passenger_destroy - destroys the given @passenger struct and exits * the corresponding thread. */ void passenger_destroy(passenger_t *passenger) { } /** * * do_arrival - takes the @pass passenger from the @_bus and then * inserts into the @stop busstop. * _SHALL ONLY BE USED BY THREAD BUS_ */ uint8_t do_arrival(passenger_t *pass, busstop_t *stop, bus_t *_bus) { CHECK_NULL(pass, "passenger.c:173"); CHECK_NULL(stop, "passenger.c:173"); CHECK_NULL(_bus, "passenger.c:173"); uint8_t is_src = at_origin(pass, _bus); uint8_t is_dst = at_destiny(pass, _bus); if (is_dst) { acquire_passenger(stop, pass, PASS_DST); pthread_cond_signal(&(pass->cond_pass_status)); return 1; } if (is_src) { pass->status = PASS_KILL; pthread_cond_signal(&(pass->cond_pass_status)); return 1; } return 0; } /** * at_origin - checks whether the passenger already came back to * origin place, when still is in bus. * * @pass: passenger to be verified. * @_bus: the stopped bus, which will indicate the busstop where * passenger is at. * * returns 1, if already came back to origin place. * 0, otherwise. */ uint8_t at_origin(passenger_t *pass, bus_t *_bus) { CHECK_NULL(pass, "passenger.c:188: "); CHECK_NULL(_bus, "passenger.c:188 "); busstop_t *where_bus = _bus->critical_stopped; busstop_t *where_pass = pass->src; return (where_bus->id_bustop == where_pass->id_bustop && pass->status == PASS_BUS_SRC); } /** * at_destiny - checks whether the passenger already arrived to * destiny place, when still is in bus. * * @pass: passenger to be verified. * @_bus: the stopped bus, which will indicate the busstop where * passenger is at. * * returns 1, if already arrived to origin place. * 0, otherwise. */ uint8_t at_destiny(passenger_t *pass, bus_t *bus) { CHECK_NULL(pass, "passenger.c:119: "); CHECK_NULL(bus, "passenger.c:119: "); busstop_t *where_bus = bus->critical_stopped; busstop_t *where_pass = pass->dst; return (where_bus->id_bustop == where_pass->id_bustop && pass->status == PASS_BUS_DST); } /** * * self_passenger- gets the corresponding struct passenger of the * current executing thread passenger */ passenger_t *self_passenger(pthread_t *passenger_thread) { CHECK_NULL(passenger_thread, "passennger.c:129: "); return NULL; } inline uint8_t end_of_process(void) { uint8_t retval = 0; pthread_mutex_lock(&lock_global_passengers); retval = ((nthreads_passengers == 0) ? 1: 0); pthread_mutex_unlock(&lock_global_passengers); return retval; } /** * decrements the number of passengers that * still does not have a busstop */ void down_passengers_bus(void) { pthread_mutex_lock(&lock_passengers_busstop); if (passengers_has_busstop > 0) passengers_has_busstop--; pthread_mutex_unlock(&lock_passengers_busstop); if (passengers_has_busstop == 0) { pthread_cond_broadcast(&cond_passengers_busstop); } }
C
#include "acorn-fs.h" int main(int argc, char *argv[]) { if (--argc) { int status; while(argc--) { const char *fsname = *++argv; acorn_fs *fs = acorn_fs_open(fsname, false); if (fs) { int astat = fs->check(fs, fsname, stderr); if (astat != AFS_OK) status++; } else { fprintf(stderr, "afschk: unable to open image file %s: %s\n", fsname, acorn_fs_strerr(errno)); status++; } } acorn_fs_close_all(); return status; } else { fputs("Usage: afschk <acorn-fs-image>\n", stderr); return 1; } }
C
/* Nome: Rafissone Manuel Macilaho Curso: Engenharia Informática - Labora, Nível 3 Cadeira: Inteligência Artificial (INAR) Resolućão da Primeira Tarefa */ #include <stdio.h> #include <stdlib.h> #include <locale.h> //Estrutura de Informacao typedef struct info { int value; }Info; //Estrutura de uma árvore binária typedef struct tree { Info info; struct tree *left; struct tree *right; }Tree; //Funcao que inicializa uma árvore binária Tree *treeInitialize(){ return NULL; } //Funcao que cria um nó de informacao e retorna o nó criado Info infoCreate(){ int cod; printf("\n Informe o valor: "); scanf("%d", &cod); Info item; item.value = cod; return item; } //Funcao que adiciona um nó na árvore e retorna o nó adicionado Tree *treeInsert(Tree *root, Info info){ //Caso a árvore esteja nula, vai-se alocar um espaćo e atribuir a informaćão if(root == NULL){ Tree *auxiliary = (Tree *)malloc(sizeof(Tree)); auxiliary->info = info; auxiliary->left = NULL; auxiliary->right = NULL; return auxiliary; } //Caso a árvore não esteja vazia else{ /*Se o novo valor informado seja maior que o valor anterior da árvore, este será armazenado na sub-árvore a direita*/ if(info.value > root->info.value){ root->right = treeInsert(root->right, info); } /*Se o novo valor informado seja menor que o valor anterior da árvore, este será armazenado na sub-árvore a esquerda*/ else if(info.value < root->info.value){ root->left = treeInsert(root->left, info); } /*Se o novo valor informado seja igua ao valor anterior da árvore, este será ignorado*/ else{ printf("\nEste valor é igaual ao valor anterior da árvore\n"); printf("Valor Ignorado\n"); } } return root; } //Funcao que faz a busca por profundidade da árvore em ordem void treePrintInOrder(Tree *root){ if(root != NULL){ treePrintInOrder(root->left); printf("Informacao: %d\n", root->info.value); treePrintInOrder(root->right); } } //Funcao que faz a busca por profundidade da árvore em pré - ordem void treePrintPreOrder(Tree *root){ if(root != NULL){ printf("Informacao: %d\n", root->info.value); treePrintPreOrder(root->left); treePrintPreOrder(root->right); } } //Funcao que faz a busca por profundidade da árvore em pos - ordem void treePrintPostOrder(Tree *root){ if(root != NULL){ treePrintPostOrder(root->left); treePrintPostOrder(root->right); printf("Informacao: %d\n", root->info.value); } } //Funcao que liberta os nos da arvore void treeFree(Tree *root){ if(root != NULL){ treeFree(root->left); treeFree(root->right); free(root); } }
C
/* Dato un array A di n interi (positivi e negativi), scrivere un programma che identifichi il sottoarray \ di A i cui elementi hanno somma massima tra tutti gli altri sottoarray di A e ne stampi la somma. La prima riga dell’input contiene la dimensione n dell’array. Le righe successive contengono gli elementi dell’array, uno per riga. L’unica riga dell’output contiene il valore della somma del sottoarray disomma massima. */ #include <stdio.h> #include <stdlib.h> int sottArrayMax(int a[], int dim); int main(){ int dim; scanf("%d", &dim); int *arr=(int *) malloc(dim * sizeof(int)); for(int i=0; i<dim; i++){ scanf("%d", &arr[i]); } printf("%d\n", sottArrayMax(arr, dim)); free(arr); return 0; } int sottArrayMax(int a[], int dim){ int max=0, somma=0; for(int i=0; i<dim; i++){ if(somma>0){ somma=somma+a[i]; } else{ somma=a[i]; } if(somma>max){ max=somma; } } return max; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> /*如果是贪婪压缩,设置为1*/ #define GREEDY 0 /* ratio vs. speed constant */ /* 最大匹配滑动窗口大小,越大速度越慢但压缩效果越好*/ #define MAXCOMPARES 75 /* unused entry flag */ #define NIL 0xFFFF /* bits per symbol- normally 8 for general purpose compression */ #define CHARBITS 8 /* minimum match length & maximum match length */ #define THRESHOLD 2 #define MATCHBITS 4 #define MAXMATCH ((1 << MATCHBITS) + THRESHOLD - 1) /* sliding dictionary size and hash table's size */ /* some combinations of HASHBITS and THRESHOLD values will not work correctly because of the way this program hashes strings */ #define DICTBITS 13 #define HASHBITS 10 #define DICTSIZE (1 << DICTBITS) #define HASHSIZE (1 << HASHBITS) /* # bits to shift after each XOR hash */ /* this constant must be high enough so that only THRESHOLD + 1 characters are in the hash accumulator at one time */ #define SHIFTBITS ((HASHBITS + THRESHOLD) / (THRESHOLD + 1)) /* sector size constants */ #define SECTORBIT 10 #define SECTORLEN (1 << SECTORBIT) #define HASHFLAG1 0x8000 #define HASHFLAG2 0x7FFF
C
#include <ctype.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <fcntl.h> #include <unistd.h> #include <math.h> #include <time.h> #include "tar.h" #include "pathTreatement.h" #define BLOCKSIZE 512 /* Replace the cursor at the start of the descriptor */ void replaceCurseurToStart (int fd){ lseek(fd,0,SEEK_SET); } /* Open a archive and print a error if there is a failure */ int openArchive (char * pathname, int flags){ int tmp = open(pathname, flags); if(tmp < 0){ print("Cette archive n'existe pas !\n"); } return tmp; } /* Read 512 bites in the descripteur and initialise it in buffer, the cursor of the descriptor have to be just in front of the header */ int readHeader (int fd, struct posix_header * buffer){ int tmp = read(fd, buffer, BLOCKSIZE); if(tmp < 0) perror("read"); return tmp; } /* Read the content of the header in the descriptor, the cursor of the descriptor have to be just in front of the content */ char * getContent (int fd, struct posix_header * header){ int numberBlock = 0; sscanf(header -> size ,"%o", &numberBlock); numberBlock = (numberBlock + BLOCKSIZE -1) /BLOCKSIZE; char * message =(char *) malloc (sizeof(char) * BLOCKSIZE * numberBlock); read (fd, message, sizeof(char) * BLOCKSIZE * numberBlock); return message; } /* Place the cursor of the descriptor after the content of the header */ void passContent (int fd, struct posix_header * header){ int numberBlock = 0; sscanf(header -> size ,"%o", &numberBlock); numberBlock = (numberBlock + BLOCKSIZE -1) /BLOCKSIZE; lseek(fd, BLOCKSIZE * numberBlock, SEEK_CUR); } /* Read the header and pass the content in one go */ int getHeader(int fd, struct posix_header * header) { int tmp = readHeader(fd, header); if(tmp == BLOCKSIZE) { if(*header->name == '\0') { return -2; } passContent(fd, header); return 0; } return -1; } /* Place the cursor of the descriptor at the end of the archive */ void passArchive(int fd) { replaceCurseurToStart (fd); struct posix_header * h = malloc(BLOCKSIZE); int tmp = getHeader(fd, h); while(tmp == 0) { tmp = getHeader(fd, h); } if(tmp == -2) { lseek(fd, -BLOCKSIZE, SEEK_CUR); } } /* Count the number of file/repertory in the archive */ int numberFileInArchive(int fd) { replaceCurseurToStart (fd); struct posix_header * h = malloc(BLOCKSIZE); int tmp = getHeader(fd, h); int count = 0; while(tmp == 0) { tmp = getHeader(fd, h); count ++; } if(tmp == -2) { lseek(fd, -BLOCKSIZE, SEEK_CUR); } return count; } /* Return the size of a header (after converting it with the Blocksize) */ int getFileSizeFromHeader (struct posix_header * buf){ int numberBlock = 0; sscanf(buf -> size ,"%o", &numberBlock); numberBlock = (numberBlock + 512 -1) /512; return numberBlock * BLOCKSIZE; } /* Search a file with the name in the descriptor, if found return 0 else -1 */ int searchFile (int fd,struct posix_header * buf, char * name){ replaceCurseurToStart (fd); while (getHeader(fd,buf) == 0){ if(strcmp(buf->name, name) == 0){ lseek(fd,-getFileSizeFromHeader(buf),SEEK_CUR); return 0; } } return -1; } /* Search a file with the name in the descriptor, if found return the size of the file else -1 */ int searchFileSize (int fd,struct posix_header * buf, char * name){ size_t size = 0; replaceCurseurToStart (fd); while (getHeader(fd,buf) == 0){ if(strcmp(buf->name, name) == 0){ int numberBlock = 0; sscanf(buf -> size ,"%o", &numberBlock); numberBlock = (numberBlock + 512 -1) /512; size = numberBlock * BLOCKSIZE + (BLOCKSIZE); return size; } } return -1; } /* Verify if destination is a repertory (destination have to be a path in a tarball) */ int isARepertoryInTar (char * destination){ char ** division = dividePathWithTar(duplicate(destination)); int fd = openArchive(division[0], O_RDONLY); struct posix_header * buf = malloc (BLOCKSIZE); searchFile (fd, buf, division[1]); if(buf -> typeflag == '5'){ free(buf); close(fd); return 0; }else{ free(buf); close(fd); return -1; } } /* Verify if destination is a repertory (destination have to be a path outside of a tarball) */ int isARepertoryOutsideTar (char * destination){ struct stat buffer; if (stat(destination,&buffer) == -1) return -1; if ((buffer.st_mode & S_IFMT) == S_IFDIR) return 0; else return -1; } /* Verify if destination is a repertory */ int isARepertory (char * destination){ if(isInTar(destination) == 0){ return isARepertoryInTar(destination); }else{ return isARepertoryOutsideTar (destination); } } /* Test function, not directly used in the project ! Print all the file in the archive with some information */ void printTar (int fd){ printf("Lancement du print\n"); replaceCurseurToStart(fd); struct posix_header * h = malloc (BLOCKSIZE); while (getHeader(fd,h) == 0){ printf("File : %s; Size : %s; FileType : %c;GUD : %s; UID : %s\n",h -> name,h->size, h->typeflag,h -> gid, h -> uid); } replaceCurseurToStart(fd); printf("Fin du print\n"); } /**** Fonction récupérer depuis le TP1 de système ****/ /* Initialise the chksum value for a pre constructed posix_header for the tar*/ void set_checksum(struct posix_header *hd) { memset(hd->chksum,' ',8); unsigned int sum = 0; char *p = (char *)hd; for (int i=0; i < BLOCKSIZE; i++) { sum += p[i]; } sprintf(hd->chksum,"%06o",sum); } /* Check that the checksum of a header is correct */ int check_checksum(struct posix_header *hd) { unsigned int checksum; sscanf(hd->chksum,"%o ", &checksum); unsigned int sum = 0; char *p = (char *)hd; for (int i=0; i < BLOCKSIZE; i++) { sum += p[i]; } for (int i=0;i<8;i++) { sum += ' ' - hd->chksum[i]; } return (checksum == sum); } /* ******************************************************/ /* Create a completely empty posix header */ struct posix_header * createBloc0 (){ struct posix_header * h = malloc (BLOCKSIZE); memset(h,0,BLOCKSIZE); return h; } /* Extract the file type from a mode_t */ char fileType (mode_t mode){ switch (mode & S_IFMT) /* S_IFMT is the mask to have the filetype */ { case S_IFBLK : return BLKTYPE;break; /* block special */ case S_IFCHR : return CHRTYPE;break; /* character special */ case S_IFIFO : return FIFOTYPE;break; /* FIFO special */ case S_IFDIR : return DIRTYPE;break; /* directory */ case S_IFLNK : return LNKTYPE;break; /* link */ default : return REGTYPE; /* regular file */ } } /* Convert a mode_t in a char [12] for the initialisation of a header */ char * convertModeToChar (mode_t mode){ char * buf = malloc (sizeof(char) * 12); sprintf(buf,"%011o",(~S_IFMT & mode)); return buf + 4; } /* Create a header from a stat */ struct posix_header * createHeader (char * name, struct stat information){ struct posix_header * h = createBloc0(); strcpy(h -> name, name); sprintf(h -> mode,"%s",convertModeToChar(information.st_mode)); sprintf(h -> uid,"%d", information.st_uid); sprintf(h -> gid,"%d", information.st_gid); sprintf(h -> size,"%011lo",information.st_size); sprintf(h -> mtime,"%ld",time(NULL)); h -> typeflag = fileType(information.st_mode); sprintf(h -> magic,TMAGIC); sprintf(h -> version,TVERSION); set_checksum(h); if(!check_checksum(h)) perror("Checksum"); return h; } /* Create a header for a folder */ struct posix_header * createHeaderFolder (char * name){ struct posix_header * h = createBloc0(); strcpy(h -> name, name); sprintf(h -> mode,"%s","0000700"); long unsigned int sizeFolder = 0; sprintf(h -> size,"%011lo", sizeFolder); sprintf(h -> mtime,"%ld",time(NULL)); h -> typeflag = '5'; sprintf(h -> magic,TMAGIC); sprintf(h -> version,TVERSION); set_checksum(h); if(!check_checksum(h)) perror("Checksum"); return h; } /* Create a header from the descriptor of the file and initialise it with the new name */ struct posix_header * createHeaderFromFile (int fd, char * newName){ struct stat information; fstat(fd,&information); return createHeader(newName,information); } /* Return the content of fd (a descriptor for the file we want to get the content) */ char * getFileContentForTar (int fd, int * size){ replaceCurseurToStart (fd); struct stat buf; fstat(fd,&buf); *size = ((buf.st_size + BLOCKSIZE -1) /BLOCKSIZE)* BLOCKSIZE; char * content = malloc (*size); memset(content,0,*size); if (read(fd,content,buf.st_size) == -1) perror("GetFileContent"); return content; } /* Add to the archive the file with the header headerfile, the content contentfile and the size size */ void addFileToTar (int archive, struct posix_header * headerfile, char * contentfile, int size){ passArchive(archive); if(write(archive,headerfile,BLOCKSIZE) < 0 || write(archive,contentfile,size) < 0) perror("addFileToTar"); } /* Copy a file in the archive with the new name nametar Warning : archive have to be openned with O_RDWR or it will not succed! FIXME: Verify that the name isn't already here and if the path is valid ! */ void copyFileToTar (int archive, int file,char * nametar){ int size; struct posix_header * headerfile = createHeaderFromFile(file,nametar); char * contentfile = getFileContentForTar(file,&size); addFileToTar(archive,headerfile,contentfile,size); free(headerfile); free(contentfile); } //à tester /* Return the size of the archive from the file path to the end */ size_t getSizeAfterFile (char * path, int fd){ replaceCurseurToStart(fd); struct posix_header * buffer = malloc (BLOCKSIZE); size_t size = 0; if(searchFile (fd, buffer, path) == -1){ //place the cursor on the FilePath free(buffer); return -1; } passContent (fd, buffer); while(getHeader(fd, buffer) == 0){ //start counting int numberBlock = 0; sscanf(buffer -> size ,"%o", &numberBlock); numberBlock = (numberBlock + 512 -1) /512; size += numberBlock * BLOCKSIZE + (BLOCKSIZE); //size content + posix header } free(buffer); return size; } /* Return the size bite of the archive */ char * getContentUntilPathFile(char * path, int fd, size_t size){ replaceCurseurToStart (fd); if (size == -1) print("Fichier introuvable"); char * res = malloc (sizeof(char) * (size)); struct posix_header * buffer = malloc (BLOCKSIZE); searchFile (fd, buffer, path); //place the cursor on the FilePath passContent (fd, buffer); if(read (fd,res,size) < 0) perror("getContentUntilPathFile"); free(buffer); return res; } /* Verify if the file filename is in the repertory repertory */ int isInRepertory (char * repertory, char * filename){ return ( strlen (repertory) < strlen(filename) && strncmp(repertory,filename,strlen(repertory)) == 0 && (numberOfSlash (filename) == numberOfSlash(repertory) || (numberOfSlash (filename) == numberOfSlash(repertory) + 1 && filename[strlen(filename) - 1] == '/'))) ? 0 : -1; } /* Check if a file exist */ int fileExist (char * path){ char * duplicatePath = duplicate (path); if (isInTar(duplicatePath) == 0){ char ** division = dividePathWithTar (duplicatePath); int fd = openArchive(division[0],O_RDWR); if (fd == -1) return -1; struct posix_header * buf = malloc (512); int retour = searchFile(fd,buf,division[1]); close (fd); return retour; }else{ int fd = open(path,O_RDONLY); if (fd == -1) { close (fd); return -1; } close (fd); return 0; } } /* Verify if the repertory have at least one file inside */ int fileInRepertory(int fd, char * repertory){ struct posix_header * buf = malloc(BLOCKSIZE); while(getHeader(fd,buf) == 0 ){ if (isInRepertory(repertory, buf -> name) == 0){ free(buf); return 0; } } free(buf); return -1; } /* Verify if path is the racine of the archive */ int isArchiveRacine (char * path){ if (isInTar(path) == -1) return -1; char * pathAfterTar = dividePathWithTar(duplicate(path))[1]; if (strlen(pathAfterTar) == 0) return 0; return -1; } /* Return the number of argument */ int getArgc (char ** argv){ int i = 0; while (argv[i] != NULL){ i++; } return i; } /* Execute the command defined in the argv */ void executeCommandExterne (char ** argv){ int child = fork (); switch (child){ case -1 : perror ("executeCommandExterne"); break; case 0 ://child if( execvp (argv[0],argv) == -1){ perror ("executeCommandExterne"); exit(0); } break; default ://father wait(NULL); break; } }
C
#include "hashmap.h" #include <stdio.h> #include <stdlib.h> #include <string.h> //Create a hashmap with specified number of buckets struct hashmap* hm_create(int num_buckets){ struct hashmap* hm; hm = malloc(sizeof(struct hashmap)); //Allocate memory for Hashmap hm->map = (struct word_node**)malloc(sizeof(struct word_node*)*num_buckets); //Allocate space for each bucket in map hm->num_buckets = num_buckets; hm->num_docs = 0; int i; for(i=0; i<num_buckets; i++){ (hm->map)[i] = NULL; //Initilize each bucket to null } return hm; } //Put a key value pair into the hashmap //If pair already exists, overwrite num_occurence value void hm_put(struct hashmap* hm, char* word, char* document_id){ //If list has not been initialized, return if(hm == NULL){ printf("Hashmap not initialized\n"); return; } int key = hash(hm, word); //Get key for data pair if((hm->map)[key] == NULL){ //If list has not been initilized, create first node (hm->map)[key] = (struct word_node*)malloc(sizeof(struct word_node)); (hm->map)[key]->word = word; (hm->map)[key]->df = 1; //New word, so doc freq = 1 (hm->map)[key]->next_word = NULL; (hm->map)[key]->next_doc = (struct doc_node*)malloc(sizeof(struct doc_node)); (hm->map)[key]->next_doc->document_id = document_id; (hm->map)[key]->next_doc->num_occurrences = 1; (hm->map)[key]->next_doc->next = NULL; return; } //If word matches list head if(strcmp((hm->map)[key]->word, word) == 0){ struct doc_node* ptr = (hm->map)[key]->next_doc; //If document id matches first document of word if(strcmp(ptr->document_id, document_id) == 0){ ptr->num_occurrences+=1; return; } //Iterate through documents to find matching document while(ptr->next != NULL){ ptr = ptr->next; if(strcmp(ptr->document_id, document_id) == 0){ //printf("%s\n", ptr->document_id); //printf("%d\n",ptr->num_occurrences); ptr->num_occurrences+=1; //printf("%d\n",ptr->num_occurrences); return; } } //If no document matches add a document node (hm->map)[key]->df+=1; //Increment doc requency becasue of new document nodes ptr->next = malloc(sizeof(struct doc_node)); ptr->next->document_id = document_id; ptr->next->num_occurrences = 1; ptr->next->next = NULL; return; } struct word_node* ptr2 = (hm->map)[key]; //Iterate through list to find data pair while(ptr2->next_word != NULL){ ptr2 = ptr2->next_word; //If data matches current node, set num_occurences return if(strcmp(ptr2->word, word) == 0){ struct doc_node* ptr = ptr2->next_doc; //If document id matches first document of word if(strcmp(ptr->document_id, document_id) == 0){ ptr->num_occurrences+=1; return; } //Iterate through documents to find matching document while(ptr->next != NULL){ ptr = ptr->next; if(strcmp(ptr->document_id, document_id) == 0){ ptr->num_occurrences+=1; return; } } //If no document matches add a document node ptr2->df+=1; //Increment doc frequency ptr->next = malloc(sizeof(struct doc_node)); ptr->next->document_id = document_id; ptr->next->num_occurrences = 1; ptr->next->next = NULL; return; } } //If data pair not in list, make new node at end of list ptr2->next_word = malloc(sizeof(struct word_node)); ptr2->next_word->word = word; ptr2->next_word->df = 1; ptr2->next_word->next_word = NULL; ptr2->next_word->next_doc = malloc(sizeof(struct doc_node)); ptr2->next_word->next_doc->document_id = document_id; ptr2->next_word->next_doc->num_occurrences = 1; ptr2->next_word->next_doc->next = NULL; } //Get term frequency of word in a document by finding word/doc id pair int hm_get_tf(struct hashmap* hm, char* word, char*document_id){ //If list has not been initialized, return -1 if(hm == NULL){ printf("Hashmap not initialized\n"); return -1; } int key = hash(hm, word); if((hm->map)[key] == NULL){ //If list head is null, return -1 return -1; } struct doc_node* docptr = (hm->map)[key]->next_doc; //If word is found look for document id if(strcmp((hm->map)[key]->word, word)==0){ while(docptr != NULL){ if(strcmp(docptr->document_id, document_id) == 0){ return docptr->num_occurrences; } docptr = docptr->next; } return -1; } //Iterate through list to find word df struct word_node* ptr = (hm->map)[key]; while(ptr->next_word != NULL){ ptr = ptr->next_word; if(strcmp(ptr->word, word) == 0){ docptr = ptr->next_doc; while(docptr != NULL){ if(strcmp(docptr->document_id, document_id) == 0){ return docptr->num_occurrences; } docptr = docptr->next; } return -1; } } return -1; //if not in list, return -1 } //Get document frequency of word node in map int hm_get_df(struct hashmap* hm, char* word){ //If list has not been initialized, return -1 if(hm == NULL){ printf("Hashmap not initialized\n"); return -1; } int key = hash(hm, word); if((hm->map)[key] == NULL){ //If list head is null, return -1 return -1; } if(strcmp((hm->map)[key]->word, word)==0){ return (hm->map)[key]->df; } //Iterate through list to find word df struct word_node* ptr = (hm->map)[key]; while(ptr->next_word != NULL){ ptr = ptr->next_word; if(strcmp(ptr->word, word) == 0){ return ptr->df; } } return -1; //if not in list, return -1 } //Remove a word node and all its document ndoes, used by stop word in search engine void hm_remove_word(struct hashmap* hm, char* word){ //If hashmap has not been initilizaed, return if(hm == NULL){ printf("Hashmap not initialized\n"); return; } int key = hash(hm, word); //If list has not been initlized, data pair not in list so return if((hm->map)[key] == NULL){ return; } struct word_node* ptr = (hm->map)[key]; struct word_node* ptr2; struct doc_node* docptr; if(strcmp(ptr->word, word)==0){ //set first node to next_doc (hm->map)[key] = ptr->next_word; //remove word and all of its documents docptr = ptr->next_doc; while(docptr != NULL){ struct doc_node* temp = docptr->next; free(docptr); docptr = temp; } free(ptr->word); free(ptr); return; } while(ptr->next_word != NULL){ //if word node is found, remove it and all its documents if(strcmp(ptr->next_word->word, word)==0){ //set next word ptr2 = ptr->next_word; ptr->next_word = ptr->next_word->next_word; //remove all documents docptr = ptr2->next_doc; while(docptr != NULL){ struct doc_node* temp = docptr->next; free(docptr); docptr = temp; } free(ptr2->word); free(ptr2); return; } ptr = ptr->next_word; } } //Free all memory of hashmap void hm_destroy(struct hashmap* hm){ if(hm == NULL){ printf("Hashmap not initialized\n"); return; } int i; //Free every list in map for(i=0; i<hm->num_buckets; i++){ struct word_node* ptr = (hm->map)[i]; while(ptr != NULL){ struct word_node* temp = ptr->next_word; hm_remove_word(hm, ptr->word); ptr = temp; } } //Free map free(hm->map); //free hashmap free(hm); } //take given word and maps them to correct bucket in hashmap //return key int hash(struct hashmap* hm, char* word){ int sum = 0; int key; char* ptr = word; //Add ASCII values of word to sum while(*ptr != '\0'){ sum += *ptr++; } //Key is sum mod 4 key = sum%(hm->num_buckets); return key; } void hm_print(struct hashmap* hm){ if(hm == NULL){ printf("Hashmap not initialized\n"); return; } int i; struct word_node* ptr; struct doc_node* doc; for(i=0; i<hm->num_buckets; i++){ printf("----------Key = %d------------\n", i); ptr = (hm->map)[i]; if(ptr == NULL){ continue; } printf("---Word: %s DF: %d---\n", ptr->word, ptr->df); doc = ptr->next_doc; printf("Doc: %s Count: %d\n", doc->document_id, doc->num_occurrences); while(doc->next != NULL){ doc = doc->next; printf("Doc: %s Count: %d\n", doc->document_id, doc->num_occurrences); } while(ptr->next_word != NULL){ ptr = ptr->next_word; printf("---Word: %s DF: %d---\n", ptr->word, ptr->df); doc = ptr->next_doc; printf("Doc: %s Count: %d\n", doc->document_id, doc->num_occurrences); while(doc->next != NULL){ doc = doc->next; printf("Doc: %s Count: %d\n", doc->document_id, doc->num_occurrences); } } } }
C
/*******************************************/ /* polynomial.c */ /*******************************************/ #include <stdio.h> #include <stdlib.h> #include "list.h" #include "polynomial.h" #include "listinterface.h" extern status read_poly( polynomial *p_poly ) { int coef ; int degree ; if ( init_list(p_poly ) == ERROR ) return ERROR ; do { printf("\tEnter coefficient, degree (0,0) when done ) : " ) ; scanf("%d,%d", &coef, &degree ) ; if ( coef != 0 ) if ( term_insert( p_poly, coef, degree ) == ERROR ) return ERROR ; } while ( coef != 0 || degree != 0 ) ; return OK ; } extern status write_term( term *p_term ) { printf( " + %dx^%d", p_term->coefficient, p_term->degree ) ; return( OK ) ; } extern void write_poly( polynomial poly ) { traverse ( poly, write_term ) ; } extern status add_poly( polynomial *p_poly1, polynomial *p_poly2 ) { list lastreturn = NULL ; list match_node ; term *p_term ; term *p_match_term ; int coef ; int degree ; while ( ( lastreturn = list_iterator( *p_poly1, lastreturn )) != NULL ) { p_term = (term *) DATA( lastreturn ) ; if( find_key( *p_poly2, (generic_ptr)p_term, cmp_degree, &match_node ) == OK ) { p_term = (term *) DATA( match_node ) ; p_term-> coefficient += p_match_term -> coefficient ; delete_node( p_poly2, match_node ) ; free(p_match_term) ; } while (empty_list(*p_poly2)== FALSE ) { if ( term_delete( p_poly2, &coef, &degree ) == ERROR ) return ERROR ; else if ( term_insert( p_poly1, coef, degree ) == ERROR ) return ERROR ; } return OK ; } static int cmp_degree( term *p_term1, term *p_term2 ) { return p_term1->degree - p_term2->degree ; } extern void destroy_poly( polynomial *p_poly ) { destroy( p_poly, free ) ; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <omp.h> #include <cilk/cilk.h> // maximum value of n #define NMAX 75000000 //#define NMAX 200 #define CHUNKSIZE 20 typedef struct{ int lt; int gt; } flag; flag *flags; double *local; int size; // void printArray(int n){ // int j; // printf("["); // int t =0; // for(j = 0; j<n; j++){ // //if(j<10){ // if(t){ // printf(", %f", N[j]); // }else{ // t=1; // printf("%f", N[j]); // } // //} // } // printf("]\n"); // } double drand ( double low, double high ) { return ( (double)rand() * ( high - low ) ) / (double)RAND_MAX + low; } void fillArrayRandom(double *arr, int n){ int j; cilk_for(j = 0; j<n; j++){ double r = drand(0,1000); arr[j]=r; } } int cmpfunc (const void * a, const void * b) { if (*(double*)a > *(double*)b) return 1; else if (*(double*)a < *(double*)b) return -1; else return 0; } void swap(double *xp, double *yp){ double temp = *xp; *xp = *yp; *yp = temp; } // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] // void merge(int l, int m, int r){ // int i, j, k; // int n1 = m - l + 1; // int n2 = r - m; // /* create temp arrays */ // int L[n1], R[n2]; // /* Copy data to temp arrays L[] and R[] */ // for (i = 0; i < n1; i++) // L[i] = N[l + i]; // for (j = 0; j < n2; j++) // R[j] = N[m + 1+ j]; // /* Merge the temp arrays back into arr[l..r]*/ // i = 0; // Initial index of first subarray // j = 0; // Initial index of second subarray // k = l; // Initial index of merged subarray // while (i < n1 && j < n2){ // if (L[i] <= R[j]){ // N[k] = L[i]; // i++; // }else{ // N[k] = R[j]; // j++; // } // k++; // } // /* Copy the remaining elements of L[], if there // are any */ // while (i < n1){ // N[k] = L[i]; // i++; // k++; // } // /* Copy the remaining elements of R[], if there // are any */ // while (j < n2){ // N[k] = R[j]; // j++; // k++; // } // } /* l is for left index and r is right index of the sub-array of arr to be sorted */ // void mergeSortHelper(int l, int r){ // if (l < r){ // int m = l+(r-l)/2; // // Sort first and second halves // mergeSortHelper(l, m); // mergeSortHelper(m+1, r); // merge(l, m, r); // } // } // double mergeSort(int n){ // double t1, t2; // #pragma omp master // t1 = omp_get_wtime(); // mergeSortHelper(0,n-1); // #pragma omp master // t2 = omp_get_wtime(); // return t2-t1; // } // double insertionSort(int n){ // int key, j, i; // double t1, t2; // #pragma omp master // t1 = omp_get_wtime(); // for (i = 1; i < n; i++){ // key = N[i]; // j = i-1; // while (j >= 0 && N[j] > key){ // N[j+1] = N[j]; // j--; // } // N[j+1] = key; // } // #pragma omp master // t2 = omp_get_wtime(); // return t2-t1; // } int partition(double *arr, int p, int r){ double key=arr[r]; int i=p-1; int j; double temp; for(j=p; j<r; j++){ if(arr[j]<=key){ i+=1; temp = arr[i]; arr[i]=arr[j]; arr[j]=temp; } } temp = arr[i+1]; arr[i+1]=arr[r]; arr[r]=temp; return i+1; } // void quickSortHelper(int p, int r){ // if(p<r){ // int q=partition(p,r); // #pragma omp task // { // quickSortHelper(p,q-1); // } // quickSortHelper(q+1,r); // } // } // double sequentialQuickSort(int n){ // double t1, t2; // #pragma omp master // t1 = omp_get_wtime(); // #pragma omp parallel // { // We only want our master thread to be executed once, thus we use the singel construct here. // nowait is used becuse we have no need for synchronization at the end of the region // #pragma omp single nowait // { // quickSortHelper(0, n-1); // } // } // #pragma omp master // t2 = omp_get_wtime(); // return t2-t1; // } void insertionSortHelper(double *arr, int p, int r){ double key; int j, i; for (i = p+1; i<r+1 ; i++){ key = arr[i]; j = i-1; while (j >= p && arr[j] > key){ arr[j+1] = arr[j]; j--; } arr[j+1] = key; } } void prefixSum(int arr[], int p, int r){ int i; for(i=p+1;i<r+1;i++){ arr[i]+=arr[i-1]; } } int log_2(int n){ int i=0; while(n >>= 1) {++i;} return i; } void parallelPrefixSum(int p, int r){ int len = r-p+1; int shift, j, h; int k = log_2(len); for(h=1; h<k+1;h++){ shift = 1<<h; // #pragma omp parallel for schedule(static) private(j) cilk_for (j=1; j<(len/shift)+1;j++){ flags[p+j*shift-1].lt+=flags[p+j*shift-(shift/2)-1].lt; flags[p+j*shift-1].gt+=flags[p+j*shift-(shift/2)-1].gt; } } for(h=k; h>-1;h--){ shift = 1<<h; // #pragma omp parallel for schedule(static) private(j) cilk_for (j=2; j<(len/shift)+1;j++){ if(j%2==1){ flags[p+j*shift-1].lt+=flags[p+j*shift-shift-1].lt; flags[p+j*shift-1].gt+=flags[p+j*shift-shift-1].gt; } } } } int parallelPartition(double *arr, int p, int r){ // printf("p %d r %d\n", p, r); double key=arr[r]; int i,j; double temp; // printf("%d: before first parallel region\n",omp_get_thread_num()); //#pragma omp for schedule(static) private(i) cilk_for (i=p; i<r+1; i++){ flags[i].lt=0; flags[i].gt=0; local[i]=arr[i]; } //#pragma omp for schedule(static) private(i) cilk_for (i = p; i <r; i++){ if(arr[i]<key){ flags[i].lt=1; flags[i].gt=0; }else{ flags[i].lt=0; flags[i].gt=1; } } // printf("before less than: ["); // for(i=p; i<r+1; i++){ // printf("%d, ", lt[i]); // } // printf("]\n"); // printf("before greater than: ["); // for(i=p; i<r+1; i++){ // printf("%d, ", gt[i]); // } // printf("]\n"); // printf("%d: before prefix sum\n",omp_get_thread_num()); parallelPrefixSum(p,r); // prefixSum(lt, p,r); // prefixSum(gt,p,r); // printf("%d: after prefix sum\n",omp_get_thread_num()); //prefixSum(lt, gt, p, r); // printf("after less than: ["); // for(i=p; i<r+1; i++){ // printf("%d, ", lt[i]); // } // printf("]\n"); // printf("after greater than: ["); // for(i=p; i<r+1; i++){ // printf("%d, ", gt[i]); // } // printf("]\n"); int pivot = flags[r].lt; // printf("pivot point is %d\n",pivot); arr[pivot+p]=key; //#pragma omp for schedule(static) private(i) cilk_for (i=p; i<r; i++){ if(local[i]<key){ int index = p+flags[i].lt-1; arr[index]=local[i]; }else{ int index = p+pivot+flags[i].gt; arr[index]=local[i]; } } // printf("%d: after second parallel\n", omp_get_thread_num()); return pivot+p; } void psqHelper(double *arr, int p, int r){ int q; if(p<r){ if(r-p<=50){ insertionSortHelper(arr, p,r); }else{ if(r-p < 0.5*size){ q = partition(arr,p,r); }else{ q=parallelPartition(arr,p,r); } // printf("left p: %d left r: %d\n", p, q-1); // printf("right p: %d right r: %d\n", q+1, r); cilk_spawn psqHelper(arr,p,q-1); psqHelper(arr,q+1,r); } } } double parallelQuickSort(double *arr, int n){ double t1, t2; flags = malloc(sizeof(flag)*n); local = malloc(sizeof(double)*n); int i; cilk_for(i=0; i<n; i++){ local[i]=0; flags[i].lt=0; flags[i].gt=0; } #pragma omp master t1 = omp_get_wtime(); // #pragma omp parallel // { // We only want our master thread to be executed once, thus we use the singel construct here. // nowait is used becuse we have no need for synchronization at the end of the region // #pragma omp single nowait // { psqHelper(arr, 0, n-1); // } // } #pragma omp master t2 = omp_get_wtime(); return t2-t1; } // double selectionSort(int n){ // int j, min_idx,i; // double t1,t2; // #pragma omp master // t1 = omp_get_wtime(); // // One by one move boundary of unsorted subarray // for (i = 0; i < n-1; i++){ // // Find the minimum element in unsorted array // min_idx = i; // for (j = i+1; j < n; j++){ // if (N[j] < N[min_idx]){ // min_idx = j; // } // } // double temp = N[i]; // N[i] = N[min_idx]; // N[min_idx]=temp; // } // #pragma omp master // t2 = omp_get_wtime(); // return t2-t1; // } int checkArray(double *arr, int n){ int j; for(j = 0; j<n-1; j++){ if(arr[j]>arr[j+1]){ return -1; } } return 0; } // void tester(int n){ // srand(getpid()); // fillArrayRandom(n); // printArray(n); // double t = parallelQuickSort(n); // printArray(n); // } int main(int argc, char * argv[]){ FILE* fp = fopen("simTimes.csv","w+"); int len=15; //int len=5; int n[] = {10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000,20000,200000,2000000,20000000,75000000}; int i; srand(getpid()); //tester(10); for(i = 0; i<len; i++){ size = n[i]; double *arr = malloc(sizeof(double)*n[i]); fillArrayRandom(arr, n[i]); //printf("Before for array of size %d:\n", n[i]); //printArray(n[i]); double t = parallelQuickSort(arr, n[i]); printf("%d elements sorted in %f time\n", n[i], t); if(checkArray(arr, n[i])==-1){ printf("SORT FAILED\n"); }else{ printf("SUCCESSFUL SORT\n"); } //printf("after for array of size %d:", n[i]); //printArray(n[i]); } fclose(fp); }
C
// Here's my iteration of the Hangman code. My approach to this is to // count the amount of correct letters contained in the word. // If you feel this code needs to be corrected, don't hesitate // to do so. #include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #define HANGED 6 #ifdef WIN32 #define CLS system("cls") #else #define CLS system("clear") #endif void displayString(char* current, int stringLength) { int i; for (i = 0; i < stringLength; i++) { // If there is no element, make the thing blank if (current[i] == 0) { printf("_"); } //Otherwise, place the letter into the string else { printf("%c", current[i]); } // Include a space between each letter printf(" "); } // Have a new line for the string printf("\n"); } // Displaying the hanging body void displayBody(int correctLetters) { printf("\t\t\t\t\t\tBody: "); switch(correctLetters) { case 1: printf("\t\t O\n"); break; case 2: printf("\t\t O\n"); printf("\t\t\t\t\t\t\t\t |\n"); break; case 3: printf("\t\t O\n"); printf("\t\t\t\t\t\t\t\t /|\n"); break; case 4: printf("\t\t O\n"); printf("\t\t\t\t\t\t\t\t /|\\\n"); break; case 5: printf("\t\t O\n"); printf("\t\t\t\t\t\t\t\t /|\\\n"); printf("\t\t\t\t\t\t\t\t /\n"); break; case 6: printf("\t\t O\n"); printf("\t\t\t\t\t\t\t\t /|\\\n"); printf("\t\t\t\t\t\t\t\t /\\\n"); break; default: return; } } // The searching prototype that Frank made. I made it into an int // function to count the variable incase it was found once. int checkChar(const char* answer, char* current, char guess) { int found = 0; int i; int length = strlen(answer); for (i = 0; i < length; i++) { if (answer[i] == guess) { found++; current[i] = guess; } } return found; } // Printing the wrong character array void wrongLetterDisplay(char *wrong) { int i; int length = strlen(wrong); for (i = 0; i < length; i++) { printf("%c", wrong[i]); printf(" "); } printf("\n"); } // Inserting the wrong letter into the wrong letter array. void wrongLetterFunction(char *wrong, char input) { int i; for (i = 0; i < HANGED; i++) { if (input == wrong[i]) break; else { wrong[strlen(wrong)] = input; break; } } } // Make a boolean function to make sure that the // letter guess is not contained in the wrong letter array. bool checkWrongLetter(char *wrong, char input) { bool check = false; int i = 0; for (i = 0; i < HANGED; i++) { if (wrong[i] == input) { check = true; } } return check; } int main(void) { // This is the char *stringGuess = "guess"; char *stringRight; char input, letter; // "Alphabet" is the wrong array. char *stringWrong; // i is the for loop, guessLen is for the length of the actual word // alphabetLetters is the length of the incorrect array // correctGuess is to equal the guess length of the word. // correctLetters is the amount of times a correct letter is found, // which will be added to correctGuess after going through the word. int i, guessLen, alphabetLetters = 0, correctGuess = 0, correctLetters = 0; int wrongGuess = 0, lives = 6; printf("Welcome to Hangman\n"); guessLen = strlen(stringGuess); // Dynamically Allocate the word to fit the thing itself. stringRight = malloc(sizeof(char) * (guessLen + 1)); stringWrong = calloc(sizeof(char), HANGED + 1); while (correctLetters < guessLen) { CLS; // display the wrong letter array after each input wrongLetterDisplay(stringWrong); // Display the string displayString(stringRight, guessLen); printf("Please input a character: "); input = tolower(getchar()); // This is to remove the extra newline from scanf // 10 is a newline. while (getchar() != 10); // Increment letter if it a letter is found; alphabetLetters = checkChar(stringGuess, stringRight, input); // If there are no letters found from the guessed character, // we increment the wrongGuess variable. if (alphabetLetters != 0) { correctLetters += alphabetLetters; } else { printf("Sorry, Wrong Letter. Please try again.\n"); // Checking to see if the input is already in the wrong character array. // If not, we increment the wrongGuess variable and add the character into the array. if (!checkWrongLetter(stringWrong, input)) { wrongGuess++; wrongLetterFunction(stringWrong, input); } displayBody(wrongGuess); // If the amount of lives and the amount of wrong guesses equal // zero, we end the loop and immediately give the GAME OVER screen if (lives - wrongGuess != 0) printf("Lives left: %d\n", lives - wrongGuess); else break; getchar(); while(getchar() != 10); } } displayString(stringRight, guessLen); // Free memory from the guessed string printf("GAME OVER\n"); // Free both the correct / wrong strings. free(stringRight); free(stringWrong); return 0; }
C
//Ajout bibliothèque #include <stdio.h> #include <wchar.h> #include <locale.h> #include <string.h> #include <stdlib.h> #include "fonctions.h" //Programme main int main(void){ struct lconv *loc; setlocale (LC_ALL, ""); loc=localeconv(); // Déclaration des variables wchar_t message[300]={0}; wchar_t messageSansAccent[300]={0}; wchar_t messageConvertie[300]={0}; wchar_t min[]=L"abcdefghijklmnopqrstuvwxyz"; wchar_t maj[]=L"ABCDEFGHIJKLMNOPQRSTUVWXYZ"; wchar_t accent[]=L"ÀÁÂÃÄÅàáâãäåÇçÈÉÊËèéêëÌÍÎÏìíîïÑñÒÓÔÕÖòóôõöÙÚÛÜùúûüÝýÿ"; int choixAlgo,clefC,choixRF; wchar_t clefV[300]={0}; // Cartouche cartourche(); // Demande de saisir le message wprintf(L"\n\n ----------- La saisie du message -----------\n\n"); wprintf(L" Saisir votre message : "); fgetws(message,300,stdin); // Vérification caractère non autoriser while(nonAutoriser(message,min,maj,accent)==2){ wprintf(L"\n ! ERREUR ! : caractere non autorise "); wprintf(L"\n Ressaisir votre message : "); fgetws(message,300,stdin); } // Convertion message if(verifExistaccent(message,accent)==1){ wprintf(L"\n Votre message contient des accents. \n"); wprintf(L" Convertion en cour ... \n\n"); }else{ wprintf(L"\n Votre message ne contient pas d'accent. \n"); } convertionMessage(message,messageSansAccent,maj,min); wprintf(L"\n Votre message : %ls \n",messageSansAccent); // Choix de l'algorithme wprintf(L"\n ----------- La saisie de l'algorithme -----------\n"); wprintf(L"\n Veuillez choisir un algorithme : \n"); wprintf(L" 1) Chiffrement Cesar \n"); wprintf(L" 2) Dechiffrement Cesar\n"); wprintf(L" 3) Chiffrement Vigenere\n"); wprintf(L" 4) Dechiffrement Vigenere\n"); wprintf(L"\n Saisir votre algorithme : "); wscanf(L"%d",&choixAlgo); // Verification while(choixAlgo<1 || choixAlgo>4){ wprintf(L"\n ! ERREUR ! : Votre choix doit etre 1, 2 ou 3 \n"); wprintf(L" Ressaisir votre choix : "); wscanf(L"%d",&choixAlgo); } wprintf(L"\n Votre choix : %d \n",choixAlgo); //selection de l'algoritme switch(choixAlgo){ case 1: wprintf(L"\n ----------- Chiffrement Cesar ----------- \n"); wprintf(L"\n Saisir la clef : "); wscanf(L"%d",&clefC); wprintf(L"\n Votre Clef : %d \n\n",clefC); cesar(messageSansAccent,messageConvertie,min,maj,clefC); wprintf(L" Votre message convertie: %ls \n\n",messageConvertie); break; case 2: wprintf(L"\n ----------- Dechiffrement Cesar ----------- \n"); wprintf(L"\n Saisir la clef : "); wscanf(L"%d",&clefC); wprintf(L"\n Votre Clef : %d \n\n",clefC); cesarDechiffrement(messageSansAccent,messageConvertie,min,maj,clefC);; wprintf(L" Votre message convertie: %ls \n",messageConvertie); break; case 3: wprintf(L"\n ----------- Chiffrement Vigenere ----------- \n"); wprintf(L"\n Saisir la clef(un mot) : "); wscanf(L"%ls",&clefV); wprintf(L"\n Votre Clef : %ls \n",clefV); vigenere(messageSansAccent,min,maj,messageConvertie,clefV); wprintf(L" Votre message convertie: %ls \n",messageConvertie); break; case 4: wprintf(L"\n ----------- Dechiffrement Vigenere ----------- \n"); wprintf(L"\n Saisir la clef(un mot) : "); wscanf(L"%ls",&clefV); wprintf(L"\n Votre Clef : %ls \n",clefV); vigenereDechiffrement(messageSansAccent,min,maj,messageConvertie,clefV); wprintf(L" Votre message convertie: %ls \n",messageConvertie); break; default: break; } //proposer à l'utilisateur de mettre le resultat dans un fichier wprintf(L"\n ----------- Resultat dans un fichier .txt ----------- \n"); wprintf(L"\n Voulez-vous mettre le resultat dans un fichier votreConvertion.txt ? \n"); wprintf(L" Taper 0 pour oui.\n"); wprintf(L" Taper 1 pour non.\n"); wprintf(L"\n Votre reponse : "); wscanf(L"%d",&choixRF); // Verification while(choixRF<0 || choixRF>1){ wprintf(L"\n ! ERREUR ! : Votre choix doit 0(pour oui) ou 1(pour non) !-\n"); wprintf(L" Ressaisir votre choix : "); wscanf(L"%d",&choixRF); } // Resultat dans un fichier if(choixRF==0){ FILE* fichier = NULL; fichier = fopen("votreConvertion.txt", "a"); switch(choixAlgo){ case 1: fwprintf(fichier,L"\n\n ------ Chiffrement Cesar ------\n\n"); fwprintf(fichier,L" Votre message : %ls \n",messageSansAccent); fwprintf(fichier,L" Votre Clef : %d \n",clefC); fwprintf(fichier,L" Votre message convertie: %ls \n",messageConvertie); break; case 2: fwprintf(fichier,L"\n ------ Dechiffrement Cesar ------\n\n"); fwprintf(fichier,L" Votre message : %ls \n",messageSansAccent); fwprintf(fichier,L" Votre Clef : %d \n",clefC); fwprintf(fichier,L" Votre message convertie: %ls \n",messageConvertie); break; case 3: fwprintf(fichier,L"\n ------ Chiffrement Vigenere ------\n\n"); fwprintf(fichier,L" Votre message : %ls \n",messageSansAccent); fwprintf(fichier,L" Votre Clef : %ls \n",clefV); fwprintf(fichier,L" Votre message convertie: %ls \n",messageConvertie); break; case 4: fwprintf(fichier,L"\n ------ Dechiffrement Vigenere ------\n\n"); fwprintf(fichier,L" Votre message : %ls \n",messageSansAccent); fwprintf(fichier,L" Votre Clef : %ls \n",clefV); fwprintf(fichier,L" Votre message convertie: %ls \n",messageConvertie); break; default: break; } fclose(fichier); } wprintf(L"\n ----------- FIN DU PROGRAMME -----------\n"); }
C
#include<stdio.h> #include<unistd.h> int main() { int no; printf("Parent %d \n",getpid()); no=fork(); if(no!=0) { printf("Parent PID %d \n",no); } return 0; }
C
#include "./public.h" #include "./list.h" char *myGets(char *src, int size) { char *dest = src; for(; dest<src+size-1; ) { *dest = getchar(); if(*src == '\n') continue; if(*dest == '\n') break; dest++; } if(*dest != '\n') while(getchar() != '\n'); *dest = '\0'; return src; } int initTime(Times *times) { printf("输入年份:"); scanf("%d",&times->year); getchar(); if(1 > times->year) return 0; printf("输入月份:"); scanf("%d",&times->month); getchar(); if(0 > times->month || 12 < times->month) return 0; printf("输入日期:"); scanf("%d",&times->day); getchar(); if(0 > times->day || 31 < times->day) return 0; return 1; } void setTime(Times *times) { while(!initTime(times)) printf("\n时间输入错误,请重新输入\n"); return; } void putTime(Times times) { printf("\t%d年%d月%d号",times.year,times.month,times.day); return; } int putInt() { int num = 0; scanf("%d",&num); getchar(); return num; } int setID() { printf("彩票ID:"); int ID = putInt(); return ID; } int setAccount() { printf("账户:"); int account = putInt(); return account; } int setPwd() { printf("密码:"); int pwd = putInt(); return pwd; } int setNum() { printf("购买数量:"); int num = putInt(); return num; } char * setName(char *str) { printf("用户名:"); return myGets(str,SIZE); } int setMoney() { printf("设置金额:"); int money = putInt(); return money; } char myGetc() //只获取一个字符 { char ch= getchar(); while(getchar()!='\n') ; return ch; } void anyKey() //在清屏前暂停显示 { printf("\n按任意键继续..\n"); if('\n' == getchar()) return; else { getchar(); return; } } void printState(bool a,int b) //彩票的几种状态的打印方式 { if(a == false){ if(0 == b) printf("false"); else printf("$:%d",b); } else printf("true "); return; }
C
//----------------------------------------------------------------- // rLCDҲյ{ // 䤤LCD_Display_String()@|ܤ@r // LCD_Display_Word()@|ܤ@Ӧr //----------------------------------------------------------------- #include <reg51.h> //------------------------------------------------------- void delay_time(int); void LCD_COMMAND(char); void LCD_Clear(void); void LCD_Home(void); void LCD_INIT(void); void LCD_Display_Word(char); void LCD_Display_String(char *s1); void LCD_ADDRESS(char,char); //------------------------------------------------------ // LCD ҲI/Owq sbit RW = P1^1; // a sbit RS = P1^0; sbit EN = P2^5; sbit K1 = P3^4; sbit K2 = P3^5; #define LCD_DATA P0 // DB0-DB7 //------------------------------------------------------- // LCD ]wɶ |HۤPCPUu@Wv(t)ӧ #define d_time 3000 //------------------------------------------------------------------ // ]wɶ(rLCDҲթҨϥ) //------------------------------------------------------------------ void delay_time(int k) { while (k>0) k--; } //------------------------------------------------------- // ]w LCD Module RO //------------------------------------------------------- void LCD_COMMAND(char temp) { RW =0; RS=0; // ]wsROȦs LCD_DATA=temp; // eXLCDROr EN=1; delay_time(d_time); EN=0; } //---------------------------------------------------- // MLCDRAM //---------------------------------------------------- void LCD_Clear(void) { LCD_COMMAND(0x01); } //---------------------------------------------------- // LCDk //---------------------------------------------------- void LCD_Home(void) { LCD_COMMAND(0x02); } //--------------------------------------------------- // bLCDWܤ@Ӧr //--------------------------------------------------- void LCD_Display_Word(char LCD_WORD) { RS = 1; RW = 0; // ]wsƼȦs LCD_DATA=LCD_WORD; // eXLCDƦr EN=1; delay_time(d_time); EN=0; } //--------------------------------------------------- // bLCDWܤ@Ӧr // Example: s1="LCD TEST\0"; // rפŸ'\0' //--------------------------------------------------- void LCD_Display_String(char *s1) { unsigned char i; for (i=0;i<50;i++){ if (*(s1+i)=='\0') break; //P_rO_wgǰe LCD_Display_Word(*(s1+i)); } } //--------------------------------------------------- // l]wLCD Module //--------------------------------------------------- void LCD_INIT (void) { int i; RW=0; // LCD gJҦ EN=0; delay_time(d_time); // delay_time(d_time); // LCD_COMMAND(0x30); // m LCD LCD_COMMAND(0X01); // MLCDRAM for(i=0;i<10;i++) // ]wɶ delay_time(d_time); LCD_COMMAND(0x3f); // ]wLCDC ,Ƭ8bits, 5*7r // LCD_COMMAND(0x0f); // |{{ LCD_COMMAND(0x0c); // L |{{ // LCD_COMMAND(0x0e); // |{{ LCD_COMMAND(0x06); // ]wLCD۰ʼW[Ҧ delay_time(d_time); LCD_Clear(); //MLCDRAM LCD_Home(); //LCDk /* 122~127 Od䥦{ϥ */ // LCD_Display_String(String1); //String1[]r // LCD_ADDRESS(2,1); //]wLCDЦ}AĤGCĤ@ // for (i=0;i<16;i++) // LCD_Display_Word(String2[i]); //ܤ@Ӧr } //---------------------------------------------------- // ]wLCDЦ} // C(row) : 1,2 // (column) : 1,16 //---------------------------------------------------- void LCD_ADDRESS(char row, char column) { unsigned char tmp1; int i; // 16*2 LCD Module Address // row_1=> 80 81 82 83 84 85 86 87 88 89 8a 8b 8c 8d 8e 8f // row_2=> c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 ca cb cc cd ce cf tmp1=(row-1)*0x40+(column-1)+0x80; //pXLCDҲդЬ۹} for (i=0;i<10;i++) // ]wɶ delay_time(d_time); LCD_COMMAND(tmp1); // ]w LCD Ц} for (i=0;i<10;i++) delay_time(d_time); // ɶ } /*------------------------------------------------------------------ // rLCDҲմեD{ //ӵ{|brLCDҲܨⵧrA| // | ICCI | // | www.icci.com.tw | //䤤LCD_Display_String()@|ܤ@r //LCD_Display_Word()@|ܤ@Ӧr --------------------------------------------------------------------*/
C
/************************************************ * bigE.c * Purpose: to print one E letter, consisting of '*', * with a height of seven stars, and a width of five stars. * Line 1: five stars * Line 2: one star * Line 3: one star * Line 4: five stars * Line 5: one star * Line 6: one star * Line 7: five stars * ********************************************/ #include <stdio.h> int main() { printf("*****\n"); printf("*\n"); printf("*\n"); printf("*****\n"); printf("*\n"); printf("*\n"); printf("*****\n"); }
C
#include <stdio.h> int main(int argc, char const *argv[]) { int horizontal, vertical, gabriel_vertical, gabriel_horizontal, possibilidade = 4; scanf("%d %d", &vertical, &horizontal); char labirinto[vertical][horizontal]; for(int i = 0; i < vertical; i++){ char labirinto_horizontal[horizontal]; scanf("%s", labirinto_horizontal); for(int j = 0; j < horizontal; j++){ labirinto[i][j] = labirinto_horizontal[j]; } } for(int i = 0; i < vertical; i++){ for(int j = 0; j < horizontal; j++){ if (labirinto[i][j] == 'G'){ gabriel_vertical = i; gabriel_horizontal = j; } } } while(labirinto[gabriel_vertical][gabriel_horizontal] != 'S' && possibilidade != 0){ if (labirinto[gabriel_vertical][gabriel_horizontal+1] != 'T' && gabriel_horizontal+1 < horizontal){ labirinto[gabriel_vertical][gabriel_horizontal] = 'T'; gabriel_horizontal++; }else{ if (labirinto[gabriel_vertical][gabriel_horizontal-1] != 'T' && gabriel_horizontal-1 >= 0){ labirinto[gabriel_vertical][gabriel_horizontal] = 'T'; gabriel_horizontal--; }else{ if(labirinto[gabriel_vertical-1][gabriel_horizontal] != 'T' && gabriel_vertical-1 >= 0){ labirinto[gabriel_vertical][gabriel_horizontal] = 'T'; gabriel_vertical--; }else{ if(labirinto[gabriel_vertical+1][gabriel_horizontal] != 'T' && gabriel_vertical+1 < vertical){ labirinto[gabriel_vertical][gabriel_horizontal] = 'T'; gabriel_vertical++; }else{ possibilidade = 0; } } } } } if(labirinto[gabriel_vertical][gabriel_horizontal] == 'S'){ printf("sim\n"); }else{ printf("nao\n"); } return 0; }
C
#include "stackt.h" #include <stdio.h> int main () { Stack S,T; CreateEmpty(&S); CreateEmpty(&T); int m,n,x,x2,x3; scanf("%d",&m); scanf("%d",&n); if (m==0 && n==0) { printf("Sama\n"); } else { int i=1; while (i<=m) { scanf("%d",&x); if ((x!=0)) { if (!(IsFull(S))) { Push(&S,x); } } else { if ((!IsEmpty(S))) { Pop(&S,&x); } } i++; } int j=1; while (j<=n) { scanf("%d",&x2); if ((x2!=0)) { if (!(IsFull(T))) { Push(&T,x2); } } else { if ((!IsEmpty(T))) { Pop(&T,&x2); } } j++; } if (IsSame(S,T)) { printf("Sama\n"); } else { printf("Tidak sama\n"); } } return 0; }
C
// // main.c // ifndef // // Created by João Dematé Jr 🤠 on 27/05/20. // Copyright © 2020 João Dematé Jr 🤠. All rights reserved. // /* CONSTANTES IFNDEF DIRETIVA DE COMPILAÇÃO */ #include <stdio.h> #ifndef PI #define PI 3.14567 #endif int main() { // insert code here... int valor = 5; printf("O valor é %d \n", valor); printf("PI vale %f \n", PI); return 0; }
C
/* * Tutorial 4 Jeopardy Project for SOFE 3950U / CSCI 3020U: Operating Systems * * Copyright (C) 2018, Clyve Widjaya 100590208 * Fawwaz Khayyat 100568635 * All rights reserved. * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include "questions.h" #include "players.h" #include "jeopardy.h" // Put macros or constants here using #define #define BUFFER_LEN 256 #define NUM_PLAYERS 4 // Put global environment variables here // Processes the answer from the user containing what is or who is and tokenizes it to retrieve the answer. void tokenize(char *input, char **tokens); // Displays the game results for each player, their name and final score, ranked from first to last place void show_results(struct player *players); bool game_state; int main(int argc, char *argv[]){ // An array of 4 players, may need to be a pointer if you want it set dynamically struct player players[NUM_PLAYERS]; int playerIndex = 0; int dollarValue; char *category = (char *) calloc(BUFFER_LEN, sizeof(char)); char *playerName = (char *) calloc(BUFFER_LEN, sizeof(char)); // Buffer for user input char buffer[BUFFER_LEN] = { 0 }; // Display the game introduction and initialize the questions initialize_game(); // Prompt for players names for (int i = 0; i < NUM_PLAYERS; i++){ printf("Player %i name: ", i+1); scanf("%s", playerName); if (!player_exists(players, NUM_PLAYERS, playerName)){ strcpy(players[i].name, playerName); } else { printf("Name exists, enter new name!\n"); i--; } } // initialize each of the players in the array for (int i = 0; i < NUM_PLAYERS; i++){ players[i].score = 0; } // Perform an infinite loop getting command input from users until game ends game_state = true; int notAnswered = NUM_QUESTIONS; while (game_state){ int count = 0; printf("\n"); display_categories(); printf("\n%s's turn to play!\n", players[playerIndex].name); printf("Enter category you want to answer > "); scanf("%s", category); printf("Enter dollar value you want > "); scanf("%i", &dollarValue); int c; while ((c = getchar()) != EOF && c != '\n'); if (already_answered(category, dollarValue)){ playerIndex--; } else { display_question(category, dollarValue); printf("start your answer with 'what is' or 'who is' >"); fgets(buffer, BUFFER_LEN, stdin); char *token; tokenize(buffer, &token); if (valid_answer(category, dollarValue, token)){ printf("Correct Answer\n"); notAnswered--; update_score(players, NUM_PLAYERS, players[playerIndex].name, dollarValue); playerIndex--; } else { printf("Wrong answer, you suck\n"); } } if (notAnswered == 0){ show_results(players); game_state = false; } if (playerIndex != 4){ playerIndex++; } else { playerIndex = 0; } //game_state = false; } return EXIT_SUCCESS; } void show_results(struct player *players){ for (int i = 0; i < NUM_PLAYERS; i++){ printf("Player %d, %s\n", i+1, players[i].name); printf("Score: %d\n\n", players[i].score); } } void tokenize(char *input, char **tokens){ printf("|%s|\n", input); //printf("|%s,%s,%s|\n", &tokens[0], &tokens[1], &tokens[2]); const char delims[2] = " \n"; char *tok; /* get the first token */ tok = strtok(input, delims); int num_tokens = 1; /* Assuming the third word is the start of the answer */ while(tok != NULL && num_tokens <=2){ tok = strtok(NULL,delims); num_tokens++; } *tokens = tok; }
C
/* * Copyright (c) 2016 Siguza */ #ifndef ARCH_H #define ARCH_H #include <stdbool.h> // bool #include <stdint.h> // uint32_t #include <mach/machine.h> // cpu_type_t, cpu_subtype_t typedef uint32_t arch_t; #define ARCH_UNKNOWN ((arch_t)0x0) #define ARCH_I386 ((arch_t)0x1) #define ARCH_X86_64 ((arch_t)0x2) #define ARCH_ARMV7 ((arch_t)0x4) #define ARCH_ARMV7S ((arch_t)0x8) #define ARCH_ARMV7K ((arch_t)0x10) #define ARCH_ARM64 ((arch_t)0x20) #define ARCH_ARM64E ((arch_t)0x40) #define ARCH_ARM64_32 ((arch_t)0x80) #define ARCH_MIN ARCH_I386 #define ARCH_MAX ARCH_ARM64_32 #define FOR_ARCH_IN(dst, src) for(arch_t dst = ARCH_MIN; dst <= ARCH_MAX; dst <<= 1) if((src & dst) > 0) const char* strArch(arch_t arch); arch_t cpu2arch(cpu_type_t cpu, cpu_subtype_t sub); bool isArch64(arch_t arch); #endif
C
#include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node *next; }Node; Node *head = NULL; Node *tail = NULL; int main() { int choice; void create_list(); void insertAtBeg(); void insertAtEnd(); void insertAtPos(); void deleteAtBeg(); void deleteAtEnd(); void deleteAtPos(); void display_list(); void display_list_pos(); void search(); int countNodes(Node *head); printf("\nCircular Singly Linked List\n"); printf("\n1.Create List"); printf("\n2.Display List"); printf("\n3.Insert at beginning"); printf("\n4.Insert at end"); printf("\n5.Insert after a node"); printf("\n6.Delete at beginning"); printf("\n7.Delete at end"); printf("\n8.Delete at position"); printf("\n9.Display List from a position"); printf("\n10.Search for an element"); printf("\n11.Count no. of nodes"); printf("\n12.Exit\n"); while(1) { printf("\nEnter your choice: "); scanf("%d",&choice); switch(choice) { case 1: create_list(); break; case 2: display_list(); break; case 3: insertAtBeg(); break; case 4: insertAtEnd(); break; case 5: insertAtPos(); break; case 6: deleteAtBeg(); break; case 7: deleteAtEnd(); break; case 8: deleteAtPos(); break; case 9: display_list_pos(); break; case 10: search(); case 11: countNodes(head); break; case 12: exit(0); } } return(0); } void create_list() { int c; Node *temp, *n; do{ n = (struct node*)malloc(sizeof(struct node)); printf("\nEnter the data: "); scanf("%d", &n->data); n->next = n; if(head == NULL) { head = tail = temp = n; } else { temp->next = n; temp = temp->next; } temp->next = head; tail = temp; printf("\nEnter your choice to continue press 1 otherwise 0: "); scanf("%d",&c); }while(c!=0); } void display_list() { Node *temp; temp = head; if (temp == NULL) printf("\nList is empty"); else { while (temp->next != head) { printf("%d->", temp->data); temp = temp->next; } printf("%d", temp->data); } } void insertAtBeg() { Node *temp; temp = (Node *)malloc(sizeof(Node)); printf("Enter the element: "); scanf("%d",&temp->data); temp->next = tail->next; tail->next = temp; head = temp; } void insertAtEnd() { Node *temp; temp = (Node *)malloc(sizeof(Node)); printf("\nEnter the element: "); scanf("%d",&temp->data); temp->next = tail->next; tail->next = temp; tail = temp; } void insertAtPos() { Node *temp,*t; int key; t = tail->next; printf("Enter the key after which new node to be inserted: "); scanf("%d",&key); do{ if(t->data == key) { temp = (Node *)malloc(sizeof(Node)); printf("Enter the element to be inserted: "); scanf("%d",&temp->data); temp->next = t->next; t->next = temp; if(t == tail) tail = temp; return; } t = t->next; }while(t != tail->next); printf("\n%d not present in the list\n",key); } void deleteAtBeg() { Node *temp = tail->next; head = temp->next; tail->next = temp->next; free(temp); } void deleteAtEnd() { Node *temp, *p; p = tail->next; while(p->next != tail) { p = p->next; } p->next = tail->next; temp = tail; tail = p; free(temp); } void deleteAtPos() { Node *prev, *temp; int i=1,pos; printf("Enter the position of node to be deleted: "); scanf("%d",&pos); temp = tail->next; while(i < pos) { prev = temp; temp = temp->next; ++i; } prev->next = temp->next; if(temp == tail) tail = prev; free(temp); } void display_list_pos() { int n, i=1; Node *temp, *halt; temp = head; printf("Enter the start position: "); scanf("%d",&n); if (temp == NULL) printf("\nList is empty"); else { while(i<n) { temp = temp->next; ++i; } halt = temp; while (temp->next != halt) { printf("%d->", temp->data); temp = temp->next; } printf("%d", temp->data); } } void search() { Node *temp; int item,i=0,flag=1; temp = head; if(temp == NULL) { printf("\nEmpty List\n"); } else { printf("\nEnter item which you want to search?\n"); scanf("%d",&item); if(head ->data == item) { printf("item found at location %d",i+1); flag=0; } else { while (temp->next != head) { if(temp->data == item) { printf("item found at location %d ",i+1); flag=0; break; } else { flag=1; } i++; temp = temp -> next; } } if(flag != 0) { printf("Item not found\n"); } } } int countNodes(Node* head) { Node* temp = head; int result = 0; if (head != NULL) { do { temp = temp->next; result++; } while (temp != head); } printf("Total number of node is :%d",result); }
C
#include <stdio.h> #include <limits.h> #include <errno.h> #include <string.h> #include <xlib/xerr.h> #include <xlib/xalloc.h> static void * xalloc_do_alloc(xalloc_t *xa, size_t size) { xalloc_ops_t *ops = XALLOC_OPS(xa); if (ops->op_alloc == NULL) { return NULL; } return (*ops->op_alloc)(xa, size); } static void xalloc_do_free(xalloc_t *xa, void *ptr) { xalloc_ops_t *ops = XALLOC_OPS(xa); if (ops->op_free == NULL) { return; } (*ops->op_free)(xa, ptr); } void * xalloc_alloc(xalloc_t *xa, size_t size) { return xalloc_do_alloc(xa, size); } void xalloc_free(xalloc_t *xa, void *ptr) { xalloc_do_free(xa, ptr); }
C
// BranchingFunctionsDelays.c Lab 6 // Runs on LM4F120/TM4C123 // Use simple programming structures in C to // toggle an LED while a button is pressed and // turn the LED on when the button is released. // This lab will use the hardware already built into the LaunchPad. // Daniel Valvano, Jonathan Valvano // January 15, 2016 // Modified by Zhanglulucat during studying the edX powered MOOC: UTAustinX-UT.6.03x-Embedded-Systems---Shape-the-World, at Mar. 2016. // built-in connection: PF0 connected to negative logic momentary switch, SW2 // built-in connection: PF1 connected to red LED // built-in connection: PF2 connected to blue LED // built-in connection: PF3 connected to green LED // built-in connection: PF4 connected to negative logic momentary switch, SW1 #include "TExaS.h" #define GPIO_PORTF_DATA_R (*((volatile unsigned long *)0x400253FC)) #define GPIO_PORTF_DIR_R (*((volatile unsigned long *)0x40025400)) #define GPIO_PORTF_AFSEL_R (*((volatile unsigned long *)0x40025420)) #define GPIO_PORTF_PUR_R (*((volatile unsigned long *)0x40025510)) #define GPIO_PORTF_DEN_R (*((volatile unsigned long *)0x4002551C)) #define GPIO_PORTF_AMSEL_R (*((volatile unsigned long *)0x40025528)) #define GPIO_PORTF_PCTL_R (*((volatile unsigned long *)0x4002552C)) #define SYSCTL_RCGC2_R (*((volatile unsigned long *)0x400FE108)) #define SYSCTL_RCGC2_GPIOF 0x00000020 // port F Clock Gating Control // basic functions defined at end of startup.s void DisableInterrupts(void); // Disable interrupts void EnableInterrupts(void); // Enable interrupts //claim subroutine void Delay100ms(unsigned long time); void PortF_Init(void); //Global var unsigned long In; //Input from PF4 unsigned long Out; //Output to PF2 int main(void){ TExaS_Init(SW_PIN_PF4, LED_PIN_PF2); // activate grader and set system clock to 80 MHz PortF_Init(); // initialization goes here EnableInterrupts(); // enable interrupts for the grader while(1){ Delay100ms(1); // Delay about 100 ms In = GPIO_PORTF_DATA_R&0x10; //Read the switch and test if the switch is pressed Out = GPIO_PORTF_DATA_R&0x04; //Read the output to PF2 if (In == 0x00) { //If PF4=0 (the switch is pressed), GPIO_PORTF_DATA_R ^= 0x04; //toggle PF2 (flip bit from 0 to 1, or from 1 to 0) } else { //If PF4=1 (the switch is not pressed), GPIO_PORTF_DATA_R |= 0x04; //set PF2, so LED is ON } } } void Delay100ms(unsigned long time){ unsigned long i; while(time > 0){ i = 1333333; // this number means 100ms while(i > 0){ i = i - 1; } time = time - 1; // decrements every 100 ms } } void PortF_Init(){ unsigned long volatile delay; SYSCTL_RCGC2_R |= SYSCTL_RCGC2_GPIOF; //Turn on the clock for Port F (page 338: bit5 is for PF in RCGCGPIO) delay = SYSCTL_RCGC2_R; //dummy delay for clock stablize GPIO_PORTF_AMSEL_R = 0x00; //Clear the PF4 and PF2 bits in Port F AMSEL to disable analog (page 684) GPIO_PORTF_PCTL_R = 0x00000000; //Clear the PF4 and PF2 bit fields in Port F PCTL to configure as GPIO (page 685) GPIO_PORTF_DIR_R = 0x04; //Set the Port F direction register so PF4 is an input and PF2 is an output (page 660) GPIO_PORTF_AFSEL_R = 0x00; //Clear the PF4 and PF2 bits in Port F AFSEL to disable alternate functions (page 668) GPIO_PORTF_DEN_R = 0x14; //Set the PF4 and PF2 bits in Port F DEN to enable digital (page 680) GPIO_PORTF_PUR_R = 0x10; //Set the PF4 bit in Port F PUR to activate an internal pullup resistor GPIO_PORTF_DATA_R |= 0x04; //Set the PF2 bit in Port F DATA so the LED is initially ON }
C
/* Practice 5: Dot Product Name : Obed N Munoz /Lecturer : */ #include <stdio.h> #include <omp.h> #define SIZE 10000 int main () { int i, size, chunk; float array_a[SIZE], array_b[SIZE], result; size = SIZE; chunk = 10; result = 0.0; printf("\n Initializing Vectors of size [%d]\n", size); for (i=0; i < size; i++) { array_a[i] = i * 3.0; array_b[i] = i * 7.0; } printf("\nStarting Dot Product ...\n"); double start = omp_get_wtime(); #pragma omp parallel for \ default(shared) private(i) \ schedule(static,chunk) \ reduction(+:result) for (i=0; i < size; i++) result += (array_a[i] * array_b[i]); double end = omp_get_wtime(); printf("\nDot Product FINISHED\n"); printf("\nFinal result= %f\n",result); printf("\nTime = %f\n",end - start); return 0; }
C
/* Exam 1 Programmer: Andrew Stake Class: CS2 Professor: Dr. Lee File Created: Feb 28, 2017 File Updated: Feb 28, 2017 */ #include<stdio.h> int main(int argc, char *argv[]) { char tbt[2][2]; //creates array for question int i, j; //count variables for(i = 0; i < 2; i++) { for(j = 0; j < 2; j++) { tbt[i][j] = ((i + j) % 2 ? 'A' : 'B'); //if i plus j is even a B is stored there, if odd, an A is stored printf("%c", tbt[i][j]); } } printf("\n"); return 0; }
C
/* ** my_putstr.c for my_roulette in /home/m4t/etna/my_roulette/ ** ** Made by Mathieu Robardey ** Login <[email protected]> ** ** Started on Thu May 14 21:39:30 2015 Mathieu Robardey ** Last update Thu May 14 21:39:30 2015 Mathieu Robardey */ #include "my.h" void my_putstr(char *str) { int i; i = 0; while (str[ i ] != '\0') { my_putchar(str[ i ]); i++; } }
C
#include <mach/mach.h> #include <mach/mach_time.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <errno.h> #include <string.h> static inline uint64_t rdtsc(void) { uint32_t lo, hi; asm volatile("rdtsc" : "=a" (lo), "=d" (hi)); return (uint64_t)hi << 32 | lo; } __attribute__((noinline)) void apply_p(void (^b)(size_t), size_t offset, size_t count) { /* This would feed through to the existing dispatch_apply() */ abort(); } /* a dynamically variable to eventually be added to the kernel/user 'commpage' */ size_t total_active_cpus = 8; __attribute__((noinline)) void apply(void (^b)(size_t), size_t offset, size_t count) { const size_t too_long = 100000; /* 100 us */ const size_t laps = 16; uint64_t delta, tmp, now; size_t i; if (total_active_cpus == 1) { for (i = 0; i < count; i++) { b(offset + i); } return; } now = mach_absolute_time(); for (i = 0; i < count; i++) { b(offset + i); if (i % laps) { continue; } tmp = mach_absolute_time(); delta = tmp - now; now = tmp; if (delta > (too_long * laps) || (i == 0 && delta > too_long)) { apply_p(b, offset + i + 1, count - (i + 1)); return; } } } int main(void) { void (^b)(size_t) = ^(size_t index) { asm volatile(""); /* defeat compiler optimizations */ }; const size_t laps = 10000000; mach_timebase_info_data_t tbi; kern_return_t kr; long double dd; uint64_t s, e; size_t i; kr = mach_timebase_info(&tbi); assert(kr == 0); assert(tbi.numer == tbi.denom); /* This will fail on PowerPC. */ s = mach_absolute_time(); for (i = 0; i < laps; i++) { b(i); } e = mach_absolute_time(); dd = e - s; dd /= laps; printf("direct:\t%Lf ns\n", dd); s = mach_absolute_time(); apply(b, 0, laps); e = mach_absolute_time(); dd = e - s; dd /= laps; printf("apply:\t%Lf ns\n", dd); return 0; }
C
#include<stdio.h> #include<string.h> int soma_asc(char nome[],int tamNome){ int soma=0; int asc[tamNome]; for(int i=0;i<tamNome;i++){ asc[i] = nome[i]; } for(int i=0;i<tamNome;i++){ soma+=asc[i]; } return soma; } int main(void){ char nome[20]; scanf("%[^\n] ",nome); int tamNome = strlen(nome); int soma = soma_asc(nome,tamNome); printf("%d\n" , (soma%50)); return 0; }
C
#include <stdio.h> #include "status.h" Status GameStatus; /*** Konstruktor ***/ void InitGameStatus (int NBPeta, int NKPeta, int NBangunan) { /* I.S. GameStatus sembarang */ /* F.S. Status GameStatus terdefinisi */ /* Proses: Melakukan alokasi, memanfaatkan konstruktor tiap komponen Status. ActivePlayer = 1. Turn = 1. */ // Algoritma MakeMatriks(NBPeta, NKPeta, &Peta(GameStatus)); MakeEmptyGraph(&Adjacency(GameStatus)); MakeEmptyStack(&StatusPemain(GameStatus)); MakeEmptyTabSkill(&S1(GameStatus)); MakeEmptyTabSkill(&S2(GameStatus)); ActivePlayer(GameStatus) = 1; Turn(GameStatus) = 1; } /*** Setup ***/ void SetupConfigGameStatus(char * ConfigPath, int * error) { /* I.S. GameStatus terdefinisi Isi file config terdefinisi, jumlah bangunan >= 2, ukuran map valid */ /* F.S. Isi GameStatus sesuai dengan config */ /* Proses: Melakukan setup GameStatus sesuai isi file di ConfigPath */ // Kamus lokal int i, j, X, Y; Graph G; // Algoritma // Inisialisasi mesin kata STARTKATA(ConfigPath, error); if ((*error) != 0) { return; } // Ukuran peta NBPeta(GameStatus) = KataToInt(CKata); ADVKATA(); NKPeta(GameStatus) = KataToInt(CKata); ReadNextLine(); // Jumlah bangunan NBangunan(GameStatus) = KataToInt(CKata); ReadNextLine(); // Inisialisasi GameStatus InitGameStatus(NBPeta(GameStatus), NKPeta(GameStatus), NBangunan(GameStatus)); // Read bangunan MakeEmptyTab(&T(GameStatus), NBangunan(GameStatus)); for (i = 1; i <= NBangunan(GameStatus); i++) { CopyBangunan(&ElmtTab(T(GameStatus), i), ParseInputBangunan(i)); ReadNextLine(); } Pemilik(ElmtTab(T(GameStatus), 1)) = 1; Pemilik(ElmtTab(T(GameStatus), 2)) = 2; // Assign ID bangunan ke Peta(GameStatus) for (i = 1; i <= NBPeta(GameStatus); i++) { for (j = 1; j <= NKPeta(GameStatus); j++) { ElmtMatriks(Peta(GameStatus), i, j) = 0; } } for (i = 1; i <= NBangunan(GameStatus); i++) { X = Absis(Lokasi(ElmtTab(T(GameStatus), i))); Y = Ordinat(Lokasi(ElmtTab(T(GameStatus), i))); ElmtMatriks(Peta(GameStatus), X, Y) = i; } // Inisialisasi Queue Skill MakeEmptyQueue(&Q1(GameStatus), 10); AddElQueue(&Q1(GameStatus), INSTANT_UPGRADE); MakeEmptyQueue(&Q2(GameStatus), 10); AddElQueue(&Q2(GameStatus), INSTANT_UPGRADE); // Adjacency matriks MakeEmptyGraph(&G); for (i = 1; i <= NBangunan(GameStatus); i++) { for (j = 1; j < NBangunan(GameStatus); j++) { if (KataToInt(CKata) == 1) InsertElGraph(&G, i, j); ADVKATA(); } if (KataToInt(CKata) == 1) InsertElGraph(&G, i, j); ReadNextLine(); } // Assign Graph G ke Adjacency(GameStatus) CopyGraph(&Adjacency(GameStatus), G); } Bangunan ParseInputBangunan(int ID) { /* Mengembalikan Bangunan sesuai input pada file Format input: "Tipe Lokasi(X) Lokasi(Y)" CKata awal ada di Tipe, CKata akhir ada di Lokasi(Y) */ // Kamus lokal char Tipe; int X, Y; // Algoritma // Tipe Tipe = Char(CKata, 1); ADVKATA(); // Lokasi X = KataToInt(CKata); ADVKATA(); Y = KataToInt(CKata); return(MakeBangunan(ID, Tipe, MakePoint(X, Y))); } /*** Save dan Load Game ***/ void SaveGameStatus(char * SavePath) { /* I.S. GameStatus terdefinisi */ /* F.S. Isi GameStatus tersimpan dalam file di SavePath */ /* Proses: Melakukan penulisan isi GameStatus ke file di GameStatus Tidak menyimpan status undo */ // Kamus lokal FILE * file; Bangunan B; Queue Q; ElTypeQueue QX; int i, j; // Algoritma // Buka file file = fopen(SavePath, "w"); // Print ukuran peta fprintf(file, "%d %d\n", NBPeta(GameStatus), NKPeta(GameStatus)); // Print jumlah bangunan dan list bangunan fprintf(file, "%d\n", NBangunan(GameStatus)); for (i = 1; i <= NBangunan(GameStatus); i++) { B = ElmtTab(T(GameStatus), i); fprintf(file, "%c %d %d\n", Tipe(B), Absis(Lokasi(B)), Ordinat(Lokasi(B))); } // Print matriks adjacency for (i = 1; i <= NBangunan(GameStatus); i++) { for (j = 1; j < NBangunan(GameStatus); j++) { if (AdaEdge(Adjacency(GameStatus), i, j)) { fprintf(file, "%d ", 1); } else { fprintf(file, "%d ", 0); } } if (AdaEdge(Adjacency(GameStatus), i, j)) { fprintf(file, "%d\n", 1); } else { fprintf(file, "%d\n", 0); } } // Print jumlah bangunan, kemudian status non default bangunan fprintf(file, "%d\n", NBangunan(GameStatus)); for (i = 1; i <= NBangunan(GameStatus); i++) { B = ElmtTab(T(GameStatus), i); fprintf(file, "%d %d %d %d\n", Pemilik(B), Level(B), Pasukan(B), SudahSerang(B)); } // Print jumlah queue dan list skill 1 CopyQueue(&Q, Q1(GameStatus)); fprintf(file, "%d\n", NBElmtQueue(Q1(GameStatus))); if (NBElmtQueue(Q1(GameStatus)) == 0) { fprintf(file, "0\n"); } else { for (i = 1; i < NBElmtQueue(Q1(GameStatus)); i++) { DelElQueue(&Q, &QX); fprintf(file, "%d ", QX); } DelElQueue(&Q, &QX); fprintf(file, "%d\n", QX); } // Print jumlah queue dan list skill 2 CopyQueue(&Q, Q2(GameStatus)); fprintf(file, "%d\n", NBElmtQueue(Q2(GameStatus))); if (NBElmtQueue(Q2(GameStatus)) == 0) { fprintf(file, "0\n"); } else { for (i = 1; i < NBElmtQueue(Q2(GameStatus)); i++) { DelElQueue(&Q, &QX); fprintf(file, "%d ", QX); } DelElQueue(&Q, &QX); fprintf(file, "%d\n", QX); } // Print tab skill 1 for (i = 1; i < MaxElTabSkill; i++) { fprintf(file, "%d ", ElmtS1(GameStatus, i)); } fprintf(file, "%d\n", ElmtS1(GameStatus, i)); // Print tab skill 2 for (i = 1; i < MaxElTabSkill; i++) { fprintf(file, "%d ", ElmtS2(GameStatus, i)); } fprintf(file, "%d\n", ElmtS2(GameStatus, i)); // Print active player fprintf(file, "%d\n", ActivePlayer(GameStatus)); // Print turn fprintf(file, "%d\n", Turn(GameStatus)); // Tutup file fclose(file); } void LoadGameStatus(char * LoadPath, int * error) { /* I.S. GameStatus terdefinisi Isi file load terdefinisi, jumlah bangunan >= 2, ukuran map valid */ /* F.S. Isi GameStatus sesuai dengan load */ /* Proses: Melakukan setup GameStatus sesuai isi file di LoadPath Memanfaatkan prosedur SetupConfigGameStatus */ // Kamus lokal int N, i; // Algoritma // Setup awal (dari ukuran peta sampai matriks adjacency) SetupConfigGameStatus(LoadPath, error); if ((*error) != 0) { return; } // Setup tambahan // Bangunan // Jumlah bangunan N = KataToInt(CKata); ReadNextLine(); // Status bangunan for (i = 1; i <= N; i++) { // Pemilik Pemilik(ElmtTab(T(GameStatus), i)) = KataToInt(CKata); ADVKATA(); // Level Level(ElmtTab(T(GameStatus), i)) = KataToInt(CKata); AssignProperti(&ElmtTab(T(GameStatus), i)); ADVKATA(); // Pasukan Pasukan(ElmtTab(T(GameStatus), i)) = KataToInt(CKata); ADVKATA(); // SudahSerang SudahSerang(ElmtTab(T(GameStatus), i)) = KataToInt(CKata); ReadNextLine(); } // Queue list 1 // Jumlah skill N = KataToInt(CKata); ReadNextLine(); // Reset skill default lalu assign skill hasil load MakeEmptyQueue(&Q1(GameStatus), 10); if (N > 0) { for (i = 1; i < N ; i++) { AddElQueue(&Q1(GameStatus), KataToInt(CKata)); ADVKATA(); } AddElQueue(&Q1(GameStatus), KataToInt(CKata)); } ReadNextLine(); // Queue list 2 // Jumlah skill N = KataToInt(CKata); ReadNextLine(); // Reset skill default lalu assign skill hasil load MakeEmptyQueue(&Q2(GameStatus), 10); if (N > 0) { for (i = 1; i < N ; i++) { AddElQueue(&Q2(GameStatus), KataToInt(CKata)); ADVKATA(); } AddElQueue(&Q2(GameStatus), KataToInt(CKata)); } ReadNextLine(); // Tab skill 1 for (i = 1; i < MaxElTabSkill; i++) { ElmtS1(GameStatus, i) = KataToInt(CKata); ADVKATA(); } ElmtS1(GameStatus, i) = KataToInt(CKata); ReadNextLine(); // Tab skill 2 for (i = 1; i < MaxElTabSkill; i++) { ElmtS2(GameStatus, i) = KataToInt(CKata); ADVKATA(); } ElmtS2(GameStatus, i) = KataToInt(CKata); ReadNextLine(); // Active player ActivePlayer(GameStatus) = KataToInt(CKata); ReadNextLine(); // Turn Turn(GameStatus) = KataToInt(CKata); ReadNextLine(); }
C
#include <stdio.h> int main() { float a,b,c,area,perimetro; scanf("%f %f %f",&a,&b,&c); if ((a+b)>c && (a+c)>b && (b+c)>a){ perimetro=(a+b+c); printf("Perimetro = %.1f\n",perimetro); } else{ area = ((a+b)*c)/2; printf("Area = %.1f\n",area); } return 0; }
C
#include "win_functions.h" #include "_cgo_export.h" #include <tlhelp32.h> boolean UpdateLoading = FALSE; // Shuts down the program void Exit() { //if (!ExitCalled){ Shell_NotifyIcon(NIM_DELETE, &nIconData); FreeMenuIfNecessary(); UnhookWindowsHookEx(KeyboardHook); UnhookWindowsHookEx(MouseHook); //} //ExitCalled = TRUE; PostQuitMessage(0); } // Uses SendInput to emulate a keyboard press void PressKeyboardKey(char key){ INPUT ip; ip.type = INPUT_KEYBOARD; ip.ki.wVk = key; ip.ki.wScan = 0; ip.ki.dwFlags = 0; ip.ki.time = 0; ip.ki.dwExtraInfo = 0; SendInput(1, &ip, sizeof(INPUT)); ip.ki.dwFlags = KEYEVENTF_KEYUP; SendInput(1, &ip, sizeof(INPUT)); } // Copys an item to clipboard. // Used instead of SendInput ctrl+c, due to it being faster in this case. void ItemToClipboard(){ HWND foreground = GetForegroundWindow(); if (foreground){ SendMessage(foreground, WM_KEYDOWN, 67, 0); SendMessage(foreground, WM_KEYUP, 67, 0); } } // Checks whether the Current active window is called "Path of Exile" boolean IsPoEActive(){ HWND foreground = GetForegroundWindow(); if (foreground){ char window_title[18]; GetWindowText(foreground, window_title, 18); if (!strcmp(window_title , "Path of Exile")){ return TRUE; } } return FALSE; } // Called whenever user presses a keyboard key. // Checks whether poe is running, if so checks item on hotkey pressed and evaluates it. LRESULT CALLBACK LowLevelKeyboardProc( int nCode, WPARAM wParam, LPARAM lParam ){ char pressedKey; // Declare a pointer to the KBDLLHOOKSTRUCTdsad KBDLLHOOKSTRUCT *pKeyBoard = (KBDLLHOOKSTRUCT *)lParam; switch( wParam ) { case WM_KEYDOWN: // When the key has been pressed down { //get the key code pressedKey = (char)pKeyBoard->vkCode; if ((pressedKey == -94) || (pressedKey == -93)){ //Ctrl CtrlPressed = TRUE; } } break; case WM_KEYUP: { //get the key code pressedKey = (char)pKeyBoard->vkCode; if ((pressedKey == -94) || (pressedKey == -93)){ //Ctrl CtrlPressed = FALSE; }else if (pressedKey == 68){ //d){ if (CtrlPressed && IsPoEActive()){ POINT p; GetCursorPos(&p); //Copy item to clipboard ItemToClipboard(); //Read from Clipboard Sleep(5); HANDLE h; if (!OpenClipboard(NULL)){ return CallNextHookEx( NULL, nCode, wParam, lParam); } h = GetClipboardData(CF_TEXT); const char* output = evaluateItem((char*)h); const size_t len = strlen(output) + 1; HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, len); memcpy(GlobalLock(hMem), output, len); GlobalUnlock(hMem); EmptyClipboard(); SetClipboardData(CF_TEXT, hMem); CloseClipboard(); if (len > 1) { PressKeyboardKey(VK_RETURN); PressKeyboardKey(65); //ctrl+a PressKeyboardKey(86); //ctrl+v PressKeyboardKey(VK_RETURN); }else if (UseDoubleclick){ mouse_event(MOUSEEVENTF_LEFTDOWN, p.x, p.y, 0, 0); mouse_event(MOUSEEVENTF_LEFTUP, p.x, p.y, 0, 0); } } } } break; } // return CallNextHookEx( NULL, nCode, wParam, lParam); } // Starts the listening for userinput. void InstallHooks(){ KeyboardHook = SetWindowsHookEx( WH_KEYBOARD_LL, LowLevelKeyboardProc, hInstance,0); //MouseHook = SetWindowsHookEx( WH_MOUSE_LL, LowLevelMouseProc, hInstance,0); } void ShowMenu(){ POINT p; GetCursorPos(&p); if (go_NeedsReload()){ CreateCustomMenu(); } SetForegroundWindow(hwnd); // Win32 bug work-around TrackPopupMenu(hMenu, TPM_BOTTOMALIGN | TPM_LEFTALIGN, p.x, p.y, 0, hwnd, NULL); } void FreeMenuIfNecessary(){ if (hMenu){ DestroyMenu(hMenu); hMenu = NULL; } } void CreateCustomMenu(){ FreeMenuIfNecessary(); hMenu = CreatePopupMenu(); HMENU hFilterSubMenu = CreatePopupMenu(); HMENU hOptionsSubMenu = CreatePopupMenu(); char *currFilter = go_GetCurrentFilterName(); //Main Menu AppendMenu(hMenu, MF_STRING | MF_GRAYED, 0, VERSION); //AppendMenuW(hSubMenu, MF_SEPARATOR, 0, NULL); //AppendMenuW(hSubMenu, MF_STRING, CMD_ABOUT, L"About"); AppendMenuW(hMenu, MF_STRING | MF_POPUP, (UINT_PTR)hFilterSubMenu, L"Filer"); AppendMenuW(hMenu, MF_STRING | MF_POPUP, (UINT_PTR)hOptionsSubMenu, L"Options"); AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL); AppendMenuW(hMenu, MF_STRING, CMD_EXIT, L"Exit"); //Sub Menu of Filters AppendMenuW(hFilterSubMenu, MF_STRING, CMD_FILTER_RELOAD, L"Reload current filter"); AppendMenuW(hFilterSubMenu, MF_SEPARATOR, 0, NULL); int count = 0; char* name = go_GetNextFilterName(); while ((strlen(name) > 0) && (count < 50)){ if (strcmp(name , currFilter) == 0){ AppendMenu(hFilterSubMenu, MF_STRING | MF_CHECKED, (UINT_PTR)hFilterSubMenu, name); }else{ AppendMenu(hFilterSubMenu, MF_STRING, CMD_FILTERSELECT_START+count, name); } free(name); name = go_GetNextFilterName(); count++; } free(name); AppendMenuW(hFilterSubMenu, MF_SEPARATOR, 0, NULL); if (strlen(currFilter) > 0){ AppendMenuW(hFilterSubMenu, MF_STRING, CMD_FILTER_NONE, L"None"); }else{ AppendMenuW(hFilterSubMenu, MF_STRING | MF_CHECKED, CMD_FILTER_NONE, L"None"); } free(currFilter); //Sub Menu of Options if (UseDoubleclick){ AppendMenuW(hOptionsSubMenu, MF_STRING | MF_CHECKED, CMD_OPTIONS_USEDOUBLECLICK, L"Send Doubleclick"); }else{ AppendMenuW(hOptionsSubMenu, MF_STRING, CMD_OPTIONS_USEDOUBLECLICK, L"Send Doubleclick"); } if (CheckForUpdates){ AppendMenuW(hOptionsSubMenu, MF_STRING | MF_CHECKED, CMD_OPTIONS_CHECKUPDATES, L"Check for updates"); }else{ AppendMenuW(hOptionsSubMenu, MF_STRING, CMD_OPTIONS_CHECKUPDATES, L"Check for updates"); } if (LaunchPoE){ AppendMenuW(hOptionsSubMenu, MF_STRING | MF_CHECKED, CMD_OPTIONS_LAUNCHPOE, L"Launch PoE on start"); }else{ AppendMenuW(hOptionsSubMenu, MF_STRING, CMD_OPTIONS_LAUNCHPOE, L"Launch PoE on start"); } // SetForegroundWindow(hWnd); // Win32 bug work-around // TrackPopupMenu(hMenu, TPM_BOTTOMALIGN | TPM_LEFTALIGN, p.x, p.y, 0, hWnd, NULL); } // Creates a Window and sets global hwnd to it. void InitializeWindow(){ // Register the window class. LPCTSTR CLASS_NAME = "PoEPricer Window Class"; WNDCLASS wc = { }; wc.lpfnWndProc = WindowProc; wc.hInstance = hInstance; wc.lpszClassName = CLASS_NAME; RegisterClass(&wc); // Create the window. hwnd = CreateWindowEx( 0, // Optional window styles. CLASS_NAME, // Window class "PoEPricer", // Window text WS_OVERLAPPEDWINDOW, // Window style // Size and position //CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0,0,0,0, NULL, // Parent window NULL, // Menu hInstance, // Instance handle NULL // Additional application data ); if (hwnd == NULL) { Exit(); } ShowWindow(hwnd, FALSE); } // Set in Initialize Window, receives WindowMessages (like when to show popup menu) LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam){ switch (uMsg) { case WM_DESTROY: Exit(); return 0; case WM_COMMAND: if( wParam == CMD_EXIT){ Exit(); return 0; }else if( wParam == CMD_FILTER_NONE){ go_LoadFilterByIndex(-1); }else if( wParam == CMD_FILTER_RELOAD){ go_ReloadFilter(); }else if( wParam == CMD_OPTIONS_USEDOUBLECLICK){ UseDoubleclick = !UseDoubleclick; go_SetUseDoubleclick(UseDoubleclick); }else if( wParam == CMD_OPTIONS_CHECKUPDATES){ CheckForUpdates = !CheckForUpdates; go_SetCheckForUpdates(CheckForUpdates); }else if( wParam == CMD_OPTIONS_LAUNCHPOE){ LaunchPoE = !LaunchPoE; go_SetLaunchPoE(LaunchPoE); }else if(wParam >= CMD_FILTERSELECT_START && wParam < CMD_FILTERSELECT_START+50){ go_LoadFilterByIndex(wParam - CMD_FILTERSELECT_START); } /*switch (LOWORD(wParam)) { case CMD_EXIT: }*/ case WM_POEPRICERMESSAGE: if (lParam == WM_RBUTTONUP){ ShowMenu(); return 0; } break; } return DefWindowProc(hwnd, uMsg, wParam, lParam); } // Creates the window needed for popup menu, then registers a tray icon, as well as // making sure to receive WM_POEPRICERMESSAGE whenever icon is rightclicked. void ShowTrayIcon(){ //Get a window for our tray InitializeWindow(); // Exits if it fails //Load icon image HICON hIcon; hIcon = LoadImage(NULL, "data/icon.ico", IMAGE_ICON, 64, 64, LR_LOADFROMFILE); //hIcon = LoadImage(NULL, IDI_INFORMATION, IMAGE_ICON, 16, 16, LR_SHARED); //Initialize Icon nIconData.cbSize = sizeof(NOTIFYICONDATA); nIconData.hWnd = hwnd; nIconData.uID = 100; nIconData.uCallbackMessage = WM_POEPRICERMESSAGE; nIconData.hIcon = hIcon; strcpy(nIconData.szTip, "PoEPricer"); nIconData.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; Shell_NotifyIcon(NIM_ADD, &nIconData); } void c_AskForUpdate(char* msg){ int answer = MessageBox(NULL, msg, "Update available", MB_YESNO|MB_ICONINFORMATION); free(msg); if (answer == IDYES){ UpdateLoading = TRUE; ShellExecute(NULL, "open", "http://poe.melanite.net", NULL, NULL, SW_SHOWNORMAL); } } void launchPoE(){ DWORD dwType = REG_SZ; HKEY hKey = 0; char directory[1024]; DWORD value_length = 1024; const char* subkey = "Software\\GrindingGearGames\\Path of Exile"; RegOpenKey(HKEY_CURRENT_USER,subkey,&hKey); if (RegQueryValueEx(hKey, "InstallLocation", NULL, &dwType, (LPBYTE)&directory, &value_length) != ERROR_SUCCESS){ MessageBox(NULL, "Could not determine Path of Exile's install location.\nDisabling autostart.", "Error", MB_OK|MB_ICONERROR); LaunchPoE = FALSE; go_SetLaunchPoE(LaunchPoE); return; } char executable[1024]; strcpy(executable, directory); strcat(executable, "\\PathOfExile.exe"); STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); ZeroMemory( &pi, sizeof(pi) ); si.cb = sizeof(si); if (!CreateProcess( executable, // No module name (use command line) NULL , // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE 0, // No creation flags NULL, // Use parent's environment block directory, // Use given starting directory &si, // Pointer to STARTUPINFO structure &pi ) // Pointer to PROCESS_INFORMATION structure ){ MessageBox(NULL, "Could not start Path of Exile.\nDisabling autostart.", "Error", MB_OK|MB_ICONERROR); LaunchPoE = FALSE; go_SetLaunchPoE(LaunchPoE); return; } PoEHandle = pi.hProcess; } DWORD FindProcessId(char* processName){ // strip path char* p = strrchr(processName, '\\'); if(p) processName = p+1; PROCESSENTRY32 processInfo; processInfo.dwSize = sizeof(processInfo); HANDLE processesSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if ( processesSnapshot == INVALID_HANDLE_VALUE ) return 0; Process32First(processesSnapshot, &processInfo); if ( !strcmp(processName, processInfo.szExeFile) ) { CloseHandle(processesSnapshot); return processInfo.th32ProcessID; } while ( Process32Next(processesSnapshot, &processInfo) ) { if ( !strcmp(processName, processInfo.szExeFile) ) { CloseHandle(processesSnapshot); return processInfo.th32ProcessID; } } CloseHandle(processesSnapshot); return 0; } void c_Loop(char* version, boolean useDoubleclick, boolean checkUpdates, boolean launchPoEBool){ VERSION = version; UseDoubleclick = useDoubleclick; CheckForUpdates = checkUpdates; LaunchPoE = launchPoEBool; PoEHandle = NULL; if(LaunchPoE && FindProcessId("PathOfExile.exe") == 0 && !UpdateLoading){ launchPoE(); } //Initialize Variables //ExitCalled = FALSE; hInstance = GetModuleHandle(NULL); CtrlPressed = FALSE; //Install Hooks InstallHooks(); //c_LoadFilters(); //CreateCustomMenu(); //Created automatically when needed ShowTrayIcon(); MSG msg = {0}; if(PoEHandle != NULL){ SetTimer(NULL, 1, 1000, NULL); } while (GetMessage(&msg, NULL, 0, 0) != 0) { TranslateMessage(&msg); DispatchMessage(&msg); if (PoEHandle != NULL){ DWORD dwExitCode; GetExitCodeProcess(PoEHandle,&dwExitCode); if(dwExitCode != STILL_ACTIVE) { Exit(); } } } Exit(); }
C
/* * imgops.c - Simple operations on images * * C laboratory exercises. * Richard Vaughan, 2014. */ #include <assert.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> /*------------------------------------------------- PART 0: OPERATIONS ON A PIXEL */ // get the value in the array at coordinate (x,y) uint8_t get_pixel(const uint8_t array[], unsigned int cols, unsigned int rows, unsigned int x, unsigned int y) { assert(x < cols); assert(y < rows); return array[y * cols + x]; } // set the pixel at coordinate {x,y} to the specified color void set_pixel(uint8_t array[], unsigned int cols, unsigned int rows, unsigned int x, unsigned int y, uint8_t color) { assert(x < cols); assert(y < rows); array[y * cols + x] = color; } /*------------------------------------------------- PART 1: OPERATIONS ON THE WHOLE IMAGE */ /* TASK 1 - Easy functions to get started */ // Set every pixel to 0 (black) void zero(uint8_t array[], unsigned int cols, unsigned int rows) { memset(array, 0, rows * cols * sizeof(uint8_t)); } // Returns a pointer to a freshly allocated array that contains the // same values as the original array, or a null pointer if the // allocation fails. The caller is responsible for freeing the array // later. uint8_t *copy(const uint8_t array[], unsigned int cols, unsigned int rows) { // your code here uint8_t *new_arr = malloc(rows * cols); for (unsigned int i = 0; i < rows * cols; i++) { new_arr[i] = array[i]; } if (new_arr != NULL) { return new_arr; } return NULL; } // Return the darkest color that appears in the array; i.e. the // smallest value uint8_t min(const uint8_t array[], unsigned int cols, unsigned int rows) { // your code here uint8_t min = array[0]; for (unsigned int i = 0; i < rows * cols; i++) { if (array[i] < min) { min = array[i]; } } return min; } // Return the lightest color that appears in the array; i.e. the // largest value uint8_t max(const uint8_t array[], unsigned int cols, unsigned int rows) { // your code here uint8_t max = array[0]; for (unsigned int i = 0; i < rows * cols; i++) { if (array[i] > max) { max = array[i]; } } return max; } // TASK 2 // Replace every instance of pre_color with post_color. void replace_color(uint8_t array[], unsigned int cols, unsigned int rows, uint8_t pre_color, uint8_t post_color) { // your code here for (unsigned int i = 0; i < rows * cols; i++) { if (array[i] == pre_color) { array[i] = post_color; } } } /* TASK 3 - two functions */ // flip the image, left-to-right, like in a mirror. void flip_horizontal(uint8_t array[], unsigned int cols, unsigned int rows) { //your code here //Create 2D array for easier flipping int new_arr[rows][cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { new_arr[i][j] = array[(i * cols) + j]; } } //Do flip for (int k = 0; k < rows; k++) { for (int l = 0; l < cols / 2; l++) { new_arr[k][l] ^= new_arr[k][cols - 1 - l]; new_arr[k][cols - 1 - l] ^= new_arr[k][l]; new_arr[k][l] = new_arr[k][cols - 1 - l]; } } //flatten array to 1D for (int m = 0; m < rows; m++) { for (int n = 0; n < cols; n++) { array[m * n] = new_arr[m][n]; } } } // flip the image top-to-bottom. void flip_vertical(uint8_t array[], unsigned int cols, unsigned int rows) { // your code here int new_arr2[rows][cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { new_arr2[i][j] = array[(i * cols) + j]; } } //Do flip //Do flip for (int p = 0; p < cols; p++) { for (int q = 0; q < rows / 2; q++) { new_arr2[q][p] ^= new_arr2[rows - 1 - q][p]; new_arr2[rows - 1 - q][p] ^= new_arr2[q][p]; new_arr2[q][p] = new_arr2[rows - 1 - q][p]; } } } /* TASK 4 */ // Find the first coordinate of the first pixel with a value that // equals color. Search from left-to-right, top-to-bottom. If it is // found, store the coordinates in *x and *y and return 1. If it is // not found, return 0. int locate_color(const uint8_t array[], unsigned int cols, unsigned int rows, uint8_t color, unsigned int *x, unsigned int *y) { // your code here for (unsigned int i = 0; i < rows * cols; i++) { if (array[i] == color) { *x = i % cols; *y = i / cols; return 1; } } return 0; } /* TASK 5 */ // Invert the image, so that black becomes white and vice versa, and // light shades of grey become the corresponding dark shade. void invert(uint8_t array[], unsigned int cols, unsigned int rows) { // your code here for (unsigned int i = 0; i < rows * cols; i++) { array[i] = 255 - array[i]; } } /* TASK 6 */ // Multiply every pixel by scale_factor, in order to brighten or // darken the image. Resulting values are rounded to the nearest // integer (0.5 rounded up) and any resulting value over 255 is // thresholded to 255. void scale_brightness(uint8_t array[], unsigned int cols, unsigned int rows, double scale_factor) { // your code here for (int i = 0; i < rows * cols; i++) { int result = round(array[i] * scale_factor); if (result > 255) { array[i] = 255; } else if (result < 0) { array[i] = 0; } else { array[i] = result; } } } /* TASK 7 */ // Normalize the dynamic range of the image, i.e. Shift and scale the // pixel colors so that that darkest pixel is 0 and the lightest pixel // is 255. Hint: you already wrote min() and max(). void normalize(uint8_t array[], unsigned int cols, unsigned int rows) { // your code here uint8_t mini = min(array, cols, rows); uint8_t maxi = max(array, cols, rows); uint8_t target_min = 0; uint8_t target_max = 255; uint8_t source_scale = maxi - mini; uint8_t target_scale = target_max - target_min; uint8_t scale; uint8_t scaled; //All values are the same dont normalize if (mini == maxi) { return; } for (int i = 0; i < rows * cols; i++) { scale = array[i] - mini; scaled = (scale * target_scale * 2 + source_scale) / source_scale / 2; array[i] = scaled + target_min; } } /* TASK 8 */ // Return a new image of size rows/2 by cols/2 If the original image // has an odd number of columns, ignore its rightmost column. If the // original image has an odd number of rows, ignore its bottom row. // The value of a pixel at (p,q) in the new image is the average of // the four pixels at (2p,2q), (2p+1,2q), (2p+1,2q+1), (2p,2q+1) in // the original image. uint8_t *half(const uint8_t array[], unsigned int cols, unsigned int rows) { // your code here uint8_t *ret = malloc((rows / 2) * (cols / 2) * sizeof(uint8_t)); if (ret != NULL) { for (unsigned int y = 0; y < rows / 2; y++) { for (unsigned int x = 0; x < cols / 2; x++) { unsigned int total = 0; for (unsigned int i = 2 * y; i < 2 * y + 2; i++) { for (unsigned int j = 2 * x; j < 2 * x + 2; j++) { total += array[i * cols + j]; ret[y * (cols / 2) + x] = round(total / 4.0); } } } } } return ret; } /*------------------------------------------------- PART 2: OPERATIONS ON IMAGE SUB-REGIONS These functions operate only on a rectangular region of the array defined by a (left,top) corner (i.e. closer to the image origin) and (right,bottom) corner (i.e. further from the image origin). The rectangle edges of a rectangular region are aligned with the x,y axes. The region includes all the columns from [left, right-1] inclusive, and all the rows from [top, bottom-1] inclusive. In every case, you may assume that left <= right and top <= bottom: do not need to test for this. The area of the region is right-left * bottom-top pixels, which implies that if left == right or top == bottom, the region has no area and is defined as "empty". Each function notes how to handle empty regions. In every function, you can use assert() to test bounds on the region corners. */ /* TASK 9 */ // Set every pixel in the region to color. If the region is empty, the // image must remained unchanged. void region_set(uint8_t array[], unsigned int cols, unsigned int rows, unsigned int left, unsigned int top, unsigned int right, unsigned int bottom, uint8_t color) { // your code here for (unsigned int i = 0; i < rows; i++) { for (unsigned int j = 0; j < cols; j++) { if (array[i * cols + j] >= 0 && array[i * cols + j] <= 255 && i >= left && i <= right && j >= bottom && j <= top) { array[i * cols + j] = color; } } } } /* TASK 10 */ // Return the sum of all the pixels in the region. Notice the large // return type to handle potentially large numbers. Empty regions // return the sum 0. unsigned long int region_integrate(const uint8_t array[], unsigned int cols, unsigned int rows, unsigned int left, unsigned int top, unsigned int right, unsigned int bottom) { // your code here unsigned long sum = 0; for (unsigned int i = 0; i < rows; i++) { for (unsigned int j = 0; j < cols; j++) { if (array[i * cols + j] >= 0 && array[i * cols + j] <= 255 && i >= left && i <= right && j >= bottom && j <= top) { sum += array[i * cols + j]; } } } return sum; } /* TASK 11 */ // Get a new image which is a copy of the region. Empty regions return // a null pointer. If memory allocation fails, return a null // pointer. The caller is responsible for freeing the returned array // later. uint8_t *region_copy(const uint8_t array[], unsigned int cols, unsigned int rows, unsigned int left, unsigned int top, unsigned int right, unsigned int bottom) { // your code here unsigned int copied_rows = abs(top - bottom); unsigned int copied_cols = abs(left - right); uint8_t *copied = malloc(copied_rows * copied_cols * sizeof(uint8_t)); if (copied) { for (unsigned int i = 0; i < rows; i++) { for (unsigned int j = 0; j < cols; j++) { if (i + rows * j <= copied_cols * copied_rows) { copied[i + rows * j] = array[i + rows * j]; } } } return copied; } return NULL; }
C
/* * Author: Alex Hiller * Year: 2019 * * Program Description: * Program to demonstrate integer division. * */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> int main (int argc, char *argv[]) { int num,den; printf("numerator\t>"); scanf("%i", &num); printf("denominator\t>"); scanf("%i", &den); printf("%i / %i = %i\n", num, den, num/den); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> int contains_char(char *, int, char, int); int is_unique_chars(char *, int); int is_unique_chars2(char *, int); int main(){ char * s; size_t ssize = 100; size_t num_of_chars; s = (char *)malloc(ssize * sizeof(char)); if(s == NULL){ perror("buy more memory!"); exit(1); } printf("write a string:"); scanf("%s", s); int n = strlen(s); printf("Does this string have unique chars?:\n'%s' (%d)\n", s, n); int r = is_unique_chars(s, n); int r2 = is_unique_chars2(s, n); printf("%s", r?"true":"false"); printf("\nUsing the idea of a boolean array with a runtime of O(256)\n"); printf("%s", r?"true":"false"); free(s); return 0; } int is_unique_chars(char * s, int n){ int i=0; while(i<n-1){ if(contains_char(s, n, s[i], i+1)) return 0; i++; } return 1; } int is_unique_chars2(char *s, int n){ int * f; size_t fsize = 256; f = (int *)malloc(fsize * sizeof(int)); memset(f, 0, sizeof f); for(int i=0; i<n; i++){ f[s[i]]++; if (f[s[i]]>1) return 0; } free (f); return 1; } int contains_char(char *s , int n, char c, int start){ int i=start; while(i<n && s[i] != c) i++; return i<n; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <ctype.h> #include <setjmp.h> #include <signal.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> #include <errno.h> #include <math.h> #include <pthread.h> #include <semaphore.h> #include <sys/socket.h> #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netinet/ip_icmp.h> void doit(int); void sig_child(int); void handle_mpty(int, int); #define err(msg) \ do { perror(msg); exit(1); }while(0); int main(int argc, char **argv) { int listenfd, connfd; int n; pid_t pid; struct addrinfo hints, *res; signal(SIGCHLD, sig_child); bzero(&hints, sizeof(hints)); hints.ai_flags = AI_PASSIVE; hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; if( (n = getaddrinfo(NULL, "5677", &hints, &res)) != 0 ){ fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(n)); exit(1); } if( (listenfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) < 0) err("socket error"); if( bind(listenfd, res->ai_addr, res->ai_addrlen) < 0) err("bind error"); if( listen(listenfd, 20) < 0) err("listen error"); printf("listen at %s: %d ...\n", res->ai_canonname, ntohs(((struct sockaddr_in *)res->ai_addr)->sin_port)); fflush(stdout); while(1){ if( (connfd = accept(listenfd, NULL, NULL)) < 0) err("accept error"); if((pid = fork()) < 0){ err("fork error"); }else if(pid == 0){ close(listenfd); doit(connfd); exit(0); }else close(connfd); } } void doit(int connfd) { pid_t pid; int mfd; if( (pid = pty_fork(&mfd, NULL, 0, NULL, NULL)) < 0){ err("pty_fork error"); }else if(pid == 0){ execl("/bin/bash", "sh", (char *)0); exit(127); }else{ handle_mpty(connfd, mfd); } /* printf("handle a connection\n"); if( dup2(connfd, 0) == -1) err("dup2 0 error"); if( dup2(connfd, 1) == -1) err("dup2 1 error"); if( dup2(connfd, 2) == -1) err("dup2 2 error"); close(connfd); execl("/bin/bash", "sh", (char *)0); exit(127); */ } void sig_child(int signo) { pid_t pid; while( (pid = waitpid(-1, NULL,WNOHANG)) > 0) ; if(pid < 0 && errno != ECHILD) err("waitpid error"); return; } void handle_mpty(int connfd, int mfd) { pid_t pid; char buf[512]; int n; if( (pid = fork()) < 0){ err("handle_mpty fork error"); }else if(pid > 0){ while( (n = read(connfd, buf, sizeof(buf))) > 0) write(mfd, buf, n); }else{ while( (n = read(mfd, buf, sizeof(buf))) > 0) write(connfd, buf, n); } }
C
#ifndef ATTAQUE_H #define ATTAQUE_H /* attaque.c/attaque.h : permet au joueur d'attaquer un ennemi */ /* ----- A inclure ----- */ /* ----- Define ----- */ /* ----- Structure + Enumeration ----- */ typedef struct Attaque Attaque; struct Attaque { unsigned int aAttaqueEnnemi; unsigned int indexEnnemiAttaque; }; /* ----- Prototype ----- */ /* Inflige des degats indiques en paramtre a l'ennemi indique en parametre */ void inffligerDegatEnnemi(const unsigned int indexEnnemi, const unsigned int degat); /* Renvoie un nombre different de 0 si le joueur peut attaque l'ennemi indique en parametre */ unsigned int joueurPeutAttaquerEnnemi(const unsigned int indexEnnemi); /* Permet au joueur d'attaquer un ennemi */ void attaquerEnnemi(void); /* ----- Declaration ----- */ #endif
C
#include "Struct.h" void in_die() { printf("\nHousekeeping...Will Exit UNIXcrt NOW"); exit(0); } int main (int argc, char * argv[]){ sigset(SIGINT,in_die); //Define signal handling int parent_id, file_id; int bufferSize = BUFFERSIZE; caddr_t mmap_ptr; struct Buffer * output_mem_p; char output_text[MAXCHAR]; sscanf(argv[1], "%d", &parent_id); sscanf(argv[2], "%d", &file_id); mmap_ptr = mmap((caddr_t) 0,bufferSize,PROT_READ | PROT_WRITE,MAP_SHARED,file_id, (off_t) 0); if (mmap_ptr == NULL){ //Memory mapping failed printf("ISSUES"); exit(0); } output_mem_p =(struct Buffer*) mmap_ptr; output_mem_p->data[0] = '\0'; do{ while(output_mem_p->completedFlag == 0) //Buffer Full, Wait until buffer is empty usleep(500); strcpy(output_text, output_mem_p->data); printf("\n%s", output_text); /* printf("\nUNIXcrt says: %s", output_text);*/ fflush(stdout); //FLUSHES TO THE SCREEN. output_mem_p->completedFlag = 0; kill(parent_id, SIGUSR1); //remove this line when atomicity is working. }while(1); printf("AN ISSUE HAS OCCURED WITHIN THE UNIX CRT PROCESS"); }
C
#include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #define BUF_SZ 1024 int fileread(int fdin, int fdout); int main(int argc, char *argv[]) { int in; int out = STDOUT_FILENO; in = open(argv[1], O_RDONLY); if (in == -1) { perror(argv[1]); exit(3); } int filereturn; filereturn = fileread(in, out); if (filereturn == 4) { perror(argv[1]); close(in); exit(4); } else if (filereturn == 5) { perror("write error"); close(in); exit(5); } close(in); return 0; } int fileread(int fdin, int fdout) { ssize_t reader = 1; ssize_t writer; char *buf = malloc(BUF_SZ); while (reader != 0) { reader = read(fdin, buf, BUF_SZ); if (reader == -1) return 4; writer = write(fdout, buf, reader); if (writer == -1) return 5; } free(buf); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <netdb.h> #include <netinet/in.h> #include <string.h> int main(int argc, char *argv[]) { int sockfd, portno, n; struct sockaddr_in serv_addr; struct hostent *server; char buffer[256]; if (argc < 3) { fprintf(stderr,"usage %s hostname port\n", argv[0]); exit(0); } portno = atoi(argv[2]); /* Create a socket point */ sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { perror("ERROR opening socket"); exit(1); } server = gethostbyname(argv[1]); if (server == NULL) { fprintf(stderr,"ERROR, no such host\n"); exit(0); } bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); /* Now connect to the server */ if (connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) { perror("ERROR connecting"); exit(1); } /*start loop*/ int quit=0; char request[7] = "a_list"; request[7] = '\0'; while(!quit){ /* sent a request for service list */ n = write(sockfd, request, strlen(request)); if (n < 0) { perror("ERROR writing to socket"); exit(1); } /* Now read server response */ bzero(buffer,256); n = read(sockfd, buffer, 255); if (n < 0) { perror("ERROR reading from socket"); exit(1); } printf("%s",buffer); /* Reply the service number */ char req_num[4]=""; scanf("%s",req_num); int service = atoi(req_num); /* Send message to the server */ n = write(sockfd, req_num, strlen(req_num)); if (n < 0) { perror("ERROR writing to socket"); exit(1); } /* Now read server response */ if(service==1 || service==2){ bzero(buffer,256); n = read(sockfd, buffer, 255); if (n < 0) { perror("ERROR reading from socket"); exit(1); } printf("%s",buffer); } if(service==1){ //DNS service char domain[50]; scanf("%s",domain); n = write(sockfd, domain, strlen(domain)); if(n < 0){ perror("ERROR writting to socket"); exit(1); } bzero(buffer,256); n = read(sockfd,buffer,255); if(n < 0){ perror("ERROR writting to socket"); exit; } if(strcmp(buffer,"failed")!=0) printf("address get from domain name :%s\n",buffer); } else if(service==2){ char stu_id[10]; scanf("%s",stu_id); n = write(sockfd,stu_id,strlen(stu_id)); if(n<0){ perror("ERROR writting to socket"); exit(1); } bzero(buffer,256); n = read(sockfd,buffer,255); if(n<0){ perror("ERROR reading from socket"); exit; } printf("Email get from server : %s\n",buffer); } else if(service==3){ quit=1; return 0; } getchar(); getchar(); } return 0; }
C
#ifndef PLATEAU_H #define PLATEAU_H #include "I_Plateau.h" #include <math.h> #include<stdio.h> #include <stdlib.h> void pose_pion(plateau *p, Position p1, Position p2){ if(verifier_possibilite(p, p1, p2)==0 ){ return; } Pion pion_vide; pion_vide.couleur=VIDE; pion_vide.role=RIEN; p->echiquier[ p2.x ][ p2.y ] = p->echiquier[ p1.x ][ p1.y ]; p->echiquier[ p1.x ][ p1.y ] = pion_vide; if (p->echiquier[ 1][ 4 ].role==RIEN) p->echiquier[ 1][ 4 ].role=BUT; if (p->echiquier[ 1][ 5 ].role==RIEN) p->echiquier[ 1][ 5 ].role=BUT; if (p->echiquier[ 8][ 4 ].role==RIEN) p->echiquier[ 8][ 4 ].role=BUT; if (p->echiquier[ 8][ 5 ].role==RIEN) p->echiquier[ 8][ 5 ].role=BUT; } Pion vise_pion(plateau *p, Position p1){ Pion pion; pion.role=INA; if ( p1.y >p->nb_colonnes || p1.x > p->nb_lignes ) return pion; if (p->echiquier[ p1.x ][ p1.y].role==INA ) return pion; return p->echiquier[p1.x][p1.y]; } void mettre_case_vide(plateau *p, Position p1) { p->echiquier[p1.x][p1.y].role=RIEN; p->echiquier[p1.x][p1.y].couleur=VIDE; } int deplace_lion_dragon_singe(plateau *p, Position p1, Position p2, unsigned int type_pion){ if(verifier_possibilite(p, p1, p2)){ if (abs(p1.x-p2.x)<=1 && abs(p1.y-p2.y)<=1){ pose_pion(p,p1,p2); return 3; } /* Si on soustrait les positions finales aux positions initial et que l'on trouve une valeur inf ou égal à 1 on retourne 3 / On se déplace en diagonale */ if (abs(p1.x-p2.x)==2 && abs(p1.y-p2.y)==0){ /* On se déplace de deux cases vers le haut ou le bas / Déplacement vertical */ if (p1.x-p2.x==2){ /* Déplacement de deux cases vers le haut */ if(p->echiquier[p1.x-1][p1.y].role>type_pion && p->echiquier[p1.x-1][p1.y].role < BUT) return 0; /* Si la case intermédiaire à un pion ayant un rôle plus important que le pion que l'on souhaite déplacer et inférieur à un BUT (car but dispose du rôle le plus important) alors rien faire */ if(p->echiquier[p1.x-1][p1.y].couleur!=p->echiquier[p1.x][p1.y].couleur){ p1.x-=1; mettre_case_vide(p, p1); p1.x+=1; pose_pion(p,p1,p2); return 2; } /* Si le pion intermédiaire est d'une autre couleur que celui qu'on a choisi alors le programme sélectionne ce pion est le supprimé. Il reprend ensuite le nôtre et le place */ pose_pion(p,p1,p2); return 1; } /* Si aucun de ces cas alors il applique un déplacement de deux cases tout simplement */ if (p1.x-p2.x==-2){ if(p->echiquier[p1.x+1][p1.y].role>type_pion && p->echiquier[p1.x+1][p1.y].role < BUT) return 0; if(p->echiquier[p1.x+1][p1.y].couleur!=p->echiquier[p1.x][p1.y].couleur){ p1.x+=1; mettre_case_vide(p, p1); p1.x-=1; pose_pion(p,p1,p2); return 2; } pose_pion(p,p1,p2); return 1; } } /* Déplacement de deux cases vers le bas. Même procédure */ if (abs(p1.x-p2.x)==0 && abs(p1.y-p2.y)==2){ /* Déplacement horizontal de deux cases */ if (p1.y-p2.y==2){ if(p->echiquier[p1.x][p1.y-1].role>type_pion && p->echiquier[p1.x][p1.y-1].role < BUT) return 0; if(p->echiquier[p1.x][p1.y-1].couleur!=p->echiquier[p1.x][p1.y].couleur){ p1.y-=1; mettre_case_vide(p, p1); p1.y+=1; pose_pion(p,p1,p2); return 2; } pose_pion(p,p1,p2); return 1; } /* Deux cases vers la gauche */ if (p1.y-p2.y==-2){ if(p->echiquier[p1.x][p1.y+1].role>type_pion && p->echiquier[p1.x][p1.y+1].role < BUT) return 0; if(p->echiquier[p1.x][p1.y+1].couleur!=p->echiquier[p1.x][p1.y].couleur){ p1.y+=1; mettre_case_vide(p, p1); p1.y-=1; pose_pion(p,p1,p2); return 2; } pose_pion(p,p1,p2); return 1; } } /* Deux cases vers la droite */ if (abs(p1.x-p2.x)==2 && abs(p1.y-p2.y)==2){ /* Déplacement en diagonale */ if (p1.x-p2.x==2 && p1.y-p2.y==2){ if(p->echiquier[p1.x-1][p1.y-1].role > type_pion && p->echiquier[p1.x-1][p1.y-1].role < BUT) return 0; if(p->echiquier[p1.x-1][p1.y-1].couleur!=p->echiquier[p1.x][p1.y].couleur){ p1.y-=1; p1.x-=1; mettre_case_vide(p, p1); p1.y+=1; p1.x+=1; pose_pion(p,p1,p2); return 2; } pose_pion(p,p1,p2); return 1; } /* En haut à gauche */ if (p1.x-p2.x==2 && p1.y-p2.y==-2){ if(p->echiquier[p1.x-1][p1.y+1].role>type_pion && p->echiquier[p1.x-1][p1.y+1].role < BUT) return 0; if(p->echiquier[p1.x-1][p1.y+1].couleur!=p->echiquier[p1.x][p1.y].couleur) { p1.y+=1; p1.x-=1; mettre_case_vide(p, p1); p1.y-=1; p1.x+=1; pose_pion(p,p1,p2); return 2; } pose_pion(p,p1,p2); return 1; } /* En haut à droite */ if (p1.x-p2.x==-2 && p1.y-p2.y==2){ if(p->echiquier[p1.x+1][p1.y-1].role>type_pion && p->echiquier[p1.x+1][p1.y-1].role < BUT) return 0; if(p->echiquier[p1.x+1][p1.y-1].couleur!=p->echiquier[p1.x][p1.y].couleur){ p1.y-=1; p1.x+=1; mettre_case_vide(p, p1); p1.y+=1; p1.x-=1; pose_pion(p,p1,p2); return 2; } pose_pion(p,p1,p2); return 1; } /* En bas à gauche */ if (p1.x-p2.x==-2 && p1.y-p2.y==-2){ if(p->echiquier[p1.x+1][p1.y+1].role>type_pion && p->echiquier[p1.x+1][p1.y+1].role < BUT) return 0; if(p->echiquier[p1.x+1][p1.y+1].couleur!=p->echiquier[p1.x][p1.y].couleur){ p1.y+=1; p1.x+=1; mettre_case_vide(p, p1); p1.y-=1; p1.x-=1; pose_pion(p,p1,p2); return 2; } pose_pion(p,p1,p2); return 1; } /* En bas à droite */ } return 0; } return 0; } int deplace_lion(plateau *p, Position p1, Position p2){ /* Pas de déplacement de deux cases s'il n'y a pas de pièces en intermédiaire. On enlève les possibilités de déplacement simple en deux cases mais on autorise les sauts */ int val=0; if (abs(p1.x-p2.x)>1 || abs(p1.y-p2.y)>1){ if (verif_case_interm(p,p1,p2)==0) return 0; if(verif_case_interm(p,p1,p2)==2){ val=deplace_lion_dragon_singe(p, p1, p2, LION); if(val!=0) return 2; return 0; } } return deplace_lion_dragon_singe(p, p1, p2, LION); } int deplace_dragon(plateau *p, Position p1, Position p2){ /* On enlève tous les déplacements ayant un x et un y compris entre 0 et 1 -> Tous les déplacements "simples" du lion */ if (abs(p1.x-p2.x)<=1 && abs(p1.y-p2.y)<=1) return 0; /* On accepte les sauts */ if(abs(p1.x-p2.x)==2 || abs(p1.y-p2.y)==2){ if (verif_case_interm(p,p1,p2)==0) return 0; } return deplace_lion_dragon_singe(p, p1, p2, DRAGON); } int deplace_singe(plateau *p, Position p1, Position p2){ int val=deplace_lion_dragon_singe(p, p1, p2, SINGE); /* test : printf("appel deplace_singe\n");*/ if(val==1){ int direction=recupere_direction(p1,p2); /* test : printf(" singe pos1(%d,%d) pos2=(%d,%d)\n", p1.x,p1.y,p2.x,p2.y);*/ /* On appelle la fonction nous permettant de savoir sur quelle ligne l'utilisateur souhaite se déplacer */ if (direction==1){ /* En haut à droite */ /* test : printf("1 \n");*/ p1.x=p2.x; p1.y=p2.y; p2.x-=1; p2.y+=1; /* La position initiale devient celle où on souhaite se rendre et la position finale devient celle qui vient après la nôtre sur la même ligne */ if (p2.x >=0 && p2.y <p->nb_colonnes){ /* On verifie que la case qui se trouve après la notre et sur la même ligne soit bien sur l'echiquier */ if (p->echiquier[p1.x][p1.y].couleur!=p->echiquier[p2.x][p2.y].couleur && p->echiquier[p2.x][p2.y].role!=INA){ /* Si la case qui se trouve après celle où on souhaite se rendre est d'une couleur différentes on s'arrête car on refait appel à la même fonction mais avec un val != 0, on peut plus rentrer dans la boucle. */ p2.x-=1; p2.y+=1; return deplace_singe(p, p1, p2); } } return 1; } /* Même action pour toutes les autres directions */ if (direction==2){ /* Au dessus */ /*test : printf("2 \n");*/ p1=p2; p2.x-=1; if (p2.x >=0 ){ if (p->echiquier[p1.x][p1.y].couleur!=p->echiquier[p2.x][p2.y].couleur && p->echiquier[p2.x][p2.y].role!=INA){ p2.x-=1; return deplace_singe(p, p1, p2); } } return 1; } if (direction==3){ /* En haut à gauche */ /* test : printf("3 \n");*/ p1=p2; p2.x-=1; p2.y-=1; if (p2.x >=0 && p2.y>=0){ if (p->echiquier[p1.x][p1.y].couleur!=p->echiquier[p2.x][p2.y].couleur && p->echiquier[p2.x][p2.y].role!=INA){ p2.x-=1; p2.y-=1; return deplace_singe(p, p1, p2); } } return 1; } if (direction==4){ /* A gauche */ /* test : printf("4 \n");*/ p1=p2; p2.y-=1; if (p2.y>=0){ if (p->echiquier[p1.x][p1.y].couleur!=p->echiquier[p2.x][p2.y].couleur && p->echiquier[p2.x][p2.y].role!=INA){ p2.y-=1; return deplace_singe(p, p1, p2); } } return 1; } if (direction==5){ /* En bas à gauche */ /* test : printf("5 \n");*/ p1=p2; p2.x+=1; p2.y-=1; if (p2.x <p->nb_lignes && p2.y>=0){ if (p->echiquier[p1.x][p1.y].couleur!=p->echiquier[p2.x][p2.y].couleur && p->echiquier[p2.x][p2.y].role!=INA){ p2.x+=1; p2.y-=1; return deplace_singe(p, p1, p2); } } return 1; } if (direction==6){ /* En bas à droite */ /* test : printf("6 \n");*/ p1=p2; p2.x+=1; if (p2.x < p->nb_lignes){ if (p->echiquier[p1.x][p1.y].couleur!=p->echiquier[p2.x][p2.y].couleur && p->echiquier[p2.x][p2.y].role!=INA){ p2.x+=1; return deplace_singe(p, p1, p2); } } return 1; } if (direction==7){ /* En bas à droite */ /* test : printf("7 \n");*/ p1=p2; p2.x+=1; p2.y+=1; if (p2.x <p->nb_lignes && p2.y<p->nb_colonnes){ if (p->echiquier[p1.x][p1.y].couleur!=p->echiquier[p2.x][p2.y].couleur && p->echiquier[p2.x][p2.y].role!=INA){ p2.x+=1; p2.y+=1; return deplace_singe(p, p1, p2); } } return 1; } if (direction==8){ /* A droite */ /* test :printf("8 \n");*/ p1=p2; p2.y+=1; if (p2.y<p->nb_colonnes){ if (p->echiquier[p1.x][p1.y].couleur!=p->echiquier[p2.x][p2.y].couleur && p->echiquier[p2.x][p2.y].role!=INA){ p2.y+=1; return deplace_singe(p, p1, p2); } } return val; } } return val; } int recupere_direction(Position p1, Position p2){ /* programme permettant de placer des numéros sur les différentes possibilités */ int difX=p1.x-p2.x; int difY=p1.y-p2.y; if (difX < 0){ /* Ligne du bas */ if (difY<0){ return 7; /* En bas à droite */ } if (difY==0){ return 6; /* En dessous*/ } if (difY>0){ return 5; /* En bas à gauche */ } } if (difX==0) { /* Lignes de la position initiale */ if (difY<0){ return 8; /* A droite */ } if (difY>0){ return 4; /* A gauche */ } } if (difX>0){ /* Lignes en haut */ if (difY<0){ return 1; /* En haut à droite */ } if (difY==0){ return 2; /* Au dessus */ } if (difY>0){ return 3; /* En haut à gauche */ } } return -1; } #endif
C
// // Use USART serial communication between ATmega168 and PC // Use external interrupt INT0 and INT1 on ATmega168 // Use Interrupt Service Routine (ISR) // // Connecting ATmega168 with PC use USB serial adaptor (for Mac) // 1. In terminal, type: ls /dev/*usbserial* // 2. Find: cu.usbserial-XXXX // 3. connect: screen [adapterName] 9600 // // Xiaolou Huang // 11/9/2019 // #include <avr/io.h> #include <util/delay.h> #include <util/setbaud.h> #include <avr/interrupt.h> void USART_init(); void USART_transmit(unsigned char data); unsigned char USART_receive(); void RGBled_7Segment_init(); void Interrupt_init(); void Timer_init(); unsigned char data; // main int main(void) { // initialization USART_init(); RGBled_7Segment_init(); Interrupt_init(); Timer_init(); while(1) { data = USART_receive(); // receive data // if it's "R,r", "G, g", "B, b", light up that color on RGB LED if (data == 0x52 || data == 0x72) { // if it's "R" or "r" PORTD |= (1 << PD5); } else if (data == 0x47 || data == 0x67) { // if it's "G" or "g" PORTD |= (1 << PD6); } else if (data == 0x42 || data == 0x62) { // if it's "B" or "b" PORTD |= (1 << PD7); } // if it's number 0 to 9, show that number on 7-segment display // PC0 = a, PC1 = b, PC2 = c, PC3 = d, PC4 = e, PC5 = f, PB1 = g if (data == 0x30) { // if it's 0, show 1 on 7-segment display PORTC = (1 << PC0) | (1 << PC1) | (1 << PC2) \ | (1 << PC3) | (1 << PC4) | (1 << PC5); PORTB = ~(1 << PB1); } else if (data == 0x31) { // if it's 1, show 1 on 7-segment display PORTC = (1 << PC1) | (1 << PC2); PORTB = ~(1 << PB1); } else if (data == 0x32) { // if it's 2, show 2 on 7-segment display PORTC = (1 << PC0) | (1 << PC1) | (1 << PC3) | (1 << PC4); PORTB = (1 << PB1); } else if (data == 0x33) { // if it's 3, show 3 on 7-segment display PORTC = (1 << PC0) | (1 << PC1) | (1 << PC2) | (1 << PC3); PORTB = (1 << PB1); } else if (data == 0x34) { // if it's 4, show 4 on 7-segment display PORTC = (1 << PC1) | (1 << PC2) | (1 << PC5); PORTB = (1 << PB1); } else if (data == 0x35) { // if it's 5, show 5 on 7-segment display PORTC = (1 << PC0) | (1 << PC2) | (1 << PC3) | (1 << PC5); PORTB = (1 << PB1); } else if (data == 0x36) { // if it's 6, show 6 on 7-segment display PORTC = (1 << PC2) | (1 << PC3) | (1 << PC4) | (1 << PC5); PORTB = (1 << PB1); } else if (data == 0x37) { // if it's 7, show 7 on 7-segment display PORTC = (1 << PC0) | (1 << PC1) | (1 << PC2); PORTB = ~(1 << PB1); } else if (data == 0x38) { // if it's 8, show 8 on 7-segment display PORTC = (1 << PC0) | (1 << PC1) | (1 << PC2) \ | (1 << PC3) | (1 << PC4) | (1 << PC5); PORTB = (1 << PB1); } else if (data == 0x39) { // if it's 9, show 9 on 7-segment display PORTC = (1 << PC0) | (1 << PC1) | (1 << PC2) | (1 << PC3) | (1 << PC5); PORTB = (1 << PB1); } } return 0; } //========================================== // When INT0 is rising edge, transmit the character back to PC ISR(INT0_vect) { if (TCNT1 > 1000) { // for debouncing. If count is greater than 1000, transmit data USART_transmit(data); // transmit the data back TCNT1 = 0x00; } } // Timer record time elapsed for button debounce purpose // OCRn = [ (clock_speed / Prescaler_value) * Desired_time_in_Seconds ] - 1 void Timer_init() { // set prescaler to /1024 to start the timer // In this case, count of 976 in TCNT1 will be 1s TCCR1B |= (1 << CS12) | (1 << CS10); // set prescaler to 1024 to start the timer } // Initialize external interrupt on ATmega168 (INT0, INT1) void Interrupt_init() { EICRA |= (1 << ISC01) | (1 << ISC00); // use rising edge of INT0 generates interrupts EIMSK |= (1 << INT0); // activate INT0 external interrupts sei(); } // Initialize USART with 8 data bits packet size and 1 stop bit. void USART_init() { UBRR0H = UBRRH_VALUE; UBRR0L = UBRRL_VALUE; UCSR0B |= (1 << TXEN0) | (1 << RXEN0); // enable USART transmitter/receiver UCSR0C |= (1 << UCSZ01) | (1 << UCSZ00); // set packet size to 8 data bits UCSR0C &= ~(1 << USBS0); // set stop bit amount to 1 stop bit // automatically adjust settings for BAUD rate depending on CPU clock speed and selected rate #if USE_2X UCSR0A |= (1 << U2X0); #else UCSR0A &= ~(1 << U2X0); #endif } // Initialize 7 segment display and RGB LED. void RGBled_7Segment_init() { // 7 segment display DDRC |= (1 << PC0) | (1 << PC1) | (1 << PC2) \ | (1 << PC3) | (1 << PC4) | (1 << PC5); DDRB |= (1 << PB1) | (1 << PB2); // RGB LED DDRD |= (1 << PD5) | (1 << PD6) | (1 << PD7); } // Transmit data when the transmit buffer is ready. void USART_transmit(unsigned char data) { // wait if the transmit buffer is not ready while (!(UCSR0A & (1 << UDRE0))); // if the transmit buffer ready to transmit data UDR0 = data; } // Receive data when the receive buffer has data unsigned char USART_receive() { // wait if the receive buffer has no data while(!(UCSR0A & (1 << RXC0))); // if there is unread data in the receive buffer return UDR0; }
C
#include <stdio.h> #include <stdlib.h> #include "mpi.h" #define N 1000000000 #define CHUNK_SIZE 50000 int main(int argc, char *argv[]) { double t_inicial, t_final; int cont = 0, total = 0; int i; int meu_ranque, num_procs, inicio, dest, raiz=0, tag=1, stop=0; double pi_partial = 0.0f; double pi = 0.0f; MPI_Status estado; MPI_Request r_envia; MPI_Request r_recebe; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &meu_ranque); MPI_Comm_size(MPI_COMM_WORLD, &num_procs); /* Registra o tempo inicial de execução do programa */ t_inicial = MPI_Wtime(); /* Envia pedaços com CHUNK_SIZE números para cada processo */ estado.MPI_TAG = 1; if (meu_ranque == 0) { for (dest=1, inicio=1; dest < num_procs && inicio < N; dest++, inicio += CHUNK_SIZE) { MPI_Send(&inicio, 1, MPI_INT, dest, tag, MPI_COMM_WORLD); } stop = num_procs - 1; /* Fica recebendo as contagens parciais de cada processo */ while (stop) { MPI_Recv(&pi_partial, 1, MPI_DOUBLE, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &estado); pi += pi_partial; dest = estado.MPI_SOURCE; if (inicio > N) { tag = 99; stop--; } /* Envia um nvo pedaço com CHUNK_SIZE números para o mesmo processo*/ MPI_Send(&inicio, 1, MPI_INT, dest, tag, MPI_COMM_WORLD); inicio += CHUNK_SIZE; } } else { /* Cada processo escravo recebe o início do espaço de busca */ while (estado.MPI_TAG != 99) { MPI_Recv(&inicio, 1, MPI_INT, raiz, MPI_ANY_TAG, MPI_COMM_WORLD, &estado); if (estado.MPI_TAG != 99) { for (i = inicio, pi_partial = 0.0f; i < (inicio + CHUNK_SIZE) && i < N; i++) { double t = (double) ((i+0.5)/N); pi_partial += 4.0/(1.0+t*t); } /* Envia a contagem parcial para o processo mestre */ MPI_Send(&pi_partial, 1, MPI_DOUBLE, raiz, tag, MPI_COMM_WORLD); } } } /* Registra o tempo final de execução */ t_final = MPI_Wtime(); if (meu_ranque == 0) { t_final = MPI_Wtime(); printf("Valor final de pi: %f\n", pi/N); printf("Tempo de execucao: %1.3f \n", t_final - t_inicial); } /* Finaliza o programa */ MPI_Barrier(MPI_COMM_WORLD); MPI_Finalize(); return(0); }
C
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/ioctl.h> #include <unistd.h> #include <getopt.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <ifaddrs.h> #include "sniffer_ioctl.h" #include <netinet/in.h> #include <arpa/inet.h> static char * program_name; static char * dev_file = "sniffer.dev"; struct hostent *host; struct in_addr **addr_list; #define SRCIP 0 #define DSTIP 1 char* chdown(char * s) { int l = strlen(s); int i; for(i = 0; i < l; i++){ if(s[i]>=97&&s[i]<=122) s[i]-=32; } return s; } void parse_ip(struct flow_entry* e, char* ip, int type){ int ip_i=0; int mark_i; struct in_addr addr; char * pch = strchr(ip,'/'); if(pch == NULL){ inet_aton(ip,&addr); if(type==SRCIP){ e->src_ip = addr.s_addr; e->src_ip_mark =32; }else{ e->dst_ip = addr.s_addr; e->dst_ip_mark =32; } }else{ *pch='\0'; char * mark_s=pch+1; int mark = atoi(mark_s); // printf("%s:%d\n",ip,mark); inet_aton(ip,&addr); if(type==SRCIP){ e->src_ip = addr.s_addr; e->src_ip_mark = mark; }else{ e->dst_ip = addr.s_addr; e->dst_ip_mark = mark; } } return ; } void file_rule_process(char* rule){ printf("rule : %s", rule); // make entry struct flow_entry e; flow_entry_init(&e); char * pch; char * arg; pch = strtok (rule," "); if(strcmp(chdown(pch),"enable")==0){ e.mode=FLOW_ENABLE; }else if(strcmp(chdown(pch),"disable")==0){ e.mode=FLOW_DISABLE; } pch = strtok (NULL, " "); if(strcmp(chdown(pch),"tcp")==0){ e.proto=TCP; }else if(strcmp(chdown(pch),"udp")==0){ e.proto=UDP; }else if(strcmp(chdown(pch),"icmp")==0){ e.proto=ICMP; } // ip port start pch = strtok (NULL, " "); while (pch != NULL){ //get arg arg = strtok (NULL, " "); //printf ("%s:%s\n",pch,arg); if(strcmp(arg,"any")!=0){ if(strcmp(pch,"src_ip")==0){ parse_ip(&e,arg,SRCIP); }else if(strcmp(pch,"dst_ip")==0){ parse_ip(&e,arg,DSTIP); }else if(strcmp(pch,"src_port")==0){ e.src_port=atoi(arg); }else if(strcmp(pch,"dst_port")==0){ e.dst_port=atoi(arg); } } //next pch = strtok (NULL, " "); } sniffer_send_command(&e); return ; } void file_input(char* filename){ FILE * fp; char * line = NULL; size_t len = 0; ssize_t read; fp = fopen(filename, "r"); if (fp == NULL) exit(EXIT_FAILURE); while ((read = getline(&line, &len, fp)) != -1) { file_rule_process(line); } fclose(fp); if (line) free(line); exit(EXIT_SUCCESS); } void usage() { fprintf(stderr, "Usage: %s [parameters]\n" "parameters: \n" " --mode [enable|disable]\n" " --src_ip [url|any] : default is any \n" " --src_port [XXX|any] : default is any \n" " --dst_ip [url|any] : default is any \n" " --dst_port [XXX|any] : default is any \n" " --p [TCP|UDP|ICMP] : default is 0(TCP)\n" " --i [filename] : input file", program_name); exit(EXIT_FAILURE); } int sniffer_send_command(struct flow_entry *flow) { printf("mode:%d\n" "proto:%d\n" "src_ip:%d\n" "src_ip_mark:%d\n" "src_port:%d\n" "dst_ip:%d\n" "dst_ip_mark:%d\n" "dst_port:%d\n",flow->mode,flow->proto,flow->src_ip,flow->src_ip_mark,flow->src_port,flow->dst_ip,flow->dst_ip_mark,flow->dst_port); int shift = flow->src_ip_mark; uint32_t mark =((~0)<<(shift)) ; printf("%x,%x\n",mark,~mark); int fd; fd=open(dev_file,O_WRONLY); if(fd<0){ printf(" open file err %x\n",fd); return 0; } ioctl(fd,flow->mode,flow); return 0; } void flow_entry_init(struct flow_entry* e){ e->src_ip=0; e->src_port=0; e->src_ip_mark=32; e->dst_ip=0; e->dst_port=0; e->dst_ip_mark=32; e->mode= FLOW_ENABLE; e->proto=TCP; } int main(int argc, char **argv) { int c; program_name = argv[0]; struct flow_entry e; flow_entry_init(&e); while(1) { static struct option long_options[] = { {"mode", required_argument, 0, 0}, {"src_ip", required_argument, 0, 0}, {"src_port", required_argument, 0, 0}, {"dst_ip", required_argument, 0, 0}, {"dst_port", required_argument, 0, 0}, {"p", required_argument, 0, 0}, {"i", required_argument, 0, 0}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long (argc, argv, "", long_options, &option_index); if (c == -1) break; switch (c) { case 0: printf("option %d %s", option_index, long_options[option_index].name); if (optarg) printf(" with arg %s", optarg); printf("\n"); switch(option_index) { case 0: // mode if(strcmp(chdown(optarg),"enable")==0){ e.mode=FLOW_ENABLE; }else if(strcmp(chdown(optarg),"disable")==0){ e.mode=FLOW_DISABLE; } break; case 1: // src_ip if(strcmp(optarg,"any")==0){ e.src_ip=0; }else { if((host=gethostbyname(optarg))<=0){ printf("err\n"); return 0; } addr_list = (struct in_addr **)host->h_addr_list; int i=0; for(i = 0; addr_list[i] != NULL; i++) { printf("add address %x \n",addr_list[i]->s_addr); e.src_ip=(addr_list[i]->s_addr); break; } } break; break; case 2: // src_port if(strcmp(optarg,"any")==0){ e.src_port=0; }else e.src_port=atoi(optarg); break; case 3: // dst_ip if(strcmp(optarg,"any")==0){ e.dst_ip=0; }else { if((host=gethostbyname(optarg))<=0){ printf("err\n"); return 0; } addr_list = (struct in_addr **)host->h_addr_list; int i=0; for(i = 0; addr_list[i] != NULL; i++) { printf("add address %x \n",addr_list[i]->s_addr); e.dst_ip=(addr_list[i]->s_addr); break; } } break; case 4: // dst_port if(strcmp(optarg,"any")==0){ e.dst_port=0; }else e.dst_port=atoi(optarg); break; case 5: // action if(strcmp(optarg,"ICMP")==0) e.proto=ICMP; else if(strcmp(optarg,"UDP")==0) e.proto=UDP; else if(strcmp(optarg,"TCP")==0) e.proto=TCP; break; case 6: // file input file_input(optarg); break; } break; default: usage(); } } sniffer_send_command(&e); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* instructions.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ppatel <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/10/18 18:41:56 by ppatel #+# #+# */ /* Updated: 2017/10/20 12:28:31 by ppatel ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/op.h" #include "../includes/asm.h" t_token *add_label(t_token *token, t_env *env) { t_label *label; if (!(label = (t_label *)malloc(sizeof(t_label)))) return (NULL); label->name = token; label->addr = env->pc; env->labels[env->label_count] = label; env->label_count = env->label_count + 1; return (token->next); } void add_inst(t_inst *inst, t_env *env) { t_inst *tmp; tmp = env->inst; while (tmp && tmp->next) tmp = tmp->next; if (!tmp) env->inst = inst; else tmp->next = inst; } t_inst *init_inst(void) { t_inst *inst; if (!(inst = (t_inst *)malloc(sizeof(t_inst)))) ft_exit("Malloc Error."); inst->size = 0; inst->opcode = 0; inst->type = 0; inst->pcount = 0; inst->params = NULL; inst->next = NULL; return (inst); } void ft_make_inst(t_token *start, t_token *end, t_env *env) { t_inst *inst; t_op *op; int i; i = 0; op = NULL; if (start->type == T_LAB) start = add_label(start, env); if (start == end) return ; inst = init_inst(); if (start != end && start->type == 16) { op = get_op_by_name(start->value); inst->opcode = op->opcode; inst->size = op->code_byte ? inst->size + 2 : inst->size + 1; } if (start->next != end) inst->params = start->next; inst->pcount = op->pcount; inst->type = op->label_size ? 1 : 0; check_pcount(start, end, inst, env); check_ptype(inst, op, env); env->pc = env->pc + inst->size; add_inst(inst, env); }
C
#include <stdio.h> int naturalSum(int); int main() { int n = 10; int sum = naturalSum(n); printf("sum of %d natural numbers is %d\n", n, sum); return 0; } int naturalSum(int n) { if (n == 1) // TERMINAL CONDITION return 1; return n + naturalSum(n - 1); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> int heap[1000],len=0; int insert(int no) { heap[len++] = no; int parent,temp; for(int i=len-1;i>0;i--) { parent = (i&1)?(i-1)/2:(i-2)/2; if(parent>=0 && heap[parent]<heap[i]) { temp = heap[i]; heap[i] = heap[parent]; heap[parent] = temp; } } } int main() { int n,temp; scanf(" %d",&n); for(int i=0;i<n;i++) { scanf(" %d",&temp); insert(temp); } for(int i=0;i<n;i++) { printf(" %d",heap[i]); } printf("\n"); return 0; }
C
/** * Matt Martin, Makoto Kinoshita * Mar 26, 2017 * CS363 Robotics * utility function file */ #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <signal.h> #include <string.h> #include <sys/time.h> #include <math.h> #include <SVM_VisionModule.h> #include <map.h> #include "Mage.h" #include "socketUtil.h" #include "utils.h" #include "robot.h" #include "particle.h" #include "../inc/robot.h" /** * Handles the command line arguments for all the different tasks that the robot can do * @param argc number of arguments * @param argv array of argguments * @param robot pointer for field correction * @return -1 if invalid command, 1 otherwise */ int handleCommandLine(int argc, char const* argv[], Robot *robot) { if (argc < 2) { printf("Usage: %s <type of movement> <other args...>\n" " type:\n" " -1 ->TEST\n" " 0 -> IDLE\n" " 1 -> POINT_FOLLOW\n" " 2 -> WALL_FOLLOW\n" " 3 -> MAZE\n" " 4 -> ROTATE\n" " 5 -> WANDER\n" " 6 -> GOTO\n" " 7 -> PINK_TRACK\n" " 8 -> HOUGH_WALL_FOLLOW\n" " 9 -> FACE_FIND\n" " 10 -> LOCALIZE\n" " 11 -> GET_TO_SECOND_FLOOR\n", argv[0] ); freeRobot(robot); return(-1); } switch (atoi(argv[1])) { case -1: if (argc < 2) { freeRobot(robot); return -1; } robot->task = TEST; break; case 0: robot->task = IDLE; break; case 1: if (argc < 4) { printf("Usage: %s 1 <nPoints> <x> <y> <x> <y> <x> <y> ...\n" " nPoints:\n" " number of points to follow\n" " x y x y x,y,...:\n" " series of integer points, separated by" "a space. A single x y pair is one point.\n", argv[0] ); freeRobot(robot); return(-1); } robot->task = POINT_FOLLOW; robot->pfIndex = 0; robot->nPfPoints = atoi(argv[2]); robot->pfPoints = (int *)malloc(sizeof(int) * robot->nPfPoints * 2); for (int i = 0; i < robot->nPfPoints * 2; ++i) { robot->pfPoints[i] = atoi(argv[3+i]); } robot->goalPosition[0] = robot->pfPoints[0]; robot->goalPosition[1] = robot->pfPoints[1]; break; case 2: if (argc < 3) { printf("Usage: %s 2 <buffer> <side> \n" " buffer:\n" " distance in mm to stay away from wall\n" " side:\n" " -1 = wall on left side of robot\n" " 1 = wall on right side of robot\n" , argv[0] ); freeRobot(robot); return(-1); } robot->task = WALL_FIND; robot->goalDistance = atoi(argv[2]); robot->laserSide = -1; if (atoi(argv[3]) == -1) robot->goalOrientation = 280; else if (atoi(argv[3]) == 1) robot->goalOrientation = 60; else { printf("Invalid side argument %s\n", argv[3]); return(-1); } break; case 3: if (argc < 5) { printf("Usage: %s 3 <buffer> \n" " buffer:\n" " distance in mm to stay away from wall\n" , argv[0] ); freeRobot(robot); return(-1); } robot->task = MAZE; robot->goalDistance = atoi(argv[2]); robot->houghRadius = 57.15; robot->houghBuffer = 100; robot->laserSide = -1; break; case 4: if (argc < 3) { printf("Usage: %s 4 <angle>\n" " angle:\n" " angle in degrees to rotate from [-180,180]\n", argv[0] ); freeRobot(robot); return(-1); } robot->task = ROTATE; robot->goalOrientation = (int)((float)atoi(argv[2]) * 1000.0 * PI / 180.0); break; case 5: robot->task = WANDER; break; case 6: if (argc < 3) { printf("Usage: %s 6 <x> <y>\n" " x:\n" " x (in mm) positoin\n" " y:\n" " y (in mm) position\n", argv[0]); freeRobot(robot); return -1; } robot->task = GOTO; robot->goalPosition[0] = atoi(argv[2]); robot->goalPosition[1] = atoi(argv[3]); break; case 7: if (argc < 3) { printf("Usage: %s 7 <distance>\n" " distance:\n" " distance in mm to stay away from pink object\n", argv[0]); freeRobot(robot); return -1; } robot->task = PINK_FIND; robot->svm_operator = SVM_OP_Pink_Blob; robot->svm_previous_operator = 0; robot->svm_command_change = 0; robot->goalDistance = atoi(argv[2]); robot->connectToIPC = 1; break; case 8: if (argc < 3) { printf("Usage: %s 8 <buffer> <side> \n" " buffer:\n" " distance in mm to stay away from wall (must be < 700)\n" " side:\n" " -1 = wall on left side of robot\n" " 1 = wall on right side of robot\n" , argv[0] ); freeRobot(robot); return(-1); } robot->task = HOUGH_WALL_FOLLOW; robot->goalDistance = atoi(argv[2]); robot->laserSide = -1; if (atoi(argv[3]) == -1) robot->goalOrientation = 1570; else if (atoi(argv[3]) == 1) robot->goalOrientation = -1570; else { printf("Invalid side argument %s\n", argv[3]); return(-1); } break; case 9: if (argc < 3) { printf("Usage: %s 9 <distance>\n" " distance:\n" " distance in mm to stay away from face\n", argv[0]); freeRobot(robot); return -1; } robot->task = FACE_FIND; robot->svm_operator = 24; robot->goalDistance = atoi(argv[2]); robot->face_track_counter = 1; robot->face_track_x_location = 0; robot->face_track_y_location = 0; robot->svm_command_change = 0; robot->connectToIPC = 1; break; case 10: if (argc < 4) { printf("Usage: %s 10 <nLasers> <mapFile>\n" " nLasers:\n" " number of laser sensors to sample from in particle filter\n" "mapFile:\n" " pgm image file of the map to localize in\n", argv[0]); freeRobot(robot); return -1; } robot->task = LOCALIZE; robot->map = map_read((char*)argv[3]); robot->pfImage = (Pixel *)malloc(sizeof(Pixel) * robot->map->rows * robot->map->cols); robot->particle_iter = 0; pf_create(robot->particleFilter,atoi(argv[2]),0.2); pf_init(robot->particleFilter,robot->map); robot->particleLasers = (float*)malloc(sizeof(float) * robot->particleFilter->nReadings); robot->particleLaserAngles = (float*)malloc(sizeof(float) * robot->particleFilter->nReadings); break; case 11: if (argc < 3) { printf("Usage: %s 11 <distance>\n" " distance:\n" " distance in mm to stay away from person when following\n", argv[0]); freeRobot(robot); return -1; } robot->task = WAIT_FOR_FACE; robot->svm_operator = SVM_OP_HaarFaceDetector; robot->svm_previous_operator = 0; robot->goalDistance = atoi(argv[2]); robot->connectToIPC = 1; robot->IPCLostCount = 0; robot->svm_command_change = 0; robot->histogramsMade = 0; break; default: printf("Invalid command: "); for (int j = 0; j < argc; ++j) { printf("%s ",argv[j]); } printf("\n"); return(-1); } return 1; } /** * creates a pointer to a Robot struct and mallocs for fields that can be malloced now * call this whenever you want to get a new Robot * @return pointer to Robot */ Robot * robotCreate() { Robot *robot = (Robot*)malloc(sizeof(Robot)); // create robot object and create important fields robot->vSensors = (long *) malloc(sizeof(long) * NUM_VSENSORS); robot->laser = (int *) malloc(sizeof(int) * NUM_LASERS); robot->laserXY = (Point *) malloc(sizeof(Point) * NUM_LASERS); robot->SVMData = (SVM_Operator_Data *) malloc(sizeof(SVM_Operator_Data)); robot->occupancyGrid = (Point*)malloc(sizeof(Point) * OG_SIZE * OG_SIZE); robot->particleFilter = (ParticleFilter*)malloc(sizeof(ParticleFilter)); return robot; } /** * initializes fields of robot so default values * call this after calling robotCreate() * @param robot pointer to robot */ void robotInit(Robot* robot) { // give all fields appropriate initial values robot->vt = 0; robot->wt = 0; robot->iterations = 0; robot->task = IDLE; robot->goalDistance = 100; robot->goalOrientation = 0; robot->goalPosition[0] = 0; robot->goalPosition[1] = 0; robot->pfIndex = 0; robot->nPfPoints = 0; robot->orientationPiToPi = 0; robot->laserIdxClosestFlat = 170; robot->laserSide = 0; robot->houghRadius = 0; robot->houghBuffer = 100; robot->houghCircleCenter.x = 0; robot->houghCircleCenter.y = 0; robot->svm_operator = NULL; robot->face_track_counter = 0; robot->face_track_x_location = 0; robot->face_track_y_location = 0; robot->connectToIPC = 0; robot->IPCLostCount = 0; robot->occupancyGridSize = 0; gettimeofday(&(robot->time),NULL); robot->particle_iter = 0; robot->timeSinceLastFace = 0; for (int i = 0; i < NUM_LASERS; ++i) { robot->laserXY[i].x = 0; robot->laserXY[i].y = 0; } } /** * handles control-c for quitting the program * @param signal */ void sighandler(int signal) { // turn everything off and disconnect irOff(); sonarOff(); usleep(1000000); disconnectRobot(); fprintf(stderr, "Exiting on signal %d after 1 second\n", signal); usleep(1000000); exit(signal); } /** * puts the IR readings into the readings pointer for easier access * @param State pointer to Mage State array * @param readings pointer to destination array */ void getAllIRReadings(long* State, int* readings) { for (int i = 0; i < INFRAREDS; ++i) { readings[i] = State[i]; } } /** * puts the sonar readings into the readings pointer for easier access * @param State pointer to Mage State array * @param readings pointer to destination array */void getAllSonarReadings(long* State, int* readings) { for (int i = 0; i < SONARS; ++i) { readings[i] = State[i+17]; } } /** * reads both IR and sonars and assign the minimum values to create a virtual sensor * @param robot pointer */ void getVirtualSensorReadings(Robot *robot) { int *ireads = (int *)malloc(sizeof(int) * INFRAREDS); int *sreads = (int *)malloc(sizeof(int) * SONARS); getAllIRReadings(robot->State,ireads); getAllSonarReadings(robot->State,sreads); int minReading0,minReading1; for (int i = 0; i < SONARS/2; i++) { minReading0 = ireads[2*i] < sreads[2*i] ? ireads[2*i] : sreads[2*i]; minReading1 = ireads[2*i+1] < sreads[2*i+1] ? ireads[2*i+1] : sreads[2*i+1]; robot->vSensors[i] = minReading1 < minReading0 ? minReading1 : minReading0; } free(ireads); free(sreads); } /** * grabs the laser readings from the URGserver and stores them in robot pointer * @param robot pointer to store the readings */ void getLaserSensorReadings(Robot *robot) { int sock; char serverName[128]; char clientName[128]; char message[512]; int N; int *data; strcpy( serverName, "/tmp/socket-urglaser-server" ); strcpy( clientName, "/tmp/socket-urglaser-client" ); sock = makeFilenameSocket( clientName ); // send request message strcpy( message, "I" ); N = sendFilenameSocket( sock, serverName, message, strlen(message)+1 ); // read the image data = readFilenameData( sock, &N); for (int i = 0; i < NUM_LASERS; ++i) { robot->laser[i] = data[i] < 10 || data[i] > 7000 ? 0 : data[i]; } closeFilenameSocket( sock, clientName ); free(data); } /** * convert laser readings (which are in polar coords) to euclidean X-Y coords * @param robot struct to with pointer to laserXY field store the new points in */ void convertLaserToXY(Robot *robot) { int li; for (int i = 0; i < NUM_LASERS; ++i) { li = i - NUM_LASERS/2; robot->laserXY[i].x = (robot->laser[i] * cos((double)(li * DEGREES_PER_LASER * PI / 180.0))) + ROBOT_RADIUS_MM; robot->laserXY[i].y = robot->laser[i] * sin((double)(li * DEGREES_PER_LASER * PI / 180.0)); } } /** * stores the correct laser readings into the particle filter laser array and sets the angles correctly * @param robot */ void updatePFSensors(Robot * robot) { int idx; printf("n: %d\n",robot->particleFilter->nReadings); for (int i = 0; i < robot->particleFilter->nReadings; ++i) { idx = (int)((float)i*(float)NUM_LASERS/(float)robot->particleFilter->nReadings); robot->particleLaserAngles[i] = (idx - NUM_LASERS/2) * DEGREES_PER_LASER * PI / 180.0; robot->particleLaserAngles[i] = robot->particleLaserAngles[i] < 0 ? robot->particleLaserAngles[i] + 2.0 * PI : robot->particleLaserAngles[i]; robot->particleLasers[i] = robot->laser[idx]; } } /** * builds an occupancy grid based on the laseyXY field, where a 1 means that grid cell * is occupied and a 0 means not occupied. the grid is square with side size OG_SIZE/OG_RES, * which are both constants defined in "robot.h" * @param robot */ void buildOccupancyGrid(Robot * robot) { int size = OG_SIZE / OG_RES; int **grid = (int**)malloc(sizeof(int*) * size); for (int i = 0; i < size; i++) { grid[i] = (int*)malloc(sizeof(int) * size); for (int j = 0; j < size; j++) { if (i == 0 || i == size - 1 || j == 0 || j == size -1) { grid[i][j] = 1; } else { grid[i][j] = 0; } } } robot->occupancyGridSize = 0; for (int i = 0; i < NUM_LASERS; i++) { double x = (double)robot->laserXY[i].x/(double)OG_RES; double y = (double)robot->laserXY[i].y/(double)OG_RES; long row = lround(x); long col = lround(y); if (row < size/2 && row > -size/2 && col < size/2 && col > -size/2) { // if within OG_SIZE range grid[row + size/2][col + size/2] = 1; Point p; p.x = (int)col + size/2; p.y = (int)row + size/2; robot->occupancyGrid[robot->occupancyGridSize] = p; robot->occupancyGridSize++; } } for (int i = 0; i < OG_SIZE / OG_RES; ++i) { for (int j = 0; j < OG_SIZE / OG_RES; ++j) { if (grid[i][j] == 0) { printf(" "); } else { printf("0"); } } printf("\n"); } // free grid for (int i = 0; i < size; i++) { free(grid[i]); } free(grid); } /** * Finds if a line segment defined by p0 and p1 intersects a circle defined by center and radius * @param center circle definition * @param radius center definition * @param p0 line start * @param p1 line end * @param intersection Point pointer of the intersection point, NULL if no intersection */ void findLineSegCircleIntersection(Point center, double radius, Point p0, Point p1, Point* intersection) { float dx, dy, A, B, C, det, t; dx = p1.x - p0.x; dy = p1.y - p0.y; A = dx * dx + dy * dy; B = 2 * (dx * (p0.x - center.x) + dy * (p0.y - center.y)); C = (p0.x - center.x) * (p0.x - center.x) + (p0.y - center.y) * (p0.y - center.y) - radius * radius; det = B * B - 4 * A * C; if ((A <= 0.000001) || (det < 0)) { // no real solutions intersection->x = NULL; intersection->y = NULL; } else if (det == 0) { // one solution t = -B / (2 * A); intersection->x = p0.x + t * dx; intersection->y = p0.y + t * dy; } else { // two solutions if (p0.x + (-B + sqrt(det)) / (2 * A) * dx > p0.x + (-B - sqrt(det)) / (2 * A) * dx) { intersection->x = p0.x + (-B + sqrt(det)) / (2 * A) * dx; intersection->y = p0.y + (-B + sqrt(det)) / (2 * A) * dy; } else { intersection->x = p0.x + (-B - sqrt(det)) / (2 * A) * dx; intersection->y = p0.y + (-B - sqrt(det)) / (2 * A) * dy; } } } /** * this funciton converts the orientation of robot to -pi to pi range * @param robot */ void convertOrientation(Robot *robot) { robot->orientationPiToPi = robot->State[STATE_T] > PI * 1000.0 ? robot->State[STATE_T] - (int)(2.0 * PI * 1000.0) : robot->State[STATE_T]; } /* Generates numbers from a Gaussian distribution with zero mean and unit variance. Concept and code from NRC Modified to use drand48() and return doubles */ double gaussDist() { static int iset=0; static double gset; float fac,rsq,v1,v2; // generate a new pair of numbers and return the first if(iset == 0) { do { v1 = 2.0*drand48()-1.0; v2 = 2.0*drand48()-1.0; rsq = v1*v1+v2*v2; } while (rsq >= 1.0 || rsq == 0.0); fac = sqrt(-2.0*log(rsq)/rsq); gset = v1*fac; iset = 1; return(v2*fac); } // return the last number we generated iset = 0; return(gset); } /** * finds the closest flat surface around the robot by taking the minimum reading and * scanning the adjacent readings to look for values that stay pretty similar, * then returns the center of that segment * @param robot */ void findClosestFlatSurface(Robot *robot) { int i, dir, min, mind; min = 8000; mind = 0; for (i=20; i < NUM_LASERS - 20; i++) { if (robot->laser[i] < min ) { if (abs(robot->laser[i+1] - robot->laser[i]) < 20 && abs(robot->laser[i-1] - robot->laser[i]) < 20 && abs(robot->laser[i+2] - robot->laser[i]) < 20 && abs(robot->laser[i-2] - robot->laser[i]) < 20) { min = robot->laser[i]; mind = i; } } } int distFromMin = 1; int donel = 0; int doner = 0; int indl = mind; int indr = mind; printf("min: %d, mind: %d\n", min, mind); while (donel != 1 && doner != 1) { distFromMin = abs(mind - indl); if ((abs(robot->laser[indl] - min) > distFromMin*10) || indl == 0) donel = 1; distFromMin = abs(mind - indr); if ((abs(robot->laser[indr] - min) > distFromMin*10) || indr == NUM_LASERS -1) doner = 1; indr++; indl--; } dir = (indl + indr)/2; robot->laserIdxClosestFlat = dir; } /** * writes a hough accumulator to a text file for debugging * @param accum double pointer to the accumulator * @param nump first dimension size * @param numtheta second dimension size */ void writeHoughAccumulator(int** accum, int nump, int numtheta) { int max = 0; for (int i = 0; i < nump; ++i) { for (int j = 0; j < numtheta; j++) { max = accum[i][j] > max ? accum[i][j] : max; } } printf("done max\n"); for (int i = 0; i < nump; ++i) { for (int j = 0; j < numtheta; j++) { accum[i][j] = (int)(((float)accum[i][j] / (float)max) * 255.0); } } FILE *f = fopen("accum.txt", "w"); if (f == NULL) { printf("Error opening file!\n"); exit(1); } printf("opened file\n"); for (int i = 0; i < nump; ++i) { for (int j = 0; j < numtheta; j++) { if (j == numtheta -1 ) { fprintf(f, "%d", accum[i][j] ); } else { fprintf(f, "%d,", accum[i][j] ); } } fprintf(f,"\n"); } printf("done writing\n"); fclose(f); } /** * performs a hough transform using the laser readings to look for a flat surface * * tweak pmax, thetamaz, deltap, deltatheta for different use cases * stores direction and distance of best straight line in fields of robot * @param robot for accessing lasers */ void houghLine(Robot *robot, int numLines) { printf("in hough\n"); int pmax, deltarho, deltatheta, thetamax, numrho, numtheta, currho, curtheta, x, y, smoothed,rhoidx; pmax = 2000; // max 0.75m thetamax = (int)(2.0 * PI * 1000.0); // 2 pi millirads deltarho = 50; deltatheta = (int)(2.0 * PI * 1000.0 / 90.0); numrho = pmax/deltarho; numtheta = thetamax/deltatheta; // initialize accumulator to zeros Line *lines = (Line*)malloc(sizeof(Line) * numrho * numtheta); for (int i = 0; i < numrho; i++) { for (int j = 0; j < numtheta; j++) { Line l; l.votes = 0; l.rho = i * deltarho; l.theta = (j*deltatheta > PI * 1000.0 ? j*deltatheta - (int)(2.0 * PI * 1000.0) : j*deltatheta); lines[i * numtheta + j] = l; } } printf("made accumulator\n"); for (int i = 0; i < NUM_LASERS; ++i) { for (int j = 0; j < numtheta; j++) { curtheta = j * deltatheta; if (robot->laser[i] == 0) { break; } x = robot->laserXY[i].x; y = robot->laserXY[i].y; currho = (int)(x * cos(((float)curtheta/1000.0)) + y * sin(((float)curtheta/1000.0))); rhoidx = currho/deltarho; if (currho < pmax && currho >= 0) { lines[rhoidx * numtheta + j].votes++; } } } printf("did counts\n"); Line tmp; // sort line list to get best ones for (int i = 0; i < numrho * numtheta - 1; i++) { for (int j = i + 1; j < numrho * numtheta; j++) { if (lines[j].votes > lines[i].votes) { // swap i and j tmp = lines[i]; lines[i] = lines[j]; lines[j] = tmp; } } } static Line *bestLines; bestLines = NULL; if (bestLines == NULL) { bestLines = (Line *) malloc(sizeof(Line) * numLines); } for (int k = 0; k < numLines; ++k) { bestLines[k].rho = -99999; bestLines[k].theta = -99999; bestLines[k].votes = -99999; } // get the best different lines int numAdded = 0; int toAdd; for (int i = 0; i < numrho * numtheta; i++) { toAdd = 1; for (int j = 0; j < numLines; j++) { int thetaDiff = abs(lines[i].theta - bestLines[j].theta); //int rhoDiff = abs(lines[i].rho - bestLines[j].rho); if (thetaDiff < 250) { toAdd = 0; } } if (toAdd){ bestLines[numAdded++] = lines[i]; } if (numAdded == numLines) { break; } } robot->houghBestLines = bestLines; for (int i = 0; i < numLines; ++i) { printf("max accum: %d, distance to line (mm): %d, angle from origin (millirad): %d\n", bestLines[i].votes,bestLines[i].rho,bestLines[i].theta); } if (bestLines[numLines-1].votes < 40) { for (int i = 0; i < numLines; ++i) { printf("bestCounts is less than 40, there are no lines visible\n"); bestLines[i].rho = -999; bestLines[i].theta = -999; } } // writeHoughAccumulator(accumulator,numrho,numtheta); free(lines); } /** * performs a hough transform looking for a circle instead of a line * @param robot */ void houghCircle(Robot *robot) { printf("in hough\n"); int xmax,ymax,numx,numy, x, y, smoothed, maxaccum, bestx, besty, numpoints, thisx, thisy; double deltatheta,curtheta; xmax = 500; ymax = 500; // max .5m numx = xmax*2; numy = ymax*2; numpoints = 720; deltatheta = 2 * PI / 180.0; // initialize accumulator to zeros int **accumulator = (int**)malloc(sizeof(int*) * numx); int **smoothAccum = (int**)malloc(sizeof(int*) * numx); for (int i = 0; i < numx; ++i) { accumulator[i] = (int*)malloc(sizeof(int) * numy); smoothAccum[i] = (int*)malloc(sizeof(int) * numy); } for (int i = 0; i < numx; ++i) { for (int j = 0; j < numy; ++j) { accumulator[i][j] = 0; } } printf("made accumulator\n"); for (int i = 0; i < NUM_LASERS; ++i) { for (int j = 0; j < numpoints; j++) { curtheta = j * deltatheta; x = robot->laserXY[i].x; y = robot->laserXY[i].y; thisx = (int)(x + robot->houghRadius * cos(curtheta)); thisy = (int)(y + robot->houghRadius * sin(curtheta)); if (thisx < xmax && thisx > -xmax && thisy < ymax && thisy > -ymax) { accumulator[thisx+xmax][thisy+ymax]++; } } } printf("did counts\n"); // smooth accumulator maxaccum = 0; for (int i = 1; i < numx-1; ++i) { for (int j = 1; j < numy-1; ++j) { smoothed = accumulator[i][j]*0.3 + accumulator[i-1][j]*0.125 + accumulator[i+1][j]*0.125 + accumulator[i][j-1]*0.125 + accumulator[i][j+1]*0.125 + accumulator[i-1][j-1]*0.05 + accumulator[i+1][j-1]*0.05 + accumulator[i-1][j+1]*0.05 + accumulator[i-1][j-1]*0.05; smoothAccum[i][j] = smoothed; if (maxaccum < smoothed) { maxaccum = smoothed; bestx = i-xmax; besty = j-ymax; } } } if (maxaccum < 5) { printf("maxaccum is less than 3, there are no circles visible\n"); robot->houghCircleCenter.x = 8000; robot->houghCircleCenter.y = 8000; } else { printf("max accum: %d, x: %d, y: %d\n",maxaccum,bestx,besty); robot->houghCircleCenter.x = bestx; robot->houghCircleCenter.y = besty; } // writeHoughAccumulator(accumulator,nump,numtheta); for (int i = 0; i < numx; ++i) { free(accumulator[i]); free(smoothAccum[i]); } free(accumulator); free(smoothAccum); } /** * limits the translation and rotation velocity commands to a hard max and an acceleration max * @param robot * @param vt proposed translation command * @param wt proposed rotation command */ void limitVMCommands(Robot* robot,int *vt, int *wt) { int vaccel,waccel; while (*vt > MAX_TRANS_SPEED || *wt > MAX_ROT_SPEED || *vt < -MAX_TRANS_SPEED || *wt < -MAX_ROT_SPEED ) { //printf("the first while loop %d,%d,%d,%d\n", *vt,*wt,lastv,lastw); *vt = (*vt) * 9 / 10; *wt = (*wt) * 9 / 10; } vaccel = (*vt) - robot->vt; waccel = (*wt) - robot->wt; *vt = vaccel > MAX_TRANS_ACCEL ? robot->vt + MAX_TRANS_ACCEL : *vt; *vt = vaccel < -MAX_TRANS_ACCEL ? robot->vt - MAX_TRANS_ACCEL : *vt; *wt = waccel > MAX_ROT_ACCEL ? robot->wt + MAX_ROT_ACCEL : *wt; *wt = waccel < -MAX_ROT_ACCEL ? robot->wt - MAX_ROT_ACCEL : *wt; } /** * makes sure the robot isn't gonna run into something, and stops it if it is * called right before executing the vm() command in the main loop * @param robot * @param vt proposed translation velocity * @param wt proposed rotation velocity */ void stopForObstacles(Robot *robot,int*vt,int*wt) { int minObj = 80000; int dir; // if moving forward if ((*vt) > 0) { // loop through front IR/sonar for (int i = 0; i < NUM_VSENSORS; i++) { if (robot->vSensors[i] < minObj && robot->vSensors[i] > 3) { i = i == -1 ? 6 : i; minObj = robot->vSensors[i]; dir = i; } } // loop through lasers for (int i = 0; i < NUM_LASERS; i++) { int dist = (int)sqrt(robot->laserXY->x*robot->laserXY->x - robot->laserXY->y*robot->laserXY->y); minObj = dist - ROBOT_RADIUS_MM < minObj ? dist - ROBOT_RADIUS_MM : minObj; } // else moving backward } else { for (int i = 2; i < 6; ++i) { if (robot->vSensors[i] < minObj && robot->vSensors[i] > 3) { minObj = robot->vSensors[i]; dir = i; } } } if (minObj < 75 && minObj != 0) { printf("emergency stop! Object in %d mm\n",minObj); *vt = (*vt) > 0 ? -100 : 100; *wt = 0; } } /** * returns the p-value association with a given zscore based on a table * @param zscore * @return */ float getPValue(float zscore) { float pVals[] = { .0003 ,.0003 ,.0003 ,.0003 ,.0003 ,.0003 ,.0003 ,.0003 ,.0003 ,.0002 ,.0005 ,.0005 ,.0005 ,.0004 ,.0004 ,.0004 ,.0004 ,.0004 ,.0004 ,.0003 ,.0007 ,.0007 ,.0006 ,.0006 ,.0006 ,.0006 ,.0006 ,.0005 ,.0005 ,.0005 ,.0010 ,.0009 ,.0009 ,.0009 ,.0008 ,.0008 ,.0008 ,.0008 ,.0007 ,.0007 ,.0013 ,.0013 ,.0013 ,.0012 ,.0012 ,.0011 ,.0011 ,.0011 ,.0010 ,.0010 ,.0019 ,.0018 ,.0018 ,.0017 ,.0016 ,.0016 ,.0015 ,.0015 ,.0014 ,.0014 ,.0026 ,.0025 ,.0024 ,.0023 ,.0023 ,.0022 ,.0021 ,.0021 ,.0020 ,.0019 ,.0035 ,.0034 ,.0033 ,.0032 ,.0031 ,.0030 ,.0029 ,.0028 ,.0027 ,.0026 ,.0047 ,.0045 ,.0044 ,.0043 ,.0041 ,.0040 ,.0039 ,.0038 ,.0037 ,.0036 ,.0062 ,.0060 ,.0059 ,.0057 ,.0055 ,.0054 ,.0052 ,.0051 ,.0049 ,.0048 ,.0082 ,.0080 ,.0078 ,.0075 ,.0073 ,.0071 ,.0069 ,.0068 ,.0066 ,.0064 ,.0107 ,.0104 ,.0102 ,.0099 ,.0096 ,.0094 ,.0091 ,.0089 ,.0087 ,.0084 ,.0139 ,.0136 ,.0132 ,.0129 ,.0125 ,.0122 ,.0119 ,.0116 ,.0113 ,.0110 ,.0179 ,.0174 ,.0170 ,.0166 ,.0162 ,.0158 ,.0154 ,.0150 ,.0146 ,.0143 ,.0228 ,.0222 ,.0217 ,.0212 ,.0207 ,.0202 ,.0197 ,.0192 ,.0188 ,.0183 ,.0287 ,.0281 ,.0274 ,.0268 ,.0262 ,.0256 ,.0250 ,.0244 ,.0239 ,.0233 ,.0359 ,.0351 ,.0344 ,.0336 ,.0329 ,.0322 ,.0314 ,.0307 ,.0301 ,.0294 ,.0446 ,.0436 ,.0427 ,.0418 ,.0409 ,.0401 ,.0392 ,.0384 ,.0375 ,.0367 ,.0548 ,.0537 ,.0526 ,.0516 ,.0505 ,.0495 ,.0485 ,.0475 ,.0465 ,.0455 ,.0668 ,.0655 ,.0643 ,.0630 ,.0618 ,.0606 ,.0594 ,.0582 ,.0571 ,.0559 ,.0808 ,.0793 ,.0778 ,.0764 ,.0749 ,.0735 ,.0721 ,.0708 ,.0694 ,.0681 ,.0968 ,.0951 ,.0934 ,.0918 ,.0901 ,.0885 ,.0869 ,.0853 ,.0838 ,.0823 ,.1151 ,.1131 ,.1112 ,.1093 ,.1075 ,.1056 ,.1038 ,.1020 ,.1003 ,.0985 ,.1357 ,.1335 ,.1314 ,.1292 ,.1271 ,.1251 ,.1230 ,.1210 ,.1190 ,.1170 ,.1587 ,.1562 ,.1539 ,.1515 ,.1492 ,.1469 ,.1446 ,.1423 ,.1401 ,.1379 ,.1841 ,.1814 ,.1788 ,.1762 ,.1736 ,.1711 ,.1685 ,.1660 ,.1635 ,.1611 ,.2119 ,.2090 ,.2061 ,.2033 ,.2005 ,.1977 ,.1949 ,.1922 ,.1894 ,.1867 ,.2420 ,.2389 ,.2358 ,.2327 ,.2296 ,.2266 ,.2236 ,.2206 ,.2177 ,.2148 ,.2743 ,.2709 ,.2676 ,.2643 ,.2611 ,.2578 ,.2546 ,.2514 ,.2483 ,.2451 ,.3085 ,.3050 ,.3015 ,.2981 ,.2946 ,.2912 ,.2877 ,.2843 ,.2810 ,.2776 ,.3446 ,.3409 ,.3372 ,.3336 ,.3300 ,.3264 ,.3228 ,.3192 ,.3156 ,.3121 ,.3821 ,.3783 ,.3745 ,.3707 ,.3669 ,.3632 ,.3594 ,.3557 ,.3520 ,.3483 ,.4207 ,.4168 ,.4129 ,.4090 ,.4052 ,.4013 ,.3974 ,.3936 ,.3897 ,.3859 ,.4602 ,.4562 ,.4522 ,.4483 ,.4443 ,.4404 ,.4364 ,.4325 ,.4286 ,.4247 ,.5000 ,.4960 ,.4920 ,.4880 ,.4840 ,.4801 ,.4761 ,.4721 ,.4681 ,.4641 }; int z,total,rem,tens,idx; z = zscore < 0 ? (int)(-100.0*zscore) : (int)(100.0*zscore); if (z > 350) { return 0.0001; } total = 350; rem = z%10; tens = (int)ceil((double)z/10.0) * 10; idx = total - (tens - rem) - 1; // printf("idx:%d,tens:%d,rem%d\n",idx,tens,rem); return pVals[idx]; } /** * writes the particle filter to an image with all particles being red dots * @param particleFilter * @param est best particle for special drawing * @param map to draw on * @param pfImage Pixel array * @param N index of image */ void writePFToImage(ParticleFilter *particleFilter,Particle est,Map*map,Pixel*pfImage,int N) { for (int i = 0; i < particleFilter->N; i++) { map_set(map, particleFilter->p[i].x, particleFilter->p[i].y, 50); } map_set(map, est.x, est.y, 49); printf("done drawing particles\n"); map_setPix(map, pfImage); // reset particles to white for (int i = 0; i < particleFilter->N; i++) { map_set(map, particleFilter->p[i].x, particleFilter->p[i].y, 255); } char f[50]; sprintf(f, "../out/p%03d.ppm", N); writePPM(pfImage, map->rows, map->cols, 255, f); printf("wrote ppm\n"); } /** * frees a robot and all inner fields. needs to be called before program exits * @param robot to free */ void freeRobot(Robot *robot) { free(robot->vSensors); free(robot->laser); free(robot->laserXY); free(robot->pfPoints); IPC_freeData(IPC_msgFormatter(SVM_DATA_RESPONSE), robot->SVMData); free(robot->occupancyGrid); pf_free(robot->particleFilter); map_free(robot->map); free(robot->particleLasers); free(robot->particleLaserAngles); free(robot->pfImage); free(robot); }
C
#include <value.h> #include <basic.h> #include <num.h> #include <output.h> #include <str.h> #include <type_num.h> #include <type_output.h> #include <type_str.h> static void putv(value x) { x = eval(hold(x)); while (1) { if (x->T == type_str) put_str(data(x)); else if (x->T == type_num) put_num(data(x)); else if (x->T == type_T) put_ch('T'); else if (x->T == type_F) put_ch('F'); else if (x->T == type_cons && x->L && x->L->L) { putv(x->L->R); /* Eliminated tail recursive call putv(x->R) here. */ { value y = eval(hold(x->R)); drop(x); x = y; continue; } } drop(x); return; } } value type_put(value f) { if (!f->L) return 0; putv(f->R); return hold(I); } value type_nl(value f) { (void)f; nl(); return hold(I); } value type_say(value f) { f = type_put(f); if (f == I) nl(); return f; } /* (put_to_error x) = x. Evaluates x with all output going to stderr. */ value type_put_to_error(value f) { if (!f->L) return 0; { output save = putd; put_to_error(); f = eval(hold(f->R)); putd = save; return f; } }
C
/* Lista de exerccios 3 Exerccio 1 - Programa que cadastra as notas de n alunos de uma disciplina e retorna os alunos que obtiveram a maior e a menor nota */ #include <stdio.h> #include <stdlib.h> #define TAMANHO 100 // O vetor nota guardara a nota de no maximo 100 alunos int main(){ int n, i, j, indice_maior, indice_menor; float nota[TAMANHO]; float maior, menor; printf("Numero de alunos:\n"); scanf("%d", &n); printf("Entre com as notas\n"); for(i=0; i<n; i++){ scanf("%f", &nota[i]); } /* Encontra a maior nota */ maior = nota[0]; indice_maior = 1; for(j=1; j<n; j++){ if(maior < nota[j]){ maior = nota[j]; indice_maior = j + 1; } } /* Encontra a menor nota */ menor = nota[0]; indice_menor = 1; for(j=1; j<n; j++){ if(menor > nota[j]){ menor = nota[j]; indice_menor = j + 1; } } /* Imprime as posicoes e as notas dos alunos que obtiveram a maior e a menor nota, respectivamente */ printf("O aluno numero %d teve a maior nota (%2.2f) e o aluno %d teve a menor nota (%2.2f)\n\n", indice_maior, maior, indice_menor, menor); system ("pause"); return 0; }
C
// // Created by q on 4/10/2020. // #ifndef ASSIGNMENT5_GRAPHALGORITHMS_H #define ASSIGNMENT5_GRAPHALGORITHMS_H #include "matrix.h" #include "node.h" #include "traversGraph.h" #include "edge.h" #define UNDEFINED -1 #define MAX_LIMIT 9999 /* * kruskal */ void kruskal(int N, int ** A); // find parent of node int findParent(int * parents, int node); // create array of parents int * createParentArray(int M); // unite two components void unite(int *parents, EdgeT edge); // find min edge which doesn't close a cycle EdgeT findMinEdge(int N, int ** A, int * parents); /* * bellman-ford */ //bellman void bellmanFord(int N, int ** A, int start); // create array int * createAndInitializeArray(int N, int init); // print array pf distances void printDistances(int N, int * distances); // print the shortest distance path void printPath(int i, int * previous); // get the number of edges int getNoOfEdges(int N, int ** A); // create array of edges EdgeT * getAllEdges(int N, int ** A, int noOfEdges); // function to detect if there are any negative cycles int detectNegativeCycle(int M,EdgeT * edges, int * distances); #endif //ASSIGNMENT5_GRAPHALGORITHMS_H
C
#include "utils.h" #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdint.h> #include "app-error.h" char *read_line(int *len) { return file_read_line(stdin, len); } char *file_read_line(FILE *f, int *str_len) { size_t buf_size, new_buf_size, i; char c, *new_str, *str; int will_overflow; *str_len = 0; buf_size = 256; str = malloc(buf_size * sizeof(char)); i = 0; while (1) { if (buf_size == i) { if (buf_size == SIZE_MAX) { handle_fatal_error(E_ALLOC); } will_overflow = (buf_size >> (sizeof(size_t) * 8 - 1)) == 1; new_buf_size = will_overflow ? SIZE_MAX : buf_size*2; new_str = (char *)realloc(str, new_buf_size); if (new_str == NULL) { handle_fatal_error(E_ALLOC); } *str_len = strlen(str); str = new_str; } c = fgetc(f); if (c == '\n' || c == EOF) { *str_len = i; str[i++] = '\0'; return str; } str[i++] = c; *str_len = strlen(str); } return str; } char *strdup_(char *str) { size_t i; char *str_c; if (str == NULL) { str_c = NULL; } else { str_c = malloc((strlen(str) + 1) * sizeof(char)); if (str_c == NULL) { handle_fatal_error(E_ALLOC); } i = 0; while ((str_c[i] = str[i]) != '\0') { i++; } } return str_c; } /* Taken from GNU Libc. */ char *strsep_(char **stringp, const char *delim) { char *begin, *end; begin = *stringp; if (begin != NULL) { end = begin + strcspn (begin, delim); if (*end) { *(end++) = '\0'; *stringp = end; } else { *stringp = NULL; } } return begin; } int strcnt_(char *str, const char sym) { int count; count = 0; while (*str != '\0') { if (*str == sym) { count++; } str++; } return count; } char* str_repeat(char* str, size_t times) { char *ret = malloc((strlen(str) * times + 1) * sizeof(char)); if (ret == NULL) { handle_fatal_error(E_ALLOC); } ret[0] = '\0'; while (times-- > 0) { strcat(ret, str); } return ret; } void str_trunc(char *str, int max_len) { if ((int)strlen(str) > max_len) { str[max_len] = '~'; str[max_len+1] = '\0'; } } error_t str_validate(char *str, char *whilelist) { error_t err; int is_empty_str; is_empty_str = 1; err = SUCCESS; while (*str != '\0' && SUCC(err)) { if (!(char_is_valid(*str) || strchr(whilelist, *str) != NULL)) { err = E_INVALID_STR; } str++; is_empty_str = 0; } if (is_empty_str) { err = E_INVALID_STR; } return err; } int char_is_valid(char c) { return !( c == ':' || c == ';' || c == '*' || c == '?' || c == '"' || c == '|' || c == '<' || c == '>' || c == '+' || c == '%' || c == '!' || c == '@' ); }
C
#include <errno.h> #include <string.h> #include <unistd.h> #include <netdb.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/select.h> #include <stdlib.h>//Linux #include <stdio.h>//Linux int g_id = 0; typedef struct s_c{ int fd; int id; char *rcvBuf; struct s_c *nxt; }t_c; typedef struct s_info{ int sock; int fdMax; fd_set select; fd_set save; t_c *clients; }t_info; int extract_message(char **buf, char **msg) { char *newbuf; int i; *msg = 0; if (*buf == 0) return (0); i = 0; while ((*buf)[i]) { if ((*buf)[i] == '\n') { newbuf = calloc(1, sizeof(*newbuf) * (strlen(*buf + i + 1) + 1)); if (newbuf == 0) return (-1); strcpy(newbuf, *buf + i + 1); *msg = *buf; (*msg)[i + 1] = 0; *buf = newbuf; return (1); } i++; } return (0); } char *str_join(char *buf, char *add) { char *newbuf; int len; if (buf == 0) len = 0; else len = strlen(buf); newbuf = malloc(sizeof(*newbuf) * (len + strlen(add) + 1)); if (newbuf == 0) return (0); newbuf[0] = 0; if (buf != 0) strcat(newbuf, buf); if (buf) free(buf); strcat(newbuf, add); return (newbuf); } void exit_error(int code, t_info *info){ if (info){ FD_CLR(info->sock, &info->save); close(info->sock); t_c *nxt; t_c *cli = info->clients; while (cli){ nxt = cli->nxt; FD_CLR(cli->fd, &info->save); close(cli->fd); if (cli->rcvBuf) free(cli->rcvBuf); free(cli); cli = nxt; } } if (code == 0) write(2, "Wrong number of arguments\n", strlen("Wrong number of arguments\n")); else write(2, "Fatal error\n", strlen("Fatal error\n")); exit(1); } void init(t_info *info, int port){ int sockfd; struct sockaddr_in servaddr; // socket create and verification sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) exit_error(1, info); info->sock = sockfd; info->fdMax = sockfd; FD_ZERO(&info->select); FD_ZERO(&info->save); FD_SET(info->sock, &info->save); info->clients = NULL; bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(2130706433); //127.0.0.1 servaddr.sin_port = htons(port); // Binding newly created socket to given IP and verification if ((bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr))) != 0) exit_error(1, info); if (listen(sockfd, 10) != 0) exit_error(1, info); } int add_client(t_info *info, int fd){ t_c *cli = info->clients; t_c *new; if ( !(new = malloc(sizeof(t_c))) ) exit_error(1, info); new->fd = fd; new->id = g_id++; new->nxt = NULL; new->rcvBuf = NULL; if (!cli){ info->clients = new; return (new->id); } while (cli->nxt) cli = cli->nxt; cli->nxt = new; return (new->id); } void send_all(t_info *info, char *msg, int fd){ t_c *cli = info->clients; int len = strlen(msg); while(cli){ if (cli->fd != info->sock && cli->fd != fd){ int sent = 0; int ret = 0; while (sent < len){ ret = send(cli->fd, msg + sent, len - sent, MSG_DONTWAIT); if (ret <= 0) break; sent += ret; } } cli = cli->nxt; } } void new_client(t_info *info){ int connfd; unsigned int len; struct sockaddr_in cli; char msg[50]; len = sizeof(cli); connfd = accept(info->sock, (struct sockaddr *)&cli, &len); if (connfd < 0) exit_error(1, info); int id = add_client(info, connfd); sprintf(msg, "server: client %d just arrived\n", id); send_all(info, msg, connfd); FD_SET(connfd, &info->save); if (connfd > info->fdMax) info->fdMax = connfd; } void remove_client(t_info *info, int fd){ t_c *bef = info->clients; t_c *cli = bef->nxt; FD_CLR(fd, &info->save); close(fd); if (bef->fd == fd){ info->clients = cli; if (bef->rcvBuf) free(bef->rcvBuf); free(bef); return ; } while (cli){ if (cli->fd == fd){ bef->nxt = cli->nxt; if (cli->rcvBuf) free(cli->rcvBuf); free(cli); return ; } bef = cli; cli = cli->nxt; } } void recv_client(t_info *info, t_c *cli){ char buf[15000 + 1]; char msg[50]; char *sendBuf; char *newMsg; int ret = recv(cli->fd, buf, 15000, MSG_DONTWAIT); buf[ret] = '\0'; cli->rcvBuf = str_join(cli->rcvBuf, buf); if (!cli->rcvBuf) exit_error(1, info); if (ret == 0){ sprintf(msg, "server: client %d just left\n", cli->id); remove_client(info, cli->fd); send_all(info, msg, -1); } else if (ret > 0){ while ( (ret = extract_message(&cli->rcvBuf, &newMsg)) == 1){ if ( !(sendBuf = (char *)malloc(sizeof(char) * (strlen(newMsg) + 50))) ) exit_error(1, info); bzero(sendBuf, strlen(sendBuf) + 50);// or use calloc sprintf(sendBuf, "client %d: %s", cli->id, newMsg); send_all(info, sendBuf, cli->fd); if (newMsg) free(newMsg); free(sendBuf); } if (ret == -1) exit_error(1, info); } } int main(int ac, char **av) { t_info info; if (ac != 2) exit_error(0, NULL); init(&info, atoi(av[1])); while (1){ info.select = info.save; if ( (select(info.fdMax +1, &info.select, 0, 0, 0)) == -1) exit_error(1, &info); if (FD_ISSET(info.sock, &info.select)) new_client(&info); t_c *cli = info.clients; t_c *nxt; while (cli){ nxt = cli->nxt; if (FD_ISSET(cli->fd, &info.select)) recv_client(&info, cli); cli = nxt; } } return (0); }
C
#include <stdio.h> #include <stdlib.h> #include<math.h> void giaipt(float a,float b,float c) { if(a==0) { if(b==0) { if(c==0) printf("phuong trinh co vo so nghiem "); else printf("phuong trinh vo nghiem "); } else { printf("phuong trinh co 1 nghiem x=%f ",-c/b); } } else { float delta=b*b-4*a*c; if(delta<0) printf("phuong trinh vo nghiem!"); else if(delta==0) printf("phuong trinh co nghiem kep x1=x2=%f ",-b/(2*a)); else printf("phuong trinh co 2 nghiem phan biet x1=%f,x2=%f",(-b-sqrt(delta))/(2*a),(-b+sqrt(delta))/(2*a)); } } int main() { float a,b,c,delta; printf("nhap vao he so a,b,c: "); scanf("%f%f%f",&a,&b,&c); giaipt(a,b,c); return 0; }
C
int check_buf(char *buf, char **line, char *p) { if (p) { *p = '\0'; if (!(*line = free_set(*line, ft_strjoin(*line, buf)))) return (-1)); while (*++p) *buf++ = *p; *buf = '\0'; return (1); } else if (!(*line = free_set(*line, ft_strjoin(*line, buf)))) return (-1)); return (0); } int get_next_line(int fd, char **line) { int ret; char *p; int64_t len; static char buf[(uint64_t)BUFFER_SIZE + 1]; *line = NULL; if ((ret = check_buf(&buf, line, ft_strchr(buf, '\n')))) return (ret); while (1) { if ((len = read(fd, buf, BUFFER_SIZE)) < 1) break ; buf[len] = '\0'; if ((p = ft_strchr(buf, '\n'))) return (check_buf(&buf, line, p)); if (!(*line = free_set(*line, ft_strjoin(*line, buf)))) return (freeturn(&buf, -1)); } return (len ? -1 : 0); }
C
/* Largest Independent Set in a BT Given a binary tree, find the size of the largest independent set [LIS] in it. Independent set: Subset of all tree nodes such that there is no edge between any two nodes \ of the subset.Refer q11 for explanation. Instead of taking the root->data in this ques, we need to count that node in the independent set. -------------------------------------------------------------------------------------------------- Note: If we directly try to solve this problem using the recursive equation, it will be an exponential time solution. We notice that the subproblems are repeating, so we use DP. LISS(x)=max(1+sum(LIIS(grand children)), sum(LISS(children))) NOTE: We use post order traversal to compute the LISS. It means that we compute the LIS when we visit the node for the first time. TC=O(n)*O(6) [because in worst case, we check 2 children and 4 grand children] =O(n) */
C
#include <string.h> #include <stdio.h> #include <stdlib.h> #include <sys/wait.h> #include <unistd.h> #include "ThinkGridWorldShell.h" #define INPUT_BUFF_SIZE 1024; #define PARAM_BUFF_SIZE 64; #define NUM_BUILTINS 1; int toExit = 0; /* */ char *BUILTIN_COMMANDS[] = {"cd"}; /* */ int (*BUILTIN_COMMAND_FUNCTIONS[]) (char**) = { &shell_cd }; int shell_cd(char **inputParams) { if (inputParams[1] == NULL) { perror("shell"); } else { if (chdir(inputParams[1]) != 0) { perror("shell"); } } return 1; } /* */ int execute(char **inputParams) { int i; for (i = 0; i < 1; i++) { if (strcmp(inputParams[0], BUILTIN_COMMANDS[i]) == 0) { return (*BUILTIN_COMMAND_FUNCTIONS[i])(inputParams); } } /* If it is not a built-in command, go ahead and execute. */ pid_t process, waitProcess; int process_state; printf("Kicking off process"); process = fork(); if (process == 0) { if (execvp(inputParams[0], inputParams) == -1) { perror("shell"); } exit(EXIT_FAILURE); } else if (process < 0) { perror("shell"); } else { do { waitProcess = waitpid(process, &process_state, WUNTRACED); } while (!WIFEXITED(process_state) && !WIFSIGNALED(process_state)); } return 1; } /* Reads and seperates user parameters on a single line *inputLine: reference to line to be parsed */ char** parseParams(char *inputLine){ size_t size = PARAM_BUFF_SIZE; char **paramsList = (char **)malloc(size * sizeof(char)); char *token; token = strtok(inputLine," "); //Current seperator set by spaces int i=0; while(token!=NULL){ paramsList[i]= token; i++; token = strtok(NULL," "); } paramsList[i]=NULL; return paramsList; } /* Reads and stores the user's input from stdin into buffer */ char* readLine(){ size_t size = 0; //INPUT_BUFF_SIZE; //automatically allocated with getline //char *inputBuff = (char *)malloc(size * sizeof(char)); char* inputBuff = NULL; printf(">>> "); getline(&inputBuff,&size,stdin); return inputBuff; } /* Loops through reading and parsing lines until exit command is reached */ void shell_loop(){ while(1){ char *inputLine = readLine(); char **inputParams = parseParams(inputLine); int status = execute(inputParams); /* toExit = 1; //Tempory Force Break until error handling if(toExit){ break; }*/ } } int main(int argc, char **argv){ shell_loop(); return 0; }
C
#include <stdio.h> #include <math.h> int isprime(int num); int main(void) { int n; printf("Enter a number: "); scanf("%i",&n); if(n>1) { if(isprime(n)) { printf("Prime\n"); } else { printf("Not prime\n"); } } return 0; } int isprime(int num) { int i, count = sqrt(num); for(i=2;i<=count;i++) { if(num%i==0) { return 0; } } if(i>count) { return 1; } }
C
#include <stdio.h> #include <cs50.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <math.h> int main(void) { //get input string text = get_string("Text: "); int num_letras = 0; int num_palabras = 1; int num_sent = 0; //loop to get letters for (int i = 0; text[i] != '\0'; i++) { if (isalpha(text[i])) { //printf("%c",text[i]); num_letras ++; } if (text[i] == ' ' || text[i] == '\n' || text[i] == '\t') { num_palabras++; } if (text[i] == '!' || text[i] == '.' || text[i] == '?') { num_sent ++; } } //get average letter and sentences float avg_let = ((float)(num_letras) / (float)num_palabras) * 100; float avg_sent = ((float)(num_sent) / (float)num_palabras) * 100; //calculate int index = (int)round((0.0588 * avg_let) - (0.296 * avg_sent) - 15.8); //print if (index < 1) { printf("Before Grade 1\n"); } else if (index > 16) { printf("Grade 16+\n"); } else { printf("Grade %i\n", index); } }
C
// Hopefully useful code for C (memory block movers) // Copyright (C) 2022 Recherche en Prevision Numerique // // This code is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, // version 2.1 of the License. // // This code is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // #include <stdint.h> #include "with_simd.h" #include <rmn/misc_operators.h> // SIMD does not seem to be useful any more for these funtions #undef WITH_SIMD #if ! defined(__INTEL_COMPILER_UPDATE) #pragma GCC optimize "tree-vectorize" #endif // special case for rows shorter than 8 elements // insert a contiguous block (ni x nj) of 32 bit words into f from blk // ni : row size (row storage size in blk) // lni : row storage size in f // nj : number of rows int put_word_block_07(void *restrict f, void *restrict blk, int ni, int lni, int nj){ uint32_t *restrict d = (uint32_t *) f ; uint32_t *restrict s = (uint32_t *) blk ; int i, ni7 ; #if defined(__x86_64__) && defined(__AVX2__) && defined(WITH_SIMD) __m256i vm = _mm256_memmask_si256(ni) ; // mask for load and store operations #endif if(ni > 7) return 1 ; ni7 = (ni & 7) ; while(nj--){ #if defined(__x86_64__) && defined(__AVX2__) && defined(WITH_SIMD) _mm256_maskstore_epi32 ((int *)d, vm, _mm256_maskload_epi32 ((int const *) s, vm) ) ; #else for(i=0 ; i < ni7 ; i++) d[i] = s[i] ; #endif s += ni ; d += lni ; } return 0 ; } // special case for rows shorter than 8 elements // extract a contiguous block (ni x nj) of 32 bit words from f into blk // ni : row size (row storage size in blk) // lni : row storage size in f // nj : number of rows int get_word_block_07(void *restrict f, void *restrict blk, int ni, int lni, int nj){ uint32_t *restrict s = (uint32_t *) f ; uint32_t *restrict d = (uint32_t *) blk ; int i, ni7 ; #if defined(__x86_64__) && defined(__AVX2__) && defined(WITH_SIMD) __m256i vm = _mm256_memmask_si256(ni) ; // mask for load and store operations #endif if(ni > 7) return 1 ; ni7 = (ni & 7) ; while(nj--){ #if defined(__x86_64__) && defined(__AVX2__) && defined(WITH_SIMD) _mm256_maskstore_epi32 ((int *)d, vm, _mm256_maskload_epi32 ((int const *) s, vm) ) ; #else for(i=0 ; i < ni7 ; i++) d[i] = s[i] ; #endif s += lni ; d += ni ; } return 0 ; } // specialized versions for ni = 8 / 32 / 64 (not needed for now) #if 0 // special case for row length 8 // insert a contiguous block (ni x nj) of 32 bit words into f from blk // ni : row size (row storage size in blk) // lni : row storage size in f // nj : number of rows int put_word_block_08(void *restrict f, void *restrict blk, int ni, int lni, int nj){ uint32_t *restrict d = (uint32_t *) f ; uint32_t *restrict s = (uint32_t *) blk ; int i0, i, j ; if(ni != 8) return 1 ; if(nj == 8){ for(j=0 ; j<8 ; j++){ for(i=0 ; i<8 ; i++) d[i] = s[i] ; s += 8 ; d += lni ; } }else{ while(nj--){ for(i=0 ; i<8 ; i++) d[i] = s[i] ; s += 8 ; d += lni ; } } return 0 ; } // special case for row length 8 // extract a contiguous block (ni x nj) of 32 bit words from f into blk // ni : row size (row storage size in blk) // lni : row storage size in f // nj : number of rows int get_word_block_08(void *restrict f, void *restrict blk, int ni, int lni, int nj){ uint32_t *restrict s = (uint32_t *) f ; uint32_t *restrict d = (uint32_t *) blk ; int i0, i, j ; if(ni != 8) return 1 ; if(nj == 8){ for(j=0 ; j<8 ; j++){ for(i=0 ; i<8 ; i++) d[i] = s[i] ; s += lni ; d += 8 ; } }else{ while(nj--){ for(i=0 ; i<8 ; i++) d[i] = s[i] ; s += lni ; d += 8 ; } } return 0 ; } // special case for row length 32 // insert a contiguous block (ni x nj) of 32 bit words into f from blk // ni : row size (row storage size in blk) // lni : row storage size in f // nj : number of rows int put_word_block_32(void *restrict f, void *restrict blk, int ni, int lni, int nj){ uint32_t *restrict d = (uint32_t *) f ; uint32_t *restrict s = (uint32_t *) blk ; int i0, i ; if(ni != 32) return 1 ; while(nj--){ #if defined(__x86_64__) && defined(__AVX2__) && defined(WITH_SIMD) _mm256_storeu_si256((__m256i *)(d+ 0), _mm256_loadu_si256((__m256i *)(s+ 0))) ; _mm256_storeu_si256((__m256i *)(d+ 8), _mm256_loadu_si256((__m256i *)(s+ 8))) ; _mm256_storeu_si256((__m256i *)(d+16), _mm256_loadu_si256((__m256i *)(s+16))) ; _mm256_storeu_si256((__m256i *)(d+24), _mm256_loadu_si256((__m256i *)(s+24))) ; #else for(i=0 ; i<32 ; i++) d[i] = s[i] ; #endif s += 32 ; d += lni ; } return 0 ; } // special case for row length 32 // extract a contiguous block (ni x nj) of 32 bit words from f into blk // ni : row size (row storage size in blk) // lni : row storage size in f // nj : number of rows int get_word_block_32(void *restrict f, void *restrict blk, int ni, int lni, int nj){ uint32_t *restrict s = (uint32_t *) f ; uint32_t *restrict d = (uint32_t *) blk ; int i0, i ; if(ni != 32) return 1 ; while(nj--){ #if defined(__x86_64__) && defined(__AVX2__) && defined(WITH_SIMD) _mm256_storeu_si256((__m256i *)(d+ 0), _mm256_loadu_si256((__m256i *)(s+ 0))) ; _mm256_storeu_si256((__m256i *)(d+ 8), _mm256_loadu_si256((__m256i *)(s+ 8))) ; _mm256_storeu_si256((__m256i *)(d+16), _mm256_loadu_si256((__m256i *)(s+16))) ; _mm256_storeu_si256((__m256i *)(d+24), _mm256_loadu_si256((__m256i *)(s+24))) ; #else for(i=0 ; i<32 ; i++) d[i] = s[i] ; #endif s += lni ; d += 32 ; } return 0 ; } // special case for row length 64 // insert a contiguous block (ni x nj) of 32 bit words into f from blk // ni : row size (row storage size in blk) // lni : row storage size in f // nj : number of rows int put_word_block_64(void *restrict f, void *restrict blk, int ni, int lni, int nj){ uint32_t *restrict d = (uint32_t *) f ; uint32_t *restrict s = (uint32_t *) blk ; int i0, i, ni7 ; if(ni != 64) return 1 ; while(nj--){ #if defined(__x86_64__) && defined(__AVX2__) && defined(WITH_SIMD) _mm256_storeu_si256((__m256i *)(d+ 0), _mm256_loadu_si256((__m256i *)(s+ 0))) ; _mm256_storeu_si256((__m256i *)(d+ 8), _mm256_loadu_si256((__m256i *)(s+ 8))) ; _mm256_storeu_si256((__m256i *)(d+16), _mm256_loadu_si256((__m256i *)(s+16))) ; _mm256_storeu_si256((__m256i *)(d+24), _mm256_loadu_si256((__m256i *)(s+24))) ; _mm256_storeu_si256((__m256i *)(d+32), _mm256_loadu_si256((__m256i *)(s+32))) ; _mm256_storeu_si256((__m256i *)(d+40), _mm256_loadu_si256((__m256i *)(s+40))) ; _mm256_storeu_si256((__m256i *)(d+48), _mm256_loadu_si256((__m256i *)(s+48))) ; _mm256_storeu_si256((__m256i *)(d+56), _mm256_loadu_si256((__m256i *)(s+56))) ; #else for(i=0 ; i<32 ; i++) d[i] = s[i] ; for(i=32 ; i<64 ; i++) d[i] = s[i] ; #endif s += 64 ; d += lni ; } return 0 ; } // special case for row length 64 // extract a contiguous block (ni x nj) of 32 bit words from f into blk // ni : row size (row storage size in blk) // lni : row storage size in f // nj : number of rows int get_word_block_64(void *restrict f, void *restrict blk, int ni, int lni, int nj){ uint32_t *restrict s = (uint32_t *) f ; uint32_t *restrict d = (uint32_t *) blk ; int i0, i, ni7 ; if(ni != 64) return 1 ; while(nj--){ #if defined(__x86_64__) && defined(__AVX2__) && defined(WITH_SIMD) _mm256_storeu_si256((__m256i *)(d+ 0), _mm256_loadu_si256((__m256i *)(s+ 0))) ; _mm256_storeu_si256((__m256i *)(d+ 8), _mm256_loadu_si256((__m256i *)(s+ 8))) ; _mm256_storeu_si256((__m256i *)(d+16), _mm256_loadu_si256((__m256i *)(s+16))) ; _mm256_storeu_si256((__m256i *)(d+24), _mm256_loadu_si256((__m256i *)(s+24))) ; _mm256_storeu_si256((__m256i *)(d+32), _mm256_loadu_si256((__m256i *)(s+32))) ; _mm256_storeu_si256((__m256i *)(d+40), _mm256_loadu_si256((__m256i *)(s+40))) ; _mm256_storeu_si256((__m256i *)(d+48), _mm256_loadu_si256((__m256i *)(s+48))) ; _mm256_storeu_si256((__m256i *)(d+56), _mm256_loadu_si256((__m256i *)(s+56))) ; #else for(i=0 ; i<32 ; i++) d[i] = s[i] ; for(i=32 ; i<64 ; i++) d[i] = s[i] ; #endif s += lni ; d += 64 ; } return 0 ; } #endif // insert a contiguous block (ni x nj) of 32 bit words into f from blk // ni : row size (row storage size in blk) // lni : row storage size in f // nj : number of rows int put_word_block(void *restrict f, void *restrict blk, int ni, int lni, int nj){ uint32_t *restrict d = (uint32_t *) f ; uint32_t *restrict s = (uint32_t *) blk ; int i0, i, ni7 ; if(ni < 8) return put_word_block_07(f, blk, ni, lni, nj) ; // if(ni == 8) return put_word_block_08(f, blk, ni, lni, nj) ; // if(ni == 32) return put_word_block_32(f, blk, ni, lni, nj) ; // if(ni == 64) return put_word_block_64(f, blk, ni, lni, nj) ; ni7 = (ni & 7) ; ni7 = ni7 ? ni7 : 8 ; while(nj--){ #if defined(__x86_64__) && defined(__AVX2__) && defined(WITH_SIMD) _mm256_storeu_si256((__m256i *)(d), _mm256_loadu_si256((__m256i *)(s))) ; for(i0 = ni7 ; i0 < ni-7 ; i0 += 8 ){ _mm256_storeu_si256((__m256i *)(d+i0), _mm256_loadu_si256((__m256i *)(s+i0))) ; } #else for(i=0 ; i<8 ; i++) d[i] = s[i] ; // first and second chunk may overlap if ni not a multiple of 8 for(i0 = ni7 ; i0 < ni-7 ; i0 += 8 ){ for(i=0 ; i<8 ; i++) d[i0+i] = s[i0+i] ; } #endif s += ni ; d += lni ; } return 0 ; } // extract a contiguous block (ni x nj) of 32 bit words from f into blk // ni : row size (row storage size in blk) // lni : row storage size in f // nj : number of rows int get_word_block(void *restrict f, void *restrict blk, int ni, int lni, int nj){ uint32_t *restrict s = (uint32_t *) f ; uint32_t *restrict d = (uint32_t *) blk ; int i0, i, ni7 ; if(ni < 8) return get_word_block_07(f, blk, ni, lni, nj) ; // if(ni == 8) return get_word_block_08(f, blk, ni, lni, nj) ; // if(ni == 32) return get_word_block_32(f, blk, ni, lni, nj) ; // if(ni == 64) return get_word_block_64(f, blk, ni, lni, nj) ; ni7 = (ni & 7) ; ni7 = ni7 ? ni7 : 8 ; while(nj--){ #if defined(__x86_64__) && defined(__AVX2__) && defined(WITH_SIMD) _mm256_storeu_si256((__m256i *)(d), _mm256_loadu_si256((__m256i *)(s))) ; for(i0 = ni7 ; i0 < ni-7 ; i0 += 8 ){ _mm256_storeu_si256((__m256i *)(d+i0), _mm256_loadu_si256((__m256i *)(s+i0))) ; } #else for(i=0 ; i<8 ; i++) d[i] = s[i] ; // first and second chunk may overlap if ni not a multiple of 8 for(i0 = ni7 ; i0 < ni-7 ; i0 += 8 ){ for(i=0 ; i<8 ; i++) d[i0+i] = s[i0+i] ; } #endif s += lni ; d += ni ; } return 0 ; }
C
/* * Lift.c * * Created on: Mar 12, 2015 * Author: Erik */ #include "main.h" Pickup initPickup(PantherMotor motor) { Pickup newPickup = {motor}; return newPickup; } void clawAtSpeed(Pickup pickup, int speed) { setPantherMotor(pickup.motor, limit(speed, 127, -127)); } void openPickup(Pickup pickup) { clawAtSpeed(pickup, 127); } void closePickup(Pickup pickup) { clawAtSpeed(pickup, -100); } void stopPickup(Pickup pickup) { clawAtSpeed(pickup, 0); }
C
#include "genotype.h" #include <math.h> #include <assert.h> #include <stdlib.h> static const double MUTATION_PROBABLITY = 0.1; static const double MUTATION_DEVIATION = 0.2; struct _Genotype_ { double *genes; // genome double fitness; // fitness }; static int genotype_size = -1; int genotype_get_size() { return genotype_size; } void genotype_set_size(int size) { genotype_size = size; } Genotype genotype_create() { //assert(genotype_size > 0); Genotype gen = malloc(sizeof(struct _Genotype_)); gen->fitness = 0.0; gen->genes = malloc(genotype_size * sizeof(double)); // initialize with random uniform numbers in the range [0,1] int i; for (i = 0; i < genotype_size; i++) gen->genes[i] = 0.0; return gen; } Genotype create_genotype_from_file(FILE *fd) { int i; int ret; int numberArray[1]; for (i = 0; i < 1; i++){ fscanf(fd, "%d", &numberArray[i] ); } //printf("number is: %d\n", numberArray[0]); //assert(genotype_size > 0); Genotype gen = malloc(sizeof(struct _Genotype_)); gen->fitness = 0.0; gen->genes = malloc(numberArray[0] * sizeof(double)); for (i = 0; i < numberArray[0]-1; i++) { ret = fscanf(fd, "%lf", &gen->genes[i]); if (ret == EOF) fprintf(stderr, "Cannot decode the genotype file\n"); } genotype_set_size(numberArray[0]-1); return gen; } void genotype_destroy(Genotype g) { free(g->genes); free(g); } Genotype genotype_clone(Genotype g) { Genotype clone = genotype_create(); int i; for (i = 0; i < genotype_size; i++) clone->genes[i] = g->genes[i]; clone->fitness = g->fitness; return clone; } double drand(){ double dr; int r; r = rand(); dr = (double)(r)/(double)(RAND_MAX); return(dr); } void genotype_set_fitness(Genotype g, double fitness) { g->fitness = fitness; } double genotype_get_fitness(Genotype g) { return g->fitness; } const double *genotype_get_genes(Genotype g) { return g->genes; } void genotype_fread(Genotype g, FILE *fd) { int i; for (i = 0; i < genotype_size; i++) { int ret = fscanf(fd, "%lf", &g->genes[i]); if (ret == EOF) fprintf(stderr, "Cannot decode the genotype file\n"); } } void genotype_fwrite(Genotype g, FILE *fd) { int i; for (i = 0; i < genotype_size; i++) fprintf(fd, " %lf", g->genes[i]); fprintf(fd, "\n"); } void print_genotype(Genotype g) { int i; printf("size is: %d\n", genotype_size); for (i = 0; i < genotype_size; i++) printf(" %lf", g->genes[i]); printf("\n"); }
C
//////////////////////////////////////////////////////// /// (c) 2014. My-Classes.com /// Basic version of fusing the ZMQ raw ROUTER (frontend) socket and NanoMsg REQ-REP (backend) sockets. /// /// Read More at: /// http://my-classes.com/2014/04/26/combining-zeromq-and-nanomsg-for-serving-web-requests/ /// /////////////////////////////////////////////////////// #include "czmq.h" #include "nn.h" #include "reqrep.h" #define WORKER_SOCKET_ADDRESS "inproc://test" void* nano_worker(void* args) { int rc; int workerSock; char request[4096]; char response[] = "HTTP / 1.0 200 OK\r\nContent - Type: text / plain\r\n\r\nHello World!!"; int nResponseLen = strlen(response); workerSock = nn_socket(AF_SP, NN_REP); assert(workerSock >= 0); nn_bind(workerSock, WORKER_SOCKET_ADDRESS); int i = 0; while (1) { rc = nn_recv(workerSock, request, sizeof (request), 0); assert(rc >= 0); rc = nn_send(workerSock, response, nResponseLen+1, 0); assert(rc >= 0); } } int main(void) { zctx_t *ctx = zctx_new(); void *router = zsocket_new(ctx, ZMQ_ROUTER); zsocket_set_router_raw(router, 1); zsocket_set_sndhwm(router, 0); zsocket_set_rcvhwm(router, 0); int rc = zsocket_bind(router, "tcp://*:8080"); assert(rc != -1); zthread_new(nano_worker, NULL); int sock = nn_socket(AF_SP, NN_REQ); assert(sock >= 0); assert(nn_connect(sock, WORKER_SOCKET_ADDRESS) >= 0); while (true) { // Get HTTP request zframe_t *identity = zframe_recv(router); if (!identity) break; // Ctrl-C interrupt char *request = zstr_recv(router); { // forward the http-request to NanoMsg int bytes = nn_send(sock, request, strlen(request), 0); assert(bytes >= 0); } free(request); // free the memory // read the response from NanoMsg worker char* response = NULL; int bytes = nn_recv(sock, &response, NN_MSG, 0); assert(bytes >= 0); { // Send response to client/browser zframe_send(&identity, router, ZFRAME_MORE + ZFRAME_REUSE); zstr_send(router, response); // Close connection to browser zframe_send(&identity, router, ZFRAME_MORE); zmq_send(router, NULL, 0, 0); } nn_freemsg(response); // free the memory } zctx_destroy(&ctx); return 0; }
C
/* ============================================================================ Name : libreriaKeAprobo.c Author : Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include "funesMemory.h" int main(void) { puts("Iniciando Funes Memory..."); iniciarVariables(); socketEscucha = socketServidor(PUERTO_ESCUCHA, IP, 50); socketDam = servidorConectarComponente(socketEscucha, "FUNES_MEMORY", "DAM"); socketCpu = servidorConectarComponente(socketEscucha, "FUNES_MEMORY", "CPU"); finalizarVariables(); puts("Finalizo Funes Memory..."); return EXIT_SUCCESS; } void iniciarVariables(){ config = config_create("./config/config.txt"); if(config == NULL){ puts("Error al leer configuraciones..."); finalizarVariables(); exit(1); } ipEscucha = config_get_string_value(config, "IP_ESCUCHA"); puertoEscucha = config_get_int_value(config, "PUERTO_ESCUCHA"); } void finalizarVariables(){ shutdown(socketEscucha,2); shutdown(socketDam,2); shutdown(socketCpu,2); }
C
#include<stdio.h> int main() { int liter,km; float Avg; printf("Enter total distance: "); scanf("%d",&km); printf("Enter liter: "); scanf("%d",&liter); Avg=km/liter; printf("Average consumption: %.3f",Avg); }
C
// Dem so ky tu #include <stdio.h> #include <string.h> //check a char 'ch' in string s int check(char ch, char s[]) { for (int i = 0; i < strlen(s); i++) if (ch == s[i]) return 1; return 0; } int countWords(char st[],char s[]) { int i = 0, n = strlen(st), d = 0; while (i < n) { while ((check(st[i], s) == 1) && (i<n)) i++; while ((check(st[i], s) == 0) && (i < n)) i++; d = d + 1; } return d; } int main() { char s[] = { '.',',','!',' ','-','+','*'}; char st[255]; printf("Enter a string:"); gets(st); printf("The number of words are %d", countWords(st, s)); }
C
#ifndef FILAS_H_INCLUDED #define FILAS_H_INCLUDED #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct _Nodo { char dato[20]; int edicion; struct _Nodo *siguiente; } Nodo; Nodo* crearNodo(char d[20],int e) { Nodo *nuevo; nuevo=(Nodo*)malloc(sizeof(Nodo)); strcpy(nuevo->dato,d); nuevo->edicion=e; nuevo->siguiente=NULL; return nuevo; } Nodo* Push(Nodo *top, char d[20],int e) { Nodo *nuevo,*aux; nuevo=crearNodo(d,e); if(top==NULL) { return nuevo; } else { aux=top; while(aux->siguiente!=NULL) { aux=aux->siguiente; } } aux->siguiente=nuevo; return top; } Nodo* Pop(Nodo *top) { Nodo *aux; aux=top; if(aux!=NULL) { top=top->siguiente; free(aux); } return top; } void verCola(Nodo *top) { Nodo *aux; aux=top; if(aux==NULL) { printf("\n\tNINGUNA\n"); } else { // printf("\n\tCARACTERES EN LA COLA"); while(aux!=NULL) { printf("%s%d ", aux->dato,aux->edicion); aux=aux->siguiente; } printf("\n"); } } void tamano(Nodo *top) { int contadorTop=0; Nodo *aux; aux=top; if(aux==NULL) { printf("Cola vacia\n"); } else { while(aux!=NULL) { contadorTop++; aux=aux->siguiente; } } printf("\nNumero De Caracteres En La Cola: %d \n", contadorTop); } #endif // FILAS_H_INCLUDED
C
#include "PCA9655.h" const unsigned char ADDR_ARRAY [9] = { 0x40, 0x42, 0x44, 0x46, 0x4C, 0x48, 0x4E, 0x4A, 0x50 }; const unsigned char PCA_REG_READ [2] = { 0,1 }; const unsigned char PCA_REG_WRITE [2] = { 2,3 }; const unsigned char PCA_REG_POLARITY [2] = { 4,5 }; const unsigned char PCA_REG_CONFIG [2] = { 6,7 }; void PCA9655_INIT (void) { PCA_SELECT_DDR |= ((1<<PCA_SELECT_WRITE)|(1<<PCA_SELECT_READ)); PCA_SELECT_PORT &= ~((1<<PCA_SELECT_WRITE)|(1<<PCA_SELECT_READ)); PCA_SELECT_PORT |= (1<<PCA_SELECT_WRITE); for (uint8_t ADDR = 0; ADDR < 9; ADDR++) { i2c_start(ADDR_ARRAY[ADDR]); i2c_write(PCA_REG_CONFIG[0]); i2c_write(0xFF); i2c_write(0xFF); i2c_stop(); i2c_start(ADDR_ARRAY[ADDR]); i2c_write(PCA_REG_WRITE[0]); i2c_write(0xFF); i2c_write(0xFF); i2c_stop(); _delay_us(1); } PCA_SELECT_PORT &= ~(1<<PCA_SELECT_WRITE); PCA_SELECT_PORT |= (1<<PCA_SELECT_READ); for (uint8_t ADDR = 0; ADDR < 9; ADDR++) { i2c_start(ADDR_ARRAY[ADDR]); i2c_write(PCA_REG_CONFIG[0]); i2c_write(0xFF); i2c_write(0xFF); i2c_stop(); _delay_us(1); } PCA_SELECT_PORT &= ~(1<<PCA_SELECT_READ); } void PCA9655_SET_PIN (unsigned char PIN) { PCA_SELECT_PORT |= (1<<PCA_SELECT_WRITE); int DATA = (~(1<<(PIN%16))) & 0xFFFF; i2c_start(ADDR_ARRAY[PIN/16]); i2c_write(PCA_REG_CONFIG[0]); i2c_write(DATA & 0xFF); i2c_write((DATA>>8) & 0xFF); i2c_stop(); PCA_SELECT_PORT &= ~(1<<PCA_SELECT_WRITE); } void PCA9655_CLEAR_PIN (unsigned char PIN) { PCA_SELECT_PORT |= (1<<PCA_SELECT_WRITE); i2c_start(ADDR_ARRAY[PIN/16]); i2c_write(PCA_REG_WRITE[0]); i2c_write(0x0); i2c_write(0x0); i2c_stop(); i2c_start(ADDR_ARRAY[PIN/16]); i2c_write(PCA_REG_CONFIG[0]); i2c_write(0xFF); i2c_write(0xFF); i2c_stop(); i2c_start(ADDR_ARRAY[PIN/16]); i2c_write(PCA_REG_WRITE[0]); i2c_write(0xFF); i2c_write(0xFF); i2c_stop(); PCA_SELECT_PORT &= ~(1<<PCA_SELECT_WRITE); } uint8_t PCA9655_GET_PIN (unsigned char PIN) { unsigned int DATA = 0; PCA_SELECT_PORT |= (1<<PCA_SELECT_READ); i2c_start(ADDR_ARRAY[PIN/16]); i2c_write(PCA_REG_READ[0]); i2c_start((ADDR_ARRAY[PIN/16]) | 0x1); DATA = i2c_read_ack(); DATA = (i2c_read_nack() << 8)| DATA; i2c_stop(); PCA_SELECT_PORT &= ~(1<<PCA_SELECT_READ); return ((DATA >> (PIN%16)) & 0x1); }
C
#include "exterior.h" int IsBackground(char command[1024]) { int i = 0; while(command[i] != '\0') i++; if(command[i-2] == '&') return 1; return 0; } char* MakeString(char command[1024], int startidx, int endidx) { char* ret = (char*)malloc(sizeof(char) * (endidx - startidx)); int retcnt = 0; for(int i = startidx; i < endidx; i++) { ret[retcnt++] = command[i]; } return ret; } void ExecuteCommand(char command[1024]) { int j = 0; int cnt = 1; while(command[j] != '\n') { j++; if(command[j] == ' ') cnt++; } j++; int i = 0; char** commandptr = (char**)malloc(sizeof(char*) * (cnt + 1)); commandptr[cnt] = NULL; cnt = 0; int start = 0; int end = 0; while(command[i] != '\n') { start = i; while(i < j-2 && command[i] != ' ') { i++; } if(i == j-2 && command[i] != ' ' && command[i] != '&') i++; end = i; commandptr[cnt++] = MakeString(command, start, end); if(command[i] == '\n'|| command[i] == '&') break; while(command[i] == ' ') i++; } execvp(commandptr[0], commandptr); } void ChangeDir(char command[1024]) { int j = 3; while(command[j] != '\n') j++; char* changepath = (char*)malloc(sizeof(char*) * (j - 3)); for(int i = 0;i < j - 3;i++) { changepath[i] = command[i+3]; } if(chdir(changepath) != 0) printf("%s failed!!\n", changepath); }
C
#include<stdio.h> int main(void){ static int a[] = {0,1,2,3,4}; static int *p[] = {a, a+1, a+2, a+3, a+4}; int **ptr; ptr = p; **ptr++ ; // * has more precedence than ++ operator printf("%d\t%d\t%d\n", ptr - p, *ptr - a, **ptr); *++*ptr; printf("%d\t%d\t%d\n", ptr - p, *ptr - a, **ptr); ++**ptr; printf("%d\t%d\t%d\n", ptr - p, *ptr - a, **ptr); return 0; } /* output 1 1 1 1 2 2 1 2 3 */
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/types.h> #include <signal.h> #include <string.h> #include <pthread.h> struct Shm { pthread_mutex_t mutex; pthread_cond_t cond; char buff[1024]; }; struct Shm *share_memory = NULL; void print() { printf("<Recv> : %s\n", share_memory->buff); memset(share_memory->buff, 0, sizeof(share_memory->buff)); } int main() { int shmid; key_t key = ftok(".", 199); if ((shmid = shmget(key, sizeof(struct Shm), IPC_CREAT | 0666)) < 0) { perror("shmget"); return 1; } //printf("After shmget!\n"); if ((share_memory = (struct Shm *)shmat(shmid, NULL, 0)) == NULL) { perror("shmat"); return 1; } //printf("After shmat!\n"); memset(share_memory, 0, sizeof(struct Shm)); pthread_mutexattr_t m_attr; pthread_condattr_t c_attr; pthread_mutexattr_init(&m_attr); pthread_condattr_init(&c_attr); pthread_mutexattr_setpshared(&m_attr, PTHREAD_PROCESS_SHARED); pthread_condattr_setpshared(&c_attr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&share_memory->mutex, &m_attr); pthread_cond_init(&share_memory->cond, &c_attr); while (1) { pthread_mutex_lock(&share_memory->mutex); //printf("After mutex lock\n"); pthread_cond_wait(&share_memory->cond, &share_memory->mutex); //printf("After cond wait\n"); //sleep(2); print(); pthread_mutex_unlock(&share_memory->mutex); } return 0; }
C
#pragma config(Sensor, dgtl1, backLeft, sensorQuadEncoder) #pragma config(Sensor, dgtl3, backRight, sensorQuadEncoder) #pragma config(Motor, port2, frontRightMotor, tmotorServoContinuousRotation, openLoop) #pragma config(Motor, port3, backRightMotor, tmotorServoContinuousRotation, openLoop) #pragma config(Motor, port4, frontLeftMotor, tmotorServoContinuousRotation, openLoop, reversed) #pragma config(Motor, port5, backLeftMotor, tmotorServoContinuousRotation, openLoop, reversed) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// const float WHEELDIAM = 4; // DEGRAT NEEDS TO BE TESTED AND CHANGED FOR EACH INDIVIDUAL BOT!!! const float DEGRAT = 2.3; const int FAST = 127; const int SLOW = 110; // Sets Motors to 0 void ZeroMotors(){ motor[frontRightMotor] = 0; motor[backRightMotor] = 0; motor[frontLeftMotor] = 0; motor[backLeftMotor] = 0; } // Sets Encoders to 0 void ZeroEncoders(){ SensorValue[backLeft] = 0; SensorValue[backRight] = 0; } // Moves a specified number of inches void moveForward(int dist){ // tickgoal = (60 / ( pi * wheel diameter)) * dist float tickgoal = (360 / (3.1415926535 * WHEELDIAM)) * dist; // Zero out both encoders ZeroEncoders(); // Sets all motors to 127 motor[frontRightMotor] = FAST; motor[backRightMotor] = FAST; motor[frontLeftMotor] = FAST; motor[backLeftMotor] = FAST; // Checks to see whether the tick goal has been met on both encoders while(SensorValue[backRight] < tickgoal && SensorValue[backLeft] < tickgoal){ if(SensorValue[backRight] == SensorValue[backLeft]){ motor[frontRightMotor] = FAST; motor[backRightMotor] = FAST; motor[frontLeftMotor] = FAST; motor[backLeftMotor] = FAST; } if(SensorValue[backRight] < SensorValue[backLeft]){ motor[frontRightMotor] = FAST; motor[backRightMotor] = FAST; motor[frontLeftMotor] = SLOW; motor[backLeftMotor] = SLOW; } if(SensorValue[backRight] > SensorValue[backLeft]){ motor[frontRightMotor] = SLOW; motor[backRightMotor] = SLOW; motor[frontLeftMotor] = FAST; motor[backLeftMotor] = FAST; } } // Sets all motors to 0 ZeroMotors(); } // Turns right a given number of degrees void turnRightDeg(int degrees){ // tickgoal = num of degrees to move * tick to degree ratio float tickgoal = degrees * DEGRAT; // Zero out both encoders ZeroEncoders(); // Sets all motors to 127 motor[frontRightMotor] = FAST; motor[backRightMotor] = FAST; motor[frontLeftMotor] = -1 * FAST; motor[backLeftMotor] = -1 * FAST; // Checks to see whether the tick goal has been met on both encoders while(SensorValue[backRight] > -1 * tickgoal || SensorValue[backLeft] < tickgoal){ if(SensorValue[backLeft] > tickgoal){ motor[frontLeftMotor] = 0; motor[backLeftMotor] = 0; } if(SensorValue[backRight] < -1 * tickgoal){ motor[frontRightMotor] = 0; motor[backRightMotor] = 0; } } // Sets all motors to 0 ZeroMotors(); } // Turns left a given number of degrees void turnLeftDeg(int degrees){ // tickgoal = num of degrees to move * tick to degree ratio float tickgoal = degrees * DEGRAT; // Zero out both encoders ZeroEncoders(); // Sets all motors to 127 motor[frontRightMotor] = -1 * FAST; motor[backRightMotor] = -1 * FAST; motor[frontLeftMotor] = FAST; motor[backLeftMotor] = FAST; // Checks to see whether the tick goal has been met on both encoders while(SensorValue[backRight] < tickgoal || SensorValue[backLeft] > -1 * tickgoal){ if(SensorValue[backLeft] < -1 * tickgoal){ motor[frontLeftMotor] = 0; motor[backLeftMotor] = 0; } if(SensorValue[backRight] > tickgoal){ motor[frontRightMotor] = 0; motor[backRightMotor] = 0; } } // Sets all motors to 0 ZeroMotors(); } task main(){ }
C
/* * File: C_Lab_9.c * Author: Ugur Ozkan * * Created on 27 Agustos 2019 Persembe * * Konu : Pointer kullanimi ve pointer fonksiyonlri * */ /* * Pointer tanimlama * char *s; // Pointer tanimlandi * s= (char *) 0x4fc0; // S isimli gstericinin iine adres yerlestiriliyor * *s = 'a'; // S adresinin (0x4fc0) ierigin a karakteri yaziliyor * ++s; // S adresi 1 artiriliyor * *s = 'b' // Artirilina adrese b karakteri yaziliyor * * * */ #include <stdio.h> #include <stdlib.h> void __swap(int *x, int *y); // Pointer fonk prototipi int main(int argc, char *argv[]) { int a=10, b=20; __swap(&a,&b); // pointer oldugu icin adres verilmeli Swap fonk. calistrildi. printf("Swap A : %d\n\r",a); printf("Swap B : %d\n\r",b); return 0; } void __swap(int *x, int *y) // Pointer fonksiyon tanimlandi. { // Fonksiyon icerigi pointer oldugundan adres verilecek int Buff; Buff = *x ; *x = *y ; *y = Buff; }
C
/* From:ITC 3 Inappropriate code 3.1 Dead code 3.1.4 "if statement Function arguments" */ void dead_code_004_func_001 (int flag) { int a = 0; int ret; if (flag) { a ++; /*Tool should detect this line as error*/ /*ERROR:Dead Code*/ } ret = a; sink = ret; } void dead_code_004 () { dead_code_004_func_001(0); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <string.h> int main(int argc, char *argv[]) { int r_count = 0, w_count = 0, fd1 = 0, fd2 = 0; char buff[BUFSIZ]; if(argc != 3) { fprintf(stderr, "Err parameters. Usage %s <FILE1> <FILE2>.\n", argv[0]); return EXIT_FAILURE; } if(argv[1][0] == '-') { fd1 = 0; } else if((fd1 = open(argv[1], O_RDONLY)) == -1 ) { fprintf(stderr, "Cannot read file <%s>, err: %s.\n", argv[1], strerror(errno)); return EXIT_FAILURE; } if(argv[2][0] == '-') { fd2 = 1; } else if((fd2 = open(argv[2], O_WRONLY)) == -1 ) { fprintf(stderr, "Cannot read file <%s>, err: %s.\n", argv[2], strerror(errno)); return EXIT_FAILURE; } while((r_count = read(fd1, buff, sizeof(buff))) > 0) { w_count = write(fd2, buff, r_count); if(w_count != r_count) { fprintf(stderr, "Read error: %s.\n", strerror(errno)); break; } } close(fd1); close(fd2); return EXIT_SUCCESS; }
C
// // Static_Variable.c // C_Learning // // Created by shiji zhao on 12/19/19. // Copyright © 2019 shiji zhao. All rights reserved. // #include <stdio.h> void display(void); int main(){ display(); display(); } void display(){ static int c = 1; c += 5; printf("%d\n", c); }
C
#include <stdio.h> int main() { long long int n , i , j; scanf( "%lld", &n ); for( i = 1 ; i <= n ; ++i) //Printing first n rows { for( j = 1 ; j < i ; ++j ) printf(" "); for( j = 1 ; j <= i ; ++j ) printf("#"); j = ( 4 * ( n - i ) ); //Number of spaces to be left between Hashes for( ; j > 0 ; --j ) printf(" "); for( j = 1 ; j <= i ; ++j ) printf("#"); printf("\n"); } for( i = n ; i > 0 ; --i) //Printing next n rows { for( j = 1 ; j < i ; ++j ) printf(" "); for( j = 1 ; j <= i ; ++j ) printf("#"); j = ( 4 * ( n - i ) ); //Number of spaces to be left between Hashes for( ; j > 0 ; --j ) printf(" "); for( j = 1 ; j <= i ; ++j ) printf("#"); printf("\n"); } }
C
#include <stdio.h> #include <stdlib.h> #include <assert.h> /* each node contains a value and a next pointer */ typedef struct dll_node_t { int val; struct dll_node_t *next; struct dll_node_t *prev; } dll_node; /* to make tail and head insertion fast, keep head and tail pointers */ typedef struct dll_t { dll_node *head; dll_node *tail; } dll; /* to create an empty linked list, create a list with NULL head,tail */ dll *dll_create() { dll *list = malloc(sizeof(dll)); list->head = list->tail = NULL; return list; } /* delete the first match in doubly linked list */ void dll_delete(dll *list, int v) { dll_node *walk = list->head; while (walk && walk->val != v) walk = walk->next; if (!walk) return; if (walk->prev) { walk->prev->next = walk->next; /* (*(*walk.prev)).next */ } else { list->head = walk->next; } if (walk->next) { walk->next->prev = walk->prev; } else { list->tail = walk->prev; } free(walk); } /* compute the length of a list by traversing it */ unsigned int dll_length(const dll* list) { unsigned int count = 0; dll_node *elt; /* this for loop traverses the list */ for (elt = list->head; elt; elt = elt->next) { printf("%d\n", elt->val); /* added this for debugging */ if (elt->next) { assert(elt->next->prev == elt); } else { assert(list->tail == elt); } count++; /* increment the count for each node we see */ } return count; } void dll_insert_head(dll *list, int val) { dll_node *tmp = malloc(sizeof(dll_node)); /* alloc space */ /* when inserting into an empty list, set tail */ if (!list->head) list->tail = tmp; /* set our value, our next pointer to the current head, update current head */ tmp->val = val; tmp->next = list->head; tmp->prev = NULL; if (list->head) list->head->prev = tmp; list->head = tmp; } void dll_insert_tail(dll *list, int val) { dll_node *tmp = malloc(sizeof(dll_node)); /* when inserting into an empty list, set head */ if (!list->head) list->head = tmp; /* we're inserting a new last value so ->next is always NULL */ tmp->prev = list->tail; tmp->next = NULL; tmp->val = val; /* splice in tmp from the last element of the current list, * taking care to not crash if the list is empty */ if (list->tail) list->tail->next = tmp; /* update the tail pointer */ list->tail = tmp; } int main() { dll *list = dll_create(); dll_insert_tail(list, 5); printf("Len: %d\n", dll_length(list)); dll_delete(list, 5); printf("Len: %d\n", dll_length(list)); dll_insert_tail(list, 5); printf("Len: %d\n", dll_length(list)); dll_insert_tail(list, 7); printf("Len: %d\n", dll_length(list)); dll_insert_head(list, 3); printf("Len: %d\n", dll_length(list)); dll_insert_tail(list, 10); printf("Len: %d\n", dll_length(list)); dll_delete(list, 3); printf("Len: %d\n", dll_length(list)); dll_insert_head(list, 3); printf("Len: %d\n", dll_length(list)); dll_delete(list, 7); printf("Len: %d\n", dll_length(list)); dll_delete(list, 10); printf("Len: %d\n", dll_length(list)); dll_delete(list, 11); printf("Len: %d\n", dll_length(list)); }
C
#include <stdio.h> int main() { float celsius, fahrenheit; printf("Escreva qual temperatura eh ideal para voce em celsius: " ); scanf("%f", &celsius); getchar(); fahrenheit = (celsius * 9 / 5) +32; printf("%.1f graus Celsius equivalem a %.1f graus Fahrenheit", celsius, fahrenheit); return 0; }
C
#include "main.h" #include "htable.h" static void dump_buckets(htable *t){ for(size_t i = 0; i < t->m_max_size; i++){ if(t->m_array[i]){ printf("%3zu: %zu\n", i, t->m_array[i]->size); } } } static void test_insert_many(){ htable *t = htable_new(128, &aLong_type.compare); const size_t NUMS = 40000; const size_t GAP = 307; size_t i; for(i = GAP % NUMS; i != 0; i = (i + GAP) % NUMS) htable_insert(t, (Object*)aLong_new(i), FALSE);//typically it is more appropriate to access via &Object->method->interface. It is OK here, because there is no polymorphism printf("Insert (many): %s\n", (NUMS-1 == t->size)?"PASS":"FAIL"); //printf("%lu Nodes, %lu leaves\n", nodes, leaves); //printf("Tree Statistics: min: %lu, max: %lu, avg: %lu, optimal: %lu\n", min, max, avg, (size_t)(log(nodes+1)/log(2)+.5)); htable_clear(t, TRUE); htable_destroy(t); } static void test_find(){ htable *t = htable_new(0, &aLong_type.compare); long x[] = { 8, 3, 1, 6, 4, 7, 10, 14, 13 }; for(size_t i = 0; i < ARRLENGTH(x); i++) htable_insert(t, (Object*)aLong_new(x[i]), FALSE); BOOLEAN failure = FALSE; //dump_buckets(t); size_t i = 0; for(i = 0; i < ARRLENGTH(x); i++){ aLong *obj = (aLong*)htable_find(t, (Object*)&(aLong){.method = &aLong_type, .data = x[i]}, t->data_method); if(!obj){ //printf("%ld ", x[i]); failure = TRUE; break; } } printf("Find: "); if(failure) printf("FAIL"); else printf("PASS"); printf("\n"); htable_clear(t, TRUE); htable_destroy(t); } static void test_remove(){ htable *t = htable_new(0, &aLong_type.compare); long x[] = { 8, 3, 1, 6, 4, 7, 10, 14, 13 }; for(size_t i = 0; i < ARRLENGTH(x); i++) htable_insert(t, (Object*)aLong_new(x[i]), FALSE); BOOLEAN failure = FALSE; //void dump_htable(htable*); dump_htable(t); size_t i = 0; for(i = 0; i < ARRLENGTH(x); i+=2){ htable_remove(t, (Object*)&(aLong){.method = &aLong_type, .data = x[i]}, t->data_method, TRUE); //printf("%zu (%ld), %d, %d\n", i, x[i], !obj && (i&1) == 1, obj && (i&1)==0); } //dump_htable(t); if(!failure){ for(i = 0; i < ARRLENGTH(x); i++){ aLong *obj = (aLong*)htable_find(t, (Object*)&(aLong){.method = &aLong_type, .data = x[i]}, t->data_method); //printf("%zu (%ld), %p, %d, %d\n", i, x[i], obj, !obj && (i&1) == 1, obj && (i&1)==0); if((!obj && (i&1) == 1) || (obj && (i&1)==0)){//did we find something we should have, or not find something we should have? failure = TRUE; break; } } } printf("Remove: "); if(failure) printf("FAIL"); else printf("PASS"); printf("\n"); htable_clear(t, TRUE); htable_destroy(t); } void test_htable(){ #if 0 { struct rusage start, end; getrusage(RUSAGE_SELF, &start); test_performance(); getrusage(RUSAGE_SELF, &end); struct timeval diff; timersub(&end.ru_utime, &start.ru_utime, &diff); printf("Insert time: %lf\n", diff.tv_sec+diff.tv_usec/1e9); } #endif test_insert_many(); test_find(); test_remove(); }
C
#include <stdio.h> int main(int argc, char *argv[]) { long input; long result; scanf("%ld", &input); result = input * input * input; printf("%ld\n", result); return 0; } /* #include <stdio.h> */ /* #include <stdlib.h> */ /* #include <limits.h> */ /* #include <errno.h> */ /* #include <math.h> */ /* long validate_input(char *input); */ /* int main(int argc, char *argv[]) */ /* { */ /* long input; */ /* long result; */ /* /\* /\\* Check argument num *\\/ *\/ */ /* /\* if (argc != 2) { *\/ */ /* /\* exit(EXIT_FAILURE); *\/ */ /* /\* } *\/ */ /* scanf("%ld", &input); */ /* /\* input = validate_input(argv[1]); *\/ */ /* /\* if (input == LONG_MAX) { *\/ */ /* /\* printf("Invalid argument.\n"); *\/ */ /* /\* exit(EXIT_FAILURE); *\/ */ /* /\* } *\/ */ /* result = input * input * input; */ /* printf("%ld\n", result); */ /* return 0; */ /* } */ /* /\* */ /* * 入力値をチェック */ /* *\/ */ /* long validate_input(char *input) */ /* { */ /* long val; */ /* char *error; */ /* if (input == NULL) { */ /* return LONG_MAX; */ /* } */ /* errno = 0; */ /* val = strtol(input, &error, 10); */ /* if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) */ /* || (errno != 0 && val == 0)) { */ /* perror("strtol"); */ /* return LONG_MAX; */ /* } */ /* if (*error != '\0') { */ /* /\* Invalid value *\/ */ /* return LONG_MAX; */ /* } */ /* return val; */ /* } */
C
// auxiliary serial functions for supporting tiled Cholesky factorization. // written by Peter Strazdins, May 20 for COMP4300/8300 Assignment 2 // v1.0 08/05/20 /**** square tiled algorithm support functions ****/ // returns a, where void a[nT][nT] is an array with element size eltSize, // and a[i][j] = 0 void **allocTileArray(size_t eltSize, int nT); // frees a, allocated by allocTileArray() void freeTileArray(void **a); // pre: a is an wT x wT array // for clean output format, entries are assumed to be in range 0..99 // post: prints out a; void printIntTile(int wT, int **a); // sets the number of decimal places to be printed by printDoubleTile() etc void setPrintDoublePrecision(int decimalPlaces); // pre: a stores an wT x wT array in row-major order; // for clean output format, entries are assumed to be in range (-10,+10) // post: prints out a as an wT x wT array; void printDoubleTile(int wT, double *a); /**** tiled lower triangular matrix support functions ****/ // pre: A has storage for a nT x nT array of (double*), nT=(N+wT-1)/wT // post: A[][] holds an nT x nT tiled +ve definite lower tri. matrix, t // tile size of wT void initLowerPosDefTileArray(int seed, int N, int nT, int wT, double ***A); // pre: a has storage for an wT x wT array in row-major order; 0 <= i, j <= wT // post: a[ii*wT+jj] is set to an appropriate value for the global element // (i*wT+ii, j*wT+jj) for an N x N positive definite symmetric matrix // (stored in the lower triangular portion). // Elements are random in the range [-1.0,1.0] with a seed // s = s(i*wT+ii,j*wT+jj,seed); // note: a suitable bias added to diagonal elements to make +ve definite void initLowerPosDefTile(int i, int j, int seed, int N, int wT, double *a); // post: return the approximate row norm of NxN matrices generated by // initLowerPosDefTile() double getNrmA(int N); // prints a global nT*wT x nT*wT tiled array with tile pointers stored in A. // Whitespace is printed for where tile pointers are null; // only lower tri. tiles printed. // For clean output format, entries are assumed to be in range (-10,+10) void printLowerTileArray(int nT, int wT, double ***A); /**** miscellaneous generic functions ****/ // x[0..N-1] is set to random values in [-1,1], seeded by seed void initVec(int seed, double *x, int N); // print x[0..N-1] across a line with the label name void printVec(char *name, double *x, int N); /**** result checking functions ****/ //pre: A stores the local tiles of a global symmetric matrix stored in the // lower triangular array of nT x nT tiles of size wT; // x and y are replicated vectors of size nT*wT //post: y = A*x void triMatVecMult(int nT, int wT, double ***A, double *x, double *y); //pre: L stores the local tiles of a global lower triangular array of // nT x nT tiles of size wT; // y is a replicated vector of size nT*wT //post: y = (L^-1)^T * (L^-1) * y; void triMatVecSolve(int nT, int wT, double ***L, double *y);
C
/* ** EPITECH PROJECT, 2017 ** PSU_my_sokoban_2017 ** File description: ** PSU_my_sokoban_2017 made by Sanchez Lucas */ #include "my.h" char *load_file_in_mem(char const *filepath) { int fd = open(filepath, O_RDONLY); char *buf = malloc(sizeof(char) * 100010006); int size = read(fd, buf, 100010006); buf[size] = 0; close(fd); return (buf); } char **mem_alloc_2d_array(int nb_rows, int nb_cols) { char **array = malloc(sizeof(char *) * nb_rows); for (int i = 0 ; i < nb_rows ; i++) array[i] = malloc(sizeof(char) * nb_cols); return (array); } coord_t find_size_of_map(char *str) { coord_t size = {0, 0}; char *map = load_file_in_mem(str); int j = 0; for (int i = 0 ; map[i] != 0 ; i++) { j += 1; if (j > size.width) size.width = j; if (map[i] == '\n' || map[i + 1] == '\0') { size.height += 1; j = 0; } } free (map); return (size); } char **mem_dup_2d_array(char **arr, int nb_rows, int nb_cols) { char **new_arr = malloc(sizeof(char *) * nb_rows); int i = 0; int j = 0; for (int i = 0 ; i < nb_rows ; i++) new_arr[i] = malloc(sizeof(char) * nb_cols); while (i < nb_rows) { while (j < nb_cols) { new_arr[i][j] = arr[i][j]; j += 1; } j = 0; i += 1; } return (new_arr); } char **load_2d_arr_from_file(char const *filepath) { char **str; char *buf = load_file_in_mem(filepath); int i = 0; int j = 0; int n = 0; coord_t size = find_size_of_map((char *)filepath); str = mem_alloc_2d_array(size.height, size.width); while (i < size.height) { while (buf[n] != '\n' && buf[n] != 0) { str[i][j] = buf[n]; j += 1; n += 1; } str[i][j] = '\n'; n += 1; j = 0; i += 1; } return (str); }
C
#ifndef TEST_H_ #define TEST_H_ #include "util.h" #include <stdio.h> #include <stdlib.h> #include <string.h> static inline void assert_die(const char *file, unsigned line, const char *func, const char *expr) { fflush(NULL); fprintf(stderr, "ASSERT FAILED %s:%u in %s(): %s\n", file, line, func, expr); fflush(stderr); abort(); } #define TEST_ASSERT(cond) \ do { \ if (cond) { \ } else { \ assert_die(__FILE__, __LINE__, __FUNCTION__, #cond); \ } \ } while (0) #endif
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* load_data.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: conoel <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/10 18:05:59 by conoel #+# #+# */ /* Updated: 2019/01/13 17:52:00 by conoel ### ########.fr */ /* */ /* ************************************************************************** */ #include "fillit.h" static char **load_tetris(char *buffer) { int data_len; char **data; t_index ind; data_len = (int)ft_strlen(buffer); if (!(data = malloc(sizeof(*data) * (unsigned long)((data_len + 1) / 21 ) + 1))) return (NULL); ind.i = 0; ind.j = 0; while (ind.i < data_len) { if (!(data[ind.j] = ft_memdup(&buffer[ind.i], 20))) return (NULL); ind.j++; ind.i += 21; } data[ind.j] = NULL; return (data); } static void decal_horizontal(char *tetri) { int i; i = 0; while (i < 4) { if (tetri[i] != '.') break ; i++; } if (i == 4) { i = 0; while (i < 5) { tetri[i] = tetri[i + 5]; tetri[i + 5] = tetri[i + 10]; tetri[i + 10] = tetri[i + 15]; tetri[i + 15] = '.'; i++; } decal_horizontal(tetri); } } static void decal_vertical(char *tetri) { int i; i = 0; while (i < 20) { if (tetri[i] != '.') break ; i += 5; } if (i == 20) { i = 0; while (i < 20) { tetri[i] = tetri[i + 1]; tetri[i + 1] = tetri[i + 2]; tetri[i + 2] = tetri[i + 3]; tetri[i + 3] = '.'; i += 5; } decal_vertical(tetri); } } static char **change_tetri(char **data) { int i; int j; i = 0; while (data[i]) { j = 0; while (data[i][j] != '\0') { if (data[i][j] == '#') data[i][j] = (char)i + 65; if (data[i][j] == '\n') data[i][j] = '.'; j++; } decal_horizontal(data[i]); decal_vertical(data[i]); i++; } return (data); } char **load_data(char *path) { char **data; char buffer[MAX_FILE + 2]; int fd; ssize_t ret; if ((fd = open(path, O_RDONLY)) < 0) return (NULL); ret = read(fd, buffer, MAX_FILE + 1); close(fd); buffer[ret] = '\0'; buffer[ret + 1] = '\0'; if (((ft_strlen(buffer) + 1) % 21) != 0) return (NULL); if (!is_valid(buffer)) return (NULL); if (!(data = load_tetris(buffer))) return (NULL); data = change_tetri(data); return (data); }
C
inherit "/bldg/wall/wall"; #include <shape.h> NAME( "pad" ) DISTANT( 0 ) SPECIFIC( "the pad" ) PLURAL( "pads" ) LOOK( "It's a pad on the ground. It has seams around the edge, suggesting it might depress if stepped upon." ) PHRASE( 0 ) int color; symbol trigger_object; // Note: The reason I am not using a closure for this is that I // want the trigger_function & trigger_value variables to survive // a mud reboot! Closures cannot do this. This is obviously less // flexible than a closure, but hopefully will do the job. It's // also a bit easier to understand than closures if you're a // beginner... string trigger_function; mixed trigger_value; void set_color( int x ){ color = x; } int query_color() { return color; } int query_tile_width() { return 1; } int query_tile_height() { return 1; } void set_trigger_object( object ob ) { trigger_object = to_objectref(ob); } object query_trigger_object() { return find_objectref( trigger_object ); } void set_trigger_function( mixed x ) { trigger_function = x; } string query_trigger_function() { return trigger_function; } void set_trigger_value( mixed x ) { trigger_value = x; } string query_trigger_value() { return trigger_value; } void on_map_paint( object painter ) { int point, ix, iy; mapping spots; spots = query_spots(); foreach( point : spots ) { if( CX(point) > environment()->query_map_xdim() || CY(point) > environment()->query_map_ydim() ) { remove_spot(point); continue; } painter->paint( CX(point), CY(point), '*', query_color(), LAYER_TERRAIN ); } } int on_walk( object actor, int start, int end ) { object ob; if( actor->query_is_living() && member(query_spots(), end) && !member(query_spots(), start) ) { actor->msg_local("~CACTAs ~name ~verbstep on the pad, it sinks slightly into the ground, and a faint clicking sound is heard.~CDEF"); if( ob = query_trigger_object() ) { call_other( ob, trigger_function, trigger_value ); return 1; } } return 0; }
C
/** @file sal_structure.h * @brief Function prototypes for sal_structure * * * This header file is used to define the * structure of salary * */ #ifndef sal_h #define sal_h struct sal { int id; /* employee id*/ char name[40]; /* name of employee*/ float hours; /* no of hours worked*/ int mon; /* month*/ float salary; /* salary for that month */ }; struct sal s; /* a variable of type sal */ #endif /* end of sal_structure.h */
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <mpi.h> // $mpiexec mergeMPI.c void merge(int vetor[], int comeco, int meio, int fim) { int com1 = comeco, com2 = meio+1, comAux = 0, tam = fim-comeco+1; int *vetAux; vetAux = (int*)malloc(tam * sizeof(int)); while(com1 <= meio && com2 <= fim){ if(vetor[com1] < vetor[com2]) { vetAux[comAux] = vetor[com1]; com1++; } else { vetAux[comAux] = vetor[com2]; com2++; } comAux++; } while(com1 <= meio){ //Caso ainda haja elementos na primeira metade vetAux[comAux] = vetor[com1]; comAux++; com1++; } while(com2 <= fim) { //Caso ainda haja elementos na segunda metade vetAux[comAux] = vetor[com2]; comAux++; com2++; } for(comAux = comeco; comAux <= fim; comAux++){ //Move os elementos de volta para o vetor original vetor[comAux] = vetAux[comAux-comeco]; } free(vetAux); } void mergeSort(int vetor[], int comeco, int fim){ if (comeco < fim) { int meio = (fim+comeco)/2; mergeSort(vetor, comeco, meio); mergeSort(vetor, meio+1, fim); merge(vetor, comeco, meio, fim); } } int main(int argc, char const *argv[]){ int *vet; int tam = 10; int i; vet = malloc(tam*(sizeof(int))); srandom(time(NULL)); for(i = 0; i < tam; i++){ vet[i] = (int) random() % tam; printf("%d\n", vet[i]); } printf("-----------\n"); mergeSort(vet, 0, tam); for(i = 0; i < tam; i++){ printf("%d\n", vet[i]); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_validation.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vaisha <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/12/23 17:49:53 by vaisha #+# #+# */ /* Updated: 2019/12/23 20:01:15 by vaisha ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" static char *read_big_file(char *file_str, char *filename) { int i; int fd; int size; char buf[5000]; i = -1; if (!filename) return (NULL); if ((fd = open(filename, O_RDONLY)) < 0) return (NULL); if ((read(fd, buf, 0)) < 0) return (NULL); if ((size = (read(fd, buf, 5000))) < 0) return (NULL); file_str = (char *)ft_safe_malloc(sizeof(char) * (size + 1)); while (++i < size) file_str[i] = buf[i]; file_str[i] = '\0'; close(fd); return (file_str); } static int ft_len_arr(char **arr) { int i; i = 0; while (arr[i]) ++i; return (i); } static void fill_line(int i, char **split_white_space, t_map *map) { int k; k = -1; map->arr[i] = (int *)ft_safe_malloc(sizeof(int) * map->width); while (split_white_space[++k]) map->arr[i][k] = ft_atoi(split_white_space[k]); } static void fill_matrix(char **file_split_n, t_map *map) { int i; int width; char **split_white_space; i = -1; while (++i < map->height) { if (!(split_white_space = ft_strsplit(file_split_n[i], ' '))) ft_exit(ERROR_MALLOC); if (i == 0) map->width = ft_len_arr(split_white_space); else width = ft_len_arr(split_white_space); if (i > 0) if (map->width != width) ft_exit(ERROR_INPUT); fill_line(i, split_white_space, map); ft_destroy_string_arr(split_white_space); } } void validation(char *file, t_map *map) { char **file_split_n; char *file_to_str; if (!(file_to_str = read_big_file(file_to_str, file))) ft_exit(ERROR_INPUT); if (!(file_split_n = ft_strsplit(file_to_str, '\n'))) ft_exit(ERROR_INPUT); map->height = ft_len_arr(file_split_n); map->arr = (int **)ft_safe_malloc(sizeof(int *) * (map->height + 1)); map->arr[map->height] = NULL; fill_matrix(file_split_n, map); ft_strdel(&file_to_str); ft_destroy_string_arr(file_split_n); for (size_t i = 0; i < map->height; i++) { for (size_t k = 0; k < map->width; k++) { ft_putnbr(map->arr[i][k]); ft_putchar(' '); } ft_putchar('\n'); } }