language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
int main(){
//OUTLINE
// socket() => connection() => recv()
int network_socket ;
// creating a socket
network_socket = socket(AF_INET , SOCK_STREAM , 0);
// specifing the address to connect to socket
struct sockaddr_in server_address ;
server_address.sin_family = AF_INET ;
server_address.sin_port = htons(9002) ;
server_address.sin_addr.s_addr = INADDR_ANY ;
int connection_status = connect(network_socket , (struct sockaddr* ) &server_address , sizeof(server_address)) ;
// checking for errors
if(connection_status == -1){
printf("Something wrong with the connections \n \n");
}
//recive data from server
char response[256] ;
recv(network_socket , &response , sizeof(response) , 0 ) ;
// print out the data we get back
printf("THe data we got back: %s\n ", response);
//close the socket
close(network_socket);
return 0 ;
}
|
C
|
#include<stdio.h>
#define N 100
int main()
{
int i,j;
int n;
int a[N][N]={};
printf("请输入一个n级方阵\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(j>=i)
{
a[i][j]=1;
}
else
{
a[i][j]=i-j+1;
}
printf("%2d ",a[i][j]);
}
printf("\n");
}
return 0;
}
|
C
|
//% file: hello_pthread.c
//% cmd: gcc -O3 -Wall -Wextra -o hello_pthread hello_pthread.c -lpthread
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
/* スレッドによって実行される関数 */
void * f(void * args_) {
(void)args_;
pthread_t tid = pthread_self();
for (int i = 0; i < 3; i++) {
printf("%ld : hello %d\n", tid, i);
usleep(100); /* 100 μ秒 = 0.0001 秒休眠 */
}
return 0;
}
int main() {
pthread_t tid[2];
/* スレッドを2個作る */
for (int i = 0; i < 2; i++) {
pthread_create(&tid[i], NULL, f, NULL);
}
/* 終了待ち */
for (int i = 0; i < 2; i++) {
pthread_join(tid[i], NULL);
}
return 0;
}
|
C
|
/*****************************************************
* HEADER FILE: hn_modes_q.c *
* MODULE: Utility functions depending on *
* the update mode (to be used with *
* hn_test_pattern_q) *
* *
* *
* PROJECT NAME: Hopfield Network simulation *
* (prototype) *
* *
* SUPERVISOR: Mark van Rossum *
* *
* AUTHOR: Lorenzo Mella *
* VERSION: 31/07/2016 *
* *
*****************************************************/
#include <stdlib.h>
#include <stdio.h>
#include "hn_types.h"
#include "hn_macro_utils.h"
#include "hn_modes_q.h"
#include "debug_log.h"
hn_mode_utils_q hn_utils_with_mode_q(update_mode mode)
{
hn_mode_utils_q utils;
switch (mode) {
case SEQUENTIAL:
utils.select_unit = &sequential_select_unit_q;
utils.stability_warning = &sequential_stability_warning_q;
utils.stability_check = &sequential_stability_check_q;
break;
case RANDOM:
default:
utils.select_unit = &random_select_unit_q;
utils.stability_warning = &sequential_stability_warning_q;
utils.stability_check = &random_stability_check_q;
break;
}
return utils;
}
size_t sequential_select_unit_q(size_t max_units, int reset)
{
static size_t counter = 0;
if (reset) {
return (counter = 0);
} else {
return counter++ % max_units;
}
}
int sequential_stability_warning_q(int unit_has_flipped, size_t threshold)
{
/* Count how many consecutive updates don't result in changes */
static size_t stability_counter = 0;
if (unit_has_flipped) {
stability_counter = 0;
} else {
++stability_counter;
}
debug_log("stability_counter = %lu\n", stability_counter);
/* As soon as we have a warning, reset the counter for future use
* and return 1, otherwise return 0 */
if (stability_counter >= threshold) {
stability_counter = 0;
return 1;
} else {
return 0;
}
}
int sequential_stability_check_q(int *flipped_units, size_t max_units)
{
size_t i;
for (i = 0; i < max_units; ++i) {
/* If even one unit has flipped, stability fails */
if (flipped_units[i] != 0) {
return 0;
}
}
/* We get here only if all units are stable */
return 1;
}
size_t random_select_unit_q(size_t max_units, int reset)
{
return RANDI(max_units);
}
int random_stability_check_q(int *flipped_units, size_t max_units)
{
size_t i;
for (i = 0; i < max_units; ++i) {
/* If even one unit has flipped, stability fails */
if (flipped_units[i] != 0) {
return 0;
}
}
/* We get here only if all units are stable */
return 1;
}
|
C
|
#include <stdio.h>
int main(void)
{
int i;
for (i=1;i<101;i++) /*1to100*/
{
if (i%3==0 && i%5==0){ /*multiple of 3and5*/
printf("FizzBuzz");
}
else if (i%3==0){ /*multiple of 3*/
printf("Fizz");
}
else if (i%5==0){ /*multiple of 5*/
printf("Buzz");
}
else{
printf("%d", i);
}
if (i!=100) /*space*/
{
printf(" ");
}
}
return (0);
}
|
C
|
#include "usb.h"
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/uinput.h>
#include <linux/hidraw.h>
struct USBDevice {
FILE* file;
char* name;
};
USBDevice* openDevice(char* name) {
FILE* file = fopen(name, "r");
if(file == NULL) return NULL;
USBDevice* device = malloc(sizeof(USBDevice));
device->file = file;
device->name = name;
return device;
}
void closeDevice(USBDevice* device) {
fclose(device->file);
free(device);
}
void reopenDevice(USBDevice* device) {
freopen(device->name, "r", device->file);
}
void readDeviceData(USBDevice* device, void* buffer, int length) {
reopenDevice(device);
fread(buffer, length, 1, device->file);
}
|
C
|
/**
* Copyright (c) 2015 Lazu Ioan-Bogdan
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, without any restrictions.
*/
#ifndef EN_SCALAR_H
#define EN_SCALAR_H
#include "types.h"
#include <math.h>
const enScalar PI = 3.141592653589793238f;
const enScalar D2R = PI / 180.0f;
const enScalar R2D = 180.0f / PI;
// Got them from <float.h>
const enScalar SCALAR_MIN = 1.175494351e-38F;
const enScalar SCALAR_MAX = 3.402823466e+38F;
#define DEG2RAD(x) ((x) * D2R)
#define RAD2DEG(x) ((x) * R2D)
INLINE enScalar enSqrt(enScalar x)
{
return sqrtf(x);
}
INLINE enScalar enFabs(enScalar x)
{
return fabsf(x);
}
INLINE enScalar enCos(enScalar x)
{
return cosf(x);
}
INLINE enScalar enSin(enScalar x)
{
return sinf(x);
}
INLINE enScalar enAcos(enScalar x)
{
return acosf(x);
}
INLINE enScalar enAsin(enScalar x)
{
return asinf(x);
}
INLINE enScalar enClamp(enScalar v, enScalar min, enScalar max)
{
if (v < min) return min;
if (v > max) return max;
return v;
}
INLINE enScalar enFmodf(enScalar v, enScalar d)
{
return fmodf(v, d);
}
#endif
|
C
|
int is_valid(const char c, char **grid, const int y, const int x)
{
int i;
i = 0;
while (i < 9)
{
if (grid[y][i] == c || grid[i][x] == c)
return 0;
++i;
}
return ((c == grid[(y / 3) * 3 + (y + 1) % 3][(x / 3) * 3 + (x + 1) % 3])
|| (c == grid[(y / 3) * 3 + (y + 2) % 3][(x / 3) * 3 + (x + 1) % 3])
|| (c == grid[(y / 3) * 3 + (y + 1) % 3][(x / 3) * 3 + (x + 2) % 3])
|| (c == grid[(y / 3) * 3 + (y + 2) % 3][(x / 3) * 3 + (x + 2) % 3]));
}
int sudoku(char **grid, int row, int col)
{
char c;
c = '0';
if (row == 9)
return 1;
if (grid[row][col] != '.')
return (col < 8) ? sudoku(grid, row, col + 1)
: sudoku(grid, row + 1, 0);
while (++c <= '9')
{
if (is_valid(c, grid, row, col))
{
grid[row][col] = c;
if (col < 8)
{
if (sudoku(grid, row, col + 1))
return 1;
}
else
if (sudoku(grid, row + 1, 0))
return 1;
grid[row][col] = '.';
}
}
return 0;
}
|
C
|
/* conf.h */
/*
* Declaration of block device switch. Each entry (row) is the only link between
* the main code and the driver. The initialization of the device switches
* is in the file conf1.c.
*/
extern struct bdevsw
{
int (*d_open)();
int (*d_close)();
int (*d_strategy)();
} bdevsw[];
/*
* Character device switch.
*/
extern struct cdevsw
{
int (*d_open)();
int (*d_close)();
int (*d_read)();
int (*d_write)();
int (*d_ioctl)();
int (*d_stop)();
struct tty *d_ttys;
} cdevsw[];
/*
* tty line control switch.
*/
extern struct linesw
{
int (*l_open)();
int (*l_close)();
int (*l_read)();
int (*l_write)();
int (*l_ioctl)();
int (*l_input)();
int (*l_output)();
int (*l_start)();
int (*l_mdmint)();
} linesw[];
extern int linecnt; /* number of entries in lineswitch table */
/*
* Disk layout info -- used only by drivers: Virtual disk specification:
*/
struct vd_size
{
int vd_unit; /* Unit v.d. starts on; */
daddr_t vd_blkoff; /* Offset on unit of v.d.; */
daddr_t vd_nblocks; /* Size of v.d. */
};
|
C
|
/** Code by Uspensky *****/
/**************************************************************************************/
/* ДЗ №7 Программа "Телефонный справочник" */
/**************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
int ch;
struct str_list {
int id;
char Name [40];
char Phone [30];
} Phone_book[MAX];
/***************************************************************************************/
void init (void){ // Функция инициализации списка
int n;
for(n=0; n<MAX; ++n){
Phone_book[n].id = n;
Phone_book[n].Name[0] = '\0';
}
}
/***************************************************************************************/
int select_menu(void)
{
char s[80];
int c;
printf("1. Введите имя и телефон\n");
printf("2. Выведите список\n");
printf("3. Поиск в базе\n");
printf("4. Выход\n");
do {
printf("\nВведите номер нужного пункта: ");
gets(s);
c = atoi(s);
} while(c<0 || c>4);
return c;
}
/**************************************************************************************/
void enter(void)
{
int slot; //функция ввода
slot = find_free();
if(slot==-1) {
printf("\nСписок заполнен");
return;
}
printf("Введите имя:");
gets(Phone_book[slot].Name);
printf("Введите номер телефона:");
gets(Phone_book[slot].Phone);
}
/****************************************************************************************/
int find_free(void) //функция поиска свободной структуры
{
int t;
for(t=0; Phone_book[t].Name[0] && t<MAX; ++t) ;
if(t==MAX) return -1; // свободных структур нет
return t;
}
/****************************************************************************************/
void Out_list(void)
{ //функция вывода списка на экран
// и записи в файл
int t;
FILE *fp;
fp = fopen ("t.txt", "r+");
for(t=0; t<MAX; ++t) {
if(Phone_book[t].Name[0]) {
printf("%d\t", Phone_book[t].id+1);
printf("%s\t", Phone_book[t].Name);
printf("%s\n", Phone_book[t].Phone);
fprintf(fp,"%d\t", Phone_book[t].id+1); // запись в файл
fprintf(fp,"%s\t", Phone_book[t].Name);
fprintf(fp,"%s\n", Phone_book[t].Phone);
}
}fclose (fp);
printf("\n\n");
}
/****************************************************************************************/
int main () {
char choice;
init();
for(;;) {
choice = select_menu();
switch(choice) {
case 1: enter();
break;
case 2: Out_list();
break;
case 3: printf("Функция временно не работает\n\n");
break;
case 4: exit(0);
}
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* error.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: zcugni <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/11/18 16:56:35 by zcugni #+# #+# */
/* Updated: 2018/11/18 17:00:19 by zcugni ### ########.fr */
/* */
/* ************************************************************************** */
#include "asm.h"
static void display_lib_err(int err)
{
if (err == MULT_ARGS_ERR)
ft_putstr("Error : Too many arguments\n");
else if (err == MISSING_ARGS_ERR)
ft_putstr("Error : Not enough arguments\n");
else if (err == WRONG_FILE_NAME)
ft_putstr("Error : Wrong file name\n");
}
static void display_name_com_err(int err)
{
if (err == WRONG_NAME_CMD_ERR)
ft_printf("Error : Name command badly written (\"%s\")\n", g_err->line);
else if (err == WRONG_COM_CMD_ERR)
ft_printf("Error : Comment command badly written (\"%s\")\n",
g_err->line);
else if (err == BAD_NAME_ERR)
ft_printf("Error : Name badly written (\"%s\")\n", g_err->line);
else if (err == BAD_COM_ERR)
ft_printf("Error : Comment badly written (\"%s\")\n", g_err->line);
else if (err == NAME_TOO_BIG_ERR)
ft_printf("Error : Name too big\n");
else if (err == COM_TOO_BIG_ERR)
ft_printf("Error : Comment too big\n");
else if (err == INCOMPLETE_FILE)
ft_printf("Error : Incomplete file\n");
}
static void display_lbl_err(int err)
{
if (err == LBL_FORMAT_ERR)
ft_printf("Error : Unexpected char in label (\"%s\")\n", g_err->line);
else if (err == LBL_EXIST_ERR)
ft_printf("Error : Label already declared (\"%s\")\n", g_err->line);
else if (err == LBL_NOT_EXIST_ERR)
ft_printf("Error : Referenced label doesn't exist (\"%s\")\n",
g_err->str);
}
static void display_param_err(int err)
{
if (err == LARGE_REG_ERR)
ft_printf("Error : Register number too big (\"%s\")\n", g_err->line);
else if (err == NEG_REG_ERR)
ft_printf("Error : Negative register (\"%s\")\n", g_err->line);
else if (err == WRONG_PARAM_TYPE_ERR)
ft_printf("Error : Wrong param type (\"%s\")\n", g_err->line);
else if (err == WRONG_PARAM_NUM_ERR)
ft_printf("Error : Too many or not enough params (\"%s\")\n",
g_err->line);
else if (err == WRONG_NUM_FORMAT_ERR)
ft_printf("Error : Value badly written or missing (\"%s\")\n",
g_err->line);
}
void display_custom_err(int err)
{
if (err >= MULT_ARGS_ERR && err <= WRONG_FILE_NAME)
display_lib_err(err);
else if (err == WRONG_FORMAT_ERR)
ft_printf("Error : Unexpected char in line (\"%s\")\n", g_err->line);
else if (err == WRONG_CHAR_INST_ERR)
ft_printf("Error : Unexpected char in inst (\"%s\")\n", g_err->line);
else if (err == UNKNOWN_INST_ERR)
ft_printf("Error : Unknown instruction (\"%s\")\n", g_err->line);
else if (err >= WRONG_NAME_CMD_ERR && err <= INCOMPLETE_FILE)
display_name_com_err(err);
else if (err >= LBL_FORMAT_ERR && err <= LBL_NOT_EXIST_ERR)
display_lbl_err(err);
else if (err >= LARGE_REG_ERR && err <= WRONG_NUM_FORMAT_ERR)
display_param_err(err);
else
ft_printf("Error\n", -1);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* nm.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pdeguing <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/01/02 11:03:14 by pdeguing #+# #+# */
/* Updated: 2019/01/04 10:34:44 by pdeguing ### ########.fr */
/* */
/* ************************************************************************** */
#include <nm.h>
static void handle_64(void *ptr)
{
int ncmds;
int i;
struct mach_header_64 *header;
struct load_command *lc;
struct symtab_command *sym;
header = ptr;
ncmds = header->ncmds;
lc = ptr + sizeof(struct mach_header_64);
i = 0;
while (i < ncmds)
{
if (lc->cmd == LC_SYMTAB)
{
sym = (struct symtab_command *)lc;
(void)symtab_dump(sym->nsyms, sym->symoff, sym->stroff, ptr);
break ;
}
lc = (void *)lc + lc->cmdsize;
i++;
}
}
static void handle_32(void *ptr)
{
int ncmds;
int i;
struct mach_header *header;
struct load_command *lc;
struct symtab_command *sym;
header = ptr;
ncmds = header->ncmds;
lc = ptr + sizeof(struct mach_header);
i = 0;
while (i < ncmds)
{
if (lc->cmd == LC_SYMTAB)
{
sym = (struct symtab_command *)lc;
(void)symtab_dump(sym->nsyms, sym->symoff, sym->stroff, ptr);
break ;
}
lc = (void *)lc + lc->cmdsize;
i++;
}
}
void nm(void *ptr)
{
uint32_t magic;
magic = *(uint32_t *)ptr;
if (magic == MH_MAGIC_64)
{
(void)handle_64(ptr);
}
else if (magic == MH_CIGAM_64)
{
(void)ft_putendl("swap64");
}
else if (magic == MH_MAGIC)
{
ft_putendl("normal32");
(void)handle_32(ptr);
}
else if (magic == MH_CIGAM)
{
ft_putendl("swap32");
}
else if (magic == FAT_MAGIC || magic == FAT_CIGAM)
ft_putendl("fat");
else
ft_putendl("unknown");
}
|
C
|
/*
** ls_l.c for in /home/WASSEX/Semestre1/PSU_2016_my_ls
**
** Made by Wassim Alkayar
** Login <WASSEX@epitech.net>
**
** Started on Tue Apr 18 00:27:21 2017 Wassim Alkayar
** Last update Sun Jul 16 01:37:48 2017 Wassim Alkayar
*/
#include "my.h"
void ut_tw(struct stat fileStat, int a,
struct s_DlistCell *tmp, int maxsize)
{
char *timebuf;
int i;
i = get_length_number(fileStat.st_size);
while (i < maxsize)
{
my_putchar(' ');
i = i + 1;
}
my_put_nbr(fileStat.st_size);
my_putstr(" ");
timebuf = ctime(&fileStat.st_mtime);
timebuf = timebuf_changer(timebuf);
my_putstr(timebuf);
my_putstr(" ");
if (a == 1)
my_putstr(file_name(tmp->str));
else
my_putstr(file_name(tmp->str));
my_putchar('\n');
}
void ls_l(t_dlist li)
{
struct stat fileStat;
struct s_DlistCell *tmp;
int a;
int total;
int maxsize;
maxsize = format_ls_l(li);
tmp = li->begin;
tmp = tmp->next;
total = count_blocks(li->begin->str);
my_putstr("total ");
my_put_nbr(total);
my_putchar('\n');
while (tmp != NULL)
{
if (stat(tmp->str, &fileStat) == -1)
return ;
a = mode(fileStat);
utils_ls_l(fileStat);
ut_tw(fileStat, a, tmp, maxsize);
if (tmp->next == NULL)
return ;
tmp = tmp->next;
}
}
void lspt(struct s_DlistCell *tmp, struct dirent *f, DIR *dir)
{
t_dlist list2;
struct s_DlistCell *tmp2;
char *strbegin;
list2 = NULL;
list2 = prepare_sorted_list(f, dir, tmp->str);
list2 = push_front_dlist(list2, tmp->str);
tmp2 = list2->begin->next;
strbegin = my_strdup(list2->begin->str);
while (tmp2 != NULL)
{
tmp2->str = my_strdup(path_str(strbegin, tmp2->str));
tmp2 = tmp2->next;
}
ls_l(list2);
}
void ls_l_prepare(struct dirent *fichierlu, DIR *dir, t_dlist list)
{
int i;
struct s_DlistCell *tmp;
i = 1;
tmp = list->begin;
while (i <= list->length)
{
if (list->length != 1)
my_printf("%s:\n", tmp->str);
if ((dir = opendir(tmp->str)) != NULL)
lspt(tmp, fichierlu, dir);
else
{
my_printf("ls : cannot access '%s': ", tmp->str);
perror("");
}
if (i < list->length)
my_putchar('\n');
tmp = tmp->next;
i = i + 1;
}
}
|
C
|
#include<stdio.h>
int main()
{
char s1[10],x;
int i;
printf("enter char which u want to replace:\n");
scanf("%c",&x);
printf("enter the string:\n");
scanf("%s",s1);
for(i=0;s1[i]!='\0';i++)
{
if(s1[i]==x)
{
s1[i]='g';
}
}
printf("%s",s1);
return 0;
}
|
C
|
#include<stdio.h>
int dp[10001][10][2] = {0};
int vec[10001];
int ob[10001];
int top = -1;
int n, pp = 0, tt;
/* go Լ . ٸ DP[x][p][1] ߰ ܰ迡 ° ּ ּ ش. */
// X ڸ߱ . ְ, .
int go(int x, int p){
if(x >= n+1) return 0;
if(dp[x][p][0] != -1) return dp[x][p][0];
int c1, c2, temp = (vec[x] + p) % 10;
if(temp < ob[x]){
c1 = ob[x] - temp + go(x+1, (p + ob[x] - temp) % 10);
c2 = 10 + temp - ob[x] + go(x+1, p);
}
else if(temp > ob[x]){
c1 = 10 + ob[x] - temp + go(x+1, (p + 10 + ob[x] - temp) % 10);
c2 = temp - ob[x] + go(x+1, p);
}
else {dp[x][p][1] = 2; return dp[x][p][0] = go(x+1, p);}
if(c1 < c2) {dp[x][p][1] = 1; return dp[x][p][0] = c1;}
else {dp[x][p][1] = 3; return dp[x][p][0] = c2;}
}
int main(){
scanf("%d", &n);
for(int i = 1; i <= n; i++) scanf("%1d", &vec[i]);
for(int i = 1; i <= n; i++) scanf("%1d", &ob[i]);
for(int i = 1; i <= n; i++)
for(int j = 0; j <= 9; j++)
dp[i][j][0] = -1;
printf("%d\n", go(1, 0));
/* ϵ DP[x][p][1] ̿ؼ ش ܰ ش*/
for(int i = 1; i <= n; i++){
tt = (vec[i] + pp) % 10;
if(dp[i][pp][1] == 1){
if(tt < ob[i]){
printf("%d %d\n", i, ob[i] - tt);
pp = (pp + ob[i] - tt) % 10;
}
else {
printf("%d %d\n", i, 10 + ob[i] - tt);
pp = (pp + 10 + ob[i] - tt) % 10;
}
}
else if(dp[i][pp][1] == 3){
if(tt < ob[i])
printf("%d %d\n", i, (10 + tt - ob[i]) * -1);
else
printf("%d %d\n", i, (tt - ob[i]) * -1);
}
}
}
|
C
|
#include "push_swap.h"
void swap(t_pile *p)
{
int x;
int y;
if (p->length > 1)
{
x = popup(p);
y = popup(p);
addup(p, x);
addup(p, y);
}
}
void sswap(t_pile *p1, t_pile *p2)
{
swap(p1);
swap(p2);
}
void push(t_pile *p1, t_pile *p2)
{
int x;
if (p2->length)
{
x = popup(p2);
addup(p1, x);
}
}
void rotate(t_pile *p)
{
int x;
if (p->length > 1)
{
x = popup(p);
adddown(p, x);
}
}
void rrotate(t_pile *p1, t_pile *p2)
{
rotate(p1);
rotate(p2);
}
|
C
|
#ifndef LOGGER_H
#define LOGGER_H
#include <stdio.h>
#include <string.h>
#define LOG_LEVEL_FATAL (0)
#define LOG_LEVEL_ERROR (1)
#define LOG_LEVEL_WARN (2)
#define LOG_LEVEL_INFO (3)
#define LOG_LEVEL_DEBUG (4)
extern FILE *_default_log_stream;
extern int _default_log_level;
int setup_logger(FILE *fd, int log_level);
void close_logger(FILE *fd);
void log_msg(void *zc, int level, const char *file, int line, const char *func,
const char *format, ...);
#define LOGGING_FATAL(...) \
{ \
log_msg(_default_log_stream, LOG_LEVEL_FATAL, __FILE__, __LINE__, __func__, __VA_ARGS__); \
} \
#define LOGGING_ERROR(...) \
{ \
log_msg(_default_log_stream, LOG_LEVEL_ERROR, __FILE__, __LINE__, __func__, __VA_ARGS__); \
} \
#define LOGGING_WARN(...) \
{ \
log_msg(_default_log_stream, LOG_LEVEL_WARN, __FILE__, __LINE__, __func__, __VA_ARGS__); \
} \
#define LOGGING_INFO(...) \
{ \
log_msg(_default_log_stream, LOG_LEVEL_INFO, __FILE__, __LINE__, __func__, __VA_ARGS__); \
} \
#define LOGGING_DEBUG(...) \
{ \
log_msg(_default_log_stream, LOG_LEVEL_DEBUG, __FILE__, __LINE__, __func__, __VA_ARGS__); \
} \
#endif /* LOGGER_H */
|
C
|
//
// Created by gcyganek on 12.03.2021.
//
#include <sys/times.h>
#include <unistd.h>
#include "library.h"
#ifdef DYNAMIC
#include <dlfcn.h>
#endif
double time_in_seconds(clock_t start, clock_t end) {
return (double)(end - start) / sysconf(_SC_CLK_TCK);
}
int main(int argc, char* argv[]) {
Table *table = NULL;
#ifdef DYNAMIC
void* handle = dlopen("./liblibrary.so", RTLD_LAZY);
if(!handle) {
fprintf(stderr, "dlopen() %s\n", dlerror());
exit(1);
}
Table* (*create_table)(int) = dlsym(handle, "create_table");
void (*free_table)(Table*) = dlsym(handle, "free_table");
void (*write_files_to_tmp)(char*, char*) = dlsym(handle, "write_files_to_tmp");
int (*create_block_from_tmp)(Table*) = dlsym(handle, "create_block_from_tmp");
void (*merge_file_sequence)(Table*, char**) = dlsym(handle, "merge_file_sequence");
int (*rows_in_block_count)(Table*, int) = dlsym(handle, "rows_in_block_count");
void (*delete_row)(Table*, int, int) = dlsym(handle, "delete_row");
void (*delete_block)(Table*, int) = dlsym(handle, "delete_block");
void (*read_table)(Table*) = dlsym(handle, "read_table");
#endif
struct tms *start_time = malloc(sizeof(struct tms));
struct tms *end_time = malloc(sizeof(struct tms));
clock_t clock_start_time;
clock_t clock_end_time;
char *command;
int i = 1;
while (i < argc) {
clock_start_time = times(start_time);
command = argv[i];
if (strcmp(argv[i], "create_table") == 0) {
if (table != NULL) {
free_table(table);
}
int size = atoi(argv[++i]);
table = create_table(size);
i += 1;
} else if (strcmp(argv[i], "merge_file_sequence") == 0) {
merge_file_sequence(table, argv + i + 1);
i += table->size + 1;
} else if (strcmp(argv[i], "rows_in_block_count") == 0) {
int block_id = atoi(argv[++i]);
int result = rows_in_block_count(table, block_id);
printf("\nrows in block nr %d: %d\n", block_id, result);
i += 1;
} else if (strcmp(argv[i], "delete_row") == 0) {
int block_id = atoi(argv[++i]);
int row_id = atoi(argv[++i]);
delete_row(table, block_id, row_id);
i += 1;
} else if (strcmp(argv[i], "delete_block") == 0) {
int block_id = atoi(argv[++i]);
delete_block(table, block_id);
i += 1;
} else if (strcmp(argv[i], "read_table") == 0) {
read_table(table);
i += 1;
} else if (strcmp(argv[i], "create_block") == 0) {
create_block_from_tmp(table);
i += 1;
} else if (strcmp(argv[i], "create_and_remove_blocks") == 0) {
int blocks_to_create = atoi(argv[++i]);
for (int j = 0; j < blocks_to_create; j++) {
create_block_from_tmp(table);
}
for (int j = 0; j < blocks_to_create; j++) {
delete_block(table, j);
}
i += 1;
} else if (strcmp(argv[i], "write_files_to_tmp") == 0) {
write_files_to_tmp(argv[i + 1], argv[i + 2]);
i += 3;
} else {
printf("Unknown command: %s\n", argv[i]);
return 1;
}
clock_end_time = times(end_time);
printf("\n %s\n", command);
printf("real time: %lf\n", time_in_seconds(clock_start_time, clock_end_time));
printf("user time: %lf\n", time_in_seconds(start_time->tms_utime, end_time->tms_utime));
printf(" sys time: %lf\n", time_in_seconds(start_time->tms_stime, end_time->tms_stime));
}
free_table(table);
#ifdef DYNAMIC
dlclose(handle);
#endif
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "bintree.h"
void bin_insertNode(bnode **root, int data)
{
bnode *temp = (bnode *) malloc(sizeof(bnode));
temp->left = NULL;
temp->right = NULL;
temp->data = data;
if (*root == NULL)
{
*root = temp;
return;
}
bin_insertAtParent(*root, temp);
}
void bin_insertAtParent(bnode *node, bnode *child)
{
if (node->data > child->data)
{
if (node->left)
bin_insertAtParent(node->left, child);
else
node->left = child;
}
else
{
if (node->right)
bin_insertAtParent(node->right, child);
else
node->right = child;
}
}
//전위순회
void bin_preOrder(bnode *node)
{
if (node == NULL)
return;
printf("%c ", node->data);
if (node->left)
bin_preOrder(node->left);
if (node->right)
bin_preOrder(node->right);
}
//중위순회
void bin_inOrder(bnode *node)
{
if (node == NULL)
return;
if (node->left)
bin_inOrder(node->left);
printf("%c ", node->data);
if (node->right)
bin_inOrder(node->right);
}
//후위순회
void bin_postOrder(bnode *node)
{
if (node == NULL)
return;
if (node->left)
bin_postOrder(node->left);
if (node->right)
bin_postOrder(node->right);
printf("%c ", node->data);
}
|
C
|
//chargement des librairies standard
#include <stdio.h>
#include <stdlib.h>
// chargement de la librairie mathsh pour la puissance de 10
#include <math.h>
//chargement de la librairie windows.h pour grer les fichier en partie et la fonction sleep
#include <windows.h>
# define TAILLE_CHAINE_CHAR 21
# define ALPHA 0.992
#include "divers.h"
#include "lecture.h"
float *Lecture(FILE* fichier, int mode)
{
char* tab=NULL;
int *nombres=NULL;
int i;
if(mode==1)
{
// printf("test\n");
// printf("prec=%s\n",data_precedent);
// printf("tab=%s\n",*tab);
tab=recupFichier(fichier);
/* for(i=0;i<20;i++)
{
*data_precedent=*tab;
}
*/
nombres=centrerAC(conversion(tab));
return nombres;
//free(data_precedent);
free(tab);
free(nombres);
}
else if(mode==2)
{
return centrerAC(conversion(recupUSB()));
}
}
// convertie la chaine de 21 caractres en tableau de 4 entiers coorespondant
float *conversion(char *donnee)
{
// on alloue la mmoire du tableau qui va contenir acr, dcr, acir, dcir (4 entiers) et on remplit par des zros
float *tab= calloc(4,sizeof(float));
int i;// variable temporaire pour se placer dans la chine de caractre d'ente
int j=0;// variable temporaire pour se placer dans le tableau d'entier de sortie
int k=0;// variable pour stocker la puissance de 10 correspondant la place du caractre correspondant
for(i=0; i<=21; i++)//on parcourt la chaine de caractre
{
if(donnee[i]==',')//si le cractre lu est une virgule
{
j++;//on change de case dans le tableau de sortie
k=0;
}
else if (donnee[i]>47 && donnee[i]<58)// si le caractre lu est un nombre
{
//on convertit le caractre ascii en entier et on le multiplit pr la puissance de 10 correspondante
tab[j]+=(donnee[i]-48)*pow(10,3-k);
k++;//on fait descendre la puissance de 10 (3-k => k augmente => la puissance de 10 diminue)
}
}
return tab;// on retourne le tableau de 4 flottants
}
// centre le signal sinu
float *centrerAC(float *donnee)
{
// on soustrait dc ac car dc pour le centrer en zro est l moyenne de ac
//normalement on recoupe dc ac mais pour d'obscures raison on prend 2048
donnee[0]=donnee[0]-2048;//donnee[1]->pour acr
donnee[2]=donnee[2]-2048;//donnee[3]->pour acir
// printf("int=%f,%f,%f,%f\n",donnee[0],donnee[1],donnee[2],donnee[3]);
return donnee;
}
char *recupFichier(FILE* fichier)
{
//FILE* fichier = NULL;
char* chaineSortie= malloc(TAILLE_CHAINE_CHAR *sizeof(char));
int n=0;
if (fichier != NULL) // On peut lire et crire dans le fichier
{
// On lit maximum TAILLE_CHAINE_CHR caractres du fichier, on stocke le tout dans "chaineSortie"
do
{
chaineSortie[n]=fgetc(fichier);
//printf("%c",chaineSortie[n]);
if(chaineSortie[n]==EOF)
{
printf("fin fichier\n");
return "9999,9999,9999,9999\n";
}
n++;
}
while((int)chaineSortie[n-1]!=10);
// printf("\n");
}
else
{
// On affiche un message d'erreur si on veut
printf("Impossible d'ouvrir le fichier record1.dat\n");
return "error";
}
return chaineSortie;//on retourne la chaine de 21 caractres en sortie
}
int choixMode()
{
printf("\n \t choix du mode\n");//titre de la fentre
printf("\t 1----> lecture des donnees dans fichier data\n");//lit dans les fichiers qui doivent tres placs dans le mme rpertoire que l'ecxecutable
printf("\t 2----> lecture du flux de donnes USB\n");//lit le blux usb en live (4 dones toutes les 2 ms normalement)
char touche;//on dclare la variable qui va stocker le code de la touche qui va tre appuye
touche=getch();
if(touche=='1')//si la touche appuye est 1 alors:
{
system("cls");//on efface le terminal
return 1;//on retourne 1
}
else if(touche=='2')//si la touche appuye est 2 alors:
{
system("cls");//on efface le terminal
return 2;//on return 2
}
else// si la touche est autre que 1 ou 2
{
system("cls");// on efface le treminal
return choixMode();//on rapplelle la fonction choixmode jusqu' ce que la touche appuye soit 1 ou 2
}
}
char *recupUSB()
{
char* chaineSortie= malloc(TAILLE_CHAINE_CHAR *sizeof(char));
FT_HANDLE ftHandle;
FT_STATUS ftStatus;
DWORD EventDWord;
DWORD TxBytes;
DWORD RxBytes;
DWORD BytesReceived;
char RxBuffer[20];
ftStatus = FT_Open(0, &ftHandle);
if(ftStatus != FT_OK)
{
// FT_Open failed
// return error_status_t;
}
FT_GetStatus(ftHandle,&RxBytes,&TxBytes,&EventDWord);
if (RxBytes > 0)
{
ftStatus = FT_Read(ftHandle,RxBuffer,RxBytes,&BytesReceived);
if (ftStatus == FT_OK)
{
chaineSortie=RxBytes;
}
else
{
// FT_Read Failed
}
}
FT_Close(ftHandle);
return chaineSortie;
}
/*
char *gestionErreurs(char *data_c, char *data_precedent)
{
int i=0;
// Sleep(3000);
// printf("%s",data_c);
printf("dataprec=%s\n",*data_precedent);
for(i=0; i<=20; i++)
{
// printf("%d-->",i);
// printf("%c\n",data_c[i]);
if(i==4 || i==9 || i==14)
{
if(data_c[i] != ',')//si ce n'est pas une virgule
{
printf("test 1\n");
return data_precedent;
}
}
else if(i!=4 && i!=9 && i!=14 && i!=19 && i != 20)
{
// printf("i=%d-->",i);
// printf("%d,",(int)data_c[i]);
if((int)data_c[i]<47 || (int)data_c[i]>58)// si data_c[i] n'est pas un nombre
{
printf("test 2\n");
return data_precedent;
}
}
//printf("test 3\n");
/* else if( i==20)
{
if(data_c[i] != 10)//lf
{
return data_precedent;
}
}
else if( i==21)
{
if(data_c[i] != 13)//cr
{
return data_precedent;
}
}
}
// printf("test_f\n");
return data_c;
}
*/
|
C
|
/*
--Done: Player movement and hitting an enemy, my backgrounds, Losing, Lives, Enemy sprites, BG1 + BG2, all states
scoring
--To Do: bullet cheats (and update all the art). Also colliding with
the sides of the BG2 should cause you to lose a life but my BG2 is messed up so i removed it. and regulate
enemies coming in, and their speeds
--Maybe To Do: I might add an enemy3 if I have time and I want to change the speed of enemy 2 to be faster
OR change it to get faster later on in the game. Prob will use a collision map for hitting the sides of the BG2
instead of limited layer movement
Also I want to change my sprite sizes to be bigger and control the number of enemies coming and going
--How to Play: just move the player around and avoid the incoming aliens, can shoot to kill them with A. Some require more
bullets than others. After a certain period, more
enemies will start to appear and they will require TWO bullets to kill instead of one. You have 4 lives. No win state.
*/
//I want to use timers to spawn the enemies but I'm not really sure how to yet, so i ended up using frame counting
//need to fix the sound from strting over when you return to game from PAUSE
#include <stdlib.h>
#include <stdio.h>
#include "myLib.h"
#include "game.h"
#include "startscrn.h"
#include "instrscrn.h"
#include "pausescrn.h"
#include "gamescrn.h"
#include "topScrn.h"
#include "losescrn.h"
#include "winscrn.h"
#include "spritesht.h"
#include "sound.h"
#include "Lorn.h"
#include "gameSong.h"
#include "shoot.h"
#include "bgo.h"
#include "collision.h"
#include "text.h"
#include "font.h"
//Prototypes
void initialize();
void goToStart();
void start();
void goToInstr();
void instr();
void goToPause();
void pause();
void goToWin();
void win();
void goToLose();
void lose();
void goToGame();
void game();
//vertical and horizontal offsets
int hOff = 0;
int vOff = 0;
int arr[35];
int pauseToGame;
//Sound stuff
SOUND soundA;
SOUND soundB;
// States for game
void (*state)();
// Button Variables
unsigned short buttons;
unsigned short oldButtons;
// Random Seed
int seed;
//characters
char buffer[41];
int main() {
hideSprites();
setupSounds();
setupInterrupts();
initialize();
while(1) {
// Update button variables
oldButtons = buttons;
buttons = BUTTONS;
// State Machine
state();
}
return 0;
}
void initialize() {
//load the sprites
DMANow(3, spriteshtPal, SPRITEPALETTE, spriteshtPalLen/2);
DMANow(3, spriteshtTiles, &CHARBLOCK[4], spriteshtTilesLen/2);
//hide em
hideSprites();
pauseToGame = 0;
//enable mode 0, background 0, and the sprites
//IF YOU WANT YOUR GAME STATES TO NOT HAVE THE SPRITES, MOVE SPRITE_ENABLE ELSEWHERE
REG_BG0CNT = BG_CHARBLOCK(0) | BG_SCREENBLOCK(28) | BG_8BPP | BG_SIZE_SMALL;
REG_DISPCTL = MODE0 | BG0_ENABLE | SPRITE_ENABLE;
initGame();
buttons = BUTTONS;
// Set up the first state
goToStart();
}
// Sets up the start state
void goToStart() {
//Waits for vertical blank and flips the page
waitForVBlank();
flipPage();
state = start;
// stopSound();
playSoundA(Lorn,LORNLEN,LORNFREQ, 1);
// Begin the seed randomization
seed = 0;
}
// Runs every frame of the start state
void start() {
//load the start screen into DMA
DMANow(3, startscrnPal, PALETTE, startscrnPalLen/2);
DMANow(3, startscrnTiles, &CHARBLOCK[0], startscrnTilesLen/2);
DMANow(3, startscrnMap, &SCREENBLOCK[28], startscrnMapLen/2);
REG_BG0CNT = BG_CHARBLOCK(0) | BG_SCREENBLOCK(28) | BG_8BPP | BG_SIZE_SMALL;
REG_DISPCTL = MODE0 | BG0_ENABLE;
seed++;
// Lock the framerate to 60 fps
waitForVBlank();
// State transitions
if (BUTTON_PRESSED(BUTTON_START)) {
REG_DISPCTL = SPRITE_ENABLE;
// Seed the random generator
srand(seed);
goToGame();
// initGame();
}
if(BUTTON_PRESSED(BUTTON_SELECT)){
goToInstr();
}
}
// Sets up the instructions state
void goToInstr() {
waitForVBlank();
flipPage();
state = instr;
// stopSound();
}
void instr() {
hideSprites();
//load the win screen into DMA
DMANow(3, instrscrnPal, PALETTE, instrscrnPalLen/2);
DMANow(3, instrscrnTiles, &CHARBLOCK[0], instrscrnTilesLen/2);
DMANow(3, instrscrnMap, &SCREENBLOCK[28], instrscrnMapLen/2);
REG_BG0CNT = BG_CHARBLOCK(0) | BG_SCREENBLOCK(28) | BG_8BPP | BG_SIZE_SMALL;
REG_DISPCTL = MODE0 | BG0_ENABLE;
// Lock the framerate to 60 fps
waitForVBlank();
// State transitions
if (BUTTON_PRESSED(BUTTON_SELECT))
goToStart();
}
// Sets up the game state
void goToGame() {
// load the game screen into DMA
REG_DISPCTL = MODE0 | BG2_ENABLE | SPRITE_ENABLE;
REG_DISPCTL |= BG1_ENABLE;
REG_DISPCTL |= BG0_ENABLE;
DMANow(3, topScrnPal, PALETTE, topScrnPalLen/2);
REG_BG2CNT = BG_CHARBLOCK(0) | BG_SCREENBLOCK(25) | BG_8BPP | BG_SIZE_TALL;
DMANow(3, gamescrnTiles, &CHARBLOCK[0], gamescrnTilesLen/2);
DMANow(3, gamescrnMap, &SCREENBLOCK[25], gamescrnMapLen/2);
REG_BG1CNT = BG_CHARBLOCK(1) | BG_SCREENBLOCK(28) | BG_8BPP | BG_SIZE_SMALL;
DMANow(3, topScrnTiles, &CHARBLOCK[1], topScrnTilesLen/2);
DMANow(3, topScrnMap, &SCREENBLOCK[28], topScrnMapLen/2);
REG_BG0CNT = BG_CHARBLOCK(2) | BG_SCREENBLOCK(31) | BG_8BPP | BG_SIZE_SMALL;
DMANow(3, bgoTiles, &CHARBLOCK[2], bgoTilesLen/2);
DMANow(3, bgoMap, &SCREENBLOCK[31], bgoMapLen/2);
if (!pauseToGame) {
stopSound();
playSoundA(gameSong,GAMESONGLEN,GAMESONGFREQ, 1);
}
state = game;
}
// Runs every frame of the game state
void game() {
updateGame();
drawGame();
//Copy the shadowOAM into the OAM
DMANow(3, shadowOAM, OAM, 128*4);
flipPage();
if (BUTTON_PRESSED(BUTTON_SELECT)) {
goToPause();
} else if (livesLeft < 1) {
goToLose();
}
vOff--;
REG_BG2VOFF = vOff*2;
REG_BG1VOFF = vOff/2;
}
// Sets up the pause state
void goToPause() {
waitForVBlank();
flipPage();
state = pause;
// stopSound();
}
// Runs every frame of the pause state
void pause() {
//load the pause screen into DMA
hideSprites();
DMANow(3, pausescrnPal, PALETTE, pausescrnPalLen/2);
DMANow(3, pausescrnTiles, &CHARBLOCK[0], pausescrnTilesLen/2);
DMANow(3, pausescrnMap, &SCREENBLOCK[28], pausescrnMapLen/2);
// Set up Background 0
REG_BG0CNT = BG_CHARBLOCK(0) | BG_SCREENBLOCK(28) | BG_4BPP | BG_SIZE_SMALL;
REG_DISPCTL = MODE0 | BG0_ENABLE;
// Lock the framerate to 60 fps
waitForVBlank();
// State transitions
if (BUTTON_PRESSED(BUTTON_START)){
REG_DISPCTL = SPRITE_ENABLE;
pauseToGame = 1;
goToGame();
} else if (BUTTON_PRESSED(BUTTON_SELECT)){
pauseToGame = 0;
main();
}
}
// Sets up the win state
void goToWin() {
//Wait for vertical blank and flip the page
waitForVBlank();
flipPage();
state = win;
}
// Runs every frame of the win state
void win() {
hideSprites();
//load the win screen into DMA
DMANow(3, winscrnPal, PALETTE, winscrnPalLen/2);
DMANow(3, winscrnTiles, &CHARBLOCK[0], winscrnTilesLen/2);
DMANow(3, winscrnMap, &SCREENBLOCK[28], winscrnMapLen/2);
REG_BG0CNT = BG_CHARBLOCK(0) | BG_SCREENBLOCK(28) | BG_4BPP | BG_SIZE_SMALL;
REG_DISPCTL = MODE0 | BG0_ENABLE;
// Lock the framerate to 60 fps
waitForVBlank();
// State transitions
if (BUTTON_PRESSED(BUTTON_START))
main();
}
// Sets up the lose state
void goToLose() {
flipPage();
hideSprites();
REG_DISPCTL = MODE3 | BG2_ENABLE;
fillScreen3(BLACK);
sprintf(buffer, "Score: %d", score);
drawString3(40, 90, "GAME OVER!", WHITE);
drawString3(50, 90, buffer, WHITE);
drawString3(60, 85, "Press START to", WHITE);
drawString3(70, 85, "return to menu", WHITE);
state = lose;
// stopSound();
flipPage();
fillScreen3(BLACK);
sprintf(buffer, "Score: %d", score);
drawString3(40, 90, "GAME OVER!", WHITE);
drawString3(50, 90, buffer, WHITE);
drawString3(60, 85, "Press START to", WHITE);
drawString3(70, 85, "return to menu", WHITE);
waitForVBlank();
}
// Runs every frame of the lose state
void lose() {
// State transitions
if (BUTTON_PRESSED(BUTTON_START))
main();
}
|
C
|
/*
|1nȫ, |
|16/11/05ztx, thanks to wangqiqi|
*/
void Pern(int list[], int k, int n) { // kʾǰkƶn-kλ
if (k == n - 1) {
for (int i = 0; i < n; i++) {
printf("%d", list[i]);
}
printf("\n");
}else {
for (int i = k; i < n; i++) { // ƶȫ
swap(list[k], list[i]);
Pern(list, k + 1, n);
swap(list[k], list[i]);
}
}
}
|
C
|
inherit "/std/food.c";
#include <std.h>
#include "../vesprus.h"
void create(){
::create();
set_name("%^BOLD%^%^RED%^A juicy cherry%^RESET%^");
set_id(({"cherry","fruit","food"}));
set_strength(1);
set_weight(0);
set_short("%^BOLD%^%^RED%^A large red cherry%^RESET%^");
set_destroy();
set_long("%^BOLD%^%^RED%^This small piece of fruit is almost heart shaped and a very %^RESET%^%^RED%^deep red %^BOLD%^%^RED%^in color. A single %^GREEN%^green %^RED%^stem sticks out from the top.%^RESET%^");
set_your_mess("%^BOLD%^%^RED%^pulls the stem off of the cherry and eats it with a smile.%^RESET%^");
set_my_mess("%^BOLD%^%^RED%^You pull the stem off of the cherry before placing it in your mouth... Mmm, it's soft, juicy and sweet.%^RESET%^");
}
|
C
|
/*
** EPITECH PROJECT, 2020
** CPE_corewar_2019
** File description:
** cw_asm_instruct_compile_global
*/
#include "asm/instructs/cw_asm_instruct.h"
void cw_asm_instruct_compile_global(cw_asm_instruct_t *instruct)
{
int i = 0;
for (; instruct->parameters[i]; i++) {
switch (*instruct->parameters[i]) {
case 'r':
instruct->coding_byte += 0x01;
instruct->instruct_size += 1;
break;
case DIRECT_CHAR:
instruct->coding_byte += 0x02;
instruct->instruct_size += DIR_SIZE;
break;
default:
instruct->coding_byte += 0x03;
instruct->instruct_size += IND_SIZE;
}
instruct->coding_byte = instruct->coding_byte << 2;
}
instruct->instruct_size += 2;
for (; i < 3; i++)
instruct->coding_byte = instruct->coding_byte << 2;
}
|
C
|
/*
* Jacopo Del Granchio
* #063 11.12.2019
*
* Controlla se due rette sono parallele o perpendicolari.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <locale.h>
#include <stdarg.h>
#include <stdbool.h>
// Macro
#define chiedi(msg, format, ...) \
printf(msg); \
scanf(format, __VA_ARGS__);
// Prototipi
bool parallele(float, float, float, float);
bool perpendicolari(float, float, float, float);
// Funzioni
int main() {
setlocale(LC_ALL, "");
float mA, qA, mB, qB;
chiedi("Inserisci il coefficente angolare della prima retta: ", "%f", &mA);
chiedi("Inserisci l'ordinata all'origine della prima retta: ", "%f", &qA);
chiedi("Inserisci il coefficente angolare della seconda retta: ", "%f", &mB);
chiedi("Inserisci l'ordinata all'origine della seconda retta: ", "%f", &qB);
if (parallele(mA, qA, mB, qB)) printf("Le rette sono parallele\n");
if (perpendicolari(mA, qA, mB, qB)) printf("Le rette sono perpendicolari\n");
// getchar();
// system("pause");
return 0;
}
bool parallele(float mA, float qA, float mB, float qB) {
return mA == mB && qA != qB;
}
bool perpendicolari(float mA, float qA, float mB, float qB) {
return mA == 1 / mB;
}
|
C
|
//#include<stdio.h>
//
//int search(int *A, int size, int search_value);
//
//int main()
//{
// int A[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
//
// search(A, 10, 8);
//
// return 0;
//}
//
//int search(int *A, int size, int search_value)
//{
// int i;
//
// for(i=0; i<10; i++){
// if(A[i] == search_value)
// printf("%d\n", A[i]);
// }
//}
|
C
|
#include <assert.h>
#include "ddhcp.h"
#include "dhcp.h"
#include "logger.h"
#include "tools.h"
int ddhcp_block_init(ddhcp_config* config) {
if (config->number_of_blocks < 1) {
FATAL("ddhcp_block_init(...)-> Need at least 1 blocks to be configured\n");
return 1;
}
DEBUG("ddhcp_block_init(config)\n");
config->blocks = (struct ddhcp_block*) calloc(sizeof(struct ddhcp_block), config->number_of_blocks);
if (config->blocks == NULL) {
FATAL("ddhcp_block_init(...)-> Can't allocate memory for block structure\n");
return 1;
}
time_t now = time(NULL);
// TODO Maybe we should allocate number_of_blocks dhcp_lease_blocks previous
// and assign one here instead of NULL. Performance boost, Memory defrag?
struct ddhcp_block* block = config->blocks;
for (uint32_t index = 0; index < config->number_of_blocks; index++) {
block->index = index;
block->state = DDHCP_FREE;
addr_add(&config->prefix, &block->subnet, index * config->block_size);
block->subnet_len = config->block_size;
memset(&block->owner_address, 0, sizeof(struct in6_addr));
block->timeout = now + config->block_timeout;
block->claiming_counts = 0;
block->addresses = NULL;
block++;
}
return 0;
}
void ddhcp_block_free(ddhcp_config* config) {
ddhcp_block* block = config->blocks;
for (uint32_t i = 0; i < config->number_of_blocks; i++) {
block_free(block++);
}
block_free_claims(config);
free(config->blocks);
}
void ddhcp_block_process(uint8_t* buffer, int len, struct sockaddr_in6 sender, ddhcp_config* config) {
struct ddhcp_mcast_packet packet;
int ret = ntoh_mcast_packet(buffer, len, &packet);
packet.sender = &sender;
if (ret == 0) {
switch (packet.command) {
case DDHCP_MSG_UPDATECLAIM:
ddhcp_block_process_claims(&packet, config);
break;
case DDHCP_MSG_INQUIRE:
ddhcp_block_process_inquire(&packet, config);
break;
default:
break;
}
free(packet.payload);
} else {
DEBUG("epoll_ret: %i\n", ret);
}
}
void ddhcp_block_process_claims(struct ddhcp_mcast_packet* packet, ddhcp_config* config) {
DEBUG("ddhcp_block_process_claims(packet, config )\n");
assert(packet->command == 1);
time_t now = time(NULL);
ddhcp_block* blocks = config->blocks;
for (unsigned int i = 0; i < packet->count; i++) {
struct ddhcp_payload* claim = &packet->payload[i];
uint32_t block_index = claim->block_index;
if (block_index >= config->number_of_blocks) {
WARNING("ddhcp_block_process_claims(...): Malformed block number\n");
continue;
}
if (blocks[block_index].state == DDHCP_OURS) {
INFO("ddhcp_block_process_claims(...): node 0x%02x%02x%02x%02x%02x%02x%02x%02x claims our block %i\n", HEX_NODE_ID(packet->node_id), block_index);
// TODO Decide when and if we reclaim this block
// Which node has more leases in this block, ..., who has the better node_id.
} else {
// Notice the ownership
blocks[block_index].state = DDHCP_CLAIMED;
blocks[block_index].timeout = now + claim->timeout;
// Save the connection details for the claiming node
// We need to contact him, for dhcp forwarding actions.
memcpy(&blocks[block_index].owner_address, &packet->sender->sin6_addr, sizeof(struct in6_addr));
memcpy(&blocks[block_index].node_id, &packet->node_id, sizeof(ddhcp_node_id));
#if LOG_LEVEL >= LOG_DEBUG
char ipv6_sender[INET6_ADDRSTRLEN];
DEBUG("Register block to %s\n",
inet_ntop(AF_INET6, &blocks[block_index].owner_address, ipv6_sender, INET6_ADDRSTRLEN));
#endif
INFO("ddhcp_block_process_claims(...): node 0x%02x%02x%02x%02x%02x%02x%02x%02x claims block %i with ttl: %i\n", HEX_NODE_ID(packet->node_id), block_index, claim->timeout);
}
}
}
void ddhcp_block_process_inquire(struct ddhcp_mcast_packet* packet, ddhcp_config* config) {
DEBUG("ddhcp_block_process_inquire( blocks, packet, config )\n");
assert(packet->command == 2);
time_t now = time(NULL);
ddhcp_block* blocks = config->blocks;
for (unsigned int i = 0; i < packet->count; i++) {
struct ddhcp_payload* tmp = &packet->payload[i];
if (tmp->block_index >= config->number_of_blocks) {
WARNING("ddhcp_block_process_inquire(...): Malformed block number\n");
continue;
}
INFO("ddhcp_block_process_inquire(...): node 0x%02x%02x%02x%02x%02x%02x%02x%02x inquires block %i\n", HEX_NODE_ID(packet->node_id), tmp->block_index);
if (blocks[tmp->block_index].state == DDHCP_OURS) {
// Update Claims
INFO("ddhcp_block_process_inquire(...): block %i is ours notify network", tmp->block_index);
blocks[tmp->block_index].timeout = 0;
block_update_claims(0, config);
} else if (blocks[tmp->block_index].state == DDHCP_CLAIMING) {
INFO("ddhcp_block_process_inquire(...): we are interested in block %i also\n", tmp->block_index);
// QUESTION Why do we need multiple states for the same process?
if (NODE_ID_CMP(packet->node_id, config->node_id) > 0) {
INFO("ddhcp_block_process_inquire(...): .. but other node wins.\n");
blocks[tmp->block_index].state = DDHCP_TENTATIVE;
blocks[tmp->block_index].timeout = now + config->tentative_timeout;
}
// otherwise keep inquiring, the other node should see our inquires and step back.
} else {
INFO("ddhcp_block_process_inquire(...): set block %i to tentative \n", tmp->block_index);
blocks[tmp->block_index].state = DDHCP_TENTATIVE;
blocks[tmp->block_index].timeout = now + config->tentative_timeout;
}
}
}
void ddhcp_dhcp_process(uint8_t* buffer, int len, struct sockaddr_in6 sender, ddhcp_config* config) {
struct ddhcp_mcast_packet packet;
int ret = ntoh_mcast_packet(buffer, len, &packet);
packet.sender = &sender;
if (ret == 0) {
switch (packet.command) {
case DDHCP_MSG_RENEWLEASE:
ddhcp_dhcp_renewlease(&packet, config);
break;
case DDHCP_MSG_LEASEACK:
ddhcp_dhcp_leaseack(&packet, config);
break;
case DDHCP_MSG_LEASENAK:
ddhcp_dhcp_leasenak(&packet, config);
break;
case DDHCP_MSG_RELEASE:
ddhcp_dhcp_release(&packet, config);
break;
default:
break;
}
}
}
void ddhcp_dhcp_renewlease(struct ddhcp_mcast_packet* packet, ddhcp_config* config) {
DEBUG("ddhcp_dhcp_renewlease(request, config)\n");
#if LOG_LEVEL >= LOG_DEBUG
char* hwaddr = hwaddr2c(packet->renew_payload->chaddr);
DEBUG("ddhcp_dhcp_renewlease( ... ): Request for xid: %u chaddr: %s\n", packet->renew_payload->xid, hwaddr);
free(hwaddr);
#endif
int ret = dhcp_rhdl_request(&(packet->renew_payload->address), config);
ddhcp_mcast_packet* answer = NULL;
if (ret == 0) {
DEBUG("ddhcp_dhcp_renewlease( ... ): %i ACK\n", ret);
answer = new_ddhcp_packet(DDHCP_MSG_LEASEACK, config);
} else if (ret == 1) {
DEBUG("ddhcp_dhcp_renewlease( ... ): %i NAK\n", ret);
answer = new_ddhcp_packet(DDHCP_MSG_LEASENAK, config);
// TODO Can we hand over the block?
} else {
// Unexpected behaviour
WARNING("ddhcp_dhcp_renewlease( ... ) -> Unexpected return value from dhcp_rhdl_request.");
return;
}
answer->renew_payload = packet->renew_payload;
send_packet_direct(answer, &packet->sender->sin6_addr, config->server_socket, config->mcast_scope_id);
free(answer->renew_payload);
free(answer);
}
void ddhcp_dhcp_leaseack(struct ddhcp_mcast_packet* request, ddhcp_config* config) {
// Stub functions
DEBUG("ddhcp_dhcp_leaseack(request,config)\n");
#if LOG_LEVEL >= LOG_DEBUG
char* hwaddr = hwaddr2c(request->renew_payload->chaddr);
DEBUG("ddhcp_dhcp_leaseack( ... ): ACK for xid: %u chaddr: %s\n", request->renew_payload->xid, hwaddr);
free(hwaddr);
#endif
dhcp_packet* packet = dhcp_packet_list_find(&config->dhcp_packet_cache, request->renew_payload->xid, request->renew_payload->chaddr);
if (packet == NULL) {
// Ignore packet
DEBUG("ddhcp_dhcp_leaseack( ... ) -> No matching packet found, ignore message\n");
} else {
// Process packet
dhcp_rhdl_ack(config->client_socket, packet, config);
}
dhcp_packet_free(packet, 1);
free(packet);
free(request->renew_payload);
}
void ddhcp_dhcp_leasenak(struct ddhcp_mcast_packet* request, ddhcp_config* config) {
// Stub functions
DEBUG("ddhcp_dhcp_leasenak(request,config)\n");
#if LOG_LEVEL >= LOG_DEBUG
char* hwaddr = hwaddr2c(request->renew_payload->chaddr);
DEBUG("ddhcp_dhcp_leaseack( ... ): NAK for xid: %u chaddr: %s\n", request->renew_payload->xid, hwaddr);
free(hwaddr);
#endif
dhcp_packet* packet = dhcp_packet_list_find(&config->dhcp_packet_cache, request->renew_payload->xid, request->renew_payload->chaddr);
if (packet == NULL) {
// Ignore packet
DEBUG("ddhcp_dhcp_leaseack( ... ) -> No matching packet found, ignore message\n");
} else {
// Process packet
dhcp_nack(config->client_socket, packet);
}
dhcp_packet_free(packet, 1);
free(packet);
free(request->renew_payload);
}
void ddhcp_dhcp_release(struct ddhcp_mcast_packet* packet, ddhcp_config* config) {
DEBUG("ddhcp_dhcp_release(packet,config)\n");
dhcp_release_lease(packet->renew_payload->address, config);
free(packet->renew_payload);
}
|
C
|
#include "stdio.h"
int fibonacci(int n)
{
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
}
return (fibonacci(n - 1) + fibonacci(n - 2));
}
int main()
{
int a;
a = 10;
printf("fibonacci(%d) = %d\n", a, fibonacci(a));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(){
int vet1[10];
int i, n;
for (i=0 ; i<10 ; i++)
{
printf("digite o valor do numero na posicao [%d]: ",i+1 );
scanf("%d", &n);
vet1[i]= n;
}
for (i=9 ; i>=0 ; i--)
{
printf("os numeros invertidos sao:\n %d\n", vet1[i]);
}
return 0;
}
|
C
|
/**
Ŀ
֪ABֱʾǿռϣԪСһABԪظ2000Ϸʹҵѧ⣨8֣
ˣ
ʽ
5 2 3 4 5 6
4 1 2 5 8
˵
һеһAĸΪAԪأ
ڶеһBĸΪBԪء
ʽ
7
˵
ABIJԪظ**/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int lenA=10,lenB=10;
int A[lenA],B[lenB];
int i,j,k=0,len;
scanf("%d",&lenA);
for(i=0;i<lenA;i++)
{
scanf("%d",&A[i]);
}
scanf("%d",&lenB);
for(i=0;i<lenB;i++)
{
scanf("%d",&B[i]);
}
for(i=0;i<lenA;i++)
{
for(j=0;j<lenB;j++)
{
if(A[i]==B[j])
k++;
}
}
len=lenA+lenB-k;
printf("%d",len);
return 0;
}
|
C
|
#include "flux_code.h"
#include<string.h> // memcpy
#include<stdlib.h> // malloc
#include<endian.h>
#include "flux_command.h"
#include "flux_exception.h"
#include "flux_exception_table.h"
#include "flux_instruction.h"
#include"flux_list.h"
#include"flux_log.h"
#include "flux_object.h"
#if __BYTE_ORDER == __LITTLE_ENDIAN
#define INT32_TO_SYSTEM_ENDIANNESS(x) (x<<24) | ((x&0xf00)<<8) | ((x>>8)&0xff00) | ((x>>24)&0xff)
#elif __BYTE_ORDER == __BIG_ENDIAN
#define INT32_TO_SYSTEM_ENDIANNESS(x) x
#elif __BYTE_ORDER == __PDP_ENDIAN
#error "System Endianness not supported"
#endif
FluxCode* flux_code_init(char* bytes, int length) {
FluxCode* code = malloc(sizeof(FluxCode));
FluxExceptionTable* exception_table = flux_exception_table_init();
FluxCommand** commands;
int number_of_commands = flux_code_convert_to_flux_commands(bytes, length, &commands, &exception_table);
code->commands = commands;
code->number_of_commands = number_of_commands;
code->exception_table = exception_table;
return code;
}
void flux_code_free(FluxCode* code) {
if(code == NULL)
return;
for(int i = 0; i < code->number_of_commands; i++) {
if(code->commands[i] != NULL)
flux_command_free(code->commands[i]);
}
free(code->commands);
flux_exception_table_free(code->exception_table);
free(code);
}
int flux_code_convert_to_flux_commands(char* bytes, int length, FluxCommand*** commands, FluxExceptionTable** exception_table) {
FluxList* list = flux_list_init(sizeof(FluxCommand*), NULL);
int number_of_commands = 0;
for(int i = 0; i < length; i++) {
if (bytes[i] == POP) {
FluxCommand* pop_command = flux_command_init(POP, NULL, 0);
flux_list_add(list, pop_command);
number_of_commands++;
}
else if (bytes[i] == IPUSH) {
int number;
memcpy(&number, (bytes + i + 1), 4);
i += 4;
number = INT32_TO_SYSTEM_ENDIANNESS(number);
FluxObject* int_obj = flux_object_iinit(number);
FluxObject** param = malloc(sizeof(FluxObject*));
param[0] = int_obj;
FluxCommand* ipush_command = flux_command_init(IPUSH, param, 1);
flux_list_add(list, ipush_command);
number_of_commands++;
}
else if (bytes[i] == AEX) {
i++;
int from_instruction = read_integer((bytes + i));
i += 4;
int to_instruction = read_integer((bytes + i));
i += 4;
int jump_location = read_integer((bytes + i));
i += 4;
int exception_type = read_integer((bytes + i));
i += 4;
FluxException* ex = flux_exception_init(from_instruction, to_instruction, jump_location, exception_type);
flux_exception_table_add(*exception_table, ex);
i--; // the index is incremeted in the next loop
}
else if (bytes[i] == SPUSH) {
int str_length;
memcpy(&str_length, (bytes + i + 1), 4);
str_length = INT32_TO_SYSTEM_ENDIANNESS(str_length);
i += 5;
FluxObject* obj = flux_object_strinit((bytes + i), str_length);
i += str_length - 1;
FluxObject** param = malloc(sizeof(FluxObject*));
param[0] = obj;
FluxCommand* spush_command = flux_command_init(SPUSH, param, 1);
flux_list_add(list, spush_command);
number_of_commands++;
}
else if (bytes[i] == IADD || bytes[i] == ISUB || bytes[i] == LOAD || bytes[i] == LOAD0 || bytes[i] == LOAD1 || bytes[i] == LOAD2 || bytes[i] == LOAD3|| bytes[i] == STORE || bytes[i] == STORE0 || bytes[i] == STORE1 || bytes[i] == STORE2 || bytes[i] == STORE3|| bytes[i] == CMP || bytes[i] == IMUL || bytes[i] == IDIV || bytes[i] == THROW || bytes[i] == RET || bytes[i] == EXIT) {
flux_list_add(list, flux_command_init(bytes[i], NULL, 0));
number_of_commands++;
}
else if (bytes[i] == PRINT || bytes[i] == INSPECT) {
FluxInstruction instruction = bytes[i];
FluxCommand* c = flux_command_init(instruction, NULL, 0);
flux_list_add(list, c);
number_of_commands++;
}
else if (bytes[i] == ITOD) {
int number;
memcpy(&number, (bytes + i + 1), 4);
i += 4;
number = INT32_TO_SYSTEM_ENDIANNESS(number);
FluxObject* itod_obj = flux_object_iinit(number);
FluxObject** param = malloc(sizeof(FluxObject*));
param[0] = itod_obj;
FluxCommand* ipush_command = flux_command_init(ITOD, param, 1);
flux_list_add(list, ipush_command);
number_of_commands++;
}
else if (bytes[i] == JSR || bytes[i] == JE || bytes[i] == JL || bytes[i] == JLE || bytes[i] == JGE) {
FluxInstruction instruction = bytes[i];
int number = read_integer((bytes + i + 1));
i += 4;
FluxObject* obj = flux_object_iinit(number);
FluxObject** param = malloc(sizeof(FluxObject*));
param[0] = obj;
FluxCommand* jmp = flux_command_init(instruction, param, 1);
flux_list_add(list, jmp);
number_of_commands++;
} else if(bytes[i] == IREF || bytes[i] == DREF) {
FluxInstruction instruction = bytes[i];
int index;
memcpy(&index, (bytes + i + 1), 4);
index = INT32_TO_SYSTEM_ENDIANNESS(index);
i+=4;
FluxObject* obj = flux_object_iinit(index);
FluxObject** param = malloc(sizeof(FluxObject*));
param[0] = obj;
FluxCommand* iref = flux_command_init(instruction,param, 1);
flux_list_add(list, iref);
number_of_commands++;
}
else {
FLUX_WLOG("Unknown Command '%d' in bytecode at byte position %d -- Command is being ignored", bytes[i], i);
}
}
*commands = (FluxCommand**)flux_list_to_array(list);
flux_list_free(list);
return number_of_commands;
}
int read_integer(char* buffer) {
int number;
memcpy(&number, buffer, 4);
number = INT32_TO_SYSTEM_ENDIANNESS(number);
return number;
}
|
C
|
#include "gc.h"
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
// testing framework
static void* __finalisersCalled[2048];
static int __finaliserIndex = 0;
static void __finaliser ( void* ptr )
{
__finalisersCalled[__finaliserIndex++] = ptr;
}
#define ASSERT(x, message) if (!(x)) { printf("Assertion failure: %s\n\t%s : %d\n", message, __FILE__, __LINE__); abort(); }
typedef void* object;
static object NEW () { object obj = GC_new_object(10, GC_ROOT, __finaliser); return obj; }
static void RELEASE ( object obj ) { GC_unregister_reference(GC_ROOT, obj); }
#define ASSERTLIVE(obj) ASSERT(GC_object_live(obj), "object murdered")
#define ASSERTDEAD(obj) ASSERT(!GC_object_live(obj), "object survived unexpectedly")
#define ASSERTWRZ(wr) ASSERT(wr == NULL, "weak reference pointing to zombie")
#define ASSERTWRL(wr) ASSERT(wr != NULL, "weak reference unexpectedly nullified")
#define ASSERTFINAL(obj) { bool __finaliserF = 0; int __finaliserI; for (__finaliserI = 0; __finaliserI < __finaliserIndex; __finaliserI++) { if (__finalisersCalled[__finaliserI] == obj) { __finaliserF = 1; break; } } ASSERT(__finaliserF, "object finaliser not called"); }
#define ASSERTNOFINAL(obj) { bool __finaliserF = 0; int __finaliserI; for (__finaliserI = 0; __finaliserI < __finaliserIndex; __finaliserI++) { if (__finalisersCalled[__finaliserI] == obj) { __finaliserF = 1; break; } } ASSERT(!__finaliserF, "object finaliser unexpectedly called"); }
|
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 */
struct Curl_easy {int dummy; } ;
typedef scalar_t__ CURLcode ;
/* Variables and functions */
scalar_t__ Curl_urldecode (struct Curl_easy*,char const*,int /*<<< orphan*/ ,char**,size_t*,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ FALSE ;
int /*<<< orphan*/ free (char*) ;
char* malloc (size_t) ;
__attribute__((used)) static char *unescape_word(struct Curl_easy *data, const char *inputbuff)
{
char *newp = NULL;
char *dictp;
size_t len;
CURLcode result = Curl_urldecode(data, inputbuff, 0, &newp, &len, FALSE);
if(!newp || result)
return NULL;
dictp = malloc(len*2 + 1); /* add one for terminating zero */
if(dictp) {
char *ptr;
char ch;
int olen = 0;
/* According to RFC2229 section 2.2, these letters need to be escaped with
\[letter] */
for(ptr = newp;
(ch = *ptr) != 0;
ptr++) {
if((ch <= 32) || (ch == 127) ||
(ch == '\'') || (ch == '\"') || (ch == '\\')) {
dictp[olen++] = '\\';
}
dictp[olen++] = ch;
}
dictp[olen] = 0;
}
free(newp);
return dictp;
}
|
C
|
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
uint8_t fabric[1000][1000] = {0};
uint32_t overlaps = 0;
void fill_count(uint16_t cx, uint16_t cy, uint16_t width, uint16_t height) {
for (int x = cx, i = 0; i < width; x++, i++) {
for (int y = cy, j = 0; j < height; y++, j++) {
if (!fabric[x][y]) {
fabric[x][y] = 1;
} else if (fabric[x][y] == 1) {
overlaps++;
fabric[x][y] = 2;
}
}
}
}
int main(void) {
FILE *fp;
char read_buffer[128];
const char *file_name = "input.txt";
fp = fopen(file_name, "r");
if (fp == NULL) {
printf("Could not open file");
return 1;
}
while (fgets(read_buffer, 128, fp) != NULL) {
uint16_t id, cx, cy, width, height;
sscanf(read_buffer, "%*c%hu %*c %hu%*c%hu%*c %hu%*c%hu", &id, &cx, &cy, &width, &height);
fill_count(cx, cy, width, height);
}
fclose(fp);
printf("Overlaping squinches: %d\n", overlaps);
return 0;
}
|
C
|
#include "_.h"
extern Value AT_VALUES;
#define LIB_COUNT 4
static Value at_Math_init ();
static Value at_Console_init ();
static Value at_IO_init ();
static Value at_Date_init ();
static struct { Chars name; InitFunc func; }
__lib[LIB_COUNT] = {
{"Math", at_Math_init},
{"IO", at_IO_init},
{"Console", at_Console_init},
{"Date", at_Date_init}
};
InitFunc LIB_getInitFunc (Chars name) {
int i = 0;
for (; i < LIB_COUNT; ++i) {
if (!strcmp(name, __lib[i].name)) {
return __lib[i].func;
}
}
return NULL;
}
// ================================================================================================
// Math
// ================================================================================================
#define MATH_FUNC_1(FUNC_NAME, CALLED_FUNC_NAME) \
static Value at_Math_##FUNC_NAME (Procedure proc, Value at, Exp arg) {\
Exp argE = NULL;\
Value argV = NULL;\
Value result = NULL;\
if (arg) {\
TRAVERSEL_COMMA_EXP(arg, argE);\
argV = Procedure_eval(proc, argE);\
if (argV && Value_is(argV, at_Number)) {\
result = Value_number(CALLED_FUNC_NAME(argV->u.number));\
}\
}\
return result;\
}
#define MATH_FUNC_2(FUNC_NAME, CALLED_FUNC_NAME) \
static Value at_Math_##FUNC_NAME (Procedure proc, Value at, Exp arg) {\
Exp argE = NULL;\
Value argV1 = NULL, argV2 = NULL;\
Value result = NULL;\
if (arg) {\
TRAVERSEL_COMMA_EXP(arg, argE);\
argV1 = Procedure_eval(proc, argE);\
if (arg) {\
TRAVERSEL_COMMA_EXP(arg, argE);\
argV2 = Procedure_eval(proc, argE);\
if (argV1 && argV2 && Value_is(argV1, at_Number) && Value_is(argV2, at_Number)) {\
result = Value_number(CALLED_FUNC_NAME(argV1->u.number, argV2->u.number));\
}\
}\
}\
return result;\
}
#define VALUE_SET(FUNC_NAME) Value_set(self, Value_string(#FUNC_NAME), Value_func(at_Math_##FUNC_NAME))
MATH_FUNC_1(sin, sin)
MATH_FUNC_1(cos, cos)
MATH_FUNC_1(tan, tan)
MATH_FUNC_1(asin, asin)
MATH_FUNC_1(acos, acos)
MATH_FUNC_1(atan, atan)
MATH_FUNC_1(sinh, sinh)
MATH_FUNC_1(cosh, cosh)
MATH_FUNC_1(tanh, tanh)
MATH_FUNC_1(log, log)
MATH_FUNC_1(log10, log10)
MATH_FUNC_1(exp, exp)
MATH_FUNC_1(sqrt, sqrt)
MATH_FUNC_1(ceil, ceil)
MATH_FUNC_1(floor, floor)
MATH_FUNC_1(round, round)
MATH_FUNC_1(sign, math_sign)
MATH_FUNC_2(atan2, atan2)
MATH_FUNC_2(pow, pow)
MATH_FUNC_2(mod, fmod)
MATH_FUNC_2(hypot, hypot)
static Value at_Math_max (Procedure proc, Value at, Exp arg) {
Exp argE = NULL;
Value argV = NULL;
Value result = NULL;
while (arg) {
TRAVERSEL_COMMA_EXP(arg, argE);
argV = Procedure_eval(proc, argE);
if (!result) {
result = argV;
} else if (argV && Value_is(result, at_Number) && Value_is(argV, at_Number)) {
if (result->u.number < argV->u.number) {
result = argV;
}
}
}
return result;
}
static Value at_Math_min (Procedure proc, Value at, Exp arg) {
Exp argE = NULL;
Value argV = NULL;
Value result = NULL;
while (arg) {
TRAVERSEL_COMMA_EXP(arg, argE);
argV = Procedure_eval(proc, argE);
if (!result) {
result = argV;
} else if (argV && Value_is(result, at_Number) && Value_is(argV, at_Number)) {
if (result->u.number > argV->u.number) {
result = argV;
}
}
}
return result;
}
static Value at_Math_init () {
Value self = Value_new(at_True, NULL);
VALUE_SET(sin); VALUE_SET(cos); VALUE_SET(tan);
VALUE_SET(asin); VALUE_SET(acos); VALUE_SET(atan);
VALUE_SET(sinh); VALUE_SET(cosh); VALUE_SET(tanh);
VALUE_SET(log); VALUE_SET(log10);
VALUE_SET(exp); VALUE_SET(sqrt);
VALUE_SET(ceil); VALUE_SET(floor); VALUE_SET(round); VALUE_SET(sign);
VALUE_SET(atan2);
VALUE_SET(pow); VALUE_SET(mod);
VALUE_SET(hypot);
VALUE_SET(max); VALUE_SET(min);
Value_set(self, Value_string("random"), Value_number((double)rand() / RAND_MAX));
Value_set(self, Value_string("pi"), Value_number(M_PI));
Value_set(self, Value_string("e"), Value_number(M_E));
Value_set(self, Value_string("log2e"), Value_number(M_LOG2E));
Value_set(self, Value_string("log10e"), Value_number(M_LOG10E));
Value_set(self, Value_string("sqrt2"), Value_number(M_SQRT2));
Value_set(self, Value_string("ln2"), Value_number(M_LN2));
Value_set(self, Value_string("ln10"), Value_number(M_LN10));
return self;
}
// ================================================================================================
// Console
// ================================================================================================
static Value at_Console_log (Procedure proc, Value at, Exp arg) {
Exp argE = NULL;
Value argV = NULL;
int isFirst = 1;
while (arg) {
isFirst || printf(", "), isFirst = 0;
TRAVERSEL_COMMA_EXP(arg, argE);
argV = Procedure_eval(proc, argE);
if (argV) {
if (Value_is(argV, at_Number)) printf(r2s(argV->u.number));
else if (Value_is(argV, at_String)) printf(argV->u.string);
else if (Value_is(argV, at_Array)) printf("Array");
else if (Value_is(argV, at_Function)) printf("Function");
else if (Value_is(argV, at_Accessor)) printf("Accessor");
else if (Value_is(argV, at_Func)) printf("Func");
else if (Value_is(argV, at_True)) printf("True");
else printf("unknown value type");
} else {
printf("<null>");
}
}
printf("\n");
return NULL;
}
static Value at_Console_assert (Procedure proc, Value at, Exp arg) {
Exp argE = NULL;
Value argV = NULL;
if (arg) {
TRAVERSEL_COMMA_EXP(arg, argE);
argV = Procedure_eval(proc, argE);
if (!argV) {
at_Console_log(proc, at, arg);
}
}
return NULL;
}
static Value at_Console_timerStart (Procedure proc, Value at, Exp arg) {
return NULL;
}
static Value at_Console_timerEnd (Procedure proc, Value at, Exp arg) {
return NULL;
}
static Value at_Console_new (Procedure proc, Value at, Exp arg) {
Exp argE = NULL;
Value argV = NULL;
while (arg) {
TRAVERSEL_COMMA_EXP(arg, argE);
if (argV = Value_toStringValue(Procedure_eval(proc, argE))) {
system(argV->u.string);
}
}
return NULL;
}
static Value at_Console_init () {
Value self = Value_new(at_Func, at_Console_new);
//printf("Console_init\n");
Value_set(self, Value_string("log"), Value_func(at_Console_log));
Value_set(self, Value_string("assert"), Value_func(at_Console_assert));
Value_set(self, Value_string("timerStart"), Value_func(at_Console_timerStart));
Value_set(self, Value_string("timerEnd"), Value_func(at_Console_timerEnd));
return self;
}
// ================================================================================================
// Date
// ================================================================================================
static Value at_Date = NULL;
static Value at_Date_date (Procedure proc, Value at, Exp arg) {
if (!Value_is(at, at_Date)) return NULL;
return NULL;
}
static Value at_Date_day (Procedure proc, Value at, Exp arg) {
if (!Value_is(at, at_Date)) return NULL;
struct tm *details;
time_t timestamp;
Value result = NULL;
if (arg && arg->u.value) {
timestamp = (at == at_Date ? time(NULL) : ((struct timeval *)at->u.pointer)->tv_sec);
details = localtime(×tamp);
if (arg->u.value->u.func == at_Date_day) {
result = Value_number(details->tm_mday);
}
free(details);
}
return result;
}
static Value at_Date_month (Procedure proc, Value at, Exp arg) {
return NULL;
}
static Value at_Date_year (Procedure proc, Value at, Exp arg) {
return NULL;
}
static Value at_Date_hours (Procedure proc, Value at, Exp arg) {
if (!Value_is(at, at_Date)) return NULL;
struct tm *details;
time_t timestamp;
Value result = NULL;
if (arg && arg->u.value) {
timestamp = (at == at_Date ? time(NULL) : ((struct timeval *)at->u.pointer)->tv_sec);
details = localtime(×tamp);
if (arg->u.value->u.func == at_Date_hours) {
result = Value_number(details->tm_hour);
}
free(details);
}
return result;
}
static Value at_Date_minutes (Procedure proc, Value at, Exp arg) {
return NULL;
}
static Value at_Date_seconds (Procedure proc, Value at, Exp arg) {
return NULL;
}
static Value at_Date_miniseconds (Procedure proc, Value at, Exp arg) {
if (!Value_is(at, at_Date)) return NULL;
struct timeval *tv_ptr = NULL;
struct timeval tv;
if (arg && arg->u.value && arg->u.value->u.func == at_Date_miniseconds) {
if (at == at_Date) {
gettimeofday(&tv, NULL);
return Value_number(tv.tv_usec / 1000.0);
}
tv_ptr = (struct timeval *)at->u.pointer;
return Value_number(tv_ptr->tv_usec / 1000.0);
}
return NULL;
}
static Value at_Date_time (Procedure proc, Value at, Exp arg) {
return NULL;
}
static Value at_Date_toString (Procedure proc, Value at, Exp arg) {
return NULL;
}
static Value at_Date_new (Procedure proc, Value at, Exp arg) {
Value result = NULL;
struct timeval *tv = (struct timeval *)malloc(sizeof(struct timeval));
gettimeofday(tv, NULL);
result = Value_new(at_Date, tv);
return result;
}
static Value at_Date_init () {
Value self = Value_new(at_Func, at_Date_new);
//printf("Console_init\n");
Value_set(self, Value_string("date"), Value_funcAccessor(at_Date_date));
Value_set(self, Value_string("day"), Value_funcAccessor(at_Date_day));
Value_set(self, Value_string("month"), Value_funcAccessor(at_Date_month));
Value_set(self, Value_string("year"), Value_funcAccessor(at_Date_year));
Value_set(self, Value_string("hours"), Value_funcAccessor(at_Date_hours));
Value_set(self, Value_string("minutes"), Value_funcAccessor(at_Date_minutes));
Value_set(self, Value_string("seconds"), Value_funcAccessor(at_Date_seconds));
Value_set(self, Value_string("miniseconds"), Value_funcAccessor(at_Date_miniseconds));
Value_set(self, Value_string("time"), Value_funcAccessor(at_Date_time));
Value_set(self, Value_string("toString"), Value_func(at_Date_toString));
at_Date = self;
return self;
}
// ================================================================================================
// IO
// ================================================================================================
extern Interpreter at_currentInterpreter;
static Value at_IO = NULL;
static Value at_IO_read (Procedure proc, Value at, Exp arg) {
if (!Value_is(at, at_IO)) return NULL;
File stream = (at == at_IO ? stdin : (File)at->u.pointer);
char buffer[256];
fscanf(stream, "%s", buffer);
return Value_string(buffer);
}
static Value at_IO_readLine (Procedure proc, Value at, Exp arg) {
if (!Value_is(at, at_IO)) return NULL;
File stream = (at == at_IO ? stdin : (File)at->u.pointer);
int letter = fgetc((stream));
Value result = NULL;
for (; letter != EOF && letter != '\n'; letter = fgetc(stream)) {
StringBuffer_add(letter);
}
result = StringBuffer_close();
return result;
}
static Value at_IO_write (Procedure proc, Value at, Exp arg) {
if (!Value_is(at, at_IO)) return NULL;
File stream = (at == at_IO ? stdout : (File)at->u.pointer);
Exp argE = NULL;
Value argV = NULL;
while (arg) {
TRAVERSEL_COMMA_EXP(arg, argE);
if (argV = Value_toStringValue(Procedure_eval(proc, argE))) {
fprintf(stream, argV->u.string);
}
}
return NULL;
}
static Value at_IO_writeLine (Procedure proc, Value at, Exp arg) {
if (!Value_is(at, at_IO)) return NULL;
File stream = (at == at_IO ? stdout : (File)at->u.pointer);
Exp argE = NULL;
Value argV = NULL;
while (arg) {
TRAVERSEL_COMMA_EXP(arg, argE);
if (argV = Value_toStringValue(Procedure_eval(proc, argE))) {
fprintf(stream, "%s\n", argV->u.string);
}
}
return NULL;
}
static Value at_IO_new (Procedure proc, Value at, Exp arg) {
File stream = NULL;
Exp argE = NULL;
Value path = NULL, mode = NULL;
Value result = NULL;
if (arg) {
TRAVERSEL_COMMA_EXP(arg, argE);
path = Value_toStringValue(Procedure_eval(proc, argE));
if (arg) {
TRAVERSEL_COMMA_EXP(arg, argE);
mode = Value_toStringValue(Procedure_eval(proc, argE));
}
path = Interpreter_getFilePath(at_currentInterpreter, path);
if (!mode) mode = Value_string("r+");
stream = fopen(path->u.string, mode->u.string);
if (!stream) {
printf("file can't open. (%s)\n", path->u.string);
return NULL;
}
result = Value_new(at_IO, stream);
}
return result;
}
static Value at_IO_file_open (Procedure proc, Value at, Exp arg) {
return NULL;
}
static Value at_IO_file_close (Procedure proc, Value at, Exp arg) {
return NULL;
}
static Value at_IO_init () {
Value self = Value_new(at_Func, at_IO_new);
Value_set(self, Value_string("read"), Value_func(at_IO_read));
Value_set(self, Value_string("readLine"), Value_func(at_IO_readLine));
Value_set(self, Value_string("write"), Value_func(at_IO_write));
Value_set(self, Value_string("writeLine"), Value_func(at_IO_writeLine));
at_IO = self;
return self;
}
|
C
|
/*!
* This file defines an interface to compare single characters.
*
* @author Louis Dionne
*/
#ifndef JOY_CHAR_CMP_H
#define JOY_CHAR_CMP_H
#include <joy/char/value.h>
#include <chaos/preprocessor/control/branch.h>
#include <chaos/preprocessor/comparison/equal.h>
#include <chaos/preprocessor/comparison/less.h>
#define JOY_CHAR_CMP(a, b) \
JOY_I_CHAR_CMP(JOY_CHAR_VALUE(a), JOY_CHAR_VALUE(b))
#define JOY_I_CHAR_CMP(a, b) CHAOS_PP_BRANCH \
(0xIF) (CHAOS_PP_EQUAL(a, b)) ( \
JOY_CHAR_CMP_EQUAL \
) (0xELIF) (CHAOS_PP_LESS(a, b)) ( \
JOY_CHAR_CMP_LESSER \
) (0xELSE) ( \
JOY_CHAR_CMP_GREATER \
) (0xENDIF) \
/**/
#define JOY_CHAR_CMP_EQUAL 0
#define JOY_CHAR_CMP_LESSER 1
#define JOY_CHAR_CMP_GREATER 2
#endif /* !JOY_CHAR_CMP_H */
|
C
|
#include "seqlist.h"
void InitSeqlist(pseqlist pseq)//ʼ˳
{
assert(pseq);
pseq->size = 0;
}
void PrintSeqlist(pseqlist pseq)//ӡ˳
{
assert(pseq);
size_t i = 0;
if ((pseq->size) == 0)
{
printf("ѾΪ");
return;
}
else
{
for (i = 0; i < pseq->size; i++)
{
printf("%d->", pseq->arr[pseq->size]);
}
printf("\n");
}
}
int Find(pseqlist pseq, DataType data)//Ԫ
{
assert(pseq);
if ((pseq->size) == 0)
{
printf("ѾΪ");
return 0;
}
for (int i = 0; i < pseq->size; i++)
{
if (pseq->arr[pseq->size] == data)
{
return i;
}
else
{
return -1;
}
}
}
void PushBack(pseqlist pseq, DataType data)//β
{
assert(pseq);//жָǷΪ
if ((pseq->size) >= max_size)//
{
printf("Ѿ");
return;
}
else
{
pseq->arr[pseq->size] = data;//sizeλ˳ЧԪصĺ
}
pseq->size++;//size
}
void PopBack(pseqlist pseq)//βɾ
{
assert(pseq);
if ((pseq->size) == 0)
{
printf("ѿ");
return;
}
else
{
pseq->size--;
printf("ɾɹ");
}
}
void PushFront(pseqlist pseq, DataType data)//ͷ
{
assert(pseq);
if ((pseq->size) >= max_size)
{
printf("Ѿ");
return;
}
else
{
for (int i = pseq->size; i >= 0; i--)
{
pseq->arr[i] = pseq->arr[i - 1];//Ԫƣճarr[0]λ
pseq->arr[0] = data;
}
pseq->size++;
}
}
void PopFront(pseqlist pseq)//ͷɾ
{
assert(pseq);
if (pseq->size == 0)
{
printf("ѿ");
return;
}
else
{
for (int i = pseq->size - 1; i >0; i--)
{
pseq->arr[i - 1] = pseq->arr[i];//ǰ
}
pseq->size--;
printf("ɾɹ");
}
}
void Insert(pseqlist pseq, int pos, DataType data)//λò
{
assert(pseq);//1.жָǷΪ
if ((pseq->size) >= max_size)//2.жǷΪ
{
printf("Ѿ");
return;
}
if (pos < 0 || pseq->size < pos)//3.жλǷǷ
{
printf("λ÷Ƿ");
return;
}
else
{
for (int i = pseq->size - 1; i >= pos; --i)
{
pseq->arr[i + 1] = pseq->arr[i];//posԼposλԺĺ
pseq->arr[pos - 1] = data;//ڳλ÷Ҫ
}
pseq->size++;
}
}
void Erase(pseqlist pseq, int pos)//λõɾ
{
assert(pseq);//1.жָǷΪ
if ((pseq->size) == 0)//2.жǷΪ
{
printf("ѿ");
return;
}
if (pos < 0 || pseq->size < pos)//3.жλǷǷ
{
printf("λ÷Ƿ");
return;
}
else
{
for (int i = pos - 1; i<pseq->size - 1; i++)
{
pseq->arr[i] = pseq->arr[i + 1];//һԪؿʼposλýǰ
}
pseq->size--;
}
}
void Remove(pseqlist pseq, DataType data)//ɾһΪdataԪ
{
assert(pseq);
int i = Find(pseq, data);
if (i >= 0)
{
while (i < (int)pseq->size)
{
pseq->arr[i - 1] = pseq->arr[i];
i++;
}
pseq->size--;
printf("ɾ\n");
return;
}
else
{
printf("ûҵԪ");
return;
}
}
void RemoveAll(pseqlist pseq, DataType data)//ɾλõdata
{
assert(pseq);
int pos = Find(pseq, data);
while (-1 != pos)
{
Erase(pseq, pos);
pos++;
}
}//ʱ临Ӷȸ
void RemoveAll1(pseqlist pseq, DataType data)
{
assert(pseq);
int count = 0;
int i = 0;
DataType *ptmp = (DataType *)malloc(sizeof(DataType)*(pseq->size));//һοռ,ptmpָοռ
for (i = 0; i < pseq->size; i++)
{
if (pseq->arr[i] != data)
{
ptmp[count++] = pseq->arr[i];//dataݵķѾٺõĿռ
}
}//ռ临Ӷȸ
}
void RemoveAll2(pseqlist pseq, DataType data)
{
int i = 0;
int count = 0;
for (i = 0; i < pseq->size; i++)
{
if (pseq->arr[i] != data)
{
pseq->arr[i - count] = pseq->arr[i];
}
else
{
count++;
}//¼ɾdataĸ
}
pseq->size -= count;
}
//ʱ临ӶO(n),ռ临ӶO(1
int Empty(pseqlist pseq)//п
{
assert(pseq);
if (pseq->size == 0)
return true;
else
return false;
}
void Bubblesort(pseqlist pseq)//ð
{
assert(pseq);
int i = 0;
int j = 0;
int flag = 0;
for (i = 0; i < pseq->size; i++)
{
int flag = 0;
for (j = 0; j < pseq->size - i; i++)
{
if (pseq->arr[j]>pseq->arr[j + 1])
{
DataType tmp = pseq->arr[j];
pseq->arr[j] = pseq->arr[j + 1];
pseq->arr[j + 1] = tmp;
}
flag = 1;
}
}
}
void SelectSort(pseqlist pseq)//ѡ
{
assert(pseq);
int i = 0;
int j = 0;
int max = 0;
for (i = 0; i < pseq->size - 1; i++)//sizeΪ10ֻñȽ9ˣ08
{
max = 0;
for (j = 1; j < pseq->size - i; j++)//iΪ8ʱڲֻҪȽ1Σ
{
if (pseq->arr[j]>pseq->arr[max])
max = j;
}
}
//max,Ϊ0 9 1 2 3 4 5 6 7 8
DataType tmp = pseq->arr[max];//
pseq->arr[max] = pseq->arr[pseq->size - i - 1];//һ˽һֵmax
pseq->arr[pseq->size - i - 1] = tmp;//9ŵ
}
|
C
|
#include "holberton.h"
int prime_num(int i, int num);
int _abs(int x);
/**
* is_prime_number - calculates a prime
* @n: an integer
* Return: 1 if is prime
* otherwise 0
*/
int is_prime_number(int n)
{
int i = 2;
if (n <= 1)
return (0);
else if (n == 2)
return (1);
else
return (prime_num(i, n));
}
/**
* prime_num - look for a prime
* @i: integer
* @num: number to test
* Return: an integer
*/
int prime_num(int i, int num)
{
if (num % i == 0)
return (0);
else if ((i * i) > _abs(num))
return (1);
else
return (prime_num(i + 1, num));
}
/**
* _abs - absolute value.
* @x: number
* Return: an integer
*/
int _abs(int x)
{
if (x >= 0)
return (x);
else
return ((-1) * x);
}
|
C
|
//Rafaella Silva Almeida
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int menor(int *vet, int dim, int menorvalor){
if(dim == 0)
return menorvalor;
else if(vet[dim-1]<menorvalor)
return menor(vet, dim-1, vet[dim-1]);
else
return menor(vet, dim-1, menorvalor);
}
int main(){
srand(time(NULL));
int i, dim;
do{
scanf("%d", &dim);
}while(dim <= 0);
int vet[dim];
printf("Elementos no vetor: ");
for(i = 0; i < dim; i++){
vet[i] = rand()%100;
printf("%d ", vet[i]);
}
printf("\nMenor valor no vetor: %d", menor(vet, dim-1, vet[dim-1]));
return 0;
}
|
C
|
#include <stdio.h>
#define COUNT 15
int main(void) {
int num[COUNT], tmp;
int i, j;
FILE *fp;
//ファイルを開く(読み込みモード)処理
if ((fp=fopen("01number.txt", "r"))==NULL) {
printf("File is not found.\n");
return 1;
}
i = 0;
while(fscanf(fp, "%d", &tmp) != EOF){
num[i]=tmp; //配列(num[i])に格納
i++;
}
for(j=0;j<i;j++) {
printf("%d ", num[j]);
}
printf("\n");
fclose(fp);
return 0;
}
|
C
|
#include<stdio.h>
/**int main()
{
int a,b;
a=3+2,b=a,12;
printf("%d %d\n\n",a,b);
}**/
int main()
{
int a,b;
a=(3+2,b=a,12);
printf("%d %d",a,b);
}
/// when bracket is taken right most number will consider as final value
/**
a=(5,b=garb,12);
a=12;
**/
|
C
|
//Author: Shawn Esseltine 400145888
//Problem 1
//Import all required libraries
#include <stdio.h>
#include <math.h>
void circleCircumference(double); // function prototype
void circleArea(double); // function prototype
void sphereVolume(double); // function prototype
int main(void){
// Initialize array of 3 pointers to functions that each take a
// double argument and return void
void (*f[3])(double) = {circleCircumference, circleArea, sphereVolume};
printf("%s", "Enter a number between 0 and 2, 3 to end: ");
size_t choice; // variable to hold users choice
scanf("%zu", &choice);
// process user's choice
while(choice >= 0 && choice < 3){
printf("%s", "Enter a radius: ");
double radius; // variable to hold user enter radius
scanf("%lf", &radius);
// invoke function at location choice in array f and pass
// radius as an argument
(*f[choice])(radius);
printf("%s", "Enter a number between 0 and 2, 3 to end: ");
scanf("%zu", &choice);
}
}
void circleCircumference(double r){
// print the circumference of circle radius r
printf("%s%lf%s%lf\n", "Circumference of circle radius ", r, " = ", 2 * M_PI * r);
}
void circleArea(double r){
// print the area of circle radius r
printf("%s%lf%s%lf\n", "Area of circle radius ", r, " = ", M_PI * pow(r,2));
}
void sphereVolume(double r){
// print the volume of sphere radius r
printf("%s%lf%s%lf\n", "Volume of sphere radius ", r, " = ", (4.0/3.0) * M_PI * pow(r,3));
}
|
C
|
/* Our Header File that contains the our library of function prototypes */
/********************************/
/* Encryption/Decipher - RSA */
/********************************/
/*Check whether a given number is prime or not*/
int checkPrime(int n);
/*to find gcd*/
int gcd(int a, int h);
void Encrypt();
void Decrypt();
int getPublicKeys();
int getPrivateKeys();
/************************************************/
/* Compression/Decompress - Run Length Encoding */
/************************************************/
/* To compress the given input */
void Compress ();
/* To reverse/decompress */
void Decompress ();
/********************************/
/* Data Structure - Linked List (JAMES BUSTAMANTE -12900926) */
/********************************/
struct node
{ /* Setup struct for linked list */
char *title;
char *username;
char *password;
struct node *next;
};
/*typedef struct node *head;*/
/* the read linked list section of the menu where you can search or sort or view */
void print_search_sort(struct node **node);
/* Insert log in details into the linked list */
void insertDetails(struct node **, char *title, char *username, char *password);
struct node ** insert(struct node **node, char *title, char *username, char *password);
/* Insert log in details into the linked list */
struct node ** insertDetailsInput(struct node **);
/* Print out the entire linked list */
void print(struct node *node);
/* Save the contents of a linked list*/
void saveLinkedList(struct node *node);
/* Load the contents into linked list*/
void LoadContentsInLinkedList(struct node **node);
/* Reads input from the user to add to linked list */
char *readWord();
/* used to ask whether user wants add to the linked list or not */
struct node ** tempMenu(struct node **node);
/* menu select for the user */
void selection(struct node **node);
void insertDetailsDECRYPT(struct node **node, int *title, char *username, char *password);
/* This function prints the initial menu with all instructions on how to use */
void print_menu(void);
/********************************/
/* Sorting - Merge Sort */
/********************************/
/* Determines whether the first node is ahead of the second, alphabetically by node title. */
/* Returns 1 if 'node1' is first, -1 if 'node2' is first, 0 if nodes have the same title. */
int alphabeticalOrderTitle(struct node* node1, struct node* node2);
/* Merge Sort main function, recursively calls itself to sort a provided linkedlist. */
void mergeSortMainTitle(struct node** headReference);
/* Merge Sort split function, finds the mid point of an array and splits it into two. */
void mergeSortSplitTitle(struct node* list, struct node** frontPtr, struct node** backPtr);
/* Merge Sort merge function, orders elements alphabetically and merges them. */
struct node* mergeSortMergeTitle(struct node* node1, struct node* node2);
int alphabeticalOrderUsername(struct node* node1, struct node* node2);
/* Merge Sort main function, recursively calls itself to sort a provided linkedlist. */
void mergeSortMainUsername(struct node** headReference);
/* Merge Sort split function, finds the mid point of an array and splits it into two. */
void mergeSortSplitUsername(struct node* list, struct node** frontPtr, struct node** backPtr);
/* Merge Sort merge function, orders elements alphabetically and merges them. */
struct node* mergeSortMergeUsername(struct node* node1, struct node* node2);
/* FUNCTION PROTOTYPES */
void searchTitle (struct node** headReference, char* target);
void searchUsername (struct node** headReference, char* target);
void binarySearchTitle(struct node **headRef, char* target);
void binarySearchUsername(struct node **headRef, char* target);
/*************************************/
/* Reading & Writing to files - Menu */
/*************************************/
void printMenu(void);
|
C
|
#include "mesg.h"
ssize_t mesg_send(int fd, MESG *mesg){
return write(fd, mesg, MESGHDRSIZE + mesg->mesg_len);
}
ssize_t mesg_recv(int fd, MESG *mesg){
size_t len;
ssize_t n;
// read head count, get true len.
if((n = read(fd, mesg, MESGHDRSIZE)) == 0){
return 0;
}else if(n != MESGHDRSIZE){
printf("mesg have error.");
return 0;
}
if((len = mesg->mesg_len) != 0){
if((n = read(fd, mesg->mesg_data, len)) != len){
printf("mesg count is error.");
return 0;
}
}
return len;
}
|
C
|
/*********************************************************
* SCANF & PRINTF *
* Author: Reez Patel *
* Source: Ex: 3.15 (P-81) = ANSI-C *
**********************************************************/
#include <stdio.h>
int main()
{
int a,b,c,max,min;
printf("Enter 3 Numbers: ");
scanf("%d %d %d",&a,&b,&c);
max = a>b?a:b;
min = a<b?a:b;
max = max>c?max:c;
min = min<c?min:c;
printf( "Sum \t %d \n"
"Avg.\t %.2f \n"
"MAX \t %d \n"
"MIN \t %d \n",
a+b+c,(a+b+c)/(float)3,max,min);
return 0;
}
|
C
|
/* ---------------------------------------------------------------------------
* IDs
* --------------------------------------------------------------------------- */
#define ui_push_unique_index_id(s,idx) ui_push_id(s, murmur_hash(FILE_LINE, strlen(FILE_LINE),(uintptr_t)idx))
#define ui_push_unique_id(s) ui_push_unique_index_id(s,0)
#define ui_push_ptr_id(s, p) ui_push_id(s, (uintptr_t)p)
static ui_bool
ui_id_eq(const struct ui_id *a, const struct ui_id *b)
{
return a->lo == b->lo && a->hi == b->hi;
}
static struct ui_id
ui_gen_id(struct ui_id_stk *s)
{
struct ui_id id;
struct ui_id *entry;
assert(s && s->top);
entry = &s->stk[s->top-1];
id.lo = ++entry->lo;
id.hi = entry->hi;
return id;
}
static void
ui_set_id(struct ui_id_stk *s, const struct ui_id *id)
{
assert(s->top > 0);
s->stk[s->top-1] = *id;
}
static void
ui_push_id(struct ui_id_stk *s, uintptr_t id)
{
struct ui_id *entry = 0;
assert(s->top < UI_ID_STACK_DEPTH);
entry = s->stk + s->top++;
entry->hi = id;
entry->lo = 0;
}
static void
ui_pop_id(struct ui_id_stk *s)
{
assert(s->top > 1);
s->top--;
}
static struct ui_id
ui_peek_id(struct ui_id_stk *s)
{
assert(s);
assert(s->top);
return s->stk[s->top-1];
}
/* ---------------------------------------------------------------------------
* Box
* --------------------------------------------------------------------------- */
static void
ui_anchor_left_right(struct ui_box *b, int left, int right)
{
assert(b);
if (!b) return;
b->left = left;
b->right = right;
b->width = b->right - b->left;
b->center_x = b->left + (b->width >> 1);
}
static void
ui_anchor_left_width(struct ui_box *b, int left, int width)
{
assert(b);
if (!b) return;
b->left = left;
b->width = width;
b->right = b->left + width;
b->center_x = b->left + (b->width >> 1);
}
static void
ui_anchor_right_width(struct ui_box *b, int right, int width)
{
assert(b);
if (!b) return;
b->right = right;
b->width = width;
b->left = b->right - width;
b->center_x = b->left + (b->width >> 1);
}
static void
ui_anchor_center_width(struct ui_box *b, int center, int width)
{
assert(b);
if (!b) return;
b->width = width;
b->center_x = center;
b->right = b->center_x + (width >> 1);
b->left = b->right - width;
}
static void
ui_anchor_left_center(struct ui_box *b, int left, int center)
{
assert(b);
if (!b) return;
b->left = left;
b->center_x = center;
b->width = (center - left) << 1;
b->right = b->left + b->width;
}
static void
ui_anchor_right_center(struct ui_box *b, int right, int center)
{
assert(b);
if (!b) return;
b->right = right;
b->center_x = center;
b->width = (right - center) << 1;
b->left = b->right - b->width;
}
static void
ui_anchor_top_bottom(struct ui_box *b, int top, int bottom)
{
assert(b);
if (!b) return;
b->top = top;
b->bottom = bottom;
b->height = bottom - top;
b->center_y = top + (b->height >> 1);
}
static void
ui_anchor_top_height(struct ui_box *b, int top, int height)
{
assert(b);
if (!b) return;
b->top = top;
b->height = height;
b->bottom = top + height;
b->center_y = b->top + (b->height >> 1);
}
static void
ui_anchor_bottom_height(struct ui_box *b, int bottom, int height)
{
assert(b);
if (!b) return;
b->height = height;
b->bottom = bottom;
b->top = bottom - height;
b->center_y = b->top + (b->height >> 1);
}
static void
ui_anchor_center_height(struct ui_box *b, int center, int height)
{
assert(b);
if (!b) return;
b->height = height;
b->center_y = center;
b->top = center - (b->height >> 1);
b->bottom = b->top + b->height;
}
static void
ui_anchor_top_center(struct ui_box *b, int top, int center)
{
assert(b);
if (!b) return;
b->top = top;
b->center_y = center;
b->height = (center - top) << 1;
b->bottom = b->top + b->height;
}
static void
ui_anchor_bottom_center(struct ui_box *b, int bottom, int center)
{
assert(b);
if (!b) return;
b->center_y = center;
b->bottom = bottom;
b->height = (bottom - center) << 1;
b->top = b->bottom - b->height;
}
static void
ui_anchor_xywh(struct ui_box *b, int left, int top, int width, int height)
{
ui_anchor_left_width(b, left, width);
ui_anchor_top_height(b, top, height);
}
/* ---------------------------------------------------------------------------
* Panel
* --------------------------------------------------------------------------- */
static void
ui_panel_hot(struct ui_ctx *ctx, struct ui_panel *p)
{
assert(ctx && p);
const struct sys *s = ctx->sys;
const int mx = s->mouse.pos.x;
const int my = s->mouse.pos.y;
const struct ui_box *b = &p->box;
if (p->unselectable) return;
if (p->parent && !p->parent->hovered) return;
if (!inbox(mx,my, b->left,b->top,b->width,b->height))
return;
p->hovered = ui_true;
ctx->hot = p->id;
}
static void
ui_panel_input(struct ui_ctx *ctx, struct ui_panel *p)
{
assert(ctx && p);
assert(ctx->sys);
struct sys *sys = ctx->sys;
if (ctx->disabled) return;
if (ui_id_eq(&p->id, &ctx->active) &&
ui_id_eq(&ctx->active, &ctx->origin))
p->down = ui_true;
if (ui_id_eq(&p->id, &ctx->active)) {
if (sys->keys[SYS_KEY_NEXT_WIDGET].pressed) {
sys->keys[SYS_KEY_NEXT_WIDGET].pressed = ui_false;
ctx->activate_next = ui_true;
}
if (sys->keys[SYS_KEY_ACTIVATE].pressed) {
p->clicked = ui_true;
p->down = ui_true;
}
}
if (sys->mouse.d.x || sys->mouse.d.y) {
if (ui_id_eq(&p->id, &ctx->active) &&
ui_id_eq(&ctx->active, &ctx->origin))
p->dragged = ui_true;
}
if (p->hovered) {
p->doubled = sys->mouse.left.doubled;
p->down = sys->mouse.left.down;
p->pressed = sys->mouse.left.pressed;
p->released = sys->mouse.left.released;
if (p->pressed)
p->drag_begin = ui_true;
if (p->released) {
if (ui_id_eq(&ctx->hot, &ctx->active))
p->clicked = ui_true;
if (ui_id_eq(&p->id, &ctx->origin))
p->drag_end = ui_true;
}
}
}
static enum ui_state
ui_panel_state(const struct ui_ctx *ctx, const struct ui_panel *p)
{
enum ui_state state;
if (ctx->disabled)
state = UI_DISABLED;
else if (ui_id_eq(&p->id, &ctx->active) && !ctx->activate_next)
state = UI_FOCUSED;
else state = UI_NORMAL;
return state;
}
static void
ui_panel_begin(struct ui_ctx *ctx, struct ui_panel *p, struct ui_panel *parent)
{
assert(ctx && p);
p->parent = parent;
p->id = ui_gen_id(&ctx->ids);
if (ctx->activate_next && p->focusable && !ctx->disabled) {
ctx->activate_next = ui_false;
ctx->active = p->id;
}
ui_panel_hot(ctx, p);
ui_panel_input(ctx, p);
p->state = ui_panel_state(ctx, p);
}
static void
ui_panel_end(struct ui_panel *p)
{
struct ui_panel *root = p->parent;
if (!root) return;
root->max_x = max(root->max_x, p->box.right);
root->max_y = max(root->max_y, p->box.bottom);
}
static void
ui_panel(struct ui_ctx *ctx, struct ui_panel *p, struct ui_panel *parent)
{
ui_panel_begin(ctx, p, parent);
ui_panel_end(p);
}
/* ---------------------------------------------------------------------------
* Popup
* --------------------------------------------------------------------------- */
static ui_bool
ui_popup_is_active(struct ui_ctx *ctx, struct ui_id id)
{
const struct ui_popup *p = &ctx->popup;
if (!p->active || !ui_id_eq(&ctx->popup.id, &id))
return ui_false;
return ui_true;
}
static void
ui_popup_activate(struct ui_ctx *ctx, struct ui_id id,
enum ui_popup_type type)
{
struct sys *sys = ctx->sys;
struct ui_popup *p = &ctx->popup;
memset(p, 0, sizeof(*p));
ctx->active = (struct ui_id){.hi = id.lo};
ctx->origin = ctx->active;
ctx->hot = ctx->active;
p->surf = sys->popup;
p->active = ui_true;
p->seq = ctx->seq;
p->type = type;
p->id = id;
sys_clear(sys);
}
static void
ui_popup_deactivate(struct ui_ctx *ctx, struct ui_id id)
{
struct sys *sys = ctx->sys;
struct ui_popup *p = &ctx->popup;
if (!p->active || !ui_id_eq(&p->id, &id))
return;
ctx->active = ctx->root.id;
ctx->origin = ctx->root.id;
ctx->hot = ctx->root.id;
p->seq = ctx->seq - 1;
p->active = ui_false;
sys_clear(sys);
}
static ui_bool
ui_popup_resize(struct ui_ctx *ctx, struct ui_panel *pan,
struct ui_id id, int w, int h)
{
struct sys *sys = ctx->sys;
struct ui_popup *p = &ctx->popup;
if (!ui_popup_is_active(ctx, id))
return ui_false;
p->w = w, p->h = h;
memset(pan, 0, sizeof(*pan));
ui_anchor_left_width(&pan->box, p->x, w);
ui_anchor_top_height(&pan->box, p->y, h);
ui_panel_begin(ctx, pan, 0);
switch (p->type) {
default: assert(0); break;
case UI_POPUP_BLOCKING: break;
case UI_POPUP_NON_BLOCKING: {
if (sys->mouse.left.pressed && !pan->pressed) {
ui_popup_deactivate(ctx, id);
return ui_false;
}
} break;}
/* setup drawing */
xs_identity(p->surf);
xs_resize(p->surf, w, h);
xs_scissor(p->surf, 0, 0, w, h);
xs_clear(p->surf, xc_rgb(255,255,255));
xs_line_style(p->surf, XLINE_SOLID);
xs_line_thickness(p->surf, 1);
xs_color_background(p->surf, xc_rgb(212,208,200));
xs_color(p->surf, xc_rgb(0,0,0));
xs_font(p->surf, res_font(ctx->res));
xs_stroke_rect(p->surf, 0, 0, w, h, 0);
xs_translate(p->surf, -p->x, -p->y);
return ui_true;
}
static void
ui_popup_end(struct ui_ctx *ctx, struct ui_panel *pan)
{
struct sys *sys = ctx->sys;
struct ui_popup *p = &ctx->popup;
ui_pop_id(&ctx->ids);
ctx->clip = p->clip;
sys->surf = p->old;
}
static ui_bool
ui_popup_begin(struct ui_ctx *ctx, struct ui_panel *pan,
struct ui_id id, int x, int y, int w, int h)
{
struct sys *sys = ctx->sys;
struct ui_popup *p = &ctx->popup;
if (!ui_popup_is_active(ctx, id))
return ui_false;
/* close non-blocking popups by escape key */
if (sys->keys[SYS_KEY_ESC].pressed) {
switch (p->type) {
default: assert(0); break;
case UI_POPUP_BLOCKING: break;
case UI_POPUP_NON_BLOCKING: {
ui_popup_deactivate(ctx, id);
return ui_false;
} break;}
}
p->id = id;
p->seq = ctx->seq;
p->x = x, p->y = y;
p->clip = ctx->clip;
p->old = sys->surf;
sys->surf = p->surf;
ui_push_id(&ctx->ids, id.lo);
xs_scissor(p->surf, 0, 0, w, h);
ctx->clip = xr_xywh(p->x, p->y, w, h);
if (!ui_popup_resize(ctx, pan, id, w, h)) {
ui_popup_end(ctx, pan);
return ui_false;
} return ui_true;
}
/* ---------------------------------------------------------------------------
* Context
* --------------------------------------------------------------------------- */
static struct ui_panel*
ui_begin(struct ui_ctx *ctx)
{
struct sys *sys = ctx->sys;
res_activate_font(ctx->res, FONT_DEFAULT);
ctx->layout = UI_LAYOUT_STRETCH;
ctx->disabled = ui_false;
ctx->seq += 1;
/* reset IDs */
ctx->ids.top = 1;
ctx->ids.stk[0].lo = 0;
ctx->ids.stk[0].hi = 0;
/* reset surface */
xs_identity(sys->surf);
xs_line_style(sys->surf, XLINE_SOLID);
xs_line_thickness(sys->surf, 1);
xs_color_background(sys->surf, xc_rgb(212,208,200));
xs_color(sys->surf, xc_rgb(0,0,0));
xs_font(sys->surf, res_font(ctx->res));
/* tree */
struct ui_panel *pan = &ctx->root;
pan->id = ui_gen_id(&ctx->ids);
ctx->root.parent = 0;
/* input */
if (sys->mouse.left.pressed) {
ctx->origin = ctx->hot;
ctx->active = ctx->origin;
}
if (sys->mouse.left.released)
ctx->origin = ctx->root.id;
/* root */
ui_anchor_left_width(&pan->box, 0, sys->win.w);
ui_anchor_top_height(&pan->box, 0, sys->win.h);
if (ctx->popup.active == ui_false)
ui_panel_hot(ctx, pan);
else pan->hovered = ui_false;
xs_scissor(sys->surf, 0, 0, sys->win.w, sys->win.h);
ctx->clip = xr_xywh(0, 0, sys->win.w, sys->win.h);
return &ctx->root;
}
static void
ui_end(struct ui_ctx *ctx)
{
struct ui_popup *p = &ctx->popup;
if (p->active == 0 || p->seq != ctx->seq) {
p->active = ui_false;
return;
}
const struct sys *sys = ctx->sys;
xs_blit(sys->surf, p->surf, p->x, p->y, 0,0, p->w, p->h);
}
static void
ui_scissor(struct ui_ctx *ctx, int x, int y, int w, int h)
{
const struct sys *sys = ctx->sys;
struct xsurface *surf = sys->surf;
xs_scissor(surf, x, y, w, h);
ctx->clip = surf->clip;
}
static struct scissor_rect
ui_clip_begin(struct ui_ctx *ctx, int x, int y, int w, int h)
{
struct scissor_rect p = ctx->clip;
ctx->clip.x = max(p.x, x);
ctx->clip.y = max(p.y, y);
ctx->clip.w = min(p.x + p.w, x + w) - ctx->clip.x;
ctx->clip.h = min(p.y + p.h, y + h) - ctx->clip.y;
ctx->clip.w = max(0, ctx->clip.w);
ctx->clip.h = max(0, ctx->clip.h);
ui_scissor(ctx, ctx->clip.x, ctx->clip.y, ctx->clip.w, ctx->clip.h);
return p;
}
static void
ui_clip_end(struct ui_ctx *ctx, struct scissor_rect clip)
{
ui_scissor(ctx, clip.x, clip.y, clip.w, clip.h);
}
static enum ui_layout
ui_layout(struct ui_ctx *ctx, enum ui_layout layout)
{
enum ui_layout old = ctx->layout;
ctx->layout = layout;
return old;
}
static void
ui_enable(struct ui_ctx *ctx)
{
ctx->disabled = ui_false;
}
static void
ui_disable(struct ui_ctx *ctx)
{
ctx->disabled = ui_true;
}
/* ---------------------------------------------------------------------------
* Util:Text
* --------------------------------------------------------------------------- */
struct ui_text_bounds {
int len, width;
const char *end;
};
static struct ui_text_bounds
ui_text_fit(int space, const struct xfont *xf, const char *txt, const char *end)
{
struct ui_text_bounds res = {0};
if (!space) return res;
struct utf8_iter it;
for (utf8_begin(&it, txt, end); utf8_next(&it);) {
struct extend ext = xf_text_measure(xf, txt, it.rune_end);
if (ext.w > space)
return res;
res.end = it.rune_end;
res.len += it.rune_len;
res.width = ext.w;
} return res;
}
struct ui_text_window_bounds {int off, len, width;};
static struct ui_text_window_bounds
ui_text_fit_window(int space, const struct xfont *xf, const char *buf, int len)
{
struct ui_text_window_bounds res = {0};
res.len = len, res.off = 0;
if (!space) return res;
restart:; struct utf8_iter it;
for (utf8_begin(&it, buf + res.off, buf + len); utf8_next(&it);) {
struct extend ext = xf_text_measure(xf, buf + res.off, it.rune_end);
if (ext.w > space) {
res.off = cast(int, it.rune_begin - (buf + res.off));
res.len = len - res.off;
goto restart;
} res.width = ext.w;
} return res;
}
/* ---------------------------------------------------------------------------
* Util:Record
* --------------------------------------------------------------------------- */
static void
ui_record_store(struct ui_record *rec, struct ui_ctx *ctx, struct ui_panel *pan)
{
rec->ctx = ctx;
rec->pan = pan;
rec->max_x = pan->max_x;
rec->max_y = pan->max_y;
rec->id_begin = ui_peek_id(&ctx->ids);
}
static void
ui_record_restore(struct ui_record *rec)
{
struct ui_ctx *ctx = rec->ctx;
struct ui_panel *pan = rec->pan;
ui_set_id(&ctx->ids, &rec->id_begin);
pan->max_x = rec->max_x;
pan->max_y = rec->max_y;
}
/* ---------------------------------------------------------------------------
* Util: Drag
* --------------------------------------------------------------------------- */
static float
ui_drag_ratio(struct ui_ctx *ctx, enum ui_orientation orient, int cur, int min, float total)
{
int off = 0;
const struct sys *sys = ctx->sys;
switch (orient) {
default: assert(0); break;
case UI_VERTICAL: off = cur + sys->mouse.d.y; break;
case UI_HORIZONTAL: off = cur + sys->mouse.d.x; break;}
float ratio = (float)(off - min)/total;
return clamp(0, ratio, 1.0f);
return 0;
}
/* ---------------------------------------------------------------------------
* Button
* --------------------------------------------------------------------------- */
static void
ui_button_begin(struct ui_ctx *ctx, struct ui_panel *btn, struct ui_panel *parent)
{
ui_panel_begin(ctx, btn, parent); {
const struct sys *sys = ctx->sys;
const struct ui_box *b = &btn->box;
xs_line_thickness(sys->surf, 1);
xs_line_style(sys->surf, XLINE_SOLID);
xs_color(sys->surf, xc_rgb(212,208,200));
xs_fill_rect(sys->surf, b->left, b->top, b->width, b->height, 0);
switch (btn->state) {
default: assert(0); break;
case UI_DISABLED:
case UI_FOCUSED:
case UI_NORMAL: {
if (!btn->down) {
xs_color(sys->surf, xc_rgb(255,255,255));
xs_stroke_line(sys->surf, b->left, b->top, b->right, b->top);
xs_stroke_line(sys->surf, b->left, b->top, b->left, b->bottom);
xs_color(sys->surf, xc_rgb(64,64,64));
xs_stroke_line(sys->surf, b->right-1, b->top, b->right-1, b->bottom);
xs_stroke_line(sys->surf, b->left, b->bottom-1, b->right, b->bottom-1);
xs_color(sys->surf, xc_rgb(128,128,128));
xs_stroke_line(sys->surf, b->right-2, b->top+1, b->right-2, b->bottom-1);
xs_stroke_line(sys->surf, b->left+1,b->bottom-2, b->right-2, b->bottom-2);
} else {
xs_color(sys->surf, xc_rgb(0,0,0));
xs_stroke_rect(sys->surf, b->left, b->top, b->width-1, b->height-1, 0);
xs_color(sys->surf, xc_rgb(135,136,143));
xs_stroke_rect(sys->surf, b->left+1, b->top+1, b->width-3, b->height-3, 0);
}
if (btn->state == UI_FOCUSED) {
xs_line_thickness(sys->surf, 1);
xs_line_style(sys->surf, XLINE_DASHED);
xs_color(sys->surf, xc_rgb(0,0,0));
xs_stroke_rect(sys->surf, b->left+3, b->top+3, b->width-7, b->height-7, 0);
}
} break;}
}
}
static void
ui_button_end(struct ui_ctx *ctx, struct ui_panel *btn)
{
ui_panel_end(btn);
}
/* ---------------------------------------------------------------------------
* Icon
* --------------------------------------------------------------------------- */
static void
ui_icon(struct ui_ctx *ctx, struct ui_panel *pan, struct ui_panel *parent)
{
ui_panel_begin(ctx, pan, parent); {
const struct sys *sys = ctx->sys;
const struct xsurface *xs = res_icon(ctx->res);
if (xs) xs_blit(sys->surf, xs, pan->box.left, pan->box.top, 0,0, xs->w, xs->h);
} ui_panel_end(pan);
}
/* ---------------------------------------------------------------------------
* Label
* --------------------------------------------------------------------------- */
static void
ui_label(struct ui_ctx *ctx, struct ui_panel *pan, struct ui_panel *parent,
const char *str_begin, const char *str_end)
{
ui_panel_begin(ctx, pan, parent); {
const struct sys *sys = ctx->sys;
const struct xfont *xf = res_font(ctx->res);
const char *end = !str_end ? str_begin + strlen(str_begin): str_end;
struct ui_text_bounds bounds = ui_text_fit(pan->box.width, xf, str_begin, end);
switch (pan->state) {
default: assert(0); break;
case UI_DISABLED: {
xs_color(sys->surf, xc_rgb(255,255,255));
xs_draw_text(sys->surf, pan->box.left+1, pan->box.top+1,
pan->box.width, pan->box.height, str_begin, bounds.len);
xs_color(sys->surf, xc_rgb(153,153,153));
xs_draw_text(sys->surf, pan->box.left, pan->box.top,
pan->box.width, pan->box.height, str_begin, bounds.len);
} break;
case UI_FOCUSED:
case UI_NORMAL: {
xs_draw_text(sys->surf, pan->box.left, pan->box.top,
pan->box.width, pan->box.height, str_begin, bounds.len);
} break;}
} ui_panel_end(pan);
}
static void
ui_labelf(struct ui_ctx *ctx, struct ui_panel *pan, struct ui_panel *parent,
const char* fmt, ...)
{
int n = 0;
char buf[2*1024];
va_list args;
va_start(args, fmt);
n = vsnprintf(buf, cntof(buf), fmt, args);
va_end(args);
if (n >= cntof(buf)) return;
ui_label(ctx, pan, parent, buf, 0);
}
/* ---------------------------------------------------------------------------
* Time
* --------------------------------------------------------------------------- */
static void
ui_time(struct ui_ctx *ctx, struct ui_panel *pan, struct ui_panel *parent,
const char *fmt, struct tm* time)
{
char buf[2*1024];
strftime(buf, cntof(buf), fmt, time);
ui_label(ctx, pan, parent, buf, 0);
}
/* ---------------------------------------------------------------------------
* Check
* --------------------------------------------------------------------------- */
#define UI_CHECKBOX_SIZE 13
static ui_bool
ui_check(struct ui_ctx *ctx, struct ui_panel *pan, struct ui_panel *parent,
ui_bool checked)
{
ui_panel_begin(ctx, pan, parent); {
const struct sys *sys = ctx->sys;
const struct ui_box *b = &pan->box;
if (pan->clicked)
checked = !checked;
/* draw background */
xs_line_style(sys->surf, XLINE_SOLID);
xs_line_thickness(sys->surf, 1);
if (pan->state == UI_DISABLED)
xs_color(sys->surf, xc_rgb(212,208,200));
else xs_color(sys->surf, xc_rgb(255,255,255));
xs_fill_rect(sys->surf, b->left, b->top, b->width, b->height, 0);
xs_color(sys->surf, xc_rgb(128,128,128));
xs_stroke_line(sys->surf, b->left, b->top, b->left, b->bottom-1);
xs_stroke_line(sys->surf, b->left, b->top, b->right-1, b->top);
xs_color(sys->surf, xc_rgb(64,64,64));
xs_stroke_line(sys->surf, b->left+1, b->top+1, b->right-2, b->top+1);
xs_stroke_line(sys->surf, b->left+1, b->top+1, b->left+1, b->bottom-2);
if (pan->state == UI_DISABLED)
xs_color(sys->surf, xc_rgb(255,255,255));
else xs_color(sys->surf, xc_rgb(212,208,200));
xs_stroke_line(sys->surf, b->right-2, b->top+1, b->right-2, b->bottom-1);
xs_stroke_line(sys->surf, b->left+1, b->bottom-2, b->right-2, b->bottom-2);
if (checked) {
/* draw cursor */
const struct xsurface *icon = 0;
if (pan->state == UI_DISABLED)
icon = res_img(ctx->res, IMG_CHECK_DISABLED);
else icon = res_img(ctx->res, IMG_CHECK);
xs_blit(sys->surf, icon, b->left + 3, b->top + 3, 0,0, icon->w, icon->h);
}
}
ui_panel_end(pan);
return checked;
}
/* ---------------------------------------------------------------------------
* Checkbox
* --------------------------------------------------------------------------- */
static int
ui_checkbox(struct ui_ctx *ctx, struct ui_panel *pan,
struct ui_panel *parent, int *checked, const char *txt, const char *end)
{
const int old = *checked;
pan->focusable = ui_true;
ui_panel_begin(ctx, pan, parent); {
static const int pad = 4;
if (pan->clicked)
*checked = !*checked;
/* Check */
struct ui_panel chk = {0};
{struct ui_panel slot = {0};
slot.unselectable = ui_true;
ui_anchor_left_right(&slot.box, pan->box.left + pad, pan->box.right - pad);
ui_anchor_top_height(&slot.box, pan->box.top, pan->box.height);
ui_panel_begin(ctx, &slot, pan); {
const struct xfont *xf = res_font(ctx->res);
ui_anchor_left_width(&chk.box, slot.box.left, xf->h);
ui_anchor_center_height(&chk.box, slot.box.center_y, xf->h);
ui_check(ctx, &chk, &slot, *checked);
} ui_panel_end(&slot);}
/* Label */
{struct ui_panel slot = {0};
ui_anchor_left_right(&slot.box, chk.box.right + pad, pan->box.right - pad);
ui_anchor_top_height(&slot.box, pan->box.top, pan->box.height);
ui_panel_begin(ctx, &slot, pan); {
const struct sys *sys = ctx->sys;
xs_color(sys->surf, xc_rgb(0,0,0));
/* draw label */
struct ui_panel lbl = {0};
struct extend ext = xf_text_measure(res_font(ctx->res), txt, end);
ui_anchor_left_width(&lbl.box, slot.box.left, ext.w);
ui_anchor_center_height(&lbl.box, slot.box.center_y, ext.h);
ui_label(ctx, &lbl, &slot, txt, end);
/* layouting */
switch (ctx->layout) {
case UI_LAYOUT_STRETCH: default: break;
case UI_LAYOUT_FIT: {
int box_right = min(lbl.box.right + pad, pan->box.right + pad);
ui_anchor_left_right(&pan->box, pan->box.left, box_right);
} break;}
} ui_panel_end(&slot);}
/* draw focus selection */
if (pan->state == UI_FOCUSED) {
struct sys *sys = ctx->sys;
struct ui_box *b = &pan->box;
xs_line_thickness(sys->surf, 1);
xs_line_style(sys->surf, XLINE_DASHED);
xs_color(sys->surf, xc_rgb(0,0,0));
xs_stroke_rect(sys->surf, b->left+3, b->top+3, b->width-7, b->height-7, 0);
}
} ui_panel_end(pan);
return old != *checked;
}
/* ---------------------------------------------------------------------------
* Group Box
* --------------------------------------------------------------------------- */
static void
ui_group_box_begin(struct ui_ctx *ctx, struct ui_group_box *grp,
struct ui_panel *pan, struct ui_panel *parent,
const char *txt, const char *end)
{
/* setup group panel */
const struct sys *sys = ctx->sys;
static const int padx = 4, pady = 4;
static const int title_pad = 8;
grp->pan = pan;
ui_anchor_left_right(&pan->box, parent->box.left + padx, parent->box.right - padx);
ui_anchor_top_bottom(&pan->box, parent->box.top, parent->box.bottom - pady);
/* measure and draw group title */
end = !end ? txt + strlen(txt): end;
struct extend ext = xf_text_measure(res_font(ctx->res), txt, end);
pan->box.top += (ext.h >> 1);
grp->title_right = title_pad + ext.w + 1;
grp->title_pad = title_pad;
xs_color(sys->surf, xc_rgb(0,0,0));
xs_draw_text(sys->surf, pan->box.left + title_pad, pan->box.top,
ext.w, ext.h, txt, cast(int,end-txt));
ui_anchor_top_bottom(&pan->box, parent->box.top + ext.h, parent->box.bottom - pady);
ui_panel_begin(ctx, pan, parent);
}
static void
ui_group_box_end(struct ui_ctx *ctx, struct ui_group_box *grp)
{
static const int padx = 4, pady = 4;
const struct sys *sys = ctx->sys;
struct ui_panel *pan = grp->pan;
if (grp->flow & UI_GROUP_BOX_FIT_WIDTH)
ui_anchor_left_width(&pan->box, pan->box.left, min(pan->box.width, pan->max_x - pan->box.left + padx));
if (grp->flow & UI_GROUP_BOX_FIT_HEIGHT)
ui_anchor_top_height(&pan->box, pan->box.top, min(pan->box.height, pan->max_y - pan->box.top + pady));
ui_panel_end(pan);
grp->title_right += pan->box.left;
grp->top += pan->box.top;
grp->title_pad += pan->box.left-1;
/* draw group border */
xs_line_thickness(sys->surf, 1);
xs_line_style(sys->surf, XLINE_SOLID);
const struct ui_box *b = &pan->box;
xs_color(sys->surf, xc_rgb(128,128,128));
xs_stroke_line(sys->surf, b->left, grp->top, grp->title_pad, grp->top);
xs_stroke_line(sys->surf, grp->title_right, grp->top, b->right, grp->top);
xs_stroke_line(sys->surf, b->left, grp->top, b->left, b->bottom-1);
xs_stroke_line(sys->surf, b->left, b->bottom-2, b->right-1, b->bottom-2);
xs_stroke_line(sys->surf, b->right-2, grp->top, b->right-2, b->bottom-1);
xs_color(sys->surf, xc_rgb(255,255,255));
xs_stroke_line(sys->surf, b->left+1, grp->top+1, grp->title_pad, grp->top+1);
xs_stroke_line(sys->surf, grp->title_right, grp->top+1, b->right-2, grp->top+1);
xs_stroke_line(sys->surf, b->left+1, grp->top+1, b->left+1, b->bottom-2);
xs_stroke_line(sys->surf, b->left, b->bottom-1, b->right, b->bottom-1);
xs_stroke_line(sys->surf, b->right-1, grp->top, b->right-1, b->bottom-1);
}
/* ---------------------------------------------------------------------------
* Radio-Group
* --------------------------------------------------------------------------- */
static int
ui_radio_symbol(struct ui_ctx *ctx, struct ui_panel *pan,
struct ui_panel *parent, const char *txt, const char *end, int active)
{
ui_panel_begin(ctx, pan, parent); {
const struct sys *sys = ctx->sys;
if (pan->clicked) active = !active;
/* draw background */
if (pan->state == UI_DISABLED)
xs_color(sys->surf, xc_rgb(212,208,200));
else xs_color(sys->surf, xc_rgb(255,255,255));
xs_fill_circle(sys->surf, pan->box.left, pan->box.top,
pan->box.width, pan->box.height);
xs_line_thickness(sys->surf, 2);
xs_line_style(sys->surf, XLINE_SOLID);
xs_color(sys->surf, xc_rgb(128,128,128));
xs_stroke_circle(sys->surf, pan->box.left, pan->box.top,
pan->box.width, pan->box.height);
/* draw cursor */
if (active) {
xs_color(sys->surf, xc_rgb(0,0,0));
xs_fill_circle(sys->surf, pan->box.left+3, pan->box.top+3,
pan->box.width-6, pan->box.height-6);
}
} ui_panel_end(pan);
return active;
}
static int
ui_radio(struct ui_ctx *ctx, struct ui_panel *pan,
struct ui_panel *parent, const char *txt, const char *end, int active)
{
const int old = active;
pan->focusable = ui_true;
ui_panel_begin(ctx, pan, parent); {
static const int pad = 4;
const struct xfont *xf = res_font(ctx->res);
if (pan->clicked) active = !active;
/* radio symbol */
struct ui_panel sym = {0};
sym.unselectable = ui_true;
ui_anchor_left_width(&sym.box, pan->box.left + pad, xf->h);
ui_anchor_center_height(&sym.box, pan->box.center_y, xf->h);
ui_radio_symbol(ctx, &sym, pan, txt, end, active);
/* Label */
{struct ui_panel slot = {0};
ui_anchor_left_right(&slot.box, sym.box.right + pad, pan->box.right - pad);
ui_anchor_top_height(&slot.box, pan->box.top, pan->box.height);
ui_panel_begin(ctx, &slot, pan); {
const struct sys *sys = ctx->sys;
xs_color(sys->surf, xc_rgb(0,0,0));
/* draw label */
struct ui_panel lbl = {0};
struct extend ext = xf_text_measure(res_font(ctx->res), txt, end);
ui_anchor_left_width(&lbl.box, slot.box.left, ext.w);
ui_anchor_center_height(&lbl.box, slot.box.center_y, ext.h);
ui_label(ctx, &lbl, &slot, txt, end);
/* layouting */
switch (ctx->layout) {
case UI_LAYOUT_STRETCH: default: break;
case UI_LAYOUT_FIT: {
int box_right = min(lbl.box.right + pad, pan->box.right);
ui_anchor_left_right(&pan->box, pan->box.left, box_right);
} break;}
} ui_panel_end(&slot);}
/* draw focus */
if (pan->state == UI_FOCUSED) {
struct sys *sys = ctx->sys;
struct ui_box *b = &pan->box;
xs_line_thickness(sys->surf, 1);
xs_line_style(sys->surf, XLINE_DASHED);
xs_color(sys->surf, xc_rgb(0,0,0));
xs_stroke_rect(sys->surf, b->left+3, b->top+3, b->width-7, b->height-7, 0);
}
} ui_panel_end(pan);
return old != active && active;
}
static int
ui_radio_group(struct ui_ctx *ctx,
struct ui_radio_group *grp, struct ui_panel *parent)
{
if (grp->state == UI_CONSISTENT) return 0;
grp->state = UI_CONSISTENT;
ui_record_store(&grp->record, ctx, parent);
grp->idx = 0;
return 1;
}
static void
ui_radio_button(struct ui_ctx *ctx, struct ui_radio_group *grp,
struct ui_panel *pan, struct ui_panel *parent, const char *txt, const char *end)
{
if (ui_radio(ctx, pan, parent, txt, end, grp->selected == grp->idx)) {
grp->state = UI_INCONSISTENT;
grp->selected = grp->idx;
grp->toggled = ui_true;
} grp->idx++;
}
/* ---------------------------------------------------------------------------
* Button-Label
* --------------------------------------------------------------------------- */
static void
ui_button_label(struct ui_ctx *ctx, struct ui_panel *btn, struct ui_panel *parent,
const char *txt, const char *end)
{
/* Layouting */
static const int pad = 4;
struct extend ext = xf_text_measure(res_font(ctx->res), txt, end);
switch (ctx->layout) {
case UI_LAYOUT_STRETCH: default: break;
case UI_LAYOUT_FIT: {
int btn_width = min(btn->box.width, ext.w + 2 * pad);
ui_anchor_left_width(&btn->box, btn->box.left, btn_width);
} break;}
/* Widget */
btn->focusable = ui_true;
ui_button_begin(ctx, btn, parent); {
struct ui_panel lbl = {0};
lbl.unselectable = ui_true;
ui_anchor_center_width(&lbl.box, btn->box.center_x, ext.w);
ui_anchor_center_height(&lbl.box, btn->box.center_y, ext.h);
ui_label(ctx, &lbl, btn, txt, end);
} ui_button_end(ctx, btn);
}
/* ---------------------------------------------------------------------------
* Button-Icon
* --------------------------------------------------------------------------- */
static void
ui_button_icon(struct ui_ctx *ctx, struct ui_panel *btn, struct ui_panel *parent)
{
btn->focusable = ui_true;
ui_button_begin(ctx, btn, parent); {
const struct xsurface *xs = res_icon(ctx->res);
struct ui_panel ico = {0};
ico.unselectable = ui_true;
ui_anchor_center_width(&ico.box, btn->box.center_x, xs->w);
ui_anchor_center_height(&ico.box, btn->box.center_y, xs->h);
ui_icon(ctx, &ico, btn);
} ui_button_end(ctx, btn);
}
/* ---------------------------------------------------------------------------
* Icon-Label
* --------------------------------------------------------------------------- */
static void
ui_icon_label(struct ui_ctx *ctx, struct ui_panel *pan,
struct ui_panel *parent, const char *txt, const char *end)
{
ui_panel_begin(ctx, pan, parent); {
const struct sys *sys = ctx->sys;
const struct xsurface *xs = res_icon(ctx->res);
struct extend ext = xf_text_measure(res_font(ctx->res), txt, end);
/* icon */
struct ui_panel ico = {0};
ico.unselectable = ui_true;
ui_anchor_left_width(&ico.box, pan->box.left + 4, xs->w);
ui_anchor_center_height(&ico.box, pan->box.center_y, xs->h);
ui_icon(ctx, &ico, pan);
/* label */
struct ui_panel lbl = {0};
lbl.unselectable = ui_true;
xs_color(sys->surf, xc_rgb(0,0,0));
ui_anchor_left_width(&lbl.box, ico.box.right + 4, ext.w);
ui_anchor_center_height(&lbl.box, pan->box.center_y, ext.h);
ui_label(ctx, &lbl, parent, txt, end);
} ui_panel_end(pan);
}
/* ---------------------------------------------------------------------------
* Button-Icon-Label
* --------------------------------------------------------------------------- */
static void
ui_button_icon_label(struct ui_ctx *ctx, struct ui_panel *btn,
struct ui_panel *parent, const char *txt, const char *end)
{
static const int pad = 4;
static const int spacing = 4;
const struct xsurface *xs = res_icon(ctx->res);
struct extend ext = xf_text_measure(res_font(ctx->res), txt, end);
/* Layouting */
switch (ctx->layout) {
case UI_LAYOUT_STRETCH: default: break;
case UI_LAYOUT_FIT: {
const int btn_w = min(btn->box.width, ext.w + 2*pad + spacing + xs->w);
const int btn_h = max(btn->box.height, ext.h + 2*pad);
ui_anchor_left_width(&btn->box, btn->box.left, btn_w);
ui_anchor_top_height(&btn->box, btn->box.top, btn_h);
} break;}
/* Widget */
btn->focusable = ui_true;
ui_button_begin(ctx, btn, parent); {
struct ui_panel pan = {.box = btn->box};
pan.unselectable = ui_true;
ui_icon_label(ctx, &pan, btn, txt, end);
} ui_button_end(ctx, btn);
}
/* ---------------------------------------------------------------------------
* Desktop-Icon
* --------------------------------------------------------------------------- */
static void
ui_desktop_icon(struct ui_ctx *ctx, struct ui_panel *pan,
struct ui_panel *parent, const char *txt, const char *end)
{
ui_panel_begin(ctx, pan, parent); {
const struct xsurface *xs = res_icon(ctx->res);
static const int pad = 4;
/* Icon */
struct ui_panel ico = {0};
ico.unselectable = ui_true;
ui_anchor_center_width(&ico.box, pan->box.center_x, xs->w);
ui_anchor_top_height(&ico.box, pan->box.top + pad, xs->h);
ui_icon(ctx, &ico, pan);
/* align */
struct ui_panel slot = {0};
slot.unselectable = ui_true;
ui_anchor_top_bottom(&slot.box, ico.box.bottom + 2, pan->box.bottom-4);
ui_anchor_left_right(&slot.box, pan->box.left, pan->box.right);
ui_panel_begin(ctx, &slot, pan); {
struct ui_text_bounds b;
struct extend ext = xf_text_measure(res_font(ctx->res), txt, end);
b = ui_text_fit(slot.box.width - pad, res_font(ctx->res), txt, end);
/* Label */
struct ui_panel lbl = {0};
lbl.unselectable = ui_true;
ui_anchor_center_width(&lbl.box, slot.box.center_x, b.width);
ui_anchor_center_height(&lbl.box, slot.box.center_y, ext.h);
xs_color(ctx->sys->surf, xc_rgb(0,0,0));
ui_label(ctx, &lbl, &slot, txt, end);
} ui_panel_end(&slot);
} ui_panel_end(pan);
}
/* ---------------------------------------------------------------------------
* Tool-Button
* --------------------------------------------------------------------------- */
static void
ui_tool_button(struct ui_ctx *ctx, struct ui_panel *pan,
struct ui_panel *parent, const char *txt, const char *end)
{
pan->focusable = ui_true;
ui_button_begin(ctx, pan, parent); {
struct ui_panel ico = {.box = pan->box};
ico.unselectable = ui_true;
ui_desktop_icon(ctx, &ico, pan, txt, end);
} ui_button_end(ctx, pan);
}
/* ---------------------------------------------------------------------------
* Scroll
* --------------------------------------------------------------------------- */
static void
ui_scroll_cursor_layout(struct ui_panel *cur, struct ui_scroll *s)
{
/* Calculate cursor bounds */
struct ui_box *p = &s->pan.box;
int x = floori((float)p->left + (s->off_x / s->total_x) * (float)p->width);
int y = floori((float)p->top + (s->off_y / s->total_y) * (float)p->height);
int w = ceili((s->size_x / s->total_x) * (float)p->width);
int h = ceili((s->size_y / s->total_y) * (float)p->height);
ui_anchor_left_width(&cur->box, x, w);
ui_anchor_top_height(&cur->box, y, h);
}
static void
ui_scroll_cursor(struct ui_ctx *ctx, struct ui_scroll *s,
struct ui_panel *pan, struct ui_panel *parent)
{
ui_panel_begin(ctx, pan, &s->pan); {
const struct sys *sys = ctx->sys;
/* Input */
if (pan->dragged) {
const struct ui_box *b = &parent->box;
const int scrl_x = (pan->box.left + sys->mouse.d.x) - b->left;
const int scrl_y = (pan->box.top + sys->mouse.d.y) - b->top;
const float scrl_rx = cast(float, scrl_x) / cast(float, b->width);
const float scrl_ry = cast(float, scrl_y) / cast(float, b->height);
/* validate and update cursor position */
s->off_x = clamp(0, scrl_rx * s->total_x, s->total_x - s->size_x);
s->off_y = clamp(0, scrl_ry * s->total_y, s->total_y - s->size_y);
ui_scroll_cursor_layout(pan, s);
s->scrolled = ui_true;
}
/* Draw */
const struct ui_box *c = &pan->box;
switch (pan->state) {
default: assert(0); break;
case UI_DISABLED: break;
case UI_FOCUSED:
case UI_NORMAL: {
if (!pan->down) {
xs_line_style(sys->surf, XLINE_SOLID);
xs_color(sys->surf, xc_rgb(212,208,200));
xs_fill_rect(sys->surf, c->left, c->top, c->width, c->height, 0);
xs_color(sys->surf, xc_rgb(212,208,200));
xs_stroke_line(sys->surf, c->left, c->top, c->right-1, c->top);
xs_stroke_line(sys->surf, c->left, c->top, c->left, c->bottom-1);
xs_color(sys->surf, xc_rgb(255,255,255));
xs_stroke_line(sys->surf, c->left+1, c->top+1, c->right-2, c->top+1);
xs_stroke_line(sys->surf, c->left+1, c->top+1, c->left+1, c->bottom-2);
xs_color(sys->surf, xc_rgb(64,64,64));
xs_stroke_line(sys->surf, c->right-1, c->top, c->right-1, c->bottom);
xs_stroke_line(sys->surf, c->left, c->bottom-1, c->right, c->bottom-1);
xs_color(sys->surf, xc_rgb(128,128,128));
xs_stroke_line(sys->surf, c->right-2, c->top+1, c->right-2, c->bottom-1);
xs_stroke_line(sys->surf, c->left+1,c->bottom-2, c->right-2, c->bottom-2);
} else {
xs_color(sys->surf, xc_rgb(212,208,200));
xs_fill_rect(sys->surf, c->left+1, c->top+1, c->width-3, c->height-3, 0);
xs_line_style(sys->surf, XLINE_SOLID);
xs_color(sys->surf, xc_rgb(0,0,0));
xs_stroke_rect(sys->surf, c->left, c->top, c->width-1, c->height-1, 0);
}
} break;}
} ui_panel_end(pan);
}
static void
ui_scroll(struct ui_ctx *ctx, struct ui_scroll *s, struct ui_panel *parent)
{
/* Validate scroll values */
struct ui_panel *p = &s->pan;
ui_panel_begin(ctx, p, parent); {
s->size_x = max(s->size_x, 1);
s->size_y = max(s->size_y, 1);
s->total_x = max(s->total_x, 1);
s->total_y = max(s->total_y, 1);
s->total_x = max(s->total_x, s->size_x);
s->total_y = max(s->total_y, s->size_y);
s->off_x = clamp(0, s->off_x, s->total_x - s->size_x);
s->off_y = clamp(0, s->off_y, s->total_y - s->size_y);
/* draw background */
const struct ui_box *b = &p->box;
switch (p->state) {
default: assert(0); break;
case UI_DISABLED: break;
case UI_FOCUSED:
case UI_NORMAL: {
const struct sys *sys = ctx->sys;
xs_color(sys->surf, xc_rgb(255,255,255));
xs_fill_rect(sys->surf, b->left, b->top, b->width, b->height, 0);
xs_line_thickness(sys->surf, 1);
xs_color(sys->surf, xc_rgb(212,208,200));
xs_line_style(sys->surf, XLINE_DASHED);
for (int i = 0; i < b->width; i++)
xs_stroke_line(sys->surf, b->left+i, b->top+(i&1), b->left+i, b->bottom);
} break;}
/* Cursor */
struct ui_panel cur = {0};
ui_scroll_cursor_layout(&cur, s);
ui_scroll_cursor(ctx, s, &cur, p);
} ui_panel_end(p);
}
/* ---------------------------------------------------------------------------
* Arrow
* --------------------------------------------------------------------------- */
enum ui_direction {
UI_NORTH = 0x01,
UI_WEST = 0x02,
UI_SOUTH = 0x04,
UI_EAST = 0x08
};
enum ui_dir {
UI_DIR_HORIZONTAL = UI_NORTH|UI_SOUTH,
UI_DIR_VERTICAL = UI_WEST|UI_EAST,
};
static void
ui_arrow(struct ui_ctx *ctx, struct ui_panel *pan, struct ui_panel *parent,
enum ui_direction orient)
{
ui_panel_begin(ctx, pan, parent); {
const struct sys *sys = ctx->sys;
if (pan->state == UI_DISABLED)
xs_color(sys->surf, xc_rgb(152,148,140));
else xs_color(sys->surf, xc_rgb(0,0,0));
xs_line_thickness(sys->surf, 1);
xs_line_style(sys->surf, XLINE_SOLID);
switch (orient) {
default: assert(0); break;
case UI_NORTH: {
for (int i = 0; i < pan->box.height; ++i)
xs_stroke_line(sys->surf, pan->box.left+1+i, pan->box.bottom-1-i,
pan->box.left+1+pan->box.width-i, pan->box.bottom-1-i);
} break;
case UI_WEST: {
for (int i = 0; i < pan->box.width; ++i)
xs_stroke_line(sys->surf, pan->box.right-2-i, pan->box.top-1+i,
pan->box.right-2-i, pan->box.top+pan->box.height+1-i);
} break;
case UI_SOUTH: {
for (int i = 0; i < pan->box.height; ++i)
xs_stroke_line(sys->surf, pan->box.left+1+i, pan->box.top+i,
pan->box.left+1+pan->box.width-i, pan->box.top+i);
} break;
case UI_EAST: {
for (int i = 0; i < pan->box.width; ++i)
xs_stroke_line(sys->surf, pan->box.left+2+i, pan->box.top-1+i,
pan->box.left+2+i, pan->box.top+pan->box.height+1-i);
} break;}
} ui_panel_end(pan);
}
/* ---------------------------------------------------------------------------
* Scrollbar
* --------------------------------------------------------------------------- */
static void
ui_scrollbar_button(struct ui_ctx *ctx, struct ui_panel *btn,
struct ui_panel *parent, enum ui_direction orient)
{
ui_button_begin(ctx, btn, parent); {
const struct sys *sys = ctx->sys;
xs_color_background(sys->surf, xc_rgb(0,0,0));
xs_line_thickness(sys->surf, 1);
xs_line_style(sys->surf, XLINE_SOLID);
/* draw button */
struct ui_box *b = &btn->box;
xs_color(sys->surf, xc_rgb(212,208,200));
xs_fill_rect(sys->surf, b->left, b->top, b->width, b->height, 0);
xs_stroke_line(sys->surf, b->left, b->top, b->right-1, b->top);
xs_stroke_line(sys->surf, b->left, b->top, b->left, b->bottom-1);
xs_color(sys->surf, xc_rgb(255,255,255));
xs_stroke_line(sys->surf, b->left+1, b->top+1, b->right-2, b->top+1);
xs_stroke_line(sys->surf, b->left+1, b->top+1, b->left+1, b->bottom-2);
xs_color(sys->surf, xc_rgb(64,64,64));
xs_stroke_line(sys->surf, b->right-1, b->top, b->right-1, b->bottom);
xs_stroke_line(sys->surf, b->left, b->bottom-1, b->right, b->bottom-1);
xs_color(sys->surf, xc_rgb(128,128,128));
xs_stroke_line(sys->surf, b->right-2, b->top+1, b->right-2, b->bottom-1);
xs_stroke_line(sys->surf, b->left+1,b->bottom-2, b->right-2, b->bottom-2);
/* arrow icon */
static const int arrow_w = 5;
static const int arrow_h = 3;
struct ui_panel sym = {0};
ui_anchor_center_width(&sym.box, btn->box.center_x, arrow_w);
ui_anchor_center_height(&sym.box, btn->box.center_y, arrow_h);
ui_arrow(ctx, &sym, btn, orient);
} ui_button_end(ctx, btn);
}
static void
ui_scrollbarh(struct ui_ctx *ctx, struct ui_scrollbar *s,
struct ui_panel *pan, struct ui_panel *parent)
{
ui_panel_begin(ctx, pan, parent);{
s->scrolled = ui_false;
/* decrement button */
struct ui_panel btn_dec = {0};
ui_anchor_left_width(&btn_dec.box, pan->box.left, pan->box.height);
ui_anchor_bottom_height(&btn_dec.box, pan->box.bottom, pan->box.height);
ui_scrollbar_button(ctx, &btn_dec, pan, UI_WEST);
if (btn_dec.pressed) {
s->off -= s->size * 0.1f;
s->scrolled = ui_true;
sys_clear(ctx->sys);
}
/* increment button */
struct ui_panel btn_inc = {0};
ui_anchor_right_width(&btn_inc.box, pan->box.right, pan->box.height);
ui_anchor_bottom_height(&btn_inc.box, pan->box.bottom, pan->box.height);
ui_scrollbar_button(ctx, &btn_inc, pan, UI_EAST);
if (btn_inc.pressed) {
s->off += s->size * 0.1f;
s->scrolled = ui_true;
sys_clear(ctx->sys);
}
/* scroll */
struct ui_scroll scrl;
scrl.total_x = s->total;
scrl.total_y = scrl.size_y = 1;
scrl.size_x = s->size;
scrl.off_x = s->off;
scrl.off_y = 0;
ui_anchor_bottom_height(&scrl.pan.box, pan->box.bottom, pan->box.height);
ui_anchor_left_right(&scrl.pan.box, btn_dec.box.right, btn_inc.box.left);
ui_scroll(ctx, &scrl, pan);
s->scrolled = s->scrolled || scrl.scrolled;
s->off = scrl.off_x;
} ui_panel_end(pan);
}
static void
ui_scrollbarv(struct ui_ctx *ctx, struct ui_scrollbar *s,
struct ui_panel *pan, struct ui_panel *parent)
{
ui_panel_begin(ctx, pan, parent); {
s->scrolled = ui_false;
/* decrement button */
struct ui_panel btn_dec = {0};
ui_anchor_left_width(&btn_dec.box, pan->box.left, pan->box.width);
ui_anchor_top_height(&btn_dec.box, pan->box.top, pan->box.width);
ui_scrollbar_button(ctx, &btn_dec, pan, UI_NORTH);
if (btn_dec.pressed) {
s->off -= s->size * 0.1f;
s->scrolled = ui_true;
sys_clear(ctx->sys);
}
/* increment button */
struct ui_panel btn_inc = {0};
ui_anchor_left_width(&btn_inc.box, pan->box.left, pan->box.width);
ui_anchor_bottom_height(&btn_inc.box, pan->box.bottom, pan->box.width);
ui_scrollbar_button(ctx, &btn_inc, pan, UI_SOUTH);
if (btn_inc.pressed) {
s->off += s->size * 0.1f;
s->scrolled = ui_true;
sys_clear(ctx->sys);
}
/* scroll */
struct ui_scroll scrl = {0};
scrl.total_x = scrl.size_x = 1;
scrl.total_y = s->total;
scrl.size_y = s->size;
scrl.off_y = s->off;
scrl.off_x = 0;
ui_anchor_top_bottom(&scrl.pan.box, btn_dec.box.bottom, btn_inc.box.top);
ui_anchor_left_right(&scrl.pan.box, pan->box.left, pan->box.right);
ui_scroll(ctx, &scrl, pan);
s->scrolled = s->scrolled || scrl.scrolled;
s->off = scrl.off_y;
} ui_panel_end(pan);
}
/* ---------------------------------------------------------------------------
* Text Box
* --------------------------------------------------------------------------- */
static int ui_rune_is_default(long c) {return ui_true;}
static int ui_rune_is_binary(long c) {return c == '0' || c == '1';}
static int
ui_rune_is_numeric(long c)
{
return (c >= '0' && c <= '9') || (c == '+') || (c == '-');
}
static int
ui_rune_is_real(long c)
{
return (c >= '0' && c <= '9') || (c == '+') || (c == '-') || (c == '.');
}
static int
ui_rune_is_hex(long c)
{
return ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
}
static void
ui_edit_box_input_text(struct ui_ctx *ctx, struct ui_edit_box *box,
ui_filter_f rune_filter, char *buf, int *len, int max)
{
struct utf8_iter it;
struct sys *sys = ctx->sys;
for (utf8_begin(&it, sys->text, sys->text + sys->text_len); utf8_next(&it);) {
if (rune_filter(it.rune) == ui_false) continue;
if (*len + it.rune_len >= max) break;
memcpy(buf + *len, it.rune_begin, cast(size_t, it.rune_len));
*len += it.rune_len;
} sys->text_len = 0;
}
static void
ui_edit_box_input(struct ui_ctx *ctx, struct ui_edit_box *box,
char *buf, int *len, int max)
{
struct sys *sys = ctx->sys;
if (sys->text_len) {
static const ui_filter_f filter[UI_EDIT_BOX_MAX] = {
ui_rune_is_default,
ui_rune_is_numeric,
ui_rune_is_real,
ui_rune_is_hex,
ui_rune_is_binary
};
if (box->filter)
ui_edit_box_input_text(ctx, box, box->filter, buf, len, max);
else ui_edit_box_input_text(ctx, box, filter[box->type], buf, len, max);
} else if (sys->keys[SYS_KEY_BACKSPACE].pressed)
*len = max(0, *len - 1);
}
static void
ui_edit_field(struct ui_ctx *ctx, struct ui_edit_box *box,
struct ui_panel *pan, struct ui_panel *parent,
char *buf, int *len, int max)
{
ui_panel_begin(ctx, pan, parent); {
const struct sys *sys = ctx->sys;
/* text input */
if (pan->pressed) ctx->active = pan->id;
const int active = ui_id_eq(&pan->id, &ctx->active);
if (active) ui_edit_box_input(ctx, box, buf, len, max);
/* calculate text measurements */
struct ui_text_window_bounds bounds = {0};
const struct xfont *xf = res_font(ctx->res);
struct extend ext = xf_text_measure(xf, buf, buf+*len);
if (ext.w <= pan->box.width) {
bounds.width = ext.w;
bounds.len = *len;
bounds.off = 0;
} else bounds = ui_text_fit_window(pan->box.width, xf, buf, *len);
/* store temporary state */
const unsigned fg = xs_color_foreground(sys->surf, xc_rgb(0,0,0));
const unsigned bg = xs_color_background(sys->surf, xc_rgb(255,255,255));
/* draw text */
struct ui_panel lbl = {0};
ui_anchor_left_right(&lbl.box, pan->box.left, pan->box.right);
ui_anchor_center_height(&lbl.box, pan->box.center_y, ext.h);
ui_label(ctx, &lbl, pan, buf + bounds.off, buf + *len);
if (active) {
/* draw cursor */
xs_color(sys->surf, xc_rgb(0,0,0));
xs_stroke_line(sys->surf, pan->box.left + bounds.width,
pan->box.top+1, pan->box.left + bounds.width,
pan->box.bottom);
}
/* draw focus */
if (pan->state == UI_FOCUSED) {
xs_line_style(sys->surf, XLINE_DASHED);
xs_color(sys->surf, xc_rgb(0,0,0));
xs_stroke_rect(sys->surf, pan->box.left-1, pan->box.top+1,
pan->box.width, pan->box.height-1, 0);
}
/* restore state */
xs_color_foreground(sys->surf, fg);
xs_color_background(sys->surf, bg);
}
ui_panel_end(pan);
}
static void
ui_edit_box(struct ui_ctx *ctx, struct ui_edit_box *box, struct ui_panel *pan,
struct ui_panel *parent, char *buf, int *len, int max)
{
const struct sys *sys = ctx->sys;
ui_panel_begin(ctx, pan, parent); {
xs_line_style(sys->surf, XLINE_SOLID);
xs_line_thickness(sys->surf, 1);
/* draw background */
if (pan->state == UI_DISABLED)
xs_color(sys->surf, xc_rgb(212,208,200));
else xs_color(sys->surf, xc_rgb(255,255,255));
xs_fill_rect(sys->surf, pan->box.left, pan->box.top, pan->box.width, pan->box.height, 0);
xs_color(sys->surf, xc_rgb(128,128,128));
xs_stroke_line(sys->surf, pan->box.left, pan->box.top, pan->box.right, pan->box.top);
xs_stroke_line(sys->surf, pan->box.left, pan->box.top, pan->box.left, pan->box.bottom);
xs_color(sys->surf, xc_rgb(212,208,200));
xs_stroke_line(sys->surf, pan->box.left+1, pan->box.bottom-1, pan->box.right, pan->box.bottom-1);
xs_stroke_line(sys->surf, pan->box.right-1, pan->box.top+1, pan->box.right-1, pan->box.bottom-1);
xs_color(sys->surf, xc_rgb(0,0,0));
xs_stroke_line(sys->surf, pan->box.left+1, pan->box.top+1, pan->box.right-1, pan->box.top+1);
xs_stroke_line(sys->surf, pan->box.left+1, pan->box.top+1, pan->box.left+1, pan->box.bottom-1);
xs_color(sys->surf, xc_rgb(255,255,255));
xs_stroke_line(sys->surf, pan->box.left, pan->box.bottom, pan->box.right+1, pan->box.bottom);
xs_stroke_line(sys->surf, pan->box.right, pan->box.top, pan->box.right, pan->box.bottom);
/* content */
const int padx = 4, pady = 2;
struct ui_panel content = {0};
content.focusable = ui_true;
ui_anchor_left_right(&content.box, pan->box.left + padx, pan->box.right - padx);
ui_anchor_top_bottom(&content.box, pan->box.top + pady, pan->box.bottom - pady);
ui_edit_field(ctx, box, &content, pan, buf, len, max);
}
ui_panel_end(pan);
}
/* ---------------------------------------------------------------------------
* Spinner
* --------------------------------------------------------------------------- */
#define UI_SPINNER_SIZE 16
static void
ui_spinner_button(struct ui_ctx *ctx, struct ui_panel *pan,
struct ui_panel *parent, enum ui_direction dir)
{
ui_panel_begin(ctx, pan, parent); {
const struct sys *sys = ctx->sys;
struct ui_box *box = &pan->box;
xs_line_thickness(sys->surf, 1);
xs_line_style(sys->surf, XLINE_SOLID);
/* draw background */
xs_color(sys->surf, xc_rgb(212,208,200));
xs_fill_rect(sys->surf, box->left, box->top, box->width, box->height, 0);
xs_stroke_line(sys->surf, box->left, box->top, box->right-1, box->top);
xs_stroke_line(sys->surf, box->left, box->top, box->left, box->bottom-1);
xs_color(sys->surf, xc_rgb(255,255,255));
xs_stroke_line(sys->surf, box->left+1, box->top+1, box->right-2, box->top+1);
xs_stroke_line(sys->surf, box->left+1, box->top+1, box->left+1, box->bottom-2);
xs_color(sys->surf, xc_rgb(64,64,64));
xs_stroke_line(sys->surf, box->right-1, box->top, box->right-1, box->bottom);
xs_stroke_line(sys->surf, box->left, box->bottom-1, box->right, box->bottom-1);
xs_color(sys->surf, xc_rgb(128,128,128));
xs_stroke_line(sys->surf, box->right-2, box->top+1, box->right-2, box->bottom-1);
xs_stroke_line(sys->surf, box->left+1,box->bottom-2, box->right-2, box->bottom-2);
/* draw arrow */
static const int arrow_w = 3;
static const int arrow_h = 2;
struct ui_panel arrow = {0};
arrow.unselectable = ui_true;
ui_anchor_center_width(&arrow.box, pan->box.center_x, arrow_w);
ui_anchor_center_height(&arrow.box, pan->box.center_y, arrow_h);
ui_arrow(ctx, &arrow, pan, dir);
} ui_panel_end(pan);
}
static int
ui_spin_control(struct ui_ctx *ctx, struct ui_spinner *spin,
struct ui_panel *pan, struct ui_panel *parent, int *n)
{
const int old_n = *n;
ui_panel_begin(ctx, pan, parent); {
const struct sys *sys = ctx->sys;
/* increment button */
struct ui_panel inc_btn = {0};
ui_anchor_left_right(&inc_btn.box, pan->box.left, pan->box.right);
ui_anchor_top_height(&inc_btn.box, pan->box.top, pan->box.height >> 1);
ui_spinner_button(ctx, &inc_btn, pan, UI_NORTH);
if (inc_btn.pressed) {
*n = min(*n + spin->inc, spin->max);
} else if (inc_btn.dragged) {
*n += max(sys->mouse.d.x, 0);
*n += max(-sys->mouse.d.y, 0);
*n = min(*n, spin->max);
}
/* decrement button */
struct ui_panel dec_btn = {0};
ui_anchor_left_right(&dec_btn.box, pan->box.left, pan->box.right);
ui_anchor_top_height(&dec_btn.box, inc_btn.box.bottom, pan->box.height >> 1);
ui_spinner_button(ctx, &dec_btn, pan, UI_SOUTH);
if (dec_btn.pressed) {
*n = max(*n - spin->inc, spin->min);
} else if (dec_btn.dragged) {
*n += min(sys->mouse.d.x, 0);
*n += min(-sys->mouse.d.y, 0);
*n = max(*n, spin->min);
}
} ui_panel_end(pan);
return *n != old_n;
}
static int
ui_spinner(struct ui_ctx *ctx, struct ui_spinner *spin,
struct ui_panel *pan, struct ui_panel *parent, int n)
{
ui_bool loop = ui_false;
struct ui_record record = {0};
if ((spin->min == spin->max) && !spin->min) {
spin->min = INT_MIN + 1;
spin->max = INT_MAX - 1;
spin->inc = 1;
}
ui_record_store(&record, ctx, pan);
do {loop = ui_false;
ui_record_restore(&record);
ui_panel_begin(ctx, pan, parent); {
const struct sys *sys = ctx->sys;
/* draw background */
if (pan->state == UI_DISABLED)
xs_color(sys->surf, xc_rgb(212,208,200));
else xs_color(sys->surf, xc_rgb(255,255,255));
xs_fill_rect(sys->surf, pan->box.left, pan->box.top, pan->box.width, pan->box.height, 0);
xs_line_thickness(sys->surf, 1);
xs_line_style(sys->surf, XLINE_SOLID);
xs_color(sys->surf, xc_rgb(128,128,128));
xs_stroke_line(sys->surf, pan->box.left, pan->box.top, pan->box.right, pan->box.top);
xs_stroke_line(sys->surf, pan->box.left, pan->box.top, pan->box.left, pan->box.bottom);
xs_color(sys->surf, xc_rgb(212,208,200));
xs_stroke_line(sys->surf, pan->box.left+1, pan->box.bottom-1, pan->box.right, pan->box.bottom-1);
xs_stroke_line(sys->surf, pan->box.right-1, pan->box.top+1, pan->box.right-1, pan->box.bottom-1);
xs_color(sys->surf, xc_rgb(0,0,0));
xs_stroke_line(sys->surf, pan->box.left+1, pan->box.top+1, pan->box.right-1, pan->box.top+1);
xs_stroke_line(sys->surf, pan->box.left+1, pan->box.top+1, pan->box.left+1, pan->box.bottom-1);
xs_color(sys->surf, xc_rgb(255,255,255));
xs_stroke_line(sys->surf, pan->box.left, pan->box.bottom, pan->box.right+1, pan->box.bottom);
xs_stroke_line(sys->surf, pan->box.right, pan->box.top, pan->box.right, pan->box.bottom);
/* convert int to string */
char buf[64] = "0";
snprintf(buf, sizeof(buf), "%d", n);
int len = cast(int, strlen(buf));
/* Edit field */
const int padx = 4;
struct ui_panel edit_box = {0};
struct ui_edit_box edit = {.type = UI_EDIT_BOX_INT};
edit_box.focusable = ui_true;
ui_anchor_left_right(&edit_box.box, pan->box.left + padx, pan->box.right - UI_SPINNER_SIZE - padx);
ui_anchor_top_bottom(&edit_box.box, pan->box.top + 2, pan->box.bottom - 2);
ui_edit_field(ctx, &edit, &edit_box, pan, buf, &len, szof(buf));
/* convert string to int */
if (len == 0)
buf[0] = '0', buf[1] = 0;
else buf[len] = 0;
n = atoi(buf);
/* draw focus */
if (edit_box.state == UI_FOCUSED) {
if (sys->keys[SYS_KEY_UP].pressed ||
sys->keys[SYS_KEY_RIGHT].pressed)
n = min(n + spin->inc, spin->max);
if (sys->keys[SYS_KEY_DOWN].pressed ||
sys->keys[SYS_KEY_LEFT].pressed)
n = max(n - spin->inc, spin->min);
}
/* Buttons */
struct ui_panel btn = {0};
ui_anchor_right_width(&btn.box, pan->box.right, UI_SPINNER_SIZE);
ui_anchor_top_bottom(&btn.box, pan->box.top+2, pan->box.bottom-1);
if (ui_spin_control(ctx, spin, &btn, pan, &n)) {
sys_clear(ctx->sys);
loop = ui_true;
}
} ui_panel_end(pan);
} while (loop);
return n;
}
/* ---------------------------------------------------------------------------
* Area
* --------------------------------------------------------------------------- */
#define UI_SCROLLBAR_SIZE 13
static int
ui_area_begin(struct ui_ctx *ctx, struct ui_area *d,
struct ui_panel *pan, struct ui_panel *parent)
{
const struct sys *sys = ctx->sys;
if (d->state == UI_CONSISTENT) return 0;
else d->state = UI_CONSISTENT;
ui_record_store(&d->record, ctx, parent);
/* calculate clip area */
ui_anchor_left_right(&pan->box, parent->box.left + d->padx, parent->box.right - d->padx);
ui_anchor_top_bottom(&pan->box, parent->box.top + d->pady, parent->box.bottom - d->pady);
ui_panel_begin(ctx, pan, parent);
/* draw background style */
d->pan = pan;
const struct ui_box *b = &pan->box;
switch (d->style) {
default: assert(0); break;
case UI_AREA_STYLE_FLAT: break;
case UI_AREA_STYLE_SUNKEN: {
d->background = xs_color_background(sys->surf, xc_rgb(255,255,255));
xs_color(sys->surf, xc_rgb(255,255,255));
xs_fill_rect(sys->surf, b->left, b->top, b->width, b->height, 0);
} break;}
/* draw border style */
switch (d->border_style) {
default: assert(0); break;
case UI_BORDER_STYLE_NONE: break;
case UI_BORDER_STYLE_SINGLE: {
xs_color(sys->surf, xc_rgb(0,0,0));
xs_line_style(sys->surf, XLINE_SOLID);
xs_line_thickness(sys->surf, 1);
xs_stroke_rect(sys->surf, b->left, b->top, b->width, b->height, 0);
} break;
case UI_BORDER_STYLE_3D: {
xs_line_style(sys->surf, XLINE_SOLID);
xs_line_thickness(sys->surf, 1);
xs_color(sys->surf, xc_rgb(128,128,128));
xs_stroke_line(sys->surf, b->left, b->top, b->right, b->top);
xs_stroke_line(sys->surf, b->left, b->top, b->left, b->bottom);
xs_color(sys->surf, xc_rgb(0,0,0));
xs_stroke_line(sys->surf, b->left+1, b->top+1, b->right-1, b->top+1);
xs_stroke_line(sys->surf, b->left+1, b->top+1, b->left+1, b->bottom-1);
xs_color(sys->surf, xc_rgb(255,255,255));
xs_stroke_line(sys->surf, b->left, b->bottom, b->right, b->bottom);
xs_stroke_line(sys->surf, b->right, b->top, b->right, b->bottom);
} break;}
switch (d->type) {
default: assert(0); break;
case UI_AREA_FIXED: break;
case UI_AREA_SCROLL: {
ui_anchor_left_right(&pan->box, pan->box.left, pan->box.right - UI_SCROLLBAR_SIZE);
ui_anchor_top_bottom(&pan->box, pan->box.top, b->bottom - UI_SCROLLBAR_SIZE);
} break;}
d->clip_rect = ui_clip_begin(ctx, pan->box.left, pan->box.top+3,
pan->box.width, pan->box.height);
/* apply scroll offset to area body */
const int off_x = floori(d->off_x);
const int off_y = floori(d->off_y);
ui_anchor_left_right(&pan->box, pan->box.left - off_x, pan->box.right - off_x);
ui_anchor_top_bottom(&pan->box, pan->box.top - off_y, pan->box.bottom - off_y);
return 1;
}
static void
ui_area_scroll(struct ui_ctx *ctx, struct ui_area *d)
{
const int off_x = floori(d->off_x);
const int off_y = floori(d->off_y);
struct ui_panel *pan = d->pan;
/* setup vertical scrollbar */
struct ui_scrollbar vscrl = {0};
vscrl.total = cast(float, pan->max_y - pan->box.top);
vscrl.size = cast(float, pan->box.bottom - pan->box.top);
vscrl.off = d->off_y;
/* do vertical scrollbar */
if (vscrl.total > vscrl.size) {
struct ui_panel vpan = {0};
int right = pan->box.right + UI_SCROLLBAR_SIZE + off_x;
ui_anchor_left_right(&vpan.box, pan->box.right + off_x, right);
ui_anchor_top_bottom(&vpan.box, pan->box.top+2 + off_y, pan->box.bottom + off_y);
ui_scrollbarv(ctx, &vscrl, &vpan, d->pan);
if (d->off_y != vscrl.off) {
d->off_y = vscrl.off;
d->scrolled = ui_true;
}
} else d->off_y = 0;
/* setup horizontal scrollbar */
struct ui_scrollbar hscrl = {0};
hscrl.total = cast(float, pan->max_x - pan->box.left);
hscrl.size = cast(float, pan->box.right - pan->box.left + UI_SCROLLBAR_SIZE);
hscrl.off = d->off_x;
/* do horizontal scrollbar */
if (hscrl.total > hscrl.size) {
struct ui_panel hpan = {0};
int bottom = pan->box.bottom + UI_SCROLLBAR_SIZE + off_y;
ui_anchor_left_right(&hpan.box, pan->box.left+2 + off_x, pan->box.right + off_x);
ui_anchor_top_bottom(&hpan.box, pan->box.bottom + off_y, bottom);
ui_scrollbarh(ctx, &hscrl, &hpan, d->pan);
if (d->off_x != hscrl.off) {
d->off_x = hscrl.off;
d->scrolled = ui_true;
}
} else d->off_x = 0;
d->max_offx = hscrl.total - hscrl.size;
d->max_offy = vscrl.total - vscrl.size;
}
static void
ui_area_set_offset(struct ui_area *d, float offx, float offy)
{
d->off_x = offx;
d->off_y = offy;
d->state = UI_INCONSISTENT;
}
static void
ui_area_set_offset_x(struct ui_area *d, float offx)
{
ui_area_set_offset(d, offx, d->off_y);
}
static void
ui_area_set_offset_y(struct ui_area *d, float offy)
{
ui_area_set_offset(d, d->off_x, offy);
}
static void
ui_area_end(struct ui_ctx *ctx, struct ui_area *d)
{
struct sys *sys = ctx->sys;
switch (d->style) {
default: assert(0); break;
case UI_AREA_STYLE_FLAT: break;
case UI_AREA_STYLE_SUNKEN: {
xs_color_background(sys->surf, d->background);
} break;}
ui_panel_end(d->pan);
ui_clip_end(ctx, d->clip_rect);
d->scrolled = ui_false;
switch (d->type) {
default: assert(0); break;
case UI_AREA_FIXED: break;
case UI_AREA_SCROLL: ui_area_scroll(ctx, d); break;}
if (d->state == UI_INCONSISTENT) {
sys_clear(sys);
ui_record_restore(&d->record);
memset(&d->pan, 0, sizeof(d->pan));
}
}
/* ---------------------------------------------------------------------------
* Combo
* --------------------------------------------------------------------------- */
#define UI_COMBO_DEFAULT_MAX_HEIGHT 400
#define UI_COMBO_SIZE 16
static void
ui_combo_button(struct ui_ctx *ctx, struct ui_panel *pan,
struct ui_panel *parent)
{
ui_panel_begin(ctx, pan, parent); {
const struct sys *sys = ctx->sys;
struct ui_box *b = &pan->box;
xs_line_thickness(sys->surf, 1);
xs_line_style(sys->surf, XLINE_SOLID);
/* draw background */
xs_color(sys->surf, xc_rgb(212,208,200));
xs_fill_rect(sys->surf, b->left, b->top, b->width, b->height, 0);
xs_stroke_line(sys->surf, b->left, b->top, b->right-1, b->top);
xs_stroke_line(sys->surf, b->left, b->top, b->left, b->bottom-1);
xs_color(sys->surf, xc_rgb(255,255,255));
xs_stroke_line(sys->surf, b->left+1, b->top+1, b->right-2, b->top+1);
xs_stroke_line(sys->surf, b->left+1, b->top+1, b->left+1, b->bottom-2);
xs_color(sys->surf, xc_rgb(64,64,64));
xs_stroke_line(sys->surf, b->right-1, b->top, b->right-1, b->bottom);
xs_stroke_line(sys->surf, b->left, b->bottom-1, b->right, b->bottom-1);
xs_color(sys->surf, xc_rgb(128,128,128));
xs_stroke_line(sys->surf, b->right-2, b->top+1, b->right-2, b->bottom-1);
xs_stroke_line(sys->surf, b->left+1, b->bottom-2, b->right-2, b->bottom-2);
if (pan->state == UI_FOCUSED) {
xs_line_thickness(sys->surf, 1);
xs_line_style(sys->surf, XLINE_DASHED);
xs_color(sys->surf, xc_rgb(0,0,0));
xs_stroke_rect(sys->surf, b->left+2, b->top+2, b->width-5, b->height-6, 0);
}
/* draw arrow */
static const int arrow_w = 7;
static const int arrow_h = 4;
struct ui_panel arrow = {0};
arrow.unselectable = ui_true;
ui_anchor_center_width(&arrow.box, pan->box.center_x, arrow_w);
ui_anchor_center_height(&arrow.box, pan->box.center_y, arrow_h);
ui_arrow(ctx, &arrow, pan, UI_SOUTH);
} ui_panel_end(pan);
}
static ui_bool
ui_combo_begin(struct ui_ctx *ctx, struct ui_combo *com,
const char *selected, const char *end,
struct ui_panel *pan, struct ui_panel *parent)
{
struct sys *sys = ctx->sys;
struct ui_panel *popup = &com->popup;
static const int pady = 4;
com->max_height = !com->max_height ? UI_COMBO_DEFAULT_MAX_HEIGHT: com->max_height;
com->pan = pan;
switch (com->stage) {
default: assert(0); break;
case UI_COMBO_DONE:
ui_popup_end(ctx, com->pan);
if (!com->selection_changed)
return ui_false;
ui_record_restore(&com->record);
/* fallthrough */
case UI_COMBO_HEADER: {
ui_record_store(&com->record, ctx, parent);
ui_panel_begin(ctx, pan, parent); {
/* draw combo box background */
struct ui_box *b = &pan->box;
xs_line_thickness(sys->surf, 1);
xs_line_style(sys->surf, XLINE_SOLID);
if (pan->state == UI_DISABLED)
xs_color(sys->surf, xc_rgb(212,208,200));
else xs_color(sys->surf, xc_rgb(255,255,255));
xs_fill_rect(sys->surf, b->left, b->top, b->width, b->height, 0);
xs_color(sys->surf, xc_rgb(128,128,128));
xs_stroke_line(sys->surf, b->left, b->top, b->right, b->top);
xs_stroke_line(sys->surf, b->left, b->top, b->left, b->bottom);
xs_color(sys->surf, xc_rgb(212,208,200));
xs_stroke_line(sys->surf, b->left+1, b->bottom-1, b->right, b->bottom-1);
xs_stroke_line(sys->surf, b->right-1, b->top+1, b->right-1, b->bottom-1);
xs_color(sys->surf, xc_rgb(0,0,0));
xs_stroke_line(sys->surf, b->left+1, b->top+1, b->right-1, b->top+1);
xs_stroke_line(sys->surf, b->left+1, b->top+1, b->left+1, b->bottom-1);
xs_color(sys->surf, xc_rgb(255,255,255));
xs_stroke_line(sys->surf, b->left, b->bottom, b->right+1, b->bottom);
xs_stroke_line(sys->surf, b->right, b->top, b->right, b->bottom);
/* buffer */
char buf[256];
int buf_len = cast(int, strlen(selected));
strscpy(buf, selected, cntof(buf));
/* Edit field */
const int padx = 4;
ui_bool activated = ui_false;
struct ui_panel edit_box = {0};
struct ui_edit_box edit = {.type = UI_EDIT_BOX_DEFAULT};
edit_box.focusable = ui_true;
ui_anchor_left_right(&edit_box.box, pan->box.left + padx, pan->box.right - UI_COMBO_SIZE - padx);
ui_anchor_top_bottom(&edit_box.box, pan->box.top + 2, pan->box.bottom - 2);
ui_edit_field(ctx, &edit, &edit_box, pan, buf, &buf_len, szof(buf));
/* button */
struct ui_panel btn = {0};
btn.focusable = ui_true;
ui_anchor_right_width(&btn.box, pan->box.right, UI_COMBO_SIZE);
ui_anchor_top_bottom(&btn.box, pan->box.top+2, pan->box.bottom-2);
ui_combo_button(ctx, &btn, pan);
if (btn.clicked || activated)
ui_popup_activate(ctx, pan->id, UI_POPUP_NON_BLOCKING);
} ui_panel_end(pan);
if (com->stage == UI_COMBO_DONE)
return ui_false;
if (!ui_popup_begin(ctx, popup, pan->id, pan->box.left,
pan->box.bottom, pan->box.width, com->max_height))
return ui_false;
com->state = UI_COMBO_EXPANDED;
com->stage = UI_COMBO_LAYOUT;
} /* fallthrough */
case UI_COMBO_LAYOUT: {
/* start layouting pass */
com->idx = 0;
com->at_y = popup->box.top + pady;
} return ui_true;
case UI_COMBO_EXEC: {
/* start execution pass */
com->idx = 0;
com->at_y = popup->box.top + pady;
ui_anchor_left_width(&popup->box, popup->box.left, popup->box.right-1);
ui_area_begin(ctx, &com->area, &com->area_panel, popup);
} return ui_true;}
return ui_true;
}
static int
ui_combo_label(struct ui_ctx *ctx, struct ui_combo *com,
struct ui_panel *pan, struct ui_panel *parent,
const char *label, const char *end)
{
ui_panel_begin(ctx, pan, parent); {
const struct sys *sys = ctx->sys;
if (pan->hovered) {
const unsigned fg = xs_color_foreground(sys->surf, xc_rgb(0,0,0));
const unsigned bg = xs_color_background(sys->surf, xc_rgb(255,255,255));
/* text hightlight */
xs_color(sys->surf, xc_rgb(0,0,128));
xs_fill_rect(sys->surf, pan->box.left, pan->box.top,
pan->box.width, pan->box.height, 0);
xs_color(sys->surf, xc_rgb(255,255,255));
ui_label(ctx, pan, parent, label, end);
xs_color_foreground(sys->surf, fg);
xs_color_background(sys->surf, bg);
} else {
xs_color(sys->surf, xc_rgb(0,0,0));
ui_label(ctx, pan, parent, label, end);
}
if (pan->state == UI_FOCUSED) {
struct ui_box *b = &pan->box;
xs_line_thickness(sys->surf, 1);
xs_line_style(sys->surf, XLINE_DASHED);
xs_color(sys->surf, xc_rgb(0,0,0));
xs_stroke_rect(sys->surf, b->left+2, b->top+2, b->width-5, b->height-6, 0);
}
} ui_panel_end(pan);
return pan->clicked;
}
static int
ui_combo_item(struct ui_ctx *ctx, struct ui_combo *com,
const char *label, const char *end)
{
int res = 0;
static const int padx = 4;
static const int spacing = 4;
switch (com->stage) {
case UI_COMBO_HEADER:
case UI_COMBO_DONE:
default: assert(0); break;
case UI_COMBO_LAYOUT: {
/* layout */
if (com->idx != com->selected) {
struct extend ext = xf_text_measure(res_font(ctx->res), label,end);
com->at_y += ext.h + spacing;
}
} break;
case UI_COMBO_EXEC: {
/* execute */
struct ui_panel btn = {0};
if (com->idx == com->selected) break;
struct extend ext = xf_text_measure(res_font(ctx->res), label,end);
ui_anchor_left_right(&btn.box, com->area_panel.box.left + padx,
com->area_panel.box.right - padx);
ui_anchor_top_height(&btn.box, com->at_y, ext.h);
com->at_y += ext.h + spacing;
if ((res = ui_combo_label(ctx, com, &btn, &com->area_panel, label, end))) {
ui_popup_deactivate(ctx, com->pan->id);
com->state = UI_COMBO_COLLAPSED;
com->selection_changed = ui_true;
com->selected = com->idx;
}
} break;}
com->idx++;
return res;
}
static void
ui_combo_end(struct ui_ctx *ctx, struct ui_combo *com)
{
switch (com->stage) {
case UI_COMBO_HEADER:
case UI_COMBO_DONE:
default: assert(0); break;
case UI_COMBO_LAYOUT: {
/* fit popup to content */
static const int pady = 4;
com->max_height = com->at_y - com->popup.box.top + pady;
if (com->max_height < UI_COMBO_DEFAULT_MAX_HEIGHT) {
const struct ui_panel *pan = com->pan;
if (!ui_popup_resize(ctx, &com->popup, pan->id, pan->box.width, com->max_height)) {
com->stage = UI_COMBO_DONE;
return;
}
} com->stage = UI_COMBO_EXEC;
} break;
case UI_COMBO_EXEC: {
ui_area_end(ctx, &com->area);
if (com->area.state == UI_INCONSISTENT)
com->stage = UI_COMBO_EXEC;
else com->stage = UI_COMBO_DONE;
} break;}
}
static int
ui_combo(struct ui_ctx *ctx, struct ui_combo *com,
struct ui_panel *pan, struct ui_panel *parent,
const char **list, int cnt)
{
while (ui_combo_begin(ctx, com, list[com->selected], 0, pan, parent)) {
for (int i = 0; i < cnt; ++i)
if (ui_combo_item(ctx, com, list[i], 0)) break;
ui_combo_end(ctx, com);
} return com->selection_changed ? 1:0;
}
/* ---------------------------------------------------------------------------
* Tab
* --------------------------------------------------------------------------- */
static ui_bool
ui_tab_control_begin(struct ui_ctx *ctx, struct ui_tab_control *tab,
struct ui_panel *parent)
{
tab->parent = parent;
switch (tab->stage) {
default: assert(0); break;
case UI_TAB_LAYOUT: {
tab->fixed_size = 0;
} break;
case UI_TAB_INPUT: {
tab->off_x = parent->box.left;
ui_record_store(&tab->rec, ctx, parent);
tab->idx = 0;
} break;
case UI_TAB_RENDER: {
tab->off_x = parent->box.left;
tab->idx = 0;
} break;
case UI_TAB_DONE: {
/* setup body */
ui_anchor_left_right(&tab->body.box, parent->box.left, parent->box.right);
ui_anchor_top_bottom(&tab->body.box, tab->at_y, parent->box.bottom);
if (tab->activate_next)
ctx->activate_next = ui_true;
return ui_false;
} break;}
return ui_true;
}
static void
ui_tab_control_slot(struct ui_ctx *ctx, struct ui_tab_control *tab,
const char *txt, const char *end)
{
struct ui_panel *parent = tab->parent;
switch (tab->stage) {
case UI_TAB_DONE:
default: assert(0); break;
case UI_TAB_LAYOUT: {
/* calculate desired size */
static const int tab_pady = 6;
struct extend ext = xf_text_measure(res_font(ctx->res), txt, end);
tab->fixed_size = max(ext.h + (tab_pady << 1), tab->fixed_size);
} break;
case UI_TAB_INPUT:
case UI_TAB_RENDER: {
static const int tab_padx = 8;
struct ui_panel pan = {0};
pan.focusable = ui_true;
struct extend ext = xf_text_measure(res_font(ctx->res), txt, end);
ui_anchor_left_width(&pan.box, tab->off_x, ext.w + (tab_padx << 1));
ui_anchor_top_height(&pan.box, parent->box.top, tab->fixed_size);
ui_panel_begin(ctx, &pan, parent);
tab->off_x += pan.box.width;
switch (tab->stage) {
case UI_TAB_DONE:
case UI_TAB_LAYOUT:
default: assert(0); break;
case UI_TAB_INPUT: {
/* do tab selection */
if (pan.clicked || pan.pressed) {
if (tab->selection != tab->idx)
tab->toggled = ui_true;
tab->selection = tab->idx;
}
if (pan.state == UI_FOCUSED) {
struct sys *sys = ctx->sys;
if (sys->keys[SYS_KEY_LEFT].pressed)
tab->selection = max(0, tab->selection-1);
if (sys->keys[SYS_KEY_RIGHT].pressed)
tab->selection = tab->selection+1;
}
struct ui_panel dummy = {0};
ui_panel(ctx, &dummy, &pan);
} break;
case UI_TAB_RENDER: {
/* draw tab button */
const struct sys *sys = ctx->sys;
const struct ui_box *p = &pan.box;
const ui_bool active = (tab->selection == tab->idx);
const int top = p->top + ((!active) ? 3: 0);
const int height = p->height - ((!active) ? 3: 0);
xs_line_style(sys->surf, XLINE_SOLID);
xs_line_thickness(sys->surf, 1);
xs_color_background(sys->surf, xc_rgb(0,0,0));
xs_color(sys->surf, xc_rgb(212,208,200));
xs_fill_rect(sys->surf, p->left, top, p->width, height, 0);
xs_color(sys->surf, xc_rgb(255,255,255));
xs_stroke_line(sys->surf, p->left, top, p->right, top);
if (!active)
xs_stroke_line(sys->surf, p->left, p->bottom, p->right, p->bottom);
if (tab->idx == 0 || (tab->idx-1) != tab->selection)
xs_stroke_line(sys->surf, p->left, top, p->left, p->bottom);
if (tab->selection != (tab->idx + 1)) {
xs_color(sys->surf, xc_rgb(0,0,0));
xs_stroke_line(sys->surf, p->right-1, top, p->right-1, p->bottom);
xs_color(sys->surf, xc_rgb(128,128,128));
xs_stroke_line(sys->surf, p->right-2, top, p->right-2, p->bottom);
}
/* draw label */
struct ui_panel lbl = {0};
lbl.unselectable = ui_true;
ui_anchor_center_width(&lbl.box, pan.box.center_x, ext.w);
ui_anchor_center_height(&lbl.box, pan.box.center_y, ext.h);
xs_color(sys->surf, xc_rgb(0,0,0));
ui_label(ctx, &lbl, parent, txt, end);
/* draw focus */
if (pan.state == UI_FOCUSED) {
xs_line_thickness(sys->surf, 1);
xs_line_style(sys->surf, XLINE_DASHED);
xs_color(sys->surf, xc_rgb(0,0,0));
xs_stroke_rect(sys->surf, p->left+3, p->top+5, p->width-7, p->height-9, 0);
}
} break;}
ui_panel_end(&pan);
} break;}
tab->idx++;
}
static void
ui_tab_control_end(struct ui_ctx *ctx, struct ui_tab_control *tab)
{
struct ui_panel *parent = tab->parent;
switch (tab->stage) {
case UI_TAB_DONE:
default: assert(0); break;
case UI_TAB_LAYOUT: {
/* layouting pass */
tab->stage = UI_TAB_INPUT;
tab->at_y = parent->box.top + tab->fixed_size;
} break;
case UI_TAB_INPUT: {
/* input pass */
tab->at_x = tab->off_x;
tab->stage = UI_TAB_RENDER;
tab->selection = min(tab->selection, max(0, tab->idx-1));
ui_record_restore(&tab->rec);
if (ctx->activate_next) {
tab->activate_next = ui_true;
ctx->activate_next = ui_false;
sys_clear(ctx->sys);
}
} break;
case UI_TAB_RENDER: {
/* render pass */
tab->stage = UI_TAB_DONE;
const struct sys *sys = ctx->sys;
const struct ui_panel *pan = parent;
const struct ui_box *b = &pan->box;
/* finally draw tab control border */
xs_color_background(sys->surf, xc_rgb(0,0,0));
xs_line_style(sys->surf, XLINE_SOLID);
xs_line_thickness(sys->surf, 1);
xs_color(sys->surf, xc_rgb(255,255,255));
xs_stroke_line(sys->surf, tab->at_x, tab->at_y, b->right-1, tab->at_y);
xs_stroke_line(sys->surf, b->left, tab->at_y, b->left, b->bottom-1);
xs_color(sys->surf, xc_rgb(128,128,128));
xs_stroke_line(sys->surf, b->right-2, tab->at_y+1, b->right-2, b->bottom-2);
xs_stroke_line(sys->surf, b->left+1, b->bottom-2, b->right-2, b->bottom-2);
xs_color(sys->surf, xc_rgb(0,0,0));
xs_stroke_line(sys->surf, b->right-1, tab->at_y, b->right-1, b->bottom-1);
xs_stroke_line(sys->surf, b->left, b->bottom-1, b->right-1, b->bottom-1);
} break;}
}
static int
ui_tab_control(struct ui_ctx *ctx, struct ui_tab_control *tab,
struct ui_panel *parent, const char **titles, int cnt)
{
while (ui_tab_control_begin(ctx, tab, parent)) {
for (int i = 0; i < cnt; ++i)
ui_tab_control_slot(ctx, tab, titles[i], 0);
ui_tab_control_end(ctx, tab);
} return tab->selection;
}
/* ---------------------------------------------------------------------------
* List
* --------------------------------------------------------------------------- */
static void
ui_list_init(struct ui_list *ls)
{
ls->at_x = ls->box.left + ls->padx;
ls->at_y = ls->box.top + ls->pady;
}
static void
ui_list_setup(struct ui_list *ls, const struct ui_panel *pan)
{
ls->box = pan->box;
ui_list_init(ls);
}
static void
ui_list_gen(struct ui_box *box, struct ui_list *ls)
{
ui_anchor_left_width(box, ls->at_x, ls->col_width);
ui_anchor_top_height(box, ls->at_y, ls->row_height);
switch (ls->orient) {
case UI_HORIZONTAL: {
if ((ls->flow == UI_FLOW_WRAP) &&
(box->right + ls->col_width + ls->spacing_x + ls->padx) >= ls->box.right) {
ls->at_x = ls->box.left + ls->padx;
ls->at_y += ls->row_height + ls->spacing_y;
} else ls->at_x += ls->col_width + ls->spacing_x;
} break;
case UI_VERTICAL: {
if ((ls->flow == UI_FLOW_WRAP) &&
(box->bottom + ls->row_height + ls->spacing_y + ls->pady) >= ls->box.bottom) {
ls->at_y = ls->box.top + ls->pady;
ls->at_x += ls->col_width + ls->spacing_x;
} else ls->at_y += ls->row_height + ls->spacing_y;
} break;}
}
/* ---------------------------------------------------------------------------
* View
* --------------------------------------------------------------------------- */
static void
ui_view(struct ui_view *v, struct ui_list* ls, int width, int height)
{
int total = max(1, v->total)-1;
v->space_x = max(0, width - (ls->padx << 1));
v->space_y = max(0, height - (ls->pady << 1));
v->col_width = max(1, ls->col_width + ls->spacing_x);
v->col_cnt = max(1, floori(cast(float, v->space_x) / cast(float, v->col_width)));
v->row_cnt = max(1, ceili(cast(float, total) / cast(float, max(1, v->col_cnt))));
v->row_height = max(1, ls->spacing_y + ls->row_height);
v->total_height = max(1, v->row_cnt) * v->row_height;
v->total_width = max(1, v->col_cnt) * v->col_width;
v->orient = ls->orient;
v->flow = ls->flow;
int row_off = floori(v->offset / cast(float, v->row_height));
int row_win = ceili(cast(float, v->space_y) / cast(float, v->row_height));
v->begin = row_off * v->col_cnt;
v->end = v->begin + v->col_cnt * (row_win + 1);
v->end = min(v->end, v->total);
v->max_x = ls->at_x + v->total_width;
v->max_y = ls->at_y + v->total_height;
ls->at_y += row_off * v->row_height;
}
static void
ui_view_panel(struct ui_view *v, struct ui_list* ls, struct ui_panel* pan)
{
ui_view(v, ls, pan->box.width, pan->box.height);
}
static float
ui_view_center(struct ui_view *v, int index)
{
const int total = max(1, v->total)-1;
const int idx = clamp(0, index, total);
switch (v->orient) {
default: assert(0); return 0.0f;
case UI_HORIZONTAL:
switch (v->flow) {
case UI_FLOW_WRAP: {
int row = idx / v->row_cnt;
int center_off = v->row_height * row + (v->row_height >> 1);
int off = center_off - (v->space_y >> 1);
return cast(float, clamp(0, off, v->total_height - v->space_y));
}
case UI_FLOW_STRAIGHT: {
int center_off = v->col_width * idx + (v->col_width >> 1);
int off = center_off - (v->space_x >> 1);
return cast(float, clamp(0, off, v->total_width - v->space_x));
} default: return 0.0f;}
case UI_VERTICAL:
switch (v->flow) {
case UI_FLOW_WRAP: {
int col = idx / v->col_cnt;
int center_off = v->col_width * col + (v->col_width >> 1);
int off = center_off - (v->space_x >> 1);
return cast(float, clamp(0, off, v->total_width - v->space_x));
}
case UI_FLOW_STRAIGHT: {
int center_off = v->row_height * idx + (v->row_height >> 1);
int off = center_off - (v->space_y >> 1);
return cast(float, clamp(0, off, v->total_height - v->space_y));
} default: return 0.0f;}
}
}
static float
ui_view_fit_start(struct ui_view *v, int index)
{
int total = max(1, v->total)-1;
int idx = clamp(0, index, total);
switch (v->orient) {
default: assert(0); return 0.0f;
case UI_HORIZONTAL:
switch (v->flow) {
case UI_FLOW_WRAP: {
int row = idx / v->row_cnt;
int off = v->row_height * row;
return cast(float, clamp(0, off, v->total_height - v->space_y));
}
case UI_FLOW_STRAIGHT: {
int off = v->col_width * idx;
return cast(float, clamp(0, off, v->total_width - v->space_x));
} default: return 0.0f;}
case UI_VERTICAL:
switch (v->flow) {
case UI_FLOW_WRAP: {
int col = idx / v->col_cnt;
int off = v->col_width * col;
return cast(float, clamp(0, off, v->total_width - v->space_x));
}
case UI_FLOW_STRAIGHT: {
int off = v->row_height * idx;
return cast(float, clamp(0, off, v->total_height - v->space_y));
} default: return 0.0f;}
}
}
static float
ui_view_fit_end(struct ui_view *v, int index)
{
int total = max(1, v->total)-1;
int idx = clamp(0, index, total);
switch (v->orient) {
default: assert(0); return 0.0f;
case UI_HORIZONTAL:
switch (v->flow) {
case UI_FLOW_WRAP: {
int row = idx / v->row_cnt;
int off = v->row_height * (row+1) - v->space_y;
return cast(float, clamp(0, off, v->total_height - v->space_y));
}
case UI_FLOW_STRAIGHT: {
int off = v->col_width * (idx+1) - v->space_x;
return cast(float, clamp(0, off, v->total_height - v->space_y));
} default: return 0.0f;}
case UI_VERTICAL:
switch (v->flow) {
case UI_FLOW_WRAP: {
int col = idx / v->col_cnt;
int off = v->col_width * (col+1) - v->space_x;
return cast(float, clamp(0, off, v->total_height - v->space_y));
}
case UI_FLOW_STRAIGHT: {
int off = v->row_height * (idx+1) - v->space_y;
return cast(float, clamp(0, off, v->total_height - v->space_y));
} default: return 0.0f;}
}
}
static float
ui_view_goto_begin(struct ui_view *v)
{
return ui_view_fit_start(v, 0);
}
static float
ui_view_goto_end(struct ui_view *v)
{
return ui_view_fit_end(v, v->total);
}
/* ---------------------------------------------------------------------------
* Tree
* --------------------------------------------------------------------------- */
#define UI_TREE_PLUS_MINUS_SIZE 9
static void
ui_tree_show_lines(struct ui_tree *t, int *depth_buf, int max_depth)
{
t->show_lines = ui_true;
t->max_depth = max_depth;
t->y_at_depth = depth_buf;
t->prev_depth = -1;
}
static int
ui_tree_begin(struct ui_ctx *ctx,
struct ui_tree *t, struct ui_panel *parent)
{
static const int pady = 4;
t->area.off_x = t->off_x;
t->area.off_y = t->off_y;
t->repaint = ui_false;
t->idx = 0;
const int ret = ui_area_begin(ctx, &t->area, &t->area_panel, parent);
t->at_y = t->area_panel.box.top + pady;
return ret;
}
static int
ui_tree_node_plus_minus_button(struct ui_ctx *ctx, struct ui_panel *pan,
struct ui_panel *parent, enum ui_tree_node_state state)
{
ui_panel_begin(ctx, pan, parent); {
const struct sys *sys = ctx->sys;
if (pan->clicked)
state = !state;
/* draw correct icon */
const struct xsurface *icon = 0;
switch (state) {
default: assert(0); return 0;
case UI_TREE_NODE_COLLAPSED:
icon = res_img(ctx->res, IMG_PLUS); break;
case UI_TREE_NODE_EXPANDED:
icon = res_img(ctx->res, IMG_MINUS); break;}
xs_blit(sys->surf, icon, pan->box.left, pan->box.top, 0,0, icon->w, icon->h);
} ui_panel_end(pan);
return pan->clicked;
}
static void
ui_tree_node(struct ui_ctx *ctx, struct ui_tree *t,
struct ui_tree_node *node, struct ui_panel *pan,
const char *txt, const char *end, int depth)
{
static const int padx = 6;
static const int pady = 4;
static const int spacing_x = 6;
static const int spacing_y = 0;
static const int depth_scaler = 18;
struct sys *sys = ctx->sys;
/* reset node state */
node->check_changed = 0;
node->state_changed = 0;
node->selection_changed = 0;
/* optional flags */
const ui_bool has_chk = t->flags & UI_TREE_NODE_CHECK;
const ui_bool has_icon = t->flags & UI_TREE_NODE_ICON;
const ui_bool has_state = (node->type == UI_TREE_NODE_INTERNAL);
/* calculate node extend */
const struct xsurface *xs = res_icon(ctx->res);
struct extend ext = xf_text_measure(res_font(ctx->res), txt, end);
int node_height = ext.h;
node_height = max(node_height, UI_TREE_PLUS_MINUS_SIZE);
node_height = max(node_height, UI_CHECKBOX_SIZE);
node_height = max(node_height, xs->h);
int icon_width = 0;
icon_width = max(icon_width, UI_TREE_PLUS_MINUS_SIZE);
icon_width = max(icon_width, UI_CHECKBOX_SIZE);
icon_width = max(icon_width, xs->w);
int hline_begin = 0;
int hline_end = 0;
int vline_x = 0;
int vline_y = 0;
int y_depth = 0;
memset(pan, 0, sizeof(*pan));
if (node->selected)
pan->focusable = ui_true;
else pan->focusable = ui_false;
ui_panel_begin(ctx, pan, &t->area_panel);
if (t->focus_next) {
ctx->active = pan->id;
pan->state = UI_FOCUSED;
t->focus_next = ui_false;
}
if (t->inconsistent) {
/* handle selection changes */
if (ui_id_eq(&pan->id, &t->selected_node)) {
node->selected = ui_true;
node->selection_changed = ui_true;
t->selection_changed = ui_true;
t->inconsistent = ui_false;
} else if (node->selected) {
node->selected = ui_false;
node->selection_changed = ui_true;
} else node->selected = ui_false;
}
const int center_y = t->at_y + (node_height >> 1);
int at_x = t->area_panel.box.left + padx + depth * depth_scaler;
if (has_state) {
/* Plus-minus icon (optional) */
struct ui_panel ico = {0};
ui_anchor_left_width(&ico.box, at_x, UI_TREE_PLUS_MINUS_SIZE);
ui_anchor_center_height(&ico.box, center_y, UI_TREE_PLUS_MINUS_SIZE);
if (ui_tree_node_plus_minus_button(ctx, &ico, &t->area_panel, node->state)) {
node->selected = !node->selected;
node->selection_changed = ui_true;
node->state_changed = ui_true;
node->state = !node->state;
}
if (pan->state == UI_FOCUSED) {
if (sys->keys[SYS_KEY_RIGHT].pressed && !node->state) {
node->state_changed = ui_true;
node->state = ui_true;
}
if (sys->keys[SYS_KEY_LEFT].pressed && node->state) {
node->state_changed = ui_true;
node->state = ui_false;
}
}
vline_y = ico.box.top;
y_depth = ico.box.bottom;
hline_begin = ico.box.right;
vline_x = at_x + (UI_TREE_PLUS_MINUS_SIZE >> 1);
at_x = ico.box.right + spacing_x;
} else {
y_depth = center_y;
vline_y = center_y;
hline_begin = at_x + (UI_TREE_PLUS_MINUS_SIZE >> 1);
vline_x = hline_begin;
at_x += UI_TREE_PLUS_MINUS_SIZE + spacing_x;
}
if (has_chk) {
/* Checkbox (optional) */
struct ui_panel chk = {0};
ui_anchor_left_width(&chk.box, at_x, UI_CHECKBOX_SIZE);
ui_anchor_center_height(&chk.box, center_y, UI_CHECKBOX_SIZE);
if (ui_check(ctx, &chk, &t->area_panel, node->checked) != node->checked) {
node->checked = !node->checked;
node->check_changed = ui_true;
}
hline_end = chk.box.left;
at_x = chk.box.right + spacing_x;
}
if (has_icon) {
/* Icon (optional) */
struct ui_panel ico = {0};
ui_anchor_left_width(&ico.box, at_x, xs->w);
ui_anchor_center_height(&ico.box, center_y, xs->h);
ui_icon(ctx, &ico, &t->area_panel);
if (ico.clicked) {
node->selected = !node->selected;
node->selection_changed = ui_true;
}
if (!has_chk) hline_end = ico.box.left;
at_x = ico.box.right + spacing_x;
}
if (t->show_lines) {
/* horizontal line */
if (!has_chk && !has_icon)
hline_end = at_x;
xs_line_thickness(sys->surf, 1);
xs_line_style(sys->surf, XLINE_DASHED);
xs_color(sys->surf, xc_rgb(123,123,123));
xs_stroke_line(sys->surf, hline_begin, center_y, hline_end, center_y);
/* vertical line */
if (depth == t->prev_depth) {
int off = 0;
if (t->prev_state)
off = (node_height - UI_TREE_PLUS_MINUS_SIZE) >> 1;
else off = (node_height >> 1);
int vline_end = t->at_y - spacing_y - off;
xs_stroke_line(sys->surf, vline_x, vline_y, vline_x, vline_end);
} else if (depth > t->prev_depth && depth) {
int off = (node_height - xs->h) >> 1;
int vline_end = t->at_y - spacing_y - off;
xs_stroke_line(sys->surf, vline_x, vline_y, vline_x, vline_end);
} else if (depth < t->prev_depth){
int vline_end = t->y_at_depth[depth];
xs_stroke_line(sys->surf, vline_x, vline_y, vline_x, vline_end);
}
t->y_at_depth[depth] = y_depth;
t->prev_state = has_state;
t->prev_depth = depth;
}
/* Label (required) */
struct ui_panel lbl = {0};
ui_anchor_left_width(&lbl.box, at_x, ext.w);
ui_anchor_center_height(&lbl.box, center_y, ext.h);
if (node->selected) {
/* selected item label */
const unsigned fg = xs_color_foreground(sys->surf, xc_rgb(0,0,0));
const unsigned bg = xs_color_background(sys->surf, xc_rgb(255,255,255));
/* text hightlight */
xs_color(sys->surf, xc_rgb(0,0,128));
xs_fill_rect(sys->surf, lbl.box.left-1, lbl.box.top,
lbl.box.width+2, lbl.box.height, 0);
xs_color(sys->surf, xc_rgb(255,255,255));
ui_label(ctx, &lbl, &t->area_panel, txt, 0);
xs_color_foreground(sys->surf, fg);
xs_color_background(sys->surf, bg);
} else {
xs_color_foreground(sys->surf, xc_rgb(0,0,0));
ui_label(ctx, &lbl, &t->area_panel, txt, 0);
}
if (lbl.clicked) {
/* node selection */
ctx->active = pan->id;
node->selected = !node->selected;
node->selection_changed = ui_true;
}
if (pan->state == UI_FOCUSED) {
/* cursor movement */
if (sys->keys[SYS_KEY_ACTIVATE].pressed) {
node->selection_changed = ui_true;
node->selected = !node->selected;
sys_clear(sys);
}
if (sys->keys[SYS_KEY_UP].pressed) {
pan->state = UI_NORMAL;
ctx->active = t->prev;
t->repaint = ui_true;
sys_clear(sys);
}
if (sys->keys[SYS_KEY_DOWN].pressed) {
pan->state = UI_NORMAL;
t->focus_next = ui_true;
t->repaint = ui_true;
sys_clear(sys);
}
/* cursor scrolling */
if (t->at_y + node_height > t->area_panel.box.bottom - pady + floori(t->area.off_y))
t->off_y = cast(float, (t->at_y - (t->area_panel.box.top + pady)) - t->area_panel.box.height + node_height);
else if (t->at_y < t->area_panel.box.top - pady + floori(t->area.off_y))
t->off_y = cast(float, t->at_y - (t->area_panel.box.top + pady));
/* draw cursor */
struct ui_box *b = &lbl.box;
xs_line_thickness(sys->surf, 1);
xs_line_style(sys->surf, XLINE_DASHED);
xs_color(sys->surf, xc_rgb(0,0,0));
xs_stroke_rect(sys->surf, b->left-1, b->top-1, b->width+1, b->height+1, 0);
}
if (node->selected && node->selection_changed &&
!ui_id_eq(&pan->id, &t->selected_node)) {
/* Selection invalidated current tree state, so signal another iteration */
t->off_y = cast(float, center_y - (t->area_panel.box.top + pady) - (t->area_panel.box.height >> 1));
t->selected_node = pan->id;
t->inconsistent = ui_true;
node->selection_changed = ui_false;
node->selected = ui_false;
sys_clear(sys);
}
ui_panel_end(pan);
t->at_y += max(ext.h, node_height) + spacing_y;
t->prev = pan->id;
t->idx++;
}
static void
ui_tree_end(struct ui_ctx *ctx, struct ui_tree *t)
{
if (t->inconsistent || t->repaint)
t->area.state = UI_INCONSISTENT;
ui_area_end(ctx, &t->area);
if (t->area.scrolled) {
t->off_x = t->area.off_x;
t->off_y = t->area.off_y;
} else t->off_y = clamp(0, t->off_y, t->area.max_offy);
}
|
C
|
#include "at24eeprom.h"
#ifdef USE_HAL_DRIVER
uint8_t at24read(I2C_HandleTypeDef * eeprom, uint8_t * buf, uint16_t len, uint16_t offset)
{
return HAL_I2C_Mem_Read(eeprom, 0xa0 | ((offset >> 8) << 1), offset&0xff, I2C_MEMADD_SIZE_8BIT, buf, len , 1000);
}
uint8_t at24write(I2C_HandleTypeDef * eeprom, uint8_t * buf, uint16_t len, uint16_t offset)
{
uint16_t current_offset = offset;
uint16_t remain = len;
do {
uint16_t length = 0;
if ( (current_offset & 0b00001111) + remain <= 0x10 )
{
length = remain;
} else {
length = 0x10 - (current_offset & 0b00001111);
}
HAL_I2C_Mem_Write(eeprom, 0xa0 | ((current_offset >> 8) << 1), current_offset&0xff, I2C_MEMADD_SIZE_8BIT, &buf[len-remain], length , 1000);
HAL_Delay(5);
current_offset += length;
remain -= length;
} while (remain);
return HAL_OK;
}
#endif
|
C
|
/** @file
Implementacja interfejsu kalkulatora wielomianów rzadkich wielu zmiennych
@author Bartłomiej Sadlej
@copyright Uniwersytet Warszawski
@date 2021
*/
#pragma once
#include "calc_helper_functions.h"
#include "macros.h"
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#define POLY_EXP_MAX 2147483647 // specyfikacja zadania
#define MAX_TASK_LEN 8 // IS_COEFF
/**
* Enum reprezentujący operacje wykonywane przez kalkulator
*/
static enum taskType
{
ZERO,
IS_COEFF,
IS_ZERO,
CLONE,
ADD,
MUL,
NEG,
SUB,
IS_EQ,
DEG,
DEG_BY,
AT,
PRINT,
POP,
COMPOSE,
__INVALID__
};
bool IsWhitespace(int c)
{
// '\n' nie jest tu celowo rozpatrywany
switch(c)
{
case ' ':
return true;
case '\t':
return true;
case '\v':
return true;
case '\f':
return true;
case '\r':
return true;
default:
return false;
}
}
bool IsAlpha(int c)
{
if(c >= 'A' && c <= 'Z')
return true;
if(c >= 'a' && c <= 'z')
return true;
return false;
}
/**
* Rozpoznaje zadanie na podstawie napisu.
* @param[in] input_string wczytany napis
* @return enum z typem zadania
*/
static enum taskType DecodeTask(char* input_string)
{
if(!strcmp(input_string, "ZERO"))
return ZERO;
if(!strcmp(input_string, "IS_COEFF"))
return IS_COEFF;
if(!strcmp(input_string, "IS_ZERO"))
return IS_ZERO;
if(!strcmp(input_string, "ADD"))
return ADD;
if(!strcmp(input_string, "MUL"))
return MUL;
if(!strcmp(input_string, "NEG"))
return NEG;
if(!strcmp(input_string, "SUB"))
return SUB;
if(!strcmp(input_string, "IS_EQ"))
return IS_EQ;
if(!strcmp(input_string, "DEG"))
return DEG;
if(!strcmp(input_string, "DEG_BY"))
return DEG_BY;
if(!strcmp(input_string, "AT"))
return AT;
if(!strcmp(input_string, "PRINT"))
return PRINT;
if(!strcmp(input_string, "POP"))
return POP;
if(!strcmp(input_string, "CLONE"))
return CLONE;
if(!strcmp(input_string, "COMPOSE"))
return COMPOSE;
return __INVALID__;
}
/**
* Obsługa zadania ZERO.
* @param[in] stack stos z wielomianami
*/
static void TaskZero(Stack *stack)
{
Poly p = PolyZero();
StackAdd(stack, p);
}
/**
* Obsługa zadania IS_COEFF.
* @param[in] stack stos z wielomianami
* @param[in] row_number numer aktualnego wiersza
*/
static void TaskIsCoeff(Stack *stack, size_t row_number)
{
if(StackSize(stack) == 0)
PrintError(STACK_UNDERFLOW, row_number);
else
{
bool is_coef = PolyIsCoeff(StackHead(stack));
printf("%d\n", is_coef);
}
}
/**
* Obsługa zadania IS_ZERO.
* @param[in] stack stos z wielomianami
* @param[in] row_number numer aktualnego wiersza
*/
static void TaskIsZero(Stack *stack, size_t row_number)
{
if(StackSize(stack) == 0)
PrintError(STACK_UNDERFLOW, row_number);
else
{
bool is_zero = PolyIsZero(StackHead(stack));
printf("%d\n", is_zero);
}
}
/**
* Obsługa zadania CLONE.
* @param[in] stack stos z wielomianami
* @param[in] row_number numer aktualnego wiersza
*/
static void TaskClone(Stack *stack, size_t row_number)
{
if(StackSize(stack) == 0)
PrintError(STACK_UNDERFLOW, row_number);
else
{
Poly *p = StackHead(stack);
Poly q = PolyClone(p);
StackAdd(stack, q);
}
}
/**
* Obsługa zadania ADD.
* @param[in] stack stos z wielomianami
* @param[in] row_number numer aktualnego wiersza
*/
static void TaskAdd(Stack *stack, size_t row_number)
{
if(StackSize(stack) < 2)
PrintError(STACK_UNDERFLOW, row_number);
else
{
Poly p = StackPop(stack);
Poly q = StackPop(stack);
Poly r = PolyAdd(&p, &q);
PolyDestroy(&p);
PolyDestroy(&q);
StackAdd(stack, r);
}
}
/**
* Obsługa zadania MUL.
* @param[in] stack stos z wielomianami
* @param[in] row_number numer aktualnego wiersza
*/
static void TaskMul(Stack *stack, size_t row_number)
{
if(StackSize(stack) < 2)
PrintError(STACK_UNDERFLOW, row_number);
else
{
Poly p = StackPop(stack);
Poly q = StackPop(stack);
Poly r = PolyMul(&p, &q);
PolyDestroy(&p);
PolyDestroy(&q);
StackAdd(stack, r);
}
}
/**
* Obsługa zadania NEG.
* @param[in] stack stos z wielomianami
* @param[in] row_number numer aktualnego wiersza
*/
static void TaskNeg(Stack *stack, size_t row_number)
{
if(StackSize(stack) == 0)
PrintError(STACK_UNDERFLOW, row_number);
else
{
Poly p = StackPop(stack);
Poly q = PolyNeg(&p);
PolyDestroy(&p);
StackAdd(stack, q);
}
}
/**
* Obsługa zadania SUB.
* @param[in] stack stos z wielomianami
* @param[in] row_number numer aktualnego wiersza
*/
static void TaskSub(Stack *stack, size_t row_number)
{
if(StackSize(stack) < 2)
PrintError(STACK_UNDERFLOW, row_number);
else
{
Poly p = StackPop(stack);
Poly q = StackPop(stack);
Poly r = PolySub(&p, &q);
PolyDestroy(&p);
PolyDestroy(&q);
StackAdd(stack, r);
}
}
/**
* Obsługa zadania IS_EQ.
* @param[in] stack stos z wielomianami
* @param[in] row_number numer aktualnego wiersza
*/
static void TaskIsEq(Stack *stack, size_t row_number)
{
if(StackSize(stack) < 2)
PrintError(STACK_UNDERFLOW, row_number);
else
{
Poly *p = StackHead(stack);
Poly *q = StackHead2(stack);
bool is_eq = PolyIsEq(p, q);
printf("%d\n", is_eq);
}
}
/**
* Obsługa zadania DEG.
* @param[in] stack stos z wielomianami
* @param[in] row_number numer aktualnego wiersza
*/
static void TaskDeg(Stack *stack, size_t row_number)
{
if(StackSize(stack) == 0)
PrintError(STACK_UNDERFLOW, row_number);
else
{
poly_exp_t exp = PolyDeg(StackHead(stack));
printf("%d\n", exp);
}
}
/**
* Obsługa zadania DEG_BY.
* @param[in] stack stos z wielomianami
* @param[in] var_idx wartość dla polecenia DEG_BY
* @param[in] row_number numer aktualnego wiersza
*/
static void TaskDegBy(Stack *stack, size_t var_idx, size_t row_number)
{
if(StackSize(stack) == 0)
PrintError(STACK_UNDERFLOW, row_number);
else
{
poly_exp_t exp = PolyDegBy(StackHead(stack), var_idx);
printf("%d\n", exp);
}
}
/**
* Obsługa zadania AT.
* @param[in] stack stos z wielomianami
* @param[in] poly_coeff_t wartość dla polecenia AT
* @param[in] row_number numer aktualnego wiersza
*/
static void TaskAt(Stack *stack, poly_coeff_t x, size_t row_number)
{
if(StackSize(stack) == 0)
PrintError(STACK_UNDERFLOW, row_number);
else
{
Poly p = StackPop(stack);
Poly q = PolyAt(&p, x);
PolyDestroy(&p);
StackAdd(stack, q);
}
}
/**
* Wypisuje wielomian
* @param[in] p wielomian
*/
static void PrintPoly(Poly *p);
/**
* Wypisuje jednomian
* @param[in] m jednomian
*/
static void PrintMono(Mono *m)
{
printf("(");
PrintPoly(&m->p);
printf(",%d)", m->exp);
}
static void PrintPoly(Poly *p)
{
if(PolyIsCoeff(p))
{
printf("%ld", p->coeff);
return;
}
for(size_t i = 0; i < p->size; i++)
{
if(i>0)
printf("+");
PrintMono(&p->arr[i]);
}
}
/**
* Obsługa zadania PRINT.
* @param[in] stack stos z wielomianami
* @param[in] row_number numer aktualnego wiersza
*/
static void TaskPrint(Stack *stack, size_t row_number)
{
if(StackSize(stack) == 0)
{
PrintError(STACK_UNDERFLOW, row_number);
return;
}
PrintPoly(StackHead(stack));
printf("\n");
}
/**
* Obsługa zadania POP.
* @param[in] stack stos z wielomianami
* @param[in] row_number numer aktualnego wiersza
*/
static void TaskPop(Stack *stack, size_t row_number)
{
if(StackSize(stack) == 0)
PrintError(STACK_UNDERFLOW, row_number);
else
{
Poly p = StackPop(stack);
PolyDestroy(&p);
}
}
/**
* Obsługa zadania COMPOSE.
* @param[in] stack stos z wielomianami
* @param[in] k liczba wielomianów do wykorzystania przy operacji COMPOSE
* @param[in] row_number numer aktualnego wiersza
*/
static void TaskCompose(Stack *stack, size_t k, size_t row_number)
{
if(StackSize(stack) < k + 1 || k == ULONG_MAX)
{
PrintError(STACK_UNDERFLOW, row_number);
return;
}
else
{
Poly p = StackPop(stack);
Poly *q = malloc(k * sizeof(Poly));
CHECK_PTR(q);
for(size_t i = 1; i <= k; i++)
q[k - i] = StackPop(stack);
Poly p2 = PolyCompose(&p, k, q);
PolyDestroy(&p);
StackAdd(stack, p2);
for(size_t i = 0; i < k; i++)
PolyDestroy(&q[i]);
free(q);
}
}
void ReadTask(Stack *stack, int c, size_t row_number)
{
char* input_string = malloc( (MAX_TASK_LEN + 1) * sizeof(char));
CHECK_PTR(input_string);
size_t i = 0;
while(c != '\n' && c != EOF && c != ' ')
{
if((c != '_' && !(c >='A' && c <= 'Z')) || i > 7)
{
if(IsWhitespace(c)) // AT(tab) jako zły numer
{
input_string[i] = '\0';
enum taskType task = DecodeTask(input_string);
switch(task)
{
case DEG_BY:
PrintError(DEG_BY_WRONG_VARIABLE, row_number);
break;
case AT:
PrintError(AT_WRONG_VALUE, row_number);
break;
default:
PrintError(INVALID_COMMAND, row_number);
break;
}
}
else
PrintError(INVALID_COMMAND, row_number);
BAD_INPUT(c);
free(input_string);
return;
}
input_string[i++] = c;
c = fgetc(stdin);
}
ungetc(c, stdin);
input_string[i] = '\0';
enum taskType task = DecodeTask(input_string);
free(input_string);
if(task == __INVALID__)
{
c = fgetc(stdin);
BAD_INPUT(c);
PrintError(INVALID_COMMAND, row_number);
return;
}
if(task == DEG_BY || task == AT || task == COMPOSE)
{
bool success = true;
c = fgetc(stdin);
if(c != ' ')
success = false;
else
{
c = fgetc(stdin);
if((!('0' <= c && c <= '9') && !(c == '-' && task == AT)))
success = false;
else
ungetc(c, stdin);
}
if(!success)
{
BAD_INPUT(c);
switch(task)
{
case DEG_BY:
PrintError(DEG_BY_WRONG_VARIABLE, row_number);
break;
case AT:
PrintError(AT_WRONG_VALUE, row_number);
break;
case COMPOSE:
PrintError(COMPOSE_WRONG_VALUE, row_number);
break;
default:
break;
}
return;
}
}
size_t var_idx;
poly_coeff_t x;
if(task == DEG_BY)
{
if(scanf("%lu", &var_idx) != 1 || errno != 0)
{
BAD_INPUT(c);
PrintError(DEG_BY_WRONG_VARIABLE, row_number);
return;
}
}
else if(task == AT)
{
if(scanf("%ld", &x) != 1 || errno != 0)
{
BAD_INPUT(c);
PrintError(AT_WRONG_VALUE, row_number);
return;
}
}
else if(task == COMPOSE)
{
if(scanf("%lu", &var_idx) != 1 || errno != 0)
{
BAD_INPUT(c);
PrintError(COMPOSE_WRONG_VALUE, row_number);
return;
}
}
c = fgetc(stdin);
if(c != '\n' && c != EOF)
{
BAD_INPUT(c);
switch(task)
{
case DEG_BY:
PrintError(DEG_BY_WRONG_VARIABLE, row_number);
break;
case AT:
PrintError(AT_WRONG_VALUE, row_number);
break;
case COMPOSE:
PrintError(COMPOSE_WRONG_VALUE, row_number);
break;
default:
PrintError(INVALID_COMMAND, row_number);
break;
}
return;
}
ungetc(c, stdin);
switch (task)
{
case ZERO:
TaskZero(stack);
break;
case IS_COEFF:
TaskIsCoeff(stack, row_number);
break;
case IS_ZERO:
TaskIsZero(stack, row_number);
break;
case CLONE:
TaskClone(stack, row_number);
break;
case ADD:
TaskAdd(stack, row_number);
break;
case MUL:
TaskMul(stack, row_number);
break;
case NEG:
TaskNeg(stack, row_number);
break;
case SUB:
TaskSub(stack, row_number);
break;
case IS_EQ:
TaskIsEq(stack, row_number);
break;
case DEG:
TaskDeg(stack, row_number);
break;
case DEG_BY:
TaskDegBy(stack, var_idx, row_number);
break;
case AT:
TaskAt(stack, x, row_number);
break;
case PRINT:
TaskPrint(stack, row_number);
break;
case POP:
TaskPop(stack, row_number);
break;
case COMPOSE:
TaskCompose(stack, var_idx, row_number);
break;
default:
break;
}
}
Poly* ReadPoly()
{
int c = fgetc(stdin);
if(c != '(') // musi zaczynać się ()
{
BAD_INPUT(c);
return NULL;
}
Poly *p = NULL;
c = fgetc(stdin);
if(c != '-' && c != '\n' && c != EOF)
ungetc(c, stdin);
if(c == '(') // jeśli coef to jednomian to wywołujemy się rekurencyjnie
{
p = ReadPoly();
if(p == NULL)
{
BAD_INPUT(c);
return NULL;
}
}
else if(c == '-' || (c >= '0' && c <= '9')) // wczytywanie coeff-a
{
ungetc(c, stdin);
poly_coeff_t coeff = 0;
int success = scanf("%lu", &coeff);
if(success != 1 || errno != 0)
{
if(p)
{
PolyDestroy(p);
free(p);
}
BAD_INPUT(c);
return NULL;
}
p = malloc(sizeof(Poly));
CHECK_PTR(p);
*p = PolyFromCoeff(coeff);
}
else // nie coeff, nie mono to błąd
{
BAD_INPUT(c);
return NULL;
}
c = fgetc(stdin);
Poly *q;
if(c != ',') // następnie musi być przecinek
{
BAD_INPUT(c);
PolyDestroy(p);
free(p);
return NULL;
}
else // wczytywanie wykładnika i tworzenie wielomianu
{
poly_exp_t exp = 0;
int success = scanf("%d", &exp);
if(exp > POLY_EXP_MAX || exp < 0 )
success = 0;
if(success != 1 || errno != 0)
{
PolyDestroy(p);
free(p);
BAD_INPUT(c);
return NULL;
}
if((exp == 0 && PolyIsCoeff(p)) || (PolyIsCoeff(p) && p->coeff == 0))
q = p;
else
{
q = malloc(sizeof(Poly));
CHECK_PTR(q);
Mono m[] = {MonoFromPoly(p, exp)};
*q = PolyAddMonos(1, m);
free(p);
}
}
c = getc(stdin);
if(c != ')') // potem musi być )
{
PolyDestroy(q);
free(q);
BAD_INPUT(c);
return NULL;
}
c = getc(stdin);
if(c == '\n' || c == EOF || c == ',')
{
ungetc(c, stdin);
return q;
}
else if(c == '+') // jeśli + to rekurencyjnie wczytujemy następny i zwracamy sumę
{
p = ReadPoly();
if(p == NULL)
{
PolyDestroy(q);
free(q);
return NULL;
}
Poly *w = malloc(sizeof(Poly));
CHECK_PTR(w);
*w = PolyAdd(p, q);
PolyDestroy(p);
PolyDestroy(q);
free(p);
free(q);
return w;
}
else // nie +, nie koniec lini to błąd
{
BAD_INPUT(c);
PolyDestroy(q);
free(q);
return NULL;
}
}
bool ReadPolyCoeff(Stack *stack)
{
char c;
poly_coeff_t value = 0;
int success = scanf("%ld", &value);
if(success == 1 && errno == 0)
{
c = fgetc(stdin);
if(c != '\n' && c != EOF)
success = false;
ungetc(c, stdin);
}
if(success != 1 || errno != 0)
{
BAD_INPUT(c);
return false;
}
Poly p = PolyFromCoeff(value);
StackAdd(stack, p);
return true;
}
void PrintError(enum errorType error, size_t row_number)
{
switch(error)
{
case STACK_UNDERFLOW:
fprintf(stderr, "ERROR %ld STACK UNDERFLOW\n", row_number);
break;
case INVALID_COMMAND:
fprintf(stderr, "ERROR %ld WRONG COMMAND\n", row_number);
break;
case DEG_BY_WRONG_VARIABLE:
fprintf(stderr, "ERROR %ld DEG BY WRONG VARIABLE\n", row_number);
break;
case AT_WRONG_VALUE:
fprintf(stderr, "ERROR %ld AT WRONG VALUE\n", row_number);
break;
case COMPOSE_WRONG_VALUE:
fprintf(stderr, "ERROR %ld COMPOSE WRONG PARAMETER\n", row_number);
break;
case WRONG_POLY:
fprintf(stderr, "ERROR %ld WRONG POLY\n", row_number);
break;
default:
assert(false);
break;
}
}
|
C
|
//describe taylor series for exp, cos and sin using recursion
#include<stdio.h>
#include<math.h>
int fact(int n){
if (n>0){
return fact(n-1)*n;
}
return 0;
}
double eRec(int x, int n){
static double power=1, factorial=1;
double result;
if (n==0){
return 1;
}else{
result = eRec(x,n-1);
power = power*x;
factorial = factorial*(n);
return result + power/factorial;
}
}
double sinRec(int x, int n){
static double power=1, factorial=1;
int p, f;
double result;
if (n==0){
return x;
}else{
result = sinRec(x,n-1);
f = fact(2*n+1);
power = pow(x,2*n+1);
p = pow(-1,n);
return result + p*(power/f);
}
}
int main(int argc, char const *argv[])
{
printf("%lf\n",eRec(6,20));
printf("%lf\n",sinRec(6,5));
return 0;
}
|
C
|
/* ************************************************************************** */
/* LE - / */
/* / */
/* mainval.c .:: .:/ . .:: */
/* +:+:+ +: +: +:+:+ */
/* By: jacens <jacens@student.le-101.fr> +:+ +: +: +:+ */
/* #+# #+ #+ #+# */
/* Created: 2019/12/17 15:45:03 by vroth-di #+# ## ## #+# */
/* Updated: 2020/01/18 20:18:36 by jacens ### #+. /#+ ###.fr */
/* / */
/* / */
/* ************************************************************************** */
#include "main.h"
t_list *ft_lstnew(void *content)
{
t_list *list;
list = malloc(sizeof(*list));
if (list == NULL)
return (NULL);
list->data = content;
list->next = NULL;
return (list);
}
void ft_lstclear(t_list **lst)
{
t_list *tmp;
if (!lst)
return ;
while (*lst)
{
tmp = *lst;
free(tmp->data);
*lst = tmp->next;
free(tmp);
}
*lst = NULL;
}
void ft_lstadd_back(t_list **alst, t_list *new)
{
t_list *tmp;
if (!alst || !new)
return ;
if (!(*alst))
{
new->next = NULL;
*alst = new;
return ;
}
tmp = *alst;
while (tmp->next != NULL)
tmp = tmp->next;
tmp->next = new;
}
int ft_lstsize(t_list *lst)
{
int size;
size = 0;
if (lst == NULL)
return (size);
while (lst != NULL)
{
size++;
lst = lst->next;
}
return (size);
}
int main()
{
int fd = open("text.txt", O_RDONLY);
char *buffer = calloc(sizeof(char), 100);
printf("\n~ Test write ~\n");
int p = ft_write(1, "bonjour", 7);
printf("\nret write-> %d", p);
printf("\n\n~ Test read ~\n");
p = ft_read(fd, buffer, 1000);
printf("Retour read-> %d", p);
printf("\n%s", buffer);
printf("\n~Test strlen~\n");
printf("%lu\n", ft_strlen(buffer));
char *s1 = strdup("Si au bout de cette phrase il y a un point, ceci est strcpy valide.");
char s2[100];
printf("\n~Test strcpy~\n");
printf("%s\n", ft_strcpy(s2, s1));
free(s1);
const char *s3 = "bonjour, ceci est un strdup";
printf("\n~Test strdup~\n");
char *s4 = ft_strdup((char*)s3);
printf("%s\n", s4);
free(s4);
printf("\n~Test strcmp~\n");
s3 = strdup("oOoOoOoOoOoOoOo");
const char *s5 = strdup("oOoOoOoOoOoOoOo");
printf("%d", strcmp(s3, s5));
printf(" | %d\n", ft_strcmp(s3, s5));
t_list **deb;
t_list *first;
t_list *second;
t_list *third;
t_list *fourth;
printf("\n~Test list_size~\n");
if (!(deb = malloc(sizeof(t_list**))))
return (0);
first = ft_lstnew(strdup("bonjour"));
second = ft_lstnew(strdup("good morming"));
third = ft_lstnew(strdup("guten tag"));
fourth = ft_lstnew(strdup("buongiorno"));
*deb = first;
ft_lstadd_back(deb, second);
ft_lstadd_back(deb, third);
ft_lstadd_back(deb, fourth);
printf("%d\n", ft_list_size(*deb));
printf("\n~Test ft_print_data~\n");
ft_print_data(*deb);
printf("\n~Test list_push_front~\n");
ft_list_push_front(deb, strdup("ola"));
ft_print_data(*deb);
// printf("\n~Test list_remove_if~\n");
// ft_list_remove_if(deb, "bonjour", &strcmp, &free);
// ft_print_data(*deb);
// printf("\n~Test list_sort~\n");
// printf("\n~Avant~\n");
// ft_print_data(*deb);
// printf("\n~Apres~\n");
// ft_list_sort(deb, &strcmp);
// ft_print_data(*deb);
printf("\n~Test atoi_base~\n");
p = ft_atoi_base("12345", "0e3456789abcd1f");
printf("%d\n", p);
// free((char*)s3);
// free((char*)s5);
// free(buffer);
// ft_lstclear(deb);
free(deb);
close(fd);
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cs50.h>
#include <math.h>
#include <ctype.h>
int main(int argc, string argv[])
{
int argvToInt = atoi(argv[1]);
if (argc > 2)
{
printf("Usage: ./caesar key\n");
}
if (strlen(argv[1]) == 0)
{
printf("Usage: ./caesar key\n");
}
int failureCounter = 0;
for (int i = 0, n = strlen(argv[1]); i < n; i++)
{
if (isalpha(argv[1][i]) || ispunct(argv[1][i]))
{
failureCounter++;
}
}
if (failureCounter > 0)
{
printf("Usage: ./caesar key\n");
return 1;
}
string plaintext = get_string("plaintext: ");
char ciphertext[strlen(plaintext)];
for (int i = 0, n = strlen(plaintext); i < n; i++)
{
if (isupper(plaintext[i]))
{
int currentLetter = (int) plaintext[i];
int newLetter = 0;
newLetter = (currentLetter + newLetter) % 26;
ciphertext[i] = (char) newLetter;
}
else if (islower(plaintext[i]))
{
int currentLetter = (int) plaintext[i];
int newLetter = 0;
newLetter = (currentLetter + newLetter) % 26;
ciphertext[i] = (char) newLetter;
}
else if (plaintext[i] == ' ')
{
ciphertext[i] = ' ';
}
}
printf("ciphertext: ");
for (int i = 0, n = strlen(plaintext); i < n; i++)
{
printf("%c", ciphertext[i]);
}
printf("\n");
return 0;
}
|
C
|
#include <setjmp.h> /* jmp_buf */
/*****************************************************************************
To use setjmp() and longjmp() for asynchronous (interrupt-driven;
pre-emptive) task-switching, we want to enable interrupts simultaneous
with jumping to the task. In other words, we want the EFLAGS and EIP
registers loaded at the same time.
The only instruction that can do this is IRET, which also loads the CS
register. Changing CS is done in code that uses far pointers, and it's
also done when changing address spaces, and when changing privilege levels.
We're not interested in any of those, so just push the current CS value
on the stack and let IRET use that.
Three distinct stack pointer (ESP) values are used in this routine:
- 'Old' or 'current' stack pointer value, which is discarded by
this routine (use setjmp() to save it)
- ESP is made to point, briefly, to the jmp_buf struct itself
- 'New' ESP value; stored in jmp_buf.esp
Register values are restored from the jmp_buf as follows:
1. Push jmp_buf.eflags, the current CS value, and jmp_buf.eip
onto the 'new' stack
2. Make ESP point to the jmp_buf struct itself, then use the POPA
instruction to pop the 7 general purpose registers (ESP is not
loaded by POPA). The use of POPA means that registers in the
jmp_buf MUST be stored in the order that POPA expects.
(Maybe use MOVs instead, to eliminate this restriction?
Might have to rewrite entire function in asm, instead of C.)
3. Load ESP with the 'new' stack pointer, from jmp_buf.esp
4. Use IRET to pop EIP, CS, and EFLAGS from the 'new' stack
5. ???
6. Profit! <--- obligatory Slashdot joke
This code does NOT save the floating-point state of the CPU. Either:
1. Don't use floating point, or
2. Don't use floating point in more than one thread, or
3. Rewrite this code so it DOES save the floating-point state, or
4. Save/restore the floating-point state when entering/leaving
the kernel (protected OS only)
*****************************************************************************/
void longjmp(jmp_buf buf, int ret_val)
{
unsigned *esp;
/* make sure return value is not 0 */
if(ret_val == 0)
ret_val++;
/* EAX is used for return values, so store it in jmp_buf.EAX */
buf->eax = ret_val;
/* get ESP for new stack */
esp = (unsigned *)buf->esp;
/* push EFLAGS on the new stack */
esp--;
*esp = buf->eflags;
/* push current CS on the new stack */
esp--;
__asm__ __volatile__(
"mov %%cs,%0\n"
: "=m"(*esp));
/* push EIP on the new stack */
esp--;
*esp = buf->eip;
/* new ESP is 12 bytes lower; update jmp_buf.ESP */
buf->esp = (unsigned)esp;
/* now, briefly, make the jmp_buf struct our stack */
__asm__ __volatile__(
"movl %0,%%esp\n"
/* ESP now points to 8 general-purpose registers stored in jmp_buf
Pop them */
"popa\n"
/* load new stack pointer from jmp_buf */
"movl -20(%%esp),%%esp\n"
/* ESP now points to new stack, with the IRET frame (EIP, CS, EFLAGS)
we created just above. Pop these registers: */
"iret\n"
:
: "m"(buf));
}
|
C
|
#include "../shell.h"
#include "commands.h"
int jobs(char* words[] , int word_count){
if(word_count > 2){
printf("jobs : argument error");
return 1;
}
int s_flag = 0;
int r_flag = 0;
int indices[100];
for (int j=0;j<100;j++)
{
indices[j] = j;
}
if(word_count == 2){
if(words[1][0] == '-')
{
if(words[1][1] == 's'){
s_flag = 1;
}
else if(words[1][1] == 'r'){
r_flag = 1;
}
else{
printf("\njobs: invalid flag");
}
}
else{
printf("\njobs: invalid argument");
}
}
int statuses[100] = {0};
for(int i = 0; i < total_children_bg - 1; i++){
for(int j = i + 1; j < total_children_bg; j++){
int x = strcmp(cp[indices[i]].childname, cp[indices[j]].childname );
if(x > 0){
int temp = indices[i];
indices[i] = indices[j];
indices[j] = temp;
}
}
}
// for(int i = 0; i < total_children_bg; i++){
// printf("\n index chk : %d", indices[i]);
// }
for(int i = 0; i < total_children_bg; i++){
// printf("\nlol : %d", indices[i]);
pid_t pid = cp[indices[i]].child_id;
char* proc_path = (char *) malloc (100);
sprintf(proc_path,"/proc/%d/stat", pid);
FILE* process_info;
process_info = fopen(proc_path, "r");
char* full_proc_info = (char *) malloc (INP_SIZE);
// printf("\nlol 1 : %d", indices[i]);
fread(full_proc_info, INP_SIZE, 1, process_info);
char* file_stats[100] = {NULL};
int k=0;
file_stats[k] = strtok(full_proc_info, " ");
while(file_stats[k]){
file_stats[++k] = strtok(NULL, " ");
}
// printf("\nlol 2 : %d", indices[i]);
if(file_stats[2][0] == 'S') {
statuses[i] = 1;
cp[indices[i]].status = 1;
} else{
cp[indices[i]].status = 0;
}
fclose(process_info);
free(proc_path);
// printf("\nlol 3 : %d", indices[i]);
// printf("\n in jobs: %s %d %d",cp[indices[i]].childname,cp[indices[i]].child_id, indices[i] );
if (r_flag == 0 && s_flag == 0){
printf("\n[%d] %s %s [%d]",indices[i] + 1,(cp[indices[i]].status == 1)?"Running":"Stopped", cp[indices[i]].childname , cp[indices[i]].child_id );
}
else if(r_flag == 1){
if(cp[indices[i]].status == 1){
printf("\n%s %s [%d]",(cp[indices[i]].status == 1)?"Running":"Stopped", cp[indices[i]].childname , cp[indices[i]].child_id );
}
}
else if(s_flag == 1){
if(cp[indices[i]].status == 0){
printf("\n%s %s [%d]",(cp[indices[i]].status == 1)?"Running":"Stopped", cp[indices[i]].childname , cp[indices[i]].child_id );
}
}
}
// for(int i = 0; i < total_children_bg; i++){
// printf("\nlol : %d", indices[i]);
// }
return 0;
}
|
C
|
#include "cdfs.h"
/*
* Serial port handling code
*/
void serial_init(int baudrate)
{
volatile unsigned char *s = (unsigned char *)(void *)0xffe80000;
*((volatile unsigned short *)(s+8)) = 0;
*((volatile unsigned short *)(s)) = 0;
s[4] = 50000000/(32*baudrate)-1;
*((volatile unsigned short *)(s+24)) = 12;
*((volatile unsigned short *)(s+24)) = 8;
*((volatile unsigned short *)(s+32)) = 0;
*((volatile unsigned short *)(s+16)) = 0x60;
*((volatile unsigned short *)(s+36)) = 0;
*((volatile unsigned short *)(s+8)) = 0x30;
}
void send(unsigned char c)
{
volatile unsigned char *s = (unsigned char *)(void *)0xffe8000c;
int v;
while(!((v=((volatile unsigned short *)s)[2]) & 0x20));
*s = c;
((volatile unsigned short *)s)[2] = v & 0x9f;
}
void flush()
{
volatile unsigned short *s = (unsigned short *)(void *)0xffe80010;
int v;
*s &= 0xbf;
while(!((v=*s) & 0x40));
*s = v & 0xbf;
}
void sendstr(char *str)
{
while(*str++)
send(((unsigned char *)str)[-1]);
}
void sendnum(int n)
{
char buf[16], *p;
if(n<0) {
send('-');
n = -n;
}
p=buf+16;
*--p = '\0';
do {
*--p = '0'+(n%10);
n /= 10;
} while(n);
sendstr(p);
}
/* Dummy stub to make libgcc happy... */
void atexit() { }
/*
* Simple demo program.
* Displays the root directory and the contents of READ_ME.TXT
* on the serial port.
*
*/
int main()
{
int fd;
DIR *d;
serial_init(57600);
/*
* First, cdfs_init() has to be called to reactivate the drive and
* initialize the GDROM syscalls
*/
cdfs_init();
/*
* Print the contents of the root directory
*/
d = opendir("/");
if(!d)
sendstr("opendir failed.\r\n");
else {
struct dirent *de;
while((de = readdir(d))) {
/* Found an entry */
if(de->d_size < 0) {
sendstr(" DIR: ");
sendstr(de->d_name);
sendstr("\n");
} else {
sendstr("FILE: ");
sendstr(de->d_name);
sendstr(" : ");
sendnum(de->d_size);
sendstr(" bytes\r\n");
}
}
/* End of dir */
closedir(d);
}
/*
* Print the contents of READ_ME.TXT
*/
fd = open("READ_ME.TXT", O_RDONLY);
if(fd<0)
sendstr("File not found.\r\n");
else {
static char buf[2048];
int i, r;
/* Read 2048 bytes at a time and display them */
while((r = read(fd, buf, sizeof(buf)))>0)
for(i=0; i<r; i++)
send(buf[i]);
/* Error or EOF reached */
if(r<0)
sendstr("ERROR!\r\n");
close(fd);
}
flush();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
#include "/usr/include/mysql/mysql.h"
#define PORT 9190
#define DBID "pi"
#define DBPW "1"
#define DBADR "localhost"
#define DBNAME "TEST_DB"
#define BUF_SIZE 2048
#define QUERY_BUF_SIZE 1024
#define MAX_CLNT 256
MYSQL *conn_ptr;
MYSQL_RES *res;
void *handle_clnt(void * arg); // Լ
void send_msg(); // Ȯ Լ
void error_handling(char * msg); // ó
int clnt_cnt=0;
int clnt_socks[MAX_CLNT];
pthread_mutex_t mutx;
struct AcInfomation{
char ID[45];
char Name[45];
char Phon[45];
char Carinfor[45];
char X[45];
char Y[45];
char Time[45];
};
int main(){
int serv_sock, clnt_sock;
struct sockaddr_in serv_adr, clnt_adr;
int clnt_adr_sz;
pthread_t t_id;
conn_ptr = mysql_init(NULL);
if(!conn_ptr){
fprintf(stderr,"mysql_init failed\n");
exit(1);
}
conn_ptr = mysql_real_connect(conn_ptr,DBADR,DBID,DBPW,DBNAME,0,NULL,0);
if(conn_ptr)
printf("DB connection success\n");
else
printf("DB connection failed\n");
pthread_mutex_init(&mutx, NULL);
serv_sock=socket(PF_INET, SOCK_STREAM, 0);
memset(&serv_adr, 0, sizeof(serv_adr));
serv_adr.sin_family=AF_INET;
serv_adr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_adr.sin_port=htons(PORT);
if(bind(serv_sock, (struct sockaddr*) &serv_adr, sizeof(serv_adr))==-1)
error_handling("bind() error");
if(listen(serv_sock, 5)==-1)
error_handling("listen() error");
while(1){
clnt_adr_sz=sizeof(clnt_adr);
clnt_sock=accept(serv_sock, (struct sockaddr*)&clnt_adr,&clnt_adr_sz);
pthread_mutex_lock(&mutx);
clnt_socks[clnt_cnt++]=clnt_sock;
pthread_mutex_unlock(&mutx);
pthread_create(&t_id, NULL, handle_clnt, (void*)&clnt_sock);
pthread_join(t_id,NULL);
printf("Connected client IP: %s \n", inet_ntoa(clnt_adr.sin_addr));
}
mysql_close(conn_ptr);
close(serv_sock);
return 0;
}
void * handle_clnt(void * arg){
int clnt_sock=*((int*)arg);
int str_len=0, i;
char msg[BUF_SIZE];
char query[QUERY_BUF_SIZE];
struct AcInfomation *Na;
while((str_len=read(clnt_sock, msg, sizeof(msg)))!=0) // ۹ ü
send_msg();
pthread_mutex_lock(&mutx); // ȭ
Na = (struct AcInfomation*)msg; // ü
sprintf(query,"INSERT INTO USER_CAR VALUES ('%s','%s','%s','%s','%s','%s','%s')",Na->ID,Na->Name,Na->Phon,Na->Carinfor,Na->X,Na->Y,Na->Time);
mysql_query(conn_ptr,query); // DB Է
res = mysql_use_result(conn_ptr);
for(i=0; i<clnt_cnt; i++){ // ŵ Ŭ̾Ʈ
if(clnt_sock==clnt_socks[i]){
while(i++<clnt_cnt-1)
clnt_socks[i]=clnt_socks[i+1];
break;
}
}
clnt_cnt--;
mysql_free_result(res);
pthread_mutex_unlock(&mutx);
close(clnt_sock);
return NULL;
}
void send_msg(){ // Ȯι
int i;
char ACK[25] = {"DATA Transfer Sucess!"};
pthread_mutex_lock(&mutx);
for(i=0; i<clnt_cnt; i++)
write(clnt_socks[i], ACK, strlen(ACK));
pthread_mutex_unlock(&mutx);
}
void error_handling(char * msg){
fputs(msg, stderr);
fputc('\n', stderr);
exit(1);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int arrA[] = { 4, 2, 5, 6};
int arrB[10];
// n : 복사할 인덱스 번호, k: 원소개수
void arrCopy(int n, int k);
int main(int argc, char *argv[]) {
int size = sizeof(arrA)/sizeof(arrA[0]);
int i;
//int size = sizeof(arrA)/sizeof(int);
arrCopy( 0, size);
for(i = 0; i<size;i++)
{
printf("%d ", arrB[i]);
}
return 0;
}
void arrCopy(int n, int k)
{
if(n==k)
{
return;
}
else
{
arrB[n] = arrA[n];
arrCopy(n+1,k);
return;
}
}
|
C
|
// The following Code is a demonstration purpose of Priority Inversion During V&V CEP 9/07/12
// // // Most of the code is written intentional to only demonstrate the purpose , don't try to use as it is
// // // Author V&V Team
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <assert.h>
#include <stdlib.h>
int main(int argc,char *argv[]) {
int z;
int fd;
char buf[256];
fd = open("fifo1",O_RDWR|O_NONBLOCK);
if(fd == -1) {
printf("Unable to Open File \n");
perror("Reason: ");
exit(1);
}
while((z=read(fd,buf,sizeof(buf)) <=0));
if( z >= 0 ) {
printf("Number of Characters are ready = %d \n",z);
printf("Input = %s \n",buf);
}
}
|
C
|
#include <stdio.h>
struct youli
{
double rose;
double baby;
};
int main()
{
struct youli a1, a2, res;
scanf("%lf %lf %lf %lf", &a1.rose, &a1.baby, &a2.rose, &a2.baby);
res.rose = a1.rose + a2.rose;
res.baby = a1.baby + a2.baby;
if (res.rose < 0.05)
res.rose = 0;
else if (res.baby < 0.05)
res.baby = 0;
printf("(%.1lf, %.1lf)\n", res.rose, res.baby);
return 0;
}
// #include<stdio.h>
// #include<math.h>
// int main()
// {
// double x1,y1,x2,y2,x,y;
// scanf("%lf %lf %lf %lf",&x1,&y1,&x2,&y2);
// x=x1+x2;
// y=y1+y2;
// if(fabs(x)<0.05)
// x=0;
// if(fabs(y)<0.05)
// y=0;
// printf("��%.1lf, %.1lf��\n",x,y);
// return 0;
// }
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* displacement.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: luperez <luperez@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/02/27 23:57:31 by luperez #+# #+# */
/* Updated: 2015/02/28 05:00:10 by luperez ### ########.fr */
/* */
/* ************************************************************************** */
#include "game_2048.h"
short move_left(t_game *g)
{
short have_move;
short merge;
int x;
int y;
have_move = 0;
y = -1;
while (g->tiles[++y])
{
merge = 0;
x = g->tile_size;
while (--x != -1 && g->tiles[y][x])
{
if (g->tiles[y][x]->value < 1 || x == 0 || !g->tiles[y][x - 1])
continue;
if (g->tiles[y][x - 1]->value > 0 && merge)
continue ;
have_move = 1;
if (g->tiles[y][x - 1]->value == 0)
{
g->tiles[y][x - 1]->value = g->tiles[y][x]->value;
g->tiles[y][x]->value = 0;
}
else if (g->tiles[y][x]->value == g->tiles[y][x - 1]->value)
{
g->tiles[y][x - 1]->value *= 2;
g->tiles[y][x]->value = 0;
merge = 1;
}
}
}
return (have_move);
}
short move_right(t_game *g)
{
short have_move;
short merge;
int x;
int y;
have_move = 0;
y = -1;
while (g->tiles[++y])
{
merge = 0;
x = -1;
while (g->tiles[y][++x])
{
if (g->tiles[y][x]->value < 1 || !g->tiles[y][x + 1])
continue;
if (g->tiles[y][x + 1]->value > 0 && merge)
continue ;
have_move = 1;
if (g->tiles[y][x + 1]->value == 0)
{
g->tiles[y][x + 1]->value = g->tiles[y][x]->value;
g->tiles[y][x]->value = 0;
}
else if (g->tiles[y][x + 1]->value == g->tiles[y][x]->value)
{
g->tiles[y][x + 1]->value *= 2;
g->tiles[y][x]->value = 0;
merge = 1;
}
}
}
return (have_move);
}
short move_up(t_game *g)
{
short have_move;
short merge;
int x;
int y;
have_move = 0;
x = -1;
while (g->tiles[0][++x])
{
merge = 0;
y = g->tile_size;
while (--y != -1 && g->tiles[y][x])
{
if (g->tiles[y][x]->value < 1 || y == 0 || !g->tiles[y - 1][x])
continue;
if (g->tiles[y - 1][x]->value > 0 && merge)
continue ;
have_move = 1;
if (g->tiles[y - 1][x]->value == 0)
{
g->tiles[y - 1][x]->value = g->tiles[y][x]->value;
g->tiles[y][x]->value = 0;
}
else if (g->tiles[y - 1][x]->value == g->tiles[y][x]->value)
{
g->tiles[y - 1][x]->value *= 2;
g->tiles[y][x]->value = 0;
merge = 1;
}
}
}
return (have_move);
}
short move_down(t_game *g)
{
short have_move;
short merge;
int x;
int y;
have_move = 0;
x = -1;
while (g->tiles[0][++x])
{
merge = 0;
y = -1;
while (g->tiles[++y] && g->tiles[y][x])
{
if (g->tiles[y][x]->value < 1 || !g->tiles[y + 1] || !g->tiles[y + 1][x])
continue;
if (g->tiles[y + 1][x]->value > 0 && merge)
continue ;
have_move = 1;
if (g->tiles[y + 1][x]->value == 0)
{
g->tiles[y + 1][x]->value = g->tiles[y][x]->value;
g->tiles[y][x]->value = 0;
}
else if (g->tiles[y + 1][x]->value == g->tiles[y][x]->value)
{
g->tiles[y + 1][x]->value *= 2;
g->tiles[y][x]->value = 0;
merge = 1;
}
}
}
return (have_move);
}
t_tile *take_n_empty(t_game *g, int n)
{
int i;
int x;
int y;
i = 0;
y = -1;
while (g->tiles[++y])
{
x = -1;
while (g->tiles[y][++x])
{
if (g->tiles[y][x]->value < 1)
i++;
if (n == i)
return (g->tiles[y][x]);
}
}
return (NULL);
}
int count_empty_tiles(t_game *g)
{
int i;
int x;
int y;
i = 0;
y = -1;
while (g->tiles[++y])
{
x = -1;
while (g->tiles[y][++x])
{
if (g->tiles[y][x]->value < 1)
i++;
else if (g->tiles[y][x]->value > WIN_VALUE)
{
ft_putstr("\nYou win.");
ft_error("\nYou win.");
}
}
}
return (i);
}
void gen_num(t_game *g)
{
t_tile *target;
int empty;
time_t t;
ft_putstrerrno("\n\n !! Gen ennemy\n");
if ((empty = count_empty_tiles(g)) < 2)
{
ft_putstr("\nYou loose.");
ft_error("\nYou loose.");
}
srand((unsigned) time(&t));
empty = rand() % empty;
if ((target = take_n_empty(g, empty)))
target->value = 2;
ft_putstrerrno("\n\n !! End gen ennemy\n");
}
void displacement(t_game *g, int c)
{
short have_move;
have_move = 0;
if (c == KEY_LEFT)
{
ft_putstrerrno("\n\n == KEY_LEFT\n");
have_move = move_left(g);
}
else if (c == KEY_RIGHT)
{
ft_putstrerrno("\n\n == KEY_RIGHT\n");
have_move = move_right(g);
}
else if (c == KEY_UP)
{
ft_putstrerrno("\n\n == KEY_UP\n");
have_move = move_up(g);
}
else if (c == KEY_DOWN)
{
ft_putstrerrno("\n\n == KEY_DOWN\n");
have_move = move_down(g);
}
redraw(g);
resize(g);
if (have_move)
gen_num(g);
redraw(g);
}
|
C
|
int a[8] = {8, 9, 11, 89, 1278, 76, 88, 52};
static void print_array(int a[], int lengh)
{
int index;
printf("###################\n");
for(index = 0; index < lengh; index++)
{
printf("%d\n", a[index]);
}
printf("###################\n");
}
|
C
|
#include "../inc/libmx.h"
static int indexChar(char *a, char b) {
char *r = mx_strchr(a, b);
return r - a;
}
int mx_read_line(char **lineptr, size_t buf_size, char delim, const int fd) {
char *buff = (char *)malloc(buf_size + 1);
int bytes;
while ((bytes = read(fd, buff, buf_size)) > 0) {
int position = indexChar(buff, delim);
if (position >= 0) {
char* substr = malloc(position);
mx_strncpy(substr, buff, position);
*lineptr = (char*)realloc(*lineptr, mx_strlen(*lineptr) + position + 1);
mx_strcat(*lineptr, substr);
return mx_strlen(*lineptr);
}
buff[mx_strlen(buff)] = '\0';
*lineptr = (char*)realloc(*lineptr, buf_size);
mx_strcat(*lineptr, buff);
}
if(bytes < 0 ) return -1;
free(buff);
return mx_strlen(*lineptr);
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(){
char str[1000001];
char* tok;
int cnt=0;
scanf("%[^\n]s", str);
tok = strtok(str," ");
while(tok != NULL){
cnt++;
tok = strtok(NULL, " ");
}
printf("%d", cnt);
return 0;
}
|
C
|
/* GROUP 48:
PUNEET ANAND 2016B4A70487P
MAYANK JASORIA 2016B1A70703P
SHUBHAM TIWARI 2016B4A70935P
VIBHAV OSWAL 2016B4A70594P */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "data_structures/st.h"
#include "data_structures/ast.h"
#include "codeGen.h"
#include "codeGenDef.h"
// void rte(/* char* errorMsg */) {
// fprintf(fp, "; --- START: rte() --- \n");
// /**
// * TODO: Print error message
// * RUN TIME ERROR: Array index out of bound
// */
// fprintf(fp, "\tmov ebx, 0 ;return 0 status on exit - 'No errors'\n");
// fprintf(fp, "\tmov eax, 1 ;invoke SYS_EXIT system call (kernel opcode 1)\n");
// fprintf(fp, "\tint 80h ;generate interrupt\n");
// fprintf(fp, "; --- END: rte() --- \n");
// }
void emitCodeInit(const char* fname) {
/* Open fname */
fp = fopen(fname, "w");
}
void pushRegs() {
fprintf(fp, "\tpush r10\n");
fprintf(fp, "\tpush r11\n");
fprintf(fp, "\tpush rsi\n");
fprintf(fp, "\tpush rdx\n");
fprintf(fp, "\tpush rcx\n");
fprintf(fp, "\tpush r8\n");
fprintf(fp, "\tpush r9\n");
fprintf(fp, "\tpush rax\n");
}
void popRegs() {
fprintf(fp, "\tpop rax\n");
fprintf(fp, "\tpop r9\n");
fprintf(fp, "\tpop r8\n");
fprintf(fp, "\tpop rcx\n");
fprintf(fp, "\tpop rdx\n");
fprintf(fp, "\tpop rsi\n");
fprintf(fp, "\tpop r11\n");
fprintf(fp, "\tpop r10\n");
}
void alignStack() {
pushRegs();
fprintf(fp, "; --- START: ALIGN STACK---\n");
fprintf(fp, "\tmov qword [rspreserve], rsp\n");
fprintf(fp, "\tand rsp, 0xfffffffffffffff0\n");
fprintf(fp, "\tsub rsp, 10000B\n");
fprintf(fp, "; --- END: ALIGN STACK ---\n");
}
void getBackStack() {
fprintf(fp, "\tmov rsp, qword [rspreserve]\n");
popRegs();
}
void emitCodeFinalize() {
fprintf(fp, "rte:\n");
fprintf(fp, "\tmov ebx, 0 ;return 0 status on exit - 'No errors'\n");
fprintf(fp, "\tmov eax, 1 ;invoke SYS_EXIT system call (kernel opcode 1)\n");
fprintf(fp, "\tint 80h ;generate interrupt\n");
fprintf(fp, "\noob:\n");
fprintf(fp, "\tpush rbp\n");
fprintf(fp, "\tmov rdi, rte_oob\n");
alignStack();
fprintf(fp, "\tcall printf\n");
getBackStack();
fprintf(fp, "\tpop rbp\n");
fprintf(fp, "\tjmp rte\n");
fprintf(fp, "\ntypeError:\n");
fprintf(fp, "\tpush rbp\n");
fprintf(fp, "\tmov rdi, rte_type\n");
alignStack();
fprintf(fp, "\tcall printf\n");
getBackStack();
fprintf(fp, "\tpop rbp\n");
fprintf(fp, "\tjmp rte\n");
fprintf(fp, "\nparam:\n");
fprintf(fp, "\tpush rbp\n");
fprintf(fp, "\tmov rdi, rte_param\n");
alignStack();
fprintf(fp, "\tcall printf\n");
getBackStack();
fprintf(fp, "\tpop rbp\n");
fprintf(fp, "\tjmp rte\n");
fprintf(fp, "\ninvalidbounds:\n");
fprintf(fp, "\tpush rbp\n");
fprintf(fp, "\tmov rdi, rte_invalidbounds\n");
alignStack();
fprintf(fp, "\tcall printf\n");
getBackStack();
fprintf(fp, "\tpop rbp\n");
fprintf(fp, "\tjmp rte\n");
fprintf(fp, "\ndivisionby0:\n");
fprintf(fp, "\tpush rbp\n");
fprintf(fp, "\tmov rdi, rte_divisionby0\n");
alignStack();
fprintf(fp, "\tcall printf\n");
getBackStack();
fprintf(fp, "\tpop rbp\n");
fprintf(fp, "\tjmp rte\n");
if (fp) {
fclose(fp);
fp = NULL;
}
}
void emitCodeChildren(ASTNode * head, char * fname) {
ASTNode* ch = head;
while(ch != NULL) {
emitCodeAST(ch, fname);
ch = ch -> next;
}
}
void asmComment(char * str) {
fprintf(fp, "\n; ### %s ### \n", str);
}
int getLastCaseLabel(ASTNode * curr) {
ASTNode * tmp = curr -> child -> next;
while(tmp -> child -> next -> next != NULL) {
tmp = tmp -> child -> next -> next;
}
return tmp -> nodeData.caseStmt -> lastLabel;
}
// void rte(char * str, int line_num) {
// fprintf(fp, "\tpush rbp\n");
// fprintf(fp, "\tmov rdi, %s\n", str);
// fprintf(fp, "\tmov si, %dd\n", line_num);
// alignStack();
// fprintf(fp, "\tcall printf\n");
// getBackStack();
// fprintf(fp, "\tpop rbp\n");
// fprintf(fp, "\tjmp rte\n");
// }
int getIDOffset(ASTNode * idNode) {
SymTableVar * tmp = fetchVarData(idNode -> parent -> localST, idNode -> nodeData.leaf -> tn -> lex, idNode -> nodeData.leaf -> tn -> line_num);
return tmp -> offset;
}
/**
* Returns temporary offset of the node in the expression
*/
int getExprOffset(ASTNode * expr) {
if(expr -> type == AST_NODE_LEAF)
return expr -> nodeData.leaf -> temporaryOffset;
else if(expr -> type == AST_NODE_VARIDNUM)
return expr -> nodeData.var -> temporaryOffset;
else if(expr -> type == AST_NODE_AOBEXPR)
return expr -> nodeData.AOBExpr -> temporaryOffset;
else if(expr -> type == AST_NODE_UNARY)
return expr -> nodeData.unary -> temporaryOffset;
}
/**
* Populates r10w : left index
* r11w : right index
*/
void getLeftRightIndex(SymTableVar * id) {
SymTableFunc * local = id -> table;
SymTableFunc * func = getParentFunc(local);
if(id -> offset < func -> inputSize) {
int lft, right;
int offset = id -> offset;
if(strcmp(id -> sdt.r -> lowId, "") == 0) {
lft = id -> sdt.r -> low;
fprintf(fp, "\tmov r10w, %dd\n", lft);
}
else {
fprintf(fp, "\tmov rax, rbp\n");
fprintf(fp, "\tsub rax, %dd\n", offset + typeSize[AST_TYPE_POINTER] + typeSize[AST_TYPE_INT]);
fprintf(fp, "\tmov r10w, word [rax]\n");
}
if(strcmp(id -> sdt.r -> highId, "") == 0) {
right = id -> sdt.r -> high;
fprintf(fp, "\tmov r11w, %dd\n", right);
}
else {
fprintf(fp, "\tmov rax, rbp\n");
fprintf(fp, "\tsub rax, %dd\n", offset + typeSize[AST_TYPE_POINTER] + 2*typeSize[AST_TYPE_INT]);
fprintf(fp, "\tmov r11w, word [rax]\n");
}
return;
}
fprintf(fp, "; --- START: get left and right index of %s ---\n", id->name);
int lft, right;
if(strcmp(id -> sdt.r -> lowId, "") == 0) {
lft = id -> sdt.r -> low;
fprintf(fp, "\tmov r10w, %dd\n", lft);
}
else {
SymTableVar * l = fetchVarData(id -> table, id -> sdt.r -> lowId, id -> declarationLine);
fprintf(fp, "\tmov rax, rbp\n");
fprintf(fp, "\tsub rax, %dd\n", typeSize[AST_TYPE_INT] + l -> offset);
fprintf(fp, "\tmov r10w, word[rax]\n");
}
if(strcmp(id -> sdt.r -> highId, "") == 0) {
right = id -> sdt.r -> high;
fprintf(fp, "\tmov r11w, %dd\n", right);
}
else {
SymTableVar * r = fetchVarData(id -> table, id -> sdt.r -> highId, id -> declarationLine);
fprintf(fp, "\tmov rax, rbp\n");
fprintf(fp, "\tsub rax, %dd\n", typeSize[AST_TYPE_INT] + r -> offset);
fprintf(fp, "\tmov r11w, word[rax]\n");
}
fprintf(fp, "; --- END: got left and right index of %s in r10w and r11w --- \n", id->name);
}
void getInputElement(astDataType t) {
fprintf(fp, "; START: --- getInputElement() ---\n");
fprintf(fp, "\tpush rbp\n");
if(t == AST_TYPE_INT)
fprintf(fp, "\tmov rdi, fmt_int\n");
else if(t == AST_TYPE_REAL)
fprintf(fp, "\tmov rdi, fmt_float\n");
else if(t == AST_TYPE_BOOLEAN)
fprintf(fp, "\tmov rdi, fmt_bool\n");
fprintf(fp, "\tmov rax, rbp\n");
fprintf(fp, "\tsub rax, r9\n");
fprintf(fp, "\tmov rsi, rax\n");
alignStack();
fprintf(fp, "\tcall scanf\n");
getBackStack();
fprintf(fp, "\tpop rbp\n");
fprintf(fp, "; --- END: getInputElement() --- \n");
}
/**
* r9 <- offset relative to base address of array, the offset, base address rdx
* @param arr AST node of the array
* @param index AST Node specifying index
*/
void fetchArraybyIndex(ASTNode * arr, ASTNode * index) {
fprintf(fp, "; --- START: fetchArraybyIndex() for array %s: base: rdx, offset: r9 --- \n", arr -> nodeData.leaf -> tn -> lex);
/* Array index */
ASTNode * i = index;
/* Fetch array from symbol table */
SymTableVar * id = fetchVarData(arr -> parent -> localST, arr -> nodeData.leaf -> tn -> lex, arr -> nodeData.leaf -> tn -> line_num);
/* DataType of elements of array */
astDataType type = id -> sdt.r -> dataType;
int offset = id -> offset;
int idx;
/* store the value of the index in r8w */
if(i -> nodeData.leaf -> type == AST_LEAF_IDXNUM) {
/* index is of type NUM */
idx = i -> nodeData.leaf -> tn -> value.val_int;
fprintf(fp, "\tmov r8w, %dd\n", idx);
}
else {
/* index is of type ID */
SymTableVar * tmp = fetchVarData(arr -> parent -> localST, i -> nodeData.leaf -> tn -> lex, i -> nodeData.leaf -> tn -> line_num);
// if(tmp -> isAssigned == 0) {
// rte();
// }
fprintf(fp, "\tmov rax, rbp\n");
fprintf(fp, "\tsub rax, %dd\n", typeSize[AST_TYPE_INT] + tmp -> offset);
fprintf(fp, "\tmov r8w, word [rax]\n");
}
fprintf(fp, "\tmov rsi, %dd\n", i -> nodeData.leaf -> tn -> line_num);
fprintf(fp, "\tcmp r8w, r10w\n");
fprintf(fp, "\tjl oob\n");
fprintf(fp, "\tcmp r8w, r11w\n");
fprintf(fp, "\tjg oob\n");
/* TODO: write this in assembly */
// if(idx < lft || idx > right) {
// rte();
// }
/* Move base address of array to r8x */
fprintf(fp, "\tmov rax, rbp\n");
fprintf(fp, "\tsub rax, %dd\n", offset + typeSize[AST_TYPE_POINTER]);
fprintf(fp, "\tmov rdx, qword [rax]\n");
/* compute element address as: [rdx - (r8w - r10w + 1) * width] */
fprintf(fp, "\tmov r9w, 0\n");
fprintf(fp, "\tsub r8w, r10w\n");
fprintf(fp, "\tinc r8w\n");
fprintf(fp, "\tmov rcx, %dd\n", typeSize[type]);
fprintf(fp, "label_%d:\n", label_num++);
fprintf(fp, "\tadd r9w, r8w\n");
fprintf(fp, "\tdec rcx\n");
fprintf(fp, "\tjnz label_%d\n", label_num - 1);
fprintf(fp, "\tmovsx r9, r9w\n");
fprintf(fp, "; --- END: fetchArraybyIndex() for array %s: base: rdx, offset: r9 --- \n", arr -> nodeData.leaf -> tn -> lex);
}
/**
* NOTE: Function was initially designed to modularize arrays,
* but later found out that this can be reused for non array types as well.
* don't go by the name
*/
void outputArrayElement(SymTableVar * id, int op) {
fprintf(fp, "; --- START: outputArrayElement() for %s --- \n", id -> name);
fprintf(fp, "; Function is used for both Arrays and non-Array types, don't go by the name! \n");
astDataType type = id -> dataType;
if(type == AST_TYPE_ARRAY)
type = id -> sdt.r -> dataType;
fprintf(fp, "\tpush rbp\n");
if(type == AST_TYPE_INT) {
if(op == 1)
fprintf(fp, "\tmov rdi, fmt_int\n");
else
fprintf(fp, "\tmov rdi, output_fmt_int\n");
fprintf(fp, "\tmov rax, rdx\n");
fprintf(fp, "\tsub rax, r9\n");
fprintf(fp, "\tmov si, word[rax]\n");
}
else if(type == AST_TYPE_REAL) {
if(op == 1)
fprintf(fp, "\tmov rdi, fmt_float\n");
else
fprintf(fp, "\tmov rdi, output_fmt_float\n");
fprintf(fp, "\tmov rax, rdx\n");
fprintf(fp, "\tsub rax, r9\n");
fprintf(fp, "\tcvtss2sd xmm0, dword[rax]\n");
fprintf(fp, "\tmov rax, 1\n");
}
else if(type == AST_TYPE_BOOLEAN) {
fprintf(fp, "\tmov rax, rdx\n");
fprintf(fp, "\tsub rax, r9\n");
fprintf(fp, "\tmov al, byte[rax]\n");
fprintf(fp, "\tcmp al, 0\n");
fprintf(fp, "\tjz label_%d\n", label_num++);
if(op == 1)
fprintf(fp, "\tmov rdi, fmt_string\n");
else
fprintf(fp, "\tmov rdi, output_fmt_string\n");
fprintf(fp, "\tmov rsi, bool_true\n");
fprintf(fp, "\tjmp label_%d\n", label_num++);
fprintf(fp, "label_%d:\n", label_num - 2);
if(op == 1)
fprintf(fp, "\tmov rdi, fmt_string\n");
else
fprintf(fp, "\tmov rdi, output_fmt_string\n");
fprintf(fp, "\tmov rsi, bool_false\n");
fprintf(fp, "label_%d:\n", label_num - 1);
}
alignStack();
fprintf(fp, "\tcall printf\n");
getBackStack();
fprintf(fp, "\tpop rbp\n");
fprintf(fp, "; --- END: outputArrayElement() for %s--- \n", id -> name);
}
/**
* Emits code for copying rhs to lhs
* If lhsOff is -1, left hand side is treated as an array and assumed
* that rdx is base and r9 is offset, already emitted.
* @param lshOff
* @param rhsOff
* @param type
*/
void moveOffsetToOffset(int lhsOff, int rhsOff, astDataType type) {
fprintf(fp, "; --- START: moveOffsetToOffset(): lhsoff = %d, rhsoff = %d, type = %s ---\n", lhsOff, rhsOff, typeName[type]);
/* offset of rhs is in rax */
fprintf(fp, "\tmov rax, rsp\n");
fprintf(fp, "\tsub rax, %dd\n", rhsOff + typeSize[type]);
/* */
if(type == AST_TYPE_INT) {
fprintf(fp, "\tmov r8w, word [rax]\n");
if(lhsOff == -1) {
fprintf(fp, "\tmov rax, rdx\n");
fprintf(fp, "\tsub rax, r9\n");
}
else {
fprintf(fp, "\tmov rax, rbp\n");
fprintf(fp, "\tsub rax, %dd\n", typeSize[type] + lhsOff);
}
fprintf(fp, "\tmov word [rax], r8w\n");
}
if(type == AST_TYPE_REAL) {
fprintf(fp, "\tmov r8d, dword [rax]\n");
if(lhsOff == -1) {
fprintf(fp, "\tmov rax, rdx\n");
fprintf(fp, "\tsub rax, r9\n");
}
else {
fprintf(fp, "\tmov rax, rbp\n");
fprintf(fp, "\tsub rax, %dd\n", typeSize[type] + lhsOff);
}
fprintf(fp, "\tmov dword [rax], r8d\n");
}
if(type == AST_TYPE_BOOLEAN) {
fprintf(fp, "\tmov r8b, byte [rax]\n");
if(lhsOff == -1) {
fprintf(fp, "\tmov rax, rdx\n");
fprintf(fp, "\tsub rax, r9\n");
}
else {
fprintf(fp, "\tmov rax, rbp\n");
fprintf(fp, "\tsub rax, %dd\n", typeSize[type] + lhsOff);
}
fprintf(fp, "\tmov byte [rax], r8b\n");
}
if(type == AST_TYPE_ARRAY) {
fprintf(fp, "\tmov r8, qword [rax]\n");
fprintf(fp, "\tmov rax, rbp\n");
fprintf(fp, "\tsub rax, %dd\n", typeSize[type] + lhsOff);
fprintf(fp, "\tmov qword [rax], r8\n");
}
fprintf(fp, "; --- END: moveOffsetToOffset(): lhsoff = %d, rhsoff = %d, type = %s ---\n", lhsOff, rhsOff, typeName[type]);
}
void if0else1() {
fprintf(fp, "; --- START: if0else1() --- \n");
fprintf(fp, "\tmov r8b, 0\n");
fprintf(fp, "\tjmp label_%d\n", label_num++);
fprintf(fp, "label_%d:\n", label_num - 2);
fprintf(fp, "\tmov r8b, 1\n");
fprintf(fp, "label_%d:\n", label_num - 1);
fprintf(fp, "; --- END: if0else1() --- \n");
}
void pushTemporary(astDataType type, SymTableFunc* par) {
fprintf(fp, "; --- START: pushTemporary(): type = %s ---\n", typeName[type]);
if(type == AST_TYPE_INT) {
fprintf(fp, "\tmov dx, word [rax]\n");
fprintf(fp, "\tmov rax, rsp\n");
fprintf(fp, "\tsub rax, %dd\n", par -> dynamicRecSize);
fprintf(fp, "\tmov word [rax], dx\n");
}
else if(type == AST_TYPE_REAL) {
fprintf(fp, "\tmov edx, dword [rax]\n");
fprintf(fp, "\tmov rax, rsp\n");
fprintf(fp, "\tsub rax, %dd\n", par -> dynamicRecSize);
fprintf(fp, "\tmov dword [rax], edx\n");
}
else if(type == AST_TYPE_BOOLEAN) {
fprintf(fp, "\tmov dl, byte [rax]\n");
fprintf(fp, "\tmov rax, rsp\n");
fprintf(fp, "\tsub rax, %dd\n", par -> dynamicRecSize);
fprintf(fp, "\tmov byte [rax], dl\n");
}
else if(type == AST_TYPE_ARRAY) {
fprintf(fp, "\tmov rdx, qword [rax]\n");
fprintf(fp, "\tmov rax, rsp\n");
fprintf(fp, "\tsub rax, %dd\n", par -> dynamicRecSize);
fprintf(fp, "\tmov qword [rax], rdx\n");
}
fprintf(fp, "; --- END: pushTemporary(): type = %s ---\n", typeName[type]);
}
/**
* Floating point operations source: https://gist.github.com/nikAizuddin/0e307cac142792dcdeba
* cmp eax, 0000000000000000B ;is st0 > source ?
* je .example_11_greater
cmp eax, 0000000100000000B ;is st0 < source ?
je .example_11_less
cmp eax, 0100000000000000B ;is st0 = source ?
je .example_11_equal
*/
void applyOperator(int leftOp, int rightOp, ASTNode * operator, astDataType type) {
fprintf(fp, "; --- START: applyOperator(): leftOp: %d, rightOp: %d, operator: %s, type: %s --- \n", leftOp, rightOp, operator->nodeData.leaf->tn->lex, typeName[type]);
fprintf(fp, "\tmov rax, rsp\n");
fprintf(fp, "\tsub rax, %dd\n", leftOp + typeSize[type]);
fprintf(fp, "\tmov r10, rsp\n");
fprintf(fp, "\tsub r10, %dd\n", rightOp + typeSize[type]);
SymTableFunc * par = getParentFunc(operator -> parent -> localST);
operator -> parent -> nodeData.AOBExpr -> temporaryOffset = par -> dynamicRecSize;
par -> dynamicRecSize += typeSize[operator -> parent -> nodeData.AOBExpr -> dataType];
if(type == AST_TYPE_INT) {
fprintf(fp, "\tmov r8w, word [rax]\n");
fprintf(fp, "\tmov r9w, word [r10]\n");
}
if(type == AST_TYPE_REAL) {
fprintf(fp, "\tfinit\n");
if(operator -> parent -> nodeData.AOBExpr -> dataType == AST_TYPE_BOOLEAN) {
fprintf(fp, "\tfld dword [r10]\n");
fprintf(fp, "\tfld dword [rax]\n");
}
else {
fprintf(fp, "\tfld dword [rax]\n");
fprintf(fp, "\tfld dword [r10]\n");
}
}
if(type == AST_TYPE_BOOLEAN) {
fprintf(fp, "\tmov r8b, byte [rax]\n");
fprintf(fp, "\tmov r9b, byte [r10]\n");
}
switch(operator -> nodeData.leaf -> type) {
case AST_LEAF_AND:
fprintf(fp, "\tand r8b, r9b\n");
break;
case AST_LEAF_OR:
fprintf(fp, "\tor r8b, r9b\n");
break;
case AST_LEAF_LT:
if(type == AST_TYPE_INT) {
fprintf(fp, "\tcmp r8w, r9w\n");
fprintf(fp, "\tjl label_%d\n", label_num++);
if0else1();
}
if(type == AST_TYPE_REAL) {
fprintf(fp, "\tfcom st0, st1\n");
fprintf(fp, "\tfstsw ax\n");
fprintf(fp, "\tand eax, 0100011100000000B\n");
fprintf(fp, "\tcmp eax, 0000000100000000B\n");
fprintf(fp, "\tje label_%d\n", label_num++);
if0else1();
}
break;
case AST_LEAF_LE:
if(type == AST_TYPE_INT) {
fprintf(fp, "\tcmp r8w, r9w\n");
fprintf(fp, "\tjle label_%d\n", label_num++);
if0else1();
}
if(type == AST_TYPE_REAL) {
fprintf(fp, "\tfcom st0, st1\n");
fprintf(fp, "\tfstsw ax\n");
fprintf(fp, "\tand eax, 0100011100000000B\n");
fprintf(fp, "\tcmp eax, 0000000100000000B\n");
fprintf(fp, "\tje label_%d\n", label_num++);
fprintf(fp, "\tcmp eax, 0100000000000000B\n");
fprintf(fp, "\tje label_%d\n", label_num - 1);
if0else1();
}
break;
case AST_LEAF_GT:
if(type == AST_TYPE_INT) {
fprintf(fp, "\tcmp r8w, r9w\n");
fprintf(fp, "\tjg label_%d\n", label_num++);
if0else1();
}
if(type == AST_TYPE_REAL) {
fprintf(fp, "\tfcom st0, st1\n");
fprintf(fp, "\tfstsw ax\n");
fprintf(fp, "\tand eax, 0100011100000000B\n");
fprintf(fp, "\tcmp eax, 0000000000000000B\n");
fprintf(fp, "\tje label_%d\n", label_num++);
if0else1();
}
break;
case AST_LEAF_GE:
if(type == AST_TYPE_INT) {
fprintf(fp, "\tcmp r8w, r9w\n");
fprintf(fp, "\tjge label_%d\n", label_num++);
if0else1();
}
if(type == AST_TYPE_REAL) {
fprintf(fp, "\tfcom st0, st1\n");
fprintf(fp, "\tfstsw ax\n");
fprintf(fp, "\tand eax, 0100011100000000B\n");
fprintf(fp, "\tcmp eax, 0000000000000000B\n");
fprintf(fp, "\tje label_%d\n", label_num++);
fprintf(fp, "\tcmp eax, 0100000000000000B\n");
fprintf(fp, "\tje label_%d\n", label_num - 1);
if0else1();
}
break;
case AST_LEAF_EQ:
if(type == AST_TYPE_INT) {
fprintf(fp, "\tcmp r8w, r9w\n");
fprintf(fp, "\tje label_%d\n", label_num++);
if0else1();
}
if(type == AST_TYPE_REAL) {
fprintf(fp, "\tfcom st0, st1\n");
fprintf(fp, "\tfstsw ax\n");
fprintf(fp, "\tand eax, 0100011100000000B\n");
fprintf(fp, "\tcmp eax, 0100000000000000B\n");
fprintf(fp, "\tje label_%d\n", label_num++);
if0else1();
}
break;
case AST_LEAF_NE:
if(type == AST_TYPE_INT) {
fprintf(fp, "\tcmp r8w, r9w\n");
fprintf(fp, "\tjne label_%d\n", label_num++);
if0else1();
}
if(type == AST_TYPE_REAL) {
fprintf(fp, "\tfcom st0, st1\n");
fprintf(fp, "\tfstsw ax\n");
fprintf(fp, "\tand eax, 0100011100000000B\n");
fprintf(fp, "\tcmp eax, 0100000000000000B\n");
fprintf(fp, "\tjne label_%d\n", label_num++);
if0else1();
}
break;
case AST_LEAF_PLUS:
if(type == AST_TYPE_INT)
fprintf(fp, "\tadd r8w, r9w\n");
if(type == AST_TYPE_REAL) {
fprintf(fp, "\tfadd\n");
fprintf(fp, "\tmov rax, rsp\n");
fprintf(fp, "\tsub rax, %dd\n", par -> dynamicRecSize);
// fprintf(fp, "\tsub rsp, 4\n");
fprintf(fp, "\tfstp dword [rax]\n");
}
break;
case AST_LEAF_MINUS:
if(type == AST_TYPE_INT)
fprintf(fp, "\tsub r8w, r9w\n");
if(type == AST_TYPE_REAL) {
fprintf(fp, "\tfsub\n");
fprintf(fp, "\tmov rax, rsp\n");
fprintf(fp, "\tsub rax, %dd\n", par -> dynamicRecSize);
// fprintf(fp, "\tsub rsp, 4\n");
fprintf(fp, "\tfstp dword [rax]\n");
}
break;
case AST_LEAF_MUL:
if(type == AST_TYPE_INT) {
fprintf(fp, "\tmov ax, r8w\n");
fprintf(fp, "\tmul r9w\n");
fprintf(fp, "\tmov r8w, ax\n");
}
if(type == AST_TYPE_REAL) {
fprintf(fp, "\tfmul\n");
fprintf(fp, "\tmov rax, rsp\n");
fprintf(fp, "\tsub rax, %dd\n", par -> dynamicRecSize);
// fprintf(fp, "\tsub rsp, 4\n");
fprintf(fp, "\tfstp dword [rax]\n");
}
break;
case AST_LEAF_DIV:
if(type == AST_TYPE_INT) {
fprintf(fp, "\tmov rsi, %dd\n", operator -> nodeData.leaf -> tn -> line_num);
fprintf(fp, "\tmov dx, 0\n");
fprintf(fp, "\tmov ax, r8w\n");
fprintf(fp, "\tcmp r9w, 0\n");
fprintf(fp, "\tjz divisionby0\n");
fprintf(fp, "\tdiv r9w\n");
fprintf(fp, "\tmov r8w, ax\n");
}
if(type == AST_TYPE_REAL) {
fprintf(fp, "\tfdiv\n");
fprintf(fp, "\tmov rax, rsp\n");
fprintf(fp, "\tsub rax, %dd\n", par -> dynamicRecSize);
// fprintf(fp, "\tsub rsp, 4\n");
fprintf(fp, "\tfstp dword [rax]\n");
fprintf(fp, "\tfstsw ax\n");
fprintf(fp, "\tmov rsi, %dd\n", operator -> nodeData.leaf -> tn -> line_num);
fprintf(fp, "\tand eax, 0000000000000100B\n");
fprintf(fp, "\tcmp eax, 0000000000000100B\n");
fprintf(fp, "\tje divisionby0\n");
}
break;
default:
break;
}
if(operator -> parent -> nodeData.AOBExpr -> dataType == AST_TYPE_INT) {
fprintf(fp, "\tmov rax, rsp\n");
fprintf(fp, "\tsub rax, %dd\n", par -> dynamicRecSize);
fprintf(fp, "\tmov word [rax], r8w\n");
}
else if(operator -> parent -> nodeData.AOBExpr -> dataType == AST_TYPE_BOOLEAN) {
fprintf(fp, "\tmov rax, rsp\n");
fprintf(fp, "\tsub rax, %dd\n", par -> dynamicRecSize);
fprintf(fp, "\tmov byte [rax], r8b\n");
}
fprintf(fp, "; --- START: applyOperator(): leftOp: %d, rightOp: %d, operator: %s, type: %s --- \n", leftOp, rightOp, operator->nodeData.leaf->tn->lex, typeName[type]);
}
void scopeBegin() {
fprintf(fp, "; --- START: scopeBegin() --- \n");
fprintf(fp, "\tsub rsp, 2d\n");
fprintf(fp, "\tmov ax, word [dynamic]\n");
fprintf(fp, "\tmov word [rsp], ax\n");
fprintf(fp, "\tmov ax, 0\n");
fprintf(fp, "\tmov word [dynamic], ax\n");
fprintf(fp, "; --- END: scopeBegin() --- \n");
}
void scopeEnd() {
fprintf(fp, "; --- START: scopeEnd() --- \n");
fprintf(fp, "\tmovsx rax, word [dynamic]\n");
fprintf(fp, "\tadd rsp, rax\n");
fprintf(fp, "\tmov ax, word [rsp]\n");
fprintf(fp, "\tmov word [dynamic], ax\n");
fprintf(fp, "\tadd rsp, 2d\n");
fprintf(fp, "; --- END: scopeEnd() --- \n");
}
void takeInput(astDataType t, SymTableVar * idNode) {
fprintf(fp, "; --- START: takeInput(): type: %s, Name: %s --- \n", typeName[t], idNode->name);
fprintf(fp, "\tpush rbp\n");
int offset = idNode -> offset;
// unsigned long long int addr =
switch(t) {
case AST_TYPE_INT: {
fprintf(fp, "\tmov rdi, op1\n");
fprintf(fp, "\tmov rsi, type_int\n");
alignStack();
fprintf(fp, "\tcall printf\n");
getBackStack();
fprintf(fp, "\tpop rbp\n");
fprintf(fp, "\tmov r9, %dd\n", offset + typeSize[t]);
getInputElement(t);
}
break;
case AST_TYPE_REAL: {
fprintf(fp, "\tmov rdi, op1\n");
fprintf(fp, "\tmov rsi, type_float\n");
alignStack();
fprintf(fp, "\tcall printf\n");
getBackStack();
fprintf(fp, "\tpop rbp\n");
fprintf(fp, "\tmov r9, %dd\n", offset + typeSize[t]);
getInputElement(t);
}
break;
case AST_TYPE_BOOLEAN: {
fprintf(fp, "\tmov rdi, op1\n");
fprintf(fp, "\tmov rsi, type_bool\n");
alignStack();
fprintf(fp, "\tcall printf\n");
getBackStack();
fprintf(fp, "\tpop rbp\n");
fprintf(fp, "\tmov r9, %dd\n", offset + typeSize[t]);
getInputElement(t);
}
break;
case AST_TYPE_ARRAY: {
getLeftRightIndex(idNode);
/* TODO write it in register format */
// if(lft > right) {
// rte();
// }
astDataType type = idNode -> sdt.r -> dataType;
fprintf(fp, "\n; --- Asking for user input for Array ---\n");
fprintf(fp, "\tmov rdi, op2\n");
fprintf(fp, "\tmov si, r11w\n");
fprintf(fp, "\tsub si, r10w\n");
fprintf(fp, "\tmovsx rsi, si\n");
fprintf(fp, "\tinc rsi\n");
if(type == AST_TYPE_INT)
fprintf(fp, "\tmov rdx, type_int\n");
else if(type == AST_TYPE_REAL)
fprintf(fp, "\tmov rdx, type_float\n");
else if(type == AST_TYPE_BOOLEAN)
fprintf(fp, "\tmov rdx, type_bool\n");
fprintf(fp, "\tmovsx rcx, r10w\n");
fprintf(fp, "\tmovsx r8, r11w\n");
alignStack();
fprintf(fp, "\tcall printf\n");
getBackStack();
fprintf(fp, "\tpop rbp\n");
fprintf(fp, "\n; --- rdx will be the address of the first element of the array ---\n");
fprintf(fp, "\tmov rax, rbp\n");
fprintf(fp, "\tsub rax, %dd\n", offset + typeSize[AST_TYPE_POINTER]);
fprintf(fp, "\tmov rdx, qword [rax]\n");
fprintf(fp, "\n; --- Loop for scanning each element of the array --- \n");
getLeftRightIndex(idNode);
fprintf(fp, "\tmov cx, r11w\n");
fprintf(fp, "\tsub cx, r10w\n");
fprintf(fp, "\tmovsx rcx, cx\n");
fprintf(fp, "\tinc rcx\n");
fprintf(fp, "label_%d:\n", label_num++);
fprintf(fp, "\tpush rdx\n");
fprintf(fp, "\tpush rcx\n");
fprintf(fp, "\tpush rbp\n");
fprintf(fp, "\n; --- Scanning input ---\n");
if(type == AST_TYPE_INT)
fprintf(fp, "\tmov rdi, fmt_int\n");
else if(type == AST_TYPE_REAL)
fprintf(fp, "\tmov rdi, fmt_float\n");
else if(type == AST_TYPE_BOOLEAN)
fprintf(fp, "\tmov rdi, fmt_bool\n");
fprintf(fp, "\tsub rdx, %dd\n", typeSize[type]);
fprintf(fp, "\tmov rsi, rdx\n");
alignStack();
fprintf(fp, "\tcall scanf\n");
getBackStack();
fprintf(fp, "\tpop rbp\n");
fprintf(fp, "\tpop rcx\n");
fprintf(fp, "\tpop rdx\n");
fprintf(fp, "\tsub rdx, %dd\n", typeSize[type]);
fprintf(fp, "\tdec rcx\n");
fprintf(fp, "\tcmp rcx, 0x0\n");
fprintf(fp, "\tjnz label_%d\n", label_num - 1);
// fprintf(fp, "\tpop rbp\n");
}
break;
}
fprintf(fp, "; --- END: takeInput(): type: %s, Name: %s --- \n", typeName[t], idNode->name);
}
void giveOutput(ASTNode * curr) {
fprintf(fp, "; --- START: giveInput()");
ASTNode * ch = curr;
if(ch -> type == AST_NODE_LEAF) {
fprintf(fp, " type: AST_NODE_LEAF, ");
switch(ch -> nodeData.leaf -> type) {
case AST_LEAF_VARIDNUM_NUM: {
fprintf(fp, " leaf-type: AST_LEAF_VARIDNUM_NUM --- \n");
int val = ch -> nodeData.leaf -> tn -> value.val_int;
fprintf(fp, "\tpush rbp\n");
fprintf(fp, "\tmov rdi, output_fmt_int\n");
fprintf(fp, "\tmov rsi, %d\n", val);
alignStack();
fprintf(fp, "\tcall printf\n");
getBackStack();
fprintf(fp, "\tpop rbp\n");
}
break;
case AST_LEAF_VARIDNUM_RNUM: {
float val = ch -> nodeData.leaf -> tn -> value.val_float;
fprintf(fp, " leaf-type: AST_LEAF_VARIDNUM_RNUM, value: %f --- \n", val);
fprintf(fp, "\tpush rbp\n");
fprintf(fp, "\tmov rdi, output_fmt_float\n");
fprintf(fp, "\tsub rsp, 4\n");
fprintf(fp, "\tmov dword [rsp], __float32__(%f)\n", val);
fprintf(fp, "\tcvtss2sd xmm0, [rsp]\n");
fprintf(fp, "\tadd rsp, 4\n");
fprintf(fp, "\tmov rax, 1\n");
alignStack();
fprintf(fp, "\tcall printf\n");
getBackStack();
fprintf(fp, "\tpop rbp\n");
}
break;
case AST_LEAF_BOOLTRUE: {
fprintf(fp, " leaf-type: AST_LEAF_BOOLTRUE --- \n");
fprintf(fp, "\tpush rbp\n");
fprintf(fp, "\tmov rdi, output_fmt_string\n");
fprintf(fp, "\tmov rsi, bool_true\n");
alignStack();
fprintf(fp, "\tcall printf\n");
getBackStack();
fprintf(fp, "\tpop rbp\n");
}
break;
case AST_LEAF_BOOLFALSE: {
fprintf(fp, " leaf-type: AST_LEAF_BOOLFALSE --- \n");
fprintf(fp, "\tpush rbp\n");
fprintf(fp, "\tmov rdi, output_fmt_string\n");
fprintf(fp, "\tmov rsi, bool_false\n");
alignStack();
fprintf(fp, "\tcall printf\n");
getBackStack();
fprintf(fp, "\tpop rbp\n");
}
break;
default: {
fprintf(fp, " leaf-type: default case hit --- \n");
/* do nothing */
}
break;
}
}
if(ch -> type == AST_NODE_VARIDNUM) {
fprintf(fp, " type: AST_NODE_VARIDNUM --- \n");
/* non array variable */
ASTNode * idNode = ch -> child;
SymTableVar * id = fetchVarData(curr -> localST, idNode -> nodeData.leaf -> tn -> lex, idNode -> nodeData.leaf -> tn -> line_num);
if(id -> dataType != AST_TYPE_ARRAY) {
// if(id -> isAssigned == 0) {
// rte();
// }
fprintf(fp, "\tmov r9, %dd\n", (id -> offset) + typeSize[id -> dataType]);
fprintf(fp, "\tmov rdx, rbp\n");
outputArrayElement(id, 0);
return;
}
getLeftRightIndex(id);
// if(lft > right) {
// rte();
// }
astDataType type = id -> sdt.r -> dataType;
if(idNode -> next == NULL) {
fprintf(fp, "; --- idNode->next is NULL --- \n");
int offset = id -> offset;
fprintf(fp, "\tpush rbp\n");
fprintf(fp, "\tmov rdi, output_fmt_plain\n" );
alignStack();
fprintf(fp, "\tcall printf\n");
getBackStack();
fprintf(fp, "\tpop rbp\n");
fprintf(fp, "\tmov rax, rbp\n");
fprintf(fp, "\tsub rax, %dd\n", offset + typeSize[AST_TYPE_POINTER]);
fprintf(fp, "\tmov rdx, qword [rax]\n");
fprintf(fp, "\tmov cx, r11w\n");
fprintf(fp, "\tsub cx, r10w\n");
fprintf(fp, "\tmovsx rcx, cx\n");
fprintf(fp, "\tinc rcx\n");
fprintf(fp, "\tmov r9, %dd\n", typeSize[type]);
fprintf(fp, "label_%d:\n", label_num++);
int loopLabel = label_num - 1;
fprintf(fp, "\tpush rdx\n");
fprintf(fp, "\tpush rcx\n");
outputArrayElement(id, 1);
fprintf(fp, "\tpop rcx\n");
fprintf(fp, "\tpop rdx\n");
fprintf(fp, "\tpush rdx\n");
fprintf(fp, "\tpush rcx\n");
fprintf(fp, "\tpush rbp\n");
fprintf(fp, "\tmov rdi, single_space\n" );
alignStack();
fprintf(fp, "\tcall printf\n");
getBackStack();
fprintf(fp, "\tpop rbp\n");
fprintf(fp, "\tpop rcx\n");
fprintf(fp, "\tpop rdx\n");
fprintf(fp, "\tsub rdx, %dd\n", typeSize[type]);
fprintf(fp, "\tdec rcx\n");
fprintf(fp, "\tjnz label_%d\n", loopLabel);
// fprintf(fp, "\tpop rbp\n");
fprintf(fp, "\tpush rbp\n");
fprintf(fp, "\tmov rdi, end_line\n" );
alignStack();
fprintf(fp, "\tcall printf\n");
getBackStack();
fprintf(fp, "\tpop rbp\n");
}
else {
fprintf(fp, "; --- idNode->next is not NULL --- \n");
fetchArraybyIndex(ch -> child, ch -> child -> next);
outputArrayElement(id, 0);
}
}
fprintf(fp, "; --- END: giveInput() --- \n");
}
void codegenInit() {
/*
init data section and code section
global main ;NOTE: In case you are linking with ld, use _start. Use main when linking with gcc
*/
fprintf(fp, "; --- START: init code and data --- \n");
fprintf(fp, "section .data\n");
fprintf(fp, "\tfmt_float: db \"%%f\", 0\n");
fprintf(fp, "\tfmt_int: db \"%%hd\", 0\n");
fprintf(fp, "\tfmt_string: db \"%%s\", 0\n");
fprintf(fp, "\tfmt_bool: db \"%%hhu\", 0\n");
fprintf(fp, "\tsingle_space: db \" \", 0\n");
fprintf(fp, "\tend_line: db \"\", 0xA, 0\n");
fprintf(fp, "\ttype_int: db \"Integer\", 0\n");
fprintf(fp, "\ttype_float: db \"Real Number\", 0\n");
fprintf(fp, "\ttype_bool: db \"Boolean\", 0\n");
fprintf(fp, "\top1: db \"Input: Enter an %%s Value\", 0xA, 0\n");
fprintf(fp, "\top2: db \"Input: Enter %%d array elements of %%s type for range %%d to %%d\", 0xA, 0\n");
fprintf(fp, "\toutput_fmt_float: db \"Output: %%f\", 0xA, 0\n");
fprintf(fp, "\toutput_fmt_int: db \"Output: %%hd\", 0xA, 0\n");
fprintf(fp, "\toutput_fmt_string: db \"Output: %%s\", 0xA, 0\n");
fprintf(fp, "\toutput_fmt_plain: db \"Output: \", 0\n");
fprintf(fp, "\tbool_true: db \"true\", 0\n");
fprintf(fp, "\tbool_false: db \"false\", 0\n");
fprintf(fp, "\trte_oob: db \"RUN TIME ERROR: Array index out of bounds at line %%hd.\", 0xA, 0\n");
fprintf(fp, "\trte_type: db \"RUN TIME ERROR: Dynamic array type checking failed on line %%hd.\", 0xA, 0\n");
fprintf(fp, "\trte_param: db \"RUN TIME ERROR: Dynamic array type checking failed on function reuse parameter passing on line %%hd.\", 0xA, 0\n");
fprintf(fp, "\trte_invalidbounds: db \"RUN TIME ERROR: Invalid dynamic array bounds on line %%hd.\", 0xA, 0\n");
fprintf(fp, "\trte_divisionby0: db \"RUN TIME ERROR: division by zero on line %%hd.\", 0xA, 0\n");
fprintf(fp, "section .bss\n");
fprintf(fp, "\tbuffer: resb 64\n");
fprintf(fp, "\tdynamic: resw 1\n");
fprintf(fp, "\trspreserve: resq 1\n");
fprintf(fp, "section .text\n");
fprintf(fp, "\tglobal main\n");
fprintf(fp, "\textern printf\n");
fprintf(fp, "\textern scanf\n");
fprintf(fp, "; --- END: init code and data --- \n");
}
void emitCodeAST(ASTNode* curr, char* fname) {
switch(curr -> type) {
case AST_NODE_PROGRAM: {
codegenInit();
ASTNode* ch = curr -> child;
emitCodeChildren(ch, fname);
}
break;
case AST_NODE_MODULEDECLARATION: {
/* no need */
}
break;
case AST_NODE_MODULELIST: {
ASTNode* ch = curr -> child;
if(curr -> nodeData.moduleList -> type == AST_MODULE_DRIVER) {
if(ch == NULL)
return;
SymTableFunc * driver = fetchFuncData("driver");
asmComment("Begining of the driver program.");
fprintf(fp, "main:\n");
fprintf(fp, "mov rbp, rsp\n");
int actRecSize = driver -> actRecSize;
fprintf(fp, "\tsub rsp, %dd\n", actRecSize);
fprintf(fp, "\tmov word [dynamic], 0\n");
emitCodeAST(ch, "driver");
asmComment("Resetting(aligning) the rsp.");
fprintf(fp, "\tmovsx rax, word [dynamic]\n");
fprintf(fp, "\tadd rsp, rax\n");
fprintf(fp, "\tadd rsp, %dd\n", driver -> actRecSize);
// rte();
fprintf(fp, "\tret\n");
asmComment("End of driver function.");
}
else
emitCodeChildren(ch, fname);
}
break;
case AST_NODE_MODULE: {
ASTNode* ch = curr -> child;
ASTNode * ret = ch -> next -> next;
char fn[30];
strcpy(fn, ch -> nodeData.leaf -> tn -> lex);
SymTableFunc * func = fetchFuncData(fn);
asmComment("Begin of a moduledef.");
fprintf(fp, "%s:\n", fn);
fprintf(fp, "mov word [dynamic], 0\n");
emitCodeChildren(ch, fname);
fprintf(fp, "\tmovsx rax, word [dynamic]\n");
fprintf(fp, "\tadd rsp, rax\n");
fprintf(fp, "\tret\n");
}
break;
case AST_NODE_INPUTLIST: {
/* Verify: nothing to do*/
}
break;
case AST_NODE_OUTPUTLIST: {
/* Verify: nothing to do */
}
break;
case AST_NODE_ARRAY: {
/* nothing required */
}
break;
case AST_NODE_RANGEARRAYS: {
/* nothing required */
}
break;
case AST_NODE_STATEMENT: {
ASTNode* ch = curr -> child;
emitCodeChildren(ch, fname);
/* Todo: if end stament of moduledef fprinf ret*/
}
break;
case AST_NODE_IO: {
ASTNode* ch = curr -> child;
if(curr -> nodeData.io -> type == AST_IO_GETVAL) {
SymTableVar * idNode = fetchVarData(curr -> localST, ch -> nodeData.leaf -> tn -> lex, ch -> nodeData.leaf -> tn -> line_num);
astDataType t = idNode -> dataType;
takeInput(t, idNode);
}
else { // AST_IO_PRINT
giveOutput(ch);
}
}
break;
case AST_NODE_SIMPLESTMT: {
ASTNode* ch = curr -> child;
emitCodeChildren(ch, fname);
}
break;
case AST_NODE_ASSIGN: {
ASTNode* ch = curr -> child;
emitCodeChildren(ch, fname);
ch = curr -> child;
if(ch -> next -> type == AST_NODE_LVALARRSTMT) {
/* Fetching Array data form Symbol Table */
SymTableVar * id = fetchVarData(curr -> localST, ch -> nodeData.leaf -> tn -> lex, ch -> nodeData.leaf -> tn -> line_num);
/* Getting index of array element being accessed */
ASTNode * index = ch -> next -> child;
/* Getting range limits of array: r10 left, r11 right*/
getLeftRightIndex(id);
/* rdx -> base, r9 -> offset of array element */
fetchArraybyIndex(ch, index);
/* Evaluating expression on RHS */
ASTNode * rhs = ch -> next -> child -> next;
/* Get offset of temporary variable on RHS of operator */
int rhsOff = getExprOffset(rhs);
astDataType type = getExprType(rhs);
moveOffsetToOffset(-1, rhsOff, type);
}
else {
/* LVALUE_ID_STMT */
int lhsOff = getIDOffset(ch);
int rhsOff = getExprOffset(ch -> next);
SymTableVar * tmp = fetchVarData(curr -> localST, ch -> nodeData.leaf -> tn -> lex, ch -> nodeData.leaf -> tn -> line_num);
if(tmp -> dataType == AST_TYPE_ARRAY) {
SymTableVar * rhs = fetchVarData(curr -> localST, ch -> next -> child -> nodeData.leaf -> tn -> lex, ch -> next -> child -> nodeData.leaf -> tn -> line_num);
fprintf(fp, "\tmov rsi, %dd\n", ch -> nodeData.leaf -> tn -> line_num);
getLeftRightIndex(tmp);
fprintf(fp, "\tmov r8w, r10w\n");
getLeftRightIndex(rhs);
fprintf(fp, "\tcmp r8w, r10w\n");
fprintf(fp, "\tjnz typeError\n");
getLeftRightIndex(tmp);
fprintf(fp, "\tmov r8w, r11w\n");
getLeftRightIndex(rhs);
fprintf(fp, "\tcmp r8w, r11w\n");
fprintf(fp, "\tjnz typeError\n");
}
astDataType type = tmp -> dataType;
moveOffsetToOffset(lhsOff, rhsOff, type);
}
// fprintf(fp, "\tadd rsp, %dd\n", curr -> localST -> dynamicRecSize);
curr -> localST -> dynamicRecSize = 0;
}
break;
case AST_NODE_MODULEREUSE: {
ASTNode * ch = curr -> child;
/* Setting up stack frame. Set the current stack pointer as the starting
of the base of stack frame of the function being called, and storing
current base pointer in stack */
fprintf(fp, "; --- Setting up the stack frame ---\n");
fprintf(fp, "\tsub rsp, 2\n");
fprintf(fp, "\tmov ax, word [dynamic]\n");
fprintf(fp, "\tmov word [rsp], ax\n");
fprintf(fp, "\tsub rsp, 8\n");
fprintf(fp, "\tmov qword [rsp], rbp\n");
// fprintf(fp, "\tpush rbp\n");
fprintf(fp, "\tmov rbp, rsp\n");
/* Actual parameters */
ASTNode * inParam = ch -> next;
if(inParam -> type != AST_NODE_IDLIST)
inParam = inParam -> next;
ch = curr -> child;
if(ch -> type != AST_NODE_LEAF)
ch = ch -> next;
SymTableFunc * func = fetchFuncData(inParam -> prev -> nodeData.leaf -> tn -> lex);
Node * head = func -> input_plist -> head;
int inputSize = 0;
/* Traversing actual parameters */
while(inParam != NULL) {
ASTNode * idNode = inParam -> child;
/* Fetch current ID from symbol table */
SymTableVar * id = fetchVarData(curr -> localST, idNode -> nodeData.leaf -> tn -> lex, idNode -> nodeData.leaf -> tn -> line_num);
// if(id -> isAssigned == 0)
// rte();
fprintf(fp, "\tmov rcx, qword [rbp]\n");
// fprintf(fp, "\tmov rcx, [rax]\n");
fprintf(fp, "\tsub rcx, %dd\n", typeSize[id -> dataType] + id -> offset);
inputSize += typeSize[id -> dataType];
if(id -> dataType == AST_TYPE_ARRAY)
inputSize += 2*typeSize[AST_TYPE_INT];
fprintf(fp, "\tsub rsp, %dd\n", typeSize[id -> dataType]);
if(id -> dataType == AST_TYPE_INT) {
fprintf(fp, "\tmov ax, word [rcx]\n");
// fprintf(fp, "\tpush ax\n");
fprintf(fp, "\tmov word [rsp], ax\n");
}
if(id -> dataType == AST_TYPE_REAL) {
fprintf(fp, "\tmov eax, dword [rcx]\n");
// fprintf(fp, "\tpush eax\n");
fprintf(fp, "\tmov dword [rsp], eax\n");
}
if(id -> dataType == AST_TYPE_BOOLEAN) {
fprintf(fp, "\tmov al, byte [rcx]\n");
// fprintf(fp, "\tpush al\n");
fprintf(fp, "\tmov byte [rsp], al\n");
}
if(id -> dataType == AST_TYPE_ARRAY) {
fprintf(fp, "\tmov r9, rbp\n");
fprintf(fp, "\tmov rbp, qword [rbp]\n");
getLeftRightIndex(id);
fprintf(fp, "\tmov rbp, r9\n");
fprintf(fp, "\tmov rax, qword [rcx]\n");
// fprintf(fp, "\tpush rax\n");
fprintf(fp, "\tmov qword [rsp], rax\n");
SymTableVar * recievedParam = (SymTableVar*) (head -> data);
fprintf(fp, "mov rsi, %dd\n", ch -> nodeData.leaf -> tn -> line_num);
if(strcmp(recievedParam -> sdt.r -> lowId, "") == 0) {
// getLeftRightIndex(recievedParam);
fprintf(fp, "mov r8w, %dd\n", recievedParam -> sdt.r -> low);
fprintf(fp, "cmp r8w, r10w\n");
fprintf(fp, "jnz param\n");
}
if(strcmp(recievedParam -> sdt.r -> highId, "") == 0) {
// getLeftRightIndex(recievedParam);
fprintf(fp, "mov r8w, %dd\n", recievedParam -> sdt.r -> high);
// getLeftRightIndex(id);
fprintf(fp, "cmp r8w, r11w\n");
fprintf(fp, "jnz param\n");
}
fprintf(fp, "\tsub rsp, %dd\n", typeSize[AST_TYPE_INT]);
fprintf(fp, "\tmov word[rsp], r10w\n");
fprintf(fp, "\tsub rsp, %dd\n", typeSize[AST_TYPE_INT]);
fprintf(fp, "\tmov word[rsp], r11w\n");
}
inParam = inParam -> child -> next;
head = head -> next;
}
SymTableFunc * fun = fetchFuncData(ch -> nodeData.leaf -> tn -> lex);
int actRecSize = fun -> actRecSize;
fprintf(fp, "\tsub rsp, %dd\n", actRecSize - inputSize);
fprintf(fp, "\tcall %s\n", ch -> nodeData.leaf -> tn -> lex);
/* Function has returned here after */
fprintf(fp, "\tmov rax, qword [rbp]\n");
fprintf(fp, "\tadd rbp, 8d\n");
fprintf(fp, "\tmov dx, word [rbp]\n");
fprintf(fp, "\tmov word [dynamic], dx\n");
fprintf(fp, "\tadd rbp, 2d\n");
fprintf(fp, "\tmov rsp, rbp\n");
fprintf(fp, "\tmov rbp, rax\n");
ASTNode * ret = curr -> child;
if(ret -> type == AST_NODE_LEAF)
return;
while(ret != NULL) {
ASTNode * idNode = ret -> child;
SymTableVar * id = fetchVarData(curr -> localST, idNode -> nodeData.leaf -> tn -> lex, idNode -> nodeData.leaf -> tn -> line_num);
fprintf(fp, "\tmov rdx, rbp\n");
fprintf(fp, "\tsub rdx, %dd\n", typeSize[id -> dataType] + id -> offset);
fprintf(fp, "\tmov rax, rsp\n");
fprintf(fp, "\tsub rax, 8\n");
fprintf(fp, "\tsub rax, 2\n");
fprintf(fp, "\tsub rax, %dd\n", inputSize + typeSize[id -> dataType]);
if(id -> dataType == AST_TYPE_INT) {
fprintf(fp, "\tmov cx, word [rax]\n");
fprintf(fp, "\tmov word [rdx], cx\n");
}
if(id -> dataType == AST_TYPE_REAL) {
fprintf(fp, "\tmov ecx, dword [rax]\n");
fprintf(fp, "\tmov dword [rdx], ecx\n");
}
if(id -> dataType == AST_TYPE_BOOLEAN) {
fprintf(fp, "\tmov cl, byte [rax]\n");
fprintf(fp, "\tmov byte [rdx], cl\n");
}
if(id -> dataType == AST_TYPE_ARRAY) {
fprintf(fp, "\tmov rcx, qword [rax]\n");
fprintf(fp, "\tmov qword [rdx], rcx\n");
}
inputSize += typeSize[id -> dataType];
ret = ret -> child -> next;
}
}
break;
case AST_NODE_IDLIST: {
/* no need*/
}
break;
case AST_NODE_EXPR: {
/* no need*/
}
break;
case AST_NODE_AOBEXPR: {
ASTNode * ch = curr -> child;
emitCodeChildren(ch, fname);
ch = curr -> child;
int leftOpTemp, rightOpTemp;
leftOpTemp = getExprOffset(ch);
rightOpTemp = getExprOffset(ch -> next -> next);
astDataType type = getExprType(ch);
applyOperator(leftOpTemp, rightOpTemp, ch -> next, type);
}
break;
case AST_NODE_DECLARESTMT: {
ASTNode * ch = curr -> child;
if(ch -> next -> type == AST_NODE_ARRAY) {
ASTNode * idNode = ch;
ASTNode * arr = ch -> next;
astDataType type = arr -> nodeData.dataType -> dataType;
if(arr -> nodeData.dataType -> is_static == 1) {
while(idNode != NULL) {
SymTableVar * id = fetchVarData(curr -> localST, idNode -> child -> nodeData.leaf -> tn -> lex, idNode -> child -> nodeData.leaf -> tn -> line_num);
fprintf(fp, "\tmov rax, rbp\n");
fprintf(fp, "\tsub rax, %dd\n", typeSize[AST_TYPE_POINTER] + id -> offset);
fprintf(fp, "\tmov rcx, rax\n");
fprintf(fp, "\tmov qword[rcx], rax\n");
idNode = idNode -> child -> next;
}
return;
}
while(idNode != NULL) {
SymTableVar * id = fetchVarData(curr -> localST, idNode -> child -> nodeData.leaf -> tn -> lex, idNode -> child -> nodeData.leaf -> tn -> line_num);
fprintf(fp, "\tmov rax, rbp\n");
fprintf(fp, "\tsub rax, %dd\n", typeSize[AST_TYPE_POINTER] + id -> offset);
fprintf(fp, "\tmov qword [rax], rsp\n");
getLeftRightIndex(id);
fprintf(fp, "\tmov rsi, %dd\n", idNode -> child -> nodeData.leaf -> tn -> line_num);
fprintf(fp, "\tcmp r10w, r11w\n");
fprintf(fp, "\tjg invalidbounds\n");
fprintf(fp, "\tmov cx, r11w\n");
fprintf(fp, "\tsub cx, r10w\n");
fprintf(fp, "\tmovsx rcx, cx\n");
fprintf(fp, "\tinc rcx\n");
fprintf(fp, "\tmov r9w, word [dynamic]\n");
fprintf(fp, "label_%d:\n", label_num++);
fprintf(fp, "\tsub rsp, %dd\n", typeSize[type]);
fprintf(fp, "\tadd r9w, %dd\n", typeSize[type]);
fprintf(fp, "\tdec rcx\n");
fprintf(fp, "\tjnz label_%d\n", label_num - 1);
fprintf(fp, "\tmov word [dynamic], r9w\n");
idNode = idNode -> child -> next;
}
}
}
break;
case AST_NODE_CONDSTMT: {
ASTNode* ch = curr -> child;
SymTableVar * switchVar = fetchVarData(curr -> localST, ch -> nodeData.leaf -> tn -> lex, ch -> nodeData.leaf -> tn -> line_num);
ch -> next -> nodeData.caseStmt -> breakLabel = label_num++;
int tmp = label_num - 1;
scopeBegin();
emitCodeAST(ch -> next, fname);
int label = getLastCaseLabel(curr);
if(tmp != label)
fprintf(fp, "label_%d:\n", label);
if(ch -> next -> next != NULL)
emitCodeAST(ch -> next -> next, fname);
fprintf(fp, "label_%d:\n", tmp);
scopeEnd();
/* Check: defualt will automatically be handled(statements) */
}
break;
/* todo: complete it */
case AST_NODE_CASESTMT: {
ASTNode * ch = curr -> child;
SymTableVar * switchvar = fetchVarData(curr -> localST, curr -> localST -> dependentVar, curr -> localST -> start_line_num);
if(curr -> parent -> type == AST_NODE_CASESTMT)
fprintf(fp, "label_%d:\n", curr -> nodeData.caseStmt -> label);
fprintf(fp, "\tmov rax, rbp\n");
fprintf(fp, "\tsub rax, %dd\n", typeSize[switchvar -> dataType] + switchvar -> offset);
if(switchvar -> dataType == AST_TYPE_INT) {
fprintf(fp, "\tmov ax, word [rax]\n");
int val = ch -> nodeData.leaf -> tn -> value.val_int;
fprintf(fp, "\tcmp ax, %dd\n", val);
fprintf(fp, "\tjnz label_%d\n", label_num++);
int nextcase = label_num - 1;
// fprintf(fp, "label_%d:\n", label_num - 2);
emitCodeAST(ch -> next, fname);
fprintf(fp, "\tjmp label_%d\n", curr -> nodeData.caseStmt -> breakLabel);
ASTNode * chtmp = ch;
ch = ch -> next -> next;
if(ch != NULL) {
ch -> nodeData.caseStmt -> breakLabel = curr -> nodeData.caseStmt -> breakLabel;
ch -> nodeData.caseStmt -> label = nextcase;
emitCodeAST(ch, fname);
}
else {
chtmp -> parent -> nodeData.caseStmt -> lastLabel = nextcase;
}
}
else if(switchvar -> dataType == AST_TYPE_BOOLEAN) {
fprintf(fp, "\tmov al, byte [rax]\n");
int val = (ch -> nodeData.leaf -> tn -> sym.T == TRUE);
fprintf(fp, "\tcmp al, %dd\n", val);
fprintf(fp, "\tjnz label_%d\n", label_num++);
int nextcase = label_num - 1;
// fprintf(fp, "label_%d:\n", label_num - 2);
emitCodeAST(ch -> next, fname);
fprintf(fp, "jmp label_%d\n", curr -> nodeData.caseStmt -> breakLabel);
ASTNode * chtmp = ch;
ch = ch -> next -> next;
if(ch != NULL) {
ch -> nodeData.caseStmt -> breakLabel = curr -> nodeData.caseStmt -> breakLabel;
ch -> nodeData.caseStmt -> label = nextcase;
emitCodeAST(ch, fname);
}
else {
chtmp -> parent -> nodeData.caseStmt -> lastLabel = nextcase;
}
}
}
break;
case AST_NODE_UNARY: {
ASTNode* ch = curr -> child;
emitCodeChildren(ch, fname);
ch = curr -> child;
int tempOff = getExprOffset(ch -> next);
astDataType type = getExprType(ch -> next);
SymTableFunc * par = getParentFunc(curr -> localST);
curr -> nodeData.unary -> temporaryOffset = par -> dynamicRecSize;
par -> dynamicRecSize += typeSize[type];
if(type == AST_TYPE_INT) {
fprintf(fp, "\tmov rax, rsp\n");
fprintf(fp, "\tsub rax, %dd\n", typeSize[type] + tempOff);
fprintf(fp, "\tmov ax, word [rax]\n");
if(ch -> nodeData.leaf -> type == AST_LEAF_UOPMINUS) {
fprintf(fp, "\txor ax, 0xffff\n");
fprintf(fp, "\tinc ax\n");
}
fprintf(fp, "\tmov rdx, rsp\n");
fprintf(fp, "\tsub rdx, %dd\n", par -> dynamicRecSize);
fprintf(fp, "\tmov word [rdx], ax\n");
}
else {
fprintf(fp, "\tmov rax, rsp\n");
fprintf(fp, "\tsub rax, %dd\n", typeSize[type] + tempOff);
if(ch -> nodeData.leaf -> type == AST_LEAF_UOPMINUS) {
fprintf(fp, "\tfinit\n");
fprintf(fp, "\tfld dword [rax]\n");
fprintf(fp, "\tfchs\n");
}
fprintf(fp, "\tmov rdx, rsp\n");
fprintf(fp, "\tsub rdx, %dd\n", par -> dynamicRecSize);
fprintf(fp, "\tfstp dword [rdx]\n");
}
}
break;
case AST_NODE_LVALARRSTMT: {
/* do nothing */
ASTNode * ch = curr -> child;
emitCodeChildren(ch, fname);
}
break;
case AST_NODE_ITERSTMT: {
ASTNode * ch = curr -> child;
if(curr -> nodeData.iterStmt -> type == AST_ITER_FOR) {
SymTableVar * loopVar = fetchVarData(curr -> localST, ch -> nodeData.leaf -> tn -> lex, ch -> nodeData.leaf -> tn -> line_num);
int num1 = ch -> next -> child -> nodeData.leaf -> tn -> value.val_int;
int num2 = ch -> next -> child -> next -> nodeData.leaf -> tn -> value.val_int;
if(num1 > num2)
return;
// optimized
fprintf(fp, "\tmov cx, %dd\n", num1);
fprintf(fp, "label_%d:\n", label_num++);
scopeBegin();
int tmp = label_num - 1;
fprintf(fp, "\tmov rax, rbp\n");
fprintf(fp, "\tsub rax, %dd\n", typeSize[AST_TYPE_INT] + loopVar -> offset);
fprintf(fp, "\tmov word [rax], cx\n");
emitCodeAST(ch -> next -> next, fname);
scopeEnd();
fprintf(fp, "\tmov rax, rbp\n");
fprintf(fp, "\tsub rax, %dd\n", typeSize[AST_TYPE_INT] + loopVar -> offset);
fprintf(fp, "\tmov cx, word[rax]\n");
fprintf(fp, "\tinc cx\n");
fprintf(fp, "\tcmp cx, %d\n", num2 + 1);
fprintf(fp, "\tjnz label_%d\n", tmp);
}
else {
SymTableFunc * par = getParentFunc(curr -> localST);
par -> dynamicRecSize = 0;
fprintf(fp, "label_%d:\n", label_num++);
scopeBegin();
int tmp = label_num - 1;
int last = label_num++;
emitCodeAST(ch, fname);
int tmpOff = par -> dynamicRecSize;
fprintf(fp, "\tmov rax, rsp\n");
fprintf(fp, "\tsub rax, %dd\n", tmpOff);
fprintf(fp, "\tmov dl, byte [rax]\n");
fprintf(fp, "\tcmp dl, 0\n");
fprintf(fp, "\tjz label_%d\n", last);
emitCodeAST(ch -> next, fname);
scopeEnd();
fprintf(fp, "\tjmp label_%d\n", tmp);
fprintf(fp, "label_%d:\n", last);
scopeEnd();
par -> dynamicRecSize = 0;
}
}
break;
case AST_NODE_VARIDNUM: {
ASTNode* ch = curr -> child;
SymTableFunc * par = getParentFunc(curr -> localST);
SymTableVar * id = fetchVarData(curr -> localST, ch -> nodeData.leaf -> tn -> lex, ch -> nodeData.leaf -> tn -> line_num);
if(ch -> next == NULL) {
fprintf(fp, "\tmov rax, rbp\n");
fprintf(fp, "\tsub rax, %dd\n", id -> offset + typeSize[id -> dataType]);
curr -> nodeData.var -> temporaryOffset = par -> dynamicRecSize;
par -> dynamicRecSize += typeSize[id -> dataType];
astDataType type = id -> dataType;
pushTemporary(type, par);
}
else {
getLeftRightIndex(id);
fetchArraybyIndex(ch, ch -> next);
curr -> nodeData.var -> temporaryOffset = par -> dynamicRecSize;
par -> dynamicRecSize += typeSize[id -> sdt.r -> dataType];
astDataType type = id -> sdt.r -> dataType;
fprintf(fp, "\tmov rax, rdx\n");
fprintf(fp, "\tsub rax, r9\n");
pushTemporary(type, par);
}
}
break;
case AST_NODE_LEAF: {
switch(curr -> nodeData.leaf -> type) {
case AST_LEAF_VARIDNUM_NUM: {
SymTableFunc * par = getParentFunc(curr -> localST);
curr -> nodeData.leaf -> temporaryOffset = par -> dynamicRecSize;
par -> dynamicRecSize += typeSize[AST_TYPE_INT];
int val = curr -> nodeData.leaf -> tn -> value.val_int;
fprintf(fp, "\tmov ax, %dd\n", val);
fprintf(fp, "\tmov rdx, rsp\n");
fprintf(fp, "\tsub rdx, %dd\n", par -> dynamicRecSize);
fprintf(fp, "\tmov word [rdx], ax\n");
}
break;
case AST_LEAF_VARIDNUM_RNUM: {
SymTableFunc * par = getParentFunc(curr -> localST);
curr -> nodeData.leaf -> temporaryOffset = par -> dynamicRecSize;
par -> dynamicRecSize += typeSize[AST_TYPE_REAL];
float val = curr -> nodeData.leaf -> tn -> value.val_float;
fprintf(fp, "\tmov rdx, rsp\n");
fprintf(fp, "\tsub rdx, %dd\n", par -> dynamicRecSize);
fprintf(fp, "\tmov dword [rdx], __float32__(%f)\n", val);
}
break;
case AST_LEAF_BOOLTRUE: {
SymTableFunc * par = getParentFunc(curr -> localST);
curr -> nodeData.leaf -> temporaryOffset = par -> dynamicRecSize;
par -> dynamicRecSize += typeSize[AST_TYPE_BOOLEAN];
fprintf(fp, "\tmov al, 1d\n");
fprintf(fp, "\tmov rdx, rsp\n");
fprintf(fp, "\tsub rdx, %dd\n", par -> dynamicRecSize);
fprintf(fp, "\tmov byte [rdx], al\n");
}
break;
case AST_LEAF_BOOLFALSE: {
SymTableFunc * par = getParentFunc(curr -> localST);
curr -> nodeData.leaf -> temporaryOffset = par -> dynamicRecSize;
par -> dynamicRecSize += typeSize[AST_TYPE_BOOLEAN];
fprintf(fp, "\tmov al, 0\n");
fprintf(fp, "\tmov rdx, rsp\n");
fprintf(fp, "\tsub rdx, %dd\n", par -> dynamicRecSize);
fprintf(fp, "\tmov byte [rdx], al\n");
}
break;
default: {
/* nothing required as of now */
}
}
}
break;
default: {
/* do nothing */
// fprintf(stderr, "Default error!\n");
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define N 5
int main(){
double a[N] = {
1.0, 2.0, 3.0, 4.0, 5.0
};
double b[N] = {0.0};
size_t ret = 0;
FILE* fp = fopen("temp.bin", "wb");
fwrite(a, sizeof(*a), N, fp);
fclose(fp);
fp = fopen("temp.bin", "rb");
ret = fread(b, sizeof(*b), N, fp);
if(ret == N){
puts("Array read successfully, contents: \n");
int i = 0;
for(; i < N; ++i){
printf("%f ", b[i]);
}
printf("\n");
}
else{
if(feof(fp)){
printf("Error reading temp.bin: unexpected end of file.\n");
}
else if(ferror(fp)){
perror("Error reading temp.bin.\n");
}
}
fclose(fp);
return 0;
}
|
C
|
#include "queue.h"
#include <pthread.h>
bool queueIsEmpty(Queue this)
{
return this.head->next == NULL;
}
Node *nodeCreate(void *data)
{
Node *this = malloc(sizeof(Node));
this->data = data;
this->next = this;
return this;
}
void queueEnqueue(Queue *this, void *data)
{
Node *node = nodeCreate(data);
if (this->head == NULL)
{
this->head = node;
this->tail = this->head;
this->head->next = this->tail;
}
else
{
this->tail->next = node;
this->tail = node;
}
}
void *queueDequeue(Queue *this)
{
if (this->head == NULL)
return NULL;
void *data;
Node *headNode = this->head;
data = headNode->data;
if (this->head == this->head->next)
{
this->head = NULL;
this->tail = NULL;
}
else
{
this->head = this->head->next;
}
if (headNode)
{
free(headNode);
}
return data;
}
void queueDestroy(Queue *this)
{
while (this->head)
{
Node *oldHead = this->head;
if (this->head->next == this->head)
{
this->head->next = NULL;
}
this->head = this->head->next;
free(oldHead);
}
this->tail = NULL;
}
|
C
|
#import <cs50.h>
#import <stdio.h>
#import <math.h>
int main (void) {
float amount;
do
{
printf("How much change is owed? ");
amount= get_float();
}
while (amount < 0);
// convert to cents
int cents = round(amount * 100);
int coins = 0;
if (cents >= 25)
{
coins += cents / 25;
cents %= 25;
}
if (cents >= 10)
{
coins += cents / 10;
cents %= 10;
}
if (cents >= 5)
{
coins += cents / 5;
cents %= 5;
}
if (cents >= 1)
{
coins += cents;
}
printf("%i\n", coins);
}
|
C
|
#include <stdio.h>
int main()
{
int a = 625;
char b = 65;
a = a / 25;
b = b + 2;
printf("a=%d\nb=%c", a, b);
return 0;
}
|
C
|
#include <stdlib.h>
#include <iostream>
#include <string>
#include "hash.h"
using namespace std;
hash::hash()
{
int i;
for(i = 0 ; i< tableSize; i++)
{
HashTable[i] = new item;
HashTable[i]->name = "empty";
HashTable[i]->drink = 0;
HashTable[i]->next = NULL;
}
}
void hash::AddItem(string name, double drink)
{
int index = Hash(name);
if(HashTable[index]->name == "empty")
{
HashTable[index]->name = name;
HashTable[index]->drink = drink;
}
else
{
item* Ptr = HashTable[index];
item* n = new item;
n->name = name;
n->drink = drink;
n->next = NULL;
while(Ptr->next != NULL)
{
Ptr = Ptr->next;
}
Ptr->next = n;
}
}
int hash::NumberOfItemsInIndex(int index)
{
int count = 0;
if(HashTable[index]->name == "empty")
{
return count;
}
else
{
count++;
item* Ptr = HashTable[index];
while(Ptr->next != NULL)
{
count++;
Ptr = Ptr->next;
}
}
return count;
}
void hash::PrintTable()
{
int number;
int i;
for(i = 0; i< tableSize; i++)
{
number = NumberOfItemsInIndex(i);
cout << "--------------------------\n";
cout << "index = " << i << endl;
cout << HashTable[i]->name << endl;
cout << HashTable[i]->drink << endl;
cout << "# of items = " << number << endl;
cout << "--------------------------\n";
}
}
void hash::PrintItemsInIndex(int index)
{
item* Ptr = HashTable[index];
if(Ptr->name == "empty")
{
cout << "index = " << index << " is empty" << endl;
}
else
{
cout << "index " << index << " contains the following items \n";
while(Ptr != NULL)
{
cout << "--------------------\n";
cout << Ptr->name << endl;
cout << Ptr->drink << endl;
cout << "--------------------\n";
Ptr = Ptr->next;
}
}
}
int hash::Hash(string key)
{
int hash = 0;
int index;
//index = key.length();
// cout << "key[0] = " << (int)key[0] <<endl;
// cout << "key[1] = " << (int)key[1] <<endl;
// cout << "key[2] = " << (int)key[2] <<endl;
// cout << "key[3] = " << (int)key[3] <<endl;
int i;
for(i=0; i< key.length(); i++)
{
hash = hash + (int)key[i];
//cout << "hash = " << hash << endl;
}
index = hash % tableSize;
return index;
}
|
C
|
/*
** EPITECH PROJECT, 2021
** B-PSU-101-BAR-1-1-minishell1
** File description:
** show_prompt
*/
#include "mini.h"
int last_slash(char *cwd)
{
int i = 0;
int slash_pos = 0;
while (cwd[i] != '\0') {
if (cwd[i] == '/')
slash_pos = i;
i++;
}
return (slash_pos);
}
char *set_color(char *color_code, char *str)
{
char *str_colored = my_malloc(my_strlen(str) + my_strlen(color_code) + 8);
str_colored = my_strcat(str_colored, color_code);
str_colored = my_strcat(str_colored, str);
str_colored = my_strcat(str_colored, "\033[0m");
return (str_colored);
}
void print_prompt(void)
{
int i = 0;
int j = 0;
char *buf = NULL;
size_t size = 0;
char *cwd = getcwd(buf, size);
char *color = my_malloc(my_strlen(cwd));
if (cwd == NULL) {
my_putstr("\033[22;34$>\033[0m");
} else {
i = last_slash(cwd);
while (cwd[i] != '\0') {
color[j] = cwd[i++];
j++;
}
my_putstr("\033[22;34m<\033[0m");
my_putstr(set_color("\033[1;32m", color));
my_putstr("\033[22;34m> \033[0m");
my_putstr(set_color("\033[1;31m", "~> "));
}
}
|
C
|
/* -*- Mode:C; Coding:us-ascii-unix; fill-column:132 -*- */
/* ****************************************************************************************************************************** */
/**
@file slvSysC.c
@author Mitch Richling <https://www.mitchr.me/>
@Copyright Copyright 1998 by Mitch Richling. All rights reserved.
@brief Demonstrate LAPACK's sgesv functions.@EOL
@Keywords claback cblas sgesv numerical linear algebra
@Std C99
*/
/* ------------------------------------------------------------------------------------------------------------------------------ */
#include <stdio.h> /* I/O lib ISOC */
#include <stdlib.h> /* Standard Lib ISOC */
#ifdef __APPLE__
#include <Accelerate/Accelerate.h> /* The MacOS X blas/lapack stuff */
typedef __CLPK_integer CLPKinteger;
typedef __CLPK_doublereal CLPKdoublereal;
#else
#include <clapack.h> /* C LAPACK */
typedef int CLPKinteger;
typedef double CLPKdoublereal;
#endif
#include "blaio.h" /* Basic Linear Algebra I/O */
int main(int argc, char **argv) {
CLPKdoublereal a[4*4] = { 1, 2, 3, 4,
6, 7, 9, 9,
11,12,19,14,
16,17,18,12,
};
CLPKdoublereal b[4] = {1, 3, 5, 6};
CLPKinteger pivs[4], inf;
CLPKinteger n=4, lda=4, nrhs=1, ldb=4;
char tbuf[1024];
int i;
sprintf(tbuf, " a[%dx%d]= ", 4, 4);
printMatrix(CblasColMajor, 4, 4, a, 15, 10, NULL, NULL, NULL, NULL, NULL, tbuf);
sprintf(tbuf, " b[%dx%d]= ", 1, 4);
printMatrix(CblasColMajor, 1, 4, b, 15, 10, NULL, NULL, NULL, NULL, NULL, tbuf);
//sgesv_(&n, &nrhs, a, &lda, pivs, b, &ldb, &inf);
dgesv_(&n, &nrhs, a, &lda, pivs, b, &ldb, &inf);
if(inf == 0) {
printf("Successful Solution\n");
} else if(inf < 0) {
printf("Illegal value at: %d\n", -(int)inf);
exit(1);
} else if(inf > 0) {
printf("Matrix was singular\n");
exit(1);
} else {
printf("Unknown Result (Can't happen!)\n");
exit(1);
} /* end if/else */
sprintf(tbuf, "a'[%dx%d]= ", 4, 4);
printMatrix(CblasColMajor, 4, 4, a, 15, 10, NULL, NULL, NULL, NULL, NULL, tbuf);
sprintf(tbuf, "b'[%dx%d]= ", 1, 4);
printMatrix(CblasColMajor, 1, 4, b, 15, 10, NULL, NULL, NULL, NULL, NULL, tbuf);
printf("PIV=");
for(i=0;i<4;i++)
printf("%4d ", (int)(pivs[i]));
printf("\n");
// * IPIV (output) INTEGER array, dimension (N)
// * The pivot indices that define the permutation matrix P;
// * row i of the matrix was interchanged with row IPIV(i).
// *
return 0;
} /* end func main */
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: obamzuro <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/10/06 19:24:19 by obamzuro #+# #+# */
/* Updated: 2018/10/06 22:17:32 by obamzuro ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <unistd.h>
int main(void)
{
register int s;
register int bytes;
struct sockaddr_in sa;
char buffer[BUFSIZ+1];
if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0)
{
perror("socket");
return (1);
}
bzero(&sa, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(1025);
sa.sin_addr.s_addr = htonl((((((127 << 8) | 0) << 8) | 0) << 8) | 1);
if (connect(s, (struct sockaddr *)&sa, sizeof(sa)) < 0)
{
perror("socket");
close(s);
return (2);
}
while ((bytes = read(s, buffer, BUFSIZ)) > 0)
write(1, buffer, bytes);
close(s);
return (0);
}
|
C
|
#include <stdio.h>
/*
* Our binary search makes two tests inside the loop,
* when one would suffice (at the price of more tests outside.)
* Write a version with only one test inside the loop
* and measure the difference in runtime.
*/
int bin_search(int x, int arr[], int n);
int main(void)
{
int arr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
printf("%d", bin_search(1, arr, 10));
return 0;
}
int bin_search(int x, int arr[], int n)
{
int low = 0;
int high = n - 1;
int mid = (low + high) / 2;
while (low < high && x != arr[mid])
{
if (x > arr[mid])
low = mid + 1;
else
low = high - 1;
}
if (x == arr[mid])
return mid;
else
return -1;
}
|
C
|
#include <WiFi.h>;
#include <AWS_IOT.h>;
AWS_IOT aws_iot;
int status = WL_IDLE_STATUS;
void connectToWifi(char* ssid, char* password) {
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
if(aws_iot.connect(AWS_HOST_ADDRESS, AWS_CLIENT_ID) == 0) {
Serial.println("Connected to AWS");
delay(1000);
} else {
Serial.println("AWS connection failed, Check the HOST Address");
}
}
int sendData(const char * data) {
char payload[sizeof(data)/sizeof(char*)];
sprintf(payload, data);
if (aws_iot.publish(AWS_TOPIC_NAME, payload) == 0) {
Serial.print("Publish Message:");
Serial.println(data);
} else {
Serial.println("Publish failed");
}
}
|
C
|
// Fixed on 03-19-2019 by Rodney DuPlessis (type mismatches)
#include <stdio.h>
#include <stdlib.h>
/* ----------------- Type definitions ----------------------------------- */
typedef struct /* period ( congruence class ) */
{
int mod; /* modulus of the period */
int ini; /* starting point */
} periode;
typedef struct /* intersection of several periods */
{
int clnb; /* number of terms in the intersection */
periode *cl; /* terms in the intersection */
periode clr; /* resulting period */
unsigned long ptval; /* current point value */
} inter;
/* Function prototype */
periode ReducInter(short u); /* computation of the intersections */
/* ----------------- variables ------------------------------------------- */
inter *fCrib; /* sieve formula */
int unb = 0; /* number of unions in the formula */
short u0, u1, u = 0; /* current union index */
short i = 0; /* current intersection index */
unsigned long lastval,n0,ptnb = 0;
periode CL_EMPTY = { 0, 0 }; /* empty period */
#define NONEMPTY 1
short flag = 0;
short decomp = 0;
/* ========================== Euclide's algorithm ======================== */
short Euclide (a1, a2) /* a1 >= a2 > 0 */
short a1;
short a2;
{
short tmp;
while ((tmp = a1 % a2) != 0)
{
a1 = a2;
a2 = tmp;
}
return a2;
}
/* ========================== De Meziriac's theorem ====================== */
short Meziriac (c1, c2) /* c1 >= c2 > 0 */
short c1;
short c2;
{
short T = 0;
if (c2 == 1)
T = 1;
else
while (((++T * c1) % c2) != 1)
;
return T;
}
/* =============Decomposition into an intersection of prime modules ====== */
void Decompos (periode pr)
{
periode pf;
short fct;
if (pr.mod == 0)
{
printf(" = (%d,%d)\n", pr.mod, pr.ini);
return;
}
printf(" =");
for ( i = 0, fct = 2; pr.mod != 1; fct++)
{
pf.mod = 1;
while (pr.mod % fct == 0 && pr.mod != 1)
{
pf.mod *= fct;
pr.mod /= fct;
}
if (pf.mod != 1)
{
pf.ini = pr.ini % pf.mod;
pr.ini %= pr.mod;
if (i != 0)
printf(" *");
printf(" (%d,%d)", pf.mod, pf.ini);
i++;
}
}
printf("\n");
}
/* ======================================================================= */
void main(void)
{
printf("SIEVES: user's guide\n\n"
"A. GENERATION OF POINTS ON A STRAIGHT LINE FROM\n"
" THE LOGICAL FORMULA OF THE SIEVE\n\n"
"Example:\n"
"---------------------------------\n"
"DEFINITION OF A SIEVE:\n"
" L = [() * () * ... * ()]\n"
" + [() * () * ... * ()]\n"
" + ...\n"
" + [() * () * ... * ()]\n\n"
"In each parenthesis are given in order: modulus, starting point\n"
" (taken from the set of integers)\n"
"[] + [] is a union\n"
"() * () is an intersection\n\n");
printf("---------------------------------\n"
"Given the formula of a sieve made out of unions and\n"
"intersections of moduli, the program reduces the number of\n"
"intersections to one and keeps only the given unions.\n"
"Then, the abscissa of the final points of the sieve are\n"
"computed from these unions and displayed.\n\n");
/* -------------- get the formula of the sieve ------------------------ */
while (unb == 0)
{
printf("NUMBER OF UNIONS? = ");
scanf("%d",&unb);
}
fCrib = (inter *)(malloc (sizeof(inter) * unb));
if (fCrib == NULL)
{
printf("not enough memory\n");
exit(1);
}
printf("---------------------------------\n");
for (u = 0; u < unb; u++)
{
printf("union %d: number of modules? = ", u + 1);
scanf("%d",&fCrib[u].clnb);
printf("\n");
fCrib[u].cl = (periode *)(malloc (sizeof(periode) * fCrib[u].clnb));
if (fCrib[u].cl == NULL)
{
printf("not enough memory\n");
exit(1);
}
for (i = 0; i < fCrib[u].clnb; i++)
{
printf("\n modulus %d? = ", i + 1);
scanf("%d",&fCrib[u].cl[i].mod);
printf(" start? = ");
scanf("%d",&fCrib[u].cl[i].ini);
}
printf("---------------------------------\n");
}
/* -------------- reduction of the formula ---------------------------- */
printf("FORMULA OF THE SIEVE:\n\n"
" L = [ ");
for (u = 0; u < unb; u++)
{
if (u != 0)
printf(" + [ ");
for (i = 0; i < fCrib[u].clnb; i++)
{
if (i != 0)
{
if (i % 4 == 0)
printf("\n ");
printf("* ");
}
printf("(%5d,%5d) ", fCrib[u].cl[i].mod, fCrib[u].cl[i].ini);
}
printf("]\n");
}
printf("---------------------------------\n");
printf("REDUCTION OF THE INTERSECTIONS:\n\n");
for (u = 0; u < unb; u++)
{
printf("union %d\n [ ",u + 1);
for (i = 0; i < fCrib[u].clnb; i++)
{
printf("(%d,%d) ", fCrib[u].cl[i].mod, fCrib[u].cl[i].ini);
if (i != fCrib[u].clnb - 1)
printf("* ");
}
fCrib[u].clr = ReducInter(u); /* reduction of an intersection */
printf("] = (%d,%d)\n\n", fCrib[u].clr.mod, fCrib[u].clr.ini);
printf(" Decomposition into prime modules ?\n"
" (press 'y' for yes, any other key for no): ");
if (getchar() == 'y')
{
printf("\n\n (%d,%d)", fCrib[u].clr.mod, fCrib[u].clr.ini);
Decompos(fCrib[u].clr);
}
else
printf("\n\n");
}
printf("---------------------------------\n");
/* -------------- display the simplified formula ---------------------- */
printf("SIMPLIFIED FORMULA OF THE SIEVE:\n\n");
printf(" L = ");
for (u = 0; u < unb; u++)
{
if (u != 0)
{
if (u % 4 == 0)
printf("\n ");
printf("+ ");
}
printf("(%5d,%5d) ", fCrib[u].clr.mod, fCrib[u].clr.ini);
}
printf("\n---------------------------------\n");
/* -------------- points of the sieve --------------------------------- */
printf("POINTS OF THE SIEVE CALCULATED WITH THIS FORMULA:\n");
printf("Rank of first displayed point? = ");
scanf("%lu",&n0);
n0 = n0 - n0 % 10;
printf("\npress <enter> to get a series of 10 points\n\n"
"Rank |");
for (u = 0; u < unb; u++)
{
if (fCrib[u].clr.mod != 0 || fCrib[u].clr.ini != 0)
{
fCrib[u].ptval = fCrib[u].clr.ini;
flag = NONEMPTY;
}
else
fCrib[u].ptval = 0xFFFFFFFF;
}
if (flag != NONEMPTY)
return;
u0 = u1 = 0;
lastval = 0xFFFFFFFF;
while (1)
{
for (u = (u0 + 1) % unb; u != u0; u = (u + 1) % unb)
{
if (fCrib[u].ptval <= fCrib[u1].ptval)
u1 = u;
}
if (fCrib[u1].ptval != lastval) /* new point */
{
lastval = fCrib[u1].ptval;
if (ptnb >= n0)
{
if (ptnb % 10 == 0)
{
getchar(); /* get a character from the keyboard */
printf("\n%7lu |", ptnb);
}
printf("%6lu ", fCrib[u1].ptval);
}
ptnb++;
}
fCrib[u1].ptval += fCrib[u1].clr.mod;
u0 = u1;
}
}
/* ========================== Reduction of an intersection =============== */
periode ReducInter(short u)
{
periode cl,cl1,cl2,cl3;
short pgcd,T,n;
long c1,c2;
cl3 = fCrib[u].cl[0];
for (n = 1; n < fCrib[u].clnb; n++)
{
cl1 = cl3;
cl2 = fCrib[u].cl[n];
if (cl1.mod < cl2.mod)
{
cl = cl1;
cl1 = cl2;
cl2 = cl;
}
if (cl1.mod != 0 && cl2.mod != 0)
{
cl1.ini %= cl1.mod;
cl2.ini %= cl2.mod;
}
else
return CL_EMPTY;
/* module resulting from the intersection of 2 modules */
pgcd = Euclide(cl1.mod, cl2.mod);
c1 = cl1.mod / pgcd;
c2 = cl2.mod / pgcd;
if (pgcd != 1
&& ( (cl1.ini - cl2.ini) % pgcd != 0 ))
return CL_EMPTY;
if (pgcd != 1
&& ((cl1.ini - cl2.ini) % pgcd == 0)
&& (cl1.ini != cl2.ini) && (c1 == c2) )
{
cl3.mod = pgcd;
cl3.ini = cl1.ini;
continue;
}
T = Meziriac((short) c1, (short) c2);
cl3.mod = (short) (c1 * c2 * pgcd);
cl3.ini = (short) (( cl1.ini
+ T * (cl2.ini - cl1.ini) * c1) % cl3.mod);
while (cl3.ini < cl1.ini || cl3.ini < cl2.ini)
cl3.ini += cl3.mod;
}
return cl3;
}
|
C
|
/*
* File: CONTROLDEMOTOR.c
* Author: kenst
*
* Created on 11 de mayo de 2021, 10:34
*/
#include <xc.h>
#include <stdio.h>
#include "LCD2.h"
#define _XTAL_FREQ 4000000
float ciclo;
float ccp = 0;
float ccp1 = 0;
float dato[];
int res;
void configuracion_registros(void);
void Ciclo_util (void);
void PWM (void);
void main(void)
{
TRISA = 1;
TRISC = 0;
TRISD = 0;
TRISC = 0;
configuracion_registros();
lcd_init();
lcd_clear_display();
__delay_ms (10);
lcd_clear_display();
lcd_goto(3,0);
lcd_print ("DUTY CYCLE");
while (1){
Ciclo_util ();
sprintf (dato, "%f",ciclo);
lcd_goto(0,2);
lcd_print(dato);
lcd_print(" % ");
__delay_ms(100);
PWM ();
}
return;
}
void configuracion_registros(void)
{
ADCON0 = 0;
ADCON1 = 14;
ADCON2 = 148;
}
void Ciclo_util (void){
ADCON0bits.ADON = 1;
ADCON0bits.GO_DONE = 1;
while(ADCON0bits.GO_DONE == 1)
{
float dutycycle = 0;
float dutycyclet = 0;
dutycyclet = ADRESL +(ADRESH*256);
dutycycle = dutycyclet*100/1023;
ciclo = dutycycle;
}
}
void PWM (void){
/*PR2 = 99;
ccp = ciclo;
CCPR1L = ccp;
TRISCbits.RC1 = 0;
TRISCbits.RC2 = 0;
if (ccp >=768){
ccp1 = 3;
}
else if (ccp >=512){
ccp1 = 2;
}
else if (ccp >=256){
ccp1 = 1;
}
else{
ccp1 = 0;
}
T2CON = 0x00;
CCP1CON = (ccp1*16)+12;
TMR2 = 0;
T2CONbits.TMR2ON = 1;*/
PR2 = 99;
ccp = ciclo;
res = ccp*400/100; // Variacion del del motor
CCPR1L = res>>2;// sin las 2 ultimas cifras
TRISCbits.RC1 = 0;
TRISCbits.RC2 = 0;
T2CON = 0x00;
CCP1CON =0x0C;// configurado como PWM
TMR2 = 0;
T2CONbits.TMR2ON = 1;
}
|
C
|
#include<stdio.h>
void main()
{
int N,k,i,j=1;
int ar[10];
printf("Enter the values:");
scanf("%d %d",&N,&k);
for(i=N;i>=1;i--)
{
if(N%i==0)
{
ar[j]=i;
j++;
}
}
if(k<j)
{
printf("%d",ar[k]);
}
else
printf("1");
}
|
C
|
#pragma once
#include "constants.h"
#define ui unsigned int
#define uli unsigned long int
#define cp char *
#define MAX_FRIENDS 50
#define MAX_USERS 100
typedef struct tophChatUser TUSER;
typedef struct database TINFO;
/*For our data structure, we will use a
* graph and represent the users as nodes*/
struct tophChatUser
{
cp userName;
ui password;
ui hashedPassword;
cp name;
ui hashID;
cp email;
cp phone;
TUSER *friends[MAX_FRIENDS]; //Edges to graph
ui friendCount;
uli publicKey;
int numOfRoomUserIn;
int listOfRooms[CHAT_ROOM_LIMIT];
int socket;
};
struct database
{
ui numOfUsers;
TUSER *Users[MAX_USERS];
uli publicKey;
uli privateKey;
};
/*Creates a dataBase for data collecting */
TINFO *createTINFO();
TUSER *addUser(cp _userName, cp _name,
ui _hashedPassword, TINFO *userBase);
//Deletes the user
int deleteUser(TUSER *user);
ui hashID(cp userName);
//returns 0 if successful, 1 if not successful
//sends in both userName of the person who the inidivudal
//wants added, as well as the address of the person making
//the request
int addFriend(cp userName, TUSER *user, TINFO *userbase);
//Check if user exists in the database
//traverses through linked list to check
//if user is found, return address,
//else null
TUSER *checkUserByName(cp userName, TUSER *user);
//List friends
void showFriends(TUSER *user);
//Lists all the friends
/* returns a list of the friends like this
* james/arvin/boostedgorilla/abel + '\0'
*/
int getFriends(cp username, TINFO *userbase, cp list);
//Authentification gets the actual user struct
//and checks if the password is correct
//return 0 for true
//return 1 for false
int authentifyUser(cp username, ui hashpassword, TINFO *userbase);
int checkIfFriends(TUSER *user1, TUSER *user2);
//Find a user based off username
TUSER *findUserByName(cp username, TINFO *userbase);
//Remove friend
int deleteFriend(TUSER *user1, cp username);
//chek if user is online,
int checkSocket(TUSER *user);
//Change socket based off if they are online
int changeSocket(TUSER *user, int socket);
//Saves the user to a text file (appends it to the end
int saveUser(TUSER *user);
//Loads the user
int loadUser(cp textFile, TINFO *userBase);
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
#include "../include/str_list.h"
#define MAX_WORD_LENGTH 50
int load_lines_from_file(char* fileName, str_list *out_line_list) {
char str[MAX_WORD_LENGTH];
FILE *fp;
if ((fp = fopen(fileName, "r")) == NULL) {
//printf("Cannot open file %s\n", fileName);
return 0;
}
while (fgets(str, MAX_WORD_LENGTH, fp) != NULL) {
// remove newline char
if (str[strlen(str) - 1] == '\n') {
str[strlen(str) - 1] = '\0';
}
add_str(out_line_list, str);
}
fclose(fp);
if (size(out_line_list) == 0) {
//printf("Could not open file %s or file was empty.", fileName);
return 0;
}
return 1;
}
|
C
|
/*
** Chapter 1, Exercise 2
** Write a program that reads lines from the standard input.
** Each line is printed on the standard output preceded by its line number.
** Try to write the program so that it has no built‐in limit on how long a line
** it can handle.
*/
#include <stdio.h>
int main(void) {
char ch;
int lines = 0;
int new_line = 1;
while ((ch = getchar()) != EOF) {
if (new_line) {
lines++;
printf("%d: ", lines);
new_line = 0;
}
putchar(ch);
if (ch == '\n')
new_line = 1;
}
return 0;
}
|
C
|
#include "lvp_nqueue.h"
LVPNQueue *lvp_nqueue_alloc(int cap){
LVPNQueue *q = (LVPNQueue*)lvp_mem_mallocz(sizeof(*q));
q->cap = cap;
q->datas = lvp_mem_mallocz(sizeof(LVPQueueEntry)*cap);
for (size_t i = 0; i < cap; i++)
{
q->datas[i] = lvp_mem_mallocz(sizeof(LVPQueueEntry));
}
return q;
}
void lvp_nqueue_free(LVPNQueue *q){
lvp_nqueue_clear(q);
for (size_t i = 0; i < q->cap; i++)
{
lvp_mem_free(q->datas[i]);
}
lvp_mem_free(q->datas);
lvp_mem_free(q);
}
int lvp_nqueue_push(LVPNQueue *q, void *data,void *usr_data, lvp_custom_free free,LVP_BOOL need_free){
if(q->size==q->cap){
return LVP_FALSE;
}
LVPQueueEntry *entry = q->datas[q->wpos];
entry->data = data;
entry->usr_data = usr_data;
entry->need_free = need_free;
entry->free = free;
q->wpos++;
q->size++;
if (q->wpos == q->cap) {
q->wpos = 0;
}
return LVP_TRUE;
}
void* lvp_nqueue_pop(LVPNQueue *q){
if(q->size==0){
return NULL;
}
LVPQueueEntry *entry = q->datas[q->rpos];
q->rpos++;
if (q->rpos == q->cap) {
q->rpos = 0;
}
q->size--;
return entry->data;
}
void lvp_nqueue_clear(LVPNQueue* q)
{
while (q->size>0)
{
if (q->rpos == q->cap)
{
q->rpos = 0;
}
LVPQueueEntry* entry = q->datas[q->rpos];
if (entry->need_free == LVP_TRUE) {
if (entry->free) {
entry->free(entry->data, entry->usr_data);
}
else
{
lvp_mem_free(entry->data);
}
entry->data = NULL;
entry->usr_data = NULL;
}
q->size--;
q->rpos++;
}
q->rpos = 0;
q->wpos = 0;
q->size = 0;
return;
}
|
C
|
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <signal.h>
#include <errno.h>
void TestFun()
{
printf("child\n");
}
int main()
{
int procnum =10;
int loopnum = 100;
int i =0;
int ret;
pid_t pid;
for(i=0; i< procnum; i++)
{
pid = fork();
if(pid == 0)
{
TestFun();
exit(0);
}
}
// ?????????????????????????????????
while(1)
{
ret = wait(NULL);
if(ret == -1)
{
if(errno == EINTR)
continue;
break;
}
}
printf("parent quit \n");
return 0;
}
|
C
|
int main()
{
int a,b,c,err;
printStr("Enter the first number: ");
a = readInt(&err);
printStr("Enter the second number: ");
b = readInt(&err);
printStr("Enter the third number: ");
c = readInt(&err);
int *x,*y,*z;
char p,q,r;
char *m,*n,*o;
p = 'a';
q = 'b';
r = 'd';
m = &p;
n = &q;
o = &r;
x = &a;
y = &b;
z = &c;
*x = *y;
printStr("The first number address was pointed to second one: ");
printInt(a);
printStr("\n");
*y = *z;
printStr("The second number address was pointed to third one: ");
printInt(b);
printStr("\n");
int i = 0;
if(a<b)
{
do
{
i++;
a++;
}while(a<b);
printStr("After pointer arrangements second was greater than first by :");
printInt(i);
printStr("\n");
}
else
{
do
{
i++;
b++;
}while(a>b);
printStr("After pointer arrangements second was less than first by :");
printInt(i);
printStr("\n");
}
printStr("Character comparison");
printStr("\n");
if(*n<*o)
{
printStr("q was less\n");
}
else
{
if(*n>*m)
{
printStr("q was best\n");
}
else
{
printStr("p was best\n");
}
}
printStr("A character array handling. Ignore the garbage due to lack of terminal null char\n");
char car[5];
car[0] = 'y';
car[1] = 'o';
car[2] = 'u';
car[3] = 'r';
car[4] = '\n';
int i;
for(i=0;i<5;i++)
{
printStr(&car[i]);
printStr("\n");
}
return 0;
}
|
C
|
/*
// Title: example.c
// Author: Sahaj Sarup
// Copyright (c) 2019 Linaro Limited
*/
#include <stdio.h>
#include <stdlib.h>
/* mraa header */
#include "mraa/i2c.h"
#include "fpga_mezz.h"
int main()
{
mraa_result_t status = MRAA_SUCCESS;
mraa_i2c_context i2c;
mraa_init();
i2c = mraa_i2c_init(I2C_BUS);
int input, ver;
if (i2c == NULL) {
fprintf(stderr, "Failed to initialize I2C\n");
mraa_deinit();
return EXIT_FAILURE;
}
/* set slave address */
status = mraa_i2c_address(i2c, FPGA_MEZZI_ADDR);
if (status != MRAA_SUCCESS) {
}
/* Simple Test function to test the I2C Communication */
if(test(i2c)==0)
{
printf("Test Passed\n");
}
else
{
printf("Test Failed\n");
return 1;
}
/* Check Firmware Revision of the FPGA Mezzanine */
ver = check_version(i2c);
if(ver == -1)
{
printf("Version Check Error\n");
return 1;
}
else
{
printf("Version %d\n",&ver);
}
/* Set Pins 7,6,5 and 4 as output */
pinMode(7,OUTPUT,i2c);
pinMode(6,OUTPUT,i2c);
pinMode(5,OUTPUT,i2c);
pinMode(4,OUTPUT,i2c);
/* Passthrough I2C0 to 96Boards LS header */
pinFunction(ARD_I2C_0_FUNC,FUNC_PASSTHROUGH,i2c);
/* Do not passthrough SPI, use as GPIO instead */
pinFunction(ARD_SPI_FUNC,FUNC_GPIO,i2c);
/* Set pin 13 as input */
pinMode(13,INPUT,i2c);
/* Write pins D7 and D4 on the Arduino header */
digitalWrite(7,HIGH,i2c);
digitalWrite(4,HIGH,i2c);
while(1)
{
/* Read pin D13 on the Arduino header */
input = digitalRead(13,i2c);
if(input == LOW)
{
digitalWrite(6,HIGH,i2c);
digitalWrite(5,LOW,i2c);
}
else if(input == HIGH)
{
digitalWrite(6,LOW,i2c);
digitalWrite(5,HIGH,i2c);
}
printf("%d\n",input);
usleep(100);
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <fpga.h>
#include <drvLib.h>
#include "csl/csl.h"
#include "csl/fpga.h"
/*
// Fpga_Open - Open FPGA Object.
//
// RETURNS: 0 success, -1 if failed.
*/
int Fpga_Open( void )
{
return Drv_Open(CSL_MODULE_FPGA);
}
/*
// Fpga_Close - Close FPGA Object.
//
// RETURNS: 0 success, -1 if failed.
*/
int Fpga_Close( int hndl )
{
return Drv_Close(hndl);
}
/*
// Fpga_Load - Program PFGA file.
//
// RETURNS: 0 success, -1 if failed.
*/
int Fpga_Load( int hndl, char* name )
{
char buf[CSL_FPGA_DATA_SZ];
FILE *fp = NULL;
/* Start Program */
if (Drv_Ioctl(hndl, CSL_FPGA_CMD_START, NULL))
{
return -1;
}
/* Open updated file */
fp = fopen(name, "r");
if (fp == NULL)
{
return -2;
}
/* Send all data to FPGA */
while (!feof(fp))
{
memset(buf, 0, CSL_FPGA_DATA_SZ);
fread(buf, CSL_FPGA_DATA_SZ, 1, fp);
if (Drv_Ioctl(hndl, CSL_FPGA_CMD_LOAD, buf))
{
fclose(fp);
return -3;
}
}
fclose(fp);
/* End FPGA update */
if (Drv_Ioctl(hndl, CSL_FPGA_CMD_STOP, NULL))
{
return -4;
}
return 0;
}
/*
// Fpga_Done - Check if FPGA Object is done.
//
// RETURNS: 0 success, -1 if failed.
*/
int Fpga_Done( int hndl )
{
int done = 0;
/* End FPGA update */
if (Drv_Ioctl(hndl, CSL_FPGA_CMD_DONE, &done))
{
return -1;
}
return done;
}
/* End of file */
|
C
|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
/*=============================================================
**
** Source: getmodulefilenamew.c
**
** Purpose: Positive test the GetModuleFileName API.
** Call GetModuleFileName to retrive current process
** full path and file name by passing a NULL module handle
** in UNICODE
**
**
**============================================================*/
#define UNICODE
#include <palsuite.h>
#define MODULENAMEBUFFERSIZE 1024
int __cdecl main(int argc, char *argv[])
{
DWORD ModuleNameLength;
WCHAR *ModuleFileNameBuf;
int err;
//Initialize the PAL environment
err = PAL_Initialize(argc, argv);
if(0 != err)
{
ExitProcess(FAIL);
}
ModuleFileNameBuf = malloc(MODULENAMEBUFFERSIZE*sizeof(WCHAR));
//retrive the current process full path and file name
//by passing a NULL module handle
ModuleNameLength = GetModuleFileName(
NULL, //a NULL handle
ModuleFileNameBuf,//buffer for module file name
MODULENAMEBUFFERSIZE);
//free the memory
free(ModuleFileNameBuf);
if(0 == ModuleNameLength)
{
Fail("\nFailed to all GetModuleFileName API!\n");
}
PAL_Terminate();
return PASS;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include "jiggle.h"
jgSpace *jgSpaceAlloc()
{
jgSpace *space = malloc(sizeof(jgSpace));
space->particles = jgListNew();
space->areas = jgListNew();
space->springs = jgListNew();
space->pendingCollisions = jgListNew();
space->collisions = jgListNew();
return space;
}
jgSpace *jgSpaceInit(jgSpace *space)
{
space->penetrationThreshold = 0.3;
space->damping = 0.999;
space->gravity = jgVector2Zero();
return space;
}
jgSpace *jgSpaceNew()
{
return jgSpaceInit(jgSpaceAlloc());
}
void jgSpaceFree(jgSpace *space)
{
jgListFree(space->particles);
jgListFree(space->areas);
jgListFree(space->springs);
jgListFree(space->pendingCollisions);
jgListFree(space->collisions);
free(space);
}
void jgSpaceClearCollisions(jgSpace *space)
{
jgCollision *collision;
JG_LIST_FOREACH(space->collisions, collision)
jgCollisionFree(collision);
jgListClear(space->collisions);
}
void jgSpaceFreeChildren(jgSpace *space)
{
jgSpaceClearCollisions(space);
jgParticle *currentParticle;
JG_LIST_FOREACH(space->particles, currentParticle)
{
jgParticleFree(currentParticle);
}
jgSpring *currentSpring;
JG_LIST_FOREACH(space->springs, currentSpring)
{
jgSpringFree(currentSpring);
}
jgArea *currentArea;
JG_LIST_FOREACH(space->areas, currentArea)
{
jgAreaFree(currentArea);
}
}
#define CREATE_ADDS_AND_REMOVES(class, name) \
void jgSpaceAdd ## class(jgSpace *space, jg ## class *name) \
{ \
if(!jgListContains(space->name ## s, name)) \
{ \
jgListAdd(space->name ## s, name); \
} \
} \
\
void jgSpaceRemove ## class(jgSpace *space, jg ## class *name) \
{ \
if(jgListContains(space->name ## s, name)) \
{ \
jgListRemove(space->name ## s, name); \
} \
} \
CREATE_ADDS_AND_REMOVES(Area, area)
CREATE_ADDS_AND_REMOVES(Particle, particle)
CREATE_ADDS_AND_REMOVES(Spring, spring)
#undef CREATE_ADDS_AND_REMOVES
void jgSpaceHandleCollisions(jgSpace *space, float timeStep)
{
jgCollision *collision;
JG_LIST_FOREACH(space->pendingCollisions, collision)
{
jgParticle *A = collision->particle;
jgParticle *B1 = collision->areaParticleA;
jgParticle *B2 = collision->areaParticleB;
if(collision->penetration > space->penetrationThreshold)
{
space->penetrationCount++;
continue;
}
jgVector2 averageBVelocity = jgVector2Divide(jgVector2Add(B1->velocity, B2->velocity), 2);
jgVector2 relativeVelocity = jgVector2Subtract(A->velocity, averageBVelocity);
float relativeDot = jgVector2Dot(collision->normal, relativeVelocity);
float jDenom = 1.0/A->mass + 1.0/(B1->mass + B2->mass);
float elasticity = 1 + A->elasticity * (B1->elasticity + B2->elasticity) / 2;
jgVector2 numV = jgVector2Multiply(relativeVelocity, elasticity);
float jNumerator = -jgVector2Dot(numV, collision->normal);
float j = jNumerator / jDenom;
jgVector2 tangent = jgVector2Perpendicular(collision->normal);
float friction = A->friction * (B1->friction + B2->friction) / 2;
float fNumerator = jgVector2Dot(relativeVelocity, tangent) * friction;
float f = fNumerator / jDenom;
if(A->mass != INFINITY)
{
A->position = jgVector2Add(A->position, jgVector2Multiply(collision->normal, collision->Amove));
}
if(B1->mass + B2->mass != INFINITY)
{
B1->position = jgVector2Subtract(B1->position, jgVector2Multiply(collision->normal, collision->B1move));
B2->position = jgVector2Subtract(B2->position, jgVector2Multiply(collision->normal, collision->B2move));
}
if(relativeDot < 0)
{
jgVector2 Achange = jgVector2Subtract(jgVector2Multiply(collision->normal, j / A->mass),
jgVector2Multiply(tangent, f / A->mass));
A->prevPos = jgVector2Subtract(A->prevPos, jgVector2Multiply(Achange, timeStep));
jgVector2 B1change = jgVector2Subtract(jgVector2Multiply(collision->normal, j / B1->mass * (1.0 - collision->edgeD)),
jgVector2Multiply(tangent, f / B1->mass * (1.0 - collision->edgeD)));
B1->prevPos = jgVector2Add(B1->prevPos, jgVector2Multiply(B1change, timeStep));
jgVector2 B2change = jgVector2Subtract(jgVector2Multiply(collision->normal, j / B2->mass * collision->edgeD),
jgVector2Multiply(tangent, f / B2->mass * collision->edgeD));
B2->prevPos = jgVector2Add(B2->prevPos, jgVector2Multiply(B2change, timeStep));
}
}
jgListClear(space->pendingCollisions);
}
void jgSpaceStep(jgSpace *space, float timeStep)
{
space->penetrationCount = 0;
jgParticle *currentParticle;
JG_LIST_FOREACH(space->particles, currentParticle)
{
jgParticleDampenVelocity(currentParticle, space->damping);
if(!currentParticle->floating)
jgParticleAddMasslessForce(currentParticle, space->gravity);
}
jgSpring *currentSpring;
JG_LIST_FOREACH(space->springs, currentSpring)
{
jgSpringExert(currentSpring);
}
jgArea *currentArea;
JG_LIST_FOREACH(space->areas, currentArea)
{
jgAreaDerive(currentArea);
if(currentArea->isShapeMatching)
jgAreaMatchShape(currentArea);
}
JG_LIST_FOREACH(space->particles, currentParticle)
{
jgParticleIntegrate(currentParticle, timeStep);
}
JG_LIST_FOREACH(space->areas, currentArea)
{
currentArea->isValid = !jgAreaIsInsideOut(currentArea);
jgAreaUpdateAABB(currentArea, timeStep);
jgAreaUpdateCenterOfMass(currentArea);
}
jgQuadtree *tree = jgQuadtreeNew(space->areas);
jgParticle *particle;
JG_LIST_FOREACH(space->particles, particle)
{
if(!particle->collidable)
continue;
void jgSpaceEachCandidate(jgArea *area)
{
if(jgListContains(area->particles, particle))
return;
if(!jgAABBContains(area->aabb, particle->position))
return;
if(!jgAreaContains(area, particle->position))
return;
if(!area->isValid)
return;
jgCollision *collision = jgCollisionFind(area, particle);
jgListAdd(space->collisions, collision);
jgListAdd(space->pendingCollisions, collision);
}
jgQuadtreeEachCandidate(tree, particle->position, jgSpaceEachCandidate);
}
jgQuadtreeFree(tree);
jgSpaceHandleCollisions(space, timeStep);
}
|
C
|
#include<stdio.h>
int flower(int);
int flower(int n){
if((n/100)*(n/100)*(n/100)+(n/10%10)*(n/10%10)*(n/10%10)+(n%10)*(n%10)*(n%10)==n)
return 1;
else
return 0;
}
int main(){
int x;
scanf("%d",&x);
printf("%d",flower(x));
}
|
C
|
#include <stdio.h>
#include <cs50.h>
#include <string.h>
int main(void)
{
char *s1 = get_string("s1: ");
char *s2 = get_string("s2: ");
printf("%lu\n", sizeof(s1));
char *s3 = concatenate(s1, s2);
printf("%s\n", s3);
free(s3);
}
// TODO: Implement concatenate function
|
C
|
#ifndef VECTOR_H
#define VECTOR_H
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#define VECTOR_MAX_SIZE (8)
struct Vector
{
int _element_size; // the size of each element
int _size; // current used size of vector
int _max_size; // max size of vector, default is VECTOR_MAX_SIZE
void *_data; // 1*_max_size
int (*get_element_size)(struct Vector *this);
int (*get_size)(struct Vector *this);
int (*get_max_size)(struct Vector *this);
void (*push_back)(struct Vector *this,void *data);
void * (*get)(struct Vector *this,const int idx);
void (*set)(struct Vector *this,const int idx,void *data);
void (*erase)(struct Vector *this,const int idx);
void (*swap)(struct Vector *this,const int idx_a,const int idx_b);
void *(*front)(struct Vector *this);
void *(*back)(struct Vector *this);
};
typedef struct Vector Vector;
struct Vector *create_Vector(const int element_size);
struct Vector *create_size_Vector(const int element_size,const int vector_size);
void free_Vector(struct Vector *this);
#endif
|
C
|
/*
** EPITECH PROJECT, 2019
** my_sokoban
** File description:
** fragment the map
*/
#include "my.h"
void fragment_map(char *buffer, char *new_map)
{
int lines = count_lines(buffer);
char **map = malloc(sizeof(char *) * lines);
int temp = 0;
int k = 0;
for (int j = 0; buffer[temp] != '\0'; temp++) {
if (buffer[temp] == '\n')
j++;
map[j] = malloc(sizeof(char) * (temp + 1));
}
temp = 0;
for (int j = 0; buffer[temp] != '\0'; temp++, k++) {
if (buffer[temp] == '\n') {
map[j][temp] = '\0';
j++;
temp++;
k = 0;
}
map[j][k] = buffer[temp];
}
display_map(map, lines, new_map);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "fifo.h"
FIFO * fifo_new_list()
{
FIFO * li = (FIFO*)malloc(sizeof(FIFO));
if(li!=NULL)
{
li->pHeadPos = NullPos;
li->pTailPos = NullPos;
li->pCurrentPos = NullPos;
}
return li;
}
void fifo_delete_list(FIFO * li)
{
if(li==NULL)
return;
ElementNode node = fifo_pop_node(li);
while(node)
{
memory_delete_data(node);
node = fifo_pop_node(li);
}
free(li);
}
void fifo_release_data(FIFO * li)
{
if(li==NULL)
return;
ElementNode node = fifo_pop_node(li);
while(node)
{
memory_delete_data(node);
node = fifo_pop_node(li);
}
}
ElementNode fifo_get_head(FIFO * li)
{
if(li==NULL)
return NullNode;
li->pCurrentPos = li->pHeadPos;
if(li->pCurrentPos==NullPos)
return NullNode;
return li->pCurrentPos->CurrentNode;
}
ElementNode fifo_get_next(FIFO * li)
{
if(li==NULL)
return NullNode;
if(li->pCurrentPos==NullPos)
return NullNode;
li->pCurrentPos = (Position*)li->pCurrentPos->pNextPos;
if(li->pCurrentPos==NullPos)
return NullNode;
return li->pCurrentPos->CurrentNode;
}
ElementNode fifo_get_last(FIFO * li)
{
if(li==NULL)
return NullNode;
li->pCurrentPos = li->pTailPos;
if(li->pCurrentPos==NullPos)
return NullNode;
return li->pCurrentPos->CurrentNode;
}
void fifo_push_node(ElementNode node,FIFO * li)
{
if(li==NULL)
return;
Position * pos = (Position*)malloc(sizeof(Position));
if(pos==NULL)
return;
pos->CurrentNode = node;
pos->pPrevPos = li->pTailPos;
pos->pNextPos = NullPos;
if(li->pTailPos==NullPos)
li->pTailPos = pos;
else
{
li->pTailPos->pNextPos = pos;
li->pTailPos = pos;
}
if(li->pHeadPos==NullPos)
li->pHeadPos = pos;
//printf("node=%x,prev=%x,pos=%x,next=%x\n",node,pos->pPrevPos,pos,pos->pNextPos);
}
ElementNode fifo_pop_node(FIFO * li)
{
if(li==NULL)
return NullNode;
Position * pos = li->pHeadPos;
if(pos==NullPos)
return NullNode;
ElementNode node = pos->CurrentNode;
if(pos->pNextPos==NullPos)
{
li->pCurrentPos = NullPos;
li->pHeadPos = NullPos;
li->pTailPos = NullPos;
}
else
{
li->pCurrentPos = (Position*)pos->pNextPos;
li->pCurrentPos->pPrevPos = NullNode;
li->pHeadPos = li->pCurrentPos;
}
//printf("node=%x,prev=%x,pos=%x,next=%x\n",node,pos->pPrevPos,pos,pos->pNextPos);
free(pos);
return node;
}
ElementNode fifo_getcurrent_node(FIFO * li)
{
if(li==NULL)
return NullNode;
if(li->pCurrentPos==NullPos)
return NullNode;
return li->pCurrentPos->CurrentNode;
}
|
C
|
#include "clar_libgit2.h"
#include "reflog.h"
static git_repository *g_repo;
static git_reflog *g_reflog;
static size_t entrycount;
void test_refs_reflog_drop__initialize(void)
{
g_repo = cl_git_sandbox_init("testrepo.git");
git_reflog_read(&g_reflog, g_repo, "HEAD");
entrycount = git_reflog_entrycount(g_reflog);
}
void test_refs_reflog_drop__cleanup(void)
{
git_reflog_free(g_reflog);
g_reflog = NULL;
cl_git_sandbox_cleanup();
}
void test_refs_reflog_drop__dropping_a_non_exisiting_entry_from_the_log_returns_ENOTFOUND(void)
{
cl_assert_equal_i(GIT_ENOTFOUND, git_reflog_drop(g_reflog, entrycount, 0));
cl_assert_equal_sz(entrycount, git_reflog_entrycount(g_reflog));
}
void test_refs_reflog_drop__can_drop_an_entry(void)
{
cl_assert(entrycount > 4);
cl_git_pass(git_reflog_drop(g_reflog, 2, 0));
cl_assert_equal_sz(entrycount - 1, git_reflog_entrycount(g_reflog));
}
void test_refs_reflog_drop__can_drop_an_entry_and_rewrite_the_log_history(void)
{
const git_reflog_entry *before_current;
const git_reflog_entry *after_current;
git_oid before_current_old_oid, before_current_cur_oid;
cl_assert(entrycount > 4);
before_current = git_reflog_entry_byindex(g_reflog, 1);
git_oid_cpy(&before_current_old_oid, &before_current->oid_old);
git_oid_cpy(&before_current_cur_oid, &before_current->oid_cur);
cl_git_pass(git_reflog_drop(g_reflog, 1, 1));
cl_assert_equal_sz(entrycount - 1, git_reflog_entrycount(g_reflog));
after_current = git_reflog_entry_byindex(g_reflog, 0);
cl_assert_equal_i(0, git_oid_cmp(&before_current_old_oid, &after_current->oid_old));
cl_assert(0 != git_oid_cmp(&before_current_cur_oid, &after_current->oid_cur));
}
void test_refs_reflog_drop__can_drop_the_oldest_entry(void)
{
const git_reflog_entry *entry;
cl_assert(entrycount > 2);
cl_git_pass(git_reflog_drop(g_reflog, entrycount - 1, 0));
cl_assert_equal_sz(entrycount - 1, git_reflog_entrycount(g_reflog));
entry = git_reflog_entry_byindex(g_reflog, entrycount - 2);
cl_assert(git_oid_streq(&entry->oid_old, GIT_OID_HEX_ZERO) != 0);
}
void test_refs_reflog_drop__can_drop_the_oldest_entry_and_rewrite_the_log_history(void)
{
const git_reflog_entry *entry;
cl_assert(entrycount > 2);
cl_git_pass(git_reflog_drop(g_reflog, entrycount - 1, 1));
cl_assert_equal_sz(entrycount - 1, git_reflog_entrycount(g_reflog));
entry = git_reflog_entry_byindex(g_reflog, entrycount - 2);
cl_assert(git_oid_streq(&entry->oid_old, GIT_OID_HEX_ZERO) == 0);
}
void test_refs_reflog_drop__can_drop_all_the_entries(void)
{
cl_assert(--entrycount > 0);
do {
cl_git_pass(git_reflog_drop(g_reflog, 0, 1));
} while (--entrycount > 0);
cl_git_pass(git_reflog_drop(g_reflog, 0, 1));
cl_assert_equal_i(0, (int)git_reflog_entrycount(g_reflog));
}
void test_refs_reflog_drop__can_persist_deletion_on_disk(void)
{
cl_assert(entrycount > 2);
cl_git_pass(git_reflog_drop(g_reflog, 0, 1));
cl_assert_equal_sz(entrycount - 1, git_reflog_entrycount(g_reflog));
cl_git_pass(git_reflog_write(g_reflog));
git_reflog_free(g_reflog);
git_reflog_read(&g_reflog, g_repo, "HEAD");
cl_assert_equal_sz(entrycount - 1, git_reflog_entrycount(g_reflog));
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
double preco(int years, int dif, double valor)
{
if(years == 3 && valor <= 45)
{
return valor;
}
else if(years == 0 && valor <= 45)
{
return 45;
}
else if(years == 0)
{
return valor;
}
if(dif == 0)
{
if(valor <= 100)
{
return preco(years - 1, dif, valor - ( (valor * 0.25) / 2));
}
else
{
return preco(years - 1, dif, (valor * 0.75) );
}
}
if(dif == 1)
{
if(valor <= 100)
{
return preco(years - 1, dif, valor - ( (valor * 0.20) / 2));
}
else
{
return preco(years - 1, dif, (valor * 0.80) );
}
}
if(dif== 2)
{
if(valor <= 100)
{
return preco(years - 1, dif, valor - ( (valor * 0.18) / 2));
}
else
{
return preco(years - 1, dif, (valor * 0.82) );
}
}
if(dif== 3)
{
if(valor <= 100)
{
return preco(years - 1, dif, valor - ( (valor * 0.15) / 2));
}
else
{
return preco(years - 1, dif, (valor * 0.85) );
}
}
if(dif== 4)
{
if(valor <= 100)
{
return preco(years - 1, dif, valor - ( (valor * 0.12) / 2));
}
else
{
return preco(years - 1, dif, (valor * 0.88) );
}
}
if(dif== 5)
{
if(valor <= 100)
{
return preco(years - 1, dif, valor - ( (valor * 0.10) / 2));
}
else
{
return preco(years - 1, dif, (valor * 0.90) );
}
}
}
double entrada(int anos, int limite, int acumula)
{
if(acumula == limite)
{
return 0;
}
double dificuldade, preco_inicial;
scanf ( "%lf %lf", &dificuldade, &preco_inicial );
printf("Jogo[%d] = R$%.2lf\n", acumula, (double)preco(anos, dificuldade, preco_inicial));
entrada(anos, limite, acumula + 1);
}
int main()
{
int jogos, a;
a = 3;
scanf ( "%d", &jogos );
entrada(a, jogos, 0);
return 0;
} /* ---------- end of function main ---------- */
|
C
|
#include <avr/io.h>
#include <util/delay.h>
#define TRUE 1
#define FALSE 0
#define NULL '\0'
#define sbi(BYTE,BIT) BYTE|=_BV(BIT) // BYTEの指定BITに1をセット
#define cbi(BYTE,BIT) BYTE&=~_BV(BIT) // BYTEの指定BITをクリア
#define LED0_ON() sbi(PORTB, PB0)
#define LED0_OFF() cbi(PORTB, PB0)
#define LED1_ON() sbi(PORTD, PD7)
#define LED1_OFF() cbi(PORTD, PD7)
void usart_init(unsigned int bps){
unsigned int ubrr;
ubrr = F_CPU/16/bps-1;
UBRR0H = (unsigned char)(ubrr>>8); // ボーレート上位8bit
UBRR0L = (unsigned char)ubrr; // ボーレート下位8bit
UCSR0A = (0<<U2X0); // 等速
UCSR0B = (1<<RXEN0)|(1<<TXEN0)|(1<<RXCIE0); // 送受信許可、受信完了割り込み許可
UCSR0C = (0<<UMSEL00)|(3<<UCSZ00)|(1<<USBS0)|(0<<UPM00); // async 8bit 1stopbit 0parity
}
void usart_send_str(char *str){
while(*str != '\0'){
loop_until_bit_is_set(UCSR0A, UDRE0);
UDR0 = *str++;
}
}
void adc_init(void){
ADMUX = (0<<REFS0); // 外部基準電圧
ADCSRA =(1<<ADEN)|(1<<ADSC)|(0<<ADPS0); // A/D変換許可、1回目変換開始(調整)、分周率2
}
// return 1-1023
int adc_read(char pin){
ADMUX = pin; // AD変換入力ピン
cbi(ADCSRA, ADIF);
sbi(ADCSRA, ADSC); // 変換開始
loop_until_bit_is_set(ADCSRA, ADIF); // 変換完了まで待つ
return ADCL + (ADCH<<8);
}
int main(void)
{
sbi(DDRB, PB0);
sbi(DDRD, PD7);
usart_init(9600);
adc_init();
usart_send_str("start\n");
int ad, ad_p;
char buf[10];
for(;;){
ad = adc_read(5);
usart_send_str(itoa(ad, buf, 10));
usart_send_str("\n");
if(ad-ad_p > 5){
LED0_ON();
LED1_OFF();
}
else if(ad_p-ad > 5){
LED0_OFF();
LED1_ON();
}
_delay_ms(100);
ad_p = ad;
}
return 0;
}
|
C
|
/**
******************************************************************************
* @file : main.c
* @author : Vidya Viswanathan
* @brief : Fault generation and handling
******************************************************************************
*/
#if !defined(__SOFT_FP__) && defined(__ARM_FP)
#warning "FPU is not initialized, but the project is compiling for an FPU. Please initialize the FPU before use."
#endif
#include<stdint.h>
#include<stdio.h>
void UsageFault_Handler_c(uint32_t *pMSP);
int main(void)
{
//1. enable all configurable exceptions : usage fault, mem manage fault and bus fault
//Refer section 4.3.9 in Generic user guide.
uint32_t *pSHCSR = (uint32_t*)0xE000ED24; //base addr of SHCSR reg - Present in the table in section 4.3 in Generic user guide.
//Enable the faults by enabling the bit positions in SHCSR
*pSHCSR |= ( 1 << 16); //mem manage
*pSHCSR |= ( 1 << 17); //bus fault
*pSHCSR |= ( 1 << 18); //usage fault
//3. lets force the processor to execute some undefined instruction
uint32_t *pSRAM = (uint32_t*)0x20010000; //random mem location in SRAM
/*This is an undefined instruction value */
*pSRAM = 0xFFFFFFFF; //invalid instruction
/* This is a function pointer variable */
void (*some_address) (void);
/* initialize the function pointer variable to some address */
some_address = (void*)0x20010001; //Ideally 0th bit of the function addr should always be 1 to make it odd. That decides the value of T-bit (It should always be 1 for ARM Cortex Mx).
//If we change this to 0x20010000, it is wrong, trying to change from THUMB state to ARM state. In this case UFSR is 2 (10 in binary) INVSTATE is the reason.
/* change PC to jump to location 0x20010000 */
some_address();
//4. analyze the fault
for(;;);
}
//2. implement the fault handlers
void HardFault_Handler(void)
{
printf("Exception : Hardfault\n");
while(1);
}
void MemManage_Handler(void)
{
printf("Exception : MemManage\n");
while(1);
}
void BusFault_Handler(void)
{
printf("Exception : BusFault\n");
while(1);
}
__attribute__ ((naked)) void UsageFault_Handler(void)
{
//here we extracted the value of MSP which happens to be the
//base address of the stack frame(thread mode) which got saved during the exception entry
//from thread mode to handler mode
__asm ("MRS r0,MSP");
__asm ("B UsageFault_Handler_c");
}
void UsageFault_Handler_c(uint32_t *pBaseStackFrame)
{
uint32_t *pUFSR = (uint32_t*)0xE000ED2A; //Usage Fault Status Reg Base addr - See section 2.4.3 in Generic user guide.
printf("Exception : UsageFault\n");
printf("UFSR = %lx\n",(*pUFSR) & 0xFFFF); //Read only first 16 bits. If it is 1, Undefined instruction usage fault is the reason. See Table 4-27 in Generic user guide for more info
printf("pBaseStackFrame = %p\n",pBaseStackFrame);
printf("Value of R0 = %lx\n", pBaseStackFrame[0]);
printf("Value of R1 = %lx\n", pBaseStackFrame[1]);
printf("Value of R2 = %lx\n", pBaseStackFrame[2]);
printf("Value of R3 = %lx\n", pBaseStackFrame[3]);
printf("Value of R12 = %lx\n", pBaseStackFrame[4]);
printf("Value of LR = %lx\n", pBaseStackFrame[5]);
printf("Value of PC = %lx\n", pBaseStackFrame[6]);
printf("Value of XPSR = %lx\n", pBaseStackFrame[7]);
while(1);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* inside.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mguesner <mguesner@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/06/04 13:04:31 by mguesner #+# #+# */
/* Updated: 2014/06/26 14:15:46 by mguesner ### ########.fr */
/* */
/* ************************************************************************** */
#include "zappy.h"
#include <libft.h>
static void inside2(t_clients *player, int *first, char *str)
{
if ((*first) == 0)
{
ft_strcat(player->buf_write, " ");
}
ft_strcat(player->buf_write, str);
(*first) = 0;
}
void inside(t_clients *player, t_case place, int i)
{
int tmp;
int first;
first = 1;
tmp = place.joueur - i;
while (tmp--)
inside2(player, &first, "joueur");
while (place.nourriture--)
inside2(player, &first, "nourriture");
while (place.linemate--)
inside2(player, &first, "linemate");
while (place.deraumere--)
inside2(player, &first, "deraumere");
while (place.sibur--)
inside2(player, &first, "sibur");
while (place.mendiane--)
inside2(player, &first, "mendiane");
while (place.phiras--)
inside2(player, &first, "phiras");
while (place.thystame--)
inside2(player, &first, "thystame");
}
|
C
|
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<signal.h>
int cnt = 0;
void
func (int sig)
{
printf ("输入速度是每小时%d字\n", 36 * cnt);
exit (0);
}
int
main ()
{
signal (SIGALRM, func);
printf ("请输入每个字一行:\n");
alarm (100); //定时100秒,到时会收到SIGALRM信号
for (;;)
{
char buf[100];
scanf ("%s", buf);
++cnt;
}}
|
C
|
#ifndef __MISC_H
#define __MISC_H
#include <stdio.h>
/**
* Tipo: Entrada da tabela de simbolos
*/
typedef struct s_SymbolTableEntry{
char* key;
int value;
struct s_SymbolTableEntry* next;
} SymbolTableEntry;
SymbolTableEntry* SymbolTableEntry_construct(const char* key, const int value);
void SymbolTableEntry_destruct(struct s_SymbolTableEntry* _this);
/**
* Tipo: Tabela de simbolos
*/
typedef struct s_SymbolTable{
SymbolTableEntry* first;
void (*add)(struct s_SymbolTable*, SymbolTableEntry*);
} SymbolTable;
SymbolTable* SymbolTable_construct();
void SymbolTable_destruct(struct s_SymbolTable* _this);
void SymbolTable_add(struct s_SymbolTable* _this, SymbolTableEntry* _new);
int getLineNumber (void);
void yyerror (char const *mensagem);
void main_init (int argc, char **argv);
void main_finalize (void);
#endif
|
C
|
/*Write a C program to find Simple Interest.*/
#include<stdio.h>
int main(){
int p,t,r;
printf("enter principal amount\n");
scanf("%d",&p);
printf("enter time period\n");
scanf("%d",&t);
printf("enter interest rate\n");
scanf("%d",&r);
printf("simple interest is %f",p*t*r/100.0);
return 0;
}
|
C
|
void n_n(int n) {
int k = 0;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
k++;
}
void n_logn(int n) {
int k = 0;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j*=2)
k++;
}
void n_2_n(int n) {
int k = 0;
for(int i=1;i<=n;i++)
for(int j=1;j<=1<<n;j++)
k++;
}
void logn_n(int n) {
int k = 0;
for(int i=1;i<=n;i*=2)
for(int j=1;j<=n;j++)
k++;
}
void logn_logn(int n) {
int k = 0;
for(int i=1;i<=n;i*=2)
for(int j=1;j<=n;j*=2)
k++;
}
void logn_2_n(int n) {
int k = 0;
for(int i=1;i<=n;i*=2)
for(int j=1;j<=1<<n;j++)
k++;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.