language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
//
// main.c
// merge_bmp_images
//
// Created by 김주형 on 2021/09/28.
//
#include <stdio.h>
#include <stdlib.h>
#include "windows.h"
#define WIDTHBYTES(bits) (((bits) + 31) / 32 * 4) // 각 행은 반드시 4bytes의 배수이다.
typedef unsigned char BYTE;
int main()
{
FILE *file, *file1, *file2, *file3, *file4; // 파일 포인터
BITMAPFILEHEADER hf; // 비트맵 파일 헤더
BITMAPINFOHEADER hInfo; // 비트맵 정보 헤더
int rwsize, out_rwsize; // 라인 당 바이트 수
BYTE *inPutImg1, *inPutImg2, *inPutImg3, *inPutImg4; // 입력 이미지 포인터
BYTE *outPutImg; // 출력 데이터 포인터
int x, y;
// 1.bmp 입력 영상 파일을 연다.
file1 = fopen("/Users/juhyung/Desktop/merge_bmp_images/images/1.bmp", "rb");
if(file1 == NULL){
printf("1.bmp 파일이 없습니다!\n");
return -1;
}
fread(&hf, sizeof(BITMAPFILEHEADER), 1, file1); // 파일 헤더 읽음
if(hf.bfType != 0x4D42) // BMP 포맷('BM') 인지를 확인
return -1;
fread(&hInfo, sizeof(BITMAPINFOHEADER), 1, file1); // 비트맵 정보 헤더 읽음
// 24bit 영상만 입력으로 받음
if(hInfo.biBitCount != 24){
printf("bit수가 다른 파일입니다!\n");
return -1;
}
// 2.bmp 입력 영상 파일을 연다.
file2 = fopen("/Users/juhyung/Desktop/merge_bmp_images/images/2.bmp", "rb");
if(file2 == NULL){
printf("2.bmp 파일이 없습니다!\n");
return -1;
}
fread(&hf, sizeof(BITMAPFILEHEADER), 1, file2); // 파일 헤더 읽음
if(hf.bfType != 0x4D42) // BMP 포맷('BM') 인지를 확인
return -1;
fread(&hInfo, sizeof(BITMAPINFOHEADER), 1, file2); // 비트맵 정보 헤더 읽음
// 24bit 영상만 입력으로 받음
if(hInfo.biBitCount != 24){
printf("bit수가 다른 파일입니다!\n");
return -1;
}
// 3.bmp 입력 영상 파일을 연다.
file3 = fopen("/Users/juhyung/Desktop/merge_bmp_images/images/3.bmp", "rb");
if(file3 == NULL){
printf("3.bmp 파일이 없습니다!\n");
return -1;
}
fread(&hf, sizeof(BITMAPFILEHEADER), 1, file3); // 파일 헤더 읽음
if(hf.bfType != 0x4D42) // BMP 포맷('BM') 인지를 확인
return -1;
fread(&hInfo, sizeof(BITMAPINFOHEADER), 1, file3); // 비트맵 정보 헤더 읽음
// 24bit 영상만 입력으로 받음
if(hInfo.biBitCount != 24){
printf("bit수가 다른 파일입니다!\n");
return -1;
}
// 3.bmp 입력 영상 파일을 연다.
file4 = fopen("/Users/juhyung/Desktop/merge_bmp_images/images/4.bmp", "rb");
if(file4 == NULL){
printf("4.bmp 파일이 없습니다!\n");
return -1;
}
fread(&hf, sizeof(BITMAPFILEHEADER), 1, file4); // 파일 헤더 읽음
if(hf.bfType != 0x4D42) // BMP 포맷('BM') 인지를 확인
return -1;
fread(&hInfo, sizeof(BITMAPINFOHEADER), 1, file4); // 비트맵 정보 헤더 읽음
// 24bit 영상만 입력으로 받음
if(hInfo.biBitCount != 24){
printf("bit수가 다른 파일입니다!\n");
return -1;
}
// 입출력 데이터를 위한 라인 당 바이트 수 계산
rwsize = WIDTHBYTES(24 * hInfo.biWidth); // 입력 영상
out_rwsize = WIDTHBYTES(24 * hInfo.biWidth * 2); // 출력 영상
// 1.bmp 비트맵 데이터가 시작되는 위치로 파일 포인터를 이동
fseek(file1, hf.bfOffBits, SEEK_SET);
// 입력 영상 데이터를 위한 메모리 할당
inPutImg1 = (BYTE*)malloc(rwsize * hInfo.biHeight);
// 영상 데이터를 입력 영상으로 부터 읽음
fread(inPutImg1, sizeof(char), rwsize * hInfo.biHeight, file1);
fclose(file1);
// 2.bmp 비트맵 데이터가 시작되는 위치로 파일 포인터를 이동
fseek(file2, hf.bfOffBits, SEEK_SET);
// 입력 영상 데이터를 위한 메모리 할당
inPutImg2 = (BYTE*)malloc(rwsize * hInfo.biHeight);
// 영상 데이터를 입력 영상으로 부터 읽음
fread(inPutImg2, sizeof(char), rwsize * hInfo.biHeight, file2);
fclose(file2);
// 3.bmp 비트맵 데이터가 시작되는 위치로 파일 포인터를 이동
fseek(file3, hf.bfOffBits, SEEK_SET);
// 입력 영상 데이터를 위한 메모리 할당
inPutImg3 = (BYTE*)malloc(rwsize * hInfo.biHeight);
// 영상 데이터를 입력 영상으로 부터 읽음
fread(inPutImg3, sizeof(char), rwsize * hInfo.biHeight, file3);
fclose(file3);
// 4.bmp 비트맵 데이터가 시작되는 위치로 파일 포인터를 이동
fseek(file4, hf.bfOffBits, SEEK_SET);
// 입력 영상 데이터를 위한 메모리 할당
inPutImg4 = (BYTE*)malloc(rwsize * hInfo.biHeight);
// 영상 데이터를 입력 영상으로 부터 읽음
fread(inPutImg4, sizeof(char), rwsize * hInfo.biHeight, file4);
fclose(file4);
// 출력 영상 데이터를 위한 메모리 할당
outPutImg = (BYTE*)malloc(out_rwsize * hInfo.biHeight * 2);
// 3분면 - 3.bmp
for(y = 0; y < 300; y++){
for(x = 0; x < 400 * 3; x++){
outPutImg[y * out_rwsize + x + 2] = inPutImg3[y * rwsize + x + 2]; // R
outPutImg[y * out_rwsize + x + 1] = inPutImg3[y * rwsize + x + 1]; // G
outPutImg[y * out_rwsize + x + 0] = inPutImg3[y * rwsize + x + 0]; // B
}
}
// 4분면 - 4.bmp
for(y = 0; y < 300; y++){
for(x = 0; x < 400 * 3; x++){
outPutImg[y * out_rwsize + x + 2 + 1200] = inPutImg4[y * rwsize + x + 2]; // R
outPutImg[y * out_rwsize + x + 1 + 1200] = inPutImg4[y * rwsize + x + 1]; // G
outPutImg[y * out_rwsize + x + 0 + 1200] = inPutImg4[y * rwsize + x + 0]; // B
}
}
// 2분면 - 1.bmp
for(y = 0; y < 300; y++){
for(x = 0; x < 400 * 3; x++){
outPutImg[(y + 300) * out_rwsize + x + 2] = inPutImg1[y * rwsize + x + 2]; // R
outPutImg[(y + 300) * out_rwsize + x + 1] = inPutImg1[y * rwsize + x + 1]; // G
outPutImg[(y + 300) * out_rwsize + x + 0] = inPutImg1[y * rwsize + x + 0]; // B
}
}
// 1분면 - 2.bmp
for(y = 0; y < 300; y++){
for(x = 0; x < 400 * 3; x++){
outPutImg[(y + 300) * out_rwsize + x + 2 + 1200] = inPutImg2[y * rwsize + x + 2]; // R
outPutImg[(y + 300) * out_rwsize + x + 1 + 1200] = inPutImg2[y * rwsize + x + 1]; // G
outPutImg[(y + 300) * out_rwsize + x + 0 + 1200] = inPutImg2[y * rwsize + x + 0]; // B
}
}
// 출력 영상의 정보
hInfo.biWidth = 800; // 영상의 가로 길이
hInfo.biHeight = 600; // 영상의 세로 길이
hInfo.biBitCount = 24;
hInfo.biSizeImage = out_rwsize * hInfo.biHeight * 2;
hInfo.biClrUsed = hInfo.biClrImportant = 0;
hf.bfOffBits = 54;
hf.bfSize = hf.bfOffBits + hInfo.biSizeImage;
file = fopen("/Users/juhyung/Desktop/merge_bmp_images/result.bmp", "wb");
fwrite(&hf, sizeof(char), sizeof(BITMAPFILEHEADER), file);
fwrite(&hInfo, sizeof(char), sizeof(BITMAPINFOHEADER), file);
fwrite(outPutImg, sizeof(char), out_rwsize * hInfo.biHeight, file);
fclose(file);
// 메모리 해제
free(outPutImg);
free(inPutImg1);
free(inPutImg2);
free(inPutImg3);
free(inPutImg4);
return 0;
}
|
C
|
#include <stdio.h>
#include "apto.h"
// (2.12.2)
float area_Apto(tApto *x) {
return x->AreaC;
}
// (2.12.1)
float price_Apto(tApto *x) {
if (x->Lazer == 'S')
return x->pM2AC * x->AreaC * (0.9 + (float) (x->Andar / x->nAndares))*1.15;
else
return x->pM2AC * x->AreaC * (0.9 + (x->Andar / (float) x->nAndares))*1;
}
// (2.12)
void read_Apto(tApto *x, FILE* file, float *area, float *preco) {
fscanf(file, "%d%d%d", &x->nQuarto, &x->nVagas, &x->Andar);
fscanf(file, "%f%d%*c%c%d%*c", &x->AreaC, &x->pM2AC, &x->Lazer, &x->nAndares);
*area = area_Apto(x);
*preco = price_Apto(x);
}
/*
tApto (1.4){
2.12) read_Apto:
-Lê os dados específicos do imóvel do tipo Apartamento, calcula seu preço e sua área;
2.12.1) price_Apto:
- Calcula o preço do apto;
2.12.2) area_Apto:
- Calcula a área do apto;
}
*/
|
C
|
/*
+----------------------------------------------------+
| |
| ####### |
| # # #### # # ###### ##### |
| # # # # # # # # |
| # # # #### ##### # |
| # # # # # # # |
| # # # # # # # # |
| # # #### # # ###### # |
| |
| ###### |
| ##### #### # # # ##### ###### |
| # # # # # # # # # |
| # # # ###### # # # ##### |
| # # # # # # # # # |
| # # # # # # # # # |
| # #### # # # ##### ###### |
| |
| |
+----------------------------------------------------+
File: jeu.h
*/
#ifndef __T2R_TEST_JEU_H__
#define __T2R_TEST_JEU_H__
#include "TicketToRideAPI.h"
typedef struct{
int nbCities; /* number of cities */
int nbTracks; /* number of tracks */
int* arrayTracks; /* tracks */
}t_board;
typedef struct{
int city1, city2; /* id of the cities */
int length; /* length of the track */
t_color color1, color2; /* colors */
int taken; /* tell if taken */
}t_track;
typedef struct{
char* name; /* name of the player */
int nbWagons; /* number of wagons */
int nbCards; /* number of cards */
t_color initialCards[4];
int cards[10]; /* number of cards of each color, ie cards[YELLOW] is the number of YELLOW cards */
int nbObjectives; /* number of objectives */
t_objective objectives[20]; /* objectives */
}t_player;
typedef struct{
char name[20]; /* name of the game */
t_color faceUp[5]; /* face up cards */
int player; /* player who plays: 0 -> I play, 1 -> the opponent plays */
t_player players[2];
t_board board; /* board of the game */
}t_game;
#endif
|
C
|
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <semaphore.h>
#include <pthread.h>
int* prepare_return_value_int(int value) {
int *result_value_ptr;
result_value_ptr = malloc(sizeof(int));
if (result_value_ptr == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
*result_value_ptr = value;
return result_value_ptr;
}
void* thread_nvocali(void *arg) {
char *str = (char*) arg;
int length = strlen(str);
int res = 0;
for (int i = 0; i <= length; i++) {
if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o'
|| str[i] == 'u' || str[i] == 'A' || str[i] == 'E'
|| str[i] == 'I' || str[i] == 'O' || str[i] == 'U') {
res++;
}
}
return (void*) prepare_return_value_int(res);
}
void* thread_nconsonanti(void *arg) {
char *str = (char*) arg;
int length = strlen(str);
int res = 0;
for (int i = 0; i <= length; i++) {
if (str[i] == 'b' || str[i] == 'c' || str[i] == 'd' || str[i] == 'f'
|| str[i] == 'g' || str[i] == 'h' || str[i] == 'j'
|| str[i] == 'k' || str[i] == 'l' || str[i] == 'm'
|| str[i] == 'n' || str[i] == 'p' || str[i] == 'q'
|| str[i] == 'r' || str[i] == 's' || str[i] == 't'
|| str[i] == 'v' || str[i] == 'w' || str[i] == 'x'
|| str[i] == 'y' || str[i] == 'z' || str[i] == 'A'
|| str[i] == 'B' || str[i] == 'C' || str[i] == 'D'
|| str[i] == 'F' || str[i] == 'G' || str[i] == 'H'
|| str[i] == 'J' || str[i] == 'K' || str[i] == 'L'
|| str[i] == 'M' || str[i] == 'N' || str[i] == 'P'
|| str[i] == 'Q' || str[i] == 'R' || str[i] == 'S'
|| str[i] == 'T' || str[i] == 'V' || str[i] == 'W'
|| str[i] == 'X' || str[i] == 'Y' || str[i] == 'Z') {
res++;
}
}
return (void*) prepare_return_value_int(res);
}
void* thread_nblank(void *arg) {
char *str = (char*) arg;
int length = strlen(str);
int res = 0;
for (int i = 0; i <= length; i++) {
if (str[i] == ' ' || str[i] == '\n') {
res++;
}
}
return (void*) prepare_return_value_int(res);
}
int main() {
char *content =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Mattis rhoncus urna neque viverra justo nec ultrices. Pretium quam vulputate dignissim suspendisse in est ante. Vitae congue mauris rhoncus aenean. Blandit cursus risus at ultrices mi. Ut lectus arcu bibendum at varius vel pharetra vel. Etiam non quam lacus suspendisse faucibus interdum posuere. Eget sit amet tellus cras adipiscing enim eu turpis egestas. Lectus magna fringilla urna porttitor rhoncus dolor purus non. Sit amet consectetur adipiscing elit duis tristique sollicitudin nibh. Nec tincidunt praesent semper feugiat nibh. Sapien pellentesque habitant morbi tristique senectus et netus et malesuada.";
pthread_t t1;
pthread_t t2;
pthread_t t3;
void *res_t1;
void *res_t2;
void *res_t3;
int *voc;
int *cons;
int *blank;
int s;
s = pthread_create(&t1, NULL, thread_nvocali, content);
if (s != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
s = pthread_create(&t2, NULL, thread_nconsonanti, content);
if (s != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
s = pthread_create(&t3, NULL, thread_nblank, content);
if (s != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
s = pthread_join(t1, &res_t1);
if (s != 0) {
perror("pthread_join");
exit(EXIT_FAILURE);
}
s = pthread_join(t2, &res_t2);
if (s != 0) {
perror("pthread_join");
exit(EXIT_FAILURE);
}
s = pthread_join(t3, &res_t3);
if (s != 0) {
perror("pthread_join");
exit(EXIT_FAILURE);
}
voc = (int*) res_t1;
cons = (int*) res_t2;
blank = (int*) res_t3;
printf("Primo thread return value %d\n", *voc);
printf("Secondo thread return value %d\n", *cons);
printf("Terzo thread return value %d\n", *blank);
printf("La stringa è lunga %d\n", strlen(content));
printf("In totale ho contato %d volte\n", (*voc+*cons+*blank));
//free(res_t1);
return 0;
}
|
C
|
/**
* @file db_test.c
* Tests for DB hash
*
* @remark Copyright 2002 OProfile authors
* @remark Read the file COPYING
*
* @author Philippe Elie
*/
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include "op_sample_file.h"
#include "odb.h"
#define TEST_FILENAME "test-hash-db.dat"
static int nr_error;
static int verbose = 0;
#define verbprintf(args...) \
do { \
if (verbose) \
printf(args); \
} while (0)
static double used_time(void)
{
struct rusage usage;
getrusage(RUSAGE_SELF, &usage);
return (usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) * 1E9 +
((usage.ru_utime.tv_usec + usage.ru_stime.tv_usec)) * 1000;
}
/* update nr item */
static void speed_test(int nr_item, char const * test_name)
{
int i;
double begin, end;
odb_t hash;
int rc;
rc = odb_open(&hash, TEST_FILENAME, ODB_RDWR, sizeof(struct opd_header));
if (rc) {
fprintf(stderr, "%s", strerror(rc));
exit(EXIT_FAILURE);
}
begin = used_time();
for (i = 0 ; i < nr_item ; ++i) {
rc = odb_update_node(&hash, i);
if (rc != EXIT_SUCCESS) {
fprintf(stderr, "%s", strerror(rc));
exit(EXIT_FAILURE);
}
}
end = used_time();
odb_close(&hash);
verbprintf("%s: nr item: %d, elapsed: %f ns\n",
test_name, nr_item, (end - begin) / nr_item);
}
static void do_speed_test(void)
{
int i;
for (i = 100000; i <= 10000000; i *= 10) {
// first test count insertion, second fetch and incr count
speed_test(i, "insert");
speed_test(i, "update");
remove(TEST_FILENAME);
}
}
static int test(int nr_item, int nr_unique_item)
{
int i;
odb_t hash;
int ret;
int rc;
rc = odb_open(&hash, TEST_FILENAME, ODB_RDWR, sizeof(struct opd_header));
if (rc) {
fprintf(stderr, "%s", strerror(rc));
exit(EXIT_FAILURE);
}
for (i = 0 ; i < nr_item ; ++i) {
odb_key_t key = (random() % nr_unique_item) + 1;
rc = odb_update_node(&hash, key);
if (rc != EXIT_SUCCESS) {
fprintf(stderr, "%s", strerror(rc));
exit(EXIT_FAILURE);
}
}
ret = odb_check_hash(&hash);
odb_close(&hash);
remove(TEST_FILENAME);
return ret;
}
static void do_test(void)
{
int i, j;
for (i = 1000; i <= 100000; i *= 10) {
for (j = 100 ; j <= i / 10 ; j *= 10) {
if (test(i, j)) {
fprintf(stderr, "%s:%d failure for %d %d\n",
__FILE__, __LINE__, i, j);
nr_error++;
} else {
verbprintf("test() ok %d %d\n", i, j);
}
}
}
}
static void sanity_check(char const * filename)
{
odb_t hash;
int rc;
rc = odb_open(&hash, filename, ODB_RDONLY, sizeof(struct opd_header));
if (rc) {
fprintf(stderr, "%s", strerror(rc));
exit(EXIT_FAILURE);
}
if (odb_check_hash(&hash)) {
fprintf(stderr, "checking file %s FAIL\n", filename);
++nr_error;
} else if (verbose) {
odb_hash_stat_t * stats;
stats = odb_hash_stat(&hash);
odb_hash_display_stat(stats);
odb_hash_free_stat(stats);
}
odb_close(&hash);
}
int main(int argc, char * argv[1])
{
/* if a filename is given take it as: "check this db" */
if (argc > 1) {
int i;
verbose = 1;
if (!strcmp(argv[1], "--speed"))
goto speed_test;
for (i = 1 ; i < argc ; ++i)
sanity_check(argv[i]);
return 0;
}
speed_test:
remove(TEST_FILENAME);
do_test();
do_speed_test();
if (nr_error)
printf("%d error occured\n", nr_error);
return nr_error ? EXIT_FAILURE : EXIT_SUCCESS;
}
|
C
|
/*
Par o impar?
*/
#include<stdio.h>
int main() {
int input;
printf("Par o impar?\n\nIngrese un numero: ");
scanf("%d", &input);
printf("El numero es %s.\n\n", (input & 1 ? "impar" : "par"));
system("PAUSE");
return 0;
}
/*
1000
0100
0010
0001
1011 8*1 + 4*0 + 2*1 + 1*1 = 11
1101 1001
0001
1110 8*1 + 4*1 + 2*1 + 1*0
*/
|
C
|
#ifdef __clang__
int maxB_int(int a, int b) {
return a < b ? b : a;
}
int minA_int(int a, int b) {
return a < b ? a : b;
}
int minB_int(int a, int b) {
return a > b ? b : a;
}
int maxA_int(int a, int b) {
return a > b ? a : b;
}
unsigned int maxB_unsigned_int(unsigned int a, unsigned int b) {
return a < b ? b : a;
}
unsigned int minA_unsigned_int(unsigned int a, unsigned int b) {
return a < b ? a : b;
}
unsigned int minB_unsigned_int(unsigned int a, unsigned int b) {
return a > b ? b : a;
}
unsigned int maxA_unsigned_int(unsigned int a, unsigned int b) {
return a > b ? a : b;
}
long int maxB_long_int(long int a, long int b) {
return a < b ? b : a;
}
long int minA_long_int(long int a, long int b) {
return a < b ? a : b;
}
long int minB_long_int(long int a, long int b) {
return a > b ? b : a;
}
long int maxA_long_int(long int a, long int b) {
return a > b ? a : b;
}
unsigned long int maxB_unsigned_long_int(unsigned long int a, unsigned long int b) {
return a < b ? b : a;
}
unsigned long int minA_unsigned_long_int(unsigned long int a, unsigned long int b) {
return a < b ? a : b;
}
unsigned long int minB_unsigned_long_int(unsigned long int a, unsigned long int b) {
return a > b ? b : a;
}
unsigned long int maxA_unsigned_long_int(unsigned long int a, unsigned long int b) {
return a > b ? a : b;
}
float maxB_float(float a, float b) {
return a < b ? b : a;
}
float minA_float(float a, float b) {
return a < b ? a : b;
}
float minB_float(float a, float b) {
return a > b ? b : a;
}
float maxA_float(float a, float b) {
return a > b ? a : b;
}
double maxB_double(double a, double b) {
return a < b ? b : a;
}
double minA_double(double a, double b) {
return a < b ? a : b;
}
double minB_double(double a, double b) {
return a > b ? b : a;
}
double maxA_double(double a, double b) {
return a > b ? a : b;
}
#endif
#ifdef TEST
#include <stdio.h>
#include <stdlib.h>
int test_maxB_int() {
int maxB_int(int, int);
#if 1
int a = (int)mrand48();
int b = (int)mrand48();
#else
int a = (int)(mrand48() % 100);
int b = (int)(mrand48() % 100);
#endif
int c0 = maxB_int(a, b);
int c1 = a < b ? b : a;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %d %d => %d\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_minA_int() {
int minA_int(int, int);
#if 1
int a = (int)mrand48();
int b = (int)mrand48();
#else
int a = (int)(mrand48() % 100);
int b = (int)(mrand48() % 100);
#endif
int c0 = minA_int(a, b);
int c1 = a < b ? a : b;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %d %d => %d\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_minB_int() {
int minB_int(int, int);
#if 1
int a = (int)mrand48();
int b = (int)mrand48();
#else
int a = (int)(mrand48() % 100);
int b = (int)(mrand48() % 100);
#endif
int c0 = minB_int(a, b);
int c1 = a > b ? b : a;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %d %d => %d\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_maxA_int() {
int maxA_int(int, int);
#if 1
int a = (int)mrand48();
int b = (int)mrand48();
#else
int a = (int)(mrand48() % 100);
int b = (int)(mrand48() % 100);
#endif
int c0 = maxA_int(a, b);
int c1 = a > b ? a : b;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %d %d => %d\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_maxB_unsigned_int() {
unsigned int maxB_unsigned_int(unsigned int, unsigned int);
#if 1
unsigned int a = (unsigned int)mrand48();
unsigned int b = (unsigned int)mrand48();
#else
unsigned int a = (unsigned int)(mrand48() % 100);
unsigned int b = (unsigned int)(mrand48() % 100);
#endif
unsigned int c0 = maxB_unsigned_int(a, b);
unsigned int c1 = a < b ? b : a;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %u %u => %u\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_minA_unsigned_int() {
unsigned int minA_unsigned_int(unsigned int, unsigned int);
#if 1
unsigned int a = (unsigned int)mrand48();
unsigned int b = (unsigned int)mrand48();
#else
unsigned int a = (unsigned int)(mrand48() % 100);
unsigned int b = (unsigned int)(mrand48() % 100);
#endif
unsigned int c0 = minA_unsigned_int(a, b);
unsigned int c1 = a < b ? a : b;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %u %u => %u\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_minB_unsigned_int() {
unsigned int minB_unsigned_int(unsigned int, unsigned int);
#if 1
unsigned int a = (unsigned int)mrand48();
unsigned int b = (unsigned int)mrand48();
#else
unsigned int a = (unsigned int)(mrand48() % 100);
unsigned int b = (unsigned int)(mrand48() % 100);
#endif
unsigned int c0 = minB_unsigned_int(a, b);
unsigned int c1 = a > b ? b : a;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %u %u => %u\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_maxA_unsigned_int() {
unsigned int maxA_unsigned_int(unsigned int, unsigned int);
#if 1
unsigned int a = (unsigned int)mrand48();
unsigned int b = (unsigned int)mrand48();
#else
unsigned int a = (unsigned int)(mrand48() % 100);
unsigned int b = (unsigned int)(mrand48() % 100);
#endif
unsigned int c0 = maxA_unsigned_int(a, b);
unsigned int c1 = a > b ? a : b;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %u %u => %u\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_maxB_long_int() {
long int maxB_long_int(long int, long int);
#if 1
long int a = (long int)mrand48();
long int b = (long int)mrand48();
#else
long int a = (long int)(mrand48() % 100);
long int b = (long int)(mrand48() % 100);
#endif
long int c0 = maxB_long_int(a, b);
long int c1 = a < b ? b : a;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %ld %ld => %ld\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_minA_long_int() {
long int minA_long_int(long int, long int);
#if 1
long int a = (long int)mrand48();
long int b = (long int)mrand48();
#else
long int a = (long int)(mrand48() % 100);
long int b = (long int)(mrand48() % 100);
#endif
long int c0 = minA_long_int(a, b);
long int c1 = a < b ? a : b;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %ld %ld => %ld\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_minB_long_int() {
long int minB_long_int(long int, long int);
#if 1
long int a = (long int)mrand48();
long int b = (long int)mrand48();
#else
long int a = (long int)(mrand48() % 100);
long int b = (long int)(mrand48() % 100);
#endif
long int c0 = minB_long_int(a, b);
long int c1 = a > b ? b : a;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %ld %ld => %ld\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_maxA_long_int() {
long int maxA_long_int(long int, long int);
#if 1
long int a = (long int)mrand48();
long int b = (long int)mrand48();
#else
long int a = (long int)(mrand48() % 100);
long int b = (long int)(mrand48() % 100);
#endif
long int c0 = maxA_long_int(a, b);
long int c1 = a > b ? a : b;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %ld %ld => %ld\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_maxB_unsigned_long_int() {
unsigned long int maxB_unsigned_long_int(unsigned long int, unsigned long int);
#if 1
unsigned long int a = (unsigned long int)mrand48();
unsigned long int b = (unsigned long int)mrand48();
#else
unsigned long int a = (unsigned long int)(mrand48() % 100);
unsigned long int b = (unsigned long int)(mrand48() % 100);
#endif
unsigned long int c0 = maxB_unsigned_long_int(a, b);
unsigned long int c1 = a < b ? b : a;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %lu %lu => %lu\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_minA_unsigned_long_int() {
unsigned long int minA_unsigned_long_int(unsigned long int, unsigned long int);
#if 1
unsigned long int a = (unsigned long int)mrand48();
unsigned long int b = (unsigned long int)mrand48();
#else
unsigned long int a = (unsigned long int)(mrand48() % 100);
unsigned long int b = (unsigned long int)(mrand48() % 100);
#endif
unsigned long int c0 = minA_unsigned_long_int(a, b);
unsigned long int c1 = a < b ? a : b;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %lu %lu => %lu\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_minB_unsigned_long_int() {
unsigned long int minB_unsigned_long_int(unsigned long int, unsigned long int);
#if 1
unsigned long int a = (unsigned long int)mrand48();
unsigned long int b = (unsigned long int)mrand48();
#else
unsigned long int a = (unsigned long int)(mrand48() % 100);
unsigned long int b = (unsigned long int)(mrand48() % 100);
#endif
unsigned long int c0 = minB_unsigned_long_int(a, b);
unsigned long int c1 = a > b ? b : a;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %lu %lu => %lu\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_maxA_unsigned_long_int() {
unsigned long int maxA_unsigned_long_int(unsigned long int, unsigned long int);
#if 1
unsigned long int a = (unsigned long int)mrand48();
unsigned long int b = (unsigned long int)mrand48();
#else
unsigned long int a = (unsigned long int)(mrand48() % 100);
unsigned long int b = (unsigned long int)(mrand48() % 100);
#endif
unsigned long int c0 = maxA_unsigned_long_int(a, b);
unsigned long int c1 = a > b ? a : b;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %lu %lu => %lu\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_maxB_float() {
float maxB_float(float, float);
#if 1
float a = (float)mrand48();
float b = (float)mrand48();
#else
float a = (float)(mrand48() % 100);
float b = (float)(mrand48() % 100);
#endif
float c0 = maxB_float(a, b);
float c1 = a < b ? b : a;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %f %f => %f\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_minA_float() {
float minA_float(float, float);
#if 1
float a = (float)mrand48();
float b = (float)mrand48();
#else
float a = (float)(mrand48() % 100);
float b = (float)(mrand48() % 100);
#endif
float c0 = minA_float(a, b);
float c1 = a < b ? a : b;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %f %f => %f\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_minB_float() {
float minB_float(float, float);
#if 1
float a = (float)mrand48();
float b = (float)mrand48();
#else
float a = (float)(mrand48() % 100);
float b = (float)(mrand48() % 100);
#endif
float c0 = minB_float(a, b);
float c1 = a > b ? b : a;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %f %f => %f\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_maxA_float() {
float maxA_float(float, float);
#if 1
float a = (float)mrand48();
float b = (float)mrand48();
#else
float a = (float)(mrand48() % 100);
float b = (float)(mrand48() % 100);
#endif
float c0 = maxA_float(a, b);
float c1 = a > b ? a : b;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %f %f => %f\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_maxB_double() {
double maxB_double(double, double);
#if 1
double a = (double)mrand48();
double b = (double)mrand48();
#else
double a = (double)(mrand48() % 100);
double b = (double)(mrand48() % 100);
#endif
double c0 = maxB_double(a, b);
double c1 = a < b ? b : a;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %lf %lf => %lf\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_minA_double() {
double minA_double(double, double);
#if 1
double a = (double)mrand48();
double b = (double)mrand48();
#else
double a = (double)(mrand48() % 100);
double b = (double)(mrand48() % 100);
#endif
double c0 = minA_double(a, b);
double c1 = a < b ? a : b;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %lf %lf => %lf\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_minB_double() {
double minB_double(double, double);
#if 1
double a = (double)mrand48();
double b = (double)mrand48();
#else
double a = (double)(mrand48() % 100);
double b = (double)(mrand48() % 100);
#endif
double c0 = minB_double(a, b);
double c1 = a > b ? b : a;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %lf %lf => %lf\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
int test_maxA_double() {
double maxA_double(double, double);
#if 1
double a = (double)mrand48();
double b = (double)mrand48();
#else
double a = (double)(mrand48() % 100);
double b = (double)(mrand48() % 100);
#endif
double c0 = maxA_double(a, b);
double c1 = a > b ? a : b;
#ifdef MAIN
fprintf(stderr, "%-40s %s # %lf %lf => %lf\n", __FUNCTION__, c0 == c1 ? "OK" : "NG", a, b, c0);
#endif
}
#endif
#ifdef MAIN
int main(int argc, char* argv[]) {
test_maxB_int();
test_minA_int();
test_minB_int();
test_maxA_int();
test_maxB_unsigned_int();
test_minA_unsigned_int();
test_minB_unsigned_int();
test_maxA_unsigned_int();
test_maxB_long_int();
test_minA_long_int();
test_minB_long_int();
test_maxA_long_int();
test_maxB_unsigned_long_int();
test_minA_unsigned_long_int();
test_minB_unsigned_long_int();
test_maxA_unsigned_long_int();
test_maxB_float();
test_minA_float();
test_minB_float();
test_maxA_float();
test_maxB_double();
test_minA_double();
test_minB_double();
test_maxA_double();
return 0;
}
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
/*
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the first and last digit are known as gapful numbers.
Example
187 is a gapful number because it is evenly divisible by the number 17 which is formed by the first and last decimal digits of 187.
*/
/* first --> units digit */
int numberIntoDigits(int a)
{ int first=0,last=0,temp=a;
while(a>0)
{ if(last==0)
{
first = a%10;
last = 10;
}
a = a/10;
if(a<10 && a>0)
{
last = a;
}
}
if(temp %(first+10*last)==0)
return 1;
else
return 0;
}
int main()
{
int number=0;
printf("Please enter your gapful number\n");
scanf("%d",&number);
if(numberIntoDigits(number)==1)
{
printf("Yes this is Gapful Number!");
}
else
printf("Sorry,this is not Gapful Number.");
return 0;
}
/*--------------------------And if you wanna see the first fifty gapful number--------------------------*/
#include <stdio.h>
#include <stdlib.h>
int main()
{ int counter = 0;
int a = 100;
while(counter<50)
{
int first=0,last=0,temp=a;
while(a>0)
{ if(last==0)
{
first = a%10;
last = 10;
}
a = a/10;
if(a<10 && a>0)
{
last = a;
}
}
if(temp %(first+10*last)==0)
{
printf("%d. : %d\n",counter+1,temp);
counter++;
}
a = temp + 1;
}
return 0;
}
|
C
|
#include "gps.h"
uint8_t UPDATE_10HZ[] = PMTK_SET_NMEA_UPDATE_10HZ;
uint8_t UPDATE_ONLY_RMC[] = PMTK_SET_NMEA_OUTPUT_RMCONLY;
uint8_t UPDATE_POSITION_10HZ[] = PMTK_API_SET_FIX_CTL_5HZ;
float currentKnots = 0;
bool InitializeGPS(void)
{
//Pins and interrupts are initialized in BOARD_InitPeripherals(void)
//PMTK_SET_NMEA_OUTPUT_RMCONLY
UART_WriteBlocking(UART3_PERIPHERAL, UPDATE_ONLY_RMC, sizeof(UPDATE_ONLY_RMC)/sizeof(UPDATE_ONLY_RMC[0]) -1);
//PMTK_API_SET_FIX_CTL_5HZ
UART_WriteBlocking(UART3_PERIPHERAL, UPDATE_POSITION_10HZ, sizeof(UPDATE_POSITION_10HZ)/sizeof(UPDATE_POSITION_10HZ[0]) -1);
//PMTK_SET_NMEA_UPDATE_10HZ
UART_WriteBlocking(UART3_PERIPHERAL, UPDATE_10HZ, sizeof(UPDATE_10HZ)/sizeof(UPDATE_10HZ[0]) -1);
return true;
}
double getGpsVelocity(void)
{
int i = 0;
if(bCheckGps){
char *ptr = strtok(gpsRxBuffer, ",");
while(ptr != NULL)
{
if(i == 7){
currentKnots = atof(ptr);
break;
}
ptr = strtok(NULL, ",");
i++;
}
bCheckGps = false;
}
/*for(int i = 0; i<GPS_BUFFER_SIZE; i++)
{
printf("%c", gpsRxBuffer[i]);
}
printf("\n");
printf("%f\n", knots);
*/
//Knots to m/s
return currentKnots*0.514444;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <pwd.h>
#include <string.h>
static void my_alarm(int signo)
{
struct passwd *rootptr;
printf("in signal handler\n");
if((rootptr=getpwnam("root"))==NULL)
printf("getpwnam(root) error\n");
alarm(1);
}
int main(int argc, char**argv)
{
struct passwd *ptr;
signal(SIGALRM,my_alarm);
alarm(1);
for(;;)
{
if((ptr=getpwnam("changer"))==NULL)
printf("getpwnam error\n");
if(strcmp(ptr->pw_name,"changer")!=0)
printf("return value corrupted!,pw_name=%s\n",ptr->pw_name);
}
}
|
C
|
/* The main jaunty engine, responsible for keeping track of
* levels, actors, etc... */
#include "jaunty.h"
#include <stdio.h>
/* Utility functions */
/* returns a number that is a number, 'a', converted into the nearest number
* that is a whole power of 2 (rounding up) */
#define mkp2(a) (int)powf(2.0, ceilf(logf((float)a)/logf(2.0)))
enum {
MAX_C_PROCESSING_LOOPS = 100
};
/* Utility function to get a pixel at ('x', 'y') from a surface */
Uint32 get_pixel(SDL_Surface *surface, int x, int y)
{
int bpp = surface->format->BytesPerPixel;
/* Here p is the address to the pixel we want to retrieve */
Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;
switch(bpp) {
case 1:
return *p;
break;
case 2:
return *(Uint16 *)p;
break;
case 3:
if(SDL_BYTEORDER == SDL_BIG_ENDIAN)
return p[0] << 16 | p[1] << 8 | p[2];
else
return p[0] | p[1] << 8 | p[2] << 16;
break;
case 4:
return *(Uint32 *)p;
break;
default:
return 0; /* shouldn't happen, but avoids warnings */
}
}
void printbitssimple(unsigned long n)
{
unsigned long i;
i = 1UL <<(sizeof(i) * CHAR_BIT - 1);
while (i > 0) {
if (n & i)
fprintf(stderr, "1");
else
fprintf(stderr, "0");
i >>= 1;
}
}
void print_overlap(struct jty_overlap *overlap)
{
fprintf(stderr, "Overlap is: a1 offset: (%f, %f)\n"
" a2 offset: (%f, %f)\n"
" overlap: (%f, %f)\n",
overlap->x.a1_offset, overlap->y.a1_offset,
overlap->x.a2_offset, overlap->y.a2_offset,
overlap->x.overlap, overlap->y.overlap);
return;
}
void print_c_info(struct jty_c_info *c_info)
{
fprintf(stderr, "Collision info is: normal: (%f, %f)\n"
" penetration: %f\n",
c_info->normal.x, c_info->normal.y,
c_info->penetration);
}
void print_c_shape(jty_shape *c_shape)
{
fprintf(stderr, "C-shape: centre: (%f, %f)\n"
" width, height: (%f, %f)\n",
c_shape->centre.x, c_shape->centre.y,
c_shape->w, c_shape->h);
}
/* Calculates the linear overlap of lines going from (a1 -> a2) and (b1->b2) */
int jty_calc_overlap_l(double a1, double a2, double b1, double b2,
struct jty_overlap_l *overlap)
{
if(a1 < b1){
if(a2 <= b1){
return 0;
}
overlap->a1_offset = b1 - a1;
overlap->a2_offset = 0;
if(a2 < b2){
overlap->overlap = a2 - b1;
}else{
overlap->overlap = b2 - b1;
}
}else{
if(b2 <= a1){
return 0;
}
overlap->a1_offset = 0;
overlap->a2_offset = a1 - b1;
if(b2 < a2){
overlap->overlap = b2 - a1;
}else{
overlap->overlap = a2 - a1;
}
}
return 1;
}
/* Engine functions */
/* Sets up the video surface */
static void initialise_video(unsigned int win_w,
unsigned int win_h)
{
const SDL_VideoInfo *info = NULL;
int flags = SDL_OPENGL;// | SDL_FULLSCREEN;
if(SDL_Init(SDL_INIT_VIDEO) == -1){
fprintf(stderr, "Video initialisation failed: %s\n", SDL_GetError());
exit(1);
}
info = SDL_GetVideoInfo();
jty_engine->screen = SDL_SetVideoMode(win_w, win_h,
info->vfmt->BitsPerPixel, flags);
if(!jty_engine->screen){
fprintf(stderr, "Failed to open screen!\n");
exit(1);
}
/* OpenGL initialisation */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glDisable(GL_DEPTH); /* This is a 2d program, no need for depth test */
return;
}
jty_eng *new_jty_eng(unsigned int win_w, unsigned int win_h)
{
jty_engine = malloc(sizeof(*jty_engine));
return jty_eng_init(jty_engine, win_w, win_h);
}
jty_eng *jty_eng_init(jty_eng *engine, unsigned int win_w, unsigned int win_h)
{
jty_engine = engine;
initialise_video(win_w, win_h);
engine->map = NULL;
engine->elapsed_frames = 0;
engine->set_up_level = NULL;
engine->is_level_finished = NULL;
engine->clean_up_level = NULL;
return engine;
}
/* Map functions */
void free_jty_map(jty_map *map)
{
if (map == NULL) {
return;
}
jty_actor *a;
/* Free actors */
while(map->actors) {
a = map->actors->actor;
map->actors = jty_actor_ls_rm(map->actors,
map->actors->actor);
free(a);
}
#ifdef DEBUG_MODE
fprintf(stderr, "Deleting map\n");
#endif
SDL_FreeSurface(map->tilepalette);
glDeleteTextures(1, &(map->texname));
free(map);
return ;
}
static int jty_map_from_string(jty_map *map,
const char *k,
const char *m)
{
SDL_Rect dst, src;
SDL_Surface *map_image;
int j, i, z = 0;
unsigned char (*map_ptr)[map->w];
unsigned char index;
map_ptr = malloc(sizeof(unsigned char) * map->w * map->h);
if(!map_ptr){
return 0;
}
for(j = 0; j < map->h; j++)
for(i = 0; i < map->w; i++){
index = (strchr(k, m[z]) - k) / (sizeof(unsigned char));
map_ptr[j][i] = index;
z++;
}
map_image = SDL_CreateRGBSurface(SDL_SWSURFACE, map->w * map->tw, map->h * map->th, 32,
RMASK, GMASK, BMASK, AMASK);
if(!map_image){
return 0;
}
src.w = map->tw;
src.h = map->th;
SDL_SetAlpha(map->tilepalette, 0, 0);
for(j = 0; j < map->h; j++)
for(i = 0; i < map->w; i++){
dst.x = i * map->tw;
dst.y = j * map->th ;
index = map_ptr[j][i];
src.x = (index % (map->tilepalette->w / map->tw)) * map->tw;
src.y = (index / (map->tilepalette->w / map->tw)) * map->th;
SDL_BlitSurface(map->tilepalette, &src, map_image, &dst);
}
#ifdef JTY_SAVE_MAPS
static int n = 0;
char fname[500];
sprintf(fname, "map_images/map%d.bmp", n);
if(!SDL_SaveBMP(map_image, fname)) {
fprintf(stderr, "level image saving failed: %s\n", SDL_GetError());
}
n++;
#endif
/* create an openGL texture and bind the sprite's image
* to it */
glGenTextures(1, &(map->texname));
glBindTexture(GL_TEXTURE_2D, map->texname);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, map_image->w,
map_image->h, 0, GL_RGBA, GL_UNSIGNED_BYTE,
map_image->pixels);
free(map_ptr);
SDL_FreeSurface(map_image);
return 1;
}
static int jty_map_set_cmap(jty_map *map, const char *cm)
{
map->c_map = malloc(sizeof(*(map->c_map)) * map->w * map->h);
memcpy(map->c_map, cm, sizeof(*(map->c_map)) * map->w * map->h);
if(map->c_map == NULL){
return 0;
}
return 1;
}
jty_map *new_jty_map(
int w, int h, int tw, int th,
const char *filename, const char *k, const char *m,
const char *cm)
{
jty_map *map = malloc(sizeof(*map));
if(!map)
return NULL;
return jty_map_init(
map,
w,
h,
tw,
th,
filename,
k,
m,
cm);
}
jty_map *jty_map_init(
jty_map *map,
int w,
int h,
int tw,
int th,
const char *filename,
const char *k,
const char *m,
const char *cm)
{
map->w = w;
map->h = h;
map->tw = tw;
map->th = th;
map->map_rect.x = 0;
map->map_rect.y = 0;
map->map_rect.w = w * tw; //jty_engine->screen->w;
map->map_rect.h = h * th; //jty_engine->screen->h;
map->actors = NULL;
map->collision_actors = NULL;
map->a_a_handlers = NULL;
map->tilepalette = IMG_Load(filename);
if(!map->tilepalette){
free_jty_map(map);
return NULL;
}
if(!jty_map_from_string(map, k, m)){
free_jty_map(map);
return NULL;
}
if(!jty_map_set_cmap(map, cm)){
free_jty_map(map);
return NULL;
}
return map;
}
/* Paint the 'actor' */
static int jty_actor_paint(jty_actor *actor)
{
double frame = jty_engine->elapsed_frames;
double fframe = frame - floor(frame); /* fframe holds what fraction we
through the current frame */
jty_sprite *curr_sprite = actor->sprites[actor->current_sprite];
/* Calculating the point where the actor should be drawn */
actor->gx = fframe * actor->x + (1 - fframe) * actor->px;
actor->gy = fframe * actor->y + (1 - fframe) * actor->py;
/* Paint the actor's texture in the right place */
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
/* Load the actor's texture */
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
/* Draw the actor */
/* translating the actor's matrix to the point where the
* the actor should be drawn */
glTranslatef(actor->gx, actor->gy, 0);
glBindTexture(GL_TEXTURE_2D,
curr_sprite->textures[actor->current_frame]);
glBegin(GL_QUADS);
glColor3f(1.0f, 1.0f, 1.0f);
glTexCoord2d(0, 0);
glVertex2i(-curr_sprite->p2w/2, -curr_sprite->p2h/2);
glTexCoord2d(0, 1);
glVertex2i(-curr_sprite->p2w/2, curr_sprite->p2h/2);
glTexCoord2d(1, 1);
glVertex2i(curr_sprite->p2w/2, curr_sprite->p2h/2);
glTexCoord2d(1, 0);
glVertex2i(curr_sprite->p2w/2, -curr_sprite->p2h/2);
glEnd();
glDisable(GL_BLEND);
return 1;
}
void jty_map_paint(jty_map *map)
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(map->map_rect.x, map->map_rect.y, map->map_rect.w,
map->map_rect.h);
glOrtho(0, map->map_rect.w, map->map_rect.h, 0, 1, -1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, map->texname);
glBegin(GL_QUADS);
glTexCoord2d(0.0, 0.0);
glVertex2i(0, 0);
glTexCoord2d(0.0, 1.0);
glVertex2i(0, map->h * map->th);
glTexCoord2d(1.0, 1.0);
glVertex2i(map->w * map->tw, map->h * map->th);
glTexCoord2d(1.0, 0.0);
glVertex2i(map->w * map->tw, 0);
glEnd();
/* Paint actors */
jty_actor_ls *pg;
for(pg = map->actors; pg != NULL; pg = pg->next){
jty_actor_paint(pg->actor);
}
return;
}
jty_actor_ls *jty_actor_ls_add(jty_actor_ls *ls, jty_actor *actor)
{
jty_actor_ls *next;
next = ls;
if((ls = malloc(sizeof(*(ls)))) == NULL){
fprintf(stderr, "Error allocating list node\n");
exit(1);
}
ls->next = next;
ls->actor = actor;
return ls;
}
/* Sprite functions */
void jty_sprite_free(jty_sprite *sprite)
{
/* Delete the textures */
glDeleteTextures(sprite->num_of_frames, sprite->textures);
free(sprite->textures);
return;
}
jty_sprite *jty_sprite_create(
int w, int h, const char *sprite_filename, jty_shape **c_shapes
)
{
jty_sprite *sprite;
Uint32 colourkey;
int max_size, xpad, ypad;
SDL_Surface *sprite_img, *image;
SDL_Rect dst, src;
int i;
if((sprite = malloc(sizeof(*sprite))) == NULL){
fprintf(stderr, "Error allocating memory for sprite.\n");
exit(1);
}
sprite->w = w;
sprite->h = h;
sprite->p2w = mkp2(w);
sprite->p2h = mkp2(h);
/* Check sprite size doesn't exceed openGL's maximum texture size */
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_size);
if(sprite->p2w > max_size || sprite->p2h > max_size){
fprintf(stderr, "Image size of sprite %s, (%d, %d) exceeds "
"maximum texture size (%d)\n",
"plcholder", sprite->p2w, sprite->p2h, max_size);
return NULL;
}
if (sprite_filename == NULL) {
/**
* If no filename stated just return a sprite with nothing
* bound to the textures
*/
sprite->textures = malloc(sizeof(*sprite->textures));
glGenTextures(1, sprite->textures);
return sprite;
}
/* Load the image file that will contain the sprite */
image = IMG_Load(sprite_filename);
sprite->num_of_frames = image->w / w;
sprite->textures = malloc(sprite->num_of_frames * sizeof(*sprite->textures));
glGenTextures(sprite->num_of_frames, sprite->textures);
if(!image){
fprintf(stderr, "Error! Could not load %s\n", sprite_filename);
return NULL;
}
/* Make SDL copy the alpha channel of the image */
SDL_SetAlpha(image, 0, SDL_ALPHA_OPAQUE);
colourkey = SDL_MapRGBA(image->format, 0xff, 0x00, 0xff, 0);
xpad = (sprite->p2w - sprite->w)/2;
ypad = (sprite->p2h - sprite->h)/2;
sprite_img = SDL_CreateRGBSurface(SDL_SWSURFACE, sprite->p2w,
sprite->p2h, 32, RMASK, GMASK, BMASK, AMASK);
if(!sprite_img){
fprintf(stderr, "Error creating a surface for the sprites\n");
jty_sprite_free(sprite);
return NULL;
}
for(i=0; i < sprite->num_of_frames; i++) {
dst.x = xpad;
dst.y = ypad;
dst.w = sprite->w;
dst.h = sprite->h;
src.w = sprite->w;
src.h = sprite->h;
src.x = i * sprite->w;
src.y = 0;
SDL_FillRect(sprite_img, NULL, colourkey);
SDL_SetColorKey(image, SDL_SRCCOLORKEY, colourkey);
SDL_BlitSurface(image, &src, sprite_img, &dst);
/* Create an openGL texture and bind the sprite's image to it */
glBindTexture(GL_TEXTURE_2D, sprite->textures[i]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, sprite->p2w, sprite->p2h,
0, GL_RGBA, GL_UNSIGNED_BYTE, sprite_img->pixels);
}
SDL_FreeSurface(image);
SDL_FreeSurface(sprite_img);
sprite->c_shapes = c_shapes;
return sprite;
}
/* Actor functions */
void jty_actor_free(jty_actor *actor)
{
int i;
#ifdef DEBUG_MODE
fprintf(stderr, "Deleting actor uid: %d\n", actor->uid);
#endif
for(i = 0; i < actor->num_of_sprites; i++) {
jty_sprite_free(actor->sprites[i]);
}
free(actor->sprites);
/* TODO: free iteration and map handlers */
free(actor);
return;
}
static jty_actor *jty_actor_init_int(
jty_actor *actor,
unsigned int groupnum,
jty_map *map,
int num_of_sprites,
int w,
int h,
const char *sprite_filename,
jty_shape **c_shapes,
va_list parg)
{
jty_sprite **sprites;
static unsigned int uid = 0;
int i;
sprites = malloc(sizeof(*sprites) * num_of_sprites);
sprites[0] = jty_sprite_create(w, h, sprite_filename, c_shapes);
for(i=1; i< num_of_sprites; i++){
w = va_arg(parg, int);
h = va_arg(parg, int);
sprite_filename = va_arg(parg, char *);
c_shapes = va_arg(parg, jty_shape **);
sprites[i] = jty_sprite_create(w, h, sprite_filename, c_shapes);
}
actor->x = actor->y = actor->px = actor->py = 0;
actor->vx = actor->vy = actor->ax = actor->ay = 0;
actor->current_sprite = 0;
actor->current_frame = 0;
actor->i_ls = NULL;
actor->m_h_ls = NULL;
actor->a_h_ls = NULL;
actor->map = map;
/* Put the actor in the map's actor list */
map->actors = jty_actor_ls_add(map->actors, actor);
/* Add any relevant actor actor handlers */
jty_a_a_handle_ls *hp;
for (hp = map->a_a_handlers; hp != NULL; hp = hp->next) {
jty_actor_add_a_handler(
actor,
hp->groupnum1,
hp->groupnum2,
hp->handler);
}
actor->groupnum = groupnum;
actor->sprites = sprites;
actor->uid = uid;
actor->num_of_sprites = num_of_sprites;
actor->collision_primed = 0;
uid++;
#ifdef DEBUG_MODE
fprintf(stderr, "\nCreating actor %d\n", actor->uid);
#endif
#ifdef DEBUG_MODE
jty_actor_ls *q;
fprintf(stderr, "List of map's actors: ");
for(q=map->actors; q!=NULL; q=q->next){
fprintf(stderr, "%d, ", q->actor->uid);
}
fprintf(stderr, "\n");
#endif
return actor;
}
jty_actor *new_jty_actor(
unsigned int groupnum,
jty_map *map,
int num_of_sprites,
int w,
int h,
const char *sprite_filename,
jty_shape **c_shapes,
...
)
{
jty_actor *actor = malloc(sizeof(*actor));
va_list parg;
va_start(parg, c_shapes);
return jty_actor_init_int(
actor,
groupnum,
map,
num_of_sprites,
w,
h,
sprite_filename,
c_shapes,
parg);
}
jty_actor *jty_actor_init(
jty_actor *actor,
unsigned int groupnum,
jty_map *map,
int num_of_sprites,
int w,
int h,
const char *sprite_filename,
jty_shape **c_shapes,
...
)
{
va_list parg;
va_start(parg, c_shapes);
return jty_actor_init_int(
actor,
groupnum,
map,
num_of_sprites,
w,
h,
sprite_filename,
c_shapes,
parg);
}
void jty_actor_add_i_handler(jty_actor *actor,
void (*i_handler)(struct jty_actor *))
{
jty_actor_i_ls *ls;
jty_actor_i_ls *next;
next = actor->i_ls;
if((ls = malloc(sizeof(*(ls)))) == NULL){
fprintf(stderr, "Error allocating list node\n");
exit(1);
}
ls->next = next;
ls->i_handler = i_handler;
actor->i_ls = ls;
return;
}
void jty_actor_map_tile_overlap(jty_actor *a, int i, int j, jty_overlap *overlap)
{
jty_sprite *curr_sprite = a->sprites[a->current_sprite];
jty_calc_overlap_l(a->x - curr_sprite->w / 2., a->x + curr_sprite->w / 2.,
i * a->map->tw, (i + 1) * a->map->tw,
&(overlap->x));
jty_calc_overlap_l(a->y - curr_sprite->h / 2., a->y + curr_sprite->h / 2.,
j * a->map->th, (j + 1) * a->map->th,
&(overlap->y));
return;
}
#define jty_actor_get_sprite(actor) (actor->sprites[actor->current_sprite])
int jty_actor_has_left_map(jty_actor *actor)
{
jty_sprite *sprite = jty_actor_get_sprite(actor);
if (actor->x + sprite->w / 2 < 0) {
return 1;
}
if (actor->y + sprite->h / 2 < 0) {
return 1;
}
double map_width = actor->map->tw * actor->map->w;
if (actor->x - sprite->w / 2 > map_width) {
return 1;
}
double map_height = actor->map->th * actor->map->h;
if (actor->y - sprite->h / 2 > map_height) {
return 1;
}
return 0;
}
jty_shape jty_actor_get_c_shape(jty_actor *actor)
{
jty_shape *csp = jty_actor_get_sprite(actor)
->c_shapes[actor->current_frame];
jty_shape c_shape = {
.centre = {
.x = csp->centre.x + actor->x,
.y = csp->centre.y + actor->y
},
.w = csp->w,
.h = csp->h,
.radius = csp->radius,
.type = csp->type
};
return c_shape;
}
/*jty_geometry_c_circle_aligned_rect(
jty_vector c_centre,
float r,
jty_vector r_centre,
float w,
float h,
jty_c_info *c_info
)
{
float a , b, c, d;
struct jty_actor normal;
a = fabs(c_centre.x - (r_centre.x + w/2));
b = fabs(c_centre.x - (r_centre.x - w/2));
c = fabs(circle_centre.y - (r_centre.y + h/2));
d = fabs(circle_centre.y - (r_centre.y - h/2));
if (a < r + w/2 && c < r + h/2) {
normal.x = -1;
normal.y = 0;
c_info->normal = normal;
c_info->penetration = a - (r + w/2);
} else if (b < r + w/2) {
normal.x = 1;
normal.y = 0;
c_info->normal = normal;
c_info->penetration = b -
}
}
*/
/**
* Calculates collision info (which is placed in the struct pointed to
* by `c_info`) for the collision between two JTY_RECT jty_shapes, `rect1`
* and `rect2`. `v_rel` is the relative velocity of `rect1` relative to
* `rect2` and is used for calculating whether the collision would have
* been between the x or y sides of the rect.
* 1 is returned if rectangles collide, 0 if they don't.
*/
typedef enum r_r_detect_dn {
R_R_DETECT_BOTH,
R_R_DETECT_X,
R_R_DETECT_Y
} r_r_detect_dn;
int jty_rect_rect_detect(
jty_shape *rect1,
jty_shape *rect2,
jty_vector v_rel,
r_r_detect_dn check_in_direction,
double *t,
jty_c_info *c_info)
{
struct jty_overlap overlap;
double t_x, t_y; /* Time before current time that rectangles
would have first collided in the x and
y directions, respectively */
double d_x, d_y; /* Distance to travel to get out of collision */
jty_vector normal;
if (
jty_calc_overlap_l(
rect1->centre.x - rect1->w/2, rect1->centre.x + rect1->w/2,
rect2->centre.x - rect2->w/2, rect2->centre.x + rect2->w/2,
&overlap.x) == 0 ||
jty_calc_overlap_l(
rect1->centre.y - rect1->h/2, rect1->centre.y + rect1->h/2,
rect2->centre.y - rect2->h/2, rect2->centre.y + rect2->h/2,
&overlap.y) == 0
)
{
return 0;
}
if (overlap.x.a1_offset == 0) {
normal.x = -1;
d_x = rect2->w - overlap.x.a2_offset;
t_x = d_x / v_rel.x * normal.x;
if (t_x < 0) {
normal.x = 1;
d_x = rect1->w + rect2->w - overlap.x.a2_offset;
t_x = d_x / v_rel.x * normal.x;
}
} else { /* a2_offset == 0 */
normal.x = 1;
d_x = rect1->w - overlap.x.a1_offset;
t_x = d_x / v_rel.x * normal.x;
if (t_x < 0) {
normal.x = -1;
d_x = rect1->w + rect2->w - overlap.x.a1_offset;
t_x = d_x / v_rel.x * normal.x;
}
}
if (t_x < 0 || v_rel.x == 0) {
t_x = INFINITY;
if (check_in_direction == R_R_DETECT_X) {
return 0;
}
}
if (overlap.y.a1_offset == 0) {
normal.y = -1;
d_y = rect2->h - overlap.y.a2_offset;
t_y = d_y / v_rel.y * normal.y;
if (t_y < 0) {
normal.y = 1;
d_y = rect2->h + rect1->h - overlap.y.a2_offset;
t_y = d_y / v_rel.y * normal.y;
}
} else { /* a2_offset == 0 */
normal.y = 1;
d_y = rect1->h - overlap.y.a1_offset;
t_y = d_y / v_rel.y * normal.y;
if (t_y < 0) {
normal.y = -1;
d_y = rect2->h + rect1->h - overlap.y.a1_offset;
t_y = d_y / v_rel.y * normal.y;
}
}
if (t_y < 0 || v_rel.y == 0) {
t_y = INFINITY;
if (check_in_direction == R_R_DETECT_Y) {
return 0;
}
}
if (fabs(v_rel.x) < 0.01 && fabs(v_rel.y) < 0.01) {
c_info->normal.x = 0;
c_info->normal.y = 0;
c_info->penetration = 0;
return 1;
}
if (
(check_in_direction == R_R_DETECT_BOTH && t_x < t_y) ||
(check_in_direction == R_R_DETECT_X)
) {
*t = t_x;
c_info->normal.x = normal.x;
c_info->normal.y = 0;
c_info->penetration = d_x;
#ifdef DEBUG_MODE
fprintf(stderr, "vrel: (%f, %f)\n", v_rel.x, v_rel.y);
fprintf(stderr, "t's: (%f, %f)\n", t_x, t_y);
print_overlap(&overlap);
print_c_info(c_info);
print_c_shape(rect1);
print_c_shape(rect2);
#endif
return 1;
}
*t = t_y;
c_info->normal.x = 0;
c_info->normal.y = normal.y;
c_info->penetration = d_y;
#ifdef DEBUG_MODE
fprintf(stderr, "vrel: (%f, %f)\n", v_rel.x, v_rel.y);
fprintf(stderr, "t's: (%f, %f)\n", t_x, t_y);
print_overlap(&overlap);
print_c_info(c_info);
print_c_shape(rect1);
print_c_shape(rect2);
#endif
return 1;
}
jty_shape jty_new_shape_rect(float x, float y, float w, float h)
{
jty_shape rect = {.centre = {.x = x, .y = y},
.radius = 0,
.w = w,
.h = h,
.type = JTY_RECT};
return rect;
}
int jty_actor_map_tile_c_detect(
jty_actor *actor,
int i,
int j,
r_r_detect_dn check_in_direction,
double *t,
jty_c_info *c_info)
{
jty_shape c_shape;
jty_map *map = actor->map;
jty_shape tile_rect = jty_new_shape_rect((i + 0.5) * map->tw,
(j + 0.5) * map->th,
map->tw,
map->th);
jty_vector v_rel = {.x = actor->x - actor->px, .y = actor->y - actor->py};
int collided;
c_shape = jty_actor_get_c_shape(actor);
if (c_shape.type == JTY_RECT) {
if ((collided = jty_rect_rect_detect(
&c_shape,
&tile_rect,
v_rel,
check_in_direction,
t,
c_info))) {
fprintf(stderr, "Collission with %d %d!!!\n", i, j);
return collided;
}
}
return 0;
}
/**
* Calls the map handler referred to in `mhl` if it should be
* called. The map handler should be called if the collision
* wouldn't push `actor` onto another tile that is handled
* by the same collision handler. This stops the actor getting
* stuck when it moves up the side of a set of tiles that
* are contiguous
*/
int set_map_handler(
jty_map_handle_ls *mhl,
jty_actor *actor,
int i,
int j,
char tile_type,
jty_c_handler *handler_max,
double *t_max,
jty_c_info *c_info_max,
double *t,
jty_c_info *c_info)
{
unsigned char (*c_map)[actor->map->w] =
(void *)actor->map->c_map;
r_r_detect_dn extra_check_dn = R_R_DETECT_BOTH;
if (c_info->normal.x == -1
&& i > 0 && strchr(mhl->tiles, c_map[j][i+1])) {
extra_check_dn = R_R_DETECT_Y;
}
if (c_info->normal.x == 1 &&
i < actor->map->w - 1 && strchr(mhl->tiles, c_map[j][i-1])) {
extra_check_dn = R_R_DETECT_Y;
}
if (c_info->normal.y == -1 &&
j > 0 && strchr(mhl->tiles, c_map[j+1][i])) {
extra_check_dn = R_R_DETECT_X;
}
if (c_info->normal.y == 1 &&
j < actor->map->h - 1 && strchr(mhl->tiles, c_map[j-1][i])) {
extra_check_dn = R_R_DETECT_X;
}
c_info->e1.actor = actor;
c_info->e2.tile = actor->map->w * j + i;
if (extra_check_dn == R_R_DETECT_BOTH) {
if (*t > *t_max) {
*t_max = *t;
*c_info_max = *c_info;
*handler_max = mhl->handler;
}
return 1;
}
if (jty_actor_map_tile_c_detect(
actor,
i,
j,
extra_check_dn,
t,
c_info)) {
if (*t > *t_max) {
*t_max = *t;
*c_info_max = *c_info;
*handler_max = mhl->handler;
}
return 1;
}
return 0;
}
void jty_actor_iterate(jty_actor *actor)
{
actor->px = actor->x;
actor->py = actor->y;
actor->x += actor->vx;
actor->y += actor->vy;
actor->vx += actor->ax;
actor->vy += actor->ay;
jty_actor_i_ls *pg;
for(pg = actor->i_ls; pg != NULL; pg = pg->next){
pg->i_handler(actor);
}
return;
}
static jty_map_handle_ls *jty_actor_add_m_handler_int(jty_actor *actor,
jty_c_handler handler,
char *tiles)
{
jty_map_handle_ls *hp;
char *tiles_copy;
hp = malloc(sizeof(*hp));
if(hp == NULL){
fprintf(stderr, "Unable to allocate memory for a "
"list handler node.\n");
exit(1);
}
tiles_copy = malloc(sizeof(*tiles_copy) * (strlen(tiles) + 1));
if(tiles_copy == NULL) {
fprintf(stderr, "Unable to alocate memory for map "
"handler tiles copy.\n");
}
strcpy(tiles_copy, tiles);
hp->tiles = tiles_copy;
hp->handler = handler;
hp->next = actor->m_h_ls;
#ifdef DEBUG_MODE
fprintf(stderr, "\nCreating map handler for actor %d\n"
"tiles %s", actor->uid, tiles_copy);
#endif
return hp;
}
void jty_actor_add_m_handler(jty_actor *actor,
jty_c_handler handler,
char *tiles)
{
if (actor->collision_primed == 0) {
actor->map->collision_actors = jty_actor_ls_add(
actor->map->collision_actors,
actor);
}
actor->collision_primed += 1;
actor->m_h_ls = jty_actor_add_m_handler_int(
actor,
handler,
tiles);
return;
}
static jty_map_handle_ls *jty_actor_rm_m_handler_int(jty_map_handle_ls *ls,
jty_actor *actor,
jty_c_handler handler)
{
if(ls == NULL)
return NULL;
if(ls->handler == handler){
jty_map_handle_ls *p = ls->next;
free(ls->tiles);
free(ls);
return p;
}
ls->next = jty_actor_rm_m_handler_int(ls->next, actor, handler);
return ls;
}
void jty_actor_rm_m_handler(jty_actor *actor,
jty_c_handler handler)
{
if (actor->collision_primed == 0) {
return;
}
actor->collision_primed -= 1;
actor->m_h_ls =
jty_actor_rm_m_handler_int(actor->m_h_ls,
actor,
handler);
return;
}
jty_actor_handle_ls *jty_actor_add_a_handler_int(jty_actor *actor,
unsigned int order,
unsigned int groupnum,
jty_c_handler handler)
{
jty_actor_handle_ls *hp;
hp = malloc(sizeof(*hp));
if(hp==NULL){
fprintf(stderr, "Unable to allocate memory for an "
"actor handler list node.\n");
exit(1);
}
hp->groupnum = groupnum;
hp->order = order;
hp->handler = handler;
hp->next = actor->a_h_ls;
return hp;
}
void jty_actor_add_a_handler(jty_actor *actor,
unsigned int groupnum1,
unsigned int groupnum2,
jty_c_handler handler)
{
if(actor->groupnum & groupnum1) {
if(actor->groupnum & groupnum2) {
groupnum2 |= groupnum1;
}
if (actor->collision_primed == 0) {
actor->map->collision_actors = jty_actor_ls_add(
actor->map->collision_actors,
actor);
}
actor->collision_primed += 1;
actor->a_h_ls =
jty_actor_add_a_handler_int(actor, 1, groupnum2, handler);
}else if(actor->groupnum & groupnum2) {
if (actor->collision_primed == 0) {
actor->map->collision_actors = jty_actor_ls_add(
actor->map->collision_actors,
actor);
}
actor->collision_primed += 1;
actor->a_h_ls =
jty_actor_add_a_handler_int(actor, 2, groupnum1, handler);
}
}
static void jty_map_add_a_a_handler_int(
jty_map *map,
unsigned int groupnum1,
unsigned int groupnum2,
jty_c_handler handler)
{
jty_actor_ls *p_actor_ls;
jty_actor *actor;
for(p_actor_ls = map->actors; p_actor_ls != NULL; p_actor_ls = p_actor_ls->next) {
actor = p_actor_ls->actor;
jty_actor_add_a_handler(actor,
groupnum1,
groupnum2,
handler);
}
}
static jty_a_a_handle_ls *jty_a_a_handle_ls_add(
jty_a_a_handle_ls *ls,
unsigned int groupnum1,
unsigned int groupnum2,
jty_c_handler handler)
{
jty_a_a_handle_ls *hp;
hp = malloc(sizeof(*hp));
if(hp==NULL){
fprintf(stderr, "Unable to allocate memory for an "
"actor-actor handler list node.\n");
exit(1);
}
hp->groupnum1 = groupnum1;
hp->groupnum2 = groupnum2;
hp->handler = handler;
hp->next = ls;
return hp;
}
void jty_map_add_a_a_handler(
jty_map *map,
unsigned int groupnum1,
unsigned int groupnum2,
jty_c_handler handler)
{
map->a_a_handlers = jty_a_a_handle_ls_add(
map->a_a_handlers,
groupnum1,
groupnum2,
handler);
jty_map_add_a_a_handler_int(map, groupnum1, groupnum2, handler);
}
void jty_paint(void)
{
/* Paint map */
jty_map_paint(jty_engine->map);
return;
}
int jty_actor_actor_c_detect(
jty_actor *a1,
jty_actor *a2,
double *t,
jty_c_info *c_info)
{
jty_vector v_rel = {
.x = (a1->x - a1->px) - (a2->x - a2->px),
.y = (a1->y - a1->py) - (a2->y - a2->py)};
jty_shape c_shape1 = jty_actor_get_c_shape(a1);
jty_shape c_shape2 = jty_actor_get_c_shape(a2);
if (c_shape1.type == JTY_RECT && c_shape2.type == JTY_RECT) {
return jty_rect_rect_detect(
&c_shape1,
&c_shape2,
v_rel,
R_R_DETECT_BOTH,
t,
c_info);
}
return 0;
}
void jty_map_find_most_ancient_tile_collision(
jty_map *map,
jty_actor *actor,
jty_c_handler *handler_max,
double *t_max,
jty_c_info *c_info_max)
{
/*
* Find which tiles are colliding with
* this actor's bounding box
*
*/
int i_min, i_max, j_min, j_max;
int i, j, k;
jty_map_handle_ls *mhl;
char tile_type;
unsigned char (*c_map)[map->w] =
(void *)map->c_map;
jty_sprite *curr_sprite = actor->sprites[actor->current_sprite];
double t;
jty_c_info c_info;
i_min = (actor->x - curr_sprite->w / 2.) / map->tw;
if (i_min <= 0)
i_min = 0;
i_max = (actor->x + curr_sprite->w / 2.) / map->tw;
if(i_max >= map->w)
i_max = map->w - 1;
j_min = (actor->y - curr_sprite->h / 2.) / map->th;
if (j_min <= 0)
j_min = 0;
j_max = (actor->y + curr_sprite->h / 2.) / map->th;
if(j_max >= map->h)
j_max = map->h -1;
#ifdef DEBUG_MODE
if (jty_engine->print_messages) {
fprintf(stderr, "Tiles between %d <= i <= %d"
" and %d <= j <= %d collided with by actor %d\n",
i_min, i_max, j_min, j_max, actor->uid);
}
#endif
/* Iterate through the map-handlers */
for(j = j_min; j <= j_max; j++)
for(i = i_min; i <= i_max; i++){
for(mhl = actor->m_h_ls; mhl != NULL; mhl = mhl->next) {
k = 0;
while((tile_type = mhl->tiles[k])) {
if(tile_type == c_map[j][i]) {
if(jty_actor_map_tile_c_detect(
actor,
i,
j,
R_R_DETECT_BOTH,
&t,
&c_info)) {
set_map_handler(
mhl,
actor,
i,
j,
tile_type,
handler_max,
t_max,
c_info_max,
&t,
&c_info);
}
break;
}
k++;
}
}
}
return;
}
int jty_actor_has_appropriate_handler(
jty_actor *a,
jty_actor *a2,
jty_c_handler *handler,
jty_c_info *c_info)
{
jty_actor_handle_ls *pahls;
/* Loop through first colliding actor's collision handlers
* to see if any of them apply to group of second actor
* in collision */
for(pahls = a->a_h_ls; pahls != NULL; pahls = pahls->next){
fprintf(stderr, "groupnum a1_h: %d\n", pahls->groupnum);
fprintf(stderr, "groupnum a2: %d\n", a2->groupnum);
if(pahls->groupnum & a2->groupnum) {
*handler = pahls->handler;
if (pahls->order == 1) {
c_info->e1.actor = a;
c_info->e2.actor = a2;
} else if (pahls->order == 2) {
c_info->e1.actor = a2;
c_info->e2.actor = a;
c_info->normal.x *= -1;
c_info->normal.y *= -1;
}
return 1;
}
}
return 0;
}
void jty_map_find_most_ancient_collision(
jty_map *map,
jty_c_handler *handler_max,
double *t_max,
jty_c_info *c_info_max)
{
jty_actor_ls *pg, *ph;
jty_actor *a1, *a2;
double t = 0;
jty_c_info c_info;
jty_c_handler handler;
for(pg = map->collision_actors; pg != NULL; pg = pg->next){
jty_map_find_most_ancient_tile_collision(
map,
pg->actor,
handler_max,
t_max,
c_info_max);
/* Check for collision with any other actor */
for(ph = pg->next; ph != NULL; ph = ph->next){
a1 = pg->actor;
a2 = ph->actor;
if(jty_actor_actor_c_detect(a1, a2, &t, &c_info)){
if (
t > *t_max &&
jty_actor_has_appropriate_handler(
a1,
a2,
&handler,
&c_info)
) {
*t_max = t;
*c_info_max = c_info;
*handler_max = handler;
}
}
}
}
}
void jty_map_process_collisions(jty_map *map)
{
jty_c_handler handler_max;
jty_c_info c_info_max;
double t_max;
int i;
for (i = 0; i <= MAX_C_PROCESSING_LOOPS; i++) {
t_max = -1;
jty_map_find_most_ancient_collision(
map,
&handler_max,
&t_max,
&c_info_max);
#ifdef DEBUG_MODE
if(t_max == -1){
if (i > 0) {
fprintf(stderr, "took %d collisions to get resolved\n", i);
}
return;
}
#endif
if (i == 0) {
fprintf(stderr, "starting to process collisions...\n");
}
fprintf(stderr, "cinfo for collision %d:", i);
print_c_info(&c_info_max);
handler_max(&c_info_max);
}
#ifdef DEBUG_MODE
fprintf(stderr, "collisions unresolved!!!\n");
#endif
return;
}
void jty_map_iterate(jty_map *map)
{
jty_actor_ls *pg;
/* Iterate each actor */
for(pg = map->actors; pg != NULL; pg = pg->next){
jty_actor_iterate(pg->actor);
}
jty_map_process_collisions(map);
}
void jty_iterate()
{
#ifdef DEBUG_MODE
static double last_t = 0;
double curr_t;
curr_t = SDL_GetTicks();
if( curr_t - last_t >= POLL_TIME * 1000){
jty_engine->print_messages = 1;
last_t = curr_t;
}else
jty_engine->print_messages = 0;
jty_map_iterate(jty_engine->map);
#endif
return;
}
jty_actor_ls *jty_actor_ls_rm(jty_actor_ls *ls, jty_actor *actor)
{
if (ls == NULL)
return NULL;
if (ls->actor == actor) {
jty_actor_ls *p;
p = ls->next;
//free(ls);
return p;
}
ls->next = jty_actor_ls_rm(ls->next, actor);
return ls;
}
jty_txt_actor *jty_txt_actor_init(
jty_txt_actor *actor,
unsigned int groupnum,
jty_map *map,
int w,
int h)
{
jty_actor_init(
(jty_actor *)actor,
groupnum,
map,
1,
w,
h,
NULL,
NULL );
actor->p2_surface = SDL_CreateRGBSurface(
SDL_SWSURFACE,
actor->parent.sprites[0]->p2w,
actor->parent.sprites[0]->p2h,
32,
RMASK,
GMASK,
BMASK,
AMASK);
if(!actor->p2_surface){
fprintf(stderr, "Error creating a surface for the sprite\n");
free_jty_actor((jty_actor *)actor);
return NULL;
}
if(SDL_MUSTLOCK(actor->p2_surface))
SDL_LockSurface(actor->p2_surface);
actor->cairo_surface = cairo_image_surface_create_for_data(
actor->p2_surface->pixels,
CAIRO_FORMAT_RGB24,
actor->p2_surface->w,
actor->p2_surface->h,
actor->p2_surface->pitch);
actor->cr = cairo_create(actor->cairo_surface);
actor->font_description = pango_font_description_new();
pango_font_description_set_family(actor->font_description, "serif");
pango_font_description_set_weight(actor->font_description,
PANGO_WEIGHT_BOLD);
pango_font_description_set_absolute_size(
actor->font_description,
20 * PANGO_SCALE);
actor->layout = pango_cairo_create_layout(actor->cr);
pango_layout_set_font_description(actor->layout, actor->font_description);
pango_layout_set_width(actor->layout, w * PANGO_SCALE);
pango_layout_set_height(actor->layout, h * PANGO_SCALE);
pango_layout_set_alignment(actor->layout, PANGO_ALIGN_CENTER);
if(SDL_MUSTLOCK(actor->p2_surface))
SDL_UnlockSurface(actor->p2_surface);
actor->text[0] = '\0';
glBindTexture(
GL_TEXTURE_2D,
actor->parent.sprites[0]->textures[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, actor->p2_surface->w,
actor->p2_surface->h,
0, GL_RGBA, GL_UNSIGNED_BYTE, actor->p2_surface->pixels);
return actor;
}
jty_txt_actor *new_jty_txt_actor(
unsigned int groupnum,
int w,
int h,
jty_map *map)
{
jty_txt_actor *actor = malloc(sizeof(*actor));
if (!actor) {
return NULL;
}
jty_txt_actor_init(
actor,
groupnum,
map,
w,
h);
return actor;
}
void jty_txt_actor_set_text(jty_txt_actor *actor, const char *text)
{
int offset_x, offset_y;
offset_x = (actor->parent.sprites[0]->p2w - actor->parent.sprites[0]->w)/2;
offset_y = (actor->parent.sprites[0]->p2h - actor->parent.sprites[0]->h)/2;
strncpy(actor->text, text, TEXTLENGTH - 1);
SDL_FillRect(actor->p2_surface, NULL, 0);
if(SDL_MUSTLOCK(actor->p2_surface))
SDL_LockSurface(actor->p2_surface);
pango_layout_set_markup(actor->layout, actor->text, -1);
cairo_move_to(actor->cr, offset_x,
offset_y);
pango_cairo_show_layout(actor->cr, actor->layout);
if(SDL_MUSTLOCK(actor->p2_surface))
SDL_UnlockSurface(actor->p2_surface);
glBindTexture(GL_TEXTURE_2D, actor->parent.sprites[0]->textures[0]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, actor->p2_surface->w,
actor->p2_surface->h,
0, GL_RGBA, GL_UNSIGNED_BYTE, actor->p2_surface->pixels);
return;
}
void free_jty_actor(jty_actor *actor)
{
actor->map->actors = jty_actor_ls_rm(actor->map->actors, actor);
if (actor->collision_primed) {
actor->map->collision_actors = jty_actor_ls_rm(
actor->map->collision_actors,
actor);
}
free(actor);
}
void jty_eng_free(void)
{
SDL_Quit();
/* Free map */
free_jty_map(jty_engine->map);
free(jty_engine);
return;
}
|
C
|
#define NULL (0)
typedef struct _Node {
int data;
struct _Node *next;
} Node;
void *malloc(int);
Node *new_node(int data) {
Node *p;
p = malloc(sizeof(Node));
p->data = data;
p->next = NULL;
return p;
}
void print_list(Node *p) {
printf(" %d ", p->data);
if (p->next == NULL)
printf("\n");
else {
printf("->");
print_list(p->next);
}
return;
}
int main(void) {
int i;
Node *list;
Node *p;
p = list = new_node(0);
for (i = 1; i <= 10; i++) {
p->next = new_node(i);
p = p->next;
}
print_list(list);
return 0;
}
|
C
|
#include <stdio.h>
int process(int (*pf)(int, int))
{
printf("process host\n");
int a = 1, b = 2, c = 3;
c = (*pf)(a, b);
printf("returned value of c = %d\n", c);
return(c);
}
int funct1(int a, int b)
{
int c = 0;
printf("guest function funct1\n value of c = %d\n", c);
printf("Value of a = %d\n Value of b = %d\n", a, b);
return(c);
}
int funct2(int x, int y)
{
int z = 49;
printf("guest funct2\n value of z = %d\n", z);
printf("Value of x = %d\n Value of y = %d\n", x, y);
return(z);
}
int main()
{
int i, j;
i = 5, j = 6;
printf("value of i = %d, value of j = %d\n", i, j);
i = process(funct1);
printf("After passing i, i = %d", i);
j = process(funct2);
printf("After calling, value of i = %d, value of j = %d\n", i, j);
return 0;
}
|
C
|
#include <stdlib.h>
typedef struct IntList{
int val;
struct IntList * next;
int refcount;
}IntList;
IntList * allocateIntList(IntList * p){
static IntList * pool=NULL;
if (!p){
if (!pool){
IntList * p=(IntList*)malloc(sizeof(IntList)*1000);
for (int i=0;i<1000;i++){
p[i].next=pool;
pool=p+i;
}
}
p=pool;
p->refcount=1;
pool=pool->next;
return p;
}else{
p->next=pool;
pool=p;
return NULL;
}
}
IntList * retainIntList(IntList * p){ // p: stolen returns: new
if (p){
p->refcount++;
}
return p;
}
IntList * releaseIntList(IntList * p){ // p: consumed returns: NULL
if (p){
p->refcount--;
if (p->refcount==0){
if (p->next){
releaseIntList(p);
}
allocateIntList(p);
}
}
return NULL;
}
IntList * newIntList(int val,IntList * nxt){ // nxt: consumed returns: new
IntList * p=allocateIntList(NULL);
p->val=val;
p->next=nxt;
return p;
}
char * convertIntListToString(IntList * list){ // l: stolen returns: new
int l=0;
for (IntList * p=list;p;p=p->next){
l++;
}
char * s=(char*)malloc(l+1);
int i=0;
for (IntList * p=list;p;p=p->next){
s[i]=p->val;
i++;
}
s[i]=0;
return s;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <assert.h>
int global_var = 1;
void* global_reciprocal (void* arg) {
if (global_var != 0)
{
// bide our time
for (int i = 0; i < 100; ++i)
{
int j = i * i;
}
// then return our reciprocal
global_var = 1/global_var;
}
}
void* to_zero (void* arg){
global_var = 0;
}
int main () {
pthread_t threads[2];
int i = 0;
pthread_create(threads+i, NULL, &global_reciprocal, NULL);
i += 1;
pthread_create(threads+i, NULL, &to_zero, NULL);
for(i = 0; i < 2; ++i){
pthread_join(threads[i], NULL);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "lists.h"
#include <string.h>
/**
* get_nodeint_at_index - returns the nth node of a listint_t list.
*@head: pointer to start of list.
*@index: index of the node starting at 0.
* Return: nth node.
*/
listint_t *get_nodeint_at_index(listint_t *head, unsigned int index)
{
unsigned int i = 0;
for (; head != NULL; i++)
{
if (i == index)
{
return (head);
}
else
{
head = head->next;
}
}
return (NULL);
}
|
C
|
/**
******************************************************************************
* @file lib_flash.c
* @author Application Team
* @version V4.3.0
* @date 2018-09-27
* @brief FLASH library.
******************************************************************************
* @attention
*
******************************************************************************
*/
#include "lib_flash.h"
#include "lib_clk.h"
/* FLASH Keys */
#define FLASH_PASS_KEY 0x55AAAA55
#define FLASH_SERASE_KEY 0xAA5555AA
#define FLASH_CERASE_KEY 0xAA5555AA
#define FLASH_DSTB_KEY 0xAA5555AA
#define FLASH_MODE_MASK 0x1F3
/**
* @brief FLASH mode initialization.
* @param CSMode:
FLASH_CSMODE_DISABLE
FLASH_CSMODE_ALWAYSON
FLASH_CSMODE_TIM2OF
FLASH_CSMODE_RTC
* @retval None
*/
void FLASH_Init(uint32_t CSMode)
{
uint32_t tmp;
/* Check parameters */
assert_parameters(IS_FLASH_CSMODE(CSMode));
tmp = FLASH->CTRL;
tmp &= ~FLASH_MODE_MASK;
tmp |= CSMode;
FLASH->CTRL = tmp;
}
/**
* @brief Configure FLASH interrupt.
* @param IntMask:
FLASH_INT_CS
NewState:
ENABLE
DISABLE
* @retval None
*/
void FLASH_INTConfig(uint32_t IntMask, uint32_t NewState)
{
uint32_t tmp;
/* Check parameters */
assert_parameters(IS_FLASH_INT(IntMask));
assert_parameters(IS_FUNCTIONAL_STATE(NewState));
tmp = FLASH->CTRL;
tmp &= ~IntMask;
if (NewState == ENABLE)
{
tmp |= IntMask;
}
FLASH->CTRL = tmp;
}
/**
* @brief Init FLASH 1USCYCLE.
* @param None
* @retval None
*/
void FLASH_CycleInit(void)
{
uint32_t hclk;
hclk = CLK_GetHCLKFreq();
if (hclk > 1000000)
MISC2->FLASHWC = (hclk/1000000)<<8;
else
MISC2->FLASHWC = 0;
}
/**
* @brief Erase FLASH sector.
* @param SectorAddr: sector address.
* @retval None
*/
void FLASH_SectorErase(uint32_t SectorAddr)
{
/* Check parameters */
assert_parameters(IS_FLASH_ADDRESS(SectorAddr));
/* Unlock flash */
FLASH->PASS = FLASH_PASS_KEY;
FLASH->PGADDR = SectorAddr;
FLASH->SERASE = FLASH_SERASE_KEY;
while (FLASH->SERASE != 0);
/* Lock flash */
FLASH->PASS = 0;
}
/**
* @brief FLASH word program.
* @param Addr: program start address
WordBuffer: word's buffer pointer to write
Length: The length of WordBuffer
* @retval None
*/
void FLASH_ProgramWord(uint32_t Addr, uint32_t *WordBuffer, uint32_t Length)
{
uint32_t i;
/* Check parameters */
assert_parameters(IS_FLASH_ADRRW(Addr));
/* Unlock flash */
FLASH->PASS = FLASH_PASS_KEY;
FLASH->PGADDR = Addr;
for (i=0; i<Length; i++)
{
FLASH->PGDATA = *(WordBuffer++);
}
while (FLASH->STS != 1);
/* Lock flash */
FLASH->PASS = 0;
}
/**
* @brief FLASH half-word progarm.
* @param Addr: program start address
HWordBuffer: half-word's buffer pointer to write
Length: The length of HWordBuffer
* @retval None
*/
void FLASH_ProgramHWord(uint32_t Addr, uint16_t *HWordBuffer, uint32_t Length)
{
uint32_t i;
/* Check parameters */
assert_parameters(IS_FLASH_ADRRHW(Addr));
/* Unlock flash */
FLASH->PASS = FLASH_PASS_KEY;
FLASH->PGADDR = Addr;
for (i=0; i<Length; i++)
{
if (((Addr + 2*i)&0x3) == 0)
*((__IO uint16_t*)(&FLASH->PGDATA)) = *(HWordBuffer++);
else
*((__IO uint16_t*)(&FLASH->PGDATA ) + 1) = *(HWordBuffer++);
}
while (FLASH->STS != 1);
/* Lock flash */
FLASH->PASS = 0;
}
/**
* @brief FLASH byte progarm.
* @param Addr: program start address
ByteBuffer: byte's buffer pointer to write
Length: The length of ByteBuffer
* @retval None
*/
void FLASH_ProgramByte(uint32_t Addr, uint8_t *ByteBuffer, uint32_t Length)
{
uint32_t i;
/* Check parameters */
assert_parameters(IS_FLASH_ADDRESS(Addr));
/* Unlock flash */
FLASH->PASS = FLASH_PASS_KEY;
FLASH->PGADDR = Addr;
for (i=0; i<Length; i++)
{
if (((Addr + i)&0x3) == 0)
*((__IO uint8_t*)(&FLASH->PGDATA)) = *(ByteBuffer++);
else if (((Addr + i)&0x3) == 1)
*((__IO uint8_t*)(&FLASH->PGDATA) + 1) = *(ByteBuffer++);
else if (((Addr + i)&0x3) == 2)
*((__IO uint8_t*)(&FLASH->PGDATA) + 2) = *(ByteBuffer++);
else
*((__IO uint8_t*)(&FLASH->PGDATA) + 3) = *(ByteBuffer++);
}
while (FLASH->STS != 1);
/* Lock flash */
FLASH->PASS = 0;
}
/**
* @brief Get Write status.
* @param None.
* @retval FLASH_WSTA_BUSY
FLASH_WSTA_FINISH
*/
uint32_t FLASH_GetWriteStatus(void)
{
if (FLASH->STS == 1)
{
return FLASH_WSTA_FINISH;
}
else
{
return FLASH_WSTA_BUSY;
}
}
/**
* @brief Set checksum range.
* @param AddrStart: checksum start address
AddrEnd: checksum end address
* @retval None
*/
void FLASH_SetCheckSumRange(uint32_t AddrStart, uint32_t AddrEnd)
{
/* Check parameters */
assert_parameters(IS_FLASH_CHECKSUMADDR(AddrStart,AddrEnd));
FLASH->CSSADDR = AddrStart;
FLASH->CSEADDR = AddrEnd;
}
/**
* @brief Set checksum compare value.
* @param Checksum: checksum compare value
* @retval None
*/
void FLASH_SetCheckSumCompValue(uint32_t Checksum)
{
FLASH->CSCVALUE = Checksum;
}
/**
* @brief Get FLASH checksum value.
* @param None
* @retval Checksum
*/
uint32_t FLASH_GetCheckSum(void)
{
return FLASH->CSVALUE;
}
/**
* @brief Get FLASH interrupt status.
* @param IntMask:
FLASH_INT_CS
* @retval 1: interrupt status set
0: interrupt status reset
*/
uint8_t FLASH_GetINTStatus(uint32_t IntMask)
{
/* Check parameters */
assert_parameters(IS_FLASH_INT(IntMask));
if (FLASH->INT&FLASH_INT_CSERR)
{
return 1;
}
else
{
return 0;
}
}
/**
* @brief Clear FLASH interrupt status.
* @param IntMask:
FLASH_INT_CS
* @retval None
*/
void FLASH_ClearINTStatus(uint32_t IntMask)
{
/* Check parameters */
assert_parameters(IS_FLASH_INT(IntMask));
if (IntMask == FLASH_INT_CS)
{
FLASH->INT = FLASH_INT_CSERR;
}
}
/*********************************** END OF FILE ******************************/
|
C
|
/**********************************************
* Malloc Lab
* Name : Li Pei
* Andrew ID : lip
**********************************************/
/**********************************************
* Implemented Dynamic Memory Allocator Function:
* malloc(size): Get size, add header,footer with
size to get asize (aligned size), search for free
block according to the azise and alignment in
free block lists.
* free(*bp): Get a block reference pointer and free
this block.
* mm_realloc(oldptr, newsize): Get the old pointer
and new allocating size of a block. If the new size
is smaller than the old, we have to truncate old.
If old size is the same as new, we return the old
pointer. If the old size is smaller than the new,
call a new malloc, copy old block in and free the
old block.
* calloc(size): Call malloc() and initial every byte
to 0
**********************************************/
/**********************************************
* Method Specifics:
* Segregated List.
* Mixed first-fit and best-fit.
**********************************************/
/**********************************************
* Block Style:
* Free Block
| Header | Prev Pointer | Next Pointer | Footer |
4Bytes 8Bytes 8Bytes 4Bytes
* Allocated Block
| Header | Contents | Footer |
4Bytes 4Bytes
* Heap Head
| Padding | Prelogue | Epilogue|
4Bytes TBD 4bytes
* Prelogue
|Header| List Reference |Footer|
4Bytes 8*(Number Of Freelist) 4Bytes
**********************************************/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "mm.h"
#include "memlib.h"
/* If you want debugging output, use the following macro.
When you hand in, remove the #define DEBUG line. */
#ifdef DEBUG
# define dbg_printf(...) printf(__VA_ARGS__)
# define dbg_mm_checkheap(...) mm_checkheap(__VA_ARGS__)
#else
# define dbg_printf(...)
# define dbg_mm_checkheap(...)
#endif
/* do not change the following! */
#ifdef DRIVER
/* create aliases for driver tests */
#define malloc mm_malloc
#define free mm_free
#define realloc mm_realloc
#define calloc mm_calloc
#endif /* def DRIVER */
/* single word (4) or double word (8) alignment */
#define ALIGNMENT 8
/* rounds up to the nearest multiple of ALIGNMENT */
#define ALIGN(p) (((size_t)(p) + (ALIGNMENT-1)) & ~0x7)
/* Basic constants and macros */
#define WSIZE 4 // word size (bytes)
#define DSIZE 8 // doubleword size (bytes)
#define CHUNKSIZE 1 << 8 // initial heap size (bytes)
#define MINIMUM 24 // minimum block size
#define MAX(x, y) ((x) > (y) ? (x) : (y))
/* Pack a size and allocated bit into a word */
#define PACK(size, alloc) ((size) | (alloc))
/* Read and write a word at address p */
#define GET(p) (*(int *)(p))
#define PUT(p, val) (*(int *)(p) = (val))
/* Read the size and allocated fields from address p */
#define GET_SIZE(p) (GET(p) & ~0x7)
#define GET_ALLOC(p) (GET(p) & 0x1)
/* Given block ptr bp, compute address of its header and footer */
#define HDRP(bp) ((void *)(bp) - WSIZE)
#define FTRP(bp) ((void *)(bp) + GET_SIZE(HDRP(bp)) - DSIZE)
/* Given block ptr bp, compute address of next and previous blocks */
#define NEXT_BLKP(bp) ((void *)(bp) + GET_SIZE(HDRP(bp)))
#define PREV_BLKP(bp) ((void *)(bp) - GET_SIZE(HDRP(bp) - WSIZE))
/* Given block ptr bp, compute address of next and previous free blocks */
#define NEXT_FREEP(bp)(*(void **)(bp + DSIZE))
#define PREV_FREEP(bp)(*(void **)(bp))
/* Internal helper routines */
static void *extendHeap(size_t words); //Extends heap
static void place(void *bp, size_t asize); //place required block
static void *findFit(size_t asize); //Find the fit free block
static void *coalesce(void *bp); //Coalesce free block
static int get_seglist_no(size_t asize); //Get the list header offset
static void insertAtFront(void *bp); //Insert free block
//into free list
static void removeBlock(void *bp); //Remove Block
//from free list
/* Implement Parameter*/
static char *heap_listp = 0; //Pointer to the heap
#define NUM_OF_LIST 7 //Free List Number
#define FIRST_BEST_INDEX 5 //Decide use first or
//Best fit
/* Structure Check*/
static void printBlock(void *bp); //Print out block
static void checkBlock(void *bp); //Check block legal
/******************************************************************
* mm_malloc - Allocate a block with at least size bytes of payload
* Alignment is considered in this part. We have to reserve position
for header and footer, and previous and next pointer needed if it
is free, so the minimum size is 24 bytes (4 bytes header, 4 bytes
footer, 8 bytes previous 8 bytes next pointer) per block.
* If no space was found, we must ask for more memory and place it
at the head of new heap
*****************************************************************/
void *mm_malloc(size_t size)
{
size_t asize; // aligned block size
size_t extendsize; // amount to extend heap if no fit
char *bp;
// Ignore meaningless requests
if (size <= 0)
{
return NULL;
}
// Get assignment
asize = MAX(ALIGN(size) + DSIZE, MINIMUM);
// Search the free list for a fit
if ((bp = findFit(asize)))
{
place(bp, asize);
return bp;
}
// No fit found. Get more memory and place the block
extendsize = MAX(asize, CHUNKSIZE);
//return NULL if unable to get heap space
if ((bp = extendHeap(extendsize/WSIZE)) == NULL)
{
return NULL;
}
place(bp, asize);
return bp;
}
/******************************************************************
* End of mm_malloc
*****************************************************************/
/******************************************************************
* mm_free - Free a block
Adds a block to the free list. Using block pointer, set the
allocation bits to 0 in header and footer of the block.
Then, coalesce with adjacent blocks, if applicable.
This function takes a block pointer as a parameter.
*****************************************************************/
void mm_free(void *bp)
{
if(!bp)
{
return; //return if the pointer is NULL
}
size_t size = GET_SIZE(HDRP(bp));
//set header and footer to unallocated
PUT(HDRP(bp), PACK(size, 0));
PUT(FTRP(bp), PACK(size, 0));
coalesce(bp); //coalesce and add the block to the free list
}
/******************************************************************
* End of mm_free
*****************************************************************/
/******************************************************************
* mm_realloc - Reallocate a block
* This function extends or shrinks an allocated block.
* If the new size is <= 0, then just free the block.
* If the new size is the same as the old size,just return the
old pointer.
* If the new size is less than the old size, shrink the block
and copy the front part fit in it.
* If the new size is greater than the old size, call malloc
using the new size, copy all of the old data, then call free
to the original block.
*****************************************************************/
void *mm_realloc(void *ptr, size_t size)
{
size_t oldsize;
void *newptr;
size_t asize = MAX(ALIGN(size) + DSIZE, MINIMUM);
// If size <= 0 then this is just free, and we return NULL.
if(size <= 0)
{
free(ptr);
return 0;
}
// If oldptr is NULL, then this is just malloc.
if(ptr == NULL)
{
return malloc(size);
}
// Get the size of the original block.
oldsize = GET_SIZE(HDRP(ptr));
// If the size doesn't need to be changed, return orig pointer
if (asize == oldsize)
{
return ptr;
}
// If the size needs to be decreased, shrink the block and
// return the same pointer
newptr = malloc(size);
// If realloc() fails the original block is left untouched
if(!newptr) {
return 0;
}
// Copy the old data.
if(size < oldsize)
{
oldsize = size;
}
memcpy(newptr, ptr, oldsize);
// Free the old block.
free(ptr);
return newptr;
}
/******************************************************************
* End of mm_realloc
*****************************************************************/
/******************************************************************
* calloc - Allocate the block and set it to zero.
* call malloc and get every byte 0
*****************************************************************/
void *calloc (size_t nmemb, size_t size)
{
size_t bytes = nmemb * size;
void *newptr;
newptr = malloc(bytes);
memset(newptr, 0, bytes);//set all to 0
return newptr;
}
/******************************************************************
* End of mm_calloc
*****************************************************************/
//Below Are Helper Routines
/******************************************************************
* mm_init - Initialize the memory manager
* The initial heap looks like this:
| Padding | Prelogue | Epilogue|
4Bytes TBD 4bytes
* Prelogue
|Header| List Reference |Footer|
4Bytes 8*(Number Of Freelist) 4Bytes
* List Reference save the value of pointer, pointing to the
* first available free block in each list
*
*****************************************************************/
int mm_init(void)
{
int INITIAL_SIZE = DSIZE * (NUM_OF_LIST + 2);
// return -1 if unable to get heap space
if ((heap_listp = mem_sbrk(2*INITIAL_SIZE)) == NULL)
return -1;
PUT(heap_listp, 0); //Alignment padding
// Initialize header of prelogue
PUT(heap_listp + WSIZE, PACK(INITIAL_SIZE - DSIZE, 1)); //WSIZE = padding
//Initialize footer of prelogue
PUT(heap_listp + INITIAL_SIZE - DSIZE, PACK(INITIAL_SIZE - DSIZE, 1));
//Initialize epilogue
PUT(heap_listp + INITIAL_SIZE - WSIZE, PACK(0, 1));
//Initialize the free list pointer for all free lists
for (int i = 1; i <= NUM_OF_LIST; i++) {
PREV_FREEP(heap_listp + i * DSIZE) = NULL;
}
//return -1 if unable to get first
if (extendHeap(CHUNKSIZE/WSIZE) == NULL)
{
return -1;
}
return 0;
}
/******************************************************************
* End of mm_init
*****************************************************************/
/******************************************************************
* extendHeap - Extend heap with free block and return its block pointer
* This function maintains alignment by only allocating an even number.
* We overwrite the epilogue of the previously heap, and put new epilogue
at the end of the newly added heap.
*****************************************************************/
static void *extendHeap(size_t words)
{
char *bp;
size_t size;
// Allocate an even number of words to maintain alignment
size = (words % 2) ? (words+1) * WSIZE : words * WSIZE;
if (size < MINIMUM)
{
size = MINIMUM;
}
// Fail to get new heap space, return NULL
if ((long)(bp = mem_sbrk(size)) == -1)
{
return NULL;
}
// Initialize free block header/footer and the epilogue header
PUT(HDRP(bp), PACK(size, 0)); // free block header
PUT(FTRP(bp), PACK(size, 0)); // free block footer
PUT(HDRP(NEXT_BLKP(bp)), PACK(0, 1)); // new epilogue
//coalesce with other block if possible
return coalesce(bp);
}
/******************************************************************
* End of extendHeap
*****************************************************************/
/******************************************************************
* place - Place block of asize bytes at start of free block bp
* This function places the block by comparing asize with the total
block size, csize.
* If the difference is at least the minimum block
size, we can split the block into an allocated block and a free block.
* If not, we declare the whole block as allocated to avoid excessive
external fragmentation.
* This function takes a block pointer to a free block and the
size of the block we wish to place there.
******************************************************************/
static void place(void *bp, size_t asize)
{
// Gets the size of the whole free block
size_t csize = GET_SIZE(HDRP(bp));
// If csize - asize >= MINIMUM:
// (1) Changing the header and footer info for the free
// block created from the remaining space
// (size = csize-asize, allocated = 0)
// (2) Coalescing the new free block with adjacent free blocks
if ((csize - asize) >= MINIMUM)
{
PUT(HDRP(bp), PACK(asize, 1));
PUT(FTRP(bp), PACK(asize, 1));
removeBlock(bp);
bp = NEXT_BLKP(bp);
PUT(HDRP(bp), PACK(csize-asize, 0));
PUT(FTRP(bp), PACK(csize-asize, 0));
coalesce(bp);
}
// Else:place in the whole block
else
{
PUT(HDRP(bp), PACK(csize, 1));
PUT(FTRP(bp), PACK(csize, 1));
removeBlock(bp);
}
}
/******************************************************************
* End of place
*****************************************************************/
/******************************************************************
* coalesce - boundary tag coalescing.
* If no adjacent free block, just put free block into free block list
* If have adjacent free block, coalesce and then put the new free
block into free list.
*****************************************************************/
static void *coalesce(void *bp)
{
size_t prev_alloc;
prev_alloc = GET_ALLOC(FTRP(PREV_BLKP(bp))) || PREV_BLKP(bp) == bp;
size_t next_alloc = GET_ALLOC(HDRP(NEXT_BLKP(bp)));
size_t size = GET_SIZE(HDRP(bp));
// Case 1, no extension, just put block in list and return
// Case 2, extend the block to right */
if (prev_alloc && !next_alloc)
{
size += GET_SIZE(HDRP(NEXT_BLKP(bp)));
//remove right adjacent block from free list
removeBlock(NEXT_BLKP(bp));
PUT(HDRP(bp), PACK(size, 0));
PUT(FTRP(bp), PACK(size, 0));
}
/* Case 3, extend the block to left */
else if (!prev_alloc && next_alloc)
{
size += GET_SIZE(HDRP(PREV_BLKP(bp)));
bp = PREV_BLKP(bp);
//remove left adjacent block from free list
removeBlock(bp);
PUT(HDRP(bp), PACK(size, 0));
PUT(FTRP(bp), PACK(size, 0));
}
/* Case 4, extend the block in both directions */
else if (!prev_alloc && !next_alloc)
{
size += GET_SIZE(HDRP(PREV_BLKP(bp))) +
GET_SIZE(HDRP(NEXT_BLKP(bp)));
removeBlock(PREV_BLKP(bp));
removeBlock(NEXT_BLKP(bp));
bp = PREV_BLKP(bp);
PUT(HDRP(bp), PACK(size, 0));
PUT(FTRP(bp), PACK(size, 0));
}
insertAtFront(bp);
return bp;
}
/******************************************************************
* End of coalesce
*****************************************************************/
// End of helper Routines
// Key Operations for Dynamic Memory Allocator
/******************************************************************
* get_seglist_no - get free list Number
* Determines to which free list a block is added
return the offset against the head of heap
*****************************************************************/
static int get_seglist_no(size_t asize){
if (asize <= 24)
return 1;
else if (asize <= 192)
return 2;
else if (asize <= 480)
return 3;
else if (asize <= 3840)
return 4;
else if (asize <= 7680)
return 5;
else if (asize <= 30720)
return 6;
else
return 7;
}
/******************************************************************
* End of get_seglist_no
*****************************************************************/
/******************************************************************
* findFit - Find a fit for a block with asize bytes
* This function iterates through all free lists
* uses first fits for small blocks and best fit for large blocks
* With the help of insertAtFront function, the selection between
first fit and best fit is automatically because insertAtFront
implement different add free block strategy for different block
size
******************************************************************/
static void *findFit(size_t asize)
{
void *head;
int offset;
// get offset according to size
offset = get_seglist_no(asize);
// Search through all the lists
for (int i = offset; i <= NUM_OF_LIST; i++)
{
head = PREV_FREEP(heap_listp + i * DSIZE);
// Search through all the blocks in list
while (head != NULL) {
if ((asize <= (size_t)GET_SIZE(HDRP(head))))
{
return head;
}
head = PREV_FREEP(head);
}
}
return NULL; // No fit, return null
}
/******************************************************************
* End of get_seglist_no
*****************************************************************/
/******************************************************************
* insertAtFront - Inserts a block into free list
* search according to the range of block asize
* for small block, just insert at the front
* for large block, insert according to asize
in ascending order
*****************************************************************/
static void insertAtFront(void *bp)
{
if (bp == NULL) {
return;
}
// get the according offset
int offset = get_seglist_no(GET_SIZE(HDRP(bp)));
void *free_list = heap_listp + offset * DSIZE;
// get the head of according list
void *head = PREV_FREEP(free_list);
// if asize is large, put in according to asize
// in ascending order
if (offset > FIRST_BEST_INDEX)
{
// if list is empty, put it as head
if (head == NULL)
{
PREV_FREEP(free_list) = bp;
NEXT_FREEP(bp) = free_list;
PREV_FREEP(bp) = NULL;
return;
}
// put it according to asize in ascending order
while (PREV_FREEP(head) != NULL)
{
if (GET_SIZE(HDRP(head)) > GET_SIZE(HDRP(bp)))
{
PREV_FREEP(NEXT_FREEP(head)) = bp;
NEXT_FREEP(bp) = NEXT_FREEP(head);
PREV_FREEP(bp) = head;
NEXT_FREEP(head) = bp;
return;
}
head = PREV_FREEP(head);
}
// if it is the largest in list
// put it as the tail of list
PREV_FREEP(head) = bp;
NEXT_FREEP(bp) = head;
PREV_FREEP(bp) = NULL;
return;
}
else // if it is small, put it in front
{
// if list is empty, put it as head
if (head == NULL)
{
PREV_FREEP(free_list) = bp;
NEXT_FREEP(bp) = free_list;
PREV_FREEP(bp) = NULL;
return;
}
// put it in the front
else
{
PREV_FREEP(free_list) = bp;
NEXT_FREEP(bp) = free_list;
PREV_FREEP(bp) = head;
NEXT_FREEP(head) = bp;
return;
}
}
}
/*****************************************************************
* End of insertAtFront
*****************************************************************/
/*****************************************************************
* removeBlock - remove free block from free list
*****************************************************************/
static void removeBlock(void *bp)
{
if (bp == NULL)
{
return;
}
// if it is not the tail of free list
if (PREV_FREEP(bp))
{
PREV_FREEP(NEXT_FREEP(bp)) = PREV_FREEP(bp);
NEXT_FREEP(PREV_FREEP(bp)) = NEXT_FREEP(bp);
}
// if it is the tail of free list
else
{
PREV_FREEP(NEXT_FREEP(bp)) = NULL;
NEXT_FREEP(bp) = NULL;
}
}
/*****************************************************************
* End of removeBlock
*****************************************************************/
// End Of Key Operations
// check functions
/******************************************************************
* mm_checkheap - Check the heap for consistency
* Checks the epilogue and prologue blocks for size and allocation bit.
* Checks the 8-byte address alignment for each block in the free list.
* Checks each free block to see if its next and previous pointers are
within heap bounds.
* Checks the consistency of header and footer size and allocation bits
for each free block.
*****************************************************************/
void mm_checkheap(int verbose)
{
void *bp = heap_listp + DSIZE; //Points to the first block in the heap
if (verbose)
{
printf("Heap (%p):\n", bp);
}
// If first block's header's size or allocation bit is wrong,
// the prologue header is wrong
if ((GET_SIZE(HDRP(bp)) != (NUM_OF_LIST + 1) * DSIZE)
|| !GET_ALLOC(HDRP(bp))){
printf("Bad prologue header\n");
}
// check the consistency of prelogue
checkBlock(heap_listp + DSIZE);
//Points to the epilogue and check the epilogue
void *ep = heap_listp + DSIZE * (NUM_OF_LIST + 2) - WSIZE;
// Print the stats of the last block in the heap
if (verbose){
printBlock(ep);
}
// If last block's header's size or allocation bit is wrong,
// the epilogue's header is wrong
if ((GET_SIZE(HDRP(ep)) != 0) || !(GET_ALLOC(HDRP(ep))))
{
printf("Bad epilogue header\n");
}
// Print the stats of every free block in the free list
for (int i = 1; i <= NUM_OF_LIST; i++) {
for (bp = PREV_FREEP(heap_listp + i * DSIZE);
bp != NULL; bp = PREV_FREEP(bp))
{
if (verbose)
{
printBlock(bp);
}
checkBlock(bp);
}
}
// Check Every Block In The Heap
bp = heap_listp + DSIZE;
while (GET_SIZE(HDRP(bp)) != 0) {
checkBlock(bp);
bp = NEXT_BLKP(bp);
}
}
/******************************************************************
* End of mm_checkheap
*****************************************************************/
/*****************************************************************
* printBlock - Prints the details of a block
* This function displays previous and next pointers if the block
is marked as free.
* This function takes a block pointer (to a block for examination)
as a parameter.
*****************************************************************/
static void printBlock(void *bp)
{
int hsize, halloc, fsize, falloc;
// Basic header and footer information
hsize = GET_SIZE(HDRP(bp));
halloc = GET_ALLOC(HDRP(bp));
fsize = GET_SIZE(FTRP(bp));
falloc = GET_ALLOC(FTRP(bp));
if (hsize == 0)
{
printf("%p: EOL\n", bp);
return;
}
// Prints out header and footer info if it's an allocated block.
// Prints out header and footer info and next and prev info
// if it's a free block.
if (halloc)
{
printf("%p: header:[%d:%c] footer:[%d:%c]\n", bp,
hsize, (halloc ? 'a' : 'f'),
fsize, (falloc ? 'a' : 'f'));
}
else
{
printf("%p:header:[%d:%c] prev:%p next:%p footer:[%d:%c]\n",
bp, hsize, (halloc ? 'a' : 'f'), PREV_FREEP(bp),
NEXT_FREEP(bp), fsize, (falloc ? 'a' : 'f'));
}
}
/*****************************************************************
* End of printBlock
*****************************************************************/
/*****************************************************************
* checkBlock - Checks a block for consistency
* Checks prev and next pointers to see if they are within heap boundaries.
* Checks for 8-byte alignment.
* Checks header and footer for consistency.
******************************************************************/
static void checkBlock(void *bp)
{
// Reports if the next and prev pointers are beyond heap bounds
// Note!! if the free list head at prelogue are empty when it
// have no prev_node, it will print error too. THIS situation
// Can be ignored.
if (NEXT_FREEP(bp)< mem_heap_lo() || NEXT_FREEP(bp) > mem_heap_hi())
{
printf("Error: next pointer %p is not within heap bounds \n"
, NEXT_FREEP(bp));
}
if (PREV_FREEP(bp)< mem_heap_lo() || PREV_FREEP(bp) > mem_heap_hi())
{
printf("Error: prev pointer %p is not within heap bounds \n"
, PREV_FREEP(bp));
}
// Reports if there isn't 8-byte alignment by checking if the block pointer
// is divisible by 8.
if ((size_t)bp % 8)
{
printf("Error: %p is not doubleword aligned\n", bp);
}
// Reports if the header information does not match the footer information
if (GET(HDRP(bp)) != GET(FTRP(bp)))
{
printf("Error: header does not match footer\n");
}
}
/*****************************************************************
* End of checkBlock
*****************************************************************/
// End of check functions
|
C
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See the LICENSE.txt file in the project root
// for the license information.
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <assert.h>
#include <stdbool.h>
#include "flex.h"
struct flex_item
{
#define FLEX_ATTRIBUTE(name, type, def) type name;
#include "flex.h"
float frame[4];
struct flex_item *parent;
struct
{
unsigned int cap;
unsigned int count;
struct flex_item **ary;
} children;
bool should_order_children;
};
typedef enum
{
#define FLEX_ATTRIBUTE(name, type, def) FLEX_PROPERTY_##name,
#include "flex.h"
} flex_property;
static void
update_should_order_children(struct flex_item *item)
{
if (item->order != 0 && item->parent != NULL)
{
item->parent->should_order_children = true;
}
}
static void
item_property_changed(struct flex_item *item, flex_property property)
{
if (property == FLEX_PROPERTY_order)
{
update_should_order_children(item);
}
}
#define FLEX_ATTRIBUTE(name, type, def) \
DLLEXPORT type flex_item_get_##name(struct flex_item *item) \
{ \
return item->name; \
} \
DLLEXPORT void flex_item_set_##name(struct flex_item *item, \
type value) \
{ \
item->name = value; \
item_property_changed(item, FLEX_PROPERTY_##name); \
}
#include "flex.h"
DLLEXPORT
struct flex_item *
flex_item_new(void)
{
struct flex_item *item =
(struct flex_item *)malloc(sizeof(struct flex_item));
assert(item != NULL);
#define FLEX_ATTRIBUTE(name, type, def) item->name = def;
#include "flex.h"
memset(item->frame, 0, sizeof item->frame);
item->parent = NULL;
item->children.cap = 0;
item->children.count = 0;
item->children.ary = NULL;
item->should_order_children = false;
return item;
}
DLLEXPORT
void flex_item_free(struct flex_item *item)
{
assert(item->parent == NULL);
if (item->children.cap > 0)
{
assert(item->children.ary != NULL);
for (unsigned int i = 0; i < item->children.count; i++)
{
struct flex_item *child = item->children.ary[i];
child->parent = NULL;
flex_item_free(child);
}
free(item->children.ary);
}
free(item);
}
static void
grow_if_needed(struct flex_item *item)
{
if (item->children.count == item->children.cap)
{
item->children.cap++;
assert(item->children.count < item->children.cap);
item->children.ary = (struct flex_item **)realloc(item->children.ary,
sizeof(struct flex_item *) * item->children.cap);
assert(item->children.ary != NULL);
}
}
static void
child_set(struct flex_item *item, struct flex_item *child, unsigned int index)
{
assert(child->parent == NULL && "child already has a parent");
item->children.ary[index] = child;
item->children.count++;
child->parent = item;
update_should_order_children(child);
}
DLLEXPORT
void flex_item_add(struct flex_item *item, struct flex_item *child)
{
grow_if_needed(item);
child_set(item, child, item->children.count);
}
DLLEXPORT
void flex_item_insert(struct flex_item *item, unsigned int index,
struct flex_item *child)
{
assert(index <= item->children.count);
grow_if_needed(item);
for (unsigned int i = item->children.count; i > index; i--)
{
item->children.ary[i] = item->children.ary[i - 1];
}
child_set(item, child, index);
}
DLLEXPORT
struct flex_item *
flex_item_delete(struct flex_item *item, unsigned int index)
{
assert(index < item->children.count);
assert(item->children.count > 0);
struct flex_item *child = item->children.ary[index];
for (unsigned int i = index; i < item->children.count - 1; i++)
{
item->children.ary[i] = item->children.ary[i + 1];
}
item->children.count--;
child->parent = NULL;
return child;
}
DLLEXPORT
unsigned int
flex_item_count(struct flex_item *item)
{
return item->children.count;
}
DLLEXPORT
struct flex_item *
flex_item_child(struct flex_item *item, unsigned int index)
{
assert(index < item->children.count);
return item->children.ary[index];
}
DLLEXPORT
struct flex_item *
flex_item_parent(struct flex_item *item)
{
return item->parent;
}
DLLEXPORT
struct flex_item *
flex_item_root(struct flex_item *item)
{
while (item->parent != NULL)
{
item = item->parent;
}
return item;
}
#define FRAME_GETTER(name, index) \
DLLEXPORT float flex_item_get_frame_##name(struct flex_item *item) \
{ \
return item->frame[index]; \
}
FRAME_GETTER(x, 0)
FRAME_GETTER(y, 1)
FRAME_GETTER(width, 2)
FRAME_GETTER(height, 3)
#undef FRAME_GETTER
struct flex_layout
{
// Set during init.
bool wrap;
bool reverse; // whether main axis is reversed
bool reverse2; // whether cross axis is reversed (wrap only)
bool vertical;
float size_dim; // main axis parent size
float align_dim; // cross axis parent size
unsigned int frame_pos_i; // main axis position
unsigned int frame_pos2_i; // cross axis position
unsigned int frame_size_i; // main axis size
unsigned int frame_size2_i; // cross axis size
unsigned int *ordered_indices;
// Set for each line layout.
float line_dim; // the cross axis size
float flex_dim; // the flexible part of the main axis size
float extra_flex_dim; // sizes of flexible items
float flex_grows;
float flex_shrinks;
float pos2; // cross axis position
// Calculated layout lines - only tracked when needed:
// - if the root's align_content property isn't set to FLEX_ALIGN_START
// - or if any child item doesn't have a cross-axis size set
bool need_lines;
struct flex_layout_line
{
unsigned int child_begin;
unsigned int child_end;
float size;
} * lines;
unsigned int lines_count;
float lines_sizes;
};
static void
layout_init(struct flex_item *item, float width, float height,
struct flex_layout *layout)
{
assert(item->padding_left >= 0);
assert(item->padding_right >= 0);
assert(item->padding_top >= 0);
assert(item->padding_bottom >= 0);
width -= item->padding_left + item->padding_right;
height -= item->padding_top + item->padding_bottom;
assert(width >= 0);
assert(height >= 0);
layout->reverse = false;
layout->vertical = true;
switch (item->direction)
{
case FLEX_DIRECTION_ROW_REVERSE:
layout->reverse = true;
case FLEX_DIRECTION_ROW:
layout->vertical = false;
layout->size_dim = width;
layout->align_dim = height;
layout->frame_pos_i = 0;
layout->frame_pos2_i = 1;
layout->frame_size_i = 2;
layout->frame_size2_i = 3;
break;
case FLEX_DIRECTION_COLUMN_REVERSE:
layout->reverse = true;
case FLEX_DIRECTION_COLUMN:
layout->size_dim = height;
layout->align_dim = width;
layout->frame_pos_i = 1;
layout->frame_pos2_i = 0;
layout->frame_size_i = 3;
layout->frame_size2_i = 2;
break;
default:
assert(false && "incorrect direction");
}
layout->ordered_indices = NULL;
if (item->should_order_children && item->children.count > 0)
{
unsigned int *indices = (unsigned int *)malloc(sizeof(unsigned int) * item->children.count);
assert(indices != NULL);
// Creating a list of item indices sorted using the children's `order'
// attribute values. We are using a simple insertion sort as we need
// stability (insertion order must be preserved) and cross-platform
// support. We should eventually switch to merge sort (or something
// else) if the number of items becomes significant enough.
for (unsigned int i = 0; i < item->children.count; i++)
{
indices[i] = i;
for (unsigned int j = i; j > 0; j--)
{
unsigned int prev = indices[j - 1];
unsigned int curr = indices[j];
if (item->children.ary[prev]->order <= item->children.ary[curr]->order)
{
break;
}
indices[j - 1] = curr;
indices[j] = prev;
}
}
layout->ordered_indices = indices;
}
layout->flex_dim = 0;
layout->flex_grows = 0;
layout->flex_shrinks = 0;
layout->reverse2 = false;
layout->wrap = item->wrap != FLEX_WRAP_NO_WRAP;
if (layout->wrap)
{
if (item->wrap == FLEX_WRAP_WRAP_REVERSE)
{
layout->reverse2 = true;
layout->pos2 = layout->align_dim;
}
}
else
{
layout->pos2 = layout->vertical
? item->padding_left
: item->padding_top;
}
layout->need_lines = layout->wrap && item->align_content != FLEX_ALIGN_START;
layout->lines = NULL;
layout->lines_count = 0;
layout->lines_sizes = 0;
}
static void
layout_cleanup(struct flex_layout *layout)
{
if (layout->ordered_indices != NULL)
{
free(layout->ordered_indices);
layout->ordered_indices = NULL;
}
if (layout->lines != NULL)
{
free(layout->lines);
layout->lines = NULL;
}
layout->lines_count = 0;
}
#define LAYOUT_RESET() \
do \
{ \
layout->line_dim = layout->wrap ? 0 : layout->align_dim; \
layout->flex_dim = layout->size_dim; \
layout->extra_flex_dim = 0; \
layout->flex_grows = 0; \
layout->flex_shrinks = 0; \
} while (0)
#define LAYOUT_CHILD_AT(item, i) \
(item->children.ary[(layout->ordered_indices != NULL \
? layout->ordered_indices[i] \
: i)])
#define _LAYOUT_FRAME(child, name) child->frame[layout->frame_##name##_i]
#define CHILD_POS(child) _LAYOUT_FRAME(child, pos)
#define CHILD_POS2(child) _LAYOUT_FRAME(child, pos2)
#define CHILD_SIZE(child) _LAYOUT_FRAME(child, size)
#define CHILD_SIZE2(child) _LAYOUT_FRAME(child, size2)
#define CHILD_MARGIN(child, if_vertical, if_horizontal) \
(layout->vertical \
? child->margin_##if_vertical \
: child->margin_##if_horizontal)
static void layout_item(struct flex_item *item, float width, float height);
static bool
layout_align(flex_align align, float flex_dim, unsigned int children_count,
float *pos_p, float *spacing_p, bool stretch_allowed)
{
assert(flex_dim > 0);
float pos = 0;
float spacing = 0;
switch (align)
{
case FLEX_ALIGN_START:
break;
case FLEX_ALIGN_END:
pos = flex_dim;
break;
case FLEX_ALIGN_CENTER:
pos = flex_dim / 2;
break;
case FLEX_ALIGN_SPACE_BETWEEN:
if (children_count > 0)
{
spacing = flex_dim / (children_count - 1);
}
break;
case FLEX_ALIGN_SPACE_AROUND:
if (children_count > 0)
{
spacing = flex_dim / children_count;
pos = spacing / 2;
}
break;
case FLEX_ALIGN_SPACE_EVENLY:
if (children_count > 0)
{
spacing = flex_dim / (children_count + 1);
pos = spacing;
}
break;
case FLEX_ALIGN_STRETCH:
if (stretch_allowed)
{
spacing = flex_dim / children_count;
break;
}
// fall through
default:
return false;
}
*pos_p = pos;
*spacing_p = spacing;
return true;
}
static flex_align
child_align(struct flex_item *child, struct flex_item *parent)
{
flex_align align = child->align_self;
if (align == FLEX_ALIGN_AUTO)
{
align = parent->align_items;
}
return align;
}
static void
layout_items(struct flex_item *item, unsigned int child_begin,
unsigned int child_end, unsigned int children_count,
struct flex_layout *layout)
{
assert(children_count <= (child_end - child_begin));
if (children_count <= 0)
{
return;
}
if (layout->flex_dim > 0 && layout->extra_flex_dim > 0)
{
// If the container has a positive flexible space, let's add to it
// the sizes of all flexible children.
layout->flex_dim += layout->extra_flex_dim;
}
// Determine the main axis initial position and optional spacing.
float pos = 0;
float spacing = 0;
if (layout->flex_grows == 0 && layout->flex_dim > 0)
{
assert(layout_align(item->justify_content, layout->flex_dim,
children_count, &pos, &spacing, false) &&
"incorrect justify_content");
if (layout->reverse)
{
pos = layout->size_dim - pos;
}
}
if (layout->reverse)
{
pos -= layout->vertical ? item->padding_bottom : item->padding_right;
}
else
{
pos += layout->vertical ? item->padding_top : item->padding_left;
}
if (layout->wrap && layout->reverse2)
{
layout->pos2 -= layout->line_dim;
}
for (unsigned int i = child_begin; i < child_end; i++)
{
struct flex_item *child = LAYOUT_CHILD_AT(item, i);
if (child->position == FLEX_POSITION_ABSOLUTE)
{
// Already positioned.
continue;
}
// Grow or shrink the main axis item size if needed.
float flex_size = 0;
if (layout->flex_dim > 0)
{
if (child->grow != 0)
{
CHILD_SIZE(child) = 0; // Ignore previous size when growing.
flex_size = (layout->flex_dim / layout->flex_grows) * child->grow;
}
}
else if (layout->flex_dim < 0)
{
if (child->shrink != 0)
{
flex_size = (layout->flex_dim / layout->flex_shrinks) * child->shrink;
}
}
CHILD_SIZE(child) += flex_size;
// Set the cross axis position (and stretch the cross axis size if
// needed).
float align_size = CHILD_SIZE2(child);
float align_pos = layout->pos2 + 0;
switch (child_align(child, item))
{
case FLEX_ALIGN_END:
align_pos += layout->line_dim - align_size - CHILD_MARGIN(child, right, bottom);
break;
case FLEX_ALIGN_CENTER:
align_pos += (layout->line_dim / 2) - (align_size / 2) + (CHILD_MARGIN(child, left, top) - CHILD_MARGIN(child, right, bottom));
break;
case FLEX_ALIGN_STRETCH:
if (align_size == 0)
{
CHILD_SIZE2(child) = layout->line_dim - (CHILD_MARGIN(child, left, top) + CHILD_MARGIN(child, right, bottom));
}
// fall through
case FLEX_ALIGN_START:
align_pos += CHILD_MARGIN(child, left, top);
break;
default:
assert(false && "incorrect align_self");
}
CHILD_POS2(child) = align_pos;
// Set the main axis position.
if (layout->reverse)
{
pos -= CHILD_MARGIN(child, bottom, right);
pos -= CHILD_SIZE(child);
CHILD_POS(child) = pos;
pos -= spacing;
pos -= CHILD_MARGIN(child, top, left);
}
else
{
pos += CHILD_MARGIN(child, top, left);
CHILD_POS(child) = pos;
pos += CHILD_SIZE(child);
pos += spacing;
pos += CHILD_MARGIN(child, bottom, right);
}
// Now that the item has a frame, we can layout its children.
layout_item(child, child->frame[2], child->frame[3]);
}
if (layout->wrap && !layout->reverse2)
{
layout->pos2 += layout->line_dim;
}
if (layout->need_lines)
{
layout->lines = (struct flex_layout_line *)realloc(layout->lines,
sizeof(struct flex_layout_line) * (layout->lines_count + 1));
assert(layout->lines != NULL);
struct flex_layout_line *line = &layout->lines[layout->lines_count];
line->child_begin = child_begin;
line->child_end = child_end;
line->size = layout->line_dim;
layout->lines_count++;
layout->lines_sizes += line->size;
}
}
static void
layout_item(struct flex_item *item, float width, float height)
{
if (item->children.count == 0)
{
return;
}
struct flex_layout layout_s = {0}, *layout = &layout_s;
layout_init(item, width, height, &layout_s);
LAYOUT_RESET();
unsigned int last_layout_child = 0;
unsigned int relative_children_count = 0;
for (unsigned int i = 0; i < item->children.count; i++)
{
struct flex_item *child = LAYOUT_CHILD_AT(item, i);
// Items with an absolute position have their frames determined
// directly and are skipped during layout.
if (child->position == FLEX_POSITION_ABSOLUTE)
{
#define ABSOLUTE_SIZE(val, pos1, pos2, dim) \
(!isnan(val) \
? val \
: (!isnan(pos1) && !isnan(pos2) \
? dim - pos2 - pos1 \
: 0))
#define ABSOLUTE_POS(pos1, pos2, size, dim) \
(!isnan(pos1) \
? pos1 \
: (!isnan(pos2) \
? dim - size - pos2 \
: 0))
float child_width = ABSOLUTE_SIZE(child->width, child->left,
child->right, width);
float child_height = ABSOLUTE_SIZE(child->height, child->top,
child->bottom, height);
float child_x = ABSOLUTE_POS(child->left, child->right,
child_width, width);
float child_y = ABSOLUTE_POS(child->top, child->bottom,
child_height, height);
child->frame[0] = child_x;
child->frame[1] = child_y;
child->frame[2] = child_width;
child->frame[3] = child_height;
// Now that the item has a frame, we can layout its children.
layout_item(child, child->frame[2], child->frame[3]);
#undef ABSOLUTE_POS
#undef ABSOLUTE_SIZE
continue;
}
// Initialize frame.
child->frame[0] = 0;
child->frame[1] = 0;
child->frame[2] = child->width;
child->frame[3] = child->height;
// Main axis size defaults to 0.
if (isnan(CHILD_SIZE(child)))
{
CHILD_SIZE(child) = 0;
}
// Cross axis size defaults to the parent's size (or line size in wrap
// mode, which is calculated later on).
if (isnan(CHILD_SIZE2(child)))
{
if (layout->wrap)
{
layout->need_lines = true;
}
else
{
CHILD_SIZE2(child) = (layout->vertical ? width : height) - CHILD_MARGIN(child, left, top) - CHILD_MARGIN(child, right, bottom);
}
}
// Call the self_sizing callback if provided. Only non-NAN values
// are taken into account. If the item's cross-axis align property
// is set to stretch, ignore the value returned by the callback.
if (child->self_sizing != NULL)
{
float size[2] = {child->frame[2], child->frame[3]};
child->self_sizing(child, size);
for (unsigned int j = 0; j < 2; j++)
{
unsigned int size_off = j + 2;
if (size_off == layout->frame_size2_i && child_align(child, item) == FLEX_ALIGN_STRETCH)
{
continue;
}
float val = size[j];
if (!isnan(val))
{
child->frame[size_off] = val;
}
}
}
// Honor the `basis' property which overrides the main-axis size.
if (!isnan(child->basis))
{
assert(child->basis >= 0);
CHILD_SIZE(child) = child->basis;
}
float child_size = CHILD_SIZE(child);
if (layout->wrap)
{
if (layout->flex_dim < child_size)
{
// Not enough space for this child on this line, layout the
// remaining items and move it to a new line.
layout_items(item, last_layout_child, i,
relative_children_count, layout);
LAYOUT_RESET();
last_layout_child = i;
relative_children_count = 0;
}
float child_size2 = CHILD_SIZE2(child);
if (!isnan(child_size2) && child_size2 > layout->line_dim)
{
layout->line_dim = child_size2;
}
}
assert(child->grow >= 0);
assert(child->shrink >= 0);
layout->flex_grows += child->grow;
layout->flex_shrinks += child->shrink;
layout->flex_dim -= child_size + (CHILD_MARGIN(child, top, left) + CHILD_MARGIN(child, bottom, right));
relative_children_count++;
if (child_size > 0 && child->grow > 0)
{
layout->extra_flex_dim += child_size;
}
}
// Layout remaining items in wrap mode, or everything otherwise.
layout_items(item, last_layout_child, item->children.count,
relative_children_count, layout);
// In wrap mode we may need to tweak the position of each line according to
// the align_content property as well as the cross-axis size of items that
// haven't been set yet.
if (layout->need_lines && layout->lines_count > 0)
{
float pos = 0;
float spacing = 0;
float flex_dim = layout->align_dim - layout->lines_sizes;
if (flex_dim > 0)
{
assert(layout_align(item->align_content, flex_dim,
layout->lines_count, &pos, &spacing, true) &&
"incorrect align_content");
}
float old_pos = 0;
if (layout->reverse2)
{
pos = layout->align_dim - pos;
old_pos = layout->align_dim;
}
for (unsigned int i = 0; i < layout->lines_count; i++)
{
struct flex_layout_line *line = &layout->lines[i];
if (layout->reverse2)
{
pos -= line->size;
pos -= spacing;
old_pos -= line->size;
}
// Re-position the children of this line, honoring any child
// alignment previously set within the line.
for (unsigned int j = line->child_begin; j < line->child_end;
j++)
{
struct flex_item *child = LAYOUT_CHILD_AT(item, j);
if (child->position == FLEX_POSITION_ABSOLUTE)
{
// Should not be re-positioned.
continue;
}
if (isnan(CHILD_SIZE2(child)))
{
// If the child's cross axis size hasn't been set it, it
// defaults to the line size.
CHILD_SIZE2(child) = line->size + (item->align_content == FLEX_ALIGN_STRETCH
? spacing
: 0);
}
CHILD_POS2(child) = pos + (CHILD_POS2(child) - old_pos);
}
if (!layout->reverse2)
{
pos += line->size;
pos += spacing;
old_pos += line->size;
}
}
}
layout_cleanup(layout);
}
#undef CHILD_MARGIN
#undef CHILD_POS
#undef CHILD_POS2
#undef CHILD_SIZE
#undef CHILD_SIZE2
#undef _LAYOUT_FRAME
#undef LAYOUT_CHILD_AT
#undef LAYOUT_RESET
DLLEXPORT
void flex_layout(struct flex_item *item)
{
assert(item->parent == NULL);
assert(!isnan(item->width));
assert(!isnan(item->height));
assert(item->self_sizing == NULL);
layout_item(item, item->width, item->height);
}
|
C
|
/***********************************************************************************
*
* Author: Eric Burgos
* Creation Date: October 21, 2016
* Modified Date: October 24, 2016
* Filename: tcpcli.c
* Purpose: Client example for TCP Sockets; sends one string at a time
* Adapted from Haviland book
*
**********************************************************************************/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <time.h>
#include <sys/resource.h>
#include <sys/time.h>
#define SIZE sizeof(struct sockaddr_in)
#define IPADDR "127.0.0.1" // localhost
//#define IPADDR "156.12.127.18" // csit
//#define IPADDR "156.12.127.9" // harry
//#define IPADDR "156.12.127.10" // hermione
int main()
{
struct timeval start, end;
int sockfd;
int connectJawn;
char c, rc;
struct sockaddr_in server;
double elapsedTime;
server.sin_family = AF_INET;
server.sin_port = htons(15041);
// convert and store the server's IP address
server.sin_addr.s_addr = inet_addr(IPADDR);
// Gets time of day since epoch(Jan 1, 1970)
// Structured by tv_sec(seconds) and tc_usec(microseconds)
if(gettimeofday(&start, NULL) == -1)
{
perror("Error getting time");
exit(-1);
}
// set up the transport end point
sockfd = socket(AF_INET, SOCK_STREAM, 0);
//Gets time of day after system call bind()
if(gettimeofday(&end, NULL) == -1)
{
perror("Error getting time");
exit(-1);
}
// Calculations for finding difference between time
printf("Start/End for socket() system call:\n");
printf("Start- %ld.%06lds\n", start.tv_sec, start.tv_usec);
printf("End- %ld.%06lds\n", end.tv_sec, end.tv_usec);
// Output in microseconds
printf("Total- %.ldμs\n\n", (end.tv_usec - start.tv_usec)*1);
if (sockfd == -1)
{
perror("socket call failed");
exit(-1);
} // end if
// Gets time of day since epoch(Jan 1, 1970)
// Structured by tv_sec(seconds) and tc_usec(microseconds)
if(gettimeofday(&start, NULL) == -1)
{
perror("Error getting time");
exit(-1);
}
// connect the socket to the server's address
connectJawn = connect(sockfd, (struct sockaddr *)&server, SIZE);
//Gets time of day after system call bind()
if(gettimeofday(&end, NULL) == -1)
{
perror("Error getting time");
exit(-1);
}
// Calculations for finding difference between time
printf("Start/End for connect() system call:\n");
printf("Start- %ld.%06lds\n", start.tv_sec, start.tv_usec);
printf("End- %ld.%06lds\n", end.tv_sec, end.tv_usec);
// Output in microseconds
printf("Total- %.ldμs\n\n", (end.tv_usec - start.tv_usec)*1);
if (connectJawn == -1)
{
perror("connect call failed");
exit(-1);
} // end if
str_cli("Hello World!\n", sockfd); /* do it all */
} // end main
|
C
|
/*----------------------------------------------------------------------------------------------
* Module: UART
*
* File Name: uart.h
*
* AUTHOR: Bassnat Yasser
*
* Data Created: 28 / 3 / 2021
*
* Description: Header file for the UART AVR driver
------------------------------------------------------------------------------------------------*/
#ifndef UART_H_
#define UART_H_
#include "micro_config.h"
#include "std_types.h"
#include "common_macros.h"
typedef enum
{
FIVE_BITS,SIXTH_BITS, SEVEN_BITS, EIGHT_BITS
}UART_BIT_DATA;
typedef enum
{
DISABLED, EVEN_PARITY = 2, ODD_PARITY
}UART_PARITY_MODE;
typedef enum
{
ONE_STOP_BIT, TWO_STOP_BIT
}UART_STOP_BIT;
typedef struct
{
UART_BIT_DATA bit_data;
UART_PARITY_MODE parity;
UART_STOP_BIT stop;
uint32 baudrate
}UART_ConfigType;
/*******************************************************************************
* Preprocessor Macros *
*******************************************************************************/
///* UART Driver Baud Rate */
//#define USART_BAUDRATE 9600
/*******************************************************************************
* Functions Prototypes *
*******************************************************************************/
void UART_init(const UART_ConfigType * Config_Ptr);
void UART_sendByte(const uint8 data);
uint8 UART_recieveByte(void);
void UART_sendString(const uint8 *Str);
void UART_receiveString(uint8 *Str); // Receive until #
#endif /* UART_H_ */
|
C
|
/*
* 程序清单1-8 从标准输入读命令并执行
*
*/
#include "apue.h"
#include <sys/wait.h>
#define MAX_CMD 1024
static void sig_int(int); /* our signal-catching function. */
int main(void) {
char cmd_buf[MAX_CMD] = {0};
int pid = 0;
int child_status = 0;
if (signal(SIGINT, sig_int) == SIG_ERR) {
err_sys("signal error.");
}
printf("%%: "); /* prompt */
while(fgets(cmd_buf, MAX_CMD, stdin) != NULL) {
if(cmd_buf[strlen(cmd_buf) - 1] == '\n') {
cmd_buf[strlen(cmd_buf) - 1] = '\0';
}
if ((pid = fork()) < 0) {
err_sys("fork error");
} else if (pid == 0) { /* child */
printf("child pid: %d\n", getpid());
execlp(cmd_buf, cmd_buf, (char *) 0);
err_quit("could not execute: %s\n", cmd_buf);
return 127;
}
if ((pid = waitpid(pid, &child_status, 0)) < 0)
err_sys("wait error");
printf("%%: ");
}
return 0;
}
void sig_int(int signo) {
printf("interrupt\n%% ");
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mgueifao <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/09/22 22:17:02 by mgueifao #+# #+# */
/* Updated: 2021/10/27 01:00:36 by mgueifao ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include "philo.h"
#include "common.h"
int parse_args(int argc, const char *argv[], t_sym *s)
{
int i;
if (!ft_isnumber(argv[1]) || !ft_isnumber(argv[2]) || !ft_isnumber(argv[3])
|| !ft_isnumber(argv[4]) || (argc == 6 && !ft_isnumber(argv[5])))
return (0);
s->eat_count = -1;
if (argc == 6)
s->eat_count = atoi(argv[5]);
if (s->eat_count == 0)
return (0);
s->sym_state = sym_running;
s->pdone = 0;
s->pcount = atoi(argv[1]);
s->tdie = atoi(argv[2]);
s->teat = atoi(argv[3]);
s->tsleep = atoi(argv[4]);
s->philos = ft_calloc(s->pcount, sizeof(t_philo));
s->forks = ft_calloc(s->pcount, sizeof(pthread_mutex_t));
if (!s->philos || !s->forks)
return (0);
i = -1;
while (++i < s->pcount)
pthread_mutex_init(&s->forks[i], NULL);
pthread_mutex_init(&s->master, NULL);
return (1);
}
int create_philos(t_sym *s)
{
int i;
i = -1;
while (++i < s->pcount)
{
if (pthread_create(&s->philos[i].id, NULL, philo_main, s))
return (0);
}
return (1);
}
int join_philos(t_sym *s)
{
int i;
i = -1;
while (1)
{
pthread_mutex_lock(&s->master);
if (s->sym_state == sym_halt)
{
pthread_mutex_unlock(&s->master);
break ;
}
pthread_mutex_unlock(&s->master);
}
while (++i < s->pcount)
{
if (pthread_join(s->philos[i].id, NULL))
printf("Join error.\n");
}
return (1);
}
void clear(t_sym *s)
{
int i;
if (!s)
return ;
i = -1;
while (++i < s->pcount)
{
pthread_mutex_destroy(&s->forks[i]);
}
pthread_mutex_destroy(&s->master);
free(s->philos);
free(s->forks);
free(s);
}
int main(int argc, char const *argv[])
{
t_sym *s;
if (argc < 5 || argc > 6)
return (1);
s = ft_calloc(sizeof(t_sym), 1);
if (!s || !parse_args(argc, argv, s)
|| ((gettimeofday(&s->start, NULL) || 1) && !create_philos(s)))
{
clear(s);
return (1);
}
join_philos(s);
clear(s);
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int T, t;
scanf("%d", &T);
for(t = 1; t <= T; t++)
{
int N;
scanf("%d", &N);
int A[1001], B[1001];
int i;
for(i = 0; i < N; i++)
scanf("%d %d", &A[i], &B[i]);
int stars[1001] = {0};
int totalstars = 0;
int completed = 0;
while(totalstars < N*2)
{
int prevstars = totalstars;
int best = -1, besti = -1;
for(i = 0; i < N; i++)
{
if(stars[i] < 2 && totalstars >= B[i])
{
totalstars += 2 - stars[i];
stars[i] = 2;
completed++;
//printf("%d ==> 2 (%d)\n", i, totalstars);
}
else if(stars[i] == 0 && totalstars >= A[i] && B[i] > best)
{
best = B[i];
besti = i;
}
}
if(totalstars == prevstars)
{
if(besti == -1)
{
completed = -1;
break;
}
else
{
stars[besti] = 1;
totalstars++;
completed++;
//printf("%d ==> 1 (%d)\n", besti, totalstars);
}
}
}
if(completed == -1)
printf("Case #%d: Too Bad\n", t);
else
printf("Case #%d: %d\n", t, completed);
}
return 0;
}
|
C
|
Notes: Trees
Trees consist of nodes (which contain values) connected by edges
The hierachical ordering of our diagram conveys parent-child relationships
A node can have many children, but only one parent
Trees cannot contain cycles (loops)
There can only be one path from each node to every other node on the tree
n nodes
n-1 edges
Definitions:
a collection of trees is called a forest
a node with no parent is called the root of the tree
a node with no parent is called a leaf
a binary tree is a tree in which every node has 0, 1, or 2 children
a binary tree is full if every node in the tree has 0 or 2 children
a binary tree is complete if all levels of the tree are completely filled up, except
perhaps for the bottom level, which must be filled from the left side to the right with
no gaps between nodes, but possibly some empty spaces on the right side of that bottom most level
a perfect binary tree is one in which all non leaf nodes have two children, and all
leaf nodes are on the same level within the tree
h = floor(log base2 (n))
Deletion:
- go to the left subtree and pick the biggest element
------------------------------------
Runtimes for BST
------------------------------------
type best worse avg
insetion O(1) O(n) O(logn)
search O(1) O(n) O(logn)
deletion O(1) O(n) O(logn)
|
C
|
/*
============================================================================
TRABALHO PRTICO 6 - Paralelismo
Algoritmos e Estruturas de Dados III
Bruno Maciel Peres
[email protected]
LISTA.C - Define as funes que operam sobre o TAD lista adequado s necessidades do algoritmo
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "lista.h"
//Cria uma lista vazia em O(1)
void lista_criar(LISTA *lista) {
lista->inicio = NULL;
lista->casado = false;
lista->casado_com_id = 0;
lista->fim = NULL;
}
//Verifica se uma lista est vazia em O(1)
int lista_vazia(LISTA *lista) {
if (lista->inicio == NULL && lista->fim==NULL) return true;
else return false;
}
//Apaga uma lista em O(n)
void lista_apagar(LISTA *lista) {
if (!lista_vazia(lista)) {
NO *paux = lista->inicio;
while (paux != NULL) {
NO *prem = paux;
paux = paux->proximo;
free(prem);
}
}
lista->inicio = NULL;
lista->fim = NULL;
}
//Push_front, O(1). Retorna 0 em caso de erro
int lista_inserir_inicio(LISTA *lista, ITEM *item) {
NO *pnovo = (NO *)malloc(sizeof(NO)); //crio um novo n
if (pnovo != NULL) { //verifica se existe memria disponvel
//preenche o os dados
pnovo->item = *item;
pnovo->proximo = lista->inicio;
pnovo->anterior = NULL;
if (lista->inicio != NULL) {
lista->inicio->anterior = pnovo;
} else {
lista->fim = pnovo; //ajusta ponteiro para fim
}
lista->inicio = pnovo; //ajusta ponteiro incio
return 1;
} else {
//Em caso de erro
return 0;
}
}
//Push_back, O(1). Retorna 0 em caso de erro
int lista_inserir_fim(LISTA *lista, ITEM *item) {
NO *pnovo = (NO *)malloc(sizeof(NO)); //Cria um novo n
if (pnovo != NULL) { //Verifica se existe memria disponvel
//Preenche os dados do n
pnovo->item = *item;
pnovo->proximo = NULL;
pnovo->anterior = lista->fim;
if (lista->fim != NULL) {
lista->fim->proximo = pnovo;
} else {
lista->inicio = pnovo; //Ajusta ponteiro para incio
}
lista->fim = pnovo; //Ajusta ponteiro fim
return 1;
} else {
//Em caso de erro
return 0;
}
}
//Busca um valor contido em um n em O(n)
NO* lista_busca(LISTA* lista, int valor_procurado) {
NO* cursor = lista->inicio;
while (cursor->item.valor != valor_procurado && cursor != NULL) {
cursor = cursor->proximo;
}
return cursor;
}
void lista_remover_inicio(LISTA* lista) {
lista_remover_no(lista, lista->inicio);
}
void lista_remover_no(LISTA* lista, NO* no) {
NO* aux;
NO* ant;
aux = no;
if (aux == NULL) return;
if (lista->inicio == lista->fim) { //lista com um elemento
lista->inicio = NULL;
lista->fim = NULL;
} else { //lista com mais de um elemento
ant = aux->anterior; //aux = aluno de menor nota
if (ant != NULL) //Verifica se n a ser removido no o primeiro elemento
ant->proximo = aux->proximo;
else lista->inicio = aux->proximo;
ant = aux->proximo;
if (ant != NULL) //Verifica se n a ser removido no o ltimo elemento
ant->anterior = aux->anterior;
else lista->fim = aux->anterior;
}
free(aux); //removo o n da memria
return;
}
//Imprime os valores de n de uma lista encadeada
void lista_imprimir(LISTA *lista) {
NO* aux;
aux = lista->inicio;
if (!lista_vazia(lista)) {
printf ("%d ", aux->item.valor); //Mostra o 1 valor
aux = aux->proximo ;
while (aux != NULL ) {
printf ("%d ", aux->item.valor);
if (aux->proximo != NULL) aux = aux->proximo ;
else break;
}
printf("\n");
} else printf("Lista vazia\n");
}
|
C
|
/*
* main.c
*
* Created on: June 18, 2020
* Author: Jon McKay
*/
#include <stdio.h>
int main(void)
{
char characterInput1;
char characterInput2;
char characterInput3;
char characterInput4;
char characterInput5;
char characterInput6;
printf("Enter 6 characters: ");
characterInput1 = getchar();
getchar();
characterInput2 = getchar();
getchar();
characterInput3 = getchar();
getchar();
characterInput4 = getchar();
getchar();
characterInput5 = getchar();
getchar();
characterInput6 = getchar();
printf("ASCII codes: %d %d %d %d %d %d", characterInput1, characterInput2, characterInput3, characterInput4, characterInput5, characterInput6);
getchar();
return(0);
}
|
C
|
#include <pthread.h>
#include <stdio.h>
void *thread_func(void *a) { return NULL; }
int main(int argc, char *argv[])
{
size_t size;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_getstacksize(&attr, &size);
printf("Default stack size = %li\n", size);
size = 32 * 1024 * 1024;
pthread_attr_setstacksize (&attr, size);
pthread_t tid;
pthread_create(&tid, &attr, thread_func, NULL);
pthread_attr_getstacksize(&attr, &size);
printf("New stack size = %li\n", size);
pthread_attr_destroy(&attr);
pthread_join(tid, NULL);
return 0;
}
|
C
|
#ifndef boolean_H
#define boolean_H
/***********************************/
/* Program : boolean.h */
/* Deskripsi : header file modul boolean */
/* NIM/Nama : 24060119120027/Iwan Suryaningrat*/
/* Tanggal : September 2020*/
/***********************************/
//type boolean enumerasi bahasa C, false=0, true=1
typedef enum {false, true} boolean;
#endif
|
C
|
#include <stdio.h>
int main(void)
{
int height,length,width,volume,weight;
height=8;
length=12;
width=10;
volume=height*length*width;
weight=(volume+165)/166;
printf("Dimensions:%dx%dx%d\n",length,width,height);
printf("Volume(cubic inches):%d\n",volume);
printf("Dimensional weight (pounds):%d\n",weight);
return 0;
}
|
C
|
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
int swap_count = 0;
int comparation_count = 0;
// Генерирует случайн int побитово беря для каждого бита последний бит rand
int randint(void){
int num = 0;
for (int i = 0; i < 8 * sizeof(int); i++){
num |= (rand() & 1) << i;
}
return num;
}
//заполняет массив a длинны n случайными числами
void random_array(int * a, int n){
for (int i = 0; i < n; i++){
a[i] = randint();
}
}
//сравнение чисел по модулю, преобразование в лонг т.к. abs(INT_MIN) > INT_MAX
int less_then(int a, int b){
comparation_count++;
long long c = a, d = b;
c = (c < 0)? -c: c;
d = (d < 0)? -d: d;
return c > d;
}
//быстрая сортировка
void quick_sort(int * a, int n){
//если в подмассиве меньше 2х элементов то соритровать нечего.
if (n <= 1){
return;
}
//выбираем опорный элемент (в данном случае средний)
int mid = a[n/2];
int left = 0, right = n - 1;
//цикл пока левый и правый указатель не пересекутся
do {
//находим первый левый (правый) элемент который меньше (больше) опорного
for (; less_then(mid, a[left]) && left < n - 1; left++);
for (; less_then(a[right], mid) && right >= 0; right--);
//если нашли такие то меняем их местами если левый действительно левее
if (left <= right){
swap_count++;
int tmp = a[left];
a[left] = a[right];
a[right] = tmp;
left++;
right--;
}
} while (left <= right);
//запускаем сортировку рекурсивно от подотрезков если есть что сортировать...
if(right > 0) {
quick_sort(a, right + 1);
}
if (left < n) {
quick_sort(a + left, n - left);
}
}
//сортировка пузырком
void bubble_sort(int * a, int n){
int current = 0;
//пока пузырек не "доплыл" до последнего элемента проверяем в правильном ли порядке соритруются элементы
while (current < n - 1){
//если элементы в неправильном порядке то меняем их местами и возвращаемся в начало массива
if (less_then(a[current], a[current + 1])){
swap_count++;
int tmp = a[current];
a[current] = a[current + 1];
a[current + 1] = tmp;
current = 0;
}
//иначе переходим к следующему элоемнту
else{
current++;
}
}
}
//проверяет массив на отсортированность
int sort_check(int * a, int n){
for (int i = 0; i < n - 1; i++){
if (less_then(a[i],a[i + 1])){
return 0;
}
}
return 1;
}
int main(void){
//установка сида rng
long long seed = time(NULL);
srand(seed);
//выбор размера массива для теста
int n = 10;
int a[n];
//создавние массива для теста
random_array(a,n);
quick_sort(a,n);
printf("%d\n", sort_check(a,n));
printf("%d %d\n", comparation_count,swap_count);
//вовзращаем состояние генератора в исходное состояние чтобы сгенерировать тот-же массив
srand(seed);
random_array(a,n);
comparation_count = 0;
swap_count = 0;
bubble_sort(a,n);
printf("\n");
printf("%d\n", sort_check(a,n));
printf("%d %d\n", comparation_count,swap_count);
return 0;
}
|
C
|
#include <stdio.h>
#include <wiringPi.h>
#include <time.h>
time_t rawtime;
struct tm * timeinfo;
int openDoor, openDoor1, openDoor2, openDoor3;
void myInterrupt (void) {
openDoor = !openDoor;
if ( openDoor )
printf("Door 1 is opened...");
else
printf("Door 1 is closed...");
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ("time=%s\n", asctime(timeinfo));
}
void myInterrupt1 (void) {
openDoor1 = !openDoor1;
if ( openDoor1 )
printf("Door 2 is opened...");
else
printf("Door 2 is closed...");
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ("time=%s\n", asctime(timeinfo));
}
void myInterrupt2 (void) {
openDoor2 = !openDoor2;
if ( openDoor2 )
printf("Door 3 is opened...");
else
printf("Door 3 is closed...");
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ("time=%s\n", asctime(timeinfo));
}
void myInterrupt3 (void) {
openDoor3 = !openDoor3;
if ( openDoor3 )
printf("Door 4 is opened...");
else
printf("Door 4 is closed...");
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ("time=%s\n", asctime(timeinfo));
}
int main (void)
{
//openDoor = false;
wiringPiSetup() ;
//pullUpDnControl(1,0);
wiringPiISR (0, INT_EDGE_BOTH, &myInterrupt);
wiringPiISR (1, INT_EDGE_BOTH, &myInterrupt1);
wiringPiISR (3, INT_EDGE_BOTH, &myInterrupt2);
wiringPiISR (4, INT_EDGE_BOTH, &myInterrupt3);
//pinMode(0,INPUT);
openDoor = digitalRead(0);
openDoor1 = digitalRead(1);
openDoor2 = digitalRead(2);
openDoor3 = digitalRead(3);
printf("1-%d; 2-%d; 3-%d; 4-%d\n\n",openDoor,openDoor1,openDoor2,openDoor3);
pullUpDnControl(0,PUD_UP);
pullUpDnControl(1,PUD_UP);
pullUpDnControl(2,PUD_UP);
pullUpDnControl(3,PUD_UP);
while(1)
{
//a = digitalRead(0);
//printf("a=%d\n",a);
delay(100);
}
return 0 ;
}
|
C
|
/***************************
* PROGRAM NAME: guess.c *
* PAGE NUMBER 214 *
* AUTHOR: SWAROOP *
***************************/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_NUMBER 100
/* external variable */
int secret_number;
/* prototypes */
void initialize_number_generator(void);
void choose_new_secret_number(void);
void read_guesses(void);
int main(void)
{
char command;
printf("Guess the secret number between 1 and %d.\n\n", MAX_NUMBER);
initialize_number_generator();
do {
choose_new_secret_number();
printf("A new number has been chosen.\n");
read_guesses();
printf("Play again? (Y/N) ");
scanf(" %c", &command);
printf("\n");
} while (command == 'y' || command == 'Y');
return 0;
}
/***********************************
* Initialize the random number *
* generator using the time of day.*
***********************************/
void initialize_number_generator(void)
{
srand((unsigned) time (NULL));
}
/************************************
* Randomly select a number between *
* 1 and MAX_NUMBER and store it in *
* the secret_number. *
************************************/
void choose_new_secret_number(void)
{
secret_number = rand() % MAX_NUMBER + 1;
}
/**************************************
* Repeatedly read user guesses and *
* tell the user whether each guess *
* is too low, too high, or correct. *
* When guess is correct, print the *
* total number of guesses and return *
**************************************/
void read_guesses(void)
{
int guess, num_guesses = 0;
for (;;)
{
num_guesses++;
printf("Etner guess: ");
scanf("%d", &guess);
if (guess == secret_number)
{
printf("You won in %d guesses!\n\n", num_guesses);
return;
}
else if (guess < secret_number)
printf("Too low; try again.\n");
else
printf("Too high;, try again.\n");
}
}
|
C
|
/*Santiago Flores
*
*
* FILE: AST.h
*
* The header file for AST.c
* Creates a new struct called ASTNode which is used to create a pointer to the data structure
* that is used to represent the parsed program.
* ASTNode contains:
* enum NODETYPE - to hold the type of node when a new node is created
* enum OPERATORS - holds operators and datatypes
* ASTNodeType s1, s2, next - nodes that point to other nodes connecting everything together
* char name - holds the name if needed
* int size - holds the size for nodes that have associated numbers if needed
*
* NEW
* ASTNode now holds the pointer to an entry in the symbol table called symbol
* ASTNode now uses a new operator called sem_type to help yacc with type checking sem_type only holds a data type
* ASTNode now also holds the function check_params
*/
#ifndef AST
#define AST
enum NODETYPE{ //nodetypes
vardec,
fundec,
param,
block,
whilestmt,
myReturn,
identifier,
call,
myWrite,
myRead,
myNum,
expr,
selecstmt,
ifelse,
ifelse1,
assignstmt,
mybool,
exprstmt,
arg
};
enum OPERATORS { ///operators and datatypes
plus,
minus,
times,
divide,
myOr,
myAnd,
myTrue,
myFalse,
boolType,//datatype
voidType,//datatype
intType,//datatype
greaterEqual,
lessEqual,
equal,
notEqual,
less,
greater,
myNot,
myEqual
};
typedef struct ASTNodeType {
enum NODETYPE type;
enum OPERATORS operator;
enum OPERATORS sem_type; //added the semantic type of the symbols
struct ASTNodeType *s1, *s2, *next;
struct SymbTab *symbol; //hold an pointer to an entry in the symbol table
char * name;
int size;
}ASTNode;//
ASTNode * ASTCreateNode(enum NODETYPE DesiredType);
void printSpaces(int num);
void ASTprint(ASTNode *p, int level);
int check_params(ASTNode *f, ASTNode *a); //added to check if the params match when calling a fucntion
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* better_in_reverse.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: oespion <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/06/09 11:21:51 by oespion #+# #+# */
/* Updated: 2018/07/15 15:25:21 by oespion ### ########.fr */
/* */
/* ************************************************************************** */
#include "../libft/includes/libft.h"
#include "push_swap.h"
int better_in_reverse_ra(t_list **g, int base_count, t_list *biggest)
{
t_list *cpy_0;
t_list *cpy_1;
int count;
cpy_0 = g[0];
cpy_1 = g[1];
count = 0;
while (!(cpy_1->nb <= cpy_0->nb && cpy_1->nb >= cpy_0->prev->nb)
&& !(cpy_0->prev == biggest && cpy_1->nb >= biggest->nb))
{
count++;
cpy_0 = cpy_0->prev;
}
if (count >= base_count)
return (0);
return (count);
}
int better_in_reverse_rb(t_list **g, int base_count, t_list *biggest)
{
t_list *cpy_0;
t_list *cpy_1;
int count;
int len;
len = 1;
cpy_0 = g[0];
cpy_1 = g[1];
count = 1;
while (cpy_1->next != g[1])
{
cpy_1 = cpy_1->next;
len++;
}
cpy_1 = cpy_1->next;
while (!(cpy_1->nb <= cpy_0->nb && cpy_1->nb >= cpy_0->prev->nb)
&& !(cpy_0->prev == biggest && cpy_1->nb >= biggest->nb))
{
count++;
cpy_1 = cpy_1->prev;
if (count > len)
return (0);
}
return (count >= base_count ? 0 : count);
}
int better_in_rrr(t_list **g, int base_count, t_list *biggest)
{
t_list *cpy_0;
t_list *cpy_1;
int count;
count = 0;
cpy_0 = g[0];
cpy_1 = g[1];
return (0);
}
|
C
|
#include <stdio.h>
int fibo(int);
int main()
{
int n=0;
printf("Ǻġ Է = ");
scanf_s("%d", &n);
for (int i = 0; i < n; i++) {
printf(" %d", fibo(i));
}
printf("\n");
return 0;
}
int fibo(int n)
{
if (n == 0)
return 0;
if (n == 1)
return 1;
else
return fibo(n - 1) + fibo(n - 2);
}
|
C
|
#include <stdio.h>
#include <glib.h>
#include <poppler.h>
#include <stdlib.h>
char ESC=27;
void bold_on()
{
printf("%c[1m",ESC);
}
void bold_off()
{
printf("%c[0m",ESC);
}
void find(const char *filename, GRegex *regex)
{
GFile *file;
gchar *uri;
PopplerDocument *doc;
PopplerPage *page;
GError *error = NULL;
gint i, n;
gint a, b;
GMatchInfo *match_info;
gchar *text;
file = g_file_new_for_commandline_arg(filename);
uri = g_file_get_uri(file);
g_object_unref(file);
if(!(doc = poppler_document_new_from_file(uri, NULL, &error)))
{
fprintf(stderr, "Could not open file %s: %s\n",
filename, error->message);
g_error_free(error);
goto cleanup;
}
n = poppler_document_get_n_pages(doc);
for(i = 0; i < n; ++i)
{
page = poppler_document_get_page(doc, i);
text = poppler_page_get_text(page);
g_regex_match(regex, text, (GRegexMatchFlags) 0, &match_info);
while(g_match_info_matches(match_info))
{
bold_on();
printf("%s:%i ", filename, i + 1);
bold_off();
g_match_info_fetch_pos(match_info, 0, &a, &b);
for(; a >= 1 && *(text + a - 1) != '\n'; --a);
for(; *(text + b) && *(text + b) != '\n'; ++b);
//print out the entire line
for(; a < b; ++a)
printf("%c", *(text + a));
printf("\n");
g_match_info_next (match_info, NULL);
}
g_match_info_free(match_info);
g_object_unref(page);
g_free(text);
}
g_object_unref(doc);
cleanup:
g_free(uri);
}
typedef struct argument
{
const char *filename;
GRegex *regex;
} argument;
void find_par(gpointer data, gpointer user_data)
{
argument *arg = (argument*) data;
find(arg->filename, arg->regex);
}
int main(int argc, char **argv)
{
const char *filename;
GError *error = NULL;
GRegex *regex;
int i;
GThreadPool *workers;
argument *args;
if(argc < 3)
{
fprintf(stderr, "Usage: %s expression filenames\n" , argv[0]);
return 1;
}
if(!(regex = g_regex_new(argv[1],
(GRegexCompileFlags) 0,
(GRegexMatchFlags) 0,
&error)))
{
fprintf(stderr, "Could not create regular expression: %s\n",
error->message);
g_error_free(error);
return 1;
}
argc -= 2;
argv += 2;
args = (argument*) malloc(argc* sizeof(argument));
workers = g_thread_pool_new((GFunc) find_par, NULL,
g_get_num_processors(), TRUE, &error);
if(error)
{
fprintf(stderr, "Could not create thread pool: %s\n",
error->message);
g_error_free(error);
return 1;
}
for(i = 0; i < argc; ++i)
{
argument *cur = args + i;
cur->filename = argv[i];
cur->regex = regex;
g_thread_pool_push(workers, cur, &error);
if(error)
{
fprintf(stderr, "Could not push job to thread pool: %s\n",
error->message);
g_error_free(error);
return 1;
}
}
// this joins all threads...
g_thread_pool_free(workers, FALSE, TRUE);
g_regex_unref(regex);
free(args);
return 0;
}
|
C
|
#include<stdio.h>
int rev(char *);
int main()
{
char str[20];
printf("enter a string");
scanf_s("%s", str,20);
rev(str);
getch();
return 0;
}
int rev(char *a)
{
if (*a)
{
rev(a + 1);
printf("%c", *a);
}
}
|
C
|
#include "holberton.h"
/**
* puts2 - takes a pointer to string and prints one char out of 2 from
* the string it's pointing to, followed by a newline.
* @str: pointer to a char
*
*/
void puts2(char *str)
{
while (*str)
{
if (!(*(str + 1)))
{
_putchar(*str);
break;
}
_putchar(*str);
str += 2;
}
_putchar('\n');
}
|
C
|
#include "holberton.h"
/**
* _strcmp - compare bytes of a string
* @s1: The destination string
* @s2: source string.
* Return: int.
*/
int _strcmp(char *s1, char *s2)
{
int i = 0;
int same = 0;
int res = 0;
while (same == 0 && *(s1 + i) && *(s2 + i))
{
if (*(s1 + i) != *(s2 + i))
{
same = 1;
}
else
{
i++;
}
}
if (same == 0)
{
return (res);
}
else
{
res = *(s1 + i) - *(s2 + i);
}
return (res);
}
|
C
|
#include "../monty.h"
static int monty_print_elem(void *user_data, dlist_value_t value) {
UNUSED(user_data);
if ( (value.as_int > 0) && (value.as_int <= 127) ) {
printf("%c", value.as_int);
return DLIST_CONTINUE;
}
return DLIST_STOP;
}
void monty_instr_pstr(monty_t *monty) {
dlist_apply_head_to_tail(monty->dl, NULL, monty_print_elem);
printf("\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int math_score = 99;
int chinese_score = 90;
int english_score = 88;
printf("your testscore:\nmath_score:%d,chinese_score:%d,english_score:%d\n",math_score,chinese_score,english_score);
return 0;
}
|
C
|
void print() {
int i;
char *c = "hello world\n";
char d[13];
printChar('c');
printStr(c);
for(i = 0; i < 13; i++)
d[i] = c[i];
printChar('d');
printStr(d);
printInt(25);
}
int main() {
int cycles, insts;
cycles = getTime();
insts = getInsts();
print();
cycles = getTime() - cycles;
insts = getInsts() - insts;
printStr("\nCycles = "); printInt(cycles); printChar('\n');
printStr("Insts = "); printInt(insts); printChar('\n');
return 0;
}
|
C
|
#include "mont_utils.h"
//ADD;
void ADD(uint32_t* t, uint8_t i, uint32_t C)
{
uint32_t W = 0xffffffff;
uint32_t sum[2] = {0, 0};
while(C != 0)
{
if(W - C < t[i])
{
sum[0] = t[i] + C;
sum[1] = 1;
}
else
{
sum[0] = t[i] + C;
sum[1] = 0;
}
C = sum[1];
t[i] = sum[0];
i += 1;
}
}
//SUB_COND;
void SUB_COND(uint32_t* u, uint32_t* n, uint32_t SIZE, uint32_t* dum)
{
uint32_t B = 0;
uint32_t sub = 0;
uint32_t t[SIZE+1];
for(uint32_t j = 0; j<=SIZE; j++)
t[j] = 0;
for (uint8_t i = 0; i <= SIZE; i++)
{
sub = u[i] - n[i] - B;
if (u[i] >= n[i] + B)
B = 0;
else
B = 1;
t[i] = sub;
}
if(B == 0)
{
for(uint8_t ix = 0; ix < SIZE; ix++)
dum[ix] = t[ix];
}
else
{
for(uint8_t iy = 0; iy < SIZE; iy++)
dum[iy] = u[iy];
}
}
//32bit multiplication;
void _32mul(uint32_t x, uint32_t y, uint32_t* sum)
{
//divide x y into two halves;
uint32_t x_lo = (uint16_t)x;
uint32_t x_hi = x >> 16;
uint32_t y_lo = (uint16_t)y;
uint32_t y_hi = y >> 16;
//multiplication's equivalent four parts;
uint32_t xyhi = x_hi * y_hi;
uint32_t xymid = x_hi * y_lo;
uint32_t yxmid = x_lo * y_hi;
uint32_t xylo = x_lo * y_lo;
//carry bits;
uint32_t carry = ((uint32_t)(uint16_t)xymid +
(uint32_t)(uint16_t)yxmid +
(xylo >> 16) ) >> 16;
//Higher bits;
uint32_t higher = xyhi + (xymid >> 16) + (yxmid >> 16)
+ carry;
//lower bits;
uint32_t lower = xylo + (xymid << 16) + (yxmid << 16);
//result;
sum[0] = lower;
sum[1] = higher;
}
|
C
|
#include <assert.h>
#include <stddef.h>
#include "hashtab.h"
#include "slist.h"
unsigned int hash(const char * key, unsigned int table_size)
{
unsigned int hash_val = 0;
key++;
while( *key != '\0')
{
hash_val = (hash_val << 5) + *key++;
}
return hash_val % table_size;
}
void hash_table_init(hash_table_t * table, unsigned int size)
{
int i;
assert(size < HASH_TABLE_MAX_SIZE);
table->size = size;
table->hash_func = hash;
for(i = 0; i < table->size; i++)
table->buckets[i] = NULL;
}
void hash_table_add(hash_table_t * table, list_node_t * node, const char *key)
{
insert_list_node(&table->buckets[table->hash_func(key, table->size)], node);
}
list_node_t ** hash_table_get_list(hash_table_t * table, const char * key)
{
return &table->buckets[table->hash_func(key, table->size)];
}
|
C
|
#include "dlistnode.h"
DListNode *dListNode_new( Data data, DListNode *prev, DListNode *next )
{
DListNode *node = (DListNode *) malloc( sizeof( DListNode ));
assert( node != NULL );
node->data = data;
node->prev = prev;
node->next = next;
return node;
}
void dListNode_destroy( DListNode *node )
{
free( node );
return;
}
|
C
|
/*
** EPITECH PROJECT, 2018
** PSU_42sh_2017
** File description:
** Check the display of the prompt.
*/
#include <criterion/criterion.h>
#include <criterion/redirect.h>
#include "shell.h"
#include "execution.h"
#include "instruction.h"
#include "mylib.h"
Test(display_prompt, correct_prompt, .timeout = 0.5)
{
shell_t *shell = NULL;
pipe_t *pipe = malloc(sizeof(pipe_t));
char **env = malloc(sizeof(char *) * (6));
char str[5][30] = {"PATH=/bin", "USER=pflorent", "HOME=/home",
"PWD=/home/marvin", "HOSTNAME=jenk-server"};
for (int i = 0; i < 5; i++) {
env[i] = malloc(sizeof(char) * my_strlen(str[i]));
env[i] = my_strcpy(env[i], str[i]);
}
env[5] = NULL;
shell = initialisation_shell(1, NULL, env);
cr_redirect_stdout();
display_prompt(shell);
}
Test(display_prompt, wrong_prompt, .timeout = 0.5)
{
shell_t *shell = NULL;
pipe_t *pipe = malloc(sizeof(pipe_t));
char **env = malloc(sizeof(char *) * (5));
char str[1][17] = {"PATH=/bin"};
for (int i = 0; i < 1; i++) {
env[i] = malloc(sizeof(char) * my_strlen(str[i]));
env[i] = my_strcpy(env[i], str[i]);
}
env[1] = NULL;
shell = initialisation_shell(1, NULL, env);
cr_redirect_stdout();
display_prompt(shell);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "mystrlib.h"
int main()
{
char string1[] = "hello";
char string2[] = " world";
int match = strComp(string1, string2);
printf("Match: %d\n", match);
int length1 = strLen(string1);
int length2 = strLen(string2);
printf("Length 1: %d\n", length1);
printf("Length 2: %d\n", length2);
char* catStr = strCat(string1, string2);
printf("Concatenated: %s\n", catStr);
char* copiedStr = malloc(strLen(catStr));
strCopy(copiedStr, catStr);
printf("Copied: %s\n", copiedStr);
}
|
C
|
// Marek Sokolowski - Computer Network large assignment problem
// Master implementation (can control players over network).
//
// Invocation:
// ./master [port-num]
//
// If port-num is given, sets up telnet server at this port; else seeks for a free
// port and sets up server there.
//
// Telnet commands:
// START location args... - start player at given network location (using SSH)
// using args; id of player is returned
// AT hh.mm location args... - start player at given local hour and network location;
// id of player is returned on success
// PAUSE id, PLAY id, STOP id - pause/play/stop player instance #id (UDP command)
// TITLE id - get current title in instance #id and print to telnet
//
#include <assert.h>
#include <errno.h>
#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <poll.h>
#include <pthread.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "at.h"
#include "err.h"
#include "headers.h"
#include "fifo_wait.h"
#include "ssh_conn.h"
#include "utils.h"
struct master_config { // Konfiguracja mastera.
uint16_t telnet_port; // Port nasluchujacy.
int listen_socket; // Gniazdo nasluchujace.
struct safe_fifo telnet_conns; // Kolejka informacji o polaczeniach telnet.
struct safe_fifo player_conns; // Kolejka informacji o playerach (SSH).
struct safe_fifo player_terms; // Kolejka zdarzen - zakonczen procesu
pthread_mutex_t ssh_read_mutex; // Mutex na (nieblokujacy) odczyt po SSH.
pthread_t cleaner_thread; // Watek czyszczacy playery.
} master_config;
struct telnet_conn_config { // Konfiguracja telneta.
pthread_t telnet_thread; // Watek sesji telnet.
int telnet_fd, udp_fd; // Deskryptor sesji telnet oraz socketa UDP.
int udp_port; // Port, po ktorym sluchamy na UDP.
};
struct player_conn_config { // Konfiguracja playera.
int telnet_fd; // Deskryptor sesji telnet.
struct ssh_conn_config ssh; // Polaczenie ssh.
};
__attribute__((noreturn))
static void fail_parameters(const char *progname) {
fprintf(stderr, "ERROR: %s [telnet_port]\n", progname ? progname : "./master");
exit(1);
}
static void process_args(int argc, char **argv) {
if (argc != 1 && argc != 2) { fail_parameters(argv[0]); }
if (argc == 2) {
char *badpos;
long port = strtol(argv[1], &badpos, 10);
if (*argv[1] == '\0' || *badpos != '\0' || port <= 0 || port > MAX_PORT) {
fail_parameters(argv[0]);
}
master_config.telnet_port = port;
} else {
master_config.telnet_port = 0; // 0 - chce dostac jakis port.
}
}
static void setup_telnet() {
debug("Setting up telnet listener\n");
// Ustawiamy polaczenie telneta.
int on_opt = 1;
int listen_socket = RUN_CMD(socket, AF_INET, SOCK_STREAM, 0);
RUN_CMD(setsockopt, listen_socket, SOL_SOCKET, SO_REUSEADDR, (char*)&on_opt, sizeof(on_opt));
struct sockaddr_in address;
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_ANY);
// Jesli 0, to chce dostac od systemu jakis port, a potem go wypisac na stdout.
bool show_port = (master_config.telnet_port == 0);
address.sin_port = htons(master_config.telnet_port);
RUN_CMD(bind, listen_socket, (struct sockaddr*)&address, sizeof(address));
if (show_port) {
// Uzyskuje numer portu, zapisuje go sobie i wypisuje uzytkownikowi.
socklen_t addrlen = sizeof(struct sockaddr_in);
RUN_CMD(getsockname, listen_socket, (struct sockaddr*)&address, &addrlen);
master_config.telnet_port = ntohs(address.sin_port);
printf("%d\n", master_config.telnet_port);
}
RUN_CMD(listen, listen_socket, 10);
master_config.listen_socket = listen_socket;
safe_fifo_init(&master_config.telnet_conns);
}
// Wlasciwe uruchomienie playera.
static void start_player(int id) {
if (id == -1) { return; }
// Dostajemy z kolejki informacje o playerze.
struct safe_fifo_elem *elem = safe_fifo_front_by_id(&master_config.player_conns, id);
if (!elem) {
debug("Weird, player should be existent\n");
return;
}
struct player_conn_config *conf = (struct player_conn_config*)(elem->elem);
// Uruchamiamy przez SSH; jesli sie nie uda, wyrzucamy z kolejki
if (!player_run_ssh(&conf->ssh)) {
safe_fifo_erase(&master_config.player_conns,
safe_fifo_front_by_id(&master_config.player_conns, id));
}
}
// Ustawiamy playera (ale go nie uruchamiamy).
static int setup_player(const char *loc, const char *args, int client_fd) {
debug("Setting up player at [%s] with args [%s]...\n", loc, args);
// Tworzymy i wypelniamy informacje playera.
struct player_conn_config *conf = calloc(sizeof(struct player_conn_config), 1);
conf->telnet_fd = client_fd;
conf->ssh.telnet_buf = utils_get_fd(client_fd);
debug("got (%p)\n", conf->ssh.telnet_buf);
conf->ssh.read_mutex = &master_config.ssh_read_mutex; // Mutex na czytanie globalny!
conf->ssh.terms = &master_config.player_terms;
strncpy(conf->ssh.host_name, loc, SSH_MAX_HOST_SIZE - 1);
strncpy(conf->ssh.player_args, args, SSH_MAX_ARGS_SIZE - 1);
// Jesli nie przejdzie ustawianie danych w SSH, wypluwamy -1
if (!player_setup_data(&conf->ssh)) { return -1; }
// Wrzucamy na kolejke playera, stad mamy jego id.
int id = safe_fifo_push_back(&master_config.player_conns, conf, -1);
conf->ssh.client_id = id;
debug("%d\n", id);
utils_block_printf(conf->ssh.telnet_buf, "OK %d\n", id);
return id;
}
// Akcja wykonywana przy poleceniu AT polegajaca na uruchomieniu playera o ID.
static void at_start_player(union sigval sigval) {
start_player(sigval.sival_int);
}
// Akcja przy poleceniu AT - zabij playera o danym ID.
static void at_end_player(union sigval sigval) {
int id = sigval.sival_int;
// Znajdujemy watek ssh obslugujacy playera i go anulujemy i joinujemy.
struct safe_fifo_elem *elem = safe_fifo_front_by_id(&master_config.player_conns, id);
if (!elem) {
debug("Wanted to cease the player's existence, but it commited suicide earlier...\n");
return;
}
struct player_conn_config *conf = (struct player_conn_config*)(elem->elem);
pthread_t *thread = &conf->ssh.thread;
pthread_cancel(*thread);
pthread_join(*thread, NULL);
}
#define UDP_PORT_BASE 34312
// Wyslij operacje op (juz sprawdzona, ze jest ok) do playera player_id.
// Socket UDP to fd, bufor telneta to telnet.
static void send_op_to_player(char *op, int player_id, int fd, FILEBUF *telnet) {
// Pobieramy informacje o polaczeniu, w szczegolnosci wyluskujemy hosta
// i port UDP.
struct safe_fifo_elem *elem = safe_fifo_front_by_id(&master_config.player_conns, player_id);
if (!elem) {
utils_block_printf(telnet, "ERROR No player id %d\n", player_id);
return;
}
struct player_conn_config *player = (struct player_conn_config*)(elem->elem);
struct ssh_conn_config *ssh = &player->ssh;
if (!ssh->started) {
utils_block_printf(telnet, "ERROR Player %d is not active yet\n", player_id);
return;
}
struct sockaddr_in *addr = &ssh->ssh_addr;
addr->sin_port = htons(ssh->udp_port);
debug("PORT = %d\n", ssh->udp_port);
// Wyslij datagram UDP.
sendto(fd, op, strlen(op), 0,
(struct sockaddr*)addr, (socklen_t)sizeof(*addr));
//utils_block_printf(telnet, "OK %s sent to %d\n", op, player_id);
// Jesli TITLE, to musimy poznac odpowiedz.
if (!strcmp(op, "TITLE")) {
struct pollfd udp_poll;
udp_poll.fd = fd;
udp_poll.events = POLLIN;
int res = poll(&udp_poll, 1, 3 * 1000); // Timeout 3 sekundy na odpowiedz.
if (res == 0) {
utils_block_printf(telnet, "ERROR %d No response in 3 seconds\n", player_id);
} else if (udp_poll.revents & (POLLERR | POLLHUP)) {
utils_block_printf(telnet, "ERROR %d Some error on UDP descriptor\n", player_id);
} else {
char buf[256];
ssize_t len = recv(fd, buf, 250, 0);
if (len < 0) {
utils_block_printf(telnet, "ERROR %d UDP error occured\n", player_id);
} else {
buf[len] = 0;
utils_block_printf(telnet, "OK %d %s\n", player_id, buf);
}
}
} else {
utils_block_printf(telnet, "OK %d\n", player_id);
}
}
// Majac polaczenie SSH, wyrzuc z niego wskazany deskryptor telneta, o ile ten
// jest wpisany. (Ma to sens, gdy sie rozlaczamy i juz pisanie na telneta nie ma
// sensu).
static void remove_telnet_fds(void *ssh_void, void *param) {
int fd = *(int*)param;
struct player_conn_config *player = (struct player_conn_config*)ssh_void;
struct ssh_conn_config *ssh = &player->ssh;
utils_erase_fd(ssh->telnet_buf, fd);
}
// Czysczenie sesji telneta.
static void cleanup_telnet(int telnet_fd) {
// Wyrzucamy deskryptory 'telnet_fd' ze wszystkich playerow.
safe_fifo_apply(&master_config.player_conns, remove_telnet_fds, &telnet_fd);
// Wyrzucamy telneta z kolejki.
struct safe_fifo_elem *elem = safe_fifo_front_by_id(&master_config.telnet_conns, telnet_fd);
safe_fifo_erase(&master_config.telnet_conns, elem);
close(telnet_fd);
}
// Watek z polaczeniem telnetowym.
static void* telnet_connection(void *param) {
#define MAX_TELNET_LINE 1024
struct telnet_conn_config *telnet = (struct telnet_conn_config*)param;
int client_fd = telnet->telnet_fd;
FILEBUF *file = utils_get_fd(client_fd);
char telnet_line[MAX_TELNET_LINE];
ssize_t linesize;
const char* delimiters = " \r\n";
// Uzyskujemy UDP.
int udp_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (udp_fd < 0) {
debug("Could not make UDP socket for connection: %s", strerror(errno));
utils_block_printf(file, "ERROR Could not setup UDP in connection: %s\n", strerror(errno));
goto telnet_cleanup;
}
struct sockaddr_in address;
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_ANY);
address.sin_port = htons(0);
if (bind(udp_fd, (struct sockaddr*)&address, sizeof(address))) {
debug("Could not bind UDP socket for telnet: %s\n", strerror(errno));
utils_block_printf(file, "ERROR Could not setup connection\n");
goto telnet_cleanup;
}
// Zgadujemy teraz numer portu
socklen_t addrlen = sizeof(address);
if (getsockname(udp_fd, (struct sockaddr*)&address, &addrlen)) {
debug("Could not get info about UDP socket: %s\n", strerror(errno));
utils_block_printf(file, "ERROR Could not setup connection\n");
goto telnet_cleanup;
}
telnet->udp_port = ntohs(address.sin_port);
telnet->udp_fd = udp_fd;
debug("Set up UDP listener at (%d)\n", listen_port);
// Pobieramy kolejne linie z polaczenia telnet.
while ((linesize = utils_getline(file, telnet_line, MAX_TELNET_LINE, true)) != FILEBUF_EOF) {
if (linesize < 0) {
debug("Some error on telnet site, need to disconnect\n");
break;
}
debug("%zd\n", linesize);
char *line = telnet_line;
char *cmd = parse_token(&line, delimiters);
if (!cmd) { continue; } // Pusta linia.
//debug("%s\n", cmd);
// Polecenie START loc ...
if (!strcmp(cmd, "START")) {
// Bierzemy pierwszy token; pozostala czesc linii jest w line.
char *loc = parse_token(&line, delimiters);
if (!loc) {
utils_block_printf(file, "ERROR No location given in START command\n");
continue;
}
// Ustawiamy playera, jak sie uda, to go startujemy.
start_player(setup_player(loc, line, client_fd));
} else if (!strcmp(cmd, "AT")) {
// Polecenie AT hh.mm MM loc ...
// Parsujemy kolejne tokeny, przetwarzamy je i sprawdzamy ich poprawnosc.
char *tm_start_str = parse_token(&line, delimiters);
char *mins_run_str = parse_token(&line, delimiters);
char *loc = parse_token(&line, delimiters);
char *badloc;
// Co moze byc zle? Moze byc za malo tokenow...
if (!tm_start_str || !mins_run_str || !loc) {
utils_block_printf(file, "ERROR AT command too short\n");
continue;
}
// ...minuty moga nie byc poprawna liczba...
long mins_run = strtol(mins_run_str, &badloc, 10);
if (!*mins_run_str || *badloc || mins_run <= 0 || mins_run > 1e7) {
utils_block_printf(file, "ERROR Incorrect duration time in AT command\n");
continue;
}
// ... hh.mm moze nie byc poprawna godzina...
int secs_start = parse_time(tm_start_str);
if (secs_start == -1) {
utils_block_printf(file, "ERROR Incorrect start time\n");
continue;
}
// ...moze sie nie udac ustawic playera...
int id = setup_player(loc, line, client_fd);
if (id == -1) {
continue;
}
// ...moze sie nie udac ustawic timera zakonczenia...
if (!do_in_time(secs_start + mins_run * 60, at_end_player, id)) {
utils_block_printf(file, "ERROR Could not set up player end\n");
continue;
}
// ...lub timera startu.
if (!do_in_time(secs_start, at_start_player, id)) {
utils_block_printf(file, "ERROR Could not set up player start\n");
continue;
}
// Komendy UDP. (cmd num)
} else if (!strcmp(cmd, "PAUSE") || !strcmp(cmd, "PLAY") ||
!strcmp(cmd, "TITLE") || !strcmp(cmd, "QUIT")) {
// Parsujemy *liczbe* - id playera. Potem ma nic nie byc.
char *num = parse_token(&line, delimiters);
if (!num) {
utils_block_printf(file, "ERROR No player id given in %s command\n", cmd);
continue;
}
if (parse_token(&line, delimiters)) {
utils_block_printf(file, "ERROR Too long %s command\n", cmd);
continue;
}
char *badpos;
long player_id = strtol(num, &badpos, 10);
if (*badpos) {
utils_block_printf(file, "ERROR Invalid player id format in %s command\n", cmd);
continue;
}
// Jak sie udalo, wysylamy UDP do playera.
send_op_to_player(cmd, player_id, telnet->udp_fd, file);
} else {
// Nie trafiles z komenda!
utils_block_printf(file, "ERROR Unrecognized command\n");
}
}
telnet_cleanup:
// Handler czyszczacy sesje telneta.
close(telnet->udp_fd);
cleanup_telnet(client_fd);
utils_free_buf(file);
return NULL;
#undef MAX_TELNET_LINE
}
// Watek czyszczacy playery.
static void* cleaner_thread(void *param) {
(void)param;
while (true) {
// Czekamy na kolejce na zdarzenia czyszczenia playerow (same nie umieja sie
// wyczyscic).
safe_fifo_wait_for_elem(&master_config.player_terms);
struct safe_fifo_elem *elem = safe_fifo_front(&master_config.player_terms);
int id = elem->id;
// Usuwamy info o zakoczeniu z kolejki - mamy juz id.
safe_fifo_erase(&master_config.player_terms, elem);
debug("Cleaning player with id %d\n", id);
// Bierzemy playera.
struct safe_fifo_elem *player_elem = safe_fifo_front_by_id(&master_config.player_conns, id);
if (!player_elem) {
debug("Weird, player with id %d not found\n", id);
continue;
}
// Niszczymy bufor telneta dla tego playera.
struct player_conn_config *player = (struct player_conn_config*)player_elem->elem;
struct ssh_conn_config *ssh = &player->ssh;
utils_block_printf(ssh->telnet_buf, "Player id %d ended\n", id);
utils_free_buf(ssh->telnet_buf);
// Wyrzucamy playera z kolejki.
safe_fifo_erase(&master_config.player_conns, player_elem);
}
return NULL;
}
static void run_cleaner() {
safe_fifo_init(&master_config.player_terms);
RUN_THREAD_CMD(pthread_create, &master_config.cleaner_thread, NULL, cleaner_thread, NULL);
}
static void run_server() {
// Ustawiamy odpowiednie kolejki i muteksy.
safe_fifo_init(&master_config.telnet_conns);
safe_fifo_init(&master_config.player_conns);
pthread_mutex_init(&master_config.ssh_read_mutex, NULL);
while (true) {
// Czekamy (blokujaco, jestesmy w koncu oddzielnym watkiem!) na polaczenia telneta.
debug("Waiting on acceptance\n");
int new_socket = accept(master_config.listen_socket, NULL, NULL);
struct telnet_conn_config *conn = calloc(sizeof(struct telnet_conn_config), 1);
conn->telnet_fd = new_socket;
debug("my id = %d\n", new_socket);
safe_fifo_push_back(&master_config.telnet_conns, conn, new_socket);
// Mamy nowego ochotnika, tworzymy mu nowy watek.
RUN_THREAD_CMD(pthread_create, &conn->telnet_thread, NULL, telnet_connection, conn);
}
safe_fifo_destroy(&master_config.player_conns);
safe_fifo_destroy(&master_config.telnet_conns);
pthread_mutex_destroy(&master_config.ssh_read_mutex);
}
int main(int argc, char **argv) {
srand((unsigned)time(NULL));
process_args(argc, argv);
setup_telnet();
run_cleaner();
run_server();
}
|
C
|
/**
* Driver for a SD Card
* @file sd.h
* @author Stefan Profanter
* @author Sean Labastille
*/
#ifndef __SD_H__
#define __SD_H__
#include <spi/spi.h>
#include <common.h>
#include <drivers/display/display.h>
#define CMD0 0
#define CMD1 100
#define CMD8 1
#define CMD16 2
#define CMD17 3
#define CMD24 7
#define CMD55 4
#define ACMD41 5
#define CMD58 6
#define R1 1
#define R1b 2
#define R2 3
#define R3 4
#define R7 5
///SD block size define
#define SD_BLOCK_SIZE 512
/// Initialize SD card
int sd_init (void);
/**
* \brief send sd command
* sends an commad with arguments to the sd card
* @param command_nr is the number of the wanted command
* @param arguments pointer array with all arguments to be passed
*/
void sd_send_command (uint8_t command_nr, uint8_t *arguments);
/**
* \brief read bytes from sd
* reads bytes on sd card at addr into buffer
* @param addr address on sd card to where start reading
* @param read_buffer pointer where the read data will be saved to
* @param size of how much will be read
*/
uint8_t sd_read_bytes (uint32_t addr, uint8_t *read_buffer, uint16_t size);
/**
* \brief write bytes to sd
* writes bytes from a buffer to th sd card
* @param addr on sd card where to start rading
* @param write_buffer pointer to the data to write to sd
* @param size of the data to write
*/
uint8_t sd_write_bytes (uint32_t addr, uint8_t *write_buffer, uint16_t size);
uint8_t read_block(uint32_t block_addr, uint8_t *read_buffer);
uint8_t write_block(uint32_t block_addr, uint8_t *write_buffer);
#endif
|
C
|
int Zero_Ex_Operator(int ref,int max);
int Ex_Sy(int size,int num);
int Zero_Ex_Operator(int ref,int max)
{
//int i;//min=0
if(ref>max-1 || ref<0)
{
return 0;
}
else
{
return 1;
}
}
int Ex_Sy(int size,int num)
{
// For WS,WA
// num :refer_point
// size:(size = width or height)
if(num >= size)
return (size-1)*2 - num;
return abs( num );
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int check_if_module_loaded(char* module)
{
char str[50];
char cmd_str[50];
int size = 0;
int usage = 0;
int rc = 0;
FILE *fp = NULL;
sprintf(cmd_str, "lsmod | grep %s > /tmp/lsmod.txt", module);
rc = system(cmd_str);
printf("%s check rc = %d -> %d\n", __func__, rc, WEXITSTATUS(rc));
fp = fopen("/tmp/lsmod.txt", "r");
if(fp == NULL) {
printf("Failed to open lsmod.txt");
return -1;
}
fscanf(fp, "%s %d %d", str, &size, &usage);
printf( "module:%s \nsize:%d \nusage:%d\n", str, size, usage);
fclose(fp);
if(strcmp(module, str) == 0) {
printf("Module %s already loaded\n", module);
}
else {
printf("Module %s is not loaded\n", module);
return 1;
}
if(usage != 0) {
printf("ERROR: Module bing used by some one else\n");
return -1;
}
return 0;
}
int main(void)
{
if(check_if_module_loaded("diag_fpga") != 0) {
printf("Issue checking if module opend\n");
}
}
|
C
|
#include<stdio.h>
int main(){
int x[1000];
int i;
for(i=0;i<1000;i++)
{
scanf("%d",&x[i]);
if(x[i]==1)
break;
}
for(i=0;i<1000;i++)
{
if(x[i]==1)
break;
printf("%c",x[i]);
}
return 0;
}
|
C
|
/*Author Name: Balasubramanian R
Github Link: https://github.com/Cyberkid2311 */
/*Ported to C by : Deepak Chauhan
Github Profile: https://github.com/RoyalEagle73
*/
/* The main aim of this program is to find the Number of turns made at the end
and not during the process. So We count the number of Rotations made at the End
and print the string accordingly */
#include<stdio.h>
#include<string.h>
int main() {
int n;
scanf("%d",&n);
char s[1000000];
scanf("%s",s);
int q;
scanf("%d",&q);
long c = 0;
while(q--) {
char t;
int l;
scanf("%c %d",&t,&l);
if (t == 'l')
{
c += l; //If the string is rotated left side then the count is increased by l
}
else
{
c -= l; //If the string is rotated right side,then the count is decreased by l
}
}
if (c >= 0)
{
c %= strlen(s); /*When the count reached the value of the size,
then the string becomes the same as original string
so we use the modulus function and fix the value of c */
}
else
{
c = -c; /* If the sum of values of right dominates the sum of values of left,
the value of c becomes negative. So we make it positive for easy accessibility */
c = strlen(s) - (c % strlen(s)); /* We reduce the value of c from Size*/
c %= strlen(s);
}
// printf("%s",s.substr(c, strlen(s) - c));
substr(&s,c+1,strlen(s)-c);
substr(&s,0,c);
// printf("\n");
// printf("%s\n",s.substr(0, c));
}
void substr(char *st, int beg, int last){
// printf("%d %d\n", beg,last);
for(int i=beg; i<=last; i++)
printf("%c", st[i]);
}
// ---TEAM SCA---
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "tree.h"
int get_priority(char c)
{
switch(c) {
case '+': case '-': return 1;
case '*': case '/': return 2;
case '^': return 3;
}
return 20; // Priority of numbers, brackets, variables, etc
}
Tree tree_create(Token *tokens, int idx_left, int idx_right)
{
Tree t = (Tree)malloc(sizeof(struct _tree));
if (idx_left > idx_right)
return NULL;
if (idx_left == idx_right) {
t->node = tokens[idx_left];
t->left = NULL;
t->right = NULL;
return t;
}
int priority = 0;
int priority_min = get_priority('a');
int brackets = 0;
int op_pos = 0;
for (int i = idx_left; i < idx_right; ++i) {
if ((tokens[i].type == BRACKET) && tokens[i].data.is_left_bracket) {
++brackets;
continue;
}
if ((tokens[i].type == BRACKET) && !tokens[i].data.is_left_bracket) {
--brackets;
continue;
}
if (brackets > 0)
continue;
if (tokens[i].type == OPERATOR) {
priority = get_priority(tokens[i].data.operator);
if (priority <= priority_min) {
priority_min = priority;
op_pos = i;
}
}
}
if ((priority_min == get_priority('a')) &&
(tokens[idx_left].type == BRACKET) &&
tokens[idx_left].data.is_left_bracket &&
(tokens[idx_right].type == BRACKET) &&
!tokens[idx_right].data.is_left_bracket) {
free(t);
return tree_create(tokens, idx_left + 1, idx_right - 1);
}
if (tokens[op_pos].data.operator == '^') {
brackets = 0;
for (int i = op_pos; i >= idx_left; --i) {
if ((tokens[i].type == BRACKET) && !(tokens[i].data.is_left_bracket)) {
++brackets;
continue;
}
if ((tokens[i].type == BRACKET) && (tokens[i].data.is_left_bracket)) {
--brackets;
continue;
}
if (brackets > 0) {
continue;
}
if (tokens[i].type == OPERATOR) {
priority = get_priority(tokens[i].data.operator);
if (priority == 3) {
op_pos = i;
}
}
}
}
t->node = tokens[op_pos];
t->left = tree_create(tokens, idx_left, op_pos - 1);
t->right = tree_create(tokens, op_pos + 1, idx_right);
if (t->right == NULL) {
fprintf(stderr, "Error: operator at the expression's end.");
exit(1);
}
return t;
}
void tree_destroy(Tree *t)
{
if ((*t) != NULL) {
tree_destroy(&((*t)->left));
tree_destroy(&((*t)->right));
}
free(*t);
*t = NULL;
}
void tree_print(Tree t, int depth)
{
if (t != NULL) {
for (int i = 0; i < depth; ++i) {
printf("\t");
}
token_print(&(t->node));
printf("\n");
tree_print(t->left, depth + 1);
tree_print(t->right, depth + 1);
}
}
void tree_infix(Tree t)
{
if (t != NULL) {
if (t->left && t->right)
printf("(");
tree_infix(t->left);
token_print(&(t->node));
tree_infix(t->right);
if (t->right && t->left)
printf(")");
}
}
void tree_simplify(Tree t)
{
if (t->left) {
tree_simplify(t->left);
}
if (t->right) {
tree_simplify(t->right);
}
if (t->node.type == OPERATOR && t->node.data.operator == '/') {
if (t->right->node.data.value_int == 1) {
if(t->right->left == NULL) {
t->right = t->right->right;
free(t->right);
} else if (t->right->right == NULL) {
t->right = t->right->left;
free(t->right);
}
t->node.data.operator = NULL;
t = t->left;
}
}
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(){
int n,i;
char v[100000];
scanf("%d", &n);
strcpy(v,"Feliz nata");
i=9;
while(n--){
v[i] = 'a';
i++;
}
printf("%sl!\n", v);
return 0;
}
|
C
|
#include <stdio.h>
#include "records.h"
int main(){
int i;
/* ask user what he wants to know
choices include:
winning seasons (above .500)
losing seasons (below .500)
seasons with 10 or more wins
undefeated seasons
seasons with equal wins and losses
bowl eligible seasons
*/
int response;//for gathering user's response
int y=1;
int currentyear=113;//+1900=2013
while(y==1){
printf("What would you like to know?\n1: Winning seasons (above .500)\n2: Losing seasons (below .500)\n3: Seasons with equal wins and losses\n4: Seasons with 10 or more wins\n5: Undefeated seasons\n6: Bowl-eligible seasons (above or equal to .500)\n7: Quit\nPlease enter your response: ");
scanf("%i", &response);
switch(response){
case 1:
printf("The winning seasons are:\n");
for(i=0; i<currentyear; i++){
if(wins[i]>losses[i]){
printf("%i\n",1900+i);
}
}
break;
case 2:
printf("The losing seasons are:\n");
for(i=0; i<currentyear; i++){
if(wins[i]<losses[i]){
printf("%i\n",1900+i);
}
}
break;
case 3:
printf("The .500 seasons (with equal wins and losses) are:\n");
for(i=0; i<currentyear; i++){
if(wins[i]==losses[i]){
printf("%i\n",1900+i);
}
}
break;
case 4:
printf("The seasons the Irish got 10 or more wins are:\n");
for(i=0; i<currentyear; i++){
if(wins[i]>=10){
printf("%i\n",1900+i);
}
}
break;
case 5:
printf("The undefeated seasons are:\n");
for(i=0; i<currentyear; i++){
if(losses[i]==0){
printf("%i\n",1900+i);
}
}
break;
case 6:
printf("The bowl-eligible seasosn are:\n");
for(i=0; i<currentyear; i++){
if(wins[i]>losses[i]){
printf("%i\n",1900+i);
}
}
break;
case 7:
y=0;
break;
default:
printf("Please enter a valid command.\n");
}
}
return 0;
}
|
C
|
/*
* tape2disk.c
*
* MPX uses 2 EOF in a row to separate sections of MPX3.x master SDT tapes.
* It uses 3 EOF in a row to indicate the EOT on MPX 3.X tapes. So we
* cannot assume EOT is at the 1st or 2nd EOF in a row. We keep looking
* for a third one. For user SDT tapes or MPX 1.X master SDT tapes use
* option -f for 2 EOFs. Use option -v for 3 eof's on VOLM tapes. For
* non MPX tapes, the 2nd EOF means EOT. Some tapes (Unix) have only one
* EOF and will terminate on EOT detected. Leave off the output file name
* to just scan the tape and output record sizes and counts.
*/
#include <stdio.h>
#include <sys/types.h>
//#include <sys/mtio.h>
#include <stdlib.h> /* for exit() */
#ifdef _WIN32
#include <fcntl.h> /* for O_RDONLY, O_WRONLY, O_CREAT */
#include <io.h> /* for _read, _open, _write, _close */
#define open _open
#define read _read
#define write _write
#define close _close
#else
#include <sys/fcntl.h> /* for O_RDONLY, O_WRONLY, O_CREAT */
#include <unistd.h> /* for open, read, write */
#include <sys/signal.h>
#endif
#if defined(_MSC_VER) && (_MSC_VER < 1600)
typedef __int8 int8;
typedef __int16 int16;
typedef __int32 int32;
typedef unsigned __int8 uint8;
typedef unsigned __int16 uint16;
typedef unsigned __int32 uint32;
typedef signed __int64 t_int64;
typedef unsigned __int64 t_uint64;
//typedef t_int64 off_t;
#else
/* All modern/standard compiler environments */
/* any other environment needa a special case above */
#include <stdint.h>
typedef int8_t int8;
typedef int16_t int16;
typedef int32_t int32;
typedef uint8_t uint8;
typedef uint16_t uint16;
typedef uint32_t uint32;
#endif /* end standard integers */
//#define FMGRTAPE /* defined for filemgr tapes, undefined for volmgr tape */
int usefmgr = 1; /* use fmgr format with 2 EOF's, else 3 EOF's */
char *buff; /* buffer for read/write */
int filen = 1; /* file number being processed */
long count=0, lcount=0; /* number of blocks for file */
#ifndef _WIN32
extern void RUBOUT(); /* handle user DELETE key signal */
#endif
off_t size=0, tsize=0; /* number of bytes in file, total */
int ln;
char *inf, *outf;
int copy;
int32 size_256K = 256 * 1024;
int main(argc, argv)
int argc;
char **argv;
{
int n, nw, inp, outp;
// struct mtop op;
int32 buf_size = size_256K;
int EOFcnt = 0; /* count the number of EOFs in a row. */
char *name = *argv;
char *p = *++argv;
if (argc <= 1 || argc > 4) {
fprintf(stderr, "Usage: tape2disk -vf src [dest]\n");
exit(1);
}
if (*p == '-') {
char ch = *++p;
argc--; /* one less arg */
if (ch == 'v')
usefmgr = 0; /* use volmgr format */
else
if (ch == 'f')
usefmgr = 1; /* use fmgr format */
else {
fprintf(stderr, "Invalid option %c\n", ch);
fprintf(stderr, "Usage: tape2disk -vf src [dest]\n");
exit(1);
}
}
inf = argv[1];
if (argc == 3) {
outf = argv[2];
copy = 1;
}
if ((inp = open(inf, O_RDONLY, 0666)) < 0) {
fprintf(stderr, "Can't open %s\n", inf);
exit(1);
}
if (copy) {
/* open output file, create it if necessary */
if ((outp = open(outf, O_WRONLY|O_CREAT, 0666)) < 0) {
fprintf(stderr, "Can't open %s\n", outf);
exit(3);
}
}
/* get a 256k buffer */
if ((buff = malloc(buf_size)) == NULL) {
fprintf(stderr, "Can't allocate memory for tapecopy\n");
exit(4);
}
#ifndef _WIN32
if (signal(SIGINT, SIG_IGN) != SIG_IGN)
(void)signal(SIGINT, RUBOUT);
#endif
ln = -2;
for (;;) {
count++;
/* read record */
while ((n = read(inp, buff, buf_size)) < 0) {
perror("Unknown read error");
// errno = 0;
exit(6); /* abort on error, comment out to ignore tape errors */
}
if (n > 0) {
/* we read some data, see if scanning or writing */
EOFcnt = 0; /* not at EOF anymore */
if (copy) {
int32 n1, n2;
/* we have data to write */
int32 hc = (n + 1) & ~1; /* make byte count even */
int32 wc = n; /* get actual byte count */
/* write actual byte count to 32 bit word as header */
n1 = write(outp, (char *)(&wc), (int32)4);
/* write the data mod 2 */
nw = write(outp, buff, (int32)hc);
/* write the byte count in 32 bit word as footer */
n2 = write(outp, (char *)(&wc), (int32)4);
if (n1 != 4 || nw != hc || n2 != 4) {
fprintf(stderr, "write (%d) !=" " read (%d)\n", nw, n);
fprintf(stderr, "COPY " "Aborted\n");
exit(5);
}
}
size += n; /* update bytes read */
if (n != ln) { /* must be last record of file if different */
if (ln > 0) {
/* we read something */
if ((count - lcount) > 1)
printf("file %d: records %ld to %ld: size %d\n",
filen, lcount, count - 1, ln);
else
printf("file %d: record %ld: size %d\n", filen, lcount, ln);
}
ln = n; /* save last record size */
lcount = count; /* also record count */
}
} else {
/* we did not read data, it must be an EOF */
/* if ln is -1, last operation was EOF, now we have a second */
/* see if fmgr or volm */
if (usefmgr) {
/* filemgr has 2 EOF's at end of tape */
if (++EOFcnt > 1) {
/* two EOFs mean we are at EOT */
printf("fmgr eot\n");
break;
}
} else {
/* volmgr has 3 EOF's at end of tape */
if (++EOFcnt > 2) {
/* three EOFs mean we are at EOT on MPX */
printf("volm eot\n");
break;
}
}
if (ln > 0) {
if ((count - lcount) > 1)
printf("file %d: records %ld to %ld: size %d\n",
filen, lcount, count - 1, ln);
else
printf("file %d: record %ld: size %d\n", filen, lcount, ln);
}
if (usefmgr) {
printf("file %d: eof after %ld records: %ld bytes\n",
filen, count - 1, size);
} else {
if (EOFcnt == 2) /* if 2nd EOF, print file info */
printf("second eof after %d files: %ld bytes\n", filen, size);
}
if (copy) {
/* write a sudo EOF to disk file as a zero 4 byte record */
int n1, hc = 0;
/* write the EOF */
/* write a zero as the byte count in 32 bit word as EOF */
n1 = write(outp, (char *)(&hc), (int32)4);
if (n1 != 4) {
perror("Write EOF");
exit(6);
}
}
if (usefmgr)
filen++; /* advance number of files */
else
if (EOFcnt < 2) /* not really a file if 2nd EOF */
filen++; /* advance number of files */
count = 0; /* file record count back to zero */
lcount = 0; /* last record count back to zero */
tsize += size; /* add to total tape size */
size = 0; /* file size back to zero */
ln = n; /* set ln to -1 showing we are at EOF */
}
}
if (copy) {
/* write a sudo EOM to disk file as a -1 4 byte record */
int32 n1, hc = 0xffffffff;
/* write the EOM to disk */
/* write a -1 as the byte count in 32 bit word as EOM */
n1 = write(outp, (char *)(&hc), (size_t)sizeof(hc));
if (n1 != 4) {
perror("Write EOM");
return(6);
}
(void)close(outp);
}
/* print out total tape size in bytes */
(void)printf("total length: %ld bytes\n", tsize);
exit(0);
}
#ifndef _WIN32
/* entered when user hit the DELETE key */
void RUBOUT()
{
if (count > lcount)
--count;
if (count)
if (count > lcount)
(void)printf("file %d: records %ld to %ld: size" " %d\n", filen, lcount, count, ln);
else
(void)printf("file %d: record %ld: size %d\n", filen, lcount, ln);
(void)printf("interrupted at file %d: record %ld\n", filen, count);
(void)printf("total length: %ld bytes\n", tsize + size);
exit(1);
}
#endif
|
C
|
// $Id: rint.c 1.2 2009/01/13 08:47:50EST 729915 Development $
//
// Math functions from GNU compiler.
#pragma once
#include "gnumath.h"
/// <summary>Rounds to the nearest integer by adding 0.5 to a double
/// or floating point number and casting to an integer, truncating the
/// decimal.</summary>
///
/// <returns>The argument rounded to the nearest integer.</returns>
///
/// <param name="x">The value to be rounded.</param>
double rint( double x )
{
return (double)((int)(x + 0.5));
}
|
C
|
/* main.c ---
*
* Filename: main.c
* Description: Lab 4, word count
* Author: Michael McCann: mimccann
* Partner: Samuel Carter: sambcart
* Maintainer: Michael McCann
* Created: 02/02/17
* Last-Updated: 02/09/17
* By: Michael McCann
* Update #: 1
*
*/
/* Change log:
* Added comments
*
*/
/* Code: */
#include <f3d_uart.h>
#include <stdio.h>
#include <stm32f30x.h> // Pull in include files for F30x standard drivers
#include <f3d_led.h> // Pull in include file for the local drivers
// Simple looping delay function
void delay(void) {
int i = 2000000;
while (i-- > 0) {
asm("nop"); /* This stops it optimising code out */
}
}
int main(void) {
f3d_uart_init();
setvbuf(stdin, NULL, _IONBF, 0);
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
int c ; // used to check current char value
int wc = 0; // used to count words
int l = 0; // used to count lines
int ch = 0; // used to count chars
int prev = 1; // used to check what prev is, 1 = non space char, 0 = space char
int curr = 1; // same as prev, but used as current
// runs until End of File char is found
while((c = getchar()) != 0x1b){
switch (c){ // will find firs true and run all until first found break below it
case ' ': // literal space char
case '\t': // literal tab char
case '\r': // literal carriage return char
case '\f': // literal from feed char
case '\v': curr = 0; curr = 0; break; // literal vertical tab char
case '\n': curr = 0; l++; curr = 0; break; // literal newline char
default: curr = 1; // any other char
}
ch++; // increments char
if(!curr && prev){ // checks for current to be space char and prev to be non space char
wc++; // increments word count
}
prev = curr; // sets previous char as current
}
printf("words: %d\nChars: %d\nLines: %d\n", wc, ch, l);
}
#ifdef USE_FULL_ASSERT
void assert_failed(uint8_t* file, uint32_t line) {
/* Infinite loop */
/* Use GDB to find out why we're here */
while (1);
}
#endif
/* main.c ends here */
|
C
|
# include <stdio.h>
# include <sys/time.h>
# include <unistd.h>
# include <sys/types.h>
# include <stdlib.h>
# include <sys/wait.h>
# include <pthread.h>
# define amount 100000000
static int arr[amount];
static int a = 50, ans;
// static int count = 0;
static int thread_num = 10;
static int i_create;
static int i_c[amount];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* counting(void* k){
printf("[child %ld]call lock \n", pthread_self());
pthread_mutex_lock( &mutex );
printf("[child %ld]do counting %d\n", pthread_self(), *((int *)k));
int len = (int)(sizeof(arr)/sizeof(arr[0]));
int c_s = len/thread_num * *((int *)k);
int count = 0;
for (int j = c_s; j<( c_s+len/thread_num); j++){
// printf("%d ", arr[j]);
if (arr[j] == a){
count++;
}
}
ans += count;
printf("[child %ld]ans complete \n", pthread_self());
pthread_mutex_unlock( &mutex );
printf("\n");
printf("[child %ld]count: %d\n", pthread_self(), count);
pthread_exit((void *)count);
}
int main(int argc, char *argv[]){
// int datasize = atoi(argv[1]);
// thread_num = atoi(argv[2]);
struct timeval start, end;
void *result = 0;
pthread_t tid[thread_num];
for (int i=0; i<amount; i++){
arr[i] = i;
i_c[i] = i;
}
// printf("arr= \n");
int len = (int)(sizeof(arr)/sizeof(arr[0]));
int c_s = 0;
// for (int i =0; i< len; i++) printf("%d ", arr[i]);
// printf("\n");
gettimeofday(&start, NULL);
for (i_create = 0; i_create < thread_num; i_create++){
printf("[main]i=%d\n", i_create);
pthread_create(&tid[i_create], NULL, counting, &i_c[i_create]);
printf("[main]created: %ld %d\n", tid[i_create], i_c[i_create]);
// pthread_create(&tid, NULL, counting, (void *)&i);
}
// printf("[main]wait\n");
for (int i =0; i<thread_num; i++){
printf("[main]join\n");
pthread_join(tid[i], NULL);
// pthread_join(tid[i], (void*)&result);
// printf("[main]count: %d\n", result);
// ans += ((int)result);
}
gettimeofday(&end, NULL);
printf("[main]count of %d = %d\n", a, ans);
printf("process time: %ld microseconds\n", ((end.tv_sec - start.tv_sec)*1000000 + (end.tv_usec - start.tv_usec)));
return 0;
}
|
C
|
/*
* Delta programming language
*/
#include "DeltaCompiler.h"
#include "delta/macros.h"
#include "delta/structs/DeltaClass.h"
struct DeltaCompiler* new_DeltaCompiler(int total_objects)
{
struct DeltaCompiler *c = (struct DeltaCompiler*) malloc(sizeof(struct DeltaCompiler));
int i;
c->alloc_functions = DELTA_MAX_FUNCTIONS;
c->total_functions = 0;
c->functions = (struct DeltaCompiledFunction*)
calloc(c->alloc_functions, sizeof(struct DeltaCompiledFunction));
c->alloc_classes = 100;
c->total_classes = 0;
c->classes = (struct DeltaClass**)
calloc(c->alloc_classes, sizeof(struct DeltaClass*));
for(i = 0; i < c->alloc_classes; ++i)
c->classes[i] = new_DeltaClass();
for(i = 0; i < c->alloc_functions; ++i) {
c->functions[i].alloc_ins = 100;
c->functions[i].total_ins = 0;
c->functions[i].ins = (struct DeltaInstruction*)
calloc(c->functions[i].alloc_ins, sizeof(struct DeltaInstruction));
c->functions[i].alloc_vars = 100;
c->functions[i].total_vars = 0;
c->functions[i].vars = (struct DeltaVariable*)
calloc(c->functions[i].alloc_vars, sizeof(struct DeltaVariable));
c->functions[i].alloc_labels = 100;
c->functions[i].total_labels = 0;
c->functions[i].labels = (struct DeltaLabel*)
calloc(c->functions[i].alloc_labels, sizeof(struct DeltaLabel));
c->functions[i].alloc_constants = 100;
c->functions[i].total_constants = 0;
c->functions[i].constants = (struct DeltaVariable*)
calloc(c->functions[i].alloc_constants, sizeof(struct DeltaVariable));
}
return c;
}
void free_DeltaCompiler(struct DeltaCompiler *c)
{
int i;
for(i = 0; i < c->alloc_functions; ++i) {
free(c->functions[i].ins);
free(c->functions[i].vars);
free(c->functions[i].labels);
free(c->functions[i].constants);
}
free(c->functions);
free(c);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int arr1[] = { 3, 5, 38, 44, 47 };
int arr2[] = { 3, 44, 38, 5, 47 };
int arr3[] = { 2, 15, 26, 27, 36 };
int arr4[] = { 15, 36, 27, 2, 26 };
printf("--> urutan arr1 benar %d\n",cek_urut(arr1, 5));
printf("--> urutan arr2 salah %d\n",cek_urut(arr2, 5));
printf("--> urutan arr3 benar %d\n",cek_urut(arr3, 5));
printf("--> urutan arr4 salah %d\n",cek_urut(arr4, 5));
return 0;
}
|
C
|
#include <stdio.h>
void clear(){
while(getchar()!='\n');
}
int main(void){
int input;
int returnFromScanf;
printf("enter a number: ");
returnFromScanf=scanf("%d",&input);
while(returnFromScanf!=1){
clear();
printf("enter a number: ");
returnFromScanf=scanf("%d",&input);
}
printf("you entered: %d\n",input);
}
|
C
|
/*****************************************************************************
* Program Description: The client side of a chat app implemented in C. The
* user on this end takes turns sending messages to server side. This
* program takes 2 arguments on the command line: the host name and port
* number, in that order.
* Name: Danielle Goodman
* Date: 2/12/2018
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
//header info for functions located below with function definitions
int setupConnection(int portNum, char *hostName);
int sendMessage(int socket, char *handle);
int receiveMessage(int socket);
int main(int argc, char *argv[]) {
int quit1; //bool value - if the user inputs or client receives "\quit"
int socket;
char handle[11];
//establish connection and return socket
socket = setupConnection(atoi(argv[2]), argv[1]);
//get user handle and prepare for appending it to sent messages
memset(handle, '\0', sizeof(handle));
printf("Please enter the user's handle\n");
fgets(handle, sizeof(handle), stdin);
handle[strlen(handle) - 1] = '\0';
//enters infinite loop and continues exchanging messages with the
//server until one of them enteres the command "\quit". The value
//returned to the quit variable represents if the quit command
//was entered or received
while (1) {
quit = sendMessage(socket, handle);
if (quit) {
close(socket);
exit(0);
}
quit = receiveMessage(socket);
if (quit) {
close(socket);
exit(0);
}
}
return 0;
}
/********************************************************************
* Description: this function receives a message from the server side
* and returns the value "1" if the message received is "\quit"
* or prints the message to the screen if any other message is
* received
* Inputs: and int that represents the socket connection
* Outputs: int value of 1 or 0 representing whether or not to quit
* the chat based on the message received
********************************************************************/
int receiveMessage(int socket) {
int quitChat = 0;
char recvMessage[500];
memset(recvMessage, '\0', sizeof(recvMessage));
recv(socket, recvMessage, sizeof(recvMessage), 0);
//is message "\quit"
if (strcmp(recvMessage, "\\quit") == 0) {
printf("QUITTING CHAT\n");
quitChat = 1;
return quitChat; //return here before message can be printed
}
printf("%s\n", recvMessage);
return quitChat;
}
/*******************************************************************
* Description: This function sends a user-entered message to the
* server. It prompts the user to enter a message and checks
* if the message is "\quit". If so, sets quitChat variable
* to 1 and sends the message. Otherwise, appends the user
* handle to the message and sends to server
* Inputs: An int representing the socket connection and a pointer
* to char that represents the user-entered handle. This handle
* is appended to all sent messages
* Outputs: An int used as bool value representing whether or not
* to quit the chat based on message entered by user
*******************************************************************/
int sendMessage(int socket, char *handle) {
int quitChat = 0;
char buffer[500];
char displayMessage[515];
memset(displayMessage, '\0', sizeof(buffer));
//get message to send
printf("%s> ", handle);
memset(buffer, '\0', sizeof(buffer));
fgets(buffer, sizeof(buffer), stdin);
//check if entered message is command to quit
if (strcmp(buffer, "\\quit\n") == 0) {
printf("QUITTING CHAT\n");
quitChat = 1;
buffer[strlen(buffer) - 1] = '\0';
send(socket, buffer, strlen(buffer), 0);
return quitChat;
}
//append handle to message sent
strcat(displayMessage, handle);
strcat(displayMessage, "> ");
strcat(displayMessage, buffer);
displayMessage[strlen(displayMessage) - 1] = '\0';
send(socket, displayMessage, strlen(displayMessage), 0);
return quitChat;
}
/******************************************************************
* Description: This function sets up the connection with the
* server
* Inputs: An int representing the port number and and pointer to
* char representing the host name of the server the program
* will connect to. Both values are entered by the user when
* the start the program
* Outputs: An int representing the socket connection that was
* established
******************************************************************/
int setupConnection(int portNumber, char *hostName) {
int socketfd;
struct sockaddr_in serverAddress;
struct hostent *server;
memset((char*)&serverAddress, '\0', sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(portNumber);
server = gethostbyname(hostName);
memcpy((char*)&serverAddress.sin_addr.s_addr, (char*)server->h_addr, server->h_length);
socketfd = socket(AF_INET, SOCK_STREAM, 0);
connect(socketfd, (struct sockaddr*)&serverAddress, sizeof(serverAddress));
printf("READY TO SEND TO SERVER\n");
return socketfd;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int arr[8] = { 3,4,6,1,2,10,9,8 };
// 보조 함수
void printAll(int len , int target[]){
if(len <= 0) { printf("{ }"); }
else{
printf("{");
for(int i = 0 ; i < len ; i++){
printf(" %d " , target[i]);
if(i < len-1){ printf(","); }
}
printf("}\n");
}
}
void printAll_Highlight(int len , int target[] , int highlight_index){
if(len <= 0) { printf("{ }"); }
else{
printf("{");
for(int i = 0 ; i < len ; i++){
if(highlight_index == i){
printf(" [ %d ]" , target[i]);
}
else{
printf(" %d " , target[i]);
}
if(i < len-1){ printf(","); }
}
printf("}\n");
}
}
// 1. partition
void partition(int low , int high , int *pivotpoint){
printf("partition method called !! low : %d , high : %d\n" , low , high );
printf("partition target : ");
printAll_Highlight(8,arr,low);
// 최초에는 첫 아이템을 기준으로 한다.
int pivotitem = arr[low];
int j = low; int temp;
for(int i = low + 1 ; i <= high ; i++){
if(arr[i] < pivotitem) {
j++;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
*pivotpoint = j;
temp = arr[low];
arr[low] = arr[*pivotpoint];
arr[*pivotpoint] = temp;
//printf("in partiion method !! j : %d pivotpoint : %d low : %d\n" , j , *pivotpoint , low);
printf("partition result : ");
printAll_Highlight(8,arr, *pivotpoint);
printf("partition finished !! pivotpoint : %d \n" , *pivotpoint);
}
void quicksort(int low , int high){
int pivotpoint = 0;
printf("quicksort method called !! low : %d , high : %d\n", low , high);
if(low < high){
partition(low , high , &pivotpoint);
quicksort(low , pivotpoint -1);
quicksort(pivotpoint + 1,high);
printf("quicksort method finished !! low : %d , high: %d\n", low , high);
}
else{
printf("quicksort method skipped !! low : %d, high : %d\n", low , high);
}
}
int main(){
printf("##### quicksort start \n");
printf("target : ");
printAll(8,arr);
printf("\n");
quicksort(0,7);
printf("\n###### RESULT\n");
printAll(8 , arr);
return 0;
}
|
C
|
/*
* utilsQuestions.c
*
* Created on: 21/06/2014
* Author: jvidiri
*/
#include "utilsQuestions.h"
int acertos;
/*
* Questões e suas respostas.
* */
static const questions_t const pxQuestions[] = {
{"1) What is Friendster?","a) A brand. ","b) A city. ","c) A social network.","d) A game. ",'C'},
{"2) Complete the sentence: \"At its peak, the network had well over ______ users, many in south east Asia\".","a) 20 million ","b) 1/5 dozen ","c) 50 trillionm","d) 100 million ",'D'},
{"3) What was one of the main reasons for the collapse suffered by Friendster?","a) The name of the site has changed. ","b) Stopped working weekend. ","c) Its design changed. ","d) It did not allow people who were over 25 years old.",'C'},
{"4) Who benefited from the collapse of Friendster?","a) Google. ","b) Facebook. ","c) Club Hadware.","d) Baixaki. ",'B'},
{"5) Where did Friendster keep alive, its collapse as a social game platform?","a) America.","b) Asia. ","c) Africa. ","d) Europe. ",'B'},
{"6) What’s the main problem of Friendster, that contributed for its collapse?","a) User problems. ","b) Page redesign. ","c) Low cost-benefit. ","d) User good distribution.",'C'},
{"7) Who tried to buy Friendster?","a) Microsoft.","b) Facebook. ","c) Google. ","d) Digg. ",'C'},
{"8) In the sentence: \"Following the collapse of the social network Friendster, computer scientists have carried out a digital autopsy to find out what went wrong.\" The expression \"carried out\" can be replaced by:","a) made. ","b) make. ","c) do. ","d) change.",'A'},
{"9) When was Friendster founded, and when did it begin declining and died?","a) 2002 - 1009","b) 2003 - 2009","c) 2000 - 2008","d) 2002 - 2009",'D'},
{"10) In the sentence: \"Indeed, the collapse of Friendster has more than a passing resemblance to the collapse of Digg, a social news aggregator, following design changes that presumably altered the cost-to-benefit ratio for its users.\" The word \"Indeed\" can be replaced by ...","a) stressful ","b) in fact ","c) like that ","d) just a little",'B'},
};
void vGetResposta(int index,result_t *result) {
char chute;
printCentralize("Answer:");
fscanf(stdin," %c",&chute);
if ( (toupper(chute)) == pxQuestions[index].correctOpt) {
result->acertos++;
}else{
result->erros++;
}
}
/**
* Realiza as perguntas, retorna struct com os resultados.
* */
result_t xMakeQuestions(){
int i;
result_t result;
//init vars
result.erros = 0;
result.acertos = 0;
for(i = 0; i < sizeof(pxQuestions) / sizeof(questions_t); i++)
{
printCentralize(pxQuestions[i].question);
printCentralize(pxQuestions[i].optA);
printCentralize(pxQuestions[i].optB);
printCentralize(pxQuestions[i].optC);
printCentralize(pxQuestions[i].optD);
vGetResposta(i,&result);
clearScreen();
}
return result;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int a[4000], b[4000], c[4000], d[4000];
int m1[16000000], m2[16000000];
int mycmp(const void* a, const void* b){
return *(int *)a-*(int *)b;
}
int main(){
int n;
scanf("%d", &n);
for (int i=0; i<n; i++){
scanf("%d", &a[i]);
scanf("%d", &b[i]);
scanf("%d", &c[i]);
scanf("%d", &d[i]);
}
int k=0;
for (int i=0; i<n; i++){
for (int j=0; j<n; j++){
m1[k++]=a[i]+b[j];
}
}
k=0;
for (int i=0; i<n; i++){
for (int j=0; j<n; j++){
m2[k++]=c[i]+d[j];
}
}
n=n*n;
qsort(m1, n, sizeof(int), mycmp);
qsort(m2, n, sizeof(int), mycmp);
int l=0, r=n-1;
long long ans=0;
while(l<n && r>=0){
if (m1[l]+m2[r]<0) l++;
else if (m1[l]+m2[r]>0) r--;
else{
long long lenl=1, lenr=1;
int peg=l+1;
while(peg<n && m1[l]==m1[peg++]) lenl++;
peg=r-1;
while(peg>=0 && m2[r]==m2[peg--]) lenr++;
ans+=lenl*lenr;
r-=lenr;
l+=lenl;
}
}
printf("%lld\n", ans);
return 0;
}
|
C
|
/*
* OpenBOR - http://www.LavaLit.com
* -----------------------------------------------------------------------
* Licensed under the BSD license, see LICENSE in OpenBOR root for details.
*
* Copyright (c) 2004 - 2009 OpenBOR Team
*/
#include "Lexer.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//MACROS
/******************************************************************************
* CONSUMECHARACTER -- This macro inserts code to remove a character from the
* input stream and add it to the current token buffer.
******************************************************************************/
#define CONSUMECHARACTER \
plexer->theTokenSource[strlen(plexer->theTokenSource)] = *(plexer->pcurChar);\
plexer->theTokenSource[strlen(plexer->theTokenSource)] = '\0';\
plexer->pcurChar++; \
plexer->theTextPosition.col++; \
plexer->offset++;
/******************************************************************************
* MAKETOKEN(x) -- This macro inserts code to create a new CToken object of
* type x, using the current token position, and source.
******************************************************************************/
#define MAKETOKEN(x) \
Token_Init(theNextToken, x, plexer->theTokenSource, plexer->theTokenPosition, \
plexer->tokOffset);
/******************************************************************************
* SKIPCHARACTER -- һַ뵽plexer->theTokenSourceС
* 2007-1-22
******************************************************************************/
#define SKIPCHARACTER \
plexer->pcurChar++; \
plexer->theTextPosition.col++; \
plexer->offset++;
/******************************************************************************
* CONSUMEESCAPE -- ȡһתַһplexer->theTokenSourceΪת
* ַַοCONSUMECHARACTERꡣ
* Ŀǰֵ֧תַ\r\n\t\s\"\'\\
* 2007-1-22
******************************************************************************/
#define CONSUMEESCAPE \
switch ( *(plexer->pcurChar))\
{\
case 's':\
plexer->theTokenSource[strlen(plexer->theTokenSource) - 1] = ' ';\
break;\
case 'r':\
plexer->theTokenSource[strlen(plexer->theTokenSource) - 1] = '\r';\
break;\
case 'n':\
plexer->theTokenSource[strlen(plexer->theTokenSource) - 1] = '\n';\
break;\
case 't':\
plexer->theTokenSource[strlen(plexer->theTokenSource) - 1] = '\t';\
break;\
case '\"':\
plexer->theTokenSource[strlen(plexer->theTokenSource) - 1] = '\"';\
break;\
case '\'':\
plexer->theTokenSource[strlen(plexer->theTokenSource) - 1] = '\'';\
break;\
case '\\':\
plexer->theTokenSource[strlen(plexer->theTokenSource) - 1] = '\\';\
break;\
default:\
CONSUMECHARACTER;\
CONSUMECHARACTER;\
MAKETOKEN( TOKEN_ERROR );\
return E_FAIL;\
}\
plexer->pcurChar++; \
plexer->theTextPosition.col++; \
plexer->offset++;
//Constructor
void Token_Init(Token* ptoken, MY_TOKEN_TYPE theType, LPCSTR theSource, TEXTPOS theTextPosition, ULONG charOffset)
{
ptoken->theType = theType;
ptoken->theTextPosition = theTextPosition;
ptoken->charOffset = charOffset;
strcpy(ptoken->theSource, theSource );
}
void Lexer_Init(Lexer* plexer, LPCSTR theSource, TEXTPOS theStartingPosition)
{
plexer->ptheSource = theSource;
plexer->theTextPosition = theStartingPosition;
plexer->pcurChar = (CHAR*)plexer->ptheSource;
plexer->offset = 0;
plexer->tokOffset = 0;
/*pl = plexer;*/
}
void Lexer_Clear(Lexer* plexer)
{
memset(plexer, 0, sizeof(Lexer));
}
/******************************************************************************
* getNextToken -- Thie method searches the input stream and returns the next
* token found within that stream, using the principle of maximal munch. It
* embodies the start state of the FSA.
*
* Parameters: theNextToken -- address of the next CToken found in the stream
* Returns: S_OK
* E_FAIL
******************************************************************************/
HRESULT Lexer_GetNextToken(Lexer* plexer, Token* theNextToken)
{
//start a whitespace-eating loop
for(;;){
memset(plexer->theTokenSource, 0, MAX_TOKEN_LENGTH * sizeof(CHAR));
plexer->theTokenPosition = plexer->theTextPosition;
plexer->tokOffset = plexer->offset;
//Whenever we get a new token, we need to watch out for the end-of-input.
//Otherwise, we could walk right off the end of the stream.
if ( !strncmp( plexer->pcurChar, "\0", 1)){ //A null character marks the end
//of the stream
MAKETOKEN( TOKEN_EOF );
return S_OK;
}
//getNextToken eats whitespace
//newline
else if ( !strncmp( plexer->pcurChar, "\n", 1)){
//increment the line counter and reset the offset counter
plexer->theTextPosition.col = 0;
plexer->theTextPosition.row++;
plexer->pcurChar++;
plexer->offset++;
}
//tab
else if ( !strncmp( plexer->pcurChar, "\t", 1)){
//increment the offset counter by TABSIZE
plexer->theTextPosition.col += TABSIZE;
plexer->pcurChar++;
plexer->offset++;
}
//carriage return
else if ( !strncmp( plexer->pcurChar, "\r", 1)){
//reset the offset counter to zero
plexer->theTextPosition.col = 0;
//increment the line counter
//plexer->theTextPosition.row++;
plexer->pcurChar++;
plexer->offset++;
}
//line feed
else if ( !strncmp( plexer->pcurChar, "\f", 1)){
//increment the line counter
plexer->theTextPosition.row++;
plexer->pcurChar++;
plexer->offset++;
}
//space
else if ( !strncmp(plexer->pcurChar, " ", 1)){
//increment the offset counter
plexer->theTextPosition.col++;
plexer->pcurChar++;
plexer->offset++;
}
//an Identifier starts with an alphabetical character or underscore
else if ( *plexer->pcurChar=='_' || (*plexer->pcurChar>= 'a' && *plexer->pcurChar <= 'z') ||
(*plexer->pcurChar >= 'A' && *plexer->pcurChar <= 'Z')){
return Lexer_GetTokenIdentifier(plexer, theNextToken );
}
//a Number starts with a numerical character
else if ((*plexer->pcurChar >= '0' && *plexer->pcurChar <= '9') ){
return Lexer_GetTokenNumber(plexer, theNextToken );
}
//string
else if (!strncmp( plexer->pcurChar, "\"", 1)){
return Lexer_GetTokenStringLiteral(plexer, theNextToken );
}
//character
else if (!strncmp( plexer->pcurChar, "'", 1)){
//skip first ' 2007 - 1 - 22
SKIPCHARACTER;
//escape characters
if (!strncmp( plexer->pcurChar, "\\", 1)){
CONSUMECHARACTER;
CONSUMEESCAPE;
}
//must not be an empty character
else if(strncmp( plexer->pcurChar, "'", 1))
{
CONSUMECHARACTER;
}
else
{
CONSUMECHARACTER;
CONSUMECHARACTER;
MAKETOKEN( TOKEN_ERROR );
return S_OK;
}
//skip last '
if (!strncmp( plexer->pcurChar, "'", 1)){
SKIPCHARACTER;
MAKETOKEN( TOKEN_STRING_LITERAL );
return S_OK;
}
else{
CONSUMECHARACTER;
CONSUMECHARACTER;
MAKETOKEN( TOKEN_ERROR );
return S_OK;
}
}
//Before checking for comments
else if ( !strncmp( plexer->pcurChar, "/", 1)){
CONSUMECHARACTER;
if ( !strncmp( plexer->pcurChar, "/", 1)){
Lexer_SkipComment(plexer, COMMENT_SLASH);
}
else if ( !strncmp( plexer->pcurChar, "*", 1)){
Lexer_SkipComment(plexer, COMMENT_STAR);
}
//Now complete the symbol scan for regular symbols.
else if ( !strncmp( plexer->pcurChar, "=", 1)){
CONSUMECHARACTER;
MAKETOKEN( TOKEN_DIV_ASSIGN );
return S_OK;
}
else{
MAKETOKEN( TOKEN_DIV);
return S_OK;
}
}
//a Symbol starts with one of these characters
else if (( !strncmp( plexer->pcurChar, ">", 1)) || ( !strncmp( plexer->pcurChar, "<", 1))
|| ( !strncmp( plexer->pcurChar, "+", 1)) || ( !strncmp( plexer->pcurChar, "-", 1))
|| ( !strncmp( plexer->pcurChar, "*", 1)) || ( !strncmp( plexer->pcurChar, "/", 1))
|| ( !strncmp( plexer->pcurChar, "%", 1)) || ( !strncmp( plexer->pcurChar, "&", 1))
|| ( !strncmp( plexer->pcurChar, "^", 1)) || ( !strncmp( plexer->pcurChar, "|", 1))
|| ( !strncmp( plexer->pcurChar, "=", 1)) || ( !strncmp( plexer->pcurChar, "!", 1))
|| ( !strncmp( plexer->pcurChar, ";", 1)) || ( !strncmp( plexer->pcurChar, "{", 1))
|| ( !strncmp( plexer->pcurChar, "}", 1)) || ( !strncmp( plexer->pcurChar, ",", 1))
|| ( !strncmp( plexer->pcurChar, ":", 1)) || ( !strncmp( plexer->pcurChar, "(", 1))
|| ( !strncmp( plexer->pcurChar, ")", 1)) || ( !strncmp( plexer->pcurChar, "[", 1))
|| ( !strncmp( plexer->pcurChar, "]", 1)) || ( !strncmp( plexer->pcurChar, ".", 1))
|| ( !strncmp( plexer->pcurChar, "~", 1)) || ( !strncmp( plexer->pcurChar, "?", 1)))
{
return Lexer_GetTokenSymbol(plexer, theNextToken );
}
//If we get here, we've hit a character we don't recognize
else{
//Consume the character so it can be sent to the error handler
CONSUMECHARACTER;
//Create an error token, and send it to the error handler
MAKETOKEN( TOKEN_ERROR );
//HandleCompileError( *theNextToken, UNRECOGNIZED_CHARACTER );
}
}
}
/******************************************************************************
* Identifier -- This method extracts an identifier from the stream, once it's
* recognized as an identifier. After it is extracted, this method determines
* if the identifier is a keyword.
* Parameters: theNextToken -- address of the next CToken found in the stream
* Returns: S_OK
* E_FAIL
******************************************************************************/
HRESULT Lexer_GetTokenIdentifier(Lexer* plexer, Token* theNextToken)
{
//copy the source that makes up this token
//an identifier is a string of letters, digits and/or underscores
do{
CONSUMECHARACTER;
}while ((*plexer->pcurChar >= '0' && *plexer->pcurChar <= '9') ||
(*plexer->pcurChar >= 'a' && *plexer->pcurChar <= 'z') ||
(*plexer->pcurChar >= 'A' && *plexer->pcurChar <= 'Z') ||
( !strncmp( plexer->pcurChar, "_", 1)));
//Check the Identifier against current keywords
if (!strcmp( plexer->theTokenSource, "auto")){
MAKETOKEN( TOKEN_AUTO );}
else if (!strcmp( plexer->theTokenSource, "break")){
MAKETOKEN( TOKEN_BREAK );}
else if (!strcmp( plexer->theTokenSource, "case")){
MAKETOKEN( TOKEN_CASE );}
else if (!strcmp( plexer->theTokenSource, "char")){
MAKETOKEN( TOKEN_CHAR );}
else if (!strcmp( plexer->theTokenSource, "const")){
MAKETOKEN( TOKEN_CONST );}
else if (!strcmp( plexer->theTokenSource, "continue")){
MAKETOKEN( TOKEN_CONTINUE );}
else if (!strcmp( plexer->theTokenSource, "default")){
MAKETOKEN( TOKEN_DEFAULT );}
else if (!strcmp( plexer->theTokenSource, "do")){
MAKETOKEN( TOKEN_DO );}
else if (!strcmp( plexer->theTokenSource, "double")){
MAKETOKEN( TOKEN_DOUBLE );}
else if (!strcmp( plexer->theTokenSource, "else")){
MAKETOKEN( TOKEN_ELSE );}
else if (!strcmp( plexer->theTokenSource, "enum")){
MAKETOKEN( TOKEN_ENUM );}
else if (!strcmp( plexer->theTokenSource, "extern")){
MAKETOKEN( TOKEN_EXTERN );}
else if (!strcmp( plexer->theTokenSource, "float")){
MAKETOKEN( TOKEN_FLOAT );}
else if (!strcmp( plexer->theTokenSource, "for")){
MAKETOKEN( TOKEN_FOR );}
else if (!strcmp( plexer->theTokenSource, "goto")){
MAKETOKEN( TOKEN_GOTO );}
else if (!strcmp( plexer->theTokenSource, "if")){
MAKETOKEN( TOKEN_IF );}
else if (!strcmp( plexer->theTokenSource, "int")){
MAKETOKEN( TOKEN_INT );}
else if (!strcmp( plexer->theTokenSource, "long")){
MAKETOKEN( TOKEN_LONG );}
else if (!strcmp( plexer->theTokenSource, "register")){
MAKETOKEN( TOKEN_REGISTER );}
else if (!strcmp( plexer->theTokenSource, "return")){
MAKETOKEN( TOKEN_RETURN );}
else if (!strcmp( plexer->theTokenSource, "short")){
MAKETOKEN( TOKEN_SHORT );}
else if (!strcmp( plexer->theTokenSource, "signed")){
MAKETOKEN( TOKEN_SIGNED );}
else if (!strcmp( plexer->theTokenSource, "sizeof")){
MAKETOKEN( TOKEN_SIZEOF );}
else if (!strcmp( plexer->theTokenSource, "static")){
MAKETOKEN( TOKEN_STATIC );}
else if (!strcmp( plexer->theTokenSource, "struct")){
MAKETOKEN( TOKEN_STRUCT );}
else if (!strcmp( plexer->theTokenSource, "switch")){
MAKETOKEN( TOKEN_SWITCH );}
else if (!strcmp( plexer->theTokenSource, "typedef")){
MAKETOKEN( TOKEN_TYPEDEF );}
else if (!strcmp( plexer->theTokenSource, "union")){
MAKETOKEN( TOKEN_UNION );}
else if (!strcmp( plexer->theTokenSource, "unsigned")){
MAKETOKEN( TOKEN_UNSIGNED );}
else if (!strcmp( plexer->theTokenSource, "void")){
MAKETOKEN( TOKEN_VOID );}
else if (!strcmp( plexer->theTokenSource, "volatile")){
MAKETOKEN( TOKEN_VOLATILE );}
else if (!strcmp( plexer->theTokenSource, "while")){
MAKETOKEN( TOKEN_WHILE );}
else{
MAKETOKEN( TOKEN_IDENTIFIER );}
return S_OK;
}
/******************************************************************************
* Number -- This method extracts a numerical constant from the stream. It
* only extracts the digits that make up the number. No conversion from string
* to numeral is performed here.
* Parameters: theNextToken -- address of the next CToken found in the stream
* Returns: S_OK
* E_FAIL
******************************************************************************/
HRESULT Lexer_GetTokenNumber(Lexer* plexer, Token* theNextToken)
{
//copy the source that makes up this token
//a constant is one of these:
//0[xX][a-fA-F0-9]+{u|U|l|L}
//0{D}+{u|U|l|L}
if (( !strncmp( plexer->pcurChar, "0X", 2)) || ( !strncmp( plexer->pcurChar, "0x", 2))){
CONSUMECHARACTER;
CONSUMECHARACTER;
while ((*plexer->pcurChar >= '0' && *plexer->pcurChar <= '9') ||
(*plexer->pcurChar >= 'a' && *plexer->pcurChar <= 'f') ||
(*plexer->pcurChar >= 'A' && *plexer->pcurChar <= 'F'))
{
CONSUMECHARACTER;
}
if (( !strncmp( plexer->pcurChar, "u", 1)) || ( !strncmp( plexer->pcurChar, "U", 1)) ||
( !strncmp( plexer->pcurChar, "l", 1)) || ( !strncmp( plexer->pcurChar, "L", 1)))
{
CONSUMECHARACTER;
}
MAKETOKEN( TOKEN_HEXCONSTANT );
}
else{
while (*plexer->pcurChar >= '0' && *plexer->pcurChar <= '9')
{
CONSUMECHARACTER;
}
if (( !strncmp( plexer->pcurChar, "E", 1)) || ( !strncmp( plexer->pcurChar, "e", 1)))
{
CONSUMECHARACTER;
while (*plexer->pcurChar >= '0' && *plexer->pcurChar <= '9')
{
CONSUMECHARACTER;
}
if (( !strncmp( plexer->pcurChar, "f", 1)) || ( !strncmp( plexer->pcurChar, "F", 1)) ||
( !strncmp( plexer->pcurChar, "l", 1)) || ( !strncmp( plexer->pcurChar, "L", 1)))
{
CONSUMECHARACTER;
}
MAKETOKEN( TOKEN_FLOATCONSTANT );
}
else if ( !strncmp( plexer->pcurChar, ".", 1))
{
CONSUMECHARACTER;
while (*plexer->pcurChar >= '0' && *plexer->pcurChar <= '9')
{
CONSUMECHARACTER;
}
if (( !strncmp( plexer->pcurChar, "E", 1)) || ( !strncmp( plexer->pcurChar, "e", 1)))
{
CONSUMECHARACTER;
while (*plexer->pcurChar >= '0' && *plexer->pcurChar <= '9')
{
CONSUMECHARACTER;
}
if (( !strncmp( plexer->pcurChar, "f", 1)) ||
( !strncmp( plexer->pcurChar, "F", 1)) ||
( !strncmp( plexer->pcurChar, "l", 1)) ||
( !strncmp( plexer->pcurChar, "L", 1)))
{
CONSUMECHARACTER;
}
}
MAKETOKEN( TOKEN_FLOATCONSTANT );
}
else{
MAKETOKEN( TOKEN_INTCONSTANT );
}
}
return S_OK;
}
/******************************************************************************
* StringLiteral -- This method extracts a string literal from the character
* stream.
* Parameters: theNextToken -- address of the next CToken found in the stream
* Returns: S_OK
* E_FAIL
******************************************************************************/
HRESULT Lexer_GetTokenStringLiteral(Lexer* plexer, Token* theNextToken)
{
//copy the source that makes up this token
//an identifier is a string of letters, digits and/or underscores
//skip that first quote mark
int esc = 0;
SKIPCHARACTER;
while ( strncmp( plexer->pcurChar, "\"", 1))
{
if(!strncmp( plexer->pcurChar, "\\", 1))
{
esc = 1;
}
CONSUMECHARACTER;
if(esc)
{
CONSUMEESCAPE;
esc = 0;
}
}
//skip that last quote mark
SKIPCHARACTER;
MAKETOKEN( TOKEN_STRING_LITERAL );
return S_OK;
}
/******************************************************************************
* Symbol -- This method extracts a symbol from the character stream. For the
* purposes of lexing, comments are considered symbols.
* Parameters: theNextToken -- address of the next CToken found in the stream
* Returns: S_OK
* E_FAIL
******************************************************************************/
HRESULT Lexer_GetTokenSymbol(Lexer* plexer, Token* theNextToken)
{
//">>="
if ( !strncmp( plexer->pcurChar, ">>=", 3))
{
CONSUMECHARACTER;
CONSUMECHARACTER;
CONSUMECHARACTER;
MAKETOKEN( TOKEN_RIGHT_ASSIGN );
}
//">>"
else if ( !strncmp( plexer->pcurChar, ">>", 2))
{
CONSUMECHARACTER;
CONSUMECHARACTER;
MAKETOKEN( TOKEN_RIGHT_OP );
}
//">="
else if ( !strncmp( plexer->pcurChar, ">=", 2))
{
CONSUMECHARACTER;
CONSUMECHARACTER;
MAKETOKEN( TOKEN_GE_OP );
}
//">"
else if ( !strncmp( plexer->pcurChar, ">", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_GT );
}
//"<<="
else if ( !strncmp( plexer->pcurChar, "<<=", 3))
{
CONSUMECHARACTER;
CONSUMECHARACTER;
CONSUMECHARACTER;
MAKETOKEN( TOKEN_LEFT_ASSIGN );
}
//"<<"
else if ( !strncmp( plexer->pcurChar, "<<", 2))
{
CONSUMECHARACTER;
CONSUMECHARACTER;
MAKETOKEN( TOKEN_LEFT_OP );
}
//"<="
else if ( !strncmp( plexer->pcurChar, "<=", 2))
{
CONSUMECHARACTER;
CONSUMECHARACTER;
MAKETOKEN( TOKEN_LE_OP );
}
//"<"
else if ( !strncmp( plexer->pcurChar, "<", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_LT );
}
//"++"
else if ( !strncmp( plexer->pcurChar, "++", 2))
{
CONSUMECHARACTER;
CONSUMECHARACTER;
MAKETOKEN( TOKEN_INC_OP );
}
//"+="
else if ( !strncmp( plexer->pcurChar, "+=", 2))
{
CONSUMECHARACTER;
CONSUMECHARACTER;
MAKETOKEN( TOKEN_ADD_ASSIGN );
}
//"+"
else if ( !strncmp( plexer->pcurChar, "+", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_ADD );
}
//"--"
else if ( !strncmp( plexer->pcurChar, "--", 2))
{
CONSUMECHARACTER;
CONSUMECHARACTER;
MAKETOKEN( TOKEN_DEC_OP );
}
//"-="
else if ( !strncmp( plexer->pcurChar, "-=", 2))
{
CONSUMECHARACTER;
CONSUMECHARACTER;
MAKETOKEN( TOKEN_SUB_ASSIGN );
}
//"-"
else if ( !strncmp( plexer->pcurChar, "-", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_SUB );
}
//"*="
else if ( !strncmp( plexer->pcurChar, "*=", 2))
{
CONSUMECHARACTER;
CONSUMECHARACTER;
MAKETOKEN( TOKEN_MUL_ASSIGN );
}
//"*"
else if ( !strncmp( plexer->pcurChar, "*", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_MUL );
}
//"%="
else if ( !strncmp( plexer->pcurChar, "%=", 2))
{
CONSUMECHARACTER;
CONSUMECHARACTER;
MAKETOKEN( TOKEN_MOD_ASSIGN );
}
//"%"
else if ( !strncmp( plexer->pcurChar, "%", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_MOD );
}
//"&&"
else if ( !strncmp( plexer->pcurChar, "&&", 2))
{
CONSUMECHARACTER;
CONSUMECHARACTER;
MAKETOKEN( TOKEN_AND_OP );
}
//"&="
else if ( !strncmp( plexer->pcurChar, "&=", 2))
{
CONSUMECHARACTER;
CONSUMECHARACTER;
MAKETOKEN( TOKEN_AND_ASSIGN );
}
//"&"
else if ( !strncmp( plexer->pcurChar, "&", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_BITWISE_AND );
}
//"^="
else if ( !strncmp( plexer->pcurChar, "^=", 2))
{
CONSUMECHARACTER;
CONSUMECHARACTER;
MAKETOKEN( TOKEN_XOR_ASSIGN );
}
//"^"
else if ( !strncmp( plexer->pcurChar, "^", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_XOR );
}
//"||"
else if ( !strncmp( plexer->pcurChar, "||", 2))
{
CONSUMECHARACTER;
CONSUMECHARACTER;
MAKETOKEN( TOKEN_OR_OP );
}
//"|="
else if ( !strncmp( plexer->pcurChar, "|=", 2))
{
CONSUMECHARACTER;
CONSUMECHARACTER;
MAKETOKEN( TOKEN_OR_ASSIGN );
}
//"|"
else if ( !strncmp( plexer->pcurChar, "|", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_BITWISE_OR );
}
//"=="
else if ( !strncmp( plexer->pcurChar, "==", 2))
{
CONSUMECHARACTER;
CONSUMECHARACTER;
MAKETOKEN( TOKEN_EQ_OP );
}
//"="
else if ( !strncmp( plexer->pcurChar, "=", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_ASSIGN );
}
//"!="
else if ( !strncmp( plexer->pcurChar, "!=", 2))
{
CONSUMECHARACTER;
CONSUMECHARACTER;
MAKETOKEN( TOKEN_NE_OP );
}
//"!"
else if ( !strncmp( plexer->pcurChar, "!", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_BOOLEAN_NOT );
}
//";"
else if ( !strncmp( plexer->pcurChar, ";", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_SEMICOLON);
}
//"{"
else if ( !strncmp( plexer->pcurChar, "{", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_LCURLY);
}
//"}"
else if ( !strncmp( plexer->pcurChar, "}", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_RCURLY);
}
//","
else if ( !strncmp( plexer->pcurChar, ",", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_COMMA);
}
//":"
else if ( !strncmp( plexer->pcurChar, ":", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_COLON);
}
//"("
else if ( !strncmp( plexer->pcurChar, "(", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_LPAREN);
}
//")"
else if ( !strncmp( plexer->pcurChar, ")", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_RPAREN);
}
//"["
else if ( !strncmp( plexer->pcurChar, "[", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_LBRACKET);
}
//"]"
else if ( !strncmp( plexer->pcurChar, "]", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_RBRACKET);
}
//"."
else if ( !strncmp( plexer->pcurChar, ".", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_FIELD);
}
//"~"
else if ( !strncmp( plexer->pcurChar, "~", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_BITWISE_NOT);
}
//"?"
else if ( !strncmp( plexer->pcurChar, "?", 1))
{
CONSUMECHARACTER;
MAKETOKEN( TOKEN_CONDITIONAL);
}
return S_OK;
}
/******************************************************************************
* Comment -- This method extracts a symbol from the character stream.
* Parameters: theNextToken -- address of the next CToken found in the stream
* Returns: S_OK
* E_FAIL
******************************************************************************/
HRESULT Lexer_SkipComment(Lexer* plexer, COMMENT_TYPE theType)
{
if (theType == COMMENT_SLASH){
do{
SKIPCHARACTER;
//break out if we hit a new line
if (!strncmp( plexer->pcurChar, "\n", 1)){
plexer->theTextPosition.col = 0;
plexer->theTextPosition.row++;
break;
}
else if (!strncmp( plexer->pcurChar, "\r", 1)){
plexer->theTextPosition.col = 0;
//plexer->theTextPosition.row++;
break;
}
else if (!strncmp( plexer->pcurChar, "\f", 1)){
plexer->theTextPosition.row++;
break;
}
}while (strncmp( plexer->pcurChar, "\0", 1));
}
else if (theType == COMMENT_STAR){
//consume the '*' that gets this comment started
SKIPCHARACTER;
//loop through the characters till we hit '*/'
while (strncmp( plexer->pcurChar, "\0", 1)){
if (0==strncmp( plexer->pcurChar, "*/", 2)){
SKIPCHARACTER;
SKIPCHARACTER;
break;
}
else if (!strncmp( plexer->pcurChar, "\n", 1)){
plexer->theTextPosition.col = 0;
plexer->theTextPosition.row++;
}
else if (!strncmp( plexer->pcurChar, "\r", 1)){
plexer->theTextPosition.col = 0;
//plexer->theTextPosition.row++;
}
else if (!strncmp( plexer->pcurChar, "\f", 1)){
plexer->theTextPosition.row++;
}
SKIPCHARACTER;
};
}
return S_OK;
}
|
C
|
#if 0
#include <sys/kprintf.h>
#include <sys/kmalloc.h>
extern uint64_t virtualMemoryAvailable;
void KMALLOC_TEST(){
kprintf("Available virtual mem %p\n", virtualMemoryAvailable);
kprintf("size of int %d\n", sizeof(int));
uint64_t* intmem = kmalloc(4096*2);
for (int i = 0; i < 512+512; ++i)
{
intmem[i] = i;
}
for (int i = 0; i < 512+512; ++i)
{
kprintf("%d ", intmem[i]);
}
kprintf("Available virtual mem %p\n", virtualMemoryAvailable);
uint64_t* charmem = kmalloc(26*sizeof(char));
for (int i = 0; i < 26; ++i)
{
charmem[i] = 'a' + i;
}
for (int i = 0; i < 26; ++i)
{
kprintf("%c ", charmem[i]);
}
}
#endif
|
C
|
/* Ingresar datos de alumnos.
nota(int)
sexo(char)- f/m
Indicar si el mejor promedio pertenece a f o m. (Utilizar switch)
*/
#include <stdio.h>
int main ()
{
char s,f;
int i, nota, acumulador_f = 0, contador_f = 0, acumulador_m = 0, contador_m = 0, promedio_f = 0, promedio_m = 0;
for (i = 0; i < 6; i++)
{
printf("Ingresar sexo:\n"); // Ingreso sexo
fflush(stdin);
scanf("%c", &s);
printf("Ingresar nota:\n"); // Ingreso nota
scanf("%d", ¬a);
if (s == 'f')
{ // Acumulo notas del genero femenino
acumulador_f += nota;
contador_f++;
}
else
{
acumulador_m += nota; // Acumulo notas del genero masculino
contador_m++;
}
}
promedio_f = acumulador_f / contador_f; // Calculo promedio de mujeres
promedio_m = acumulador_m / contador_m; // Calculo promedio de hombres
if (promedio_f > promedio_m) // Defino a que genero pertenece el mejor promedio y lo imprimo en pantalla
printf("El mejor promedio es de %d y pertenece a las mujeres/n", promedio_f);
else
printf("El mejor promedio es de %d y pertenece a los hombres/n", promedio_m);
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef int uint32_t ;
/* Variables and functions */
__attribute__((used)) static inline uint32_t interpolate_two_points(uint32_t y1, uint32_t y2, uint32_t x_step, uint32_t x)
{
//Interpolate between two points (x1,y1) (x2,y2) between 'lower' and 'upper' separated by 'step'
return ((y1 * x_step) + (y2 * x) - (y1 * x) + (x_step / 2)) / x_step;
}
|
C
|
/*
** EPITECH PROJECT, 2020
** my_compute_power_rec.c
** File description:
** 02/10/2020
*/
#include "my.h"
int my_compute_power_rec(int nb, int p)
{
if (p > 0)
return (nb * my_compute_power_rec(nb, p - 1));
else if (p < 0)
return 0;
else
return 1;
}
|
C
|
//
// Queue.h
// Tree
//
// Created by Sutej Kulkarni on 03/08/20.
// Copyright © 2020 Sutej Kulkarni. All rights reserved.
//
#ifndef Queue_h
#define Queue_h
#include <stdio.h>
#include <stdlib.h>
struct tree_node
{
struct tree_node *lchild;
int data;
struct tree_node *rchild;
};
struct qu
{
int size;
int front;
int rear;
struct tree_node **q;
};
void create_queue(struct qu *pq,int size1)
{
pq->size = size1;
pq->front = pq->rear = 0;
pq->q = (struct tree_node**)malloc(size1 * sizeof(struct tree_node *));
}
int isEmpty(struct qu s)
{
if(s.front == s.rear)
{
printf("Queue is empty\n");
return 1;
}
return 0;
}
int isFull(struct qu s1)
{
if(s1.front == (s1.rear+1)%s1.size)
{
printf("Queue is Full\n");
return 1;
}
return 0;
}
void enqueue(struct qu *q2,struct tree_node *p)
{
if(isFull(*q2))
{
printf("Queue is full\n");
return;
}
q2->rear = (q2->rear + 1) % q2->size;
q2->q[q2->rear] = p;
}
struct tree_node* dequeue(struct qu *q4)
{
//int x=-1;
struct tree_node *q = NULL;
if(isEmpty(*q4))
{
printf("Queue is empty\n");
return NULL;
}
q4->front = (q4->front + 1) % q4->size;
q = q4->q[q4->front];
printf("Dequeued value is %p\n",q);
return q;
}
#endif /* Queue_h */
|
C
|
/* */
/* Program Name: clrscr.c */
/* */
#include <conio.h>
void main(void)
{
clrscr();
gotoxy(35,13);
cputs("Hi! Borland");
gotoxy(28,25);
cputs("Press any key to clear screen");
getch();
clrscr();
gotoxy(28,24);
cputs("The screen has been cleared");
gotoxy(31,25);
cputs("Press any key to exit");
getch();
}
|
C
|
#include <stdio.h>
int main(void)
{
const int RANGE = 10;
int i, n;
printf("Enter an integer: ");
scanf("%d", &n);
i = n;
while (i <= RANGE + n)
printf(" %d", i++);
putchar('\n');
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define N_TAREFAS 1000 // Numero de tarefas no saco de trabalho
#define TAM_TAREFA 25000 // Tamanho de vetor a ser organizado pelos nodos
void initialize_matrix(int matrix[N_TAREFAS][TAM_TAREFA])
{
int i,j;
for(i=0; i<N_TAREFAS; i++)
for(j=0; j<TAM_TAREFA; j++) matrix[i][j] = TAM_TAREFA-j;
}
int cmpfunc (const void * a, const void * b) {
return ( *(int*)a - *(int*)b );
}
int main(int argc, char** argv)
{
clock_t t1, t2;
int (*tasks)[TAM_TAREFA] = malloc (N_TAREFAS * sizeof *tasks);
initialize_matrix(tasks);
t1 = clock();
//printf("Begin time: %lf\n", (double)t1/CLOCKS_PER_SEC);
int i;
for(i=0; i<N_TAREFAS; i++)
qsort(tasks[i],TAM_TAREFA, sizeof(int), cmpfunc);
t2 = clock();
//printf("Final time: %lf\n", (double)t2/CLOCKS_PER_SEC);
printf("Run time: %lf\n", (double)(t2-t1)/CLOCKS_PER_SEC);
return 0;
}
|
C
|
#include <LPC17xx.h>
void delay(unsigned int); // for delay
int main(void)
{
unsigned int i, j, valueSet;
SystemInit();
SystemCoreClockUpdate();
valueSet = 0;
// GPIO Configuration
LPC_PINCON->PINSEL0 &= 0xFF0000FF;
// FIODIR Configuration
LPC_GPIO0->FIODIR |= 0x0FF0;
while (1)
{
for (i = 0; i < 8; i++)
{
// send output via FIOPIN
LPC_GPIO0->FIOPIN = valueSet << 4; // STARTLED
valueSet = (valueSet >> 1) + (1 << 7); // SIZE
delay(10000);
}
for (i = 0; i < 8; i++)
{
LPC_GPIO0->FIOPIN = valueSet << 4;
valueSet = valueSet >> 1;
delay(10000);
}
}
}
void delay(unsigned int n)
{
unsigned int i = 0;
for (i = 0; i < n; i++);
}
|
C
|
# include <stdio.h>
# include <libmill.h>
void f(int index, const char *text)
{
printf("Worker %d, Message %s\n", index, text);
}
int main(int argc, char **argv)
{
char str[10];
for(int i=1;i<=100000; i++) {
sprintf(str, "Text %d", i);
f(i, str);
}
return 0;
}
|
C
|
#include <stdio.h>
char data[12][12];
int win (int n)
{
int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(data[i][j]!=' ')
{
return 0;
}
}
}
return 1;
}
|
C
|
void main()
{
int a[20];
int size,first=-1,last=size,n=1,num;
printf("enter the size of the stacks");
scanf("%d",&size);
while(n!=0)
{
printf("press 1 for insertion in stack 1\n");
printf("press 2 for insertion in stack 2\n");
printf("press 3 for deletion in stack 1\n");
printf("press 4 for deletion in stack 2\n");
printf("press 5 for printing stack 1\n");
printf("press 6 for printing stack 2\n");
printf("press 0 for do nothing case \n");
scanf("%d",&n);
switch(n)
{
case 1:
{
printf("insert the element in stack 1\n");
scanf("%d",&num);
if(first!=(last-1))
a[++first]=num;
else
printf("stck 1 Overflow\n");
break;
}
case 2:
{
printf("insert the element in stck 2\n");
scanf("%d",&num);
if(last!=(first+1))
a[--last]=num;
else
printf("stack 2 Overflow\n");
break;
}
case 3:
{
if(first==-1)
printf("Stack1 is in underflow condition\n");
else
{
num=a[first--];
printf("%d\n",num);
}
break;
}
case 4:
{
if(last==n)
printf("Stack 2 is in underflow condition \n");
else
{
num=a[last++];
printf("%d\n",num);
}
break;
}
case 5:
{
if(first==-1)
printf("Stack 1 is in underflow condition\n");
else
{
printf("Stack 1 is\n");
for(int i=0;i<=first;i++)
printf("%d ",a[i]);
}
break;
}
case 6:
{
if(last==n)
printf("Stack 2 is in underflow condition\n");
else
{
printf("Stack2 is\n");
for(int i=(n-1);i>=last;i--)
printf("%d ",a[i]);
printf("\n");
}
break;
}
case 0:
break;
}}}
|
C
|
/*
* Ideas for screen management extension to EGL.
*
* Each EGLDisplay has one or more screens (CRTs, Flat Panels, etc).
* The screens' handles can be obtained with eglGetScreensMESA().
*
* A new kind of EGLSurface is possible- one which can be directly scanned
* out on a screen. Such a surface is created with eglCreateScreenSurface().
*
* To actually display a screen surface on a screen, the eglShowSurface()
* function is called.
*/
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "egldisplay.h"
#include "eglglobals.h"
#include "eglmode.h"
#include "eglconfig.h"
#include "eglsurface.h"
#include "eglscreen.h"
/**
* Return a new screen handle/ID.
* NOTE: we never reuse these!
*/
EGLScreenMESA
_eglAllocScreenHandle(void)
{
EGLScreenMESA s = _eglGlobal.FreeScreenHandle;
_eglGlobal.FreeScreenHandle++;
return s;
}
/**
* Initialize an _EGLScreen object to default values.
*/
void
_eglInitScreen(_EGLScreen *screen)
{
memset(screen, 0, sizeof(_EGLScreen));
screen->StepX = 1;
screen->StepY = 1;
}
/**
* Given a public screen handle, return the internal _EGLScreen object.
*/
_EGLScreen *
_eglLookupScreen(EGLScreenMESA screen, _EGLDisplay *display)
{
EGLint i;
for (i = 0; i < display->NumScreens; i++) {
if (display->Screens[i]->Handle == screen)
return display->Screens[i];
}
return NULL;
}
/**
* Add the given _EGLScreen to the display's list of screens.
*/
void
_eglAddScreen(_EGLDisplay *display, _EGLScreen *screen)
{
EGLint n;
assert(display);
assert(screen);
screen->Handle = _eglAllocScreenHandle();
n = display->NumScreens;
display->Screens = realloc(display->Screens, (n+1) * sizeof(_EGLScreen *));
display->Screens[n] = screen;
display->NumScreens++;
}
EGLBoolean
_eglGetScreensMESA(_EGLDriver *drv, _EGLDisplay *display, EGLScreenMESA *screens,
EGLint max_screens, EGLint *num_screens)
{
EGLint n;
if (display->NumScreens > max_screens) {
n = max_screens;
}
else {
n = display->NumScreens;
}
if (screens) {
EGLint i;
for (i = 0; i < n; i++)
screens[i] = display->Screens[i]->Handle;
}
if (num_screens)
*num_screens = n;
return EGL_TRUE;
}
/**
* Example function - drivers should do a proper implementation.
*/
_EGLSurface *
_eglCreateScreenSurfaceMESA(_EGLDriver *drv, _EGLDisplay *dpy, _EGLConfig *conf,
const EGLint *attrib_list)
{
#if 0 /* THIS IS JUST EXAMPLE CODE */
_EGLSurface *surf;
surf = (_EGLSurface *) calloc(1, sizeof(_EGLSurface));
if (!surf)
return NULL;
if (!_eglInitSurface(drv, surf, EGL_SCREEN_BIT_MESA,
conf, attrib_list)) {
free(surf);
return NULL;
}
return surf;
#endif
return NULL;
}
/**
* Show the given surface on the named screen.
* If surface is EGL_NO_SURFACE, disable the screen's output.
*
* This is just a placeholder function; drivers will always override
* this with code that _really_ shows the surface.
*/
EGLBoolean
_eglShowScreenSurfaceMESA(_EGLDriver *drv, _EGLDisplay *dpy,
_EGLScreen *scrn, _EGLSurface *surf,
_EGLMode *mode)
{
if (!surf) {
scrn->CurrentSurface = NULL;
}
else {
if (surf->Type != EGL_SCREEN_BIT_MESA) {
_eglError(EGL_BAD_SURFACE, "eglShowSurfaceMESA");
return EGL_FALSE;
}
if (surf->Width < mode->Width || surf->Height < mode->Height) {
_eglError(EGL_BAD_SURFACE,
"eglShowSurfaceMESA(surface smaller than screen size)");
return EGL_FALSE;
}
scrn->CurrentSurface = surf;
scrn->CurrentMode = mode;
}
return EGL_TRUE;
}
/**
* Set a screen's current display mode.
* Note: mode = EGL_NO_MODE is valid (turns off the screen)
*
* This is just a placeholder function; drivers will always override
* this with code that _really_ sets the mode.
*/
EGLBoolean
_eglScreenModeMESA(_EGLDriver *drv, _EGLDisplay *dpy, _EGLScreen *scrn,
_EGLMode *m)
{
scrn->CurrentMode = m;
return EGL_TRUE;
}
/**
* Set a screen's surface origin.
*/
EGLBoolean
_eglScreenPositionMESA(_EGLDriver *drv, _EGLDisplay *dpy,
_EGLScreen *scrn, EGLint x, EGLint y)
{
scrn->OriginX = x;
scrn->OriginY = y;
return EGL_TRUE;
}
/**
* Query a screen's current surface.
*/
EGLBoolean
_eglQueryScreenSurfaceMESA(_EGLDriver *drv, _EGLDisplay *dpy,
_EGLScreen *scrn, _EGLSurface **surf)
{
*surf = scrn->CurrentSurface;
return EGL_TRUE;
}
/**
* Query a screen's current mode.
*/
EGLBoolean
_eglQueryScreenModeMESA(_EGLDriver *drv, _EGLDisplay *dpy, _EGLScreen *scrn,
_EGLMode **m)
{
*m = scrn->CurrentMode;
return EGL_TRUE;
}
EGLBoolean
_eglQueryScreenMESA(_EGLDriver *drv, _EGLDisplay *dpy, _EGLScreen *scrn,
EGLint attribute, EGLint *value)
{
switch (attribute) {
case EGL_SCREEN_POSITION_MESA:
value[0] = scrn->OriginX;
value[1] = scrn->OriginY;
break;
case EGL_SCREEN_POSITION_GRANULARITY_MESA:
value[0] = scrn->StepX;
value[1] = scrn->StepY;
break;
default:
_eglError(EGL_BAD_ATTRIBUTE, "eglQueryScreenMESA");
return EGL_FALSE;
}
return EGL_TRUE;
}
/**
* Delete the modes associated with given screen.
*/
void
_eglDestroyScreenModes(_EGLScreen *scrn)
{
EGLint i;
for (i = 0; i < scrn->NumModes; i++) {
if (scrn->Modes[i].Name)
free((char *) scrn->Modes[i].Name); /* cast away const */
}
if (scrn->Modes)
free(scrn->Modes);
scrn->Modes = NULL;
scrn->NumModes = 0;
}
/**
* Default fallback routine - drivers should usually override this.
*/
void
_eglDestroyScreen(_EGLScreen *scrn)
{
_eglDestroyScreenModes(scrn);
free(scrn);
}
|
C
|
/****************************************************************************
***** *****
***** formHandler.c *****
***** *****
****************************************************************************/
#include "Vk.h"
/**** Local Includes ****/
#include "stdcurses.h"
#include "keys.h"
#include "page.h"
#include "attr.h"
#include "choices.h"
/**** Form Definitions ****/
#include "form.d"
/*************************************************
********** Forward Declarations **********
*************************************************/
PrivateFnDef PAGE_Action initForm (
FORM * form,
CUR_WINDOW * win
);
PrivateFnDef PAGE_Action inputForm (
FORM * form,
CUR_WINDOW * win
);
#if 0
#define readLine()\
{\
if (!isBuffer)\
{\
if (NULL == (fgets(buffer, FORM_MaxLine, fptr)))\
return(NULL);\
}\
else\
{\
j = 0;\
while (NULL != (buffer[j] = filename[j])) j++;\
filename += j;\
}\
}
PublicFnDef FORM *FORM_read(filename, isBuffer)
char *filename;
int isBuffer;
{
int i, j, index1, index2, k, bytes, FORM_menuToForm();
char buffer[FORM_MaxLine], string[FORM_MaxLine],
*bp, *bp2;
FILE *fptr, *fopen();
FORM *form;
MENU *mptr;
if ((form = (FORM *) malloc(sizeof(FORM))) < 0)
return(NULL);
if (!isBuffer)
{
if (NULL == (fptr = fopen(filename, "r")))
return(NULL);
}
readLine();
sscanf(buffer, "%d", &form->fields);
for (i = 0; i < form->fields; i++)
{
form->field[i] = (FORM_Field *) malloc(sizeof(FORM_Field));
readLine();
sscanf(buffer, "%d %d %d %d %d %c", &form->field[i]->y,
&form->field[i]->x,
&index1,
&form->field[i]->len,
&form->field[i]->input,
&form->field[i]->type);
form->field[i]->attr = ATTRIBUTE[index1];
form->field[i]->value =
malloc((form->field[i]->len + 1) * sizeof(char));
if (form->field[i]->type != 'm')
{
bp = strchr(buffer, FORM_Quote);
j = 0;
if (bp != NULL)
{
bp++;
while (j < form->field[i]->len && *bp != FORM_Quote)
{
form->field[i]->value[j++] = *bp;
bp++;
}
}
form->field[i]->value[j] = '\0';
bp++;
}
else
bp = buffer;
/**** help message ***/
form->field[i]->help = malloc(81 * sizeof(char));
bp = strchr(bp, FORM_Quote);
j = 0;
if (bp != NULL)
{
bp++;
while (j < 80 && *bp != FORM_Quote)
{
form->field[i]->help[j++] = *bp;
bp++;
}
}
form->field[i]->help[j] = '\0';
if (form->field[i]->type == 'm')
{
form->field[i]->menu = (MENU *)malloc(sizeof(MENU));
mptr = form->field[i]->menu;
readLine();
sscanf(buffer, "%d %d %d %d", &mptr->choiceCount,
&mptr->currChoice,
&index1,
&index2);
MENU_normal(mptr) = ATTRIBUTE[index1];
MENU_hilight(mptr) = ATTRIBUTE[index2];
bp = strchr(buffer, FORM_Quote);
bp++;
j = 0;
while (j < 80 && *bp != FORM_Quote)
{
string[j++] = *bp;
bp++;
}
string[j] = '\0';
if (NULL == (mptr->title = malloc(strlen(string) + 1)))
return(NULL);
strcpy(mptr->title, string);
for (k = 0; k < mptr->choiceCount; k++)
{
if (NULL == (mptr->choice[k] =
(MENU_Choice *)malloc(sizeof(MENU_Choice))))
return(NULL);
readLine();
sscanf(buffer, "%c", &mptr->choice[k]->letter);
bp = strchr(buffer, FORM_Quote);
bp++;
j = 0;
while (j < 80 && *bp != FORM_Quote)
{
string[j++] = *bp;
bp++;
}
string[j] = '\0';
if (NULL == (mptr->choice[k]->label = malloc(strlen(string) + 1)))
return(NULL);
strcpy(mptr->choice[k]->label, string);
bp2 = bp + 1;
bp = strchr(bp2, FORM_Quote);
bp++;
j = 0;
while (j < 80 && *bp != FORM_Quote)
{
string[j++] = *bp;
bp++;
}
string[j] = '\0';
if (NULL == (mptr->choice[k]->help = malloc(strlen(string) + 1)))
return(NULL);
strcpy(mptr->choice[k]->help, string);
mptr->choice[k]->handler = FORM_menuToForm;
}
} /* if menu type */
}
if (!isBuffer) fclose(fptr);
return(form);
}
#endif
PublicFnDef PAGE_Action FORM_handler(form, win, action)
FORM *form;
CUR_WINDOW *win;
PAGE_Action action;
/***** Routine to manage user interaction with forms
*
* Arguments:
* An array of pointers containing:
* form -pointer to a completely filled in Form structure
* win -pointer to CUR_WINDOW
* action -pointer to a PAGE_Action
*
* Returns:
* PAGE_Action
*
*****/
{
switch (action)
{
case PAGE_Init:
return(initForm(form, win));
case PAGE_Input:
return(inputForm(form, win));
case PAGE_Refresh:
CUR_touchwin(win);
CUR_wnoutrefresh(win);
return(PAGE_Refresh);
default:
return(PAGE_Error);
}
}
PrivateFnDef PAGE_Action initForm (
FORM * form,
CUR_WINDOW * win
)
{
int i;
MENU *mptr;
FORM_Field *fptr;
/*** construct form ***/
if( (FORM_currField(form) < 0) ||
(FORM_currField(form) >= FORM_fieldCount(form)) ||
(FORM_fieldInput(FORM_field(form,FORM_currField(form))) == FALSE) )
FORM_currField(form) = -1;
for (i = 0; i < FORM_fieldCount (form); i++)
{
if( (FORM_fieldType (FORM_field (form, i)) == 'm') ||
(FORM_fieldType (FORM_field (form, i)) == 'M') ||
(FORM_fieldType (FORM_field (form, i)) == 'S') )
{
mptr = FORM_fieldMenu(FORM_field(form, i));
if (MENU_currChoice(mptr) < 0 ||
MENU_currChoice(mptr) >= MENU_choiceCount(mptr))
MENU_currChoice(mptr) = 0;
strcpy(FORM_fieldValue (FORM_field (form, i)),
MENU_choiceLabel (mptr, MENU_currChoice(mptr)));
}
if( (FORM_fieldType (FORM_field (form, i)) == 'M') ||
(FORM_fieldType (FORM_field (form, i)) == 'X') ||
(FORM_fieldType (FORM_field (form, i)) == 'D') ||
(FORM_fieldType (FORM_field (form, i)) == 'I') ||
(FORM_fieldType (FORM_field (form, i)) == 'A') )
continue;
CUR_wattron(win, FORM_fieldAttr (FORM_field (form, i)));
CUR_wmove(win,
FORM_fieldY (FORM_field (form, i)),
FORM_fieldX (FORM_field (form, i)));
CUR_wprintw(win,
"%-*.*s",
FORM_fieldLen (FORM_field (form, i)),
FORM_fieldLen (FORM_field (form, i)),
FORM_fieldValue (FORM_field (form, i)));
CUR_wattroff(win, FORM_fieldAttr (FORM_field (form, i)));
if (FORM_fieldInput (FORM_field (form, i)) == TRUE
&& FORM_currField(form) == -1)
FORM_currField(form) = i;
}
for (i = 0; i < FORM_fieldCount (form); i++)
{
if( (FORM_fieldType (FORM_field (form, i)) == 'X') )
{
mptr = FORM_fieldMenu(FORM_field(form, i-1));
fptr = FORM_field(form,i+1+MENU_currChoice(mptr));
CUR_wattron(win, FORM_fieldAttr (fptr));
CUR_wmove(win, FORM_fieldY (fptr), FORM_fieldX (fptr));
CUR_wprintw(win,
"%-*.*s",
FORM_fieldLen (fptr),
FORM_fieldLen (fptr),
FORM_fieldValue (fptr));
CUR_wattroff(win, FORM_fieldAttr (fptr));
}
}
CUR_touchwin(win);
CUR_wnoutrefresh(win);
return(PAGE_Init);
}
#define hilightField(w, f, index)\
{\
CUR_wattron(w, (CUR_A_BOLD | FORM_fieldAttr(f)));\
CUR_wmove(w, FORM_fieldY(f), FORM_fieldX(f));\
CUR_wprintw(w,\
"%-*.*s", FORM_fieldLen(f), FORM_fieldLen(f), &FORM_fieldValue(f)[index]);\
CUR_wattroff(w, CUR_A_BOLD);\
}\
#define unhilightField(w, f, index)\
{\
CUR_wattron(w, FORM_fieldAttr(f));\
CUR_wmove(w, FORM_fieldY(f), FORM_fieldX(f));\
CUR_wprintw(w,\
"%-*.*s", FORM_fieldLen(f), FORM_fieldLen(f), &FORM_fieldValue(f)[index]);\
}\
#define addChar()\
{\
len = strlen(FORM_fieldValue(Xfptr));\
if( (!firstKey || FORM_fieldExtKey(Xfptr)) &&\
((FORM_fieldScroll(Xfptr) && (len >= FORM_ValueMaxLen)) ||\
(!FORM_fieldScroll(Xfptr) && (len >= FORM_fieldLen(Xfptr)))) )\
ERR_displayStr(" Field is full", TRUE);\
else\
{\
if( firstKey )\
{\
firstKey = FALSE;\
if( !FORM_fieldExtKey(Xfptr) )\
{\
for( len=0 ; len<=FORM_ValueMaxLen ; len++ )\
FORM_fieldValue(Xfptr)[len] = '\0';\
}\
}\
strcpy(tbuf,&FORM_fieldValue(Xfptr)[xpos]);\
FORM_fieldValue(Xfptr)[xpos++] = c;\
strcpy(&FORM_fieldValue(Xfptr)[xpos],tbuf);\
if( (xpos - idx) > FORM_fieldLen(Xfptr) )\
idx++;\
hilightField(win, Xfptr, idx);\
}\
}
#define limitChoices()\
{\
if (FORM_fieldChoiceArray (Xfptr) != NULL)\
CHOICES_LimitOptions (win, form,\
FORM_fieldChoiceArray(Xfptr)[Pos[Xfld]], Pos);\
}
#define resetForm()\
{\
for (j = 0; j < inputFields; j++)\
FORM_fieldSetInput (FORM_field (form, input[j]));\
for (i = 0; i < FORM_fieldCount(form); i++)\
{\
fptr = FORM_field(form, i);\
if( (FORM_fieldType(fptr) == 'm') ||\
(FORM_fieldType(fptr) == 'M') ||\
(FORM_fieldType(fptr) == 'S') )\
{\
mptr = FORM_fieldMenu(fptr);\
MENU_currChoice(mptr) = Pos[i];\
}\
}\
}
PrivateVarDef int Pos[FORM_Fields];
PrivateVarDef FORM *Form;
PrivateVarDef CUR_WINDOW *Win;
PrivateFnDef PAGE_Action inputForm (
FORM * form,
CUR_WINDOW * win
)
{
int c, i, j, fld, len, Xfld, idx,
inputFields, firstKey,
xpos, isS, isX,
notDone, notExit,
input[FORM_Fields]; /** array of input fields **/
FORM_Field *fptr, *Xfptr, *tfptr;
MENU *mptr;
CUR_WINDOW *menuWin;
PAGE_Action action;
char tbuf[FORM_ValueMaxLen+1];
Form = form;
Win = win;
/*** contruct array of input field indices ****/
j = inputFields = 0;
for (i = 0; i < FORM_fieldCount(form); i++)
{
fptr = FORM_field(form, i);
mptr = FORM_fieldMenu(fptr);
if (FORM_fieldInput(fptr))
input[j++] = i;
if( (FORM_fieldType(fptr) == 'm') ||
(FORM_fieldType(fptr) == 'M') ||
(FORM_fieldType(fptr) == 'S') )
Pos[i] = MENU_currChoice(mptr);
else
Pos[i] = 0; /** used to remember choice for menu fields **/
}
inputFields = j;
if (inputFields == 0)
return(PAGE_Error); /** there are no input fields **/
/*** get data ***/
j = 0;
while (input[j] != FORM_currField(form) && j < inputFields)
j++;
notExit = TRUE;
while (notExit)
{
if (j == -1) /*** go to last field ***/
j = inputFields - 1;
if (j >= inputFields) /*** go to first field ***/
j = 0;
fld = FORM_currField(form) = input[j];
fptr = FORM_field(form, fld);
if( FORM_fieldType(fptr) == 'S' )
isS = TRUE;
else
isS = FALSE;
if( FORM_fieldType(fptr) == 'X' )
isX = TRUE;
else
isX = FALSE;
if( isX )
{
Xfld = fld+1+Pos[fld-1];
Xfptr = FORM_field(form,Xfld);
}
else
{
Xfld = fld;
Xfptr = fptr;
}
mptr = FORM_fieldMenu(Xfptr);
idx = xpos = 0;
if( isBlank(FORM_fieldValue(Xfptr)) )
{
for( i=0 ; i<=FORM_ValueMaxLen ; i++ )
FORM_fieldValue(Xfptr)[i] = '\0';
}
hilightField(win, Xfptr, idx);
limitChoices();
if( !ERR_msgDisplayed && !KEY_cready() && (FORM_fieldHelp(Xfptr) != NULL) )
ERR_displayStr(FORM_fieldHelp(Xfptr),FALSE);
firstKey = TRUE;
notDone = TRUE;
while (notDone)
{
if( !KEY_cready() )
{
CUR_touchwin(win);
CUR_wmove(win, FORM_fieldY(Xfptr), (xpos - idx) + FORM_fieldX(Xfptr));
CUR_wnoutrefresh(win);
CUR_doupdate();
CUR_forceSetCursor(win, FORM_fieldY(Xfptr), (xpos-idx)+FORM_fieldX(Xfptr));
}
c = KEY_getkey(FALSE);
if (ERR_msgDisplayed && !KEY_cready()) ERR_clearMsg();
switch(c) {
case 0:
break;
case KEY_SCRIPTR:
KEY_beginScriptRead();
break;
case KEY_SCRIPTW:
KEY_beginScriptWrite();
break;
case KEY_HELP:
if (FORM_fieldMenu(Xfptr) == NULL)
action = PAGE_Help;
else
{
menuWin = CUR_newwin(10, 20, 1, (CUR_COLS - 25));
if (PAGE_Help ==
MENU_handler(FORM_fieldMenu(Xfptr), menuWin, PAGE_Input))
action = PAGE_Help;
else if( STD_delwinDoesNotRefresh )
action = PAGE_Refresh;
else
action = PAGE_Input;
CUR_delwin(menuWin);
}
notExit = FALSE;
break;
case KEY_WINDOW:
unhilightField(win, Xfptr, 0);
CUR_touchwin(win);
CUR_wrefresh(win);
action = PAGE_Window;
notExit = FALSE;
break;
case KEY_EDIT:
action = PAGE_F4;
notExit = FALSE;
break;
case KEY_EXEC:
action = PAGE_Exec;
notExit = FALSE;
break;
case KEY_QUIT:
action = PAGE_Quit;
notExit = FALSE;
break;
case KEY_PREV:
action = PAGE_Prev;
notExit = FALSE;
break;
case KEY_SMENU:
action = PAGE_SMenu;
notExit = FALSE;
break;
case KEY_AMENU:
action = PAGE_AMenu;
notExit = FALSE;
break;
case KEY_FILES:
action = PAGE_File;
notExit = FALSE;
break;
case KEY_REGIONS:
action = PAGE_Region;
notExit = FALSE;
break;
case KEY_BTAB:
case KEY_BKCH:
j--;
unhilightField(win, Xfptr, 0);
while ((j >= 0) && !FORM_fieldInput (FORM_field (form, input[j])))
j--;
notDone = FALSE;
break;
case KEY_FCH:
case KEY_TAB:
case KEY_CR:
j++;
unhilightField(win, Xfptr, 0);
while ((j < inputFields) && !FORM_fieldInput (FORM_field (form, input[j])))
j++;
notDone = FALSE;
break;
case CUR_KEY_LEFT:
case CUR_KEY_UP:
if (FORM_fieldType(fptr) == 'a' ||
(FORM_fieldType(fptr) == 'X' && FORM_fieldType(Xfptr) != 'M') ||
FORM_fieldType(fptr) == 'n')
{
if( (c == CUR_KEY_UP) || !FORM_fieldExtKey(Xfptr) )
{
ERR_displayError(ERR_NotMenuField);
break;
}
if( xpos == 0 )
ERR_displayStr(" Beginning of field",TRUE);
else
{
xpos--;
if( xpos < idx )
idx = xpos;
}
hilightField(win, Xfptr, idx);
}
else
{
Pos[Xfld]--;
if (Pos[Xfld] < 0)
Pos[Xfld] = MENU_choiceCount(mptr) - 1;
while (MENU_choiceActive (mptr, Pos[Xfld]) == OFF)
{
Pos[Xfld]--;
if (Pos[Xfld] < 0)
Pos[Xfld] = MENU_choiceCount(mptr) - 1;
}
strcpy(FORM_fieldValue(Xfptr),
MENU_choiceLabel(mptr, Pos[Xfld]));
if( isS )
{
tfptr = FORM_field(form,Xfld+2+Pos[Xfld]);
unhilightField(win, tfptr, 0);
}
hilightField(win, Xfptr, 0);
limitChoices();
}
break;
case CUR_KEY_RIGHT:
case CUR_KEY_DOWN:
if (FORM_fieldType(fptr) == 'a' ||
(FORM_fieldType(fptr) == 'X' && FORM_fieldType(Xfptr) != 'M') ||
FORM_fieldType(fptr) == 'n')
{
if( (c == CUR_KEY_DOWN) || !FORM_fieldExtKey(Xfptr) )
{
ERR_displayError(ERR_NotMenuField);
break;
}
len = strlen(FORM_fieldValue(Xfptr));
if( xpos >= len )
ERR_displayStr(" End of field",TRUE);
else
{
xpos++;
if( (xpos - idx) > FORM_fieldLen(Xfptr) )
idx++;
hilightField(win, Xfptr, idx);
}
}
else
{
Pos[Xfld]++;
if (Pos[Xfld] >= MENU_choiceCount(mptr))
Pos[Xfld] = 0;
while (MENU_choiceActive (mptr, Pos[Xfld]) == OFF)
{
Pos[Xfld]++;
if (Pos[Xfld] >= MENU_choiceCount(mptr))
Pos[Xfld] = 0;
}
strcpy(FORM_fieldValue(Xfptr),
MENU_choiceLabel(mptr, Pos[Xfld]));
if( isS )
{
tfptr = FORM_field(form,Xfld+2+Pos[Xfld]);
unhilightField(win, tfptr, 0);
}
hilightField(win, Xfptr, 0);
limitChoices();
}
break;
case KEY_BKSP:
if (FORM_fieldType(fptr) == 'a' ||
(FORM_fieldType(fptr) == 'X' && FORM_fieldType(Xfptr) != 'M') ||
FORM_fieldType(fptr) == 'n')
{
len = strlen(FORM_fieldValue(Xfptr));
if( len == 0 )
ERR_displayStr(" Nothing to delete", TRUE);
else if( xpos == 0 )
ERR_displayStr(" Beginning of field", TRUE);
else
{
strcpy(tbuf,&FORM_fieldValue(Xfptr)[xpos]);
xpos--;
strcpy(&FORM_fieldValue(Xfptr)[xpos],tbuf);
if( xpos < idx )
idx = xpos;
hilightField(win, Xfptr, idx);
}
}
else
ERR_displayStr(" Not applicable in a menu field", TRUE);
break;
case KEY_DEL:
if (FORM_fieldType(fptr) == 'a' ||
(FORM_fieldType(fptr) == 'X' && FORM_fieldType(Xfptr) != 'M') ||
FORM_fieldType(fptr) == 'n')
{
if( !FORM_fieldExtKey(Xfptr) )
{
ERR_displayError(ERR_UndefKey);
break;
}
len = strlen(FORM_fieldValue(Xfptr));
if( len == 0 )
ERR_displayStr(" Nothing to delete", TRUE);
else if( xpos >= len )
ERR_displayStr(" End of field", TRUE);
else
{
strcpy(tbuf,&FORM_fieldValue(Xfptr)[xpos+1]);
strcpy(&FORM_fieldValue(Xfptr)[xpos],tbuf);
hilightField(win, Xfptr, idx);
}
}
else
ERR_displayStr(" Not applicable in a menu field", TRUE);
break;
case KEY_VEOL:
if (FORM_fieldType(fptr) == 'a' ||
(FORM_fieldType(fptr) == 'X' && FORM_fieldType(Xfptr) != 'M') ||
FORM_fieldType(fptr) == 'n')
{
if( !FORM_fieldExtKey(Xfptr) )
{
ERR_displayError(ERR_UndefKey);
break;
}
len = strlen(FORM_fieldValue(Xfptr));
xpos = len;
if( (xpos - idx) > FORM_fieldLen(Xfptr) )
{
idx = xpos - FORM_fieldLen(Xfptr);
if( idx < 0 )
idx = 0;
}
hilightField(win, Xfptr, idx);
}
else
ERR_displayStr(" Not applicable in a menu field", TRUE);
break;
#if 0
case KEY_BOL:
if (FORM_fieldType(fptr) == 'a' ||
(FORM_fieldType(fptr) == 'X' && FORM_fieldType(Xfptr) != 'M') ||
FORM_fieldType(fptr) == 'n')
{
if( !FORM_fieldExtKey(Xfptr) )
{
ERR_displayError(ERR_UndefKey);
break;
}
xpos = idx = 0;
hilightField(win, Xfptr, idx);
}
else
ERR_displayStr(" Not applicable in a menu field", TRUE);
break;
#endif
case KEY_DELEOL:
if (FORM_fieldType(fptr) == 'a' ||
(FORM_fieldType(fptr) == 'X' && FORM_fieldType(Xfptr) != 'M') ||
FORM_fieldType(fptr) == 'n')
{
if( !FORM_fieldExtKey(Xfptr) )
xpos = idx = 0;
for( i=xpos ; i<=FORM_ValueMaxLen ; i++ )
FORM_fieldValue(Xfptr)[i] = '\0';
hilightField(win, Xfptr, idx);
}
else
ERR_displayStr(" Not applicable in a menu field", TRUE);
break;
case KEY_SCR_R:
if (FORM_fieldType(fptr) == 'a' ||
(FORM_fieldType(fptr) == 'X' && FORM_fieldType(Xfptr) != 'M') ||
FORM_fieldType(fptr) == 'n')
{
if( !FORM_fieldExtKey(Xfptr) )
{
ERR_displayError(ERR_UndefKey);
break;
}
len = strlen(FORM_fieldValue(Xfptr));
if( (len <= FORM_fieldLen(Xfptr)) || (xpos == len) )
{
xpos = len;
break;
}
xpos += (FORM_fieldLen(Xfptr) / 2);
idx += (FORM_fieldLen(Xfptr) / 2);
if( xpos > len )
xpos = len;
if( idx >= xpos )
idx = xpos - (FORM_fieldLen(Xfptr) / 2);
if( idx < 0 )
idx = 0;
hilightField(win, Xfptr, idx);
}
else
ERR_displayStr(" Not applicable in a menu field", TRUE);
break;
case KEY_SCR_L:
if (FORM_fieldType(fptr) == 'a' ||
(FORM_fieldType(fptr) == 'X' && FORM_fieldType(Xfptr) != 'M') ||
FORM_fieldType(fptr) == 'n')
{
if( !FORM_fieldExtKey(Xfptr) )
{
ERR_displayError(ERR_UndefKey);
break;
}
xpos -= (FORM_fieldLen(Xfptr) / 2);
idx -= (FORM_fieldLen(Xfptr) / 2);
if( xpos < 0 )
xpos = 0;
if( idx < 0 )
idx = 0;
hilightField(win, Xfptr, idx);
}
else
ERR_displayStr(" Not applicable in a menu field", TRUE);
break;
case KEY_TOP:
j = 0;
unhilightField(win, Xfptr, 0);
notDone = FALSE;
break;
case KEY_BOTTOM:
j = inputFields - 1;
unhilightField(win, Xfptr, 0);
notDone = FALSE;
break;
case KEY_REPAINT:
CUR_clearok(CUR_curscr);
CUR_wrefresh(CUR_curscr);
break;
#if 0
case 'x':
case 'X':
if (FORM_fieldType(fptr) == 'l')
{
MENU_choiceSelect(mptr, MENU_currChoice(mptr)) = 'X';
CUR_wattron(win, (CUR_A_BOLD | FORM_fieldAttr(fptr)));
CUR_wmove(win, FORM_fieldY(fptr), FORM_fieldX(fptr));
CUR_wprintw(win, "%c", 'X');
CUR_wattroff(win, CUR_A_BOLD);
/* CUR_wattroff(win, (CUR_A_BOLD | FORM_fieldAttr(fptr)));*/
break;
}
case ' ':
if (FORM_fieldType(fptr) == 'l')
{
MENU_choiceSelect(mptr, MENU_currChoice(mptr)) = 'X';
CUR_wattron(win, (CUR_A_BOLD | FORM_fieldAttr(fptr)));
CUR_wmove(win, FORM_fieldY(fptr), FORM_fieldX(fptr));
CUR_wprintw(win, "%c", ' ');
CUR_wattroff(win, CUR_A_BOLD);
/* CUR_wattroff(win, (CUR_A_BOLD | FORM_fieldAttr(fptr)));*/
break;
}
#endif
case KEY_QUOTE:
KEY_QuoteNextKey = FALSE;
ERR_displayError(ERR_UndefKey);
break;
default:
if ((c & ~0x7f) || !isprint(c))
ERR_displayError(ERR_UndefKey);
else
if( (FORM_fieldType(Xfptr) == 'a') ||
(FORM_fieldType(Xfptr) == 'A') )
{
addChar();
}
else
if( (FORM_fieldType(Xfptr) == 'n') ||
(FORM_fieldType(Xfptr) == 'N') )
{
if (isdigit(c) ||
(c == '.' && (NULL == strchr(FORM_fieldValue(fptr), '.'))))
{
addChar();
}
else
ERR_displayStr(" Only digits and a decimal point allowed in a Number field", TRUE);
}
else
if( (FORM_fieldType(Xfptr) == 'I') ||
(FORM_fieldType(Xfptr) == 'D') )
{
if (isdigit(c))
{
addChar();
}
else if( FORM_fieldType(Xfptr) == 'I' )
ERR_displayStr(" Only digits allowed in an Integer field",TRUE);
else
ERR_displayStr(" Only digits allowed in a Date field",TRUE);
}
else
ERR_displayError(ERR_MenuField);
break;
} /* switch */
if (notExit == FALSE) break;
} /* while notDone */
} /* while notExit */
resetForm();
return(action);
}
PublicFnDef int FORM_menuToForm()
{
FORM_Field *fptr, *Xfptr, *tfptr;
MENU *mptr;
int fld, isS, isX, Xfld;
fld = FORM_currField(Form);
fptr = FORM_field(Form, fld);
if( FORM_fieldType(fptr) == 'S' )
isS = TRUE;
else
isS = FALSE;
if( FORM_fieldType(fptr) == 'X' )
isX = TRUE;
else
isX = FALSE;
if( isX )
{
Xfld = fld+1+Pos[fld-1];
Xfptr = FORM_field(Form,Xfld);
}
else
{
Xfld = fld;
Xfptr = fptr;
}
mptr = FORM_fieldMenu(Xfptr);
strcpy(FORM_fieldValue(Xfptr),
MENU_choiceLabel(mptr, MENU_currChoice(mptr)));
if( isS )
{
tfptr = FORM_field(Form,Xfld+2+MENU_currChoice(mptr));
unhilightField(Win, tfptr, 0);
}
hilightField(Win, Xfptr, 0);
Pos[Xfld] = MENU_currChoice(mptr);
if (FORM_fieldChoiceArray (Xfptr) != NULL)
CHOICES_LimitOptions (Win, Form,
FORM_fieldChoiceArray(Xfptr)[Pos[Xfld]], Pos);
return(0);
}
PublicFnDef int FORM_centerFormElts(fptr,width)
FORM *fptr;
int width;
{
int i;
for( i=0 ; i<FORM_fieldCount(fptr) ; i++ )
FORM_fieldX(FORM_field(fptr,i)) += ((width - 80) / 2);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_otherutils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lmedusa <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/25 16:10:32 by lmedusa #+# #+# */
/* Updated: 2020/11/25 16:10:34 by lmedusa ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/cub3d.h"
int ft_memcmp(const void *src, const void *src2, size_t n)
{
int res;
size_t i;
unsigned char *src_f;
unsigned char *src2_f;
res = 0;
i = 0;
src_f = (unsigned char *)src;
src2_f = (unsigned char *)src2;
while (i < n)
{
if (src_f[i] != src2_f[i])
{
res = src_f[i] - src2_f[i];
return (res);
}
i++;
}
return (res);
}
void *ft_calloc(size_t num, size_t size)
{
void *mem;
if (!(mem = malloc(num * size)))
return (NULL);
ft_bzero(mem, size * num);
return (mem);
}
int ft_strncmp(const char *s1, const char *s2, size_t n)
{
int rez;
size_t i;
i = 0;
rez = 0;
if (n == 0)
return (0);
while ((s1[i] != '\0') && (s2[i] != '\0') &&\
(s1[i] == s2[i]) && (i != n - 1))
{
i++;
}
rez = (unsigned char)s1[i] - (unsigned char)s2[i];
return (rez);
}
char *ft_strnstr(const char *big, const char *small, size_t len)
{
size_t i;
size_t n;
char *big_f;
big_f = (char *)big;
i = 0;
n = 0;
if (*small == '\0')
return ((char *)big);
i = ft_strlen(small);
while (big[n] && n + i <= len)
{
if (ft_strncmp(&big[n], small, i) == 0)
return (&big_f[n]);
n++;
}
return (NULL);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "key_seq.h"
typedef struct key_seq_item KeySeqItem;
struct key_seq_item {
char *key;
KeySeqItem *next;
};
KeySeqItem *new_key_seq_item(char *key) {
KeySeqItem *ksi = malloc(sizeof *ksi);
ksi->key = strdup(key);
ksi->next = NULL;
return ksi;
}
void free_key_seq_item(KeySeqItem *ksi) {
free(ksi->key);
free(ksi);
}
struct key_seq {
KeySeqItem *first;
KeySeqItem *last;
size_t len;
};
KeySeq *new_key_seq() {
KeySeq *ks = malloc(sizeof *ks);
ks->first = NULL;
ks->last = NULL;
ks->len = 0;
return ks;
}
void free_key_seq(KeySeq *ks) {
KeySeqItem *next;
for (KeySeqItem *cursor = ks->first; cursor != NULL; cursor = next) {
next = cursor->next;
free_key_seq_item(cursor);
}
free(ks);
}
void key_seq_add(KeySeq *ks, char *key) {
KeySeqItem *item = new_key_seq_item(key);
if (ks->last == NULL) {
ks->first = item;
ks->last = item;
} else {
ks->last->next = item;
ks->last = item;
}
ks->len++;
}
int key_seq_ends_with(KeySeq *ks, KeySeq *end) {
if (ks->last == NULL || end->last == NULL) {
return 0;
}
// TODO: Check more than just the last
return !strcmp(ks->last->key, end->last->key);
}
char *key_seq_str(KeySeq *ks) {
char *buf;
size_t len;
FILE *stream = open_memstream(&buf, &len);
for (KeySeqItem *cursor = ks->first; cursor != NULL; cursor = cursor->next) {
fputs(cursor->key, stream);
}
fclose(stream);
return buf;
}
|
C
|
/*
* buffer.c
*
* Created on: Apr 10, 2016
* Author: HaoranFang
*/
#include "buffer.h"
void CircBuf_init(CircBuf_t *cb, size_t size, size_t item_size){
cb->buffer = malloc(size * item_size);
cb->buffer_end = (char *)cb->buffer + size * item_size;
cb->size = size;
cb->item_size = item_size;
cb->num_items = 0;
cb->head = cb->buffer;
cb->tail = cb->buffer;
}
int CircBuf_push(CircBuf_t *cb,const void *item){
if(cb->num_items == cb->size){
return 0;
}
memcpy(cb->head, item, cb->item_size);
cb->head = (char *)cb->head + cb->item_size;
if(cb->head == cb->buffer_end) cb->head = cb->buffer;
cb->num_items = cb->num_items + 1;
return 1;
}
int CircBuf_pop(CircBuf_t *cb, void * return_item){
if(cb->num_items == 0) return 0;
memcpy(return_item, cb->tail, cb->item_size);
cb->tail = (char *)cb->tail + cb->item_size;
//edge condition
if(cb->tail == cb->buffer_end) cb->tail = cb->buffer;
cb->num_items = cb->num_items - 1;
return 1;
}
void CircBuf_free(CircBuf_t *cb)
{
free(cb->buffer);
// clear out other fields too, just to be safe
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(void) {
long * array_a;
long * result;
int size = 5;
array_a = malloc(size * sizeof(long));
memset(array_a, 4, size * sizeof(long));
// allochiamo lo spazio di memoria per la copia
result = malloc(size * sizeof(long));
memcpy(result, array_a, size * sizeof(long));
printf("\n\nArray copiato tramite memcpy:\n");
for(int i=0; i<size; i++){
printf("%d) %ld \n", i+1, result[0]);
}
// INVECE DI MEMCPY POTREI FARE COSì:
long * destination = result;
long * source = array_a;
for (unsigned int i = 0; i < size; i++) {
destination[i] = source[i];
}
printf("\n\nArray copiato col metodo alternativo:\n");
for(int i=0; i<size; i++){
printf("%d) %ld \n", i+1, result[0]);
}
// IMPORTANTE: chi riceve il risultato, dovrà occuparsi di liberare
// la memoria allocata per la copia dell'array
free(array_a);
}
|
C
|
#include"stdio.h"
#include"string.h"
int main(){
FILE* fp = fopen("myfile","r");
if(!fp){
printf("fopen error !\n");
}
char buf[1024];
const char* msg = "hello bit!\n";
while(1){
size_t ret = fread(buf,1,strlen(msg),fp);
if(ret > 0){
buf[ret] = '\0';
printf("%s",buf);
}
if(feof(fp)){
break;
}
}
// int count = 5;
// while(count--){
// fwrite(msg,strlen(msg),1,fp);
// }
fclose(fp);
return 0;
}
|
C
|
#define CROSSLOG_TAG "hexdump"
#include <crosslog.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdint.h>
#ifndef ARRAY_SIZE
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
#endif
#ifndef MIN
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#endif
static inline int local_isprint(int c) {
return ((c >= 0x20) && (c < 0x7f));
}
static ssize_t easy_snprintf(char *s, size_t n, const char *format, ...) {
int rc;
va_list args;
va_start(args, format);
rc = vsnprintf(s, n, format, args);
va_end (args);
if (rc < 0 || (size_t)rc >= n) {
return -1;
}
return (ssize_t)rc;
}
#define BUF_SNPRINTF(buf, off, fmt, ...) easy_snprintf((buf) + (off), ARRAY_SIZE(buf) - (off), fmt, ##__VA_ARGS__)
#define _HEXDUMP_APPENDLINE(fmt, ...) do { \
nbytes = BUF_SNPRINTF(line, linesz, fmt, ##__VA_ARGS__); \
if (nbytes < 0) \
goto err; \
linesz += nbytes; \
} while(0)
void _crosslog_hexdump(const void *_buf, size_t sz) {
char line[79];
size_t i;
size_t j;
const uint8_t *buf = _buf;
ssize_t nbytes;
(void)(buf);
for (i = 0; i < sz; i += 16) {
size_t linesz = 0;
size_t toread = MIN(16, sz - i);
// offset
_HEXDUMP_APPENDLINE("%08zx ", i);
// hexdump
for (j = 0; j < 16; j++) {
if (j < toread) {
_HEXDUMP_APPENDLINE(" %s%02x", j==8?" ":"", buf[i + j]);
}
else {
_HEXDUMP_APPENDLINE("%s ", j==8?" ":"");
}
}
_HEXDUMP_APPENDLINE(" |");
// ascii
for (j = 0; j < 16; j++) {
if (j < toread) {
_HEXDUMP_APPENDLINE("%c", local_isprint(buf[i + j])?buf[i + j]:'.');
}
else {
_HEXDUMP_APPENDLINE(" ");
}
}
_HEXDUMP_APPENDLINE("|");
CROSSLOGV("%s", line);
}
return;
err:
CROSSLOGV("internal hexdump error");
}
#undef _HEXDUMP_APPENDLINE
|
C
|
#include "tag.h"
void TAG_init(TAG *this)
{
memset(this->name, 0, TAG_NAME_SIZE);
this->favs = 0;
this->tags = NULL;
this->tc = 0;
}
int TAG_findTag(TAG *this, TAG t)
{
int i;
for(i = 0 ; i < this->tc ; i++)
{
if(strcmp(this->tags[i].name, t.name) == 0)
{
return i;
}
}
return -1;
}
void TAG_read(TAG *this, FILE *f)
{
fread(this, sizeof(TAG), 1, f);
this->tags = this->tc > 0 ? malloc(this->tc * sizeof(TAG)) : NULL;
int i;
for(i = 0 ; i < this->tc ; i++)
{
TAG_read(&this->tags[i], f);
}
}
void TAG_write(TAG *this, FILE *f)
{
fwrite(this, sizeof(TAG), 1, f);
int i;
for(i = 0 ; i < this->tc ; i++)
{
TAG_write(&this->tags[i], f);
}
}
void TAG_addTag(TAG *this, const char *path, int override)
{
while(*path == '.') path++;
if(*path == '\0') return;
TAG t;
TAG_init(&t);
strcpyv(t.name, path, '.');
path += strlen(t.name);
int i;
for(i = 0 ; i < this->tc ; i++)
{
if(strcmp(this->tags[i].name, t.name) == 0)
{
TAG_addTag(&this->tags[i], path, override);
return;
}
}
if(*path != '\0')
{
if(override)
{
TAG_addTag(&t, path, override);
}
else
{
return;
}
}
this->tags = realloc(this->tags, ++this->tc * sizeof(TAG));
this->tags[this->tc - 1] = t;
}
int TAG_removeTag(TAG *this, const char *path, int override)
{
while(*path == '.') path++;
if(*path == '\0') return 1;
char buf[TAG_NAME_SIZE];
strcpyv(buf, path, '.');
path += strlen(buf);
int i;
for(i = 0 ; i < this->tc ; i++)
{
if(strcmp(this->tags[i].name, buf) == 0)
{
if(*path == '\0')
{
if(this->tags[i].tc == 0 || override)
{
TAG_dispose(&this->tags[i]);
if(--this->tc - i > 0)
{
memmove(this->tags + i, this->tags + i + 1, (this->tc - i) * sizeof(TAG));
}
if(this->tc > 0)
{
this->tags = realloc(this->tags, this->tc * sizeof(TAG));
}
else
{
free(this->tags);
this->tags = NULL;
}
return 1;
}
else
{
return 0;
}
}
else
{
return TAG_removeTag(&this->tags[i], path, override);
}
}
}
return -1;
}
void TAG_listTags(TAG *this, int indent)
{
int i;
for(i = 0 ; i < indent ; i++) printf(" ");
printf("- %s (%d)\n", this->name, this->favs);
for(i = 0 ; i < this->tc ; i++)
{
TAG_listTags(&this->tags[i], indent + 2);
}
}
void TAG_dispose(TAG *this)
{
int i;
for(i = 0 ; i < this->tc ; i++)
{
TAG_dispose(&this->tags[i]);
}
free(this->tags);
TAG_init(this);
}
M_TAG *TAG_evaluateAbs(TAG *this, const char *str, M_TAG *tag)
{
while(*str == '.') str++;
if(*str == '\0') return tag;
if(tag == NULL)
{
tag = malloc(sizeof(M_TAG));
tag->c = 0;
tag->path = NULL;
}
char buf[TAG_NAME_SIZE];
strcpyv(buf, str, '.');
str += strlen(buf);
int i;
for(i = 0 ; i < this->tc ; i++)
{
if(strcmp(this->tags[i].name, buf) == 0)
{
tag->path = realloc(tag->path, ++tag->c * sizeof(int));
tag->path[tag->c - 1] = i;
return TAG_evaluateAbs(&this->tags[i], str, tag);
}
}
free(tag->path);
free(tag);
return NULL;
}
M_TAG *TAG_evaluatePart(TAG *this, const char *str, M_TAG *tags, int *l)
{
if(*str == '.')
{
M_TAG *tag = TAG_evaluateAbs(this, str, NULL);
if(tag != NULL)
{
tags = realloc(tags, ++(*l) * sizeof(M_TAG));
tags[*l - 1] = *tag;
free(tag);
}
return tags;
}
char buf[TAG_NAME_SIZE];
strcpyv(buf, str, '.');
int i;
for(i = 0 ; i < this->tc ; i++)
{
if(strcmp(this->tags[i].name, buf) == 0)
{
tags = TAG_evaluatePart(&this->tags[i], str + strlen(buf), tags, l);
}
tags = TAG_evaluatePart(&this->tags[i], str, tags, l);
}
return tags;
}
char **addString(char **src, char *line, int *size)
{
int l = *size;
src = realloc(src, ++l * sizeof(char *));
src[l - 1] = strdup(line);
*size = l;
return src;
}
char **expand(TAG *this, const char *str, int *size, char **tmp, char *path)
{
char buf[1024];
if(*str == '\0')
{
return addString(tmp, path, size);
}
if(*str == '.')
{
M_TAG *t = TAG_evaluateAbs(this, str, NULL);
if(t == NULL) return tmp;
free(t);
strcpy(buf, path);
strcat(buf, str);
return addString(tmp, buf, size);
}
char name[TAG_NAME_SIZE];
strcpyv(name, str, '.');
int i;
for(i = 0 ; i < this->tc ; i++)
{
if(strcmp(this->tags[i].name, name) == 0)
{
strcpy(buf, path);
strcat(buf, ".");
strcat(buf, name);
tmp = expand(&this->tags[i], str + strlen(name), size, tmp, buf);
}
else
{
strcpy(buf, path);
strcat(buf, ".");
strcat(buf, this->tags[i].name);
tmp = expand(&this->tags[i], str, size, tmp, buf);
}
}
return tmp;
}
char **TAG_expand(TAG *this, const char *str, int *size)
{
char eos = '\0';
return expand(this, str, size, NULL, &eos);
}
int M_TAG_compIntArr(M_TAG *m1, M_TAG *m2)
{
if(m2->c < m1->c) return 0;
int c = m1->c;
int i;
for(i = 0 ; i < c ; i++)
{
if(m1->path[i] != m2->path[i]) return 0;
}
return 1;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* libft.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tmeizo <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/10/28 11:11:52 by tmeizo #+# #+# */
/* Updated: 2021/03/12 14:46:37 by bmicheal ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef LIBFT_H
# define LIBFT_H
# include <stddef.h>
# include "gnl/get_next_line.h"
typedef struct s_list
{
void *content;
struct s_list *next;
} t_list;
void *ft_memset(void *b, int c, size_t len);
void ft_bzero(void *s, size_t n);
void *ft_memcpy(void *dst, const void *src, size_t n);
void *ft_memccpy(void *dst, const void *src, int c, size_t n);
void *ft_memmove(void *dst, const void *src, size_t len);
void *ft_memchr(const void *s, int c, size_t n);
int ft_memcmp(const void *a, const void *b, size_t n);
size_t ft_strlen(const char *s);
size_t ft_strlcpy(char *dst, const char *src, size_t dstsize);
size_t ft_strlcat(char *dst, const char *src, size_t dstsize);
char *ft_strchr(const char *s, int c);
char *ft_strrchr(const char *s, int c);
char *ft_strnstr(const char *haystack,
const char *needle, size_t len);
int ft_strcmp(const char *a, const char *b);
int ft_strncmp(const char *a, const char *b, size_t n);
int ft_atoi(const char *s);
int ft_isalpha(int c);
int ft_isdigit(int c);
int ft_isalnum(int c);
int ft_isascii(int c);
int ft_isprint(int c);
int ft_toupper(int c);
int ft_tolower(int c);
void *ft_calloc(size_t count, size_t size);
char *ft_strdup(const char *s);
char *ft_substr(const char *s, unsigned int start, size_t len);
char *ft_strjoin(const char *a, const char *b);
char *ft_strtrim(const char *s, const char *set);
char **ft_split(const char *s, char c);
char *ft_itoa(int n);
char *ft_strmapi(const char *s, char (*f)(unsigned int, char));
void ft_putchar_fd(char c, int fd);
void ft_putstr_fd(char *s, int fd);
void ft_putendl_fd(char *s, int fd);
void ft_putnbr_fd(int n, int fd);
t_list *ft_lstnew(void *content);
int ft_lstsize(t_list *lst);
t_list *ft_lstlast(t_list *lst);
void ft_lstadd_back(t_list **lst, t_list *new);
void ft_lstadd_front(t_list **lst, t_list *new);
void ft_lstdelone(t_list *lst, void (*del)(void *));
void ft_lstclear(t_list **lst, void (*del)(void *));
void ft_lstiter(t_list *lst, void (*f)(void *));
t_list *ft_lstmap(t_list *lst, void *(*f)(void *),
void (*del)(void *));
double ft_atof(char *s);
#endif
|
C
|
/*
* File: tpmeta1.c
* Author: rodrigo
*
* Created on 24 de Outubro de 2018, 15:54
*/
#include <stdio.h>
#include <stdlib.h>
#include "medit_defaults.h"
#include "server_defaults.h"
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/select.h>
#include <errno.h>
#include <signal.h>
WINDOW *vin;
void show_settings(Settings settings, char filenamepath[], int max_users, int npipes);
int verify_user(char filename[], char user[]);
void show_users();
void printmatrix(Settings settings, char tabela[settings.lines][settings.columns]);
void fillmatrix(Settings settings,char tabela[settings.lines][settings.columns]);
void edit(Settings settings, char tabela[settings.lines][settings.columns]);
int main(int argc, char** argv) {
//---------------------Variáveis----------------------//
char inputstring[50]; // string onde é guardada a string de comando da linha de comandos do servidor
char command[10]; // 1º parametro dos comandos da linha de comandos do servidor
char parametro[20]; // 2º parametro dos comandos da linha de comandos do servidor
char filepathname[100]; //pathname do ficheiro com usernames
//char caststring[20]; // ?
char intfifostring[10]; //string para criação de fifos de interação
char tempstring[20]; //string temporaria para operacoes
int getoptresult; // resultado da operação getopt()
//int setenvresult; // resultado da operação setenv
int max_users; //nº máximo de utilizadores
int npipes; // nº de pipes de interação
int fdservidor; // file descriptor do fifo para aceitação de clientes por parte do servidor
// vetor com file descriptors dos fifos para escrita com os clientes
Settings settings; // Settings que armazenam os settings do servidor
Text_Interaction_Vars itv; //variáveis para manipular a edição de texto
Users tmp;
//----------------------------------------------------//
//--------- Variáveis de Ambiente --------------------//
settings.columns = atoi(getenv("MEDIT_MAXCOLUMNS"));
settings.lines = atoi(getenv("MEDIT_MAXLINES")); // estes valores podem mudar ou não no getopt() caso tenham sido incluidos
max_users = atoi(getenv("MEDIT_MAXUSERS")); // na linha de comando que executou o servidor
//fprintf(stderr,"D\n");
strncpy(settings.pipe_name,getenv("FIFO"),100);
settings.timeout=atoi(getenv("MEDIT_TIMEOUT"));
strncpy(filepathname,getenv("FILE"),100);
npipes = atoi(getenv("INTERACTIVE"));
//--------------------------------------------------//
//---------Obtenção de parâmetros da consola----------//
opterr = 0;
while((getoptresult = getopt(argc,argv,"c:l:f:n:p:m:t:")) != -1) //código adaptado da página sobre getopt() de gnu.org
{
switch(getoptresult)
{
case 'f':
strncpy(filepathname,optarg,100);
break;
case 'c':
settings.columns = atoi(optarg);
break;
case 'l':
settings.lines = atoi(optarg);
break;
case 'p':
strncpy(settings.pipe_name,optarg,100);
break;
case 'n':
npipes = atoi(optarg);
break;
case 'm':
max_users = atoi(optarg);
break;
case 't':
settings.timeout = atoi(optarg);
break;
case '?'://getopt() devolve '?' se faltar um argumento de opção ou se o utilizador utilizou outro carater para alem dos carateres de opções
if (optopt == 'f' || optopt =='l' || optopt =='c' || optopt =='n' || optopt =='m' || optopt =='t' || optopt =='p'){
wprintw(vin, "Option -%c requires an argument.\n", optopt);
}
else if (isprint (optopt)) //se o carater de opção é printable
{
wprintw(vin, "Unknown option '-%c'.\n", optopt);
}
else{
wprintw(vin,"Unknown option character '\\x%x'.\n",optopt);
}
wprintw(vin,"Entrei no case ?\n");
wrefresh(vin);
wgetch(vin);
delwin(vin);
endwin();
return 1;
}
}
//---------------------------------------------------------------------------//
//------------Inicialização de varíáveis / pipes ----------//
int fdinteractionfifos[npipes]; //file descriptors para ler dos clientes (FIFOs de interação)
int ammountclientsfifos[npipes]; // array com o numero de clientes que cada fifo tem.
int fdclientfifos[max_users]; //file descriptors para escrever para os clientes
Users users[max_users];
strncpy(tempstring,"intfifo",8);
mkfifo(settings.pipe_name,0777);
fdservidor = open(settings.pipe_name,O_RDWR); // fifo aberto para leitura e escrita mas apenas será usado para leitura, a não ser em ocasiões especiais
for(int i = 0; i < npipes; i++)
{
ammountclientsfifos[i] = 0;
snprintf(intfifostring,9,"%s%d",tempstring,i);
fprintf(stderr,"%s\n",intfifostring);
mkfifo(intfifostring,0777);
fdinteractionfifos[i] = open(intfifostring,O_RDWR);
}
for(int i = 0;i<max_users;i++) //inicialliza o array de file descriptors para escrita com clientes a -1.
{
fdclientfifos[i] = -1;
}
//--------------------------------------------------------//
//------------------Inicialização Janela------------//
initscr();
start_color(); //codigo de inicialização da window
init_pair(1,COLOR_WHITE,COLOR_BLACK);
vin = newwin(0,0,0,0);
scrollok(vin,TRUE); //deixar com que a janela seja scrollable, que o texto possa ser todo representado
wbkgd(vin,COLOR_PAIR(1)); //as cores do pair 1 serao as da janela
keypad(stdscr,TRUE);
cbreak();
//wprintw(vin, "Olá %d %d\n",atoi(getenv("COLUMNS")),atoi(getenv("LINES")));
wrefresh(vin);
//---------------------------------------------------//
//------------Verificação de utilizador 1ª meta------------//
/*
fillmatrix(settings,itv.tabela);
wrefresh(vin);
if(verify_user(filepathname,"ze")==1)
{
wprintw(vin,"O utilizador ze existe.\n");
}
else
wprintw(vin, "O utilizador ze nao existe.\n");
*/
//------------------------------------------------------------//
//------------Código de obtenção de comandos------------//
fd_set read_tmp, read_set;
FD_ZERO(read_set);
FD_SET(fdservidor, &read_set); //fifo de receção
FD_SET(0,&read_set); //stdin
for(int i=0;i<npipes;i++)
{
FD_SET(intfifos[i],&read_set);
}
while(1){
FD_ZERO(&read_tmp);
read_tmp = read_set;
switch(select(npipes + 2, &read_tmp, NULL, NULL, NULL)) {
case -1:
if(errno=EINTR) continue;
else {
perror("Unexpected select() error!");
unlink(fdservidor);
for(int i = 0; i < npipes;i++)
{
snprintf(intfifostring,9,"%s%d",tempstring,i);
//strncat(intfifostring,c,7);
unlink(intfifostring);
}
return (EXIT_FAILURE);
}
break;
default:
break;
}
if(FD_ISSET(0, &read_tmp)){
do{
wprintw(vin,"Introduza um comando:\n->");
wrefresh(vin);
wscanw(vin,"%[^\n]s",&inputstring);
sscanf(inputstring, "%s %s",command,parametro);
if(strcmp(command,"settings")==0)
{
show_settings(settings,filepathname,max_users,npipes);
}
if(strcmp(command,"load")==0)
{
wprintw(vin,"ficheiro: %s\n",parametro);
wprintw(vin,"Funcao load por implementar\n");
}
if(strcmp(command,"save")==0)
{
wprintw(vin,"ficheiro: %s\n",parametro);
wprintw(vin,"Funcao save por implementar\n");
}
if(strcmp(command,"free")==0)
{
wprintw(vin,"ficheiro: %s\n",parametro);
wprintw(vin,"Funcao free por implementar\n");
}
if(strcmp(command,"users")==0)
{
show_users(filepathname);
}
if(strcmp(command,"edit")==0)
{
edit(settings,itv.tabela);
}
if(strcmp(command,"text")==0)
{
printmatrix(settings,itv.tabela);
}
}while(strncmp(command,"shutdown",8)!=0);
}
else if(FD_ISSET(fdservidor,&read_tmp))
{
if(!read(fdservidor,&tmp,sizeof(Users)))
{
wprintw(vin,"Error on read on server fifo\n");
}
else if(verify_user(tmp.username)){
wprintw(vin,"Utilizador %s é valido\n",tmp.username);
users[0].username = tmp.username;
users[0].fifoname = tmp.fifoname;
fdclientfifos[0] = open(users[0].fifoname,O_WRONLY);
users[0].interactionfifo = select
write(fdclientfifos[0],)
}
else
kill(users[0].fifoname,SIGUSR1);
}
}
//------------------------------------------------------------//
unlink(settings.pipe_name);
strncpy(intfifostring,"intfifo",7);
for(int i = 0; i < npipes;i++)
{
snprintf(intfifostring,9,"%s%d",tempstring,i);
//strncat(intfifostring,c,7);
unlink(intfifostring);
}
wprintw(vin, "Prima uma tecla para sair\n");
wrefresh(vin);
wgetch(vin);
delwin(vin);
endwin();
return (EXIT_SUCCESS);
}
void show_settings(Settings settings, char filepathname[],int max_users, int npipes){
wprintw(vin,"\n-----Parametros do Servidor-----\nCaminho da Base de Dados: %s\nNumero de linhas: %d\n"
"Numero de colunas: %d\nNumero Maximo de utilizadores: %d\nNumero de named pipes Interacao: %d\n"
"Caminho do named pipe principal: %s\nTimeout (em segundos) de edicao de linha: %d\n",
filepathname,settings.lines,settings.columns,max_users,npipes,settings.pipe_name,settings.timeout);
}
int verify_user(char filename[],char user[]){
char nome[50];
char c;
int i=0;
int file = open(filename,O_RDONLY);
if(file ==-1)
wprintw(vin,"Erro ao abrir ficheiro\n");
else
wprintw(vin,"Ficheiro %s aberto com sucesso!\n",filename);
while(read(file,&c,1)>0)
{
if(c!='\n'){
nome[i] = c;
i++;
}
else
{
nome[i]='\0';
i=0;
if(strncmp(nome,user,8)==0)
return 1;
}
}
return 0;
}
void show_users(char filename[])
{
char nome[50];
char c;
int i=0,j=1;
int file = open(filename,O_RDONLY);
if(file ==-1)
wprintw(vin,"Erro ao abrir ficheiro\n");
else
wprintw(vin,"Ficheiro %s aberto com sucesso!\n",filename);
while(read(file,&c,1)>0)
{
if(c!='\n'){
nome[i] = c;
i++;
}
else
{
nome[i]='\0';
i=0;
wprintw(vin,"Utilizador num%d: %s\n",j,nome);
j++;
}
}
}
void edit(Settings settings, char tabela[settings.lines][settings.columns]){
int mode=1,d;
char ch,c='*',posx=0,posy=0,tmpchar;
wclear(vin);
//noecho();
for(int i = 0;i<settings.lines;i++)
{
for(int j=0;j<settings.columns;j++)
{
if(j==0)
{
wprintw(vin,"%d",i+1);
}
wprintw(vin,"%c",tabela[i][j]);
wrefresh(vin);
if(j==settings.columns-1)
wprintw(vin,"\n");
}
}
//mvcur(0,0,0,0);
//mvwaddch(vin,0,0,' ');
//fscanf(stdout,"%d",&d);
//wprintw(vin,"%d\n",d);
//mvwaddch(vin,0,0,c);
//mvwaddch(vin,0,1,d + '0');
wrefresh(vin);
while(true)
{
if(mode==1)
{
ch = wgetch(vin);
if(ch==27) //27 = ESC
{
break;
}
if(ch==KEY_UP)
{
if(posy>0)
{
wprintw(vin,"\b \b");
posy++;
mvwaddch(vin,posx,posy,c);
}
break;
}
}
}
}
void fillmatrix(Settings settings,char tabela[settings.lines][settings.columns])
{
for(int i = 0;i<settings.lines;i++)
{
for(int j=0;j<settings.columns;j++)
{
tabela[i][j]= ' ';
}
}
}
void printmatrix(Settings settings, char tabela[settings.lines][settings.columns])
{
wclear(vin);
for(int i = 0;i<settings.lines;i++)
{
for(int j=0;j<settings.columns;j++)
{
if(j==0)
{
wprintw(vin,"%d",i+1);
}
wprintw(vin,"%c",tabela[i][j]);
wrefresh(vin);
if(j==settings.columns-1)
wprintw(vin,"\n");
}
}
wprintw(vin,"Clique num botao\n");
wgetch(vin);
}
|
C
|
#include <avr/io.h>
#include <util/delay.h>
//define pins
#define PIN_LED1 PB0
#define PIN_LED2 PB1
//define delay time
#define DELAY_MS 250
//write high
#define D_HIGH(prt, pn) prt |= (1<<pn)
//write low
#define D_LOW(prt, pn) prt &= ~(1<<pn)
//long delay, 8 bit timer protect, max 10
void long_delay_ms(uint16_t ms){
for(ms /= 10; ms > 0; ms--)_delay_ms(10) ;
}
int main(void){
DDRB |= (1 << PIN_LED1) | (1 << PIN_LED2);
D_LOW(PORTB, PIN_LED1);
D_LOW(PORTB, PIN_LED2);
uint8_t toggle = 0;
for(;;){
D_HIGH(PORTB, (toggle == 0 ? PIN_LED1 : PIN_LED2));
D_LOW(PORTB, (toggle == 0 ? PIN_LED2 : PIN_LED1));
toggle = !toggle;
long_delay_ms(DELAY_MS);
}
return 0;
}
|
C
|
/* super basic shell - starting point we can build off (using std functions) */
#include "simpleshell.h"
/**
* main - main for simple shell
* @ac: number of arguments
* @av: array of pointers to strings containing arguments passed
* @env: environmental vars being passed to shell
*
* Return: status
*/
int main(int ac, char *av[], char **env)
{
char *line = NULL, **token, *del = " ", *path = NULL;
size_t len = 0;
ssize_t actual;
int btest;
startup(ac, av);
namesave(av);
do {
print_prompt();
actual = getline(&line, &len, stdin);
global.line_no++;
record_history(line, actual);
nl_remover(line);
if (actual == -1)
{
if (flags.interactive)
write(STDERR_FILENO, "\n", 1);
break;
}
if (*line == '\0')
continue;
if (double_space_remover(line) == 0)
continue;
token = parser(line, del);
btest = search_builtins(token);
if (btest == 1)
{
path = path_finder(env);
fork_exec(path, token, env);
}
free(line);
line = NULL;
len = 0;
free(token);
free(global.command);
global.command = NULL;
} while (flags.exit == false);
return (global.exit_status);
}
/**
* record_history - records all input to the program and write out to perm file
* @input: input from getline()
* @len: num of bytes read by getline()
*
* Return: VOID
*/
void record_history(char *input, ssize_t len)
{
static int file_tmp;
int file_perm;
static size_t written_total;
ssize_t bytes_written;
char buffer[524288];
char *temp = "/tmp/simple_shell_tmp_history";
char *path = "/home/vagrant/.simple_shell_history";
if (flags.startup)
{
file_tmp = open(temp, O_WRONLY | O_CREAT | O_TRUNC, 00666);
if (file_tmp < 0)
return;
close(file_tmp);
file_tmp = open(temp, O_WRONLY, 00666);
if (file_tmp < 0)
return;
}
bytes_written = write(file_tmp, input, len);
if (bytes_written < 0)
return;
if ((ssize_t)bytes_written < len)
return;
written_total += bytes_written;
if (flags.exit == true)
{
close(file_tmp);
file_tmp = open(temp, O_RDONLY);
file_perm = open(path, O_RDWR | O_CREAT | O_APPEND, 00666);
if (file_perm < 0)
return;
read(file_tmp, buffer, written_total);
write(file_perm, buffer, written_total);
close(file_tmp);
close(file_perm);
}
}
/**
* print_prompt - if interactive mode, print prompt to stderr, else no prompt
*
* Return: VOID
*/
void print_prompt(void)
{
static char *prompt = "$ ";
if (flags.interactive == true)
write(STDERR_FILENO, prompt, 3);
}
/**
* startup - run all shell startup proscesses
* @ac: argument count
* @av: argument list
* Return: VOID
*/
void startup(int ac, char **av)
{
/* set startup flag */
flags.startup = true;
/* may end up tx startup sequences of functions here */
if (ac > 1)
global.input = open(av[1], O_RDONLY);
else
global.input = STDIN_FILENO;
if (isatty(STDOUT_FILENO) == 1 && isatty(global.input) == 1)
{
flags.interactive = true;
signal(SIGINT, &sig_handler);
}
/* set up record keeping */
record_history(NULL, 0);
/* unset startup flag */
flags.startup = false;
}
/**
* sig_handler - stops ctrl+c from exiting shell
* @n: is the actual command coming in from the OS signal
*/
void sig_handler(int n __attribute__((unused)))
{
char *prompt = "\n$ ";
write(STDERR_FILENO, prompt, 3);
}
|
C
|
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "lib/xalloc.h"
#include "lib/contracts.h"
#include "lib/bitvector.h"
#include "board-ht.h"
#include "lib/queue.h"
#include "lib/hdict.h"
#include "lib/boardutil.h"
// Abbreviation for lazyness
typedef struct board_data bd;
void free_value(void* v)
{
bd *free_me = (bd*) v;
free(free_me);
return;
}
bitvector make_move(int row, int col, uint8_t width_out,
uint8_t height_out, bitvector B) {
uint8_t i = get_index(row, col, width_out, height_out);
bitvector newboard = bitvector_flip(B, i);
if (row+1 < height_out) {
i = get_index(row+1, col, width_out, height_out);
newboard = bitvector_flip(newboard, i);
}
if (row-1 >= 0) {
i = get_index(row-1, col, width_out, height_out);
newboard = bitvector_flip(newboard, i);
}
if (col+1 < width_out) {
i = get_index(row, col+1, width_out, height_out);
newboard = bitvector_flip(newboard, i);
}
if (col-1 >= 0) {
i = get_index(row, col-1, width_out, height_out);
newboard = bitvector_flip(newboard, i);
}
return newboard;
}
void get_moves(bitvector solution, uint8_t width_out){
for (uint8_t i = 0; i < BITVECTOR_LIMIT; i++) {
bool tmp = bitvector_get(solution, i);
if (tmp){
uint8_t row = i / width_out;
uint8_t col = i % width_out;
printf("%d:%d\n", row, col);
}
}
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "Usage: lightsout <board name>\n");
return 1;
}
//Initialize variables
char *board_filename = argv[1];
queue_t Q = queue_new();
hdict_t H = ht_new((size_t)1000);
bitvector newboard = bitvector_new();
uint8_t width_out, height_out = 0;
//Check if board can be read
if (!file_read(board_filename, &newboard, &width_out, &height_out)) {
fprintf(stderr, "Error loading file\n");
queue_free(Q, NULL);
hdict_free(H);
return 1;
}
//Enqueue initial board
bitvector solution = bitvector_new();
bd *A = xmalloc(sizeof(bd));
A->board = newboard;
A->solution = solution;
ht_insert(H, A);
enq(Q, (void*) A);
//Breath First Search
while (!queue_empty(Q)) {
bd* M = (bd*) deq(Q);
newboard = M->board;
solution = M->solution;
for (int row = 0; row < height_out; row++) {
for (int col = 0; col < width_out; col++) {
//Make move
newboard = make_move(row, col, width_out,
height_out, newboard);
solution = bitvector_flip(solution, get_index(row,
col, width_out, height_out));
//if board is solved free all data structures
if (bitvector_equal(newboard, bitvector_new())) {
get_moves(solution, width_out);
queue_free(Q, NULL);
hdict_free(H);
return 0;
}
// Else add element to hash table and enq
if (ht_lookup(H, newboard) == NULL) {
bd *N = xmalloc(sizeof(bd));
N->board = newboard;
N->solution = solution;
ht_insert(H, N);
enq(Q, (void*) N);
}
}
}
}
// Free memory
queue_free(Q, NULL);
hdict_free(H);
fprintf(stderr, "No solution\n");
return 1;
}
|
C
|
/* Name : Huong Truong
* Class : CSCI 2240-003
* Program # : 3
* Due Date : Oct 24 2016
*
* Honor Pledge: On my honor as a student of the University
* of Nebraska at Omaha, I have neither given nor received
* unauthorized help on this homework assignment.
*
* NAME: Huong Truong
* EMAIL: [email protected]
* NUID: 52233854
* Colleagues: None
*/
/* Fuction Name: main
* Parameters: argc, argv for command line arguments
* Return: 0 for successful execution
* Description: This program will compile the data passed in and stored in memory. Then it executes the instructions in memory.
*/
#include <stdio.h>
#include <string.h>
#include "vc_memory.h"
#include "vc_execution.h"
#include "vc_compilation.h"
int main()
{
Memory memory;
memset(&memory, 0, sizeof(memory));
compile(&memory);
/* If memory->instrucionRegister == 1 a compilation error occured */
if(!memory.instructionRegister) {
execute(&memory);
}
return 0;
}
|
C
|
#include <stdint.h>
#include "Skribist.h"
/*
So as it turns out, these first three naive macros are actually
faster than any bit-tricks or specialized functions on amd64.
*/
#define min(a, b) ((a) < (b) ? (a) : (b))
#define max(a, b) ((a) > (b) ? (a) : (b))
#define gabs(x) ((x) >= 0 ? (x) : -(x))
#define floorf(x) __builtin_floorf(x)
#define roundf(x) __builtin_roundf(x)
#define ceilf(x) __builtin_ceilf(x)
#define GRAIN_BITS 8
#define GRAIN (1 << GRAIN_BITS)
typedef struct {
float x, y;
} Point;
typedef struct {
Point beg, end;
} Line;
typedef struct {
Point beg, end, ctrl;
} Curve;
typedef struct {
RasterCell * restrict raster;
SKR_Dimensions dims;
uint32_t rasterWidth;
} Workspace;
char * FormatUint(unsigned int n, char buf[8]);
unsigned long LengthOfString(char const * str);
int CompareStrings(char const * a, char const * b, long n);
Point Midpoint(Point a, Point b);
__attribute__((noreturn))
void SKR_assert_fail(char const * expr, char const * file,
unsigned int line, char const * function);
#define SKR_assert(expr) \
((void) ((expr) ? 0 : (SKR_assert_fail(#expr, __FILE__, __LINE__, __FUNCTION__), 0)))
typedef uint8_t const BYTES1;
typedef uint16_t const BYTES2;
typedef uint32_t const BYTES4;
static inline uint16_t ru16(BYTES2 raw)
{
BYTES1 * bytes = (BYTES1 *) &raw;
uint16_t b0 = bytes[1], b1 = bytes[0];
return b0 | b1 << 8;
}
static inline int16_t ri16(BYTES2 raw)
{
uint16_t u = ru16(raw);
return *(int16_t *) &u;
}
static inline uint32_t ru32(BYTES4 raw)
{
BYTES1 * bytes = (BYTES1 *) &raw;
uint32_t b0 = bytes[3], b1 = bytes[2];
uint32_t b2 = bytes[1], b3 = bytes[0];
return b0 | b1 << 8 | b2 << 16 | b3 << 24;
}
|
C
|
#include <stdio.h>
void main(void)
{
FILE *fp;
fp = fopen("c:\\file.txt", "w+");
if(fp == NULL)
{
puts("파일을 생성할 수 없습니다.");
}
else
{
printf("파일 포인터의 위치 : %d\n", ftell(fp));
fputs("abcde", fp);
printf("파일 포인터의 위치 : %d\n", ftell(fp));
rewind(fp);
printf("파일 포인터의 위치 : %d\n", ftell(fp));
fclose(fp);
}
}
|
C
|
/***************************************************************************************************/
/* */
/* Copyright (C) 2004 Bauhaus University Weimar */
/* Released into the public domain on 6/23/2007 as part of the VRPN project */
/* by Jan P. Springer. */
/* */
/***************************************************************************************************/
/* */
/* module : vrpn_atmellib_helper.C */
/* project : atmel-avango */
/* description: part of the serial lib for the Atmel */
/* miscellaneous functions */
/* */
/***************************************************************************************************/
/* include system headers */
#include <errno.h> // for error_t
#include <stdio.h> // for printf
/* include i/f header */
#include "vrpn_atmellib.h" // for command_t, getCmd, setCmd, etc
#include "vrpn_atmellib_errno.h" // for ATMELLIB_NOERROR, etc
#include "vrpn_atmellib_helper.h"
/***************************************************************************************************/
/* set the defined bit in the command to the expected value and leave the rest like it is */
/***************************************************************************************************/
error_t
setBitCmd( struct command_t * Cmd , const unsigned char Pos , unsigned char Val )
{
/* check if the parameter are valid */
if ((Val != 0) && (Val != 1))
return ATMELLIB_ERROR_VALINV;
if (Pos > 7)
return ATMELLIB_ERROR_VALINV;
/* check if the value for "our" pin is already correct else change it */
if (Pos == 7) {
/* bit seven is in byte one */
if (((*Cmd).addr) & 0x01) {
if (Val == 0)
(*Cmd).addr -= 1; /* it's 1 and it has to be 0*/
}
else {
if (Val == 1) /* it's 0 and it has to be 1 */
(*Cmd).addr += 1;
}
}
else { /* the bits in the second byte */
unsigned char Reference = 0x01 << Pos;
if ( ((*Cmd).value) & Reference ) {
if (Val == 0)
(*Cmd).value -= PowToTwo(Pos);
}
else { /* change necessary */
if (Val == 1)
(*Cmd).value += PowToTwo(Pos);
}
}
return ATMELLIB_NOERROR;
}
/***************************************************************************************************/
/* change only one bit of the value of the specified register */
/***************************************************************************************************/
error_t
setBitReg( const handle_t Hd , const unsigned char Reg , \
const unsigned char Pos , const unsigned char Val )
{
struct command_t Cmd;
error_t R;
unsigned char i;
/* check if the parameters are valid */
if ((Val != 0) && (Val != 1))
return ATMELLIB_ERROR_VALINV;
/* set the correct address for the register */
/* check if the first bit is already set or if it has to be done here */
if (Reg & 0x80)
Cmd.addr = Reg;
else {
Cmd.addr = Reg + 64;
Cmd.addr <<= 1;
}
Cmd.value = 0x00;
/* get the current setting of the register on the microcontroller */
/* if you get sth invalid try again */
for (i=0 ; i<10 ; ++i) {
if ( (R = getCmd( Hd , &Cmd )) != ATMELLIB_NOERROR )
return R;
if ( Cmd.value<128)
break;
}
if (i==10)
return ATMELLIB_ERROR_NOSTATEVAL;
if ( (R = setBitCmd( &Cmd , Pos , Val )) != ATMELLIB_NOERROR)
return R;
/* write the corrected value back to the microcontroller */
if ( (R = setCmd( Hd , &Cmd )) != ATMELLIB_NOERROR )
return R;
return ATMELLIB_NOERROR;
}
/***************************************************************************************************/
/* 2^Exponent */
/***************************************************************************************************/
unsigned int
PowToTwo( unsigned int Exponent )
{
unsigned int i;
unsigned int R = 1;
for( i=0 ; i<Exponent ; i++)
R *= 2;
return R;
}
/***************************************************************************************************/
/* valid address byte to the specified register */
/* the MSB data bit is set to zero */
/***************************************************************************************************/
unsigned char
getAddress( unsigned char Reg )
{
Reg += 64;
Reg <<= 1;
return Reg;
}
/***************************************************************************************************/
/* set the value in a two byte command */
/***************************************************************************************************/
void
setValue( struct command_t * Cmd , unsigned char Val)
{
if (Val>127) {
Val -= 128;
if ( ! ((*Cmd).addr & 0x01))
(*Cmd).addr +=1;
}
else
if ((*Cmd).addr & 0x01)
(*Cmd).addr -=1;
(*Cmd).value = Val;
}
/***************************************************************************************************/
/* helper function */
/***************************************************************************************************/
/* extern */ void
outBit( unsigned char Arg )
{
unsigned char Ref;
for ( Ref=0x80 ; Ref != 0x00 ; Ref >>= 1 ) {
if (Ref & Arg)
printf("1");
else
printf("0");
}
printf("\n");
}
#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
# pragma set woff 1174
#endif
#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
# pragma reset woff 1174
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <stdbool.h>
#define DIM 30
#define OVERFLOW_SUM_COND (op2 > 0 && (op1 > INT_MAX - op2)) || (op2 < 0 && (op1 < INT_MIN - op2))
#define OVERFLOW_SUBTRACT_COND (op2 > 0 && (op1 < INT_MIN + op2) ) || (op2 < 0 && op1 > INT_MAX + op2)
#define COND_1 op1 > 0 && op2 > 0 && op1 > INT_MAX/op2
#define COND_2 op1 > 0 && op2 <= 0 && op2 < INT_MIN/op1
#define COND_3 op1 <= 0 && op2 > 0 && op1 < INT_MIN/op2
#define COND_4 op1 <= 0 && op2 <= 0 && op1!=0 && op2 < INT_MAX/op1
#define OVERFLOW_MULT_COND COND_1 || COND_2 || COND_3 || COND_4
_Bool Overflow = false;
typedef struct espressione{
char* stringa;
struct espressione* next;
}Espressione;
typedef struct elem_pila{
int num;
struct elem_pila* next;
}Elem_pila;
typedef Espressione* ListaEspressioni;
typedef Elem_pila* Pila;
void* allocazione_sicura(int n, size_t dim_tipo);
void insert_espressione(ListaEspressioni *list, char* stringa);
void salva_stringa(char* buffer);
void risolvi_lista_espressioni(ListaEspressioni* lista);
void operazione(int op1, int op2, char operatore, Pila* pila, char** token);
void push(Pila *pila, int num);
int pop(Pila *pila);
void print_Two_Complement(int num, int array[]);
void free_lista(ListaEspressioni list);
int main(void){
char riga[DIM];
ListaEspressioni lista = NULL;
salva_stringa(riga);
while(strcmp(riga, "fine") != 0){
insert_espressione(&lista, riga);
salva_stringa(riga);
}
risolvi_lista_espressioni(&lista);
free_lista(lista);
}
void free_lista(ListaEspressioni list){
while((list) != NULL){
free_lista((list)->next);
free(list->stringa);
free(list);
list = NULL;
}
}
void risolvi_lista_espressioni(ListaEspressioni* lista){
Pila pila = NULL;
int array[32];
int op1, op2;
while((*lista) != NULL){
Overflow = false;
char* token = strtok((*lista)->stringa, " ");
while(token != NULL){
int num = strtol(token, NULL, 10);
if ( (num > INT_MAX ) || (num < INT_MIN) ){
Overflow = true;
puts("Overflow!");
token = NULL;
}
else if(num == 0 && strcmp(token, "0") != 0 && !Overflow){
/*SE IL NUMERO E' UN OPERATORE, ESEGUI CALCOLO*/
op2 = pop(&pila);
op1 = pop(&pila);
operazione(op1, op2, token[0], &pila, &token);
}
else{
/*E' UN NUMERO DA AGGIUNGERE ALLA PILA*/
push(&pila, num);
token = strtok(NULL, " ");
}
}
if (!Overflow){
printf("%d in C2: ", pila->num);
print_Two_Complement(pila->num, array);
pop(&pila);
}
lista = &(*lista)->next;
}
}
void print_Two_Complement(int num, int array[]){
int k, s;
if (num >= 0){
for (k = 0; k < 32; ++k){
array[k] = num%2;
num = num/2;
}
for (s = 0; s <8; ++s){
for (k = 0; k < 4; k++){
printf("%d",array[31 - (k + 4*s)] );
}
printf(" ");
}
puts("");
}
else{
int carry = 0;
for (k = 0; k < 32; ++k){
array[k] = !(num%2);
if (k == 0){
if (array[k] == 0){
array[k] = 1;
}
else{
array[k] = 0;
carry = 1;
}
}
else{
if(carry == 1){
if (array[k]==0){
array[k]=1;
carry = 0;
}
else{
array[k] = 0;
carry = 1;
}
}
}
num = num/2;
}
for (s = 0; s <8; ++s){
for (k = 0; k < 4; k++){
printf("%d",array[31 - (k + 4*s)] );
}
printf(" ");
}
puts("");
}
}
void insert_espressione(ListaEspressioni* list, char* stringa){
/*ALLOCA UNA STRUCT ESPRESSIONE*/
/*ALLOCA UNA STRINGA DELLE DIMENSIONI DI stringa*/
/*SALVA IL PUNTATORE NELLA STRUCT*/
Espressione* newElement = allocazione_sicura(1, sizeof(Espressione));
newElement->stringa = allocazione_sicura(1, (strlen(stringa)+1)*sizeof(char));
strcpy(newElement->stringa, stringa);
while((*list) != NULL){
list = &(*list)->next;
}
(*list) = newElement;
}
void operazione(int op1, int op2, char operatore, Pila* pila, char** token){
/*Esegui operazione indicata*/
/*Se l'operazione non va in overflow, fai pop e push vari*/
/*Se l'operazione va in overflow, stampa overflow*/
int result=0;
switch(operatore){
case '+':
/*ADDIZIONE SICURA*/
if (OVERFLOW_SUM_COND){
Overflow = true;
puts("Overflow!");
(*token) = NULL;
}
else{
result = op1 + op2;
push(pila, result);
(*token) = strtok(NULL, " ");
}
break;
case '-':
/*SOTTRAZIONE SICURA*/
if (OVERFLOW_SUBTRACT_COND){
Overflow = true;
puts("Overflow!");
(*token) = NULL;
}
else{
result = op1 - op2;
push(pila, result);
(*token) = strtok(NULL, " ");
}
break;
case '*':
/*MOLTIPLICAZIONE SICURA*/
if (OVERFLOW_MULT_COND){
Overflow = true;
puts("Overflow!");
(*token) = NULL;
}
else{
result = op1 * op2;
push(pila, result);
(*token) = strtok(NULL, " ");
}
break;
}
}
void push(Pila* pila, int num){
Elem_pila* newElement = allocazione_sicura(1, sizeof(Elem_pila) );
newElement->num = num;
newElement->next = (*pila);
(*pila) = newElement;
}
int pop(Pila *pila){
Elem_pila* tempPtr = (*pila);
int temp_num = tempPtr->num;
(*pila) = (*pila)->next;
free(tempPtr);
return temp_num;
}
void* allocazione_sicura(int n, size_t dim_tipo){
void* tempPtr = calloc(n, dim_tipo);
if (tempPtr != NULL){
return tempPtr;
}
else{
puts("Memoria esaurita");
exit(EXIT_FAILURE);
}
}
void salva_stringa(char* buffer){
fgets(buffer, DIM, stdin);
buffer[strlen(buffer)-1] = '\0';
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.